diff --git a/aibot-bridge/group_message_frame.cjs b/aibot-bridge/group_message_frame.cjs index 146ead8..a2f988a 100644 --- a/aibot-bridge/group_message_frame.cjs +++ b/aibot-bridge/group_message_frame.cjs @@ -2,17 +2,19 @@ * 空运群出站报文:禁止 stream(企微会加「内容由AI生成」和赞踩)。 * 只发 markdown,且不带 feedback。 * 有这次 @ 的 req_id 才走 aibot_respond_msg,群里才会引用原消息。 + * + * 2026-11-21 修复(测服超时话术跑到空运群): + * req_id 只能是「本群」的。企微 aibot_respond_msg 按 req_id 投递回原会话, + * body.chatid 不改变投递目标;以前在拿不到本群 req_id 时回退到 lastAny + * (最近一次任意群 @),结果陆运/海运群主动发言被投递到最后 @ 机器人的空运群。 + * 这里删掉跨群回退:拿不到本群 req_id 就返回空,调用方改走 aibot_send_msg + 指定 chatid。 */ -function pickReplyReqId({ fromCaller, fromChat, lastAny }) { +function pickReplyReqId({ fromCaller, fromChat }) { const caller = String(fromCaller || "").trim(); if (caller) { return caller; } - const chat = String(fromChat || "").trim(); - if (chat) { - return chat; - } - return String(lastAny || "").trim(); + return String(fromChat || "").trim(); } // 含星号的尺寸或箱量。已在行内代码里的整段跳过,避免套两层。 diff --git a/aibot-bridge/long_connection.cjs b/aibot-bridge/long_connection.cjs index d5cb814..54d02fe 100644 --- a/aibot-bridge/long_connection.cjs +++ b/aibot-bridge/long_connection.cjs @@ -50,7 +50,6 @@ function startLongConnectionLoop(opts) { lastError: "", pending: new Map(), lastCallback: new Map(), - lastAnyReq: "", heartbeatTimer: null, reconnectTimer: null, stop: () => {}, @@ -90,10 +89,10 @@ function startLongConnectionLoop(opts) { const fromCaller = String(callbackReqId || "").trim(); const chatKey = String(chatId || "").trim(); const fromChat = state.lastCallback.get(chatKey) || ""; + // 只用本群 req_id:跨群回退会把话发到别的群(企微按 req_id 投递)。 const replyReqId = pickReplyReqId({ fromCaller, fromChat, - lastAny: state.lastAnyReq || "", }); // 用这次 @ 的 req_id 回 aibot_respond_msg,群里才会引用原消息。 const reqId = replyReqId || generateReqId("aibot_send_msg"); @@ -275,17 +274,61 @@ function startLongConnectionLoop(opts) { wait.reject(err); } + /** + * 把企微智能机器人回调归一成智能体入站结构。 + * + * 2026-11-19 补(真机问题:@BOT 换行带图时正文变空): + * - 群聊里图片/文件/视频的独立回调企微不推,@ 带图只会来 mixed(文字+图片); + * - 以前只读 body.text,mixed 的正文和图片地址全丢,智能体把空正文当文字去要工单号。 + * 这里把 mixed 的多段文字拼成 content,把图片地址放进 media(加密 URL、5 分钟过期, + * 只用于判断「只有图没有字」,不在这里下载)。 + * 文件消息官方不给文件名,只有加密 URL,因此群聊文件仍只走会话存档。 + */ function normalizeInbound(frame) { const body = frame.body || {}; const from = body.from || {}; - const text = (body.text && body.text.content) || ""; + const msgType = String(body.msgtype || "text"); + let text = (body.text && body.text.content) || ""; + const media = {}; + if (msgType === "mixed") { + const items = + body.mixed && Array.isArray(body.mixed.msg_item) ? body.mixed.msg_item : []; + const texts = []; + const images = []; + for (const item of items) { + if (!item || typeof item !== "object") { + continue; + } + if (item.msgtype === "text" && item.text && item.text.content) { + texts.push(String(item.text.content)); + } + if (item.msgtype === "image" && item.image && item.image.url) { + images.push(String(item.image.url)); + } + } + if (!text && texts.length) { + text = texts.join("\n"); + } + if (images.length) { + media.image_count = images.length; + media.image_urls = images; + } + } else if (body.image && body.image.url) { + media.image_count = 1; + media.image_url = String(body.image.url); + } else if (body.video && body.video.url) { + media.video_url = String(body.video.url); + } else if (body.file && body.file.url) { + media.file_url = String(body.file.url); + } return { sender_id: String(from.userid || "").trim(), message_id: String(body.msgid || (frame.headers && frame.headers.req_id) || "").trim(), content: text, - msg_type: String(body.msgtype || "text"), + msg_type: msgType, chat_id: String(body.chatid || "").trim(), chat_type: body.chattype === "single" ? "c2c" : "group", + media, raw: { source: "aibot", aibot_req_id: frame.headers && frame.headers.req_id, @@ -335,9 +378,6 @@ function startLongConnectionLoop(opts) { if (reqId && chatKey) { state.lastCallback.set(chatKey, reqId); } - if (reqId) { - state.lastAnyReq = reqId; - } const officialBody = Object.assign({}, frame.body || {}, { aibot_direct: true, aibot_req_id: reqId || "", @@ -349,6 +389,8 @@ function startLongConnectionLoop(opts) { content: inbound.content, chat_id: inbound.chat_id, chat_type: inbound.chat_type, + // 2026-11-19:mixed 的图片地址等元信息必须一起转,否则智能体只看到空正文。 + media: inbound.media || {}, }) : officialBody; if (!payload.sender_id && !payload.from) { diff --git a/aibot-bridge/tests/group_message_frame.test.cjs b/aibot-bridge/tests/group_message_frame.test.cjs index 5f1cf44..b3eb036 100644 --- a/aibot-bridge/tests/group_message_frame.test.cjs +++ b/aibot-bridge/tests/group_message_frame.test.cjs @@ -39,10 +39,20 @@ test("dimension asterisks stay visible in group markdown", () => { assert.equal(again.body.markdown.content, "体积(CBM)(必填):`1.1*2.1*2.1`"); }); -test("reply req id falls back to last inbound when chat map misses", () => { - assert.equal(pickReplyReqId({ fromCaller: "cb_1", fromChat: "old", lastAny: "any" }), "cb_1"); - assert.equal(pickReplyReqId({ fromCaller: "", fromChat: "chat_cb", lastAny: "any" }), "chat_cb"); - assert.equal(pickReplyReqId({ fromCaller: "", fromChat: "", lastAny: "jeD_msF" }), "jeD_msF"); - assert.equal(pickReplyReqId({ fromCaller: "", fromChat: "", lastAny: "" }), ""); +test("reply req id only uses the same chat, never the last inbound from another chat", () => { + assert.equal(pickReplyReqId({ fromCaller: "cb_1", fromChat: "old" }), "cb_1"); + assert.equal(pickReplyReqId({ fromCaller: "", fromChat: "chat_cb" }), "chat_cb"); + // 2026-11-21 测服事故:没有本群 req_id 时必须主动发言,不能借用别的群 req_id。 + assert.equal(pickReplyReqId({ fromCaller: "", fromChat: "" }), ""); +}); + +test("proactive message to a chat without its own callback uses aibot_send_msg", () => { + const frame = buildGroupMessageFrame({ + chatId: "wr_land_group", + content: "产品响应超时", + callbackReqId: pickReplyReqId({ fromCaller: "", fromChat: "" }), + }); + assert.equal(frame.cmd, "aibot_send_msg"); + assert.equal(frame.body.chatid, "wr_land_group"); }); diff --git a/inquiry-agent/agent/channel/h5/land_route_page.py b/inquiry-agent/agent/channel/h5/land_route_page.py index 0b0d513..b4fc4f0 100644 --- a/inquiry-agent/agent/channel/h5/land_route_page.py +++ b/inquiry-agent/agent/channel/h5/land_route_page.py @@ -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 "" ) 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"
  • {html.escape(name)}" diff --git a/inquiry-agent/agent/channel/runtime.py b/inquiry-agent/agent/channel/runtime.py index 9bfbbbe..e1112b8 100644 --- a/inquiry-agent/agent/channel/runtime.py +++ b/inquiry-agent/agent/channel/runtime.py @@ -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 diff --git a/inquiry-agent/agent/channel/wecom/open_userid.py b/inquiry-agent/agent/channel/wecom/open_userid.py new file mode 100644 index 0000000..5e972fd --- /dev/null +++ b/inquiry-agent/agent/channel/wecom/open_userid.py @@ -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" diff --git a/inquiry-agent/agent/channel/wshoto/parse.py b/inquiry-agent/agent/channel/wshoto/parse.py index 848880e..c47ac55 100644 --- a/inquiry-agent/agent/channel/wshoto/parse.py +++ b/inquiry-agent/agent/channel/wshoto/parse.py @@ -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 "", diff --git a/inquiry-agent/agent/channel/wshoto/poll.py b/inquiry-agent/agent/channel/wshoto/poll.py index ef11c0b..5a1983a 100644 --- a/inquiry-agent/agent/channel/wshoto/poll.py +++ b/inquiry-agent/agent/channel/wshoto/poll.py @@ -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 diff --git a/inquiry-agent/agent/config/__init__.py b/inquiry-agent/agent/config/__init__.py index c505458..c57dbc4 100644 --- a/inquiry-agent/agent/config/__init__.py +++ b/inquiry-agent/agent/config/__init__.py @@ -134,6 +134,23 @@ class Settings(BaseSettings): default="http://127.0.0.1:8910/internal/aibot/inbound", alias="WECOM_AIBOT_INGRESS_URL", ) + # 群入站「加密 open_userid → 明文 userid」归一开关(2026-11-19 真机问题)。 + # + # 为什么需要:企微智能机器人回调的 from.userid,只有在「机器人创建者是超级管理员」 + # 时才是明文;否则是企业主体下的加密 open_userid(wo 开头)。群里成交/报价/锁舱 + # 都要拿它跟主账 sales_wecom_id、岗位名单比字符串,加密值永远比不上,业务全被判 + # 「不是本人」。这里做的不是「事后向企微补身份」,而是把入站报文中同一个 ID 解密 + # 回它本来的 userid,身份来源仍是入站报文。 + # + # 默认关:正服不配这个变量就完全保持既有行为(不产生任何企微调用), + # 由测服先打开验证,正服另行发布。 + wecom_openid_normalize_enabled: bool = Field( + default=False, alias="WECOM_OPENID_NORMALIZE_ENABLED" + ) + # 兑换接口超时(秒)。必须短:它在 inbox 工作线程里跑,不能拖住整条通道。 + wecom_openid_normalize_timeout_sec: float = Field( + default=3.0, alias="WECOM_OPENID_NORMALIZE_TIMEOUT_SEC" + ) deepseek_api_key: str = Field(default="", alias="DEEPSEEK_API_KEY") deepseek_base_url: str = Field(default="https://api.deepseek.com", alias="DEEPSEEK_BASE_URL") diff --git a/inquiry-agent/agent/handlers/air_group_collab.py b/inquiry-agent/agent/handlers/air_group_collab.py index 092fcea..dcabcb4 100644 --- a/inquiry-agent/agent/handlers/air_group_collab.py +++ b/inquiry-agent/agent/handlers/air_group_collab.py @@ -158,16 +158,21 @@ def handle_air_group( return "group_ignore" kind = (message.msg_type or "text").lower() if kind in {"file", "image", "video"}: - return _handle_file(engine, message) + return _handle_file( + engine, + message, + explicit=bool((message.raw or {}).get("at_burst_explicit")), + ) text = message.content or "" from agent.redis_coord.air_inbound import mark_air_text, should_skip_air_text - if should_skip_air_text( + skipped = should_skip_air_text( chat_id=chat_id, sender_id=message.sender_id, text=text, raw=message.raw, - ): + ) + if skipped: return "duplicate_inbound" mark_air_text(chat_id=chat_id, sender_id=message.sender_id, text=text) wo = copy.extract_work_order_no(text) @@ -264,9 +269,12 @@ def handle_air_group( ) -def _handle_file(engine, message: InboundMessage) -> str: +def _handle_file(engine, message: InboundMessage, *, explicit: bool = False) -> str: """ 存档听到的附件(发文件不能 @)。句中/文件名有工单号先切单;没有就跟当前单。 + + 参数 explicit:本次指令里明确 @ 过机器人(dispatch 打标)。 + 只影响「不收的文件类型」是否回一句;Excel/PDF 本来就一直有保存回执。 """ chat_id = message.chat_id media = dict(message.media or {}) @@ -303,6 +311,7 @@ def _handle_file(engine, message: InboundMessage) -> str: sender_id=message.sender_id, filename=filename, media=media, + explicit=explicit, ) if wo: ticket, phase = activate_ticket( @@ -325,6 +334,7 @@ def _handle_file(engine, message: InboundMessage) -> str: filename=filename, media=media, chat_id=chat_id, + explicit=explicit, ) diff --git a/inquiry-agent/agent/handlers/group_collab.py b/inquiry-agent/agent/handlers/group_collab.py index 6bd9b35..768c239 100644 --- a/inquiry-agent/agent/handlers/group_collab.py +++ b/inquiry-agent/agent/handlers/group_collab.py @@ -101,6 +101,26 @@ def handle_group_inbound( chat_id=chat_id, sender_id=message.sender_id or "", ) + # BOT 群已 @ 了机器人,但对不上任何工单:按产品口径提示重新下达任务, + # 不能装没听见(此时 dispatch 已保证这条是 @BOT 的文字)。 + from agent.redis_coord.group_bot import is_group_bot + + if ( + is_group_bot(chat_id) + and kind_orphan in {"", "text"} + and (message.content or "").strip() + ): + from agent.policy import inquiry_copy as copy + + send_group_text(group_client_of(engine), chat_id, copy.air_need_work_order()) + return "need_work_order" + # 明确 @ 过机器人却发来附件、群里又对不上工单:同样要回一句, + # 否则真机就是「发文件 + @机器人,BOT 一声不吭」(2026-11-21)。 + if is_group_bot(chat_id) and (message.raw or {}).get("at_burst_explicit"): + from agent.policy import inquiry_copy as copy + + send_group_text(group_client_of(engine), chat_id, copy.air_need_work_order()) + return "need_work_order" return "group_ignore" if flow is None: view0 = ticket_view(ticket) @@ -150,6 +170,7 @@ def handle_group_inbound( sender_id=message.sender_id, filename=filename, media=media, + explicit=bool((message.raw or {}).get("at_burst_explicit")), ) # 按需出表:多段群也认「生成报价单」,不要先被段报价抽取抢走。 from agent.routing.group_intent import ( @@ -249,6 +270,8 @@ def handle_group_inbound( filename=filename, media=media, sess=sess, + # dispatch 打的「本次指令明确 @ 过机器人」标记:处理完必须回一句,不能静默存档。 + explicit=bool((message.raw or {}).get("at_burst_explicit")), ) from agent.routing.group_intent import ( diff --git a/inquiry-agent/agent/handlers/text_inquiry.py b/inquiry-agent/agent/handlers/text_inquiry.py index b3e1498..e132647 100644 --- a/inquiry-agent/agent/handlers/text_inquiry.py +++ b/inquiry-agent/agent/handlers/text_inquiry.py @@ -21,6 +21,28 @@ from agent.policy.sea_text_flow import get_sea_text_flow logger = logging.getLogger(__name__) +def _mode_from_clarify_labels(text: str) -> str: + """ + 从补问粘贴清单的字段标签认运输方式。 + + 销售回填补问时常常不写「海运/陆运/空运」四个字,只贴字段行。 + 有「整柜或拼柜 / 箱型箱量」几乎只能是海运;「业务类型 + 报价场景」是陆运选项; + 「件数 + 毛重/体积」偏空运。标签互相打架时宁可不认,交给后面书签或默认空运。 + """ + raw = text or "" + sea_hits = sum(1 for k in ("整柜或拼柜", "箱型箱量", "货量", "贸易条款") if k in raw) + land_hits = sum(1 for k in ("业务类型", "报价场景", "车型/数量", "通关口岸") if k in raw) + air_hits = sum(1 for k in ("件数", "毛重", "体积", "包装方式", "包装类型") if k in raw) + # 海运清单也会写起运港/品名,不能只靠这两个;以柜型类字段为准。 + if sea_hits >= 2 and sea_hits >= land_hits and sea_hits >= air_hits: + return "SEA" + if land_hits >= 2 and land_hits > sea_hits and land_hits >= air_hits: + return "LAND" + if air_hits >= 2 and air_hits > sea_hits and air_hits > land_hits: + return "AIR" + return "" + + def _front_bookmark(sess) -> bool: """补问/核对手稿优先于已出票旧书签。还没定运输方式的草稿不算当前询价,避免抢走另一条已在补问的单。已转人工的票也不再当当前询价。""" if sess is None: @@ -154,6 +176,61 @@ def _drop_other_mode_drafts(*, owner: str, sender_id: str) -> None: clearer(sid) +def lost_reason_wait_state(sender_id: str) -> dict[str, Any]: + """ + 只读快照:当前是否有空运/海运/陆运书签停在「等未成交原因」。 + + 为什么单独抽出来(2026-11-22 正服 WO202611170021):销售点完「未成交」后 + BOT 回「请补充未成交原因」,下一句销售说「客户不要了」,DeepSeek A 把这句 + 误判成 end_inquiry;dispatch 直接把上下文清掉,未成交原因永远进不了主账。 + 分发层需要在调用 end_inquiry 之前知道「这条人正在等原因」,把这句话交回 + 询价流程当原因收下。本函数只读书签,不发消息、不改状态。 + + 返回:waiting / phase / work_order_no / status / business_line。 + 不含多段:多段流程目前没有收未成交原因的实现,不能在这里把原因吞掉。 + """ + out: dict[str, Any] = { + "waiting": False, + "phase": "", + "work_order_no": "", + "status": "", + "business_line": "", + } + sid = (sender_id or "").strip() + if not sid: + return out + try: + from agent.policy.air_text_flow import get_air_text_flow + from agent.policy.land_text_flow import get_land_text_flow + from agent.policy.sea_text_flow import get_sea_text_flow + + candidates = ( + ("AIR", get_air_text_flow()), + ("SEA", get_sea_text_flow()), + ("LAND", get_land_text_flow()), + ) + for line, flow in candidates: + sess = flow.session_of(sid) + if sess is None: + continue + phase = (sess.phase or "").strip() + if phase != "wait_lost_reason": + continue + out.update( + { + "waiting": True, + "phase": phase, + "work_order_no": str(getattr(sess, "work_order_no", "") or ""), + "status": str(getattr(sess, "status", "") or ""), + "business_line": line, + } + ) + return out + except Exception: # noqa: BLE001 - 取证失败不能影响入站分发 + logger.exception("读未成交原因等待状态失败 sender=%s", sid) + return out + + def _flow_waiting_lost_reason(sender_id: str, sea, air, land): """谁在等未成交原因就交给谁。刚记下未成交的那条优先。""" from agent.policy.deal_outcome import ticket_missing_in_ledger @@ -259,15 +336,31 @@ def _pick_text_flow(*, sender_id: str, text: str, injected_mode: str = "", prefe return multi # 本句点名运输方式:盖掉其它方式的旧补问,避免海运补字段走陆运样例图。 # 多段正在补问时例外:销售会写「段2:运输方式:空运」,不能把多段草稿丢掉改走单段。 + # 但「例外」只留给真多段续问(段标 / 本句自身两段)。销售单独发一句「陆运询价」 + # 是新开单段,必须按本句方式走,并把旧多段草稿让掉;否则一张多段比价草稿 + # 会把后面每一句都接走(2026-11-19 正服事故,持续到进程重启)。 # 已出号等拉群不算补问:再发陆运附件要走陆运,不能粘在旧工单的手动拉群提示上。 if spoken in {"SEA", "AIR", "LAND"}: + from agent.policy.multi_segments import is_multi_continuation + multi_draft = multi.session_of(sender_id) - if ( + multi_waiting = bool( multi_draft and (multi_draft.business_line or "").upper() == "MULTI" and (multi_draft.phase or "") in {"clarify", "sensitive_block"} - ): + ) + if multi_waiting and is_multi_continuation(text): return multi + if multi_waiting: + # 本句是新开单段:让位前丢掉多段草稿,避免下一句补字段又被多段接走。 + # 只丢当前书签,已出号的工单仍按工单号留在主账。 + multi.drop_current_bookmark(sender_id) + logger.info( + "text_inquiry 旧多段草稿让位 owner=%s multi_phase=%s sender=%s", + spoken, + (multi_draft.phase or "-") if multi_draft else "-", + sender_id, + ) _drop_other_mode_drafts(owner=spoken, sender_id=sender_id) stale_handoff = (multi_draft.phase or "") in { "wait_collab", @@ -281,6 +374,12 @@ def _pick_text_flow(*, sender_id: str, text: str, injected_mode: str = "", prefe if spoken == "LAND": return land return air + # 本句没点名运输方式时:多段草稿也不能无条件接管。 + # 正服 2026-11-23:销售粘贴海运补问清单(起运港/整柜或拼柜/贸易条款…,无「海运」二字), + # spoken 为空,旧逻辑仍因 multi=clarify 把整句交给多段,回「段1:陆运」。 + # 只有真多段续问(段标/本句两段)或核对卡上的「确定」才继续多段;其余让位给单段。 + from agent.policy.multi_segments import is_multi_continuation + multi_sess = multi.session_of(sender_id) if ( multi_sess @@ -288,7 +387,28 @@ def _pick_text_flow(*, sender_id: str, text: str, injected_mode: str = "", prefe and (multi_sess.phase or "") in {"clarify", "wait_confirm", "sensitive_block"} and not (looks_like_confirm(text) and (multi_sess.phase or "") != "wait_confirm") ): - return multi + phase_now = (multi_sess.phase or "").strip() + if phase_now == "wait_confirm" and looks_like_confirm(text): + return multi + if is_multi_continuation(text): + return multi + multi.drop_current_bookmark(sender_id) + logger.info( + "text_inquiry 旧多段草稿让位 owner=LABEL_OR_SINGLE multi_phase=%s sender=%s", + phase_now or "-", + sender_id, + ) + # 补问粘贴常不写「海运/陆运」:用字段标签认方式,避免让位后落到默认空运。 + label_mode = _mode_from_clarify_labels(text) + if label_mode == "SEA": + _drop_other_mode_drafts(owner="SEA", sender_id=sender_id) + return sea + if label_mode == "LAND": + _drop_other_mode_drafts(owner="LAND", sender_id=sender_id) + return land + if label_mode == "AIR": + _drop_other_mode_drafts(owner="AIR", sender_id=sender_id) + return air sea_sess = sea.session_of(sender_id) land_sess = land.session_of(sender_id) air_sess = air.session_of(sender_id) @@ -375,6 +495,48 @@ def is_land_confirm_action(message: InboundMessage) -> bool: return is_pending_land_confirm(message) or is_pending_land_tms_retry(message) +def _log_flow_pick( + *, + sender_id: str, + text: str, + engine: Any, + injected_mode: str = "", +) -> None: + """ + 记一行「这一单最后走了哪条线、为什么走这条线」。 + + 为什么需要(2026-11-19 正服事故):当时销售发「陆运询价」,模型也判出 LAND, + 但回的是海运补问;正服日志里只有 dispatch 意图和 schema.validate 的 line, + 看不出选流那一刻本句点名了什么方式、三条线各自还挂着什么书签,只能靠猜。 + 这里把 spoken(本句点名的方式)和四条线的书签阶段一次打出来, + 下次同样问题能直接对着日志定位,不必再翻 Redis。 + + 只读:不建书签、不掉书签、不改任何会话;失败也不影响业务(只记异常)。 + """ + try: + from agent.policy.multi_text_flow import get_multi_text_flow + + def _state(sess: Any) -> str: + # 形如 clarify/SEA;没有书签记 "-",方便一眼区分「没书签」和「有书签但阶段空」 + if sess is None: + return "-" + return f"{sess.phase or '-'}/{(sess.business_line or '-')}" + + spoken = (injected_mode or detect_transport_mode(text or "") or "").upper() or "-" + logger.info( + "text_inquiry 选流 engine=%s spoken=%s sea=%s air=%s land=%s multi=%s chars=%d", + type(engine).__name__, + spoken, + _state(get_sea_text_flow().session_of(sender_id)), + _state(get_air_text_flow().session_of(sender_id)), + _state(get_land_text_flow().session_of(sender_id)), + _state(get_multi_text_flow().session_of(sender_id)), + len(text or ""), + ) + except Exception: # noqa: BLE001 - 留痕失败绝不能影响询价主链路 + logger.exception("text_inquiry 选流留痕失败 sender=%s", sender_id) + + def handle_text_inquiry( message: InboundMessage, *, @@ -408,6 +570,14 @@ def handle_text_inquiry( injected_mode=injected_mode, prefer_quoted=prefer_quoted, ) + # 只有自己选流时才留痕:调用方直接指定 flow 时,选流不是这里决定的,记了会误导。 + if flow is None: + _log_flow_pick( + sender_id=message.sender_id, + text=message.content or "", + engine=engine, + injected_mode=injected_mode, + ) replies: list[str] = [] def reply(text: str, extra: dict | None = None) -> str: diff --git a/inquiry-agent/agent/jobs/deal_followup_poll.py b/inquiry-agent/agent/jobs/deal_followup_poll.py index e052426..2dbfb2e 100644 --- a/inquiry-agent/agent/jobs/deal_followup_poll.py +++ b/inquiry-agent/agent/jobs/deal_followup_poll.py @@ -151,7 +151,10 @@ def _send_group_reask( settings: Settings, ) -> bool: text = copy.group_deal_followup(sales_name=sales_name, work_order_no=work_order_no) - if business_line == "AIR": + # 空运群、以及已由 BOT 接管的陆运/海运协同群,都只能走机器人桥发群。 + from agent.redis_coord.group_bot import is_group_bot + + if business_line == "AIR" or is_group_bot(chat_id): from agent.channel.aibot.reply import AibotReplyClient out = AibotReplyClient().send_group(chat_id=chat_id, content=text) diff --git a/inquiry-agent/agent/jobs/event_exception_poll.py b/inquiry-agent/agent/jobs/event_exception_poll.py index 9421460..d5679f7 100644 --- a/inquiry-agent/agent/jobs/event_exception_poll.py +++ b/inquiry-agent/agent/jobs/event_exception_poll.py @@ -222,6 +222,16 @@ def _handle_one( mention=mention, test_prefix=test_prefix, ) + # 发群定位:工单、等待种类、业务线、会话类型、群号尾号。 + # 只打定位字段,不打印正文;排查「超时提醒发错群」时按时间线对齐桥日志。 + logger.info( + "事件异常准备发群 wo=%s kind=%s line=%s where=%s chat=%s", + no, + kind, + line or "-", + where, + chat_id[-12:] if chat_id else "", + ) ok_session = False if where == "group": if not chat_id: @@ -378,7 +388,25 @@ def _default_enqueue(**kwargs: Any) -> tuple[bool, str]: def _default_send_group(*, chat_id: str, content: str, business_line: str = "") -> bool: line = (business_line or "").strip().upper() - if line == "AIR": + # 选路标准(2026-11-21 测服事故教训): + # - 空运群是人自建的 BOT 群,只能走机器人桥; + # - 海运/陆运协同群目前都是应用 appchat 群(建群时就写了 group_bot 标记), + # 应用自己就是群成员,必须走 appchat/send; + # - 只有「真的收到过 AIBOT 回调」的群(bot_seen),才说明 BOT 在群里、可以走桥。 + # 不能再用 is_group_bot 判断:它在建群时就会写,应用群也会命中,结果超时话术 + # 被桥按「最近一次本群 req_id」投递到最后 @ 过机器人的空运群。 + from agent.redis_coord.group_bot import bot_seen + + bot_room = bool(bot_seen(chat_id)) + use_aibot = line == "AIR" or bot_room + logger.info( + "事件异常发群选路 chat=%s line=%s bot_seen=%s use_aibot=%s", + (chat_id or "")[-12:], + line or "-", + bot_room, + use_aibot, + ) + if use_aibot: from agent.channel.aibot.reply import AibotReplyClient out = AibotReplyClient().send_group(chat_id=chat_id, content=content) diff --git a/inquiry-agent/agent/llm/extract_text.py b/inquiry-agent/agent/llm/extract_text.py index 0ced4df..e8a7934 100644 --- a/inquiry-agent/agent/llm/extract_text.py +++ b/inquiry-agent/agent/llm/extract_text.py @@ -9,15 +9,27 @@ from __future__ import annotations import logging import re +from dataclasses import dataclass from typing import Any, Optional try: from agent.schema.field_validate import QUOTE_DATE_SYNONYMS except ImportError: # 测服旧 release 未导出同义词时仍可抽产品价 QUOTE_DATE_SYNONYMS = () +try: + from agent.schema.land_quote_condition import ( + apply_to_quote as apply_land_quote_condition, + parse_land_quote_condition, + strip_land_quote_condition, + ) +except ImportError: # 测服旧 release 缺模块时不阻断其它业务线出价 + apply_land_quote_condition = None + parse_land_quote_condition = None + strip_land_quote_condition = None logger = logging.getLogger(__name__) + # 报价日期同义词。长的在前,避免短词截断。货好时间、提货地址不在这里。 _QUOTE_DATE_LABEL_RE = "|".join( re.escape(name) @@ -29,6 +41,17 @@ _MODE_WORDS = ( ("海运", "SEA"), ("陆运", "LAND"), ) +_MODE_BY_WORD = {"空运": "AIR", "海运": "SEA", "陆运": "LAND"} +# 候选:文中出现的空运/海运/陆运;是否「真在说运输方式」再交给 _is_mode_mention。 +_MODE_TOKEN = re.compile(r"空运|海运|陆运") +# 复合词尾巴:…运输… / …运费 → 不是运输方式。 +_MODE_COMPOUND_TAIL = frozenset("输费") +# 左侧:标点/空白/并列,或点名方式的动词。 +_MODE_LEFT_BREAK = frozenset(" \t,,、;;::。!??\n/\\|(([【和与及跟再++") +_MODE_LEFT_VERB = frozenset("走做报要用是改转查选定按") +# 右侧:方式说完或接询价/到港。 +_MODE_RIGHT_BREAK = frozenset(" \t,,、;;::。!??\n/\\|))]】和与及跟再++") +_MODE_RIGHT_HEAD = ("询价", "报价", "查价", "到", "去", "从", "往", "至", "港", "场", "站") # 未定运输方式时:整句只回 1/2/3 对应陆运/海运/空运。10件、1.件数 不算。 _MODE_INDEX = re.compile(r"^\s*([1231-3])\s*[\.、.]?\s*$") _MODE_BY_INDEX = { @@ -46,10 +69,10 @@ _LABEL_KEYS = ( r"包装方式|包装类型|货量|货物数量|整柜或拼柜|箱型箱量|" + _QUOTE_DATE_LABEL_RE + r"|运输分类|车型/数量|车型数量|" - r"贸易条款|货好时间|货源地|提货地址|收货地址|送货地址|增值服务(非必填)|增值服务|商品海关编码|海关编码|HS编码|HS|" + r"贸易条款|货好时间|货源地|海运提货地址|海运派送地址|提货地址|收货地址|送货地址|派送地址|增值服务(非必填)|增值服务|商品海关编码|海关编码|HS编码|HS|" r"是否含油|是否含电|是否带电|是否含磁|" r"尺寸(非必填)|尺寸|货物尺寸|比例(非必填)|比例|货型|泡比|重泡比|泡重比|" - r"客户名称|货值|是否为危险品|通关口岸(非必填)|通关口岸" + r"客户名称(非必填)|客户名称|货值|是否为危险品|通关口岸(非必填)|通关口岸" ) _LABEL_LINE = re.compile(rf"^({_LABEL_KEYS})\s*[::]\s*(.+)$") _LABEL_INLINE = re.compile(rf"({_LABEL_KEYS})\s*[::]\s*(\S+)") @@ -59,8 +82,11 @@ _OPTIONAL_INQUIRY_LABELS = ( "通关口岸", "货源地(非必填)", "货好时间(非必填)", + "海运提货地址(非必填)", + "海运派送地址(非必填)", "提货地址(非必填)", "收货地址(非必填)", + "派送地址(非必填)", "贸易条款(非必填)", "起运地(非必填)", "起运港(非必填)", @@ -68,9 +94,12 @@ _OPTIONAL_INQUIRY_LABELS = ( "比例(非必填)", "货源地", "货好时间", + "海运提货地址", + "海运派送地址", "提货地址", "收货地址", "送货地址", + "派送地址", "贸易条款", "尺寸", "货物尺寸", @@ -82,6 +111,9 @@ _OPTIONAL_INQUIRY_LABELS = ( "增值服务(非必填)", "增值服务", "起运港", + # 客户名称在询价核对卡上以(非必填)出现,海空陆都可能被销售整卡复制回来。 + "客户名称(非必填)", + "客户名称", ) # 图上常见「4. 希望送到…」:编号项不是询价字段,值收到这里为止。 _NUMBERED_ITEM = re.compile(r"(?m)^\s*\d+[\.、.]\s+\S") @@ -120,9 +152,12 @@ _CLARIFY_NAMES = frozenset( "贸易条款", "货源地", "货好时间", + "海运提货地址", + "海运派送地址", "提货地址", "收货地址", "送货地址", + "派送地址", "通关口岸", "始发站", "增值服务", @@ -268,6 +303,94 @@ _COLLAB_LABELS = ( ) +@dataclass(frozen=True) +class TransportModeHit: + """原文里一次「真在说运输方式」的命中。""" + + start: int + end: int + word: str + code: str + + +def _is_mode_mention(text: str, start: int, end: int) -> bool: + """ + 这里的空运/海运/陆运是不是在说「运输方式」。 + + 判定(不猜港口、不改六态): + 1. 后面紧跟「输/费」→ 「运输/运费」复合词,不是方式; + 2. 句首,或前面是标点/并列/走报选用…,或「运输方式」「段N:」→ 是; + 3. 后面是询价/到港/标点/结尾 → 是; + 4. 夹在别的词中间(如地名里拼出的两字)→ 不是。 + """ + raw = text or "" + if start < 0 or end > len(raw) or end - start < 2: + return False + # 1) 复合词:上海运输费、威海运输、航空运输、大陆运费 + if end < len(raw) and raw[end] in _MODE_COMPOUND_TAIL: + return False + left = raw[:start] + right = raw[end:] + # 2) 左侧:点名方式 + if start == 0: + return True + prev = left[-1] + if prev in _MODE_LEFT_BREAK or prev in _MODE_LEFT_VERB: + return True + tail = left[-10:] + if "运输方式" in tail: + return True + if re.search(r"段\s*\d+\s*[::]?\s*$", tail): + return True + if re.search(r"第[一二三四五六七八九\d]+\s*段\s*[::,,]?\s*$", tail): + return True + # 3) 右侧:方式说完或接线路 + if not right: + return True + if right[0] in _MODE_RIGHT_BREAK: + return True + if right.startswith(_MODE_RIGHT_HEAD): + return True + # 4) 以往询价常见:方式贴在 A到B 后面,中间不打标点 + # 欢迎语示例「上海到洛杉矶空运,3件」;口语「广州到深圳陆运衣服」「上海到汉堡海运20GP」 + # 左侧近处有「到…」目的地,且本词不是运输/运费复合,才认成方式。 + if re.search(r"到.{1,30}$", left, flags=re.DOTALL): + nxt = right[0] + if nxt.isdigit() or nxt in _MODE_RIGHT_BREAK: + return True + # 方式后直接跟货描/箱型(衣服、普货、整柜、40HQ、20GP…) + if "\u4e00" <= nxt <= "\u9fff": + return True + if right.upper().startswith(("GP", "HQ", "OT", "RF", "FCL", "LCL", "20", "40", "45")): + return True + # 5) 夹在别的词中间拼出来的两字(无「到」语境)→ 不是方式 + return False + + +def find_transport_mode_hits(text: str) -> list[TransportModeHit]: + """ + 找出原文里真正在说运输方式的空运/海运/陆运。 + + 销售口语「陆运北京到上海运输费」只应命中陆运,不能把「上海运」当成海运。 + 副作用:无。不改主账。 + """ + raw = text or "" + out: list[TransportModeHit] = [] + for hit in _MODE_TOKEN.finditer(raw): + word = hit.group(0) + if not _is_mode_mention(raw, hit.start(), hit.end()): + continue + code = _MODE_BY_WORD.get(word) + if not code: + continue + out.append( + TransportModeHit( + start=hit.start(), end=hit.end(), word=word, code=code + ) + ) + return out + + def detect_transport_mode(text: str) -> str: """ 运输方式:空运/海运/陆运,或空运口语「飞」(南京飞吉隆坡)。 @@ -284,7 +407,9 @@ def detect_transport_mode(text: str) -> str: 多段句(同时提到海运和整车)由 multi_text_flow 先接,这里不回单段。 """ raw = text or "" - found = [code for word, code in _MODE_WORDS if word in raw] + hits = find_transport_mode_hits(raw) + # 同一方式出现多次仍算一种;两种以上方式则交给多段,这里不回单段。 + found = list(dict.fromkeys(h.code for h in hits)) if len(found) == 1: return found[0] if len(found) > 1: @@ -1093,14 +1218,18 @@ _RE_WEIGHT_BAND_OPEN = re.compile( ) # 陆运整车产品口语:车型:5T/8T:13000 10T:14000 40HQ/45HQ:19500 # 标签可斜杠并价(5T/8T 同价);40/45HQ 要拆成 40HQ+45HQ。金额至少三位,避免吃到「段1」。 +# 米长车型(7.6米、9.6米、6.8米/5T)是报价单表头写法,必须认,否则「7.6米CNY13000」 +# 会掉到普通金额回退里,把 7.6 当成运费(运行样例:东莞-春疆 7.6米/9.6米/45HQ 三档)。 +# 车型与金额之间允许逗号/顿号/分号:「45HQ,CNY18500」。 _RE_VEHICLE_RATE_ITEM = re.compile( r"(?P