协同群改为智价通BOT接管对话,报价单按需生成;补客户名称、计费重与陆运报价条件
为什么改:应用建的协同群只能代答,销售在群里发文件、@人、问报价都对不上人; 本次把群对话交给智价通BOT,应用只负责拉群和解散群,并把几处销售已反馈的口径补齐。 群与身份: - 新增 group_bot 短协调(Redis 带环境前缀):记录 BOT 已接管群、当前关联工单、 @BOT 指令窗口与窗口外先到的附件,只做协调不当六态,六态仍在主账。 - 群里没有 @BOT 的文字不回;非 @ 文字断开当前单关联,之后必须重新 @BOT 带工单号。 - 先发文件再 @BOT 也认:窗口外附件先缓冲,等 @BOT 认领后补办。 - 会话存档只补附件、不重复办理 BOT 已办的同一句文字,避免同一条消息回两遍。 - 入站 from.userid 是加密 open_userid 时按官方接口换明文(带 Redis 缓存), 否则与主账 sales_wecom_id 永远比不上,航线本人会被判成「不是本人」。 - 桥侧只认本群 req_id,不再借用别的群 req_id,避免测服把话发进别的群。 报价单: - 建群后只发字段摘要和成交卡,Excel/PDF 等群里 @BOT 说「生成报价单」再出; 多段逐段出,没价出空白表;出表后补推成交跟进不涨 deal_version、不重置等待计时。 - 陆运转人工先选业务类型和报价场景再建群,按选定模板名直取,不再靠关键词猜。 - 空运舱位只回一条时直接出该条报价,不再发选择卡。 字段与金额: - 客户名称改为海/空/陆询价非必填,有值写回工单列,后台列表、报价单与 factsJson 一致。 - 空运新增计费重投影:体积重=CBM×166.7,计费重=max(毛重,体积重); TMS 无价、航线手工按 KG 报价时按计费重×单价算整票金额,群摘要与报价单同公式。 - 陆运报价附加条件统一到 land_quote_condition:未含税/含0税/未含燃油/含燃油费, 燃油只乘主运费,不乘提货送货报关等杂费;跨境整车无备注列时追加到底部备注事项。 - 海运拼柜不适用箱型箱量:不进必填、不进补问、不出站,改回整柜可再用。 - 海运提货地址/派送地址改为非必填,写了才出站(placeOfReceipt/deliveryAddress), 禁止从港口或贸易条款反推地址;TMS 查不到价时把 TMS 原话透给销售。 - 中港集拼与跨境集拼同口径:按体积+毛重,不采车型数量;修正被国内拼车别名抢单。 - 报关费区只收报关类费目;口岸海关监管费+接驳费按车型列回填固定行。 主账与后台: - 看板处理量按协同群处理人统计;下线「平均报价销售额」;处理人搜索先把姓名换回企微 id。 - 「转人工」筛选同时兼容旧六态与新 collab_mode=handoff,新版单不再漏。 - 报价单客户名称、提货/派送地址、空运计费重、拼柜空箱型按新口径填表。 - 新增协同成员查询支持与 AIR_NEED_WO v2 迁移脚本。 文档:04 补海运/空运/陆运必填与地址口径,10 补地址出站规则,12 补测服独立应用 1000015 的部署与切换记录。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -11,8 +11,8 @@ import html
|
||||
from typing import Any
|
||||
|
||||
from agent.channel.h5.air_route_page import _PAGE_CSS, _wrap
|
||||
from agent.policy import inquiry_copy as copy
|
||||
from agent.schema.land_route_options import (
|
||||
_money,
|
||||
group_land_routes,
|
||||
land_leg_fee_blocks_for_route,
|
||||
option_eta_bits,
|
||||
@@ -99,9 +99,10 @@ def _route_card(index: int, route: dict[str, Any], quote: dict[str, Any] | None
|
||||
"<span></span></li>"
|
||||
)
|
||||
for fee in fees:
|
||||
amount = _money(fee.get("amount"), str(fee.get("currency") or "").strip())
|
||||
# 金额后带 TMS 计价单位(如「CNY 13.00/KG」),和私聊文字明细同一套口径。
|
||||
amount = copy.fee_amount_text(fee, str(quote.get("currency") or "").strip())
|
||||
name = str(fee.get("name") or "").strip()
|
||||
if not name or not amount:
|
||||
if not name or not amount or amount == "-":
|
||||
continue
|
||||
items += (
|
||||
f"<li><span class='n'>{html.escape(name)}</span>"
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import logging
|
||||
import threading
|
||||
from typing import Optional
|
||||
@@ -22,6 +23,55 @@ logger = logging.getLogger(__name__)
|
||||
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||
|
||||
|
||||
def _normalize_group_sender(message):
|
||||
"""
|
||||
把 AIBOT 群入站的加密 open_userid 换回明文 userid(2026-11-19 真机问题)。
|
||||
|
||||
为什么放在 inbox 工作线程而不是回调里:
|
||||
- 回调必须秒回;换 ID 会打企微 HTTPS(有缓存,但首次仍要一次网络往返),
|
||||
只能放在消费线程,绝不进 FastAPI 请求线程。
|
||||
只处理 `chat_type=group` 且来源是 AIBOT 的消息:
|
||||
- 私聊出站要按 touser 发,改 sender_id 会发错人;
|
||||
- 会话存档(wshoto)本来就是明文,不需要换。
|
||||
|
||||
返回值:(归一后的消息, 身份是否可信)
|
||||
- 可信=1:明文自带,或已换成明文 → 后面的成交/报价/锁舱门禁可以照常判。
|
||||
- 可信=0:确实是加密 ID 但换不到 → 不得据此判「不是本人」,
|
||||
去重逻辑必须放行会话存档那条(明文)来补办。
|
||||
|
||||
副作用:可能打企微接口(3 秒超时)、写 Redis 短缓存;不改主账、不写六态。
|
||||
"""
|
||||
raw = dict(message.raw or {})
|
||||
source = str(raw.get("source") or "").strip().lower()
|
||||
if (message.chat_type or "") != "group" or source not in {"aibot", "aibot_bridge"}:
|
||||
return message, True
|
||||
from agent.channel.wecom.open_userid import looks_like_open_userid, resolve_open_userid
|
||||
|
||||
if not looks_like_open_userid(message.sender_id):
|
||||
# 明文 ID(机器人创建者是超管,或本链路本来就没加密):不用管。
|
||||
return message, True
|
||||
try:
|
||||
plain, status = resolve_open_userid(message.sender_id)
|
||||
except Exception: # noqa: BLE001 - 归一失败不能把消息丢掉,必须走存档兜底
|
||||
logger.warning("群入站 ID 归一异常,按换不到处理", exc_info=True)
|
||||
plain, status = message.sender_id, "unresolved"
|
||||
|
||||
|
||||
if status == "resolved":
|
||||
new_raw = dict(raw)
|
||||
# 保留原始加密 ID:排障要能对上企微后台,也便于以后回放。
|
||||
new_raw["sender_open_userid"] = message.sender_id
|
||||
new_raw["sender_id_source"] = "open_userid_resolved"
|
||||
new_raw["sender_identity_trusted"] = "1"
|
||||
return dataclasses.replace(message, sender_id=plain, raw=new_raw), True
|
||||
if status == "unresolved":
|
||||
new_raw = dict(raw)
|
||||
new_raw["sender_id_source"] = "open_userid_unresolved"
|
||||
new_raw["sender_identity_trusted"] = "0"
|
||||
return dataclasses.replace(message, raw=new_raw), False
|
||||
return message, True
|
||||
|
||||
|
||||
class ChannelRuntime:
|
||||
"""
|
||||
企微通道运行时:inbox/outbox 各一条守护线程。
|
||||
@@ -79,6 +129,10 @@ class ChannelRuntime:
|
||||
continue
|
||||
try:
|
||||
message = item.message
|
||||
# 群入站先做「加密 ID → 明文」归一:成交/报价/锁舱都靠这个身份判人。
|
||||
# 放在这里(消费线程)而不是回调线程,保证回调仍然秒回。
|
||||
# 可信标记写进 raw(sender_identity_trusted),由 dispatch 决定去重是否放行。
|
||||
message = _normalize_group_sender(message)[0]
|
||||
# 群消息由 dispatch 按 BOT/存档分流,不消耗 DeepSeek A,避免空运群先卡 2~3 秒。
|
||||
if (message.chat_type or "") == "group":
|
||||
from agent.routing.decision import RouteDecision
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
"""
|
||||
企微群入站「加密 open_userid → 明文 userid」归一。
|
||||
|
||||
为什么单独一个文件(2026-11-19 真机问题):
|
||||
- 企微智能机器人回调 `from.userid` 只有在「机器人创建者是超级管理员」时才是明文;
|
||||
否则是企业主体下的加密 open_userid(`wo` 开头,约 35 位)。
|
||||
- 群里成交/未成交、航线报价、锁舱、产品报价都要拿这个 ID 跟主账 `sales_wecom_id`
|
||||
和岗位名单做字符串比较;加密值永远比不上,业务全被判成「不是本人」。
|
||||
真机日志证据:`sender=woDK6DYQAAQZ...` → `phase=not_sales`,而主账记的是
|
||||
`LuoXiaoHua`;同一句走会话存档(明文)就能办成。
|
||||
- 官方提供 `cgi-bin/batch/openuserid_to_userid` 把它换回明文,前提是成员在该
|
||||
自建应用的可见范围内。这里做的就是「解密同一个入站 ID」,不是事后向企微补身份,
|
||||
身份来源仍然是入站报文,符合 prompt/06、09 的身份约束。
|
||||
|
||||
职责:
|
||||
- `looks_like_open_userid`:只做形态判断,不打网络。
|
||||
- `resolve_open_userid`:换明文;命中 Redis 缓存不重复打企微。
|
||||
|
||||
副作用:
|
||||
- 会打企微 HTTPS(`WECOM_OPENID_NORMALIZE_ENABLED=true` 时),超时默认 3 秒。
|
||||
- 只写 Redis 短缓存(ID 映射,不是六态、不是 checkpoint)。
|
||||
- 不写日志正文、不打印密钥。
|
||||
|
||||
禁止:
|
||||
- 在回调请求线程调用(会拖慢秒回);只允许在 inbox 工作线程调用。
|
||||
- 把换不到明文的 ID 当成「不是本人」直接拒绝;调用方必须走「存档兜底」。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from agent.config import get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 企微开放接口基址;与出站客户端一致,不写死业务域名。
|
||||
_API_BASE = "https://qyapi.weixin.qq.com"
|
||||
# 换成功一次就够用很久:userid 极少变,7 天足够,过期自动再换一次。
|
||||
_HIT_TTL_SECONDS = 7 * 24 * 3600
|
||||
# 换不到(不在应用可见范围)不能一直重试打接口:10 分钟后再试,管理员加权限后能自愈。
|
||||
_MISS_TTL_SECONDS = 600
|
||||
_OPENID_PREFIX = "wecom:openid2userid:"
|
||||
_MISS_VALUE = "#miss"
|
||||
|
||||
# access_token 由同一个进程内客户端缓存;多线程共用一把小锁只保护客户端创建。
|
||||
_client_lock = threading.Lock()
|
||||
_client_cache: dict[str, object] = {}
|
||||
|
||||
|
||||
def looks_like_open_userid(value: str) -> bool:
|
||||
"""
|
||||
形态判断:是不是企微加密 open_userid。
|
||||
|
||||
明文 userid 是 `LuoXiaoHua` 这种短名字;加密值固定 `wo` 前缀且 30 位以上。
|
||||
这里宁可判宽一点:判错只会多一次接口调用(有缓存),判漏会让业务被判「不是本人」。
|
||||
"""
|
||||
text = (value or "").strip()
|
||||
return text.startswith("wo") and len(text) >= 20
|
||||
|
||||
|
||||
def _redis_client():
|
||||
"""懒取 Redis 门面;连不上返回 None,归一化退化成每次都打接口。"""
|
||||
try:
|
||||
from agent.redis_coord.runtime import get_redis_runtime
|
||||
|
||||
return get_redis_runtime().client
|
||||
except Exception: # noqa: BLE001 - 缓存不可用不能阻断业务
|
||||
logger.warning("open_userid: Redis 不可用,跳过 ID 缓存", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def _cache_get(open_userid: str) -> str:
|
||||
"""读缓存:返回明文 / 空串(未缓存) / `#miss`(上次换不到)。"""
|
||||
client = _redis_client()
|
||||
if client is None:
|
||||
return ""
|
||||
try:
|
||||
value = client.raw.get(client.key(_OPENID_PREFIX + open_userid))
|
||||
return str(value or "").strip()
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("open_userid: 读缓存失败", exc_info=True)
|
||||
return ""
|
||||
|
||||
|
||||
def _cache_set(open_userid: str, value: str, ttl: int) -> None:
|
||||
"""写缓存;失败只记日志,不影响本次结果。"""
|
||||
client = _redis_client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.raw.set(client.key(_OPENID_PREFIX + open_userid), value, ex=ttl)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("open_userid: 写缓存失败", exc_info=True)
|
||||
|
||||
|
||||
def _app_client():
|
||||
"""
|
||||
取企微自建应用客户端(只用于 access_token)。
|
||||
|
||||
复用模块级实例:每次新建都会重新取 token,群里消息一多就会打爆 gettoken 频控。
|
||||
"""
|
||||
settings = get_settings()
|
||||
corp_id = str(settings.wecom_corp_id or "").strip()
|
||||
secret = str(settings.wecom_secret or "").strip()
|
||||
if not corp_id or not secret:
|
||||
return None
|
||||
key = f"{corp_id}:{settings.wecom_agent_id}"
|
||||
with _client_lock:
|
||||
cached = _client_cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
from agent.channel.outbox.sender import WeComAppClient
|
||||
|
||||
client = WeComAppClient(
|
||||
corp_id=corp_id,
|
||||
secret=secret,
|
||||
agent_id=int(settings.wecom_agent_id or "0") or 0,
|
||||
)
|
||||
_client_cache[key] = client
|
||||
return client
|
||||
|
||||
|
||||
def _fetch_plain(open_userids: list[str], *, timeout_sec: float) -> dict[str, str]:
|
||||
"""
|
||||
调 `batch/openuserid_to_userid` 批量换明文。
|
||||
|
||||
返回 {open_userid: 明文};换不到的键不会出现在结果里(也不抛异常)。
|
||||
"""
|
||||
client = _app_client()
|
||||
if client is None:
|
||||
logger.warning("open_userid: 未配置 WECOM_CORP_ID/SECRET,无法换明文")
|
||||
return {}
|
||||
try:
|
||||
token = client.get_access_token()
|
||||
except Exception: # noqa: BLE001 - token 失败等同换不到
|
||||
logger.warning("open_userid: 取 access_token 失败", exc_info=True)
|
||||
return {}
|
||||
if not token:
|
||||
return {}
|
||||
url = f"{_API_BASE}/cgi-bin/batch/openuserid_to_userid"
|
||||
body = {"open_userid_list": list(open_userids)}
|
||||
try:
|
||||
# httpx 默认 INFO 会打印完整 URL(含 access_token),这里只打异常不打印 URL。
|
||||
with httpx.Client(timeout=max(0.5, float(timeout_sec))) as http:
|
||||
resp = http.post(url, params={"access_token": token}, json=body)
|
||||
data = resp.json()
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("open_userid: 兑换接口调用失败", exc_info=True)
|
||||
return {}
|
||||
if int(data.get("errcode") or 0) != 0:
|
||||
logger.warning(
|
||||
"open_userid: 兑换失败 errcode=%s errmsg=%s",
|
||||
data.get("errcode"),
|
||||
str(data.get("errmsg") or "")[:120],
|
||||
)
|
||||
return {}
|
||||
out: dict[str, str] = {}
|
||||
for row in data.get("userid_list") or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
src = str(row.get("open_userid") or "").strip()
|
||||
dst = str(row.get("userid") or "").strip()
|
||||
if src and dst:
|
||||
out[src] = dst
|
||||
return out
|
||||
|
||||
|
||||
def resolve_open_userid(sender_id: str, *, timeout_sec: Optional[float] = None) -> tuple[str, str]:
|
||||
"""
|
||||
把群入站发言人的加密 ID 换回明文。
|
||||
|
||||
返回 `(明文或原值, 状态)`,状态语义:
|
||||
- `plain` :本来就是明文,调用方按可信处理;
|
||||
- `resolved` :换成了明文,调用方可以把明文当身份用;
|
||||
- `unresolved` :确实是加密 ID 但换不到(没配密钥 / 不在应用可见范围 / 接口失败),
|
||||
调用方**不得**据此判「不是本人」,要让会话存档那条兜底;
|
||||
- `disabled` :开关关着,按原样返回,行为与改动前完全一致。
|
||||
|
||||
只在 inbox 工作线程调用;有缓存,命中不打网络。
|
||||
"""
|
||||
text = (sender_id or "").strip()
|
||||
if not looks_like_open_userid(text):
|
||||
return text, "plain"
|
||||
settings = get_settings()
|
||||
if not bool(getattr(settings, "wecom_openid_normalize_enabled", False)):
|
||||
return text, "disabled"
|
||||
|
||||
cached = _cache_get(text)
|
||||
if cached and cached != _MISS_VALUE:
|
||||
return cached, "resolved"
|
||||
if cached == _MISS_VALUE:
|
||||
return text, "unresolved"
|
||||
|
||||
timeout = (
|
||||
float(timeout_sec)
|
||||
if timeout_sec is not None
|
||||
else float(getattr(settings, "wecom_openid_normalize_timeout_sec", 3.0) or 3.0)
|
||||
)
|
||||
found = _fetch_plain([text], timeout_sec=timeout)
|
||||
plain = str(found.get(text) or "").strip()
|
||||
if plain:
|
||||
_cache_set(text, plain, _HIT_TTL_SECONDS)
|
||||
# 不打印完整 ID,只留前 6 位,够对照日志又不泄露身份。
|
||||
logger.info("open_userid 换明文成功 open=%s… userid=%s", text[:6], plain)
|
||||
return plain, "resolved"
|
||||
_cache_set(text, _MISS_VALUE, _MISS_TTL_SECONDS)
|
||||
logger.warning("open_userid 换不到明文 open=%s…(走存档兜底)", text[:6])
|
||||
return text, "unresolved"
|
||||
@@ -12,8 +12,9 @@ from typing import Any, Mapping, Optional, Sequence
|
||||
|
||||
from agent.channel.wecom.models import InboundMessage
|
||||
|
||||
# 存档席在群里的显示名;from 偶发不是 userid 时也要丢掉
|
||||
SEAT_DISPLAY_NAMES = frozenset({"询价机器人"})
|
||||
# 存档席在群里的显示名;from 偶发不是 userid 时也要丢掉。
|
||||
# 2026-11-19 真机:群里显示「会话存档机器人」(无连字符),两种写法都排除。
|
||||
SEAT_DISPLAY_NAMES = frozenset({"询价机器人", "会话存档机器人", "会话存档-机器人"})
|
||||
_SKIP_TYPES = frozenset({"revoke", "recall", "event", "unknown"})
|
||||
_FILE_TYPES = frozenset({"file", "image", "video", "emotion", "voice"})
|
||||
|
||||
@@ -108,7 +109,21 @@ def archive_record_to_inbound(
|
||||
if not room_id or not sender_id:
|
||||
return None
|
||||
seats = {str(x).strip() for x in seat_userids if str(x).strip()}
|
||||
if sender_id in seats or sender_id in SEAT_DISPLAY_NAMES:
|
||||
# 机器人自己的出站文字也会被存档听到:不能当业务入站,否则会把自己的
|
||||
# 「报价单已发送」当成非 @ 文字打断当前工单关联。旧名/现名一起排除。
|
||||
try:
|
||||
from agent.policy.bot_name import bot_mention_names
|
||||
|
||||
bot_senders = set(bot_mention_names())
|
||||
except Exception: # noqa: BLE001
|
||||
bot_senders = set()
|
||||
sender_name = str(record.get("from_name") or record.get("fromName") or "").strip()
|
||||
if (
|
||||
sender_id in seats
|
||||
or sender_id in SEAT_DISPLAY_NAMES
|
||||
or sender_id in bot_senders
|
||||
or sender_name in bot_senders
|
||||
):
|
||||
return None
|
||||
|
||||
msg_type = str(record.get("msgtype") or record.get("msg_type") or "text").strip().lower()
|
||||
@@ -147,6 +162,9 @@ def archive_record_to_inbound(
|
||||
media=media,
|
||||
raw={
|
||||
"source": "wshoto_archive",
|
||||
# 存档是「公司级」数据:测服与正服共用同一个企微公司,测服也会捞到正服群。
|
||||
# 打上 origin 让 dispatch 能区分「本机 AIBOT 被 @」与「存档旁听」再做环境隔离。
|
||||
"wshoto_origin": "archive",
|
||||
"seq": seq,
|
||||
"msgtype": msg_type,
|
||||
"direction": record.get("direction") or "",
|
||||
|
||||
@@ -34,6 +34,8 @@ logger = logging.getLogger(__name__)
|
||||
_NEW_ROOM_LOOKBACK_SEC = 3600
|
||||
# 微盛「请求频率过高」:本轮立刻停,下一轮再扫,避免把活跃群也拖死。
|
||||
_RATE_LIMIT_CODE = 10061
|
||||
# 测服忽略 WSHOTO_SCAN_USER_IDS 的告警只打一次,避免每 2 秒刷屏。
|
||||
_test_scan_warned = False
|
||||
|
||||
|
||||
def archive_seat_userids(settings: Optional[Settings] = None) -> list[str]:
|
||||
@@ -59,6 +61,40 @@ def _record_seq(record: dict[str, Any]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def _record_epoch(record: dict[str, Any]) -> int:
|
||||
"""
|
||||
管家记录的发送时间(秒)。
|
||||
|
||||
微盛 msgtime 常是毫秒;补洞时要按请求的时间窗裁掉更早的历史,
|
||||
否则接口若忽略 msg_time_start,会把 20 小时前的旧话重新入队并触发业务回话。
|
||||
解析失败返回 0,调用方会把它当「太旧」丢掉。
|
||||
"""
|
||||
try:
|
||||
n = int(record.get("msgtime") or record.get("msg_time") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
return n // 1000 if n > 10**12 else n
|
||||
|
||||
|
||||
def _keep_within_epoch(rows: Sequence[dict[str, Any]], floor: int) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按发送时间裁掉早于 floor 的历史记录。
|
||||
|
||||
背景:微盛接口实测会忽略 msg_time_start,把 20 小时前的旧话也吐回来
|
||||
(2026-11-19 11:10 测服因此把正服工单号当新入站,回「查不到工单」到正服群)。
|
||||
解析不出时间的记录保留:不能因为缺字段就把正常消息全丢。
|
||||
"""
|
||||
if int(floor or 0) <= 0:
|
||||
return list(rows)
|
||||
kept: list[dict[str, Any]] = []
|
||||
for rec in rows:
|
||||
ts = _record_epoch(rec)
|
||||
if ts and ts < int(floor):
|
||||
continue
|
||||
kept.append(rec)
|
||||
return kept
|
||||
|
||||
|
||||
def ingest_records(
|
||||
records: Sequence[dict[str, Any]],
|
||||
*,
|
||||
@@ -118,6 +154,8 @@ def poll_once(
|
||||
已登记协同群按房间号拉(不要带存档席 userid,应用群否则给空页)。
|
||||
还没有群时才按席位试拉。
|
||||
"""
|
||||
global _test_scan_warned
|
||||
|
||||
cfg = settings or get_settings()
|
||||
if not wshoto_ready(cfg):
|
||||
return {"ok": False, "reason": "not_configured"}
|
||||
@@ -134,6 +172,30 @@ def poll_once(
|
||||
for x in str(getattr(cfg, "wshoto_scan_user_ids", "") or "").replace(";", ",").split(",")
|
||||
if x.strip()
|
||||
]
|
||||
# 测服隔离:测服与正服共用同一个企微公司和会话存档席位(AI001)。
|
||||
# 如果按真实员工或存档席「全公司」扫,正服协同群里的工单号与报价会被拉进测服 inbox,
|
||||
# 再由测服回「查不到工单」到正服群(2026-11-19 11:10 实测事故)。
|
||||
# 因此 YTD_ENV=test 只轮询本机自己登记过的群;发现新群只能走本机 AIBOT 回调。
|
||||
is_test = str(getattr(cfg, "ytd_env", "") or "").strip().lower() == "test"
|
||||
if is_test and scan_ids:
|
||||
if not _test_scan_warned:
|
||||
logger.warning(
|
||||
"YTD_ENV=test:忽略 WSHOTO_SCAN_USER_IDS=%s,测服不按真实员工扫全公司群",
|
||||
",".join(scan_ids),
|
||||
)
|
||||
_test_scan_warned = True
|
||||
scan_ids = []
|
||||
if is_test and not rooms:
|
||||
# 测服没有登记群时,禁止退回按存档席扫全公司(存档席也在正服群里)。
|
||||
logger.info("微盛轮询:测服没有登记的协同群,本轮不按存档席扫全公司")
|
||||
return {
|
||||
"ok": True,
|
||||
"mode": "none",
|
||||
"fetched": 0,
|
||||
"enqueued": 0,
|
||||
"skipped": 0,
|
||||
"last_seq": 0,
|
||||
}
|
||||
extra: list[dict[str, Any]] = []
|
||||
if scan_ids:
|
||||
extra = _poll_by_scan_users(
|
||||
@@ -172,6 +234,9 @@ def poll_once(
|
||||
msg_time_start=time_start,
|
||||
msg_time_end=time_end,
|
||||
)
|
||||
if last <= 0:
|
||||
# 席位首次拉取同理:接口可能忽略时间窗回全量,必须自己裁。
|
||||
records = _keep_within_epoch(list(records or []), time_start)
|
||||
mode = "seat"
|
||||
except WshotoError as exc:
|
||||
if not _needs_target(exc):
|
||||
@@ -257,6 +322,9 @@ def _poll_by_scan_users(
|
||||
msg_time_start=time_start,
|
||||
msg_time_end=time_end,
|
||||
)
|
||||
if last <= 0:
|
||||
# 按人扫新群同样可能拿到全量历史:只保留本轮时间窗内的记录。
|
||||
rows = _keep_within_epoch(list(rows or []), time_start)
|
||||
except WshotoError as exc:
|
||||
logger.warning("微盛按人扫群失败 userid=%s code=%s", uid, exc.code)
|
||||
continue
|
||||
@@ -344,7 +412,11 @@ def _backfill_room_seq_gap(
|
||||
exc.msg,
|
||||
)
|
||||
return rows
|
||||
merged = _merge_records_by_seq(rows, fill or [], min_seq=last_seq)
|
||||
# 补洞结果必须真的落在本次请求的时间窗内:实测微盛会忽略 msg_time_start 返回全量历史,
|
||||
# 20 小时前的旧消息会被当成「新缺口」入队,再对正服群回业务话(2026-11-19 11:10 事故)。
|
||||
floor = now_i - window
|
||||
kept_fill = _keep_within_epoch(list(fill or []), floor)
|
||||
merged = _merge_records_by_seq(rows, kept_fill, min_seq=last_seq)
|
||||
if len(merged) > len(rows):
|
||||
logger.info(
|
||||
"微盛房间补洞成功 chat=%s added=%s total=%s",
|
||||
@@ -415,6 +487,11 @@ def _poll_by_rooms(
|
||||
rate_limited = True
|
||||
break
|
||||
continue
|
||||
if last <= 0:
|
||||
# 新群首次拉取:接口可能忽略 msg_time_start 直接回全量历史。
|
||||
# 不自己裁时间窗,20 小时前的正服工单号会被当成本轮新话入队。
|
||||
before = len(rows or [])
|
||||
rows = _keep_within_epoch(list(rows or []), time_start)
|
||||
polled += 1
|
||||
if not is_room_hot(room):
|
||||
cold_polled += 1
|
||||
|
||||
Reference in New Issue
Block a user