Commit 1c4887a3 by imwangxiaozhou Committed by 胡悦

refactor: 统一项目时区处理,调整官网agent默认展示状态并优化日志配置

- 新增 `app/infrastructure/time.py` 封装中国时区当前时间工具函数,替换全项目手动处理UTC时区的代码
- 新增数据库迁移脚本将 `official_site_agent_display` 表的 `display_status` 默认值设为 `disable`
- 更新对应模型、Schema、业务服务的默认展示状态配置
- 调整第三方库日志级别至WARNING,减少apscheduler、httpx等库的冗余日志输出
- 优化企业微信同步模块的日志格式和消息过滤逻辑,统一时区处理
1 parent 691a5d7e
# 会议纪要
**【会议主题】**:优加二手车平台业务模式、财务合规与运营策略对齐会
**【会议日期】**:[未提及]
**【参会人】**:说话人 0、说话人 1、说话人 2、说话人 3、说话人 4、说话人 5
**【缺席人】**:[未提及]
**【本次会议要点】**
1. 确定优加与广联体外合作模式:优加负责签单与确认收入,广联提供资金与服务。
2. 明确二手车税务逻辑:按销售额0.5%简易计税,收入确认以实际售出收款为准。
3. 采用清分或双合同模式规避优加与广联直接关联交易,确保财务路径合规。
4. 拍卖平台增设"包店车源"与"试拍车源"双频道,区分保收与竞价交易规则。
5. 推出轻量化拓店政策:通过企微引流、线索奖励及资金赋能激励一线销售。
6. 要求1月起全面切换新业务模式,加快平台全链路跑通与专项人员招聘。
**【详细任务列表】**
| 编号 | 类别 | 事项 | 责任人 | 计划完成时间 |
| --- | --- | --- | --- | --- |
| 1 | 财务合规 | 拟定优加与广联框架合同,明确资产管理费与资金占用费结算标准,确保体外合规运作。 | 说话人 4 | 近期 |
| 2 | 平台运营 | 开发并上线"包店车源"与"试拍车源"双频道,配置差异化保留价规则,支撑分类处置。 | 说话人 2 | 近期 |
| 3 | 商务政策 | 制定一线销售轻量化拓店激励方案,明确企微添加与线索转化奖励标准,于1月下发执行。 | 说话人 1 | 本周内 |
| 4 | 营销推广 | 精修内外部招商海报并补充引流二维码,经人工审核后统一分发,用于门店与朋友圈投放。 | 说话人 4 | 会后立即 |
| 5 | 流程跑通 | 验证收车、上拍、改价至过户结算全链路,修复系统改价卡点与财务对账逻辑,保障流程顺畅。 | 说话人 3 | 1月前 |
| 6 | 团队建设 | 落实车商拓展运营人员(肖峰等)到岗,明确驻店评估与赋能拓店职责,建立周复盘机制。 | 说话人 1 | 下周内 |
| 7 | 制度流程 | 完成OA系统二手车审批流配置,将资金拨付与业务单据全量接入优加体系,实现线上闭环。 | 说话人 2 | 近期 |
\ No newline at end of file \ No newline at end of file
"""Memory 包装层 — 封装 ConversationHistory 的消息存取和压缩。""" """Memory 包装层 — 封装 ConversationHistory 的消息存取和压缩。"""
from __future__ import annotations from __future__ import annotations
import logging
from typing import Any, List, Optional from typing import Any, List, Optional
from agentscope.message import Msg
from app.infrastructure.session_store import SessionStore from app.infrastructure.session_store import SessionStore
logger = logging.getLogger(__name__)
class SessionMemory: class SessionMemory:
"""管理单个 session 的消息历史,提供 Memory API(add / get_messages / compress)。""" """管理单个 session 的消息历史,提供 Memory API(add / get_messages / compress)。"""
...@@ -30,41 +25,22 @@ class SessionMemory: ...@@ -30,41 +25,22 @@ class SessionMemory:
return [] return []
return list(existing.get("conversation_history") or []) return list(existing.get("conversation_history") or [])
def add(self, role: str, content: str | list[dict], name: Optional[str] = None) -> None: def add(self, role: str, content: str, agent_code: Optional[str] = None) -> None:
existing = self._store.get(self.session_id) existing = self._store.get(self.session_id)
if not existing: if not existing:
return return
history: list[dict[str, Any]] = list(existing.get("conversation_history") or []) history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
msg = Msg( from app.infrastructure.time import china_now
name=name or role, history.append({
content=content, "role": role,
role=role, "content": content,
) "agent_code": agent_code,
history.append(msg.to_dict()) "agent_id": None,
"intent": None,
"timestamp": china_now().isoformat(),
})
existing["conversation_history"] = history existing["conversation_history"] = history
self._store.set(self.session_id, existing) self._store.set(self.session_id, existing)
logger.info(
"[SessionMemory] session=%s add role=%s name=%s → conversation_history 长度=%d",
self.session_id, role, name or role, len(history),
)
def remove_last(self, role: Optional[str] = None) -> Optional[dict]:
"""移除 conversation_history 最后一条(可限定 role),返回被移除的消息。"""
history = self._load()
if not history:
return None
if role is not None and history[-1].get("role") != role:
return None
popped = history.pop()
data = self._store.get(self.session_id)
if data:
data["conversation_history"] = history
self._store.set(self.session_id, data)
logger.info(
"[SessionMemory] session=%s remove_last role_filter=%s → conversation_history 长度=%d",
self.session_id, role, len(history),
)
return popped
def get_messages( def get_messages(
self, self,
...@@ -88,8 +64,7 @@ class SessionMemory: ...@@ -88,8 +64,7 @@ class SessionMemory:
result = [] result = []
if include_summary and overflow: if include_summary and overflow:
summary = self._summarize(overflow) summary = self._summarize(overflow)
summary_msg = Msg("system", f"[早期对话摘要] {summary}", "system") result.append({"role": "system", "content": f"[早期对话摘要] {summary}"})
result.append(summary_msg.to_dict())
result.extend(recent) result.extend(recent)
return result return result
......
...@@ -56,10 +56,3 @@ def configure_logging(service_name: str, level: int = logging.INFO) -> None: ...@@ -56,10 +56,3 @@ def configure_logging(service_name: str, level: int = logging.INFO) -> None:
logger.handlers.clear() logger.handlers.clear()
logger.propagate = True logger.propagate = True
logger.setLevel(logging.WARNING) logger.setLevel(logging.WARNING)
# AgentScope 框架自己的 logger("as"),默认 propagate=False,只输出到控制台。
# 清掉它的 handler 并 propagate,让模型/工具日志进入项目的文件日志。
as_logger = logging.getLogger("as")
as_logger.handlers.clear()
as_logger.propagate = True
as_logger.setLevel(level)
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from datetime import datetime
from app.infrastructure.time import china_now
from typing import Optional
from app.infrastructure.session_store import SessionStore
from app.model.session import Session
logger = logging.getLogger(__name__)
def _utcnow_iso() -> str:
return china_now().isoformat()
@dataclass(frozen=True)
class ActiveSessionInfo:
id: str
session_id: str
channel: str
room_id: str
status: str = "active"
class ActiveSessionService:
def __init__(self, store: Optional[SessionStore] = None, db=None) -> None:
self.store = store or SessionStore()
self._db = db
def get_or_create_session(
self,
session_id: str,
room_id: str = "",
channel: str = "wechat_group",
) -> ActiveSessionInfo:
# 1. 先查内存(热路径)
existing = self.store.get(session_id)
if existing:
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=existing.get("channel", channel),
room_id=existing.get("room_id", room_id),
)
# 2. 查 DB(冷恢复)
if self._db:
db_sess = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if db_sess:
payload = {
"session_id": db_sess.session_id,
"channel": db_sess.channel,
"room_id": db_sess.room_id,
"conversation_history": json.loads(
db_sess.conversation_history or "[]"
),
"context_entities": {},
"created_at": (
db_sess.created_at.isoformat()
if db_sess.created_at else _utcnow_iso()
),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=db_sess.channel,
room_id=db_sess.room_id,
)
# 3. 都没有,创建新 session
payload = {
"session_id": session_id,
"channel": channel,
"room_id": room_id,
"conversation_history": [],
"context_entities": {},
"created_at": _utcnow_iso(),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=channel,
room_id=room_id,
)
def save_to_db(self, session_id: str) -> None:
"""将内存中的 session 持久化到 DB。"""
if not self._db:
return
data = self.store.get(session_id)
if not data:
return
try:
existing = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
)
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
)
self._db.add(db_sess)
self._db.commit()
except Exception:
self._db.rollback()
logger.exception("Failed to persist session %s to DB", session_id)
...@@ -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", "deleted"} INVALID_GROUP_STATUSES = {"failed", "timeout", "invalid"}
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"
...@@ -49,8 +49,24 @@ def _utcnow() -> datetime: ...@@ -49,8 +49,24 @@ def _utcnow() -> datetime:
return china_now() return china_now()
def _format_dispatch_payload(payload: dict[str, Any]) -> str:
group = payload.get("group", {}) or {}
agents = payload.get("agents", []) or []
messages = payload.get("messages", []) or []
pretty_payload = json.dumps(payload, ensure_ascii=False, indent=2, default=str)
return (
"[dispatch_customer_group_messages] payload begin\n"
f"group: {group.get('group_name') or '-'} ({group.get('group_contact_id') or '-'})\n"
f"agents: {len(agents)}\n"
f"messages: {len(messages)}\n"
f"{pretty_payload}\n"
"[dispatch_customer_group_messages] payload end"
)
class NoopGroupMessageBatchDispatcher: class NoopGroupMessageBatchDispatcher:
def dispatch(self, payload: dict[str, Any]) -> None: def dispatch(self, payload: dict[str, Any]) -> None:
logger.info(_format_dispatch_payload(payload))
return None return None
...@@ -89,6 +105,7 @@ class HttpChatCompletionsBatchDispatcher: ...@@ -89,6 +105,7 @@ class HttpChatCompletionsBatchDispatcher:
def dispatch(self, payload: dict[str, Any]) -> None: def dispatch(self, payload: dict[str, Any]) -> None:
request_body = self._build_request_body(payload) request_body = self._build_request_body(payload)
logger.info(format_job_log("准备推送到下游接口 /api/v1/chat/completions"))
logger.info(format_job_log(f"下游请求参数: {json.dumps(request_body, ensure_ascii=False, default=str)}")) logger.info(format_job_log(f"下游请求参数: {json.dumps(request_body, ensure_ascii=False, default=str)}"))
try: try:
with httpx.Client(timeout=self.timeout_seconds) as client: with httpx.Client(timeout=self.timeout_seconds) as client:
...@@ -98,6 +115,7 @@ class HttpChatCompletionsBatchDispatcher: ...@@ -98,6 +115,7 @@ class HttpChatCompletionsBatchDispatcher:
headers={"Content-Type": "application/json"}, headers={"Content-Type": "application/json"},
) )
response.raise_for_status() response.raise_for_status()
logger.info(format_job_log(f"下游接口返回状态: /api/v1/chat/completions {response.status_code}"))
except httpx.HTTPError as exc: except httpx.HTTPError as exc:
logger.exception(format_job_log("推送下游接口失败: /api/v1/chat/completions")) logger.exception(format_job_log("推送下游接口失败: /api/v1/chat/completions"))
raise raise
...@@ -158,7 +176,6 @@ class ResolvedCustomerGroupBinding: ...@@ -158,7 +176,6 @@ class ResolvedCustomerGroupBinding:
position_id: int position_id: int
position_code: str position_code: str
position_name: str position_name: str
member_bot_ids: list[str] | None = None
class WeComCustomerGroupOrchestrationService: class WeComCustomerGroupOrchestrationService:
...@@ -169,7 +186,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -169,7 +186,7 @@ class WeComCustomerGroupOrchestrationService:
sync_service: WeComSyncService, sync_service: WeComSyncService,
batch_dispatcher: Any | None = None, batch_dispatcher: Any | None = None,
webhook_notifier: WeComWebhookNotifier | None = None, webhook_notifier: WeComWebhookNotifier | None = None,
page_size: int = 50, page_size: int = 100,
) -> None: ) -> None:
self.db = db self.db = db
self.client = client self.client = client
...@@ -177,9 +194,6 @@ class WeComCustomerGroupOrchestrationService: ...@@ -177,9 +194,6 @@ 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)
...@@ -189,10 +203,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -189,10 +203,7 @@ class WeComCustomerGroupOrchestrationService:
"created": created, "created": created,
} }
def scan_new_customers(self, *, bot_ids: Iterable[str] | None = None, dry_run: bool = False) -> list[WeComNewCustomerItem]: def scan_new_customers(self, *, bot_ids: Iterable[str] | None = None) -> 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:
...@@ -211,247 +222,13 @@ class WeComCustomerGroupOrchestrationService: ...@@ -211,247 +222,13 @@ 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._preview_bot_customers_full(bot_id=bot_id): 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)
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_contacts(
bot_id=bot.bot_id,
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:
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_contacts(
bot_id=bot.bot_id,
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 "")
existing = (
self.db.query(WeComCustomerGroup)
.filter(
WeComCustomerGroup.bot_id == bot_id,
WeComCustomerGroup.customer_contact_id == cid,
)
.first()
)
if existing is not None:
existing.is_deleted = False
existing.group_status = "pending"
existing.customer_name = customer_name
existing.group_id = None
existing.group_name = None
existing.group_create_request_id = None
existing.member_bot_ids = [m.bot_id for m in member_bots]
logger.info(
format_job_log(
"全量对比复活已删除客户:机器人[%s] 客户[%s](contact_id=%s)"
% (bot.bot_name or bot.bot_id, customer_name or "-", cid)
)
)
self.db.flush()
continue
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
...@@ -499,8 +276,6 @@ class WeComCustomerGroupOrchestrationService: ...@@ -499,8 +276,6 @@ class WeComCustomerGroupOrchestrationService:
request.status = "failed" request.status = "failed"
request.fail_reason = "timeout" request.fail_reason = "timeout"
self._notify_group_create_timeout(request) self._notify_group_create_timeout(request)
if request.customer_contact_id:
self._record_failed_customer_group(request)
processed += 1 processed += 1
continue continue
...@@ -518,24 +293,14 @@ class WeComCustomerGroupOrchestrationService: ...@@ -518,24 +293,14 @@ 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:
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:
...@@ -560,13 +325,6 @@ class WeComCustomerGroupOrchestrationService: ...@@ -560,13 +325,6 @@ class WeComCustomerGroupOrchestrationService:
seen.add(key) seen.add(key)
items.append(item) items.append(item)
for item in self._scan_pending_customer_groups(bot_ids=bot_ids):
key = (item.bot_id, item.contact_id)
if key in seen:
continue
seen.add(key)
items.append(item)
return items return items
def poll_pending_group_create_requests(self) -> int: def poll_pending_group_create_requests(self) -> int:
...@@ -644,7 +402,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -644,7 +402,7 @@ class WeComCustomerGroupOrchestrationService:
"group_contact_id": binding.group_contact_id, "group_contact_id": binding.group_contact_id,
"group_name": binding.group_name, "group_name": binding.group_name,
}, },
"agents": self._build_agents_from_member_bots(binding.member_bot_ids or []), "agents": self._build_position_agents(binding.position_id),
"messages": [ "messages": [
{ {
"msg_id": item.get("msg_id"), "msg_id": item.get("msg_id"),
...@@ -671,7 +429,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -671,7 +429,7 @@ class WeComCustomerGroupOrchestrationService:
.filter( .filter(
WeComMessage.bot_send == False, WeComMessage.bot_send == False,
WeComMessage.dispatch_status == "pending", WeComMessage.dispatch_status == "pending",
WeComMessage.msg_type != "other", WeComMessage.msg_type.in_(("text", "file")),
) )
.order_by(WeComMessage.msg_time.asc(), WeComMessage.id.asc()) .order_by(WeComMessage.msg_time.asc(), WeComMessage.id.asc())
) )
...@@ -692,6 +450,12 @@ class WeComCustomerGroupOrchestrationService: ...@@ -692,6 +450,12 @@ class WeComCustomerGroupOrchestrationService:
payload = self._build_dispatch_payload(binding, messages) payload = self._build_dispatch_payload(binding, messages)
try: try:
logger.info(
format_job_log(
"开始分发消息: bot_id=%s contact_id=%s message_count=%s agent_count=%s"
% (bot_id, contact_id, len(messages), len(payload.get("agents", [])))
)
)
self.batch_dispatcher.dispatch(payload) self.batch_dispatcher.dispatch(payload)
now = _utcnow() now = _utcnow()
for message in messages: for message in messages:
...@@ -954,7 +718,6 @@ class WeComCustomerGroupOrchestrationService: ...@@ -954,7 +718,6 @@ 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))
...@@ -1086,52 +849,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1086,52 +849,7 @@ class WeComCustomerGroupOrchestrationService:
) )
return items return items
def _scan_pending_customer_groups(self, *, bot_ids: Iterable[str] | None = None) -> list[WeComNewCustomerItem]:
query = (
self.db.query(WeComCustomerGroup)
.filter(WeComCustomerGroup.group_status == "pending")
.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: 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(
...@@ -1141,7 +859,6 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1141,7 +859,6 @@ 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}",
...@@ -1186,7 +903,6 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1186,7 +903,6 @@ class WeComCustomerGroupOrchestrationService:
position_id=position.id, position_id=position.id,
position_code=position.code, position_code=position.code,
position_name=position.name, position_name=position.name,
member_bot_ids=customer_group.member_bot_ids or [],
) )
return None return None
...@@ -1207,7 +923,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1207,7 +923,7 @@ class WeComCustomerGroupOrchestrationService:
record = self._get_latest_customer_group(bot_id=bot_id, customer_contact_id=customer_contact_id) record = self._get_latest_customer_group(bot_id=bot_id, customer_contact_id=customer_contact_id)
if record is None: if record is None:
return True return True
return record.group_status in ("invalid", "pending") 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 = (
...@@ -1248,17 +964,12 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1248,17 +964,12 @@ class WeComCustomerGroupOrchestrationService:
record = ( record = (
self.db.query(WeComCustomerGroup) self.db.query(WeComCustomerGroup)
.filter( .filter(WeComCustomerGroup.customer_contact_id == request.customer_contact_id)
WeComCustomerGroup.bot_id == request.bot_id,
WeComCustomerGroup.customer_contact_id == request.customer_contact_id,
)
.first() .first()
) )
if record is None: if record is None:
record = WeComCustomerGroup( record = WeComCustomerGroup(
customer_contact_id=request.customer_contact_id, customer_contact_id=request.customer_contact_id,
bot_id=request.bot_id,
bot_code=request.bot_code,
member_bot_ids=list(request.member_bot_ids or []), member_bot_ids=list(request.member_bot_ids or []),
is_deleted=False, is_deleted=False,
) )
...@@ -1275,39 +986,6 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1275,39 +986,6 @@ class WeComCustomerGroupOrchestrationService:
record.is_deleted = False record.is_deleted = False
self.db.flush() self.db.flush()
def _record_failed_customer_group(self, request: WeComGroupCreateRequest) -> None:
if not request.customer_contact_id:
return
record = (
self.db.query(WeComCustomerGroup)
.filter(
WeComCustomerGroup.bot_id == request.bot_id,
WeComCustomerGroup.customer_contact_id == request.customer_contact_id,
)
.first()
)
if record is None:
record = WeComCustomerGroup(
customer_contact_id=request.customer_contact_id,
bot_id=request.bot_id,
bot_code=request.bot_code,
member_bot_ids=list(request.member_bot_ids or []),
is_deleted=False,
)
self.db.add(record)
record.customer_name = request.customer_name
record.bot_id = request.bot_id
record.bot_code = request.bot_code
record.group_id = None
record.group_name = request.group_name
record.group_status = "failed"
record.group_create_request_id = request.id
record.member_bot_ids = list(request.member_bot_ids or [])
record.is_deleted = False
self.db.flush()
def _build_group_name(self, position_name: str | None, customer_contact_id: str) -> str: 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 base_name = str(position_name or "").strip() or customer_contact_id
return f"{base_name}服务群" return f"{base_name}服务群"
...@@ -1366,7 +1044,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1366,7 +1044,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=self._customer_contact_type, 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:
...@@ -1378,8 +1056,14 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1378,8 +1056,14 @@ class WeComCustomerGroupOrchestrationService:
"group": { "group": {
"group_contact_id": binding.group_contact_id, "group_contact_id": binding.group_contact_id,
"group_name": binding.group_name, "group_name": binding.group_name,
"bot_code": binding.bot_code,
},
"position": {
"position_id": binding.position_id,
"position_code": binding.position_code,
"position_name": binding.position_name,
}, },
"agents": self._build_agents_from_member_bots(binding.member_bot_ids or []), "agents": self._build_position_agents(binding.position_id),
"messages": [ "messages": [
{ {
"msg_id": message.msg_id, "msg_id": message.msg_id,
...@@ -1394,28 +1078,15 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1394,28 +1078,15 @@ class WeComCustomerGroupOrchestrationService:
], ],
} }
def _build_agents_from_member_bots(self, member_bot_ids: list[str]) -> list[dict[str, Any]]: def _build_position_agents(self, position_id: int) -> list[dict[str, Any]]:
"""从群的 member_bot_ids 查询关联的 Agent 信息。
流程:member_bot_ids → WeComBot → Agent
member_bot_ids 存的是 WeComBot.bot_id,通过它查到 WeComBot.id,
再通过 Agent.managed_user_id 关联到 Agent。
"""
cleaned_ids = [item.strip() for item in member_bot_ids if str(item).strip()]
if not cleaned_ids:
return []
bot_rows = self.db.query(WeComBot).filter(WeComBot.bot_id.in_(cleaned_ids)).all()
bot_row_ids = [row.id for row in bot_rows if row.id is not None]
if not bot_row_ids:
return []
bot_id_map: dict[int, str] = {row.id: row.bot_id for row in bot_rows}
agent_rows = ( agent_rows = (
self.db.query(Agent) self.db.query(Agent, WeComBot)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.join(WeComBot, WeComBot.id == Agent.managed_user_id)
.filter( .filter(
Agent.managed_user_id.in_(bot_row_ids), AgentPosition.position_id == position_id,
Agent.is_deleted == False,
Agent.status == AgentStatus.enable,
Agent.managed_user_id.isnot(None), Agent.managed_user_id.isnot(None),
) )
.all() .all()
...@@ -1423,13 +1094,11 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1423,13 +1094,11 @@ class WeComCustomerGroupOrchestrationService:
return [ return [
{ {
"agent_id": agent.id, "agent_id": agent.id,
"bot_id": bot_id_map.get(agent.managed_user_id, ""), "agent_name": agent.name,
"bot_id": bot.bot_id,
"is_steward": bool(agent.is_steward), "is_steward": bool(agent.is_steward),
"status": agent.status.value if agent.status else "enable",
"is_deleted": agent.is_deleted or False,
} }
for agent in agent_rows for agent, bot in agent_rows
if agent.managed_user_id in bot_id_map
] ]
def _resolve_message_group_binding(self, message: WeComMessage) -> ResolvedCustomerGroupBinding | None: def _resolve_message_group_binding(self, message: WeComMessage) -> ResolvedCustomerGroupBinding | None:
...@@ -1457,7 +1126,6 @@ class WeComCustomerGroupOrchestrationService: ...@@ -1457,7 +1126,6 @@ class WeComCustomerGroupOrchestrationService:
position_id=position.id, position_id=position.id,
position_code=position.code, position_code=position.code,
position_name=position.name, position_name=position.name,
member_bot_ids=customer_group.member_bot_ids or [],
) )
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == message.bot_id).first() bot = self.db.query(WeComBot).filter(WeComBot.bot_id == message.bot_id).first()
......
...@@ -57,9 +57,6 @@ class WeComSyncClient(Protocol): ...@@ -57,9 +57,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_contacts(self, *, bot_id: str, page: int, page_size: int, contact_type: str | None = None) -> dict[str, Any]:
...
def list_customers( def list_customers(
self, self,
*, *,
...@@ -134,7 +131,7 @@ class WeComSyncService: ...@@ -134,7 +131,7 @@ class WeComSyncService:
db: Session, db: Session,
client: WeComSyncClient, client: WeComSyncClient,
dispatcher: WeComMessageDispatcher | None = None, dispatcher: WeComMessageDispatcher | None = None,
page_size: int = 50, page_size: int = 100,
) -> None: ) -> None:
self.db = db self.db = db
self.client = client self.client = client
...@@ -274,7 +271,7 @@ class WeComSyncService: ...@@ -274,7 +271,7 @@ class WeComSyncService:
.filter( .filter(
WeComMessage.bot_send == False, WeComMessage.bot_send == False,
WeComMessage.dispatch_status == "pending", WeComMessage.dispatch_status == "pending",
WeComMessage.msg_type != "other", WeComMessage.msg_type.in_(("text", "file")),
) )
.order_by(WeComMessage.msg_time.asc(), WeComMessage.id.asc()) .order_by(WeComMessage.msg_time.asc(), WeComMessage.id.asc())
) )
...@@ -406,7 +403,7 @@ class WeComSyncService: ...@@ -406,7 +403,7 @@ class WeComSyncService:
record.session_title = data.get("session_title") record.session_title = data.get("session_title")
record.bot_send = self._infer_message_bot_send(data) record.bot_send = self._infer_message_bot_send(data)
record.payload = dict(data) record.payload = dict(data)
if not record.bot_send and record.dispatch_status is None and record.msg_type != "other": if not record.bot_send and record.dispatch_status is None and record.msg_type in ("text", "file"):
record.dispatch_status = "pending" record.dispatch_status = "pending"
record.dispatch_error = None record.dispatch_error = None
self.db.flush() self.db.flush()
...@@ -425,10 +422,22 @@ class WeComSyncService: ...@@ -425,10 +422,22 @@ class WeComSyncService:
contact_id = str(data.get("contact_id") or "").strip() contact_id = str(data.get("contact_id") or "").strip()
sender_id = str(data.get("sender_id") or "").strip() sender_id = str(data.get("sender_id") or "").strip()
if not bot_id or not contact_id or not sender_id: 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 return True
customer_contact_id = self._resolve_customer_contact_id(bot_id=bot_id, group_contact_id=contact_id) customer_contact_id = self._resolve_customer_contact_id(bot_id=bot_id, group_contact_id=contact_id)
if not customer_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 return True
# 只有客户本人发言才需要分发(bot_send=False) # 只有客户本人发言才需要分发(bot_send=False)
......
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
ALTER TABLE official_site_agent_display ALTER COLUMN display_status SET DEFAULT 'disable';
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!