协同群改为智价通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
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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 (
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<label>"
|
||||
r"\d+(?:\.\d+)?\s*(?:T|吨|HQ|GP|尺)"
|
||||
r"(?:\s*/\s*\d+(?:\.\d+)?\s*(?:T|吨|HQ|GP|尺)?)*"
|
||||
r"\d+(?:\.\d+)?\s*(?:T|吨|HQ|GP|尺|米)"
|
||||
r"(?:\s*/\s*\d+(?:\.\d+)?\s*(?:T|吨|HQ|GP|尺|米)?)*"
|
||||
r"|"
|
||||
r"\d+\s*/\s*\d+\s*(?:HQ|GP|尺|T|吨)"
|
||||
r"\d+\s*/\s*\d+\s*(?:HQ|GP|尺|T|吨|米)"
|
||||
r")"
|
||||
r"\s*[::=]?\s*"
|
||||
r"[,,、;;]?\s*"
|
||||
rf"(?:(?P<ccy>{_CCY_TOKEN})\s*)?"
|
||||
r"(?P<price>\d{3,}(?:\.\d+)?)",
|
||||
re.I,
|
||||
@@ -1110,6 +1239,9 @@ _RE_VEHICLE_QUOTE_REMARK = re.compile(
|
||||
r"(含\s*0\s*点\s*税?|含\s*0\s*点|国六车提货|不含税|含税)",
|
||||
re.I,
|
||||
)
|
||||
# 「都是含0点税」= 税率 0。单独拎出来是因为它还能填税率字段,不只是备注。
|
||||
# 只认 0 点税;「含税/不含税」看不出具体点数,仍只进备注,不许猜成 0 或 13。
|
||||
_RE_ZERO_TAX_WORD = re.compile(r"含\s*0\s*点\s*税?", re.I)
|
||||
_RE_FUEL_SURCHARGE_RATE = re.compile(
|
||||
r"燃油附加费率\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?",
|
||||
re.I,
|
||||
@@ -1144,6 +1276,29 @@ _RE_FEE_VEHICLE_PRICE = re.compile(
|
||||
)
|
||||
# 金额后紧跟车型单位:该数字是吨位/柜型,不是费用金额。
|
||||
_RE_AMOUNT_IS_VEHICLE_UNIT = re.compile(r"^\s*(?:T|吨|HQ|GP|尺)\b", re.I)
|
||||
# 产品文字报价自己写了计价单位:「陆运费1000/车」「运输费13元/KG」「报关费300元/票」。
|
||||
# 旧实现只认费名和金额,把结尾的单位整段丢掉 → 销售侧只看到 1000,
|
||||
# 分不清是整车价还是每公斤价(测服 WO202611220002 的反馈)。
|
||||
# 必须带 / 或「每」才算单位:「1000元」只是币种后缀,不是计价单位。
|
||||
_RE_AMOUNT_UOM_SUFFIX = re.compile(
|
||||
r"^\s*(?:(?:元|块|RMB|CNY)\s*)?(?:/|每)\s*"
|
||||
r"(?P<uom>次/人|小时/人|板数|页数|箱数|单数|票数|公里数|货值|计重|立方|平方米|平方|千克|"
|
||||
r"KGS|KG|CBM|M3|柜|票|板|点|次|人|天|个|份|张|台|件|卷|车|月|趟|周|批|项|托|套|袋|包|箱|吨|T)",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def _amount_uom_suffix(after_amount: str) -> str:
|
||||
"""
|
||||
金额后面自己写的计价单位:`/车`、`元/KG`、`每票` → 车 / KG / 票。
|
||||
|
||||
参数 after_amount 是原文里紧跟在金额数字之后的那一段。
|
||||
返回空串表示没写单位,调用方就不落 unit(禁止本地猜 KG/车)。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
hit = _RE_AMOUNT_UOM_SUFFIX.match(after_amount or "")
|
||||
return (hit.group("uom") or "").strip() if hit else ""
|
||||
|
||||
# 「压夜按运费80%」「压日按运费100%」是比例,禁止落成 HKD 80/100 再加进合计。
|
||||
_RE_FEE_OF_FREIGHT_PCT = re.compile(
|
||||
r"(?P<name>[\u4e00-\u9fff]{1,8}按运费|[\u4e00-\u9fffA-Za-z][\u4e00-\u9fffA-Za-z0-9/()()++\--]{0,16}费)"
|
||||
@@ -1250,6 +1405,26 @@ def _currency_of(text: str, hint: str = "") -> str:
|
||||
return "CNY" if hint_u == "RMB" else hint_u
|
||||
|
||||
|
||||
def _row_currency(sentence: str, explicit: str = "", base_ccy: str = "") -> str:
|
||||
"""
|
||||
单行费用的币种:行内显式币种 > 整句币种 > 主账基线。
|
||||
|
||||
为什么要单独一层:整句扫币种会把「运输费USD3200,燃油费USD300,
|
||||
过境费USD70,报关费CNY1400」统一成一种币,合计再把美元和人民币直接相加,
|
||||
得出一个假数(曾把 3200USD+1400CNY 报成 CNY 4970)。
|
||||
跨境陆运真实报价就是「运费美元、报关费人民币」混写,行内写了币种必须赢。
|
||||
|
||||
参数 explicit 只放该行自己匹配到的币种词(USD/CNY/美金…),空串表示该行没写。
|
||||
副作用:无。线程:调用方线程。
|
||||
"""
|
||||
hint = str(base_ccy or "").strip().upper()
|
||||
token = str(explicit or "").strip()
|
||||
if token:
|
||||
# 只拿行内片段去判币种,绝不把整句带进来,否则别的行的 cny 会把本行改掉。
|
||||
return _currency_of(token, hint) or hint
|
||||
return _currency_of(sentence, hint) or hint
|
||||
|
||||
|
||||
def _normalize_fee_project(raw: str) -> str:
|
||||
"""空运报价单项目列:空运段/起运港/目的地/其它。"""
|
||||
t = (raw or "").strip()
|
||||
@@ -1449,7 +1624,7 @@ def _parse_fee_rows(text: str, baseline_currency: str = "") -> list[dict[str, st
|
||||
if name in seen:
|
||||
return
|
||||
seen.add(name)
|
||||
line_ccy = _currency_of(raw, ccy or base_ccy) or base_ccy
|
||||
line_ccy = _row_currency(raw, ccy, base_ccy)
|
||||
row = {
|
||||
"name": name,
|
||||
"amount": amount,
|
||||
@@ -1523,12 +1698,15 @@ def _parse_fee_rows(text: str, baseline_currency: str = "") -> list[dict[str, st
|
||||
(hit.group("name") or "").strip(),
|
||||
amount,
|
||||
hit.group("ccy1") or hit.group("ccy2") or "",
|
||||
# 产品自己写的计价单位(1000/车、13元/KG)必须留着,出单和摘要都要用。
|
||||
unit=_amount_uom_suffix(after_amount),
|
||||
)
|
||||
for hit in _RE_FEE_CHANGE.finditer(raw):
|
||||
_add(
|
||||
(hit.group("name") or "").strip(),
|
||||
_ascii_amount(hit.group("amount") or ""),
|
||||
hit.group("ccy") or "",
|
||||
unit=_amount_uom_suffix(raw[hit.end("amount") :]),
|
||||
)
|
||||
return rows
|
||||
|
||||
@@ -1572,12 +1750,34 @@ _RE_UNIT_PRICE_PER_KG = re.compile(
|
||||
# 空运重量分档「+500」「+100」:不是附加费金额。服务词后的「卡转+1」不在此列。
|
||||
_RE_AIR_WEIGHT_BREAK = re.compile(r"(?<![A-Za-z0-9.\u4e00-\u9fff])\+(\d{2,4})(?!\d)")
|
||||
|
||||
# 「计费重800KG」是报价条件,不是费用行。本地已按体积/毛重算计费重,
|
||||
# 但报价行正则会把「计费」当成以「费」结尾的费用名,抽出「计费:800」这种假费目。
|
||||
# 抽取前先整段去掉;带货值由 air_chargeable.harvest_declared_chargeable 单独读。
|
||||
_RE_CHARGEABLE_DECL = re.compile(
|
||||
r"计费重(?:量)?\s*[::]?\s*\d[\d,]*(?:\.\d+)?\s*(?:KG|KGS|KGM|公斤|千克)?",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def _strip_chargeable_declaration(text: str) -> str:
|
||||
"""去掉「计费重800KG」这类报价条件,避免被当成一条费用。副作用:无。"""
|
||||
return _RE_CHARGEABLE_DECL.sub(" ", text or "")
|
||||
|
||||
|
||||
def _strip_work_order_tokens(text: str) -> str:
|
||||
"""去掉 WO+12 位工单号,禁止其数字被金额回退吃掉。"""
|
||||
return _RE_WORK_ORDER_TOKEN.sub(" ", text or "")
|
||||
|
||||
|
||||
# 车型/柜型号不是金额:「8T CNY990」单档车型价没认出来时,回退会先吃到 8(WO202611100043)。
|
||||
_RE_VEHICLE_LABEL_NOISE = re.compile(r"\d+(?:\.\d+)?\s*(?:T|吨|HQ|GP|尺|米)", re.I)
|
||||
|
||||
|
||||
def _strip_vehicle_label_noise(text: str) -> str:
|
||||
"""金额回退前剥掉车型/柜型号,禁止吨位数字被当运费。副作用:无。"""
|
||||
return _RE_VEHICLE_LABEL_NOISE.sub(" ", text or "")
|
||||
|
||||
|
||||
def _strip_air_quote_noise_for_money(text: str) -> str:
|
||||
"""
|
||||
金额回退前再剥:工单号、裸比例、口语月日、重量分档 +500。
|
||||
@@ -1627,10 +1827,12 @@ def _parse_unit_kg_quote(
|
||||
if not hit:
|
||||
return []
|
||||
price = _ascii_amount(hit.group("price") or "")
|
||||
ccy = _currency_of(
|
||||
(hit.group("ccy1") or "") + (hit.group("ccy2") or "") or raw,
|
||||
# 单价行自带币种(USD11/kg)优先,其次整句,最后主账基线;不许整句盖掉本行。
|
||||
ccy = _row_currency(
|
||||
raw,
|
||||
(hit.group("ccy1") or "") + (hit.group("ccy2") or ""),
|
||||
base_ccy,
|
||||
) or base_ccy
|
||||
)
|
||||
if not price:
|
||||
return []
|
||||
row: dict[str, str] = {
|
||||
@@ -1647,6 +1849,100 @@ def _parse_unit_kg_quote(
|
||||
return rows
|
||||
|
||||
|
||||
def _sum_same_currency(
|
||||
rows: list[dict[str, str]], fallback_ccy: str
|
||||
) -> tuple[str, str, bool]:
|
||||
"""
|
||||
合计只加同一币种:以第一行币种为主,异币种行不参与加总。
|
||||
|
||||
为何:跨境陆运常见「运输费USD3200,燃油费USD300,过境费USD70,报关费CNY1400」,
|
||||
旧实现按整句判币种,把四行全标成 CNY 再加成 4970,是一个不存在的数。
|
||||
现在各行自己带币种,合计只给主币种的真数;异币种仍留在明细里,另计且不折算。
|
||||
|
||||
参数 rows 是按文本顺序抽出的费用行(至少一行)。
|
||||
返回 (合计文本, 主币种, 是否多币种)。副作用:无。
|
||||
"""
|
||||
primary = str((rows[0] or {}).get("currency") or fallback_ccy or "").strip().upper()
|
||||
same = [
|
||||
row
|
||||
for row in rows
|
||||
if str((row or {}).get("currency") or "").strip().upper() == primary
|
||||
]
|
||||
mixed = len(same) != len(rows)
|
||||
if not same:
|
||||
return str((rows[0] or {}).get("amount") or ""), primary, mixed
|
||||
try:
|
||||
total = str(sum(float(row["amount"]) for row in same))
|
||||
except (KeyError, ValueError):
|
||||
# 有百分比或非数字金额时不硬算,退回第一行原文,避免合计写成 0。
|
||||
total = str(same[0].get("amount") or "")
|
||||
return total, primary, mixed
|
||||
|
||||
|
||||
# 陆运报价里只写车型不写价:「45HQ,运输费USD3200」。
|
||||
# 车型后面紧跟金额的不算裸车型(那是车型价矩阵,交给 _RE_VEHICLE_RATE_ITEM)。
|
||||
_RE_BARE_VEHICLE = re.compile(
|
||||
r"(?<![A-Za-z0-9.])"
|
||||
r"(\d+(?:\.\d+)?\s*(?:米|T|吨|HQ|GP|尺))"
|
||||
r"(?!\s*[::=,,、;;]?\s*(?:(?:CNY|USD|RMB|HKD|EUR|JPY|GBP|元)\s*)?\d)",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def _harvest_land_bare_vehicle(raw: str) -> str:
|
||||
"""
|
||||
陆运人工报价里的裸车型(没有紧跟价格的那个车型词)。
|
||||
|
||||
例:「45HQ,运输费USD3200」→ 45HQ。返回去空格原文,没有则空串。
|
||||
副作用:无。
|
||||
"""
|
||||
hit = _RE_BARE_VEHICLE.search(raw or "")
|
||||
if not hit:
|
||||
return ""
|
||||
return re.sub(r"\s+", "", hit.group(1))
|
||||
|
||||
|
||||
def _attach_land_vehicle_type(
|
||||
out: dict[str, Any], raw: str, business_line: str
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
陆运只写车型不写价时,把车型挂到报价对象,出单才能落到对应车型列。
|
||||
|
||||
为何:跨境整车常写「45HQ,运输费USD3200」——钱是分项而不是车型矩阵;
|
||||
车型丢了,Excel 的 45HQ 列空着,后台也看不出走的是柜车。
|
||||
已有 vehicleRates(多车型价矩阵)时不重复记;非陆运一律不动。
|
||||
副作用:原地写 out 的 vehicleType/vehicle_type。线程:调用方线程。
|
||||
"""
|
||||
if str(business_line or "").strip().upper() != "LAND":
|
||||
return out
|
||||
if out.get("vehicleRates") or out.get("vehicle_rates"):
|
||||
return out
|
||||
if str(out.get("vehicleType") or out.get("vehicle_type") or "").strip():
|
||||
return out
|
||||
token = _harvest_land_bare_vehicle(raw)
|
||||
if token:
|
||||
out["vehicleType"] = token
|
||||
out["vehicle_type"] = token
|
||||
return out
|
||||
|
||||
|
||||
def _finalize_land_quote_condition(
|
||||
quote: dict[str, Any], condition: Any
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把陆运附加条件落到报价对象上(税率/燃油费率/备注,未含燃油乘主运费)。
|
||||
|
||||
为什么在 extract_product_quote 的每个返回点都调:
|
||||
多车型价、分档价、普通费用行、金额回退四条路径各自提前 return,
|
||||
条件只在一处统一收口,避免某条路径出单时税率/备注空着。
|
||||
参数 condition 为空(非陆运或没写条件)时原样返回。
|
||||
副作用:改本次报价 dict,不落库。
|
||||
"""
|
||||
if not quote or condition is None or not apply_land_quote_condition:
|
||||
return quote
|
||||
return apply_land_quote_condition(quote, condition)
|
||||
|
||||
|
||||
def extract_product_quote(
|
||||
text: str,
|
||||
*,
|
||||
@@ -1666,17 +1962,47 @@ def extract_product_quote(
|
||||
陆运集拼:「2-500KG 单价CNY990,燃油附加费率1%,税率6%」走分档单价+费率,
|
||||
禁止把公斤档下限「2」当成燃油附加费金额(WO021)。
|
||||
无费用名时按 business_line/transport_mode 默认陆运费/空运费/海运费,禁止陆运硬套海运费。
|
||||
陆运附加条件「未含税N% / 未含税 / 含0税 / 未含燃油N% / 含燃油费N%」走
|
||||
agent.schema.land_quote_condition:税率/燃油费率/备注进报价顶层,
|
||||
只有「未含燃油」按(1+N%)乘主运费,提货/送货/报关等杂费不乘。
|
||||
正文未写币种时继承 baseline_currency(当前 TMS/主账币种),禁止默认 USD(WO107)。
|
||||
"""
|
||||
base_ccy = str(baseline_currency or "").strip().upper()
|
||||
raw = (text or "").strip()
|
||||
# 「原始报价参考」要原样展示给销售:@机器人 只是叫人,不是报价内容,先剥掉。
|
||||
# 用保留换行的剥法(strip_bot_mention 会压平空白,不适合当原话)。
|
||||
from agent.policy.bot_name import strip_mention_keep_layout
|
||||
|
||||
raw_ref = strip_mention_keep_layout(raw)
|
||||
is_land = (business_line or "").strip().upper() == "LAND" or (
|
||||
transport_mode or ""
|
||||
).strip() in {"陆运", "LAND", "land"}
|
||||
if isinstance(injected, dict) and (injected.get("total") or injected.get("fee_rows")):
|
||||
out = dict(injected)
|
||||
out.setdefault("source_label", "产品报价")
|
||||
# 上层预抽取的报价也要过陆运条件:否则「未含燃油13%」会绕过乘法,
|
||||
# 出单只有燃油费率、运费却没乘,客户少收一段燃油。
|
||||
if is_land and parse_land_quote_condition:
|
||||
injected_text = str(out.get("raw_text") or out.get("rawText") or raw)
|
||||
out = _finalize_land_quote_condition(
|
||||
out, parse_land_quote_condition(injected_text)
|
||||
)
|
||||
return out
|
||||
raw = (text or "").strip()
|
||||
if not raw:
|
||||
return {}
|
||||
stripped = _strip_group_bot_mentions(raw)
|
||||
stripped_all = _strip_group_bot_mentions(raw)
|
||||
# 陆运五句附加条件(未含税/含0税/未含燃油/含燃油费)先识别再从正文剥掉:
|
||||
# 「含燃油费13%」不剥会被费用行正则当成费目,13 会被当金额;
|
||||
# 「未含税」里的「含税」也会被旧备注正则误认。
|
||||
condition = (
|
||||
parse_land_quote_condition(stripped_all)
|
||||
if (is_land and parse_land_quote_condition)
|
||||
else None
|
||||
)
|
||||
if condition is not None and strip_land_quote_condition:
|
||||
stripped = strip_land_quote_condition(stripped_all)
|
||||
else:
|
||||
stripped = stripped_all
|
||||
compact = stripped.replace(" ", "").replace(" ", "")
|
||||
if re.fullmatch(r"WO\d{12}", compact, re.I):
|
||||
return {}
|
||||
@@ -1685,20 +2011,25 @@ def extract_product_quote(
|
||||
return {}
|
||||
quote_remark = _extract_quote_remark(stripped or raw)
|
||||
# 多车型整车价必须先于普通费用行:否则「40HQ/45HQ:19500」会被抽成 HQ=19500。
|
||||
vehicle = _parse_vehicle_rates_quote(stripped or raw, baseline_currency=base_ccy)
|
||||
vehicle = _parse_vehicle_rates_quote(
|
||||
stripped or raw, baseline_currency=base_ccy, allow_single=is_land
|
||||
)
|
||||
if vehicle:
|
||||
# 原始报价参考必须是产品原话:stripped 已把「含0点税」这类条件句剥掉,
|
||||
# 直接拿它会变成半句话(「…;都是」),销售没法照抄给客户。
|
||||
vehicle["raw_text"] = raw_ref
|
||||
note = quote_remark or str(vehicle.get("remark") or "")
|
||||
if note:
|
||||
vehicle["remark"] = note
|
||||
_attach_quote_remark(list(vehicle.get("fee_rows") or []), note)
|
||||
vehicle["fee_lines"] = list(vehicle.get("fee_rows") or [])
|
||||
return vehicle
|
||||
return _finalize_land_quote_condition(vehicle, condition)
|
||||
band = _parse_weight_band_quote(stripped or raw, baseline_currency=base_ccy)
|
||||
if band:
|
||||
if quote_remark:
|
||||
_attach_quote_remark(list(band.get("fee_rows") or []), quote_remark)
|
||||
band["fee_lines"] = list(band.get("fee_rows") or [])
|
||||
return band
|
||||
return _finalize_land_quote_condition(band, condition)
|
||||
# 费率句若仍落到普通费用行,会把「燃油附加费」配上句首公斤数。先剥掉再抽。
|
||||
# 必须用剥掉 @询价小助手 后的正文,否则句首「起运港、」分段标签匹配不到。
|
||||
# 顺带剥掉报价日期/有效期/时效要求,避免年份、天数再抽成金额。
|
||||
@@ -1710,6 +2041,8 @@ def extract_product_quote(
|
||||
scrubbed = _RE_STANDALONE_REMARK.sub(" ", scrubbed)
|
||||
# 工单号先剥:否则「WO202611100020、…CNY11/kg」会把工单数字当空运费。
|
||||
scrubbed = _strip_work_order_tokens(scrubbed)
|
||||
# 「计费重800KG」是报价条件,不能落成费目「计费:800」;值由群报价层单独读。
|
||||
scrubbed = _strip_chargeable_declaration(scrubbed)
|
||||
rows = _parse_fee_rows(scrubbed, baseline_currency=base_ccy) if scrubbed.strip() else []
|
||||
if not rows:
|
||||
# 短句「CNY11/kg,+500」:无费名时落单价行;+500 只作重量分档,不当其它费用。
|
||||
@@ -1735,17 +2068,16 @@ def extract_product_quote(
|
||||
if str(x.get("unit") or "").upper() in {"KG", "KGS"}
|
||||
and str(x.get("unit_price") or x.get("amount") or "").strip()
|
||||
]
|
||||
if money_rows and len({x.get("currency") for x in money_rows}) == 1:
|
||||
try:
|
||||
total = str(sum(float(x["amount"]) for x in money_rows))
|
||||
except ValueError:
|
||||
total = money_rows[0]["amount"]
|
||||
elif money_rows:
|
||||
total = money_rows[0]["amount"]
|
||||
mixed_currency = False
|
||||
if money_rows:
|
||||
total, ccy, mixed_currency = _sum_same_currency(money_rows, ccy)
|
||||
elif unit_rows:
|
||||
# 单价行带数量时,amount 已是「单价×数量」的行金额,合计必须用它。
|
||||
# 只有单价没有数量(如「空运费 11/kg」)才退回单价,否则整票合计会显示 11。
|
||||
# 本分支没有多币种加总,显式置 False,避免下面 if 用到未赋值变量。
|
||||
mixed_currency = False
|
||||
picked = unit_rows[0]
|
||||
ccy = str(picked.get("currency") or ccy or "").strip() or ccy
|
||||
row_amount = str(picked.get("amount") or "").strip()
|
||||
qty = str(picked.get("quantity") or "").strip()
|
||||
unit_price = str(picked.get("unit_price") or "").strip()
|
||||
@@ -1758,14 +2090,18 @@ def extract_product_quote(
|
||||
total = unit_price or row_amount
|
||||
else:
|
||||
total = rows[0]["amount"]
|
||||
mixed_currency = False
|
||||
out = {
|
||||
"total": total,
|
||||
"currency": ccy,
|
||||
"source_label": "产品报价",
|
||||
"raw_text": raw,
|
||||
"raw_text": raw_ref,
|
||||
"fee_rows": rows,
|
||||
"fee_lines": list(rows),
|
||||
}
|
||||
if mixed_currency:
|
||||
# 一句报价里有多种币:合计只是主币种小计,异币种在明细里另计,绝不折算。
|
||||
out["mixed_currency"] = True
|
||||
# 单价行上的重量分档提到报价顶层,摘要好展示。
|
||||
for _row in rows:
|
||||
wb = str((_row or {}).get("weight_break") or "").strip()
|
||||
@@ -1777,10 +2113,15 @@ def extract_product_quote(
|
||||
if wb_raw:
|
||||
out["weight_break"] = wb_raw
|
||||
out.update(_extract_rate_fields(raw))
|
||||
return out
|
||||
_attach_land_vehicle_type(out, raw, business_line)
|
||||
return _finalize_land_quote_condition(out, condition)
|
||||
# 剥掉报价日期后只剩空白时,禁止回退到原文再抽金额(否则年份 2026 会当空运费)。
|
||||
# 再剥工单号/比例/口语月日,避免 WO 数字或「11月」进金额。
|
||||
money_src = _strip_air_quote_noise_for_money(scrubbed) if scrubbed.strip() else ""
|
||||
# 再剥工单号/比例/口语月日,避免 WO 数字或「11月」进金额;车型号吨位也不能当金额。
|
||||
money_src = (
|
||||
_strip_vehicle_label_noise(_strip_air_quote_noise_for_money(scrubbed))
|
||||
if scrubbed.strip()
|
||||
else ""
|
||||
)
|
||||
hit = _RE_MONEY.search(_ascii_amount(money_src)) if money_src else None
|
||||
if not hit:
|
||||
rates = _extract_rate_fields(raw)
|
||||
@@ -1814,12 +2155,13 @@ def extract_product_quote(
|
||||
"total": amount,
|
||||
"currency": ccy,
|
||||
"source_label": "产品报价",
|
||||
"raw_text": raw,
|
||||
"raw_text": raw_ref,
|
||||
"fee_rows": rows,
|
||||
"fee_lines": list(rows),
|
||||
}
|
||||
out.update(_extract_rate_fields(raw))
|
||||
return out
|
||||
_attach_land_vehicle_type(out, raw, business_line)
|
||||
return _finalize_land_quote_condition(out, condition)
|
||||
|
||||
|
||||
def _format_percent_rate(raw: str) -> str:
|
||||
@@ -1884,7 +2226,7 @@ def _expand_vehicle_rate_label(label: str) -> list[str]:
|
||||
parts = [p.strip() for p in re.split(r"[//]", text) if p.strip()]
|
||||
suffix = ""
|
||||
for part in reversed(parts):
|
||||
hit = re.search(r"(T|HQ|GP|尺|厢车)$", part.replace(" ", ""), re.I)
|
||||
hit = re.search(r"(T|HQ|GP|尺|米|厢车)$", part.replace(" ", ""), re.I)
|
||||
if hit:
|
||||
suffix = hit.group(1)
|
||||
break
|
||||
@@ -1915,12 +2257,71 @@ def _harvest_vehicle_quote_remark(text: str) -> str:
|
||||
return " ".join(parts)
|
||||
|
||||
|
||||
def _parse_vehicle_rates_quote(text: str, baseline_currency: str = "") -> dict[str, Any]:
|
||||
# 车型价后面紧跟的币种:「10T:1700HKD/车」→ 剥掉 HKD 才能认「/车」。
|
||||
_RE_AFTER_RATE_CCY = re.compile(rf"^\s*(?:{_CCY_TOKEN})?\s*", re.I)
|
||||
# 中港陆运「运费10T:1700HKD/车」前面的主运费费名:车型号虽然紧贴费名,
|
||||
# 但它就是车型,钱是这台车的运费,产品要求落「车型/数量 + 运输费」。
|
||||
_RE_MAIN_FREIGHT_TAIL = re.compile(r"(?:运输费|陆运费|运费|车费|拖车费|干线费)$")
|
||||
# 陆运附条款关键字:超时、等候、压夜/压日、查验、实报实销。
|
||||
# 命中后整段进备注,不再把「压夜按运费80%」拆成一条 HKD 80 的费用行。
|
||||
_RE_LAND_CLAUSE_HINT = re.compile(
|
||||
r"超时|等候|压夜|压日|滞柜|滞港|实报实销|实报实|查验"
|
||||
)
|
||||
_RE_LAND_CLAUSE_LEAD = re.compile(
|
||||
rf"^\s*(?:{_CCY_TOKEN})?\s*(?:/\s*(?:车|台|趟))?\s*[,,;;。]?\s*",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def _vehicle_label_after_freight_fee(raw: str, start: int) -> bool:
|
||||
"""
|
||||
车型号是否紧跟在「运费/运输费/陆运费…」后面。
|
||||
|
||||
例:「深圳--香港元朗运费10T:1700HKD/车」→ 10T 是车型,不是吨位口径。
|
||||
只认主运费费名,避免「报关费10T」这类误判。副作用:无。
|
||||
"""
|
||||
if start <= 0:
|
||||
return False
|
||||
if raw[start - 1] != "费":
|
||||
return False
|
||||
return bool(_RE_MAIN_FREIGHT_TAIL.search(raw[:start]))
|
||||
|
||||
|
||||
def _vehicle_rate_unit(raw: str, end: int) -> str:
|
||||
"""
|
||||
车型价金额后面的计价单位:「1700HKD/车」→ 车。
|
||||
|
||||
先剥币种再认 /车、/台、/趟;没写就返回空串,禁止猜单位。副作用:无。
|
||||
"""
|
||||
tail = _RE_AFTER_RATE_CCY.sub("", (raw or "")[end:], count=1)
|
||||
return _amount_uom_suffix(tail)
|
||||
|
||||
|
||||
def _land_vehicle_clause_remark(raw: str, end: int) -> str:
|
||||
"""
|
||||
车型价之后的陆运附条款整段(超时费/等候/压夜/压日/查验/实报实销)。
|
||||
|
||||
产品口径 2026-11-23:「运费10T:1700HKD/车」后面跟的超时费、压夜压日、
|
||||
实报实销等是备注条件,不是另一笔费用。整段进备注,避免把
|
||||
「压夜按运费80%」抽成 HKD 80 再加进合计。没命中条款词返回空串。副作用:无。
|
||||
"""
|
||||
tail = _RE_LAND_CLAUSE_LEAD.sub("", (raw or "")[end:], count=1)
|
||||
tail = re.sub(r"\s+", " ", tail).strip()
|
||||
if not tail or not _RE_LAND_CLAUSE_HINT.search(tail):
|
||||
return ""
|
||||
return tail
|
||||
|
||||
|
||||
def _parse_vehicle_rates_quote(
|
||||
text: str, baseline_currency: str = "", *, allow_single: bool = False
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
陆运整车产品多车型价:车型:5T/8T:13000 10T:14000 40HQ/45HQ:19500。
|
||||
|
||||
产出 vehicleRates(键→金额)供主账按表头车型列写入;fee_rows 便于群摘要。
|
||||
至少两档车型价,或正文含「车型」且至少一档,才认定,避免普通金额误伤。
|
||||
陆运(allow_single)允许只有一档:群里常写「8T CNY990」,车型就是唯一的价,
|
||||
旧规则把这一档丢掉,金额回退再把「8T」的 8 当成运费(WO202611100043)。
|
||||
无币种时继承 baseline,再退回 CNY(整车群报常见人民币)。
|
||||
"""
|
||||
raw = _ascii_amount(text or "")
|
||||
@@ -1936,27 +2337,63 @@ def _parse_vehicle_rates_quote(text: str, baseline_currency: str = "") -> dict[s
|
||||
price = _ascii_amount(hit.group("price") or "")
|
||||
if not label or not price:
|
||||
continue
|
||||
line_ccy = _currency_of(raw, hit.group("ccy") or base_ccy) or base_ccy
|
||||
line_ccy = _row_currency(raw, hit.group("ccy") or "", base_ccy)
|
||||
ccy = ccy or line_ccy
|
||||
keys = _expand_vehicle_rate_label(label)
|
||||
if not keys:
|
||||
continue
|
||||
# 「1700HKD/车」自己写了计价单位就带着,群摘要的运输费才看得出是按车。
|
||||
unit = _vehicle_rate_unit(raw, hit.end())
|
||||
for key in keys:
|
||||
rates[key] = price
|
||||
rows.append(
|
||||
{
|
||||
"name": key,
|
||||
"amount": price,
|
||||
"currency": line_ccy or ccy or base_ccy or "CNY",
|
||||
"unit_price": price,
|
||||
}
|
||||
)
|
||||
row = {
|
||||
"name": key,
|
||||
"amount": price,
|
||||
"currency": line_ccy or ccy or base_ccy or "CNY",
|
||||
"unit_price": price,
|
||||
}
|
||||
if unit:
|
||||
row["unit"] = unit
|
||||
rows.append(row)
|
||||
if not rates:
|
||||
return {}
|
||||
has_vehicle_word = "车型" in raw
|
||||
if len(rates) < 2 and not has_vehicle_word:
|
||||
# 单档放行:车型号自成一段(「8T CNY990」)直接认;
|
||||
# 紧贴主运费费名的「运费10T:1700HKD」也认——10T 是车型、1700 是这台车的运费,
|
||||
# 产品 2026-11-23 明确要落「车型/数量 + 运输费」,不能再落成「运费=10」。
|
||||
# 只有其它汉字/字母紧贴时才拒,避免把吨位/计价口径当成车型价矩阵。
|
||||
single_ok = bool(allow_single)
|
||||
if single_ok:
|
||||
for hit in hits:
|
||||
start = hit.start("label")
|
||||
prev = raw[start - 1] if start > 0 else ""
|
||||
if not prev:
|
||||
continue
|
||||
if prev.isalnum() or "\u4e00" <= prev <= "\u9fff":
|
||||
if _vehicle_label_after_freight_fee(raw, start):
|
||||
continue
|
||||
single_ok = False
|
||||
break
|
||||
if len(rates) < 2 and not has_vehicle_word and not single_ok:
|
||||
return {}
|
||||
remark = _harvest_vehicle_quote_remark(raw)
|
||||
# 「运费10T:1700HKD/车」后面的超时费/压夜压日/实报实销整段是备注条件,
|
||||
# 不是另一笔费用;不抽成费用行,避免 80/100 被当 HKD 再加进合计。
|
||||
clause_remark = ""
|
||||
if allow_single and hits:
|
||||
last = hits[-1]
|
||||
if _vehicle_label_after_freight_fee(raw, last.start("label")):
|
||||
clause_remark = _land_vehicle_clause_remark(raw, last.end())
|
||||
word_remark = _harvest_vehicle_quote_remark(raw)
|
||||
if clause_remark:
|
||||
# 条款整段已包含「含税/不含税」等字眼,避免同一句在备注里出现两遍。
|
||||
remark = clause_remark
|
||||
if word_remark and word_remark not in clause_remark:
|
||||
remark = f"{clause_remark} {word_remark}"
|
||||
else:
|
||||
remark = word_remark
|
||||
# 产品口头说「都是含0点税」时,税率就是 0;群摘要与后续出单都要能写出来。
|
||||
# 只有 0 点税能确定数字;含税/不含税仍只留备注,不把税率编成 0 或 13。
|
||||
tax_rate = "0" if _RE_ZERO_TAX_WORD.search(raw) else ""
|
||||
# 多车型不要相加冒充合计;取第一档价作展示合计。
|
||||
first_price = next(iter(rates.values()))
|
||||
# fee_rows 用「陆运费」摘要一行(金额取第一档),禁止把 5T/40HQ 当费目名——
|
||||
@@ -1985,6 +2422,9 @@ def _parse_vehicle_rates_quote(text: str, baseline_currency: str = "") -> dict[s
|
||||
}
|
||||
if remark:
|
||||
out["remark"] = remark
|
||||
if tax_rate:
|
||||
# 税率放顶层:主账模板「税率」列、群摘要「税率:0」都读这一个键。
|
||||
out["tax_rate"] = tax_rate
|
||||
return out
|
||||
|
||||
|
||||
@@ -2006,7 +2446,7 @@ def _parse_weight_band_quote(text: str, baseline_currency: str = "") -> dict[str
|
||||
price = _ascii_amount(hit.group("price") or "")
|
||||
if not price:
|
||||
continue
|
||||
line_ccy = _currency_of(raw, hit.group("ccy") or base_ccy) or base_ccy
|
||||
line_ccy = _row_currency(raw, hit.group("ccy") or "", base_ccy)
|
||||
ccy = ccy or line_ccy
|
||||
label = f"{lo}-{hi}KG"
|
||||
tiers.append({"min": lo, "max": hi, "price": price})
|
||||
@@ -2023,7 +2463,7 @@ def _parse_weight_band_quote(text: str, baseline_currency: str = "") -> dict[str
|
||||
price = _ascii_amount(hit.group("price") or "")
|
||||
if not price:
|
||||
continue
|
||||
line_ccy = _currency_of(raw, hit.group("ccy") or base_ccy) or base_ccy
|
||||
line_ccy = _row_currency(raw, hit.group("ccy") or "", base_ccy)
|
||||
ccy = ccy or line_ccy
|
||||
label = f"{lo}KG以上"
|
||||
tiers.append({"min": lo, "max": None, "price": price})
|
||||
|
||||
@@ -37,7 +37,10 @@ _FIELD_KEYS = (
|
||||
"车型数量",
|
||||
"通关口岸",
|
||||
"贸易条款",
|
||||
"客户名称",
|
||||
"提货地址",
|
||||
"收货地址",
|
||||
"派送地址",
|
||||
)
|
||||
|
||||
|
||||
@@ -141,7 +144,15 @@ def build_extract_messages(text: str) -> list[dict[str, str]]:
|
||||
"9月15日/9月15号/2026-09-15→报价日期,规范成 yyyy-MM-dd,未写年用今年。"
|
||||
"询价日期、走货日期、询价时间、走货时间、发货时间、发货日期、出货日期、出货时间、提货时间、提货日期一律写入报价日期。"
|
||||
"货好时间、提货地址不要写成报价日期。"
|
||||
"海运提货地址写入提货地址、海运派送地址写入派送地址(或收货地址),原话只说「货交上海」也写提货地址;"
|
||||
"两项都是非必填,没说不填,禁止从起运港/目的港反推,"
|
||||
"也禁止因为贸易条款是门到门/门到港就编一个地址出来。"
|
||||
"海运贸易条款原话写门到门、港到港、门到港、港到门时原样写入贸易条款,不要改写成运输分类;"
|
||||
"运输分类只认 Port to Port、其他。"
|
||||
"陆运「通关口岸:皇岗」「通关口岸皇岗」「过皇岗」有说就写入通关口岸,没说留空,禁止编造口岸。"
|
||||
"客户名称:原话出现客户公司名/客户简称时写入客户名称,"
|
||||
"「客户:华为」「客户名称华为」都算;海空陆三条线都要抽。"
|
||||
"没说客户就留空,禁止拿销售本人、货代或目的地编一个客户;客户名称不是协同字段。"
|
||||
"原话单独出现 DAP、DDP、CIF、CIP、FOB、EXW 时写入贸易条款;没出现留空,禁止编造。"
|
||||
"「从南京飞吉隆坡」起运港=南京、目的港=吉隆坡;「北京飞吉隆坡」起运港=北京。"
|
||||
"陆运口语「广州到深圳」「广东省深圳市福田区到香港」→起运港=左侧地名、目的港=右侧地名;"
|
||||
|
||||
@@ -280,8 +280,10 @@ def activate_ticket(
|
||||
_watch_archive_room(chat_id, no)
|
||||
return ticket, "activated_deal"
|
||||
if speak:
|
||||
# 激活发摘要 + 空运模板(现网合同:进群就能看到要填哪张表)。
|
||||
send_air_brief_and_sheet(flow=flow, ticket=ticket, chat_id=chat_id)
|
||||
# 激活只发摘要,不自动发空白/填价报价单;要表再说「生成报价单」。
|
||||
send_air_brief_and_sheet(
|
||||
flow=flow, ticket=ticket, chat_id=chat_id, include_sheet=False
|
||||
)
|
||||
_watch_archive_room(chat_id, no)
|
||||
if handoff:
|
||||
# 转人工:产品会直接在群里报价,等到的就是最终报价。
|
||||
@@ -390,13 +392,14 @@ def send_air_brief_and_sheet(
|
||||
quote_override: Optional[dict[str, Any]] = None,
|
||||
tms_quote: Optional[dict[str, Any]] = None,
|
||||
product_quote: Optional[dict[str, Any]] = None,
|
||||
include_sheet: bool = True,
|
||||
include_sheet: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
空运群再发一版摘要 + 匹配到的空运模板。对齐海运 send_brief_and_sheet。
|
||||
空运群再发一版摘要;可选再发匹配到的空运模板。对齐海运 send_brief_and_sheet。
|
||||
|
||||
必须先发出工单信息,模板等摘要发出后再发,禁止后台线程抢先发文件。
|
||||
默认 include_sheet=True:激活、补字段、有价落定都给群一张能看的表(现网合同)。
|
||||
默认 include_sheet=False:激活/补字段/有价落定都只发摘要,不自动发 Excel/PDF。
|
||||
销售/商务/航线说「生成报价单」再出表。调用方若显式传 include_sheet=True 才发模板。
|
||||
填表报价必须带上 TMS 总销售价:群票上的 latest quote 常只有增点费/拆板费明细,
|
||||
若直接拿去出单,预估费用会落成明细加总(如 200)而不是 salePrice(如 7918.25)。
|
||||
调用方刚写回的询价字段(如报价日期)优先,不能被 hydrate 旧快照盖掉。
|
||||
@@ -432,20 +435,21 @@ def send_air_brief_and_sheet(
|
||||
# 出单专用:把 TMS salePrice 盖回薄报价,避免预估费用=明细 SUM。
|
||||
sheet_quote = _sheet_quote_with_tms_sale_total(quote, tms=tms, facts=facts)
|
||||
sales_name, airline_names, mention_ids = resolve_air_mentions(flow, view)
|
||||
brief_text = copy.air_group_brief(
|
||||
work_order_no=no,
|
||||
facts=facts,
|
||||
quote=quote,
|
||||
collab_facts=collab,
|
||||
has_price=bool(tms.get("total") or tms.get("quoteId")),
|
||||
tms_quote=tms,
|
||||
product_quote=manual,
|
||||
sales_name=sales_name,
|
||||
airline_names=airline_names,
|
||||
)
|
||||
send_group_text(
|
||||
group_client_of(flow),
|
||||
room,
|
||||
copy.air_group_brief(
|
||||
work_order_no=no,
|
||||
facts=facts,
|
||||
quote=quote,
|
||||
collab_facts=collab,
|
||||
has_price=bool(tms.get("total") or tms.get("quoteId")),
|
||||
tms_quote=tms,
|
||||
product_quote=manual,
|
||||
sales_name=sales_name,
|
||||
airline_names=airline_names,
|
||||
),
|
||||
brief_text,
|
||||
mention_userids=mention_ids,
|
||||
)
|
||||
if include_sheet:
|
||||
@@ -798,8 +802,10 @@ def apply_air_fields(*, flow: Any, ticket: object, text: str, sender_id: str, ch
|
||||
facts_view["报价日期"] = quote_date
|
||||
view["facts"] = facts_view
|
||||
view["collab_chat_id"] = chat_id
|
||||
# 补字段后刷新摘要 + 模板(现网合同:群里始终有一张最新的表)。
|
||||
send_air_brief_and_sheet(flow=flow, ticket=view, chat_id=chat_id)
|
||||
# 补字段后只刷新摘要,不自动再发报价单 Excel。
|
||||
send_air_brief_and_sheet(
|
||||
flow=flow, ticket=view, chat_id=chat_id, include_sheet=False
|
||||
)
|
||||
return "fields_saved"
|
||||
|
||||
|
||||
@@ -898,9 +904,18 @@ def _patch_air_manual_side_fields(
|
||||
航司落到报价对象;其余打主账 facts。不改六态。
|
||||
"""
|
||||
from agent.schema.added_services import apply_air_value_added, harvest_added_services
|
||||
from agent.schema.air_chargeable import format_kg, harvest_declared_chargeable
|
||||
from agent.schema.field_validate import _harvest_air_ratio, _harvest_quote_date
|
||||
|
||||
out = dict(quote or {})
|
||||
# 航线自己写了「计费重800KG」就照他说的落库,别再按体积×166.7 重算覆盖。
|
||||
declared = harvest_declared_chargeable(text)
|
||||
if declared is not None and not (
|
||||
str(out.get("chargeableWeightKg") or out.get("chargeable_weight_kg") or "").strip()
|
||||
):
|
||||
out["chargeableWeightKg"] = format_kg(declared)
|
||||
out["chargeable_weight_kg"] = format_kg(declared)
|
||||
out["chargeable_weight_basis"] = "explicit"
|
||||
airline = _harvest_air_manual_airline(text)
|
||||
if airline and not (
|
||||
str(out.get("airlineCode") or out.get("airline") or "").strip()
|
||||
@@ -1032,11 +1047,13 @@ def apply_air_file(
|
||||
filename: str,
|
||||
media: dict[str, Any],
|
||||
chat_id: str,
|
||||
explicit: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
空运群附件:对齐海运。只收 Excel/PDF。航线的当正式报价并出成交跟进;别人的只存档。
|
||||
|
||||
发文件不能 @,马上回「附件已保存」。不拆文件金额。已有 TMS 报价编号要留下。
|
||||
参数 explicit:本次指令明确 @ 过机器人;不收的类型也要回一句(2026-11-21)。
|
||||
"""
|
||||
ticket = hydrate_ticket(flow, ticket)
|
||||
no = ticket_no(ticket)
|
||||
@@ -1047,7 +1064,13 @@ def apply_air_file(
|
||||
if stopped:
|
||||
return stopped
|
||||
if not filename_is_excel_pdf(filename):
|
||||
send_group_text(client, chat_id, copy.group_only_excel_pdf())
|
||||
# 与海运同口径(2026-11-19 真机):不 @BOT 的 Word/zip 不搭话。
|
||||
# 文件名带工单号才说明对方是想归到某张单,才提示「只收 Excel/PDF」。
|
||||
# 2026-11-21:明确 @ 过机器人时也一定提示,不能让人干等。
|
||||
if explicit or copy.extract_work_order_no(filename or ""):
|
||||
send_group_text(client, chat_id, copy.group_only_excel_pdf())
|
||||
else:
|
||||
logger.info("air_file_type_silent wo=%s file=%s", no or "-", (filename or "")[:80])
|
||||
return "file_type_rejected"
|
||||
_archive_file(flow, no, filename, media, sender_id)
|
||||
notify_quote_attachment_saved(flow, chat_id, no, count=1)
|
||||
@@ -1692,10 +1715,19 @@ def _commit_quote(
|
||||
|
||||
转人工协同单(collab_mode=handoff):报价照常落账,但不再生成交跟进;
|
||||
成交由销售在后台处理。raw_text 是产品原话,主账只留档参考。
|
||||
|
||||
TMS 没有报价、航线按 KG 手工报价时(如「USD11/kg」),这里按工单体积/毛重
|
||||
算一次计费重(体积重 = CBM×166.7,计费重 = max(毛重, 体积重)):
|
||||
补进报价对象、把 KG 费用行补成「单价×计费重」并重算合计。
|
||||
这样群摘要、后台报价版本和报价单看到的是同一个数(产品口径 2026-11-22)。
|
||||
"""
|
||||
_ = sender_id
|
||||
no = ticket_no(ticket)
|
||||
handoff = is_handoff_collab(flow, ticket)
|
||||
from agent.schema.air_chargeable import apply_to_quote
|
||||
|
||||
facts = dict((ticket_view(ticket) or {}).get("facts") or {})
|
||||
quote = apply_to_quote(quote, facts, business_line="AIR")
|
||||
up = flow.ledger.upsert_product_quote(
|
||||
work_order_no=no,
|
||||
quote=quote,
|
||||
|
||||
@@ -151,7 +151,13 @@ def _looks_like_code(raw: str) -> bool:
|
||||
|
||||
|
||||
def _chargeable_display(quote: dict[str, Any] | None, facts: dict[str, str]) -> str:
|
||||
"""计费重。纯数字补 KG;TMS 已带单位则原样。没有就「-」。"""
|
||||
"""
|
||||
计费重。纯数字补 KG;TMS 已带单位则原样。没有就「-」。
|
||||
|
||||
兜底(2026-11-22):TMS 没有报价、航线手工按 KG 报价时,报价对象可能没带计费重,
|
||||
此时按工单体积/毛重算一次(CBM×166.7 与毛重取大),与群摘要、报价单同一口径。
|
||||
仍读不到体积和毛重才写「-」,不编数字。
|
||||
"""
|
||||
option = _option(quote, facts)
|
||||
for blob in (option, dict(quote or {})):
|
||||
raw = blob.get("chargeableWeightKg")
|
||||
@@ -164,6 +170,11 @@ def _chargeable_display(quote: dict[str, Any] | None, facts: dict[str, str]) ->
|
||||
if any(upper.endswith(unit) for unit in ("KG", "KGS", "公斤", "千克")):
|
||||
return text
|
||||
return f"{_compact_number(text)}KG"
|
||||
from agent.schema.air_chargeable import compute_chargeable, format_kg
|
||||
|
||||
computed = compute_chargeable(facts)
|
||||
if computed is not None:
|
||||
return f"{format_kg(computed.get('chargeable_kg'))}KG"
|
||||
return "-"
|
||||
|
||||
|
||||
|
||||
@@ -92,6 +92,9 @@ class FlowSession:
|
||||
pending_files: tuple[dict[str, str], ...] = ()
|
||||
# 建单前出现过、还没被品名改口清掉的违禁原话。空表示当前没有。
|
||||
sensitive_hold: str = ""
|
||||
# 上次 TMS 无价时回包的 remark 原文。销售再说「继续」时重出卡片要带上同一句原因,
|
||||
# 否则从「目的地无法匹配」退化成只剩「暂无匹配报价」。只做展示,不是六态。
|
||||
tms_miss_reason: str = ""
|
||||
|
||||
|
||||
def is_waiting_mode_session(sess) -> bool:
|
||||
@@ -179,6 +182,7 @@ def _session_from_payload(raw: dict[str, Any]) -> FlowSession:
|
||||
if isinstance(item, dict) and str(item.get("object_key") or "").strip()
|
||||
),
|
||||
sensitive_hold=str(raw.get("sensitive_hold") or ""),
|
||||
tms_miss_reason=str(raw.get("tms_miss_reason") or ""),
|
||||
)
|
||||
|
||||
|
||||
@@ -1065,7 +1069,7 @@ class AirTextInquiryFlow:
|
||||
)
|
||||
return "wait_collab"
|
||||
if sess.phase == "tms_miss":
|
||||
self._emit_tms_miss(reply, sess.work_order_no)
|
||||
self._emit_tms_miss(reply, sess.work_order_no, sess.tms_miss_reason or "")
|
||||
return "tms_miss"
|
||||
if sess.phase == "wait_file":
|
||||
self._refresh_wait_file(sess)
|
||||
@@ -1455,7 +1459,9 @@ class AirTextInquiryFlow:
|
||||
return "ledger_fail"
|
||||
first, history_wo = self._resolve_similar(created, facts=facts, current_no=no)
|
||||
out_id = reply(copy.inquiry_card(work_order_no=no, facts=facts, first_or_same=first)) or ""
|
||||
# 询价确认必须先到销售手机,再打 TMS。否则查得快时暂无报价卡会抢先发出。
|
||||
# 建单确认(工单号+正在查询TMS报价)必须先到销售手机,再打 TMS。
|
||||
# 确定后不再重复字段段(产品口径 2026-11-22),字段只在确定前的核对卡上看。
|
||||
# 否则查得快时无价/报价卡会抢先发出,销售看不到工单号。
|
||||
self._wait_inquiry_sent(str(out_id), work_order_no=no)
|
||||
|
||||
from agent.policy.system_exception import (
|
||||
@@ -1500,9 +1506,12 @@ class AirTextInquiryFlow:
|
||||
self._save(sess)
|
||||
return "tms_tech"
|
||||
if not tms.get("has_price"):
|
||||
# ok=true 才是 TMS 已查过、确认没价
|
||||
self._emit_tms_miss(reply, no)
|
||||
# ok=true 才是 TMS 已查过、确认没价;remark 原文一并带给卡片并记进书签,
|
||||
# 销售稍后说「继续」重出卡片时仍是同一句原因。
|
||||
reason = copy.tms_miss_reason(tms)
|
||||
self._emit_tms_miss(reply, no, reason)
|
||||
sess.phase = "tms_miss"
|
||||
sess.tms_miss_reason = reason
|
||||
sess.status = "询价中"
|
||||
sess.allowed = ()
|
||||
self._save(sess)
|
||||
@@ -1603,7 +1612,12 @@ class AirTextInquiryFlow:
|
||||
no,
|
||||
len(options),
|
||||
)
|
||||
self._emit_tms_miss(reply, no)
|
||||
self._emit_tms_miss(
|
||||
reply,
|
||||
no,
|
||||
copy.tms_miss_reason(tms)
|
||||
or f"TMS 回程线路没有起运地「{stated_origin}」,请调整起运地或让产品人工报价",
|
||||
)
|
||||
sess.phase = "tms_miss"
|
||||
sess.status = "询价中"
|
||||
sess.allowed = ()
|
||||
@@ -1867,18 +1881,22 @@ class AirTextInquiryFlow:
|
||||
raw,
|
||||
)
|
||||
|
||||
def _emit_tms_miss(self, reply: ReplyFn, work_order_no: str) -> None:
|
||||
def _emit_tms_miss(self, reply: ReplyFn, work_order_no: str, reason: str = "") -> None:
|
||||
"""
|
||||
TMS 已查过且确认没价:文字兜底 + 暂无报价卡片。
|
||||
禁止在没打 query_tms 前回这个。
|
||||
|
||||
reason 为 TMS 回包 remark 原文;有值时卡片「查价结果」展示它,
|
||||
销售才看得出是目的地/车型对不上,而不是只知道没价。
|
||||
"""
|
||||
from agent.config import get_settings
|
||||
|
||||
reply(
|
||||
copy.tms_miss(work_order_no=work_order_no),
|
||||
copy.tms_miss(work_order_no=work_order_no, reason=reason),
|
||||
copy.tms_miss_wecom_payload(
|
||||
work_order_no=work_order_no,
|
||||
action_url=(get_settings().public_base_url or "").strip(),
|
||||
reason=reason,
|
||||
),
|
||||
)
|
||||
# 卡片发出后再单独发拉群句,不塞进卡、不当卡片失败兜底。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
企微机器人显示名:出站话术与入站 @ 识别共用。
|
||||
|
||||
本文件职责:从后台 reply_code=system.bot_display_name 读显示名;
|
||||
失败回退默认「智报通AIQ」;过渡期识别仍认旧名「询价小助手」。
|
||||
失败回退默认「智价通AIQ」;过渡期识别仍认旧名「询价小助手」。
|
||||
禁止:每条群消息同步打主账(走 bot_reply 短缓存);禁止当六态。
|
||||
"""
|
||||
|
||||
@@ -12,10 +12,10 @@ from typing import Tuple
|
||||
|
||||
# 后台调用编码:inq_bot_reply.reply_text 只写显示名本身,不要整句。
|
||||
REPLY_CODE = "system.bot_display_name"
|
||||
# 主账空/失败时的默认显示名(产品已定新名)。
|
||||
DEFAULT_BOT_DISPLAY_NAME = "智报通AIQ"
|
||||
# 主账空/失败时的默认显示名:与主账 Java 默认、产品话术「智价通AIQ」保持一致。
|
||||
DEFAULT_BOT_DISPLAY_NAME = "智价通AIQ"
|
||||
# 企微改名过渡:旧习惯 @ 仍要听得见(含「价/报」两版现网名)。
|
||||
LEGACY_BOT_DISPLAY_NAMES: Tuple[str, ...] = ("询价小助手", "智价通AIQ", "智报通AIQ")
|
||||
LEGACY_BOT_DISPLAY_NAMES: Tuple[str, ...] = ("询价小助手", "智报通AIQ")
|
||||
|
||||
|
||||
def bot_display_name() -> str:
|
||||
@@ -53,21 +53,166 @@ def text_mentions_bot(text: str) -> bool:
|
||||
return any(name in raw for name in bot_mention_names())
|
||||
|
||||
|
||||
# 会话存档席位账号在群里的显示名(企微成员名,不是后台员工名)。
|
||||
# 2026-11-19 真机截图:群里实际显示「会话存档机器人」,中间没有连字符;
|
||||
# 后台员工名是「询价机器人」。两种写法都要能听见,允许环境变量覆盖。
|
||||
DEFAULT_ARCHIVE_SEAT_MENTION_NAMES: Tuple[str, ...] = (
|
||||
"会话存档机器人",
|
||||
"会话存档-机器人",
|
||||
"询价机器人",
|
||||
)
|
||||
ARCHIVE_SEAT_MENTION_ENV = "WECOM_ARCHIVE_SEAT_MENTION_NAMES"
|
||||
|
||||
|
||||
def archive_seat_mention_names() -> Tuple[str, ...]:
|
||||
"""
|
||||
可唤醒兜底回的会话存档账号显示名列表。
|
||||
|
||||
先读环境变量(逗号/分号分隔),再并上默认名,去重保序。
|
||||
为什么要有这个名单:智能机器人不能自动进群,@会话存档账号是唯一
|
||||
不需要人工拉人、又能被会话存档听见的唤醒方式(2026-11-19 定)。
|
||||
"""
|
||||
import os
|
||||
|
||||
names: list[str] = []
|
||||
raw = str(os.environ.get(ARCHIVE_SEAT_MENTION_ENV) or "").strip()
|
||||
for part in raw.replace(";", ",").split(","):
|
||||
name = part.strip()
|
||||
if name and name not in names:
|
||||
names.append(name)
|
||||
for item in DEFAULT_ARCHIVE_SEAT_MENTION_NAMES:
|
||||
name = (item or "").strip()
|
||||
if name and name not in names:
|
||||
names.append(name)
|
||||
return tuple(names)
|
||||
|
||||
|
||||
def _normalize_mention(value: str) -> str:
|
||||
"""
|
||||
比对用的名字归一化:只留中文、字母、数字,去掉空格/连字符/标点。
|
||||
|
||||
为什么必须归一化:企微里同一个人可能显示成「会话存档机器人」或
|
||||
「会话存档-机器人」,全角 @ 与半角 @ 也会混用;原样比较必然漏认。
|
||||
"""
|
||||
import re
|
||||
|
||||
return re.sub(r"[^0-9a-z\u4e00-\u9fff]", "", (value or "").lower())
|
||||
|
||||
|
||||
def at_mention_tokens(text: str) -> list[str]:
|
||||
"""
|
||||
抽出正文里每个 @ 后面的名字片段(到空白为止),保留 @ 之外的原样。
|
||||
|
||||
存档里拿不到结构化的 @ 列表,只能从正文里取;这是兜底唤醒的唯一依据。
|
||||
"""
|
||||
import re
|
||||
|
||||
raw = text or ""
|
||||
tokens: list[str] = []
|
||||
for idx, ch in enumerate(raw):
|
||||
if ch not in {"@", "@"}:
|
||||
continue
|
||||
matched = re.match(r"[^\s\u2005\u00a0]+", raw[idx + 1 :])
|
||||
tokens.append(matched.group(0) if matched else "")
|
||||
return tokens
|
||||
|
||||
|
||||
def text_mentions_archive_seat(text: str) -> bool:
|
||||
"""
|
||||
原文是否 @ 了会话存档席位账号(忽略连字符、空格、全半角差异)。
|
||||
|
||||
必须带 @:裸写这几个字(例如有人在讨论账号本身)不算唤醒指令,
|
||||
否则会把普通对话误判成任务,重演「没 @ 也回话」的事故。
|
||||
"""
|
||||
targets = [n for n in (_normalize_mention(x) for x in archive_seat_mention_names()) if n]
|
||||
if not targets:
|
||||
return False
|
||||
for token in at_mention_tokens(text):
|
||||
name = _normalize_mention(token)
|
||||
if name and any(name.startswith(target) for target in targets):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def strip_bot_mention(text: str) -> str:
|
||||
"""
|
||||
去掉 @显示名 与裸显示名(含旧名),便于抽字段/判「仅工单号」、出站 instructionText。
|
||||
|
||||
先剥带 @ 的,再剥裸名,避免残留 @;末尾压空白,避免「@机器人 舱位」留下双空格。
|
||||
锁舱/释放出站前必须剥干净,禁止把「@智价通AIQ」原样带给 TMS。
|
||||
同时剥掉 @会话存档账号:兜底唤醒时它出现在正文里,不能当报价内容。
|
||||
"""
|
||||
rest = text or ""
|
||||
# 长名优先,避免短名先剥留下半截。
|
||||
names = sorted(bot_mention_names(), key=len, reverse=True)
|
||||
# 长名优先,避免短名先剥留下半截;全角 @ 一并剥掉(企微客户端可能输入全角)。
|
||||
names = sorted(
|
||||
tuple(bot_mention_names()) + tuple(archive_seat_mention_names()),
|
||||
key=len,
|
||||
reverse=True,
|
||||
)
|
||||
for name in names:
|
||||
rest = rest.replace(f"@{name}", "").replace(name, "")
|
||||
rest = rest.replace(f"@{name}", "").replace(f"@{name}", "").replace(name, "")
|
||||
return " ".join(rest.split())
|
||||
|
||||
|
||||
def _name_body_pattern(name: str) -> str:
|
||||
"""
|
||||
把显示名编成容忍空白的片段:字与字之间允许夹空格。
|
||||
|
||||
为什么不能直接 replace:企微里同一个机器人可能显示成「智价通AIQ」,
|
||||
也可能被 @ 成「智价通 AIQ」,写死的整串必然漏剥。
|
||||
"""
|
||||
import re
|
||||
|
||||
chars = [c for c in (name or "") if not c.isspace()]
|
||||
if not chars:
|
||||
return ""
|
||||
return r"\s*".join(re.escape(c) for c in chars)
|
||||
|
||||
|
||||
def strip_mention_keep_layout(text: str) -> str:
|
||||
"""
|
||||
只剥 @机器人 / @存档账号 的称呼,保留原话的换行与空格。
|
||||
|
||||
与 strip_bot_mention 的区别:那个用于抽字段,会把空白压成一行;
|
||||
这个用于「原始报价参考」这类要原样展示产品原话的场景——@ 是叫机器人的称呼,
|
||||
不是报价内容,必须去掉,但多行报价不能被挤成一行。
|
||||
|
||||
三种情况都要处理(2026-11-22 真机数据):
|
||||
1) 群里 @ 的名字比后台配置名更长(测服真机:配置名「智价通AIQ」,
|
||||
群里显示「智价通AIQ测试」)——只按配置名部分替换会留下「测试」两个残字,
|
||||
所以句首的 @称呼 整体剥掉,不按名字长度截断;
|
||||
2) 名字完全对上(含旧名、会话存档席)——按 @ + 名字 整体剥;
|
||||
3) 名字中间被企微插了空格——名字片段容忍空白比对。
|
||||
名字后面的字符必须是边界,否则说明是更长的显示名,留给第 1 条整体处理。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
import re
|
||||
|
||||
rest = text or ""
|
||||
names = [
|
||||
n
|
||||
for n in tuple(bot_mention_names()) + tuple(archive_seat_mention_names())
|
||||
if (n or "").strip()
|
||||
]
|
||||
# 边界:后一个字符不能还是名字字符,避免把「@智价通AIQ测试」截成「测试」。
|
||||
tail = r"(?![0-9A-Za-z\u4e00-\u9fff])"
|
||||
head = r"(?<![0-9A-Za-z\u4e00-\u9fff])"
|
||||
# 长名优先:先剥「会话存档-机器人」再剥可能的短名,避免留下半截称呼。
|
||||
for name in sorted(names, key=len, reverse=True):
|
||||
body = _name_body_pattern(name)
|
||||
if body:
|
||||
rest = re.sub(r"[@@]\s*" + body + tail, "", rest)
|
||||
# 没有 @ 的裸显示名也一并去掉(销售偶尔直接粘贴机器人名,不是报价内容)。
|
||||
for name in sorted(names, key=len, reverse=True):
|
||||
body = _name_body_pattern(name)
|
||||
if body:
|
||||
rest = re.sub(head + body + tail, "", rest)
|
||||
# 兜底:句首还残留 @xxx(后台改名与群里显示名对不上时,含「配置名+测试」这种长名)。
|
||||
# 报价内容不会以 @ 开头,@ 开头的第一段一定是叫人。
|
||||
rest = re.sub(r"(?m)^[ \t]*(?:[@@][^\s\u2005\u00a0]+[ \t]*)+", "", rest)
|
||||
return rest.strip()
|
||||
|
||||
|
||||
def at_bot() -> str:
|
||||
"""出站示例用的「@显示名」后缀。"""
|
||||
return f"@{bot_display_name()}"
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
协同群按需生成报价单(Excel / PDF)。
|
||||
|
||||
本文件职责:销售/商务/航线说「生成报价单」等指令时,校验有价后出表发群。
|
||||
本文件职责:群内任何成员(销售/商务/产品/航线)说「生成报价单」等指令时,
|
||||
校验有价后出表发群;无价也出空白表。非群成员由群入口先拦,不在这里判岗位。
|
||||
禁止:产品报价落定时自动调用;回调线程同步 LibreOffice;私聊采用出单走这里。
|
||||
"""
|
||||
|
||||
@@ -35,47 +36,21 @@ def _group_outbound_channel(flow: Any) -> str:
|
||||
|
||||
def can_request_quote_sheet(flow: Any, ticket: object, sender_id: str) -> bool:
|
||||
"""
|
||||
谁能喊生成报价单:本单销售、员工管理岗位 sales(商务)、航线·空运。
|
||||
谁能喊「生成报价单」:群内任何成员都可以(产品口径 2026-11-22 起开放)。
|
||||
|
||||
产品岗不能靠这句指令出表(产品只负责报价)。
|
||||
例外:转人工协同群(collab_mode=handoff)里产品也在群里跟销售商量,
|
||||
「任何人发指令出表」是转人工口径,这里直接放行;非成员仍由群入口先拦掉。
|
||||
以前只放本单销售、员工管理岗位 sales(商务)、航线·空运,产品在群里要
|
||||
PDF 报价单会被回「只有销售、商务或航线可以说」;真机反馈销售/产品一起
|
||||
看价时,产品才是要表的人,于是产品拍板:谁能进这个协同群,谁就能要表。
|
||||
|
||||
为什么不在这里再查岗位:岗位只决定「能不能报/调价」,不决定「能不能看
|
||||
已经谈好的价目」;而且转人工群、自动协同群、多段群口径本来就该一致。
|
||||
非群成员不是靠这里拦,而是 group_collab 入口的 _sender_allowed 先按群
|
||||
成员过滤掉了,所以本函数只做「有发送人」的兜底判空。
|
||||
|
||||
保留 flow / ticket 形参:调用方与测试仍按原签名传,且未来若再收紧权限
|
||||
不必大改调用点;本函数无副作用、不查主账。
|
||||
"""
|
||||
from agent.policy.sea_group_ops import collab_mode_of, is_sales, ticket_view
|
||||
|
||||
uid = (sender_id or "").strip()
|
||||
if not uid:
|
||||
return False
|
||||
if collab_mode_of(ticket) == "handoff":
|
||||
return True
|
||||
if is_sales(ticket, uid):
|
||||
return True
|
||||
if _staff_role_code(flow, uid) == "sales":
|
||||
return True
|
||||
line = str(
|
||||
ticket_view(ticket).get("business_line")
|
||||
or ticket_view(ticket).get("businessLine")
|
||||
or ""
|
||||
).strip().upper()
|
||||
if line in {"AIR", "MULTI"}:
|
||||
from agent.policy.air_group_ops import is_airline
|
||||
|
||||
if is_airline(flow, uid):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _staff_role_code(flow: Any, wecom_id: str) -> str:
|
||||
book = getattr(flow, "ledger", None) or getattr(flow, "_ledger", None)
|
||||
finder = getattr(book, "get_staff_by_wecom_id", None) if book is not None else None
|
||||
if not callable(finder):
|
||||
return ""
|
||||
try:
|
||||
row = finder(wecom_id=wecom_id) or {}
|
||||
except Exception:
|
||||
logger.exception("按需出表查岗位失败 wecom=%s", wecom_id)
|
||||
return ""
|
||||
return str(row.get("roleCode") or row.get("role_code") or "").strip().lower()
|
||||
return bool((sender_id or "").strip())
|
||||
|
||||
|
||||
def quote_usable_for_sheet(quote: Optional[dict[str, Any]]) -> bool:
|
||||
@@ -173,23 +148,27 @@ def looks_like_sheet_request(text: str) -> bool:
|
||||
|
||||
def handoff_template_name(view: dict[str, Any]) -> str:
|
||||
"""
|
||||
陆运转人工按需出表时用的模板名:工单业务类型反查后台模板名。
|
||||
陆运按需出表用的模板名:业务类型 / 运输类型+线路 反查后台模板名。
|
||||
|
||||
为什么要反查:陆运 7 种业务类型靠关键词猜必错(中港整车/中港拼车/东南亚/
|
||||
国内城配的名字互相包含)。转人工时销售在卡上选过业务类型,已经落在工单
|
||||
biz_type_label 上,直接换回模板名最稳。
|
||||
非陆运、或业务类型认不出来时返回空串,交回原来的关键词匹配。
|
||||
为什么要反查:陆运 7 种业务靠关键词猜必错(国内拼车的「零担/集拼」会抢走
|
||||
中港集拼,WO202611180001)。转人工卡上的 biz_type_label 优先;没有时用
|
||||
工单事实里的运输类型+线路类别配对(自动协同群同样适用)。
|
||||
非陆运、或认不出来时返回空串,交回关键词匹配。
|
||||
副作用:无。
|
||||
"""
|
||||
line = str(view.get("business_line") or view.get("businessLine") or "").strip().upper()
|
||||
if line != "LAND":
|
||||
return ""
|
||||
label = str(view.get("biz_type_label") or view.get("bizTypeLabel") or "").strip()
|
||||
if not label:
|
||||
return ""
|
||||
from agent.schema.handoff_options import biz_by_key
|
||||
from agent.schema.handoff_options import biz_by_key, biz_for_pair
|
||||
|
||||
biz = biz_by_key(label)
|
||||
label = str(view.get("biz_type_label") or view.get("bizTypeLabel") or "").strip()
|
||||
biz = biz_by_key(label) if label else None
|
||||
if biz is None:
|
||||
facts = dict(view.get("facts") or {})
|
||||
biz = biz_for_pair(
|
||||
str(facts.get("运输类型") or "").strip(),
|
||||
str(facts.get("线路类别") or "").strip(),
|
||||
)
|
||||
return biz.template_name if biz else ""
|
||||
|
||||
|
||||
|
||||
@@ -29,8 +29,8 @@ CLARIFY_LIMIT = 3
|
||||
VIRTUAL_PREFIX = "VT"
|
||||
|
||||
# 陆运类型+线路还对不上时,转人工摘要仍列出这一套协同项,全部为「-」。
|
||||
# 客户名称 2026-11-22 已改到询价阶段(非必填),不在协同兜底里。
|
||||
_LAND_HANDOFF_COLLAB_FALLBACK = (
|
||||
"客户名称",
|
||||
"HS编码",
|
||||
"贸易条款",
|
||||
"包装方式",
|
||||
@@ -391,6 +391,93 @@ def try_commit_air_group_handoff(flow: Any, *, chat_id: str, work_order_no: str)
|
||||
return "handoff_done"
|
||||
|
||||
|
||||
def send_handoff_field_brief_now(
|
||||
flow: Any,
|
||||
*,
|
||||
chat_id: str,
|
||||
work_order_no: str,
|
||||
facts: dict[str, str] | None,
|
||||
business_line: str,
|
||||
product_names: list[str] | None = None,
|
||||
sales_name: str = "",
|
||||
airline_names: list[str] | None = None,
|
||||
biz_type_label: str = "",
|
||||
quote_scenario: str = "",
|
||||
quote_deadline: str = "",
|
||||
mention_userids: Optional[list[str]] = None,
|
||||
) -> None:
|
||||
"""
|
||||
转人工/拉群建群后立即发询价字段摘要。
|
||||
|
||||
产品口径(2026-11-20):建群瞬间就要把已整理字段发到群里,产品不用先 @BOT。
|
||||
走企微应用发群(force_app):刚 mark_group_bot 时若换成空桥 AibotReplyClient,
|
||||
群消息会发不出去。不发报价表、不跟成交——出表仍要群里说「生成报价单」。
|
||||
"""
|
||||
from agent.policy import inquiry_copy as copy
|
||||
from agent.policy.sea_group_ops import (
|
||||
app_group_client,
|
||||
force_app_group_client,
|
||||
group_client_of,
|
||||
send_group_text,
|
||||
)
|
||||
|
||||
no = (work_order_no or "").strip()
|
||||
room = (chat_id or "").strip()
|
||||
if not no or not room:
|
||||
return
|
||||
brief = copy.handoff_group_brief(
|
||||
work_order_no=no,
|
||||
facts=facts,
|
||||
business_line=business_line,
|
||||
product_names=product_names,
|
||||
sales_name=sales_name,
|
||||
airline_names=airline_names,
|
||||
biz_type_label=biz_type_label,
|
||||
quote_scenario=quote_scenario,
|
||||
quote_deadline=quote_deadline,
|
||||
)
|
||||
if not (brief or "").strip():
|
||||
return
|
||||
client = app_group_client(flow) or group_client_of(flow)
|
||||
try:
|
||||
with force_app_group_client():
|
||||
send_group_text(
|
||||
client,
|
||||
room,
|
||||
brief,
|
||||
mention_userids=mention_userids,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("建群后发转人工字段摘要失败 chat=%s wo=%s", room, no)
|
||||
|
||||
|
||||
def send_collab_field_brief_now(
|
||||
flow: Any,
|
||||
*,
|
||||
ticket: object,
|
||||
sess: Any = None,
|
||||
) -> None:
|
||||
"""
|
||||
自动协同拉群后立即发字段摘要(不发表)。
|
||||
|
||||
与转人工共用「建群即可见字段」口径;摘要走 sea_group_brief,仍 force_app 发群。
|
||||
"""
|
||||
from agent.policy.sea_group_ops import force_app_group_client, send_brief_and_sheet
|
||||
|
||||
if ticket is None:
|
||||
return
|
||||
try:
|
||||
with force_app_group_client():
|
||||
send_brief_and_sheet(
|
||||
flow=flow,
|
||||
ticket=ticket,
|
||||
sess=sess,
|
||||
include_sheet=False,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("建群后发协同字段摘要失败")
|
||||
|
||||
|
||||
def collab_keys_for_handoff(facts: dict[str, str] | None, business_line: str) -> tuple[str, ...]:
|
||||
"""转人工摘要要列出的协同键;对不上陆运套餐时用兜底五项。"""
|
||||
from agent.schema.field_validate import SEA_COLLAB_FIELDS, collab_fields_for_ticket
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -231,7 +231,20 @@ class LandTextInquiryFlow(SeaTextInquiryFlow):
|
||||
return refused
|
||||
|
||||
if not mode:
|
||||
mode = "LAND" if (sess and (sess.business_line or "").upper() == "LAND") else ""
|
||||
# 与海运/空运对齐:补问短答常不含「陆运」二字,必须沿用书签。
|
||||
# 已在陆运前半段(clarify/选项/核对)时强制 LAND;否则从前几句原话再认一次。
|
||||
line = (sess.business_line or "").upper() if sess else ""
|
||||
phase_now = (sess.phase or "").strip() if sess else ""
|
||||
if line == "LAND":
|
||||
mode = "LAND"
|
||||
elif phase_now in {"clarify", "need_land_options", "wait_confirm", "wait_land_route"}:
|
||||
mode = "LAND"
|
||||
elif sess is not None:
|
||||
from agent.llm.extract_text import detect_transport_mode
|
||||
|
||||
mode = (
|
||||
detect_transport_mode(f"{sess.immutable_text or ''}\n{text}") or ""
|
||||
).upper()
|
||||
if not mode:
|
||||
reply(copy.ask_transport())
|
||||
self._save(
|
||||
@@ -436,7 +449,8 @@ class LandTextInquiryFlow(SeaTextInquiryFlow):
|
||||
first, history_wo = self._resolve_similar(
|
||||
created, facts=facts, current_no=no, business_line="LAND"
|
||||
)
|
||||
# 与海运一样先出询价确认(工单号+字段),再查价;禁止只回一句「工单已创建」。
|
||||
# 与海运一样先出建单确认(工单号+正在查询TMS报价),再查价。
|
||||
# 产品口径 2026-11-22:确定后不再重复字段段,字段只在确定前的核对卡上看。
|
||||
out_id = reply(
|
||||
copy.inquiry_card(
|
||||
work_order_no=no,
|
||||
@@ -528,8 +542,11 @@ class LandTextInquiryFlow(SeaTextInquiryFlow):
|
||||
return "tms_tech"
|
||||
self._clear_parked_confirm(sess.sender_id)
|
||||
if not tms.get("has_price"):
|
||||
self._emit_tms_miss(reply, no)
|
||||
# TMS 已回 1002/1003:remark 原文带给卡片,并记进书签供「继续」重放。
|
||||
reason = copy.tms_miss_reason(tms)
|
||||
self._emit_tms_miss(reply, no, reason)
|
||||
sess.phase = "tms_miss"
|
||||
sess.tms_miss_reason = reason
|
||||
sess.status = "询价中"
|
||||
sess.allowed = (copy.BTN_PULL_COLLAB,)
|
||||
self._save(sess)
|
||||
@@ -1235,8 +1252,7 @@ class LandTextInquiryFlow(SeaTextInquiryFlow):
|
||||
3. 建正式工单;失败可恢复,不建群(群名必须等于正式工单号)。
|
||||
4. 按「线路类别」匹配陆运产品;一个都没有就不建空群。
|
||||
5. 企微建群 → 登记会话存档 → 绑群写 collab_mode=handoff。
|
||||
6. 群内发转人工摘要(含业务类型、报价场景、报价时效)。
|
||||
报价单不自动推:群里任何人说「生成报价单」才出表,系统按工单业务类型直取模板。
|
||||
6. 建群后立即发询价字段摘要(不发表);出表仍等群里 @BOT 说「生成报价单」。
|
||||
7. 启动产品报价等待;六态保持询价中,报价后按现有接口变已报价。
|
||||
|
||||
不查 TMS、不发成交跟进:转人工后成交由销售在后台确认。
|
||||
@@ -1268,6 +1284,17 @@ class LandTextInquiryFlow(SeaTextInquiryFlow):
|
||||
self._save(sess)
|
||||
if card_meta:
|
||||
self._grey_clicked_card(reply, card_meta)
|
||||
# 已有群可能是改造前由应用建的老群:补记 BOT 接管,后续按 @BOT 规则处理。
|
||||
try:
|
||||
from agent.redis_coord.group_bot import mark_group_bot
|
||||
|
||||
mark_group_bot(
|
||||
existing,
|
||||
"LAND",
|
||||
(sess.handoff_work_order_no or sess.work_order_no or "").strip(),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("补记已有陆运协同群 BOT 模式失败 chat=%s", existing)
|
||||
reply(copy.sea_group_exists(work_order_no=(sess.handoff_work_order_no or "").strip()))
|
||||
return "handoff_done"
|
||||
|
||||
@@ -1383,24 +1410,33 @@ class LandTextInquiryFlow(SeaTextInquiryFlow):
|
||||
sales_name = self._sales_display_name(sess.sender_id)
|
||||
deadline = deadline_text(selection.sla_hours)
|
||||
|
||||
# ⑤ 群摘要:工单号 + 询价字段 + 卡片选项 + 报价时效,产品不用再问一句。
|
||||
brief = copy.handoff_group_brief(
|
||||
work_order_no=no,
|
||||
facts=facts,
|
||||
business_line="LAND",
|
||||
product_names=product_names,
|
||||
sales_name=sales_name,
|
||||
biz_type_label=selection.biz_label,
|
||||
quote_scenario=selection.scenario_label,
|
||||
quote_deadline=deadline,
|
||||
)
|
||||
# ⑤ 产品口径(2026-11-20):建群后立即发字段摘要;出表仍等 @BOT 说「生成报价单」。
|
||||
try:
|
||||
client.send_group(chat_id=chat_id, content=brief)
|
||||
except Exception:
|
||||
logger.exception("陆运转人工群发摘要失败 chat=%s wo=%s", chat_id, no)
|
||||
from agent.redis_coord.group_bot import mark_group_bot
|
||||
|
||||
# ⑥ 不自动发表:报价单由群里「生成报价单」指令触发,和自动协同群同一口径。
|
||||
# 出表时系统按工单业务类型直取模板,不需要建群就推一张空白表。
|
||||
mark_group_bot(chat_id, "LAND", no)
|
||||
except Exception:
|
||||
logger.exception("登记陆运转人工群 BOT 模式失败 chat=%s", chat_id)
|
||||
try:
|
||||
from agent.policy.handoff_human import send_handoff_field_brief_now
|
||||
|
||||
send_handoff_field_brief_now(
|
||||
self,
|
||||
chat_id=chat_id,
|
||||
work_order_no=no,
|
||||
facts=dict(sess.facts or {}),
|
||||
business_line="LAND",
|
||||
product_names=product_names,
|
||||
sales_name=sales_name,
|
||||
biz_type_label=selection.biz_label,
|
||||
quote_scenario=selection.scenario_label,
|
||||
quote_deadline=deadline,
|
||||
mention_userids=[uid for uid in product_ids if uid],
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("陆运转人工建群后发字段摘要失败 chat=%s wo=%s", chat_id, no)
|
||||
|
||||
# ⑥ 不自动发表:报价单由群里 @BOT 说「生成报价单」触发,和自动协同群同一口径。
|
||||
|
||||
# ⑦ 盯产品报价:报价场景决定超时编码,急件为 0 小时即不提醒。
|
||||
from agent.policy.event_exception import WAIT_PRODUCT_QUOTE, start_wait
|
||||
|
||||
@@ -190,12 +190,14 @@ def apply_multi_file(
|
||||
sender_id: str,
|
||||
filename: str,
|
||||
media: Optional[dict[str, Any]] = None,
|
||||
explicit: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
多段群附件报价:落 inq_attachment,按文件名/岗位归段,不写正文抽价。
|
||||
|
||||
运行证据:石畅畅发「…空运到港报价单.xlsx」时,旧逻辑把文件名当文字报价,
|
||||
回「没有识别到报价」,附件也没进后台。
|
||||
参数 explicit:本次指令明确 @ 过机器人;不收的类型也要回一句(2026-11-21)。
|
||||
副作用:写主账附件+分段报价;可能发群确认/成交跟进。Worker 线程。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
@@ -203,7 +205,13 @@ def apply_multi_file(
|
||||
client = group_client_of(flow)
|
||||
name = (filename or "").strip()
|
||||
if not filename_is_excel_pdf(name):
|
||||
send_group_text(client, room, copy.group_only_excel_pdf())
|
||||
# 与海运/空运同口径(2026-11-19 真机):文件名不带工单号的非 Excel/PDF 一律静默,
|
||||
# 避免群里随手丢个 Word/zip 就被机器搭话;带号才提示一句。
|
||||
# 2026-11-21:本次指令明确 @ 过机器人时也一定提示(附件的本体仍不入库)。
|
||||
if explicit or copy.extract_work_order_no(name or ""):
|
||||
send_group_text(client, room, copy.group_only_excel_pdf())
|
||||
else:
|
||||
logger.info("multi_file_type_silent wo=%s file=%s", no or "-", (name or "")[:80])
|
||||
return "file_type_rejected"
|
||||
segments = load_segments(ticket)
|
||||
if not segments:
|
||||
|
||||
@@ -34,10 +34,9 @@ from agent.schema.sea_options import harvest_sea_class
|
||||
_SEG_PREFIX = (
|
||||
r"(?:段\s*(\d+)\s*[::]\s*|第\s*([一二三四五六七八九]|\d+)\s*段\s*[::,,]?\s*)"
|
||||
)
|
||||
# 行首或段标后面的运输方式。排除「空运费」,避免费用词被当成新的一段。
|
||||
_MODE_RE = re.compile(rf"(?:{_SEG_PREFIX})?(空运|海运|陆运)(?!费)")
|
||||
# 已经写了「段1:陆运」或「第一段陆运」时,段内再写「运输方式:海运」不能再切一段。
|
||||
_EXPLICIT_SEG = re.compile(rf"{_SEG_PREFIX}(空运|海运|陆运)(?!费)")
|
||||
# 无段标时不再用裸子串切段,改走 find_transport_mode_hits(按语境认方式)。
|
||||
_EXPLICIT_SEG = re.compile(rf"{_SEG_PREFIX}(空运|海运|陆运)")
|
||||
# 单段标签行没覆盖的陆运销售叫法。内部键仍交给字段校验去归一。
|
||||
_EXTRA_LABEL = re.compile(r"^(始发站|货物品名|运输类型|线路类别)\s*[::]\s*(.+)$")
|
||||
_SEG_MARK = re.compile(r"第\s*([一二三四五六七八九]|\d+)\s*段|段\s*(\d+)")
|
||||
@@ -97,10 +96,33 @@ def classify_multi_text(text: str) -> str:
|
||||
"""
|
||||
outcome = split_segments(text)
|
||||
if outcome.same_mode:
|
||||
return "same_mode"
|
||||
if outcome.ok:
|
||||
return "multi"
|
||||
return "single"
|
||||
kind = "same_mode"
|
||||
elif outcome.ok:
|
||||
kind = "multi"
|
||||
else:
|
||||
kind = "single"
|
||||
return kind
|
||||
|
||||
|
||||
def is_multi_continuation(text: str) -> bool:
|
||||
"""
|
||||
本句是不是「还在多段这一票里继续」,而不是新开一句单段询价。
|
||||
|
||||
为什么需要(2026-11-19 正服事故):销售先问「海运和陆运哪个便宜」被切成了多段,
|
||||
这张多段草稿留在会话里;之后他单独发一句「陆运询价」,选流处却因为
|
||||
「多段正在补问」把这句话也让给多段,回的是海运补问,而且每句都被它接走,
|
||||
直到进程重启才「自己好了」。所以多段让单段让位前,必须先确认本句真是多段续问。
|
||||
|
||||
认定是多段续问只有两种:
|
||||
1) 本句写了段标(「段1:国内运输拼车」「段2:运输方式:空运」都算)——
|
||||
补问回填常常只写段标、方式另起一行,不能要求段标后面紧跟「空运/海运/陆运」;
|
||||
2) 本句自身就能切成多段(「陆运+海运」两段都写了)。
|
||||
其余情况(「陆运询价」「走陆运」)算新开单段,旧多段草稿让位。
|
||||
"""
|
||||
raw = text or ""
|
||||
if _SEG_MARK.search(raw):
|
||||
return True
|
||||
return classify_multi_text(raw) == "multi"
|
||||
|
||||
|
||||
def split_segments(text: str) -> SplitOutcome:
|
||||
@@ -118,28 +140,39 @@ def split_segments(text: str) -> SplitOutcome:
|
||||
raw = text or ""
|
||||
explicit = list(_EXPLICIT_SEG.finditer(raw))
|
||||
# explicit_only_segment_split:有段标就只认段标。一份附件常被标「段1:海运」,表里还会再写一次海运。
|
||||
hits = explicit if explicit else list(_MODE_RE.finditer(raw))
|
||||
if len(hits) < 2:
|
||||
if explicit:
|
||||
anchors = [
|
||||
(hit.start(), hit.end(), _MODE_BY_WORD[hit.group(3)], _segment_index(hit, i + 1))
|
||||
for i, hit in enumerate(explicit)
|
||||
]
|
||||
else:
|
||||
# 无段标:按语境认「真在说运输方式」的命中,避免上海运输费误切海运。
|
||||
from agent.llm.extract_text import find_transport_mode_hits
|
||||
|
||||
mentions = find_transport_mode_hits(raw)
|
||||
anchors = [
|
||||
(hit.start, hit.end, hit.code, i + 1) for i, hit in enumerate(mentions)
|
||||
]
|
||||
if len(anchors) < 2:
|
||||
return SplitOutcome()
|
||||
modes = [_MODE_BY_WORD[hit.group(3)] for hit in hits]
|
||||
modes = [row[2] for row in anchors]
|
||||
unique = set(modes)
|
||||
if len(modes) != len(unique):
|
||||
# 没标出两段时,同一种方式写两次仍是单段(海运报价单标题+运输方式)。
|
||||
if len(explicit) < 2 and len(unique) == 1:
|
||||
return SplitOutcome()
|
||||
return SplitOutcome(same_mode=True)
|
||||
shared = _shared_cargo_facts(raw[: hits[0].start()])
|
||||
lead = raw[: hits[0].start()].strip()
|
||||
shared = _shared_cargo_facts(raw[: anchors[0][0]])
|
||||
lead = raw[: anchors[0][0]].strip()
|
||||
segments: list[Segment] = []
|
||||
for i, hit in enumerate(hits):
|
||||
end = hits[i + 1].start() if i + 1 < len(hits) else len(raw)
|
||||
body = raw[hit.end() : end]
|
||||
mode = modes[i]
|
||||
for i, (start, end_pos, mode, index) in enumerate(anchors):
|
||||
end = anchors[i + 1][0] if i + 1 < len(anchors) else len(raw)
|
||||
body = raw[end_pos:end]
|
||||
# 抽取要看得到段前那句货物,否则「茶叶,11kg」写在第一段前面会被丢掉。
|
||||
source = f"{lead}\n{body}".strip() if lead else body
|
||||
segments.append(
|
||||
Segment(
|
||||
index=_segment_index(hit, i + 1),
|
||||
index=index,
|
||||
mode=mode,
|
||||
facts=_fill_blank(_facts_from_body(body, mode), shared),
|
||||
source=source,
|
||||
|
||||
@@ -21,6 +21,7 @@ from agent.schema.field_validate import (
|
||||
SEA_COLLAB_FIELDS,
|
||||
collab_display_name,
|
||||
collab_fields_for_ticket,
|
||||
is_sea_lcl,
|
||||
)
|
||||
|
||||
# 主账填表按英文码取格子;中文键必须同时带上,否则货好时间/条款写不进表。
|
||||
@@ -278,6 +279,22 @@ def filename_is_excel_pdf(name: str) -> bool:
|
||||
|
||||
# 这一次群出站临时改用的客户端。只在当前线程有效,不改流程单例上的企微客户端。
|
||||
_outbound_client: ContextVar[Any] = ContextVar("inquiry_group_outbound_client", default=None)
|
||||
# 这一次群出站「强制走应用」,不允许被替换成机器人桥。
|
||||
# 用途:@会话存档账号的兜底路径成立前提就是 BOT 不在群,走桥必失败(2026-11-19)。
|
||||
_force_app: ContextVar[bool] = ContextVar("inquiry_group_force_app", default=False)
|
||||
|
||||
|
||||
def app_group_client(flow: Any) -> Any:
|
||||
"""
|
||||
取流程自己的应用客户端(建群、拉人、解散群专用)。
|
||||
|
||||
即使当前线程用 `override_group_client` 临时把出站改成了 BOT,
|
||||
解散群仍然必须走应用 `appchat/update`,否则移不掉人。
|
||||
"""
|
||||
getter = getattr(flow, "group_client", None)
|
||||
if callable(getter):
|
||||
return getter()
|
||||
return getattr(flow, "_group_client", None)
|
||||
|
||||
|
||||
def group_client_of(flow: Any) -> Any:
|
||||
@@ -290,10 +307,40 @@ def group_client_of(flow: Any) -> Any:
|
||||
override = _outbound_client.get()
|
||||
if override is not None:
|
||||
return override
|
||||
getter = getattr(flow, "group_client", None)
|
||||
if callable(getter):
|
||||
return getter()
|
||||
return getattr(flow, "_group_client", None)
|
||||
return app_group_client(flow)
|
||||
|
||||
|
||||
def outbound_group_client(client: Any, chat_id: str) -> Any:
|
||||
"""
|
||||
BOT 接管的协同群,出站文字改走机器人桥;应用客户端只保留建群/解散。
|
||||
|
||||
为什么不在建群时直接换客户端:
|
||||
- 流程单例还负责 create_group / dismiss_group / 私聊回执,这些必须走应用。
|
||||
- 只有「往群里发文字」这一步该由 BOT 做,所以按群逐个判断。
|
||||
测试里的假客户端、以及还没标记 BOT 的老群,原样返回,行为不变。
|
||||
|
||||
例外(2026-11-19):@会话存档账号的兜底路径必须是应用发群,
|
||||
因为那条路的成立前提就是「BOT 不在群里」,走桥必失败。
|
||||
线程内 `force_app_group_client()` 打开时不做桥替换。
|
||||
"""
|
||||
if _force_app.get():
|
||||
return client
|
||||
if client is None or not (chat_id or "").strip():
|
||||
return client
|
||||
try:
|
||||
from agent.redis_coord.group_bot import is_group_bot
|
||||
|
||||
if not is_group_bot(chat_id):
|
||||
return client
|
||||
except Exception: # noqa: BLE001 - 协调数据不可用时不改通道
|
||||
logger.warning("判断群 BOT 模式失败 chat=%s", chat_id, exc_info=True)
|
||||
return client
|
||||
from agent.channel.aibot.reply import AibotReplyClient
|
||||
from agent.channel.outbox.sender import WeComAppClient
|
||||
|
||||
if isinstance(client, AibotReplyClient) or not isinstance(client, WeComAppClient):
|
||||
return client
|
||||
return AibotReplyClient("")
|
||||
|
||||
|
||||
@contextmanager
|
||||
@@ -310,6 +357,24 @@ def override_group_client(client: Any) -> Iterator[None]:
|
||||
_outbound_client.reset(token)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def force_app_group_client() -> Iterator[None]:
|
||||
"""
|
||||
这一次群出站必须走企微应用,禁止被换成机器人桥。
|
||||
|
||||
为什么需要:`outbound_group_client` 见到「群已标记 BOT」就会把应用客户端
|
||||
换成 `AibotReplyClient`。但 @会话存档账号的兜底路径,前提恰恰是
|
||||
「BOT 不在群里」,换成桥后 aibot_send_msg 会失败,等于不回复。
|
||||
|
||||
只影响当前线程;不改流程单例、不改群标记。
|
||||
"""
|
||||
token = _force_app.set(True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_force_app.reset(token)
|
||||
|
||||
|
||||
def _archive_seat_ids(flow: Any) -> set[str]:
|
||||
"""会话存档账号(测服 AI001 / 询价机器人)不能出现在群 @ 里。"""
|
||||
seats: set[str] = {"AI001", "询价机器人"}
|
||||
@@ -427,7 +492,9 @@ def send_group_text(
|
||||
"""
|
||||
if not client or not chat_id or not content:
|
||||
return
|
||||
sender = getattr(client, "send_group", None)
|
||||
# 建群/解散仍用应用客户端;群文字如果该群已由 BOT 接管,就改走桥。
|
||||
actual = outbound_group_client(client, chat_id)
|
||||
sender = getattr(actual, "send_group", None)
|
||||
if not callable(sender):
|
||||
return
|
||||
mentions = [str(x).strip() for x in (mention_userids or []) if str(x).strip()]
|
||||
@@ -614,13 +681,13 @@ def send_brief_and_sheet(
|
||||
tms_quote: Optional[dict[str, Any]] = None,
|
||||
product_quote: Optional[dict[str, Any]] = None,
|
||||
persist_attachment: bool = False,
|
||||
include_sheet: bool = True,
|
||||
include_sheet: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
群里再发一版摘要 + 填好的海运/陆运模板。旧消息不撤。
|
||||
群里再发一版摘要;可选再发填好的海运/陆运模板。旧消息不撤。
|
||||
|
||||
默认 include_sheet=True:激活、补字段、有价落定都要给群一张能看的表(现网合同)。
|
||||
只有调用方明确只想发摘要时才传 False。
|
||||
默认 include_sheet=False:激活/补字段/有价落定都不自动发 Excel/PDF。
|
||||
销售/商务/航线说「生成报价单」再出表。调用方显式 True 才发文件。
|
||||
persist_attachment:正式有价出单传 True,登记后台附件;激活/补字段重发保持 False。
|
||||
"""
|
||||
ticket = hydrate_ticket(flow, ticket)
|
||||
@@ -871,15 +938,23 @@ def _render_and_send_sheet(
|
||||
template_name:非空时后台按模板名直取,陆运转人工 7 种业务各用各的表。
|
||||
"""
|
||||
renderer = getattr(flow.ledger, "render_quote", None)
|
||||
client = group_client_of(flow)
|
||||
# 报价单属于群内事务:BOT 接管的群由 BOT 发文件,应用不代发。
|
||||
client = outbound_group_client(group_client_of(flow), chat_id)
|
||||
if not callable(renderer) or not chat_id:
|
||||
return {"ok": False, "error": "no_renderer_or_chat"}
|
||||
line = (business_line or "SEA").strip() or "SEA"
|
||||
# 拼柜不指定箱型:填表前去掉旧快照的箱型/箱型列表,报价单箱型格留空(产品口径 2026-11-22)。
|
||||
# 只作用于本次出表入参,不改工单事实,历史数据仍可查。
|
||||
sheet_facts = dict(facts or {})
|
||||
if line == "SEA" and is_sea_lcl(sheet_facts.get("整柜或拼柜")):
|
||||
sheet_facts.pop("箱型箱量", None)
|
||||
sheet_facts.pop("container_type_qty", None)
|
||||
sheet_facts.pop("containerItems", None)
|
||||
# 激活空白模版:persist=False;产品/分段有价出单:persist=True 写后台附件。
|
||||
result = renderer(
|
||||
work_order_no=work_order_no,
|
||||
business_line=line,
|
||||
facts=facts,
|
||||
facts=sheet_facts,
|
||||
quote=quote,
|
||||
format="xlsx",
|
||||
sales_wecom_id=sales_id,
|
||||
@@ -888,6 +963,14 @@ def _render_and_send_sheet(
|
||||
) or {}
|
||||
if not result.get("ok"):
|
||||
logger.warning("群填表失败 wo=%s line=%s err=%s", work_order_no, line, result.get("error"))
|
||||
# 出表失败必须回群说明:销售前面已经收到「正在生成…」,
|
||||
# 若这里只记日志,群里就永远停在「请稍候」,看不出是模板缺失还是主账失败。
|
||||
# 文案沿用主账返回的失败说明;空时用后台模板维护话术。
|
||||
send_group_text(
|
||||
client,
|
||||
chat_id,
|
||||
str(result.get("message") or copy.quote_template_missing()),
|
||||
)
|
||||
return result
|
||||
from agent.quote_templates.filename import filename_from_render
|
||||
|
||||
@@ -1226,10 +1309,16 @@ def handle_group_file(
|
||||
filename: str,
|
||||
media: dict[str, Any],
|
||||
sess: Any = None,
|
||||
explicit: bool = False,
|
||||
) -> str:
|
||||
"""
|
||||
群附件:只收 Excel/PDF。终态不存要提醒。
|
||||
产品 Excel/PDF 当报价并出成交跟进;别人的只存档。
|
||||
|
||||
参数 explicit(2026-11-21):
|
||||
这条附件是不是「本次指令里明确 @ 过机器人」才来的(dispatch 打标)。
|
||||
默认 False ⇒ 保持老口径:别人的附件只存档、不搭话(群里随手丢文件不该被搭话)。
|
||||
明确 @ 过 ⇒ 必须回一句,否则真机就是「发文件 + @机器人,BOT 一声不吭」。
|
||||
"""
|
||||
no = ticket_no(ticket)
|
||||
view = ticket_view(ticket)
|
||||
@@ -1241,10 +1330,18 @@ def handle_group_file(
|
||||
if stopped:
|
||||
return stopped
|
||||
if not filename_is_excel_pdf(filename):
|
||||
send_group_text(client, chat_id, copy.group_only_excel_pdf())
|
||||
# 产品口径(2026-11-19 真机):群里没 @BOT 的 Word/zip 不要搭话。
|
||||
# 只有文件名里明确带工单号(WO/VT+12 位)才提示一句「只收 Excel/PDF」,
|
||||
# 其余不支持的类型静默丢弃;文件本体仍可由会话存档旁听,不在这里报错。
|
||||
# 2026-11-21:若这次是明确 @ 了机器人才发的,就一定要提示,不能装看不见。
|
||||
if explicit or copy.extract_work_order_no(filename or ""):
|
||||
send_group_text(client, chat_id, copy.group_only_excel_pdf())
|
||||
else:
|
||||
logger.info("group_file_type_silent wo=%s file=%s", no or "-", (filename or "")[:80])
|
||||
return "file_type_rejected"
|
||||
_archive_file(flow, no, filename, media, sender_id)
|
||||
if is_product(ticket, sender_id, flow=flow):
|
||||
product = is_product(ticket, sender_id, flow=flow)
|
||||
if product:
|
||||
quote = {
|
||||
"source_label": "产品附件报价",
|
||||
"file_name": filename,
|
||||
@@ -1254,6 +1351,11 @@ def handle_group_file(
|
||||
notify_quote_attachment_saved(flow, chat_id, no, count=1)
|
||||
emit_group_deal(flow=flow, ticket=ticket, sess=sess, quote=quote)
|
||||
return "product_file_quote"
|
||||
if explicit:
|
||||
# 明确 @ 了机器人:附件已进后台,必须回一句让人知道办成了。
|
||||
# 非产品发的仍按「只存档」处理(不改报价),只是补一条保存回执。
|
||||
notify_quote_attachment_saved(flow, chat_id, no, count=1)
|
||||
return "file_archived_notified"
|
||||
return "file_archived"
|
||||
|
||||
|
||||
@@ -1311,7 +1413,8 @@ def dissolve_orphan_group(
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return "group_ignore"
|
||||
client = group_client_of(flow)
|
||||
# 解散群归应用:成员读取与移人都用 appchat 客户端;群内告别语可走 BOT。
|
||||
client = app_group_client(flow)
|
||||
info_fn = getattr(client, "_appchat_info", None)
|
||||
info: dict[str, Any] = {}
|
||||
if callable(info_fn):
|
||||
@@ -1387,7 +1490,8 @@ def dissolve_group(*, flow: Any, ticket: object, sess: Any = None) -> str:
|
||||
view = ticket_view(ticket)
|
||||
no = ticket_no(ticket)
|
||||
chat_id = str((sess.collab_chat_id if sess else "") or view.get("collab_chat_id") or "")
|
||||
client = group_client_of(flow)
|
||||
# 解散群归应用:成员读取与移人都用 appchat 客户端;群内告别语可走 BOT。
|
||||
client = app_group_client(flow)
|
||||
members = list(view.get("collab_member_ids") or view.get("memberIds") or [])
|
||||
if sess is not None:
|
||||
members = list(sess.invited_userids or members)
|
||||
@@ -1443,7 +1547,8 @@ def emit_group_deal(
|
||||
view = ticket_view(ticket)
|
||||
no = ticket_no(ticket)
|
||||
chat_id = str((sess.collab_chat_id if sess else "") or view.get("collab_chat_id") or "")
|
||||
client = group_client_of(flow)
|
||||
# 成交跟进属于群内事务:BOT 群只发文字(机器人桥不支持应用模板卡),应用群维持原卡片。
|
||||
client = outbound_group_client(group_client_of(flow), chat_id)
|
||||
q = dict(quote or (sess.quote if sess else None) or view.get("quote") or {})
|
||||
facts = dict((sess.facts if sess else None) or view.get("facts") or {})
|
||||
# 补推时 ver 取当前版本,卡上的按钮 key 与之前那张一致;无书签则不带版本后缀,
|
||||
@@ -1892,14 +1997,20 @@ def _merged_total(
|
||||
base: dict[str, Any] | None,
|
||||
rows: list[dict[str, Any]],
|
||||
incoming: dict[str, Any],
|
||||
*,
|
||||
skip_indexes: set[int] | None = None,
|
||||
bucket_delta: float = 0.0,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
总销售价:有 TMS 原合计就按改价差额加减,不能只加产品改的那几行。
|
||||
|
||||
美元行已含在 TMS 人民币合计里,不擅自换汇;只调整和合计同币种的差额。
|
||||
海运三段另外按原小计口径重算(见 recompute_sea_bucket_totals),这些行的差额
|
||||
已由 bucket_delta 一次给出,这里用 skip_indexes 跳过,避免重复加。
|
||||
产品正文已点币种(如 RMB→CNY)时,表头跟产品,禁止 TMS HKD 再盖回去(WO040)。
|
||||
"""
|
||||
src = dict(base or {})
|
||||
skip = skip_indexes or set()
|
||||
# 产品显式币种优先:否则「1RMB/KG」合并后表头仍停在 TMS HKD。
|
||||
header_ccy = str(incoming.get("currency") or src.get("currency") or "").strip()
|
||||
if header_ccy.upper() == "RMB":
|
||||
@@ -1911,7 +2022,9 @@ def _merged_total(
|
||||
total_ccy = "CNY"
|
||||
old_rows = _quote_fee_rows(src)
|
||||
delta = 0.0
|
||||
for new_row in rows:
|
||||
for idx, new_row in enumerate(rows):
|
||||
if idx in skip:
|
||||
continue
|
||||
new_amt = _parse_fee_amount(new_row.get("amount"))
|
||||
if new_amt is None:
|
||||
continue
|
||||
@@ -1920,15 +2033,18 @@ def _merged_total(
|
||||
line_ccy = "CNY"
|
||||
if line_ccy and line_ccy != total_ccy:
|
||||
continue
|
||||
idx = _match_fee_row(str(new_row.get("name") or ""), old_rows)
|
||||
if idx < 0:
|
||||
old_idx = _match_fee_row(str(new_row.get("name") or ""), old_rows)
|
||||
if old_idx < 0:
|
||||
delta += new_amt
|
||||
continue
|
||||
old_amt = _parse_fee_amount(old_rows[idx].get("amount"))
|
||||
old_amt = _parse_fee_amount(old_rows[old_idx].get("amount"))
|
||||
if old_amt is None:
|
||||
continue
|
||||
delta += new_amt - old_amt
|
||||
return _format_fee_total(base_total + delta, str(src.get("total") or "")), header_ccy
|
||||
return (
|
||||
_format_fee_total(base_total + delta + bucket_delta, str(src.get("total") or "")),
|
||||
header_ccy,
|
||||
)
|
||||
|
||||
amounts: list[float] = []
|
||||
ccys: set[str] = set()
|
||||
@@ -1943,7 +2059,9 @@ def _merged_total(
|
||||
if amounts and len(ccys) <= 1:
|
||||
ccy = next(iter(ccys)) if ccys else header_ccy
|
||||
return _format_fee_total(sum(amounts)), ccy
|
||||
return str(src.get("total") or ""), header_ccy
|
||||
# 多币种且没有原合计:直接退回产品自己按主币种算的合计。
|
||||
# 绝不把美元行和人民币行加成一个数,也不在这里编汇率。
|
||||
return str(src.get("total") or incoming.get("total") or ""), header_ccy
|
||||
|
||||
|
||||
def _align_wrong_default_freight(
|
||||
@@ -2025,14 +2143,36 @@ def merge_quote_fees(base: dict[str, Any] | None, overlay: dict[str, Any] | None
|
||||
out["fee_rows"] = rows
|
||||
out["fee_lines"] = rows
|
||||
out["source_label"] = incoming.get("source_label") or "产品报价"
|
||||
total, currency = _merged_total(base, rows, incoming)
|
||||
# 产品改价后,海运三段小计也要跟着动;否则模板上的小计还是 TMS 原价。
|
||||
# 表头币种被产品改掉时不能拿原小计硬套,直接跳过,沿用老口径。
|
||||
base_ccy = str((base or {}).get("currency") or "").strip().upper()
|
||||
if base_ccy == "RMB":
|
||||
base_ccy = "CNY"
|
||||
head_ccy = str(incoming.get("currency") or base_ccy or "").strip().upper()
|
||||
if head_ccy == "RMB":
|
||||
head_ccy = "CNY"
|
||||
meta: dict[str, Any] = {}
|
||||
if base_ccy and head_ccy and base_ccy == head_ccy:
|
||||
from agent.schema.quote_adjust import recompute_sea_bucket_totals
|
||||
|
||||
meta = recompute_sea_bucket_totals(base, rows)
|
||||
total, currency = _merged_total(
|
||||
base,
|
||||
rows,
|
||||
incoming,
|
||||
skip_indexes=set(meta.get("bucket_rows") or ()),
|
||||
bucket_delta=float(meta.get("delta") or 0.0),
|
||||
)
|
||||
if total:
|
||||
out["total"] = total
|
||||
if currency:
|
||||
out["currency"] = currency
|
||||
for key, sub_total in (meta.get("subtotals") or {}).items():
|
||||
out["fee_total_" + key] = sub_total
|
||||
from agent.schema.quote_adjust import stamp_prices_for_sheet
|
||||
|
||||
return stamp_prices_for_sheet(out)
|
||||
out = stamp_prices_for_sheet(out)
|
||||
return out
|
||||
|
||||
|
||||
def _attach_land_weight_band_segment(
|
||||
@@ -2077,6 +2217,9 @@ def _attach_land_weight_band_segment(
|
||||
if tax:
|
||||
seg["tax_rate"] = tax
|
||||
seg["taxRate"] = tax
|
||||
remark = str(src.get("remark") or "").strip()
|
||||
if remark:
|
||||
seg["remark"] = remark
|
||||
src["landSegments"] = [seg]
|
||||
src["route_rows"] = [seg]
|
||||
return src
|
||||
@@ -2118,40 +2261,61 @@ def _attach_land_vehicle_rates_segment(
|
||||
"""
|
||||
陆运产品多车型价:把 vehicleRates 挂到 landSegments,出单才能填 5T/10T/40HQ 列。
|
||||
|
||||
无车型价表时原样返回。OD 取工单询价事实;备注进段上 remark(含0点税等)。
|
||||
无多车型价表时也不急着返回:跨境整车常只写「45HQ,运输费USD3200」,
|
||||
车型是走柜事实、钱是分项。此时把车型挂到段上,但要保留 fee_rows,
|
||||
否则费用明细被清空、出单只剩一个车型没有金额。
|
||||
|
||||
无车型价也无车型时原样返回。OD 取工单询价事实;备注、税率、燃油费率都进段上,
|
||||
出单侧栏(税率/燃油)和备注列直接读段,不再靠顶层字段兜底。
|
||||
不写裸 salePrice 冒充单车型,避免多列表头误灌同一价。
|
||||
"""
|
||||
src = dict(quote or {})
|
||||
rates = src.get("vehicleRates") or src.get("vehicle_rates")
|
||||
if not isinstance(rates, dict) or not rates:
|
||||
return src
|
||||
clean = {
|
||||
str(k).strip(): str(v).strip()
|
||||
for k, v in rates.items()
|
||||
if str(k).strip() and str(v).strip()
|
||||
}
|
||||
if not clean:
|
||||
clean: dict[str, str] = {}
|
||||
if isinstance(rates, dict) and rates:
|
||||
clean = {
|
||||
str(k).strip(): str(v).strip()
|
||||
for k, v in rates.items()
|
||||
if str(k).strip() and str(v).strip()
|
||||
}
|
||||
vehicle_type = str(src.get("vehicleType") or src.get("vehicle_type") or "").strip()
|
||||
if not clean and not vehicle_type:
|
||||
return src
|
||||
origin, dest = _land_od_from_view(view)
|
||||
remark = str(src.get("remark") or "").strip()
|
||||
seg: dict[str, Any] = {
|
||||
"origin": origin,
|
||||
"destination": dest,
|
||||
"vehicleRates": dict(clean),
|
||||
"vehicle_rates": dict(clean),
|
||||
"currency": str(src.get("currency") or "CNY"),
|
||||
}
|
||||
if clean:
|
||||
seg["vehicleRates"] = dict(clean)
|
||||
seg["vehicle_rates"] = dict(clean)
|
||||
else:
|
||||
# 只有车型没有价矩阵:车型照样落段,金额仍由 fee_rows 表达。
|
||||
seg["vehicleType"] = vehicle_type
|
||||
if remark:
|
||||
seg["remark"] = remark
|
||||
# 未含税/含0税/燃油口径:税率和燃油费率必须随段进主账,
|
||||
# 跨境整车/集拼的 routeRegions 侧栏直接读段上这两个键。
|
||||
fuel = str(src.get("fuel_surcharge_rate") or src.get("fuelSurchargeRate") or "").strip()
|
||||
tax = str(src.get("tax_rate") or src.get("taxRate") or "").strip()
|
||||
if fuel:
|
||||
seg["fuel_surcharge_rate"] = fuel
|
||||
seg["fuelSurchargeRate"] = fuel
|
||||
if tax:
|
||||
seg["tax_rate"] = tax
|
||||
seg["taxRate"] = tax
|
||||
# 展示合计用第一档,不写入 salePrice,防止 resolve 在无 map 匹配时乱灌。
|
||||
src["landSegments"] = [seg]
|
||||
src["route_rows"] = [seg]
|
||||
src["vehicleRates"] = dict(clean)
|
||||
src["vehicle_rates"] = dict(clean)
|
||||
# 多车型价只走 vehicleRates 矩阵列;fee_rows 若仍是「10T/40HQ」会被出单当成费目名
|
||||
# 写进国内段「起始地」(运行证据:国内段出现 10T/40HQ/45HQ 行)。挂段后清空费目行。
|
||||
src["fee_rows"] = []
|
||||
src["fee_lines"] = []
|
||||
if clean:
|
||||
src["vehicleRates"] = dict(clean)
|
||||
src["vehicle_rates"] = dict(clean)
|
||||
# 多车型价只走 vehicleRates 矩阵列;fee_rows 若仍是「10T/40HQ」会被出单当成费目名
|
||||
# 写进国内段「起始地」(运行证据:国内段出现 10T/40HQ/45HQ 行)。挂段后清空费目行。
|
||||
src["fee_rows"] = []
|
||||
src["fee_lines"] = []
|
||||
return src
|
||||
|
||||
|
||||
|
||||
@@ -242,11 +242,11 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
trade_source = source
|
||||
if sess and getattr(sess, "phase", "") in {"clarify", "wait_confirm", "sensitive_block"}:
|
||||
trade_source = stack_user_text(getattr(sess, "immutable_text", "") or "", text)
|
||||
# 整句只回「港到港」是贸易条款举例,不要改写成运输分类。
|
||||
# 整句只回「港到港」是贸易条款举例,不要改写成运输分类(门到门/门到港/港到门本来就不在分类名单里)。
|
||||
class_source = "" if short_sea_trade_reply(source) == "港到港" else source
|
||||
facts = harvest_sea_class(class_source, facts)
|
||||
# 贸易条款标签行原样优先;整句回复或长句里写了门到门/港到港都要收下。
|
||||
# 原话没出现这两个词时,模型冒充的门到门、港到港继续丢掉。
|
||||
# 贸易条款标签行原样优先;整句回复或长句里写了门到门/港到港/门到港/港到门都要收下。
|
||||
# 原话没出现这四项时,模型冒充的条款继续丢掉。
|
||||
# 补问用 trade_source(首句+本句),避免只补货量时丢掉已确认的港到港。
|
||||
facts = apply_spoken_sea_trade_reply(trade_source, facts)
|
||||
# 本句显式改条款时覆盖历史(短回门到门/港到港,或写出 FOB/CIF 等)。
|
||||
@@ -446,6 +446,8 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
return "ledger_fail"
|
||||
self._flush_pending_files(sender_id, no)
|
||||
first, history_wo = self._resolve_similar(created, facts=facts, current_no=no)
|
||||
# 建单确认只发「工单号 + 工单已创建,正在查询TMS报价。」;
|
||||
# 产品口径 2026-11-22:确定后不再重复字段段,字段只在确定前的核对卡上看。
|
||||
out_id = reply(
|
||||
copy.inquiry_card(
|
||||
work_order_no=no,
|
||||
@@ -499,8 +501,11 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
self._save(sess)
|
||||
return "tms_tech"
|
||||
if not tms.get("has_price"):
|
||||
self._emit_tms_miss(reply, no)
|
||||
# TMS 已回 1002/1003:把 remark 原文带给卡片并记进书签,销售能看到具体哪条条件对不上。
|
||||
reason = copy.tms_miss_reason(tms)
|
||||
self._emit_tms_miss(reply, no, reason)
|
||||
sess.phase = "tms_miss"
|
||||
sess.tms_miss_reason = reason
|
||||
sess.status = "询价中"
|
||||
sess.allowed = (copy.BTN_PULL_COLLAB,)
|
||||
self._save(sess)
|
||||
@@ -561,15 +566,20 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
return "same", history
|
||||
return "first", ""
|
||||
|
||||
def _emit_tms_miss(self, reply: ReplyFn, work_order_no: str) -> None:
|
||||
"""海运无价:一张带拉群按钮的卡,不再发手动拉人群句。"""
|
||||
def _emit_tms_miss(self, reply: ReplyFn, work_order_no: str, reason: str = "") -> None:
|
||||
"""
|
||||
海运/陆运无价:一张带拉群按钮的卡,不再发手动拉人群句。
|
||||
|
||||
reason 为 TMS 回包 remark 原文;有值时卡片「查价结果」直接展示,销售才知道哪条条件对不上。
|
||||
"""
|
||||
from agent.config import get_settings
|
||||
|
||||
reply(
|
||||
copy.sea_tms_miss(work_order_no=work_order_no),
|
||||
copy.sea_tms_miss(work_order_no=work_order_no, reason=reason),
|
||||
copy.sea_tms_miss_wecom_payload(
|
||||
work_order_no=work_order_no,
|
||||
action_url=(get_settings().public_base_url or "").strip(),
|
||||
reason=reason,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -723,7 +733,8 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
)
|
||||
return "wait_collab"
|
||||
if line in {"SEA", "LAND"} and sess.phase == "tms_miss":
|
||||
self._emit_tms_miss(reply, sess.work_order_no)
|
||||
# 重放时带上书签里记的 TMS 原因,禁止退回只剩「暂无匹配报价」。
|
||||
self._emit_tms_miss(reply, sess.work_order_no, sess.tms_miss_reason or "")
|
||||
return "tms_miss"
|
||||
return super()._replay_wait(sess, reply, source=source)
|
||||
|
||||
@@ -777,8 +788,9 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
card_meta: Optional[dict[str, Any]] = None,
|
||||
) -> str:
|
||||
"""
|
||||
点「拉产品进群协同」:按线路拉产品人,新建群,私聊回执,按钮置灰。
|
||||
点「拉产品进群协同」:按线路拉产品人,新建群,立刻发字段摘要,私聊回执,按钮置灰。
|
||||
|
||||
建群瞬间发询价字段(不发表);后续报价识别/出表仍等群里 @BOT。
|
||||
没人可拉 / 建群失败:说明原因,按钮保持可点。已有群:不新建,置灰。
|
||||
"""
|
||||
no = (sess.work_order_no or "").strip()
|
||||
@@ -812,6 +824,13 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
watch_collab_room(existing, work_order_no=no)
|
||||
except Exception:
|
||||
logger.exception("登记已有存档监听群失败 chat=%s", existing)
|
||||
# 已有群可能是改造前由应用建的老群:补记 BOT 接管,后续按 @BOT 规则处理。
|
||||
try:
|
||||
from agent.redis_coord.group_bot import mark_group_bot
|
||||
|
||||
mark_group_bot(existing, (sess.business_line or "SEA").upper(), no)
|
||||
except Exception:
|
||||
logger.exception("补记已有海运协同群 BOT 模式失败 chat=%s", existing)
|
||||
reply(copy.sea_group_exists(work_order_no=no))
|
||||
return "collab_group"
|
||||
|
||||
@@ -904,23 +923,22 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
allowed_keys=keys,
|
||||
)
|
||||
|
||||
ticket_view = ticket if isinstance(ticket, dict) else {}
|
||||
tms = copy.resolve_tms_quote(sess, ticket_view)
|
||||
brief = copy.sea_group_brief(
|
||||
work_order_no=no,
|
||||
facts=sess.facts,
|
||||
quote=sess.quote,
|
||||
collab_facts=sess.collab_facts,
|
||||
sales_name=sales_name,
|
||||
product_names=product_names,
|
||||
has_price=bool(tms or sess.quote),
|
||||
tms_quote=tms,
|
||||
product_quote=sess.quote if copy.quote_is_product(sess.quote) else None,
|
||||
transport_mode=self._group_brief_mode(sess),
|
||||
)
|
||||
client.send_group(chat_id=chat_id, content=brief)
|
||||
# 产品口径(2026-11-20):建群后立即发字段摘要;出表仍等 @BOT 说「生成报价单」。
|
||||
try:
|
||||
from agent.redis_coord.group_bot import mark_group_bot
|
||||
|
||||
mark_group_bot(chat_id, "SEA", no)
|
||||
except Exception:
|
||||
logger.exception("登记海运协同群 BOT 模式失败 chat=%s", chat_id)
|
||||
sess.collab_chat_id = chat_id
|
||||
# 建群只发摘要,不自动发空白报价单;销售/商务说「生成报价单」再出表。
|
||||
try:
|
||||
from agent.policy.handoff_human import send_collab_field_brief_now
|
||||
|
||||
ticket_now = getter(work_order_no=no) if callable(getter) else ticket
|
||||
send_collab_field_brief_now(self, ticket=ticket_now, sess=sess)
|
||||
except Exception:
|
||||
logger.exception("海运拉群后发字段摘要失败 chat=%s wo=%s", chat_id, no)
|
||||
# 不自动发空白报价单;销售/商务 @BOT 说「生成报价单」再出表。
|
||||
sess.invited_userids = tuple(userids)
|
||||
sess.invited_sales_name = sales_name
|
||||
sess.invited_product_names = tuple(product_names)
|
||||
@@ -981,8 +999,8 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
card_meta: Optional[dict[str, Any]] = None,
|
||||
) -> str:
|
||||
"""
|
||||
点转人工「拉产品进群」:建群、发转人工摘要、正式单改「转人工」。
|
||||
虚拟单不写主账。不发 TMS、不发模板、不跟成交。
|
||||
点转人工「拉产品进群」:建群,正式单改「转人工」,立刻发字段摘要。
|
||||
虚拟单不写主账。不发 TMS、不发模板、不跟成交;出表仍等群里说「生成报价单」。
|
||||
"""
|
||||
from agent.policy.handoff_human import (
|
||||
HANDOFF_STATUS,
|
||||
@@ -991,6 +1009,18 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
)
|
||||
|
||||
if sess.collab_ended or (sess.collab_chat_id or "").strip():
|
||||
existing = (sess.collab_chat_id or "").strip()
|
||||
if existing:
|
||||
try:
|
||||
from agent.redis_coord.group_bot import mark_group_bot
|
||||
|
||||
mark_group_bot(
|
||||
existing,
|
||||
(sess.business_line or "SEA").upper(),
|
||||
(sess.work_order_no or "").strip(),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("补记已有转人工群 BOT 模式失败 chat=%s", existing)
|
||||
reply(copy.already_collab())
|
||||
return "handoff_already"
|
||||
display_no = ensure_virtual_no(sess) if not (sess.work_order_no or "").strip() else sess.work_order_no
|
||||
@@ -1046,14 +1076,29 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
)
|
||||
return sess.phase or "handoff_offer"
|
||||
chat_id = str(created.get("chat_id") or "").strip()
|
||||
brief = copy.handoff_group_brief(
|
||||
work_order_no=display_no,
|
||||
facts=sess.facts,
|
||||
business_line=sess.business_line,
|
||||
product_names=product_names,
|
||||
)
|
||||
client.send_group(chat_id=chat_id, content=brief)
|
||||
real = (sess.work_order_no or "").strip()
|
||||
# 产品口径(2026-11-20):建群后立即发转人工字段摘要;出表仍等 @BOT。
|
||||
try:
|
||||
from agent.redis_coord.group_bot import mark_group_bot
|
||||
|
||||
mark_group_bot(chat_id, sess.business_line or "SEA", real)
|
||||
except Exception:
|
||||
logger.exception("登记转人工协同群 BOT 模式失败 chat=%s", chat_id)
|
||||
try:
|
||||
from agent.policy.handoff_human import send_handoff_field_brief_now
|
||||
|
||||
send_handoff_field_brief_now(
|
||||
self,
|
||||
chat_id=chat_id,
|
||||
work_order_no=display_no or real,
|
||||
facts=dict(sess.facts or {}),
|
||||
business_line=(sess.business_line or "SEA").upper(),
|
||||
product_names=product_names,
|
||||
sales_name=self._sales_display_name(sess.sender_id),
|
||||
mention_userids=[uid for uid in product_ids if uid],
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("转人工拉群后发字段摘要失败 chat=%s", chat_id)
|
||||
if real and not is_virtual_no(real):
|
||||
trans = getattr(self._ledger, "transition", None)
|
||||
if callable(trans):
|
||||
@@ -1274,21 +1319,30 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
|
||||
|
||||
sales_name = self._sales_display_name(sess.sender_id)
|
||||
|
||||
# ⑤ 群内摘要:让产品一眼看到工单号、询价字段和还缺什么。
|
||||
brief = copy.handoff_group_brief(
|
||||
work_order_no=no,
|
||||
facts=sess.facts,
|
||||
business_line="SEA",
|
||||
product_names=product_names,
|
||||
sales_name=sales_name,
|
||||
)
|
||||
# ⑤ 产品口径(2026-11-20):建群后立即发字段摘要;出表仍等 @BOT 说「生成报价单」。
|
||||
try:
|
||||
client.send_group(chat_id=chat_id, content=brief)
|
||||
except Exception:
|
||||
logger.exception("海运转人工群发摘要失败 chat=%s wo=%s", chat_id, no)
|
||||
from agent.redis_coord.group_bot import mark_group_bot
|
||||
|
||||
# ⑥ 不自动发表:报价单由群里「生成报价单」指令触发,和自动协同群同一口径。
|
||||
# 建群瞬间就推空白表,销售/产品会以为系统已经报过价,也会绕过按需出表。
|
||||
mark_group_bot(chat_id, "SEA", no)
|
||||
except Exception:
|
||||
logger.exception("登记海运转人工群 BOT 模式失败 chat=%s", chat_id)
|
||||
try:
|
||||
from agent.policy.handoff_human import send_handoff_field_brief_now
|
||||
|
||||
send_handoff_field_brief_now(
|
||||
self,
|
||||
chat_id=chat_id,
|
||||
work_order_no=no,
|
||||
facts=dict(sess.facts or {}),
|
||||
business_line="SEA",
|
||||
product_names=product_names,
|
||||
sales_name=sales_name,
|
||||
mention_userids=[uid for uid in product_ids if uid],
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("海运转人工建群后发字段摘要失败 chat=%s wo=%s", chat_id, no)
|
||||
|
||||
# ⑥ 不自动发表:报价单由群里 @BOT 说「生成报价单」触发,和自动协同群同一口径。
|
||||
|
||||
# ⑦ 盯产品报价:转人工单照常计入产品响应,超时仍提醒;不启动成交等待。
|
||||
from agent.policy.event_exception import WAIT_PRODUCT_QUOTE, start_wait
|
||||
|
||||
@@ -586,7 +586,10 @@ def _send_to_conversation(*, kind: str, target: str, text: str, extra: dict[str,
|
||||
secret=s.wecom_secret,
|
||||
agent_id=int(s.wecom_agent_id or "0") or 0,
|
||||
)
|
||||
client.send_group(chat_id=dest, content=body)
|
||||
# 恢复话术属于群内对话:BOT 群由 BOT 发,应用群仍走 appchat。
|
||||
from agent.policy.sea_group_ops import outbound_group_client
|
||||
|
||||
outbound_group_client(client, dest).send_group(chat_id=dest, content=body)
|
||||
return dest
|
||||
except Exception:
|
||||
logger.exception("系统异常群回话失败 chat=%s", dest)
|
||||
@@ -720,6 +723,13 @@ def run_admin_retry(work_order_no: str, *, ledger: Any = None) -> dict[str, Any]
|
||||
)
|
||||
return {"ok": False, "error": "still_fail", "step": STEP_GROUP}
|
||||
new_chat = str((result or {}).get("chat_id") or chat_id).strip()
|
||||
if new_chat and not chat_id and line in {"SEA", "LAND"}:
|
||||
try:
|
||||
from agent.redis_coord.group_bot import mark_group_bot
|
||||
|
||||
mark_group_bot(new_chat, line, no)
|
||||
except Exception:
|
||||
logger.exception("重试建群登记 BOT 模式失败 chat=%s", new_chat)
|
||||
binder = getattr(book, "bind_collab_group", None)
|
||||
if new_chat and callable(binder) and not chat_id:
|
||||
binder(
|
||||
@@ -792,7 +802,8 @@ def _resume_tms_quote(
|
||||
if not tms.get("has_price"):
|
||||
miss = getattr(flow, "_emit_tms_miss", None)
|
||||
if callable(miss):
|
||||
miss(reply, no)
|
||||
# 重试查价同样有 TMS 回包:把 remark 原文带到卡片,不能只剩「暂无匹配报价」。
|
||||
miss(reply, no, copy.tms_miss_reason(tms))
|
||||
else:
|
||||
reply(f"工单{no}暂无 TMS 报价。")
|
||||
if sender:
|
||||
|
||||
@@ -279,15 +279,23 @@ def _keyword_needles(kw: str) -> list[str]:
|
||||
return out
|
||||
|
||||
|
||||
# 单独出现时过宽:国内模板别名常拆出这些短词,会误配「中港零担/集拼」「跨境整车」。
|
||||
# 中港/跨境模板须用带前缀的词(中港零担、跨境集拼),不能靠裸「零担/集拼」抢单。
|
||||
_BARE_LAND_NEEDLES = frozenset({"整车", "零担", "拼车", "集拼"})
|
||||
|
||||
|
||||
def _needle_in(text: str, needle: str) -> bool:
|
||||
"""
|
||||
陆运针:普通包含。单独「整车」不命中跨境/中港,避免国内整车模板抢走跨境单。
|
||||
陆运针:普通包含。
|
||||
|
||||
裸「整车/零担/拼车/集拼」不命中含跨境/中港的文本:
|
||||
否则国内拼车模板靠「零担」「集拼」别名会抢走中港集拼单(WO202611180001)。
|
||||
"""
|
||||
hay = (text or "").lower()
|
||||
n = (needle or "").strip().lower()
|
||||
if not hay or not n or n not in hay:
|
||||
return False
|
||||
if n == "整车" and ("跨境" in hay or "中港" in hay):
|
||||
if n in _BARE_LAND_NEEDLES and ("跨境" in hay or "中港" in hay):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@@ -0,0 +1,638 @@
|
||||
"""
|
||||
协同群 BOT 模式与「当前工单关联」短协调(对齐 prompt/14)。
|
||||
|
||||
为什么需要:
|
||||
- 陆运/海运/空运产品协同群里,智价通应用只负责拉群、解散群;
|
||||
报价识别、发报价单、工单状态跟进等对话事务由智价通BOT负责。
|
||||
- 群里没有 @BOT 的文字,BOT 不回应;并且要「断开当前工单关联」,
|
||||
这样下一条 @BOT 但没有带工单号的消息,才会提示销售重新下达任务。
|
||||
- 工单号关联是短生命周期协调数据,不是六态;六态只存主账。
|
||||
因此这里只放 Redis(带环境前缀)+进程内兜底,不写 MySQL、不写 PG checkpoint。
|
||||
|
||||
存储:
|
||||
- group_bot:rooms 已由 BOT 接管的群,值形如 "chat1:SEA,chat2:AIR"。
|
||||
- group_bot:active_wo:<chat_id> 该群当前关联的工单号,24 小时过期。
|
||||
- group_bot:at_burst:<chat_id> 「@BOT 指令窗口」起点时间戳(30 分钟),
|
||||
群里 @BOT 之后到下一句普通文字之前算同一次指令,
|
||||
窗口内的图片/Excel/PDF 才当这次询价的材料。
|
||||
- group_bot:pending_media:<chat_id> 窗口外先到的群图片/附件(10 分钟),
|
||||
等紧接着的 @BOT 认领后补办(企微里附件不能被 @)。
|
||||
- group_bot:aibot_text:<chat_id> AIBOT 刚办过的群文字指纹(5 分钟),
|
||||
只用来挡住会话存档把同一句再办一遍。
|
||||
|
||||
线程:
|
||||
- 进程内 set/dict 用一把小锁只保护这两个字典,不串行任何工单业务。
|
||||
- Redis 客户端本身是连接池,可被 HTTP/Worker 多线程共用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_ROOM_KEY = "group_bot:room"
|
||||
_ROOMS_KEY = "group_bot:rooms" # 兼容早期集合写法,只读不写
|
||||
_ACTIVE_KEY = "group_bot:active_wo"
|
||||
_ACTIVE_TTL_SECONDS = 24 * 3600
|
||||
# AIBOT 已办过的群文字指纹:只覆盖存档延迟窗口,过期即失效。
|
||||
_HANDLED_KEY = "group_bot:aibot_text"
|
||||
_HANDLED_TTL_SECONDS = 300
|
||||
# 去重放行标记后缀:AIBOT 那条身份不可信(加密 ID 换不出明文)时,允许存档补办。
|
||||
_RETRY_SUFFIX = "#retry"
|
||||
# 群标记跟着群走,给 180 天;到期后旧群再被 @ 会按主账工单自动补回。
|
||||
_ROOM_TTL_SECONDS = 180 * 24 * 3600
|
||||
# 「这个群真的收到过 AIBOT 回调」——等同于「智价通BOT 已在本群」。
|
||||
# 用途:@会话存档账号的兜底触发只在 BOT 不在本群时生效,避免两套回话并存。
|
||||
# 30 天过期:BOT 被移出群后,30 天后兜底会重新接管这个群。
|
||||
_BOT_SEEN_KEY = "group_bot:bot_seen"
|
||||
_BOT_SEEN_TTL_SECONDS = 30 * 24 * 3600
|
||||
# 「@BOT 指令窗口」:群里 @BOT 之后、到下一句普通文字之前这段时间。
|
||||
# 产品口径(2026-11-21):群附件(Excel/PDF)和图片本身无法 @,
|
||||
# 只能靠这个窗口判断「是不是这次 @BOT 指令要发的材料」;窗口外一律静默。
|
||||
_AT_BURST_KEY = "group_bot:at_burst"
|
||||
_AT_BURST_TTL_SECONDS = 30 * 60
|
||||
# 「待归属的群附件」:窗口外先到、还没遇到 @ 的图片/Excel/PDF。
|
||||
# 为什么必须缓冲而不是直接丢:企微里群附件根本不能被 @,销售的真实习惯是
|
||||
# 「先发文件、再 @ 机器人说你要干什么」;只按「先 @ 后发」判断会把真业务全部丢掉
|
||||
# (2026-11-21 真机:两个报价 Excel + @会话存档机器人,BOT 一声不吭)。
|
||||
_PENDING_KEY = "group_bot:pending_media"
|
||||
# 缓冲只等「紧接着的那次 @」;10 分钟没等到就过期,避免十几分钟前的旧文件被误认。
|
||||
_PENDING_TTL_SECONDS = 600
|
||||
# 单群最多记 5 条:一次指令不会发几十个附件,超出的按最新保留。
|
||||
_PENDING_MAX = 5
|
||||
|
||||
# 进程内兜底:Redis 不可用(本地单测、memory 后端)时也能表达「BOT 已接管」。
|
||||
_local_rooms: dict[str, str] = {}
|
||||
_local_active: dict[str, str] = {}
|
||||
# 同群最近一条已由 AIBOT 办过的文字指纹(只留最后一条,够挡存档重复)。
|
||||
_local_handled: dict[str, str] = {}
|
||||
# 进程内「BOT 已在本群出现」兜底标记,语义同 _BOT_SEEN_KEY。
|
||||
_local_bot_seen: set[str] = set()
|
||||
# 进程内「@BOT 指令窗口」兜底:值是写入时的 epoch 秒,读侧自行判过期。
|
||||
_local_at_burst: dict[str, int] = {}
|
||||
# 进程内「待归属群附件」兜底:值是 (写入 epoch 秒, InboundMessage.to_dict() 列表)。
|
||||
_local_pending: dict[str, tuple[int, list[dict]]] = {}
|
||||
_guard = threading.Lock()
|
||||
|
||||
|
||||
def _client():
|
||||
"""懒取 Redis 门面;连不上返回 None,让调用方走进程内兜底。"""
|
||||
try:
|
||||
from agent.redis_coord.runtime import get_redis_runtime
|
||||
|
||||
return get_redis_runtime().client
|
||||
except Exception: # noqa: BLE001 - 协调数据不可用不能阻断业务
|
||||
logger.warning("group_bot: Redis 不可用,使用进程内兜底", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def _parse_rooms(raw: object) -> dict[str, str]:
|
||||
"""把 "chat1:SEA,chat2:AIR" 解析成 dict;坏数据直接跳过。"""
|
||||
rooms: dict[str, str] = {}
|
||||
for item in str(raw or "").split(","):
|
||||
text = item.strip()
|
||||
if not text:
|
||||
continue
|
||||
chat_id, _, line = text.partition(":")
|
||||
chat_id = chat_id.strip()
|
||||
if chat_id:
|
||||
rooms[chat_id] = (line or "").strip().upper()
|
||||
return rooms
|
||||
|
||||
|
||||
def mark_group_bot(
|
||||
chat_id: str, business_line: str = "", work_order_no: str = ""
|
||||
) -> None:
|
||||
"""
|
||||
标记某个协同群由智价通BOT接管。
|
||||
|
||||
参数:
|
||||
- chat_id:企微群 chat_id。
|
||||
- business_line:AIR / SEA / LAND / MULTI,用于把群消息路由到对应 handler。
|
||||
- work_order_no:建群/绑群时已知的工单号。带了就同时建立「当前单关联」,
|
||||
这样建群后第一条 @BOT(可能只说「成交」)不用重新带号;
|
||||
之后群里出现非 @BOT 文字才断开。
|
||||
副作用:写进程内 dict 与 Redis 短键;失败只告警,不影响建群/回执。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return
|
||||
line = (business_line or "").strip().upper()
|
||||
with _guard:
|
||||
_local_rooms[room] = line or _local_rooms.get(room, "")
|
||||
if (work_order_no or "").strip():
|
||||
# 建群/绑群即建立当前单关联;之后非 @BOT 文字才断开。
|
||||
set_active_work_order(room, work_order_no)
|
||||
client = _client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
# 一个群一个键:并发建两个群不会互相覆盖。
|
||||
client.raw.set(client.key(_ROOM_KEY, room), line, ex=_ROOM_TTL_SECONDS)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 标记群失败 chat=%s", room, exc_info=True)
|
||||
|
||||
|
||||
def group_bot_line(chat_id: str) -> str:
|
||||
"""
|
||||
返回该群的业务线(AIR/SEA/LAND/MULTI);空串表示还没标记为 BOT 群。
|
||||
|
||||
注意:空串不等于「非 BOT 群」,旧群第一次收到 BOT 消息时由
|
||||
`ensure_group_bot_line` 按主账工单补齐。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return ""
|
||||
with _guard:
|
||||
cached = _local_rooms.get(room)
|
||||
if cached is not None:
|
||||
return cached
|
||||
client = _client()
|
||||
if client is None:
|
||||
return ""
|
||||
try:
|
||||
line = str(client.raw.get(client.key(_ROOM_KEY, room)) or "").strip().upper()
|
||||
if not line:
|
||||
# 兼容早期集合写法(只读);新写入一律用 per-group 键。
|
||||
line = _parse_rooms(client.raw.get(client.key(_ROOMS_KEY))).get(room, "")
|
||||
if line:
|
||||
with _guard:
|
||||
_local_rooms[room] = line
|
||||
return line
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 读群标记失败 chat=%s", room, exc_info=True)
|
||||
return ""
|
||||
|
||||
|
||||
def is_group_bot(chat_id: str) -> bool:
|
||||
"""该群是否已由 BOT 接管;空串视为未接管(兼容旧 appchat 群)。"""
|
||||
return bool(group_bot_line(chat_id))
|
||||
|
||||
|
||||
def ensure_group_bot_line(chat_id: str, fallback: str = "AIR") -> str:
|
||||
"""
|
||||
旧群第一次收到 BOT 消息时补齐业务线。
|
||||
|
||||
优先按主账 `find_by_collab_chat` 查真实业务线;查不到用 fallback(空运)。
|
||||
副作用:可能调用一次主账 HTTP;只在首次发生。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
existing = group_bot_line(room)
|
||||
if existing:
|
||||
return existing
|
||||
line = ""
|
||||
try:
|
||||
from agent.policy.air_text_flow import get_air_text_flow
|
||||
|
||||
ledger = get_air_text_flow().ledger
|
||||
finder = getattr(ledger, "find_by_collab_chat", None)
|
||||
hit = finder(chat_id=room) if callable(finder) else None
|
||||
if hit is not None:
|
||||
from agent.policy.sea_group_ops import ticket_view
|
||||
|
||||
view = ticket_view(hit)
|
||||
line = str(view.get("business_line") or "").strip().upper()
|
||||
wo = str(view.get("work_order_no") or "").strip()
|
||||
# 老群第一次被 BOT 接管:把已绑工单补成当前单,避免第一条没带号就被要求重发。
|
||||
if wo and not get_active_work_order(room):
|
||||
set_active_work_order(room, wo)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 查群业务线失败 chat=%s", room, exc_info=True)
|
||||
line = line or (fallback or "").strip().upper()
|
||||
mark_group_bot(room, line)
|
||||
return line
|
||||
|
||||
|
||||
def _text_fingerprint(text: str) -> str:
|
||||
"""
|
||||
群文字指纹:去空白后取 sha1 前 20 位。
|
||||
|
||||
为什么要去空白:同一句在 AIBOT 回调与会话存档里,换行/空格可能被平台改写,
|
||||
原样比较会漏判,导致同一句被办两遍。
|
||||
"""
|
||||
compact = "".join(str(text or "").split())
|
||||
return hashlib.sha1(compact.encode("utf-8")).hexdigest()[:20]
|
||||
|
||||
|
||||
def mark_bot_text_handled(chat_id: str, text: str) -> None:
|
||||
"""
|
||||
记下「这条群文字已由 AIBOT 回调办过」。
|
||||
|
||||
用途:会话存档会旁听到同一句 @BOT(尤其空运),若再走一遍 handler
|
||||
就会把同一份工单摘要/模板发两遍(2026-11-19 测服真机复现)。
|
||||
TTL 5 分钟只覆盖存档延迟窗口,过期即失效,不当业务状态用。
|
||||
"""
|
||||
_write_handled(chat_id, text, retry_archive=False)
|
||||
|
||||
|
||||
def allow_archive_retry(chat_id: str, text: str) -> None:
|
||||
"""
|
||||
撤销「这句已办过」的去重,允许会话存档那条(明文身份)再办一遍。
|
||||
|
||||
为什么需要(2026-11-19 真机 WO202611190016):
|
||||
AIBOT 回调给的是加密 open_userid,被判「不是本单销售」而拒绝;约 15 秒后
|
||||
会话存档带着明文 userid 到达,本该补办,却被上面那条去重直接丢掉 ——
|
||||
结果是销售明明本人点成交,群里却一直回「只有负责该工单的销售可以确认成交状态」。
|
||||
身份换不成明文时,AIBOT 那条的结论不可信,必须让存档补办。
|
||||
"""
|
||||
_write_handled(chat_id, text, retry_archive=True)
|
||||
|
||||
|
||||
def _write_handled(chat_id: str, text: str, *, retry_archive: bool) -> None:
|
||||
"""
|
||||
写「已办」标记。retry_archive=True 时打上 `#retry` 后缀,读侧据此不再去重。
|
||||
|
||||
存储值形如 `abcdef0123456789ab`(去重生效)或 `abcdef0123456789ab#retry`(放行存档)。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
fingerprint = _text_fingerprint(text)
|
||||
if not room or not fingerprint:
|
||||
return
|
||||
value = fingerprint + _RETRY_SUFFIX if retry_archive else fingerprint
|
||||
with _guard:
|
||||
_local_handled[room] = value
|
||||
client = _client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.raw.set(client.key(_HANDLED_KEY, room), value, ex=_HANDLED_TTL_SECONDS)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 记 AIBOT 已办文字失败 chat=%s", room, exc_info=True)
|
||||
|
||||
|
||||
def bot_text_handled(chat_id: str, text: str) -> bool:
|
||||
"""
|
||||
这条群文字是否已经被 AIBOT 回调办过(同群 5 分钟内同文)。
|
||||
|
||||
带 `#retry` 后缀表示「AIBOT 那条身份不可信,允许存档补办」,这里返回 False。
|
||||
Redis 不可用时退回进程内记录;两者都没有就返回 False,让存档按老逻辑补听。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
fingerprint = _text_fingerprint(text)
|
||||
if not room or not fingerprint:
|
||||
return False
|
||||
with _guard:
|
||||
cached = str(_local_handled.get(room) or "")
|
||||
if cached and _dedupe_on(cached, fingerprint):
|
||||
return True
|
||||
client = _client()
|
||||
if client is None:
|
||||
return False
|
||||
try:
|
||||
value = client.raw.get(client.key(_HANDLED_KEY, room))
|
||||
text_value = str(value or "").strip()
|
||||
if text_value and _dedupe_on(text_value, fingerprint):
|
||||
with _guard:
|
||||
_local_handled[room] = text_value
|
||||
return True
|
||||
return False
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 读 AIBOT 已办文字失败 chat=%s", room, exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
def _dedupe_on(stored: str, fingerprint: str) -> bool:
|
||||
"""
|
||||
存的值是否代表「这句确实办成了、存档不用再来」。
|
||||
|
||||
只有指纹完全相等、且没打 `#retry` 后缀才算;后缀即「身份不可信,放行存档」。
|
||||
"""
|
||||
text = (stored or "").strip()
|
||||
if not text or text.endswith(_RETRY_SUFFIX):
|
||||
return False
|
||||
return text == fingerprint
|
||||
|
||||
|
||||
def handled_marker(chat_id: str) -> str:
|
||||
"""
|
||||
只读:取出该群当前「AIBOT 已办文字」标记,供排障日志使用。
|
||||
|
||||
为什么需要:会话存档那条被去重丢掉时,只有把标记值(指纹 / 是否带 #retry)
|
||||
与存档那句的指纹放在一起看,才能判断是「真的重复」还是「错误挡住」。
|
||||
不参与任何业务判断,验证完随探针一起删。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return ""
|
||||
client = _client()
|
||||
if client is None:
|
||||
with _guard:
|
||||
return str(_local_handled.get(room) or "")
|
||||
try:
|
||||
return str(client.raw.get(client.key(_HANDLED_KEY, room)) or "").strip()
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def set_active_work_order(chat_id: str, work_order_no: str) -> None:
|
||||
"""记录该群当前关联的工单号(@BOT 且带号时调用)。"""
|
||||
room = (chat_id or "").strip()
|
||||
work_order_no = (work_order_no or "").strip()
|
||||
if not room or not work_order_no:
|
||||
return
|
||||
with _guard:
|
||||
_local_active[room] = work_order_no
|
||||
client = _client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.raw.set(
|
||||
client.key(_ACTIVE_KEY, room), work_order_no, ex=_ACTIVE_TTL_SECONDS
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 写当前工单失败 chat=%s", room, exc_info=True)
|
||||
|
||||
|
||||
def get_active_work_order(chat_id: str) -> str:
|
||||
"""读该群当前关联的工单号;没有返回空串。"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return ""
|
||||
with _guard:
|
||||
cached = _local_active.get(room)
|
||||
if cached:
|
||||
return cached
|
||||
client = _client()
|
||||
if client is None:
|
||||
return ""
|
||||
try:
|
||||
value = client.raw.get(client.key(_ACTIVE_KEY, room))
|
||||
text = str(value or "").strip()
|
||||
if text:
|
||||
with _guard:
|
||||
_local_active[room] = text
|
||||
return text
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 读当前工单失败 chat=%s", room, exc_info=True)
|
||||
return ""
|
||||
|
||||
|
||||
def mark_bot_seen(chat_id: str) -> None:
|
||||
"""
|
||||
记下「这个群真的收到过 AIBOT 回调」=智价通BOT 已在本群。
|
||||
|
||||
用途(2026-11-19 产品口径):
|
||||
@会话存档账号只能当兜底唤醒,BOT 在群里时不该再用它,
|
||||
否则同一个群会出现两套回话身份。30 天过期,BOT 被移出群后兜底能重新接管。
|
||||
|
||||
副作用:写进程内 set 与 Redis 短键;失败只告警,不影响本条消息处理。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return
|
||||
with _guard:
|
||||
_local_bot_seen.add(room)
|
||||
client = _client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.raw.set(client.key(_BOT_SEEN_KEY, room), "1", ex=_BOT_SEEN_TTL_SECONDS)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 记 BOT 在群失败 chat=%s", room, exc_info=True)
|
||||
|
||||
|
||||
def bot_seen(chat_id: str) -> bool:
|
||||
"""
|
||||
该群是否收到过 AIBOT 回调(即智价通BOT 在群里)。
|
||||
|
||||
Redis 不可用时只用进程内标记;两者都没有返回 False,
|
||||
代表「可能没拉 BOT」,兜底唤醒才允许生效。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return False
|
||||
with _guard:
|
||||
if room in _local_bot_seen:
|
||||
return True
|
||||
client = _client()
|
||||
if client is None:
|
||||
return False
|
||||
try:
|
||||
value = client.raw.get(client.key(_BOT_SEEN_KEY, room))
|
||||
if str(value or "").strip():
|
||||
with _guard:
|
||||
_local_bot_seen.add(room)
|
||||
return True
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 读 BOT 在群标记失败 chat=%s", room, exc_info=True)
|
||||
return False
|
||||
|
||||
|
||||
def clear_active_work_order(chat_id: str) -> None:
|
||||
"""
|
||||
断开该群的当前工单关联。
|
||||
|
||||
触发点:群里出现「没有 @BOT 的文字」——按产品口径,任何非 @ 对话都算打断。
|
||||
文件/图片不带 @,不算文字打断,因此调用方只在文字消息时调用。
|
||||
|
||||
例外(2026-11-19):@会话存档账号的兜底唤醒是明确指令,调用方在走兜底分支时
|
||||
不调用本函数,保持当前单关联。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return
|
||||
with _guard:
|
||||
_local_active.pop(room, None)
|
||||
client = _client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.raw.delete(client.key(_ACTIVE_KEY, room))
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 清除当前工单失败 chat=%s", room, exc_info=True)
|
||||
|
||||
|
||||
def mark_at_burst(chat_id: str) -> None:
|
||||
"""
|
||||
进入(或刷新)该群的「@BOT 指令窗口」。
|
||||
|
||||
为什么需要(2026-11-21 产品口径):
|
||||
企微里群附件(Excel/PDF)和图片都不能被 @,只会以普通消息进会话存档;
|
||||
所以「这次附件是不是要询价」只能靠上下文判断:同一次指令内 @ 过 BOT,
|
||||
之后到下一句普通文字之前发来的附件/图片,才当成这次指令的材料。
|
||||
|
||||
语义:窗口是「按群」不是「按人」——同事 @BOT 后由另一个人代表发文件也算同一次指令。
|
||||
过期:Redis 30 分钟;进程内兜底同样按时间判过期,避免 Redis 挂掉时窗口永久有效。
|
||||
|
||||
副作用:写进程内 dict 与 Redis 短键;失败只告警,不影响当前消息处理。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return
|
||||
now = int(time.time())
|
||||
with _guard:
|
||||
_local_at_burst[room] = now
|
||||
client = _client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.raw.set(
|
||||
client.key(_AT_BURST_KEY, room), str(now), ex=_AT_BURST_TTL_SECONDS
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 记 @BOT 窗口失败 chat=%s", room, exc_info=True)
|
||||
|
||||
|
||||
def in_at_burst(chat_id: str) -> bool:
|
||||
"""
|
||||
当前是否处在「@BOT 指令窗口」内(@ 之后、下一句普通文字之前)。
|
||||
|
||||
Redis 不可用时退回进程内时间戳;两者都读不到返回 False,
|
||||
也就是「没 @ 过就按静默处理」,宁可少回一句也不主动搭话。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return False
|
||||
now = int(time.time())
|
||||
with _guard:
|
||||
local_ts = int(_local_at_burst.get(room) or 0)
|
||||
if local_ts and now - local_ts <= _AT_BURST_TTL_SECONDS:
|
||||
return True
|
||||
client = _client()
|
||||
if client is None:
|
||||
return False
|
||||
try:
|
||||
value = str(client.raw.get(client.key(_AT_BURST_KEY, room)) or "").strip()
|
||||
ts = int(value or 0)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 读 @BOT 窗口失败 chat=%s", room, exc_info=True)
|
||||
return False
|
||||
if not ts or now - ts > _AT_BURST_TTL_SECONDS:
|
||||
return False
|
||||
with _guard:
|
||||
_local_at_burst[room] = ts
|
||||
return True
|
||||
|
||||
|
||||
def clear_at_burst(chat_id: str) -> None:
|
||||
"""
|
||||
结束该群的「@BOT 指令窗口」。
|
||||
|
||||
触发点:群里出现「没有 @BOT 的普通文字」——产品口径是「@ 之后到下一句普通文字之前」,
|
||||
所以任何非 @ 对话都算这次指令结束,后续附件必须重新 @BOT。
|
||||
|
||||
例外:AIBOT 已办过的同一句存档回声、解散群口令不算「普通文字」,
|
||||
调用方须自行排除(见 dispatch)。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return
|
||||
with _guard:
|
||||
_local_at_burst.pop(room, None)
|
||||
client = _client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.raw.delete(client.key(_AT_BURST_KEY, room))
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 清除 @BOT 窗口失败 chat=%s", room, exc_info=True)
|
||||
|
||||
|
||||
def add_pending_media(chat_id: str, payload: dict) -> None:
|
||||
"""
|
||||
记下一条「窗口外先到」的群图片/附件,等紧接着的 @BOT 认领。
|
||||
|
||||
为什么要有它(2026-11-21 产品口径「@ 前后」):
|
||||
企微群里的 Excel/PDF/图片本身不能被 @,只能整条发出去;销售的习惯是
|
||||
「先发文件,再 @机器人 说要干什么」。只按「先 @ 后发」判断会把这类真询价
|
||||
全部静默丢掉。因此窗口外先到的附件先缓冲,等 @ 到来时补办一次。
|
||||
|
||||
参数:
|
||||
- chat_id:群 id;空则不记。
|
||||
- payload:InboundMessage.to_dict() 结果(含 sender/media/raw,够重放)。
|
||||
|
||||
副作用:写进程内 dict 与 Redis JSON 字符串键(10 分钟);失败只告警。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room or not isinstance(payload, dict) or not payload:
|
||||
return
|
||||
entries = _read_pending(room)
|
||||
entries.append(payload)
|
||||
if len(entries) > _PENDING_MAX:
|
||||
entries = entries[-_PENDING_MAX:]
|
||||
# 带上写入时间:进程内兜底没有 TTL 扫描,读侧只能靠自带时间戳判过期。
|
||||
now = int(time.time())
|
||||
with _guard:
|
||||
_local_pending[room] = (now, entries)
|
||||
client = _client()
|
||||
if client is None:
|
||||
return
|
||||
try:
|
||||
client.raw.set(
|
||||
client.key(_PENDING_KEY, room),
|
||||
json.dumps({"ts": now, "items": entries}, ensure_ascii=False, default=str),
|
||||
ex=_PENDING_TTL_SECONDS,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 记待归属附件失败 chat=%s", room, exc_info=True)
|
||||
|
||||
|
||||
def drain_pending_media(chat_id: str) -> list[dict]:
|
||||
"""
|
||||
取出并清空该群「待归属的群附件」。
|
||||
|
||||
只在 @BOT 到来时调用:取到就把它们当成这次指令的材料补办,然后清掉,
|
||||
避免同一个文件被下一次 @ 重复处理。两条来源(进程内 / Redis)一起清。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
if not room:
|
||||
return []
|
||||
entries = _read_pending(room)
|
||||
with _guard:
|
||||
_local_pending.pop(room, None)
|
||||
client = _client()
|
||||
if client is not None:
|
||||
try:
|
||||
client.raw.delete(client.key(_PENDING_KEY, room))
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 清待归属附件失败 chat=%s", room, exc_info=True)
|
||||
return entries
|
||||
|
||||
|
||||
def _read_pending(room: str) -> list[dict]:
|
||||
"""
|
||||
读该群待归属附件列表(只读,不清)。
|
||||
|
||||
优先级:进程内 → Redis。进程内没有 TTL 扫描,因此自带时间戳判过期:
|
||||
超过 _PENDING_TTL_SECONDS 就当作没有,避免十几分钟前的旧文件被误认领。
|
||||
"""
|
||||
now = int(time.time())
|
||||
with _guard:
|
||||
cached = _local_pending.get(room)
|
||||
if cached is not None:
|
||||
ts, items = cached
|
||||
if ts and now - int(ts) <= _PENDING_TTL_SECONDS:
|
||||
return [dict(x) for x in items if isinstance(x, dict)]
|
||||
with _guard:
|
||||
_local_pending.pop(room, None)
|
||||
return []
|
||||
client = _client()
|
||||
if client is None:
|
||||
return []
|
||||
try:
|
||||
raw = client.raw.get(client.key(_PENDING_KEY, room))
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("group_bot 读待归属附件失败 chat=%s", room, exc_info=True)
|
||||
return []
|
||||
if not raw:
|
||||
return []
|
||||
try:
|
||||
data = json.loads(raw if isinstance(raw, str) else str(raw, "utf-8"))
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
if not isinstance(data, dict):
|
||||
return []
|
||||
ts = int(data.get("ts") or 0)
|
||||
items = data.get("items")
|
||||
if not ts or now - ts > _PENDING_TTL_SECONDS or not isinstance(items, list):
|
||||
return []
|
||||
entries = [x for x in items if isinstance(x, dict)]
|
||||
if entries:
|
||||
with _guard:
|
||||
_local_pending[room] = (ts, [dict(x) for x in entries])
|
||||
return entries
|
||||
@@ -127,13 +127,14 @@ class IntentRouter:
|
||||
names = [str(r.get("name") or "") for r in quote_fee_rows(getattr(sess, "quote", None))]
|
||||
except Exception:
|
||||
logger.exception("route 收集调价书签失败 sender=%s", sender_id)
|
||||
return self.route(
|
||||
decision = self.route(
|
||||
text=text,
|
||||
sender_id=sender_id,
|
||||
session_quoted=quoted,
|
||||
fee_names=names,
|
||||
work_order_no=wo,
|
||||
)
|
||||
return decision
|
||||
|
||||
def enqueue_ordered_actions(
|
||||
self,
|
||||
|
||||
@@ -118,6 +118,9 @@ _SYSTEM = (
|
||||
"【结束询价】intent=end_inquiry,action_type=END_INQUIRY。"
|
||||
"销售要断开当前询价上下文、好开新单:结束询价、终止询价、这单先不算了、别跟这单了。"
|
||||
"不是成交/未成交,也不是转人工。问「怎么结束询价」仍是闲聊。"
|
||||
"销售在交代客户的成交结果时(客户不要了、客户不想要了、客户不做了、客户取消、"
|
||||
"客户嫌贵、客户比价、客户没回)不是结束询价,标 ordinary_text_other;"
|
||||
"机器人正在追问未成交原因时,这类原话就是原因,更不能再标结束询价。"
|
||||
"【闲聊】intent=ordinary_text_other,action_type=ORDINARY_TEXT_OTHER。"
|
||||
"问候、谢谢、无关闲聊。点卡片按钮字(生成Excel/生成PDF/不采用等)也标闲聊。"
|
||||
"禁止因为销售没说指定口令就把续办或调价判成新询价或闲聊。"
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Callable, Optional
|
||||
from contextlib import contextmanager
|
||||
from typing import Callable, Iterator, Optional
|
||||
|
||||
from agent.channel.wecom.models import InboundMessage
|
||||
from agent.handlers import abnormal, card_action, close_deal, continue_thread, new_inquiry
|
||||
@@ -21,12 +22,59 @@ from agent.handlers.text_inquiry import (
|
||||
handle_text_inquiry,
|
||||
handle_text_other,
|
||||
is_land_confirm_action,
|
||||
lost_reason_wait_state,
|
||||
should_resume_other_as_inquiry,
|
||||
)
|
||||
from agent.routing.decision import RouteDecision
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _fp(text: str) -> str:
|
||||
"""排障用:算与去重逻辑一致的群文字指纹;失败返回空串,不影响业务。"""
|
||||
try:
|
||||
from agent.redis_coord.group_bot import _text_fingerprint
|
||||
|
||||
return _text_fingerprint(text)
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _handled_marker(chat_id: str) -> str:
|
||||
"""排障用:读当前「AIBOT 已办文字」标记;失败返回空串。"""
|
||||
try:
|
||||
from agent.redis_coord.group_bot import handled_marker
|
||||
|
||||
return handled_marker(chat_id)
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def _ledger_binding(chat_id: str) -> tuple[bool, str, str]:
|
||||
"""
|
||||
排障用:查主账「这个群绑的哪张单」,返回 (是否命中, 工单号, 状态)。
|
||||
|
||||
为什么要查主账而不只看 Redis:Redis 的 active_wo 是短命关联,群里一句普通
|
||||
闲聊就会被清掉;主账绑群关系才是「这个群在服务哪张单」的权威来源。
|
||||
失败一律按「没命中」返回,不能影响业务分支。
|
||||
"""
|
||||
try:
|
||||
from agent.policy.air_text_flow import get_air_text_flow
|
||||
from agent.policy.sea_group_ops import ticket_no, ticket_view
|
||||
|
||||
flow = get_air_text_flow()
|
||||
raw = flow.ledger.find_by_collab_chat(chat_id=chat_id)
|
||||
if raw is None:
|
||||
return False, "", ""
|
||||
view = ticket_view(raw)
|
||||
return (
|
||||
True,
|
||||
ticket_no(raw),
|
||||
str(view.get("status") or ""),
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
return False, "", ""
|
||||
|
||||
# Handler 签名约定:只收 InboundMessage(出站/store 由 handler 自行取依赖)
|
||||
HandlerFn = Callable[[InboundMessage], None]
|
||||
|
||||
@@ -202,11 +250,301 @@ def _is_air_collab_room(message: InboundMessage) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _group_bot_text_is_dissolve(text: str) -> bool:
|
||||
"""群内「解散群」不要求带工单号;只做宽松识别,精确判断仍交给 handler。"""
|
||||
compact = "".join((text or "").split())
|
||||
return "解散" in compact and "群" in compact
|
||||
|
||||
|
||||
# handler 里「按人判不通过」的返回码:这些都是拿 sender 跟主账 sales_wecom_id / 岗位
|
||||
# 名单比字符串得出的结论。只要入站身份是加密 open_userid 且换不成明文,这个结论就
|
||||
# 不可信,必须允许会话存档(明文)那条补办,否则销售本人也会被一直拒。
|
||||
_IDENTITY_REJECT_PHASES = frozenset(
|
||||
{"not_sales", "not_airline", "not_product", "not_airline_or_product"}
|
||||
)
|
||||
|
||||
|
||||
def _sender_identity_untrusted(message: InboundMessage) -> bool:
|
||||
"""
|
||||
这条群入站的发送人身份是否不可信(加密 open_userid 且没换出明文)。
|
||||
|
||||
判定顺序:
|
||||
1. 归一阶段已明确标 `sender_identity_trusted=0` → 不可信;
|
||||
2. 否则看形态:`wo` 开头长 ID 说明这条还是加密值(归一关掉时也会走到这里)。
|
||||
明文 userid 一律可信,保持改动前行为。
|
||||
"""
|
||||
raw = message.raw or {}
|
||||
if str(raw.get("sender_identity_trusted") or "").strip() == "0":
|
||||
return True
|
||||
try:
|
||||
from agent.channel.wecom.open_userid import looks_like_open_userid
|
||||
|
||||
return looks_like_open_userid(message.sender_id)
|
||||
except Exception: # noqa: BLE001 - 判不出来就按可信处理,避免误放行存档
|
||||
return False
|
||||
|
||||
|
||||
def _allow_archive_retry_if_untrusted(
|
||||
message: InboundMessage, *, chat_id: str, raw_text: str, phase: str
|
||||
) -> None:
|
||||
"""
|
||||
AIBOT 那条因身份不可信而被拒时,撤销去重,让会话存档带着明文再办一遍。
|
||||
|
||||
为什么必须这样做(2026-11-19 真机 WO202611190016):
|
||||
- AIBOT 先到,sender 是 `wo...` 加密值 → 判 not_sales;
|
||||
- 存档晚 12~15 秒到,sender 是 `LuoXiaoHua` 明文,本来能办成;
|
||||
- 但 AIBOT 那条已把文字指纹写进去重,存档被 `archive_dup_ignore` 丢掉,
|
||||
销售于是只看到「只有负责该工单的销售可以确认成交状态」。
|
||||
只对「按人判不通过」的返回码放行:办成了(发过模板/改过状态)不能放行,
|
||||
否则同一句会被办两遍(2026-11-19 11:26 已经复现过双发模板)。
|
||||
"""
|
||||
if not chat_id or not raw_text:
|
||||
return
|
||||
if str(phase or "") not in _IDENTITY_REJECT_PHASES:
|
||||
return
|
||||
if not _sender_identity_untrusted(message):
|
||||
return
|
||||
from agent.redis_coord.group_bot import allow_archive_retry
|
||||
|
||||
allow_archive_retry(chat_id, raw_text)
|
||||
logger.info(
|
||||
"dispatch 身份不可信被拒,放行存档补办 chat=%s phase=%s", chat_id, phase
|
||||
)
|
||||
|
||||
|
||||
def _reply_group_need_work_order(message: InboundMessage) -> None:
|
||||
"""
|
||||
BOT 群 @ 了机器人却没带工单号、当前单也被打断:提示销售重新下达任务。
|
||||
|
||||
应用群不走这里(应用不回应群对话)。AIBOT 入站带 response_url/req_id,
|
||||
由桥回话;会话存档兜底则用流程客户端,`send_group_text` 仍会按群改走 BOT。
|
||||
"""
|
||||
from agent.policy import inquiry_copy as copy
|
||||
from agent.policy.sea_group_ops import send_group_text
|
||||
|
||||
chat_id = (message.chat_id or "").strip()
|
||||
source = str((message.raw or {}).get("source") or "").lower()
|
||||
if source in {"aibot", "aibot_bridge"}:
|
||||
from agent.channel.aibot.reply import AibotReplyClient
|
||||
|
||||
client = AibotReplyClient(
|
||||
str((message.raw or {}).get("response_url") or ""),
|
||||
callback_req_id=str((message.raw or {}).get("aibot_req_id") or ""),
|
||||
)
|
||||
else:
|
||||
from agent.policy.sea_text_flow import get_sea_text_flow
|
||||
|
||||
client = get_sea_text_flow().group_client()
|
||||
prompt = copy.air_need_work_order()
|
||||
send_group_text(client, chat_id, prompt)
|
||||
|
||||
|
||||
def resolve_handler(intent: str) -> Optional[HandlerFn]:
|
||||
"""查表;未知意图返回 None。"""
|
||||
return HANDLER_REGISTRY.get(intent)
|
||||
|
||||
|
||||
def _mark_explicit_attachment(message: InboundMessage) -> InboundMessage:
|
||||
"""
|
||||
给「明确 @ 过机器人」才进来的群附件打标记,供 handler 决定「必须回一句」。
|
||||
|
||||
为什么需要(2026-11-21 真机 WO 群):
|
||||
海运/陆运群的附件默认口径是「别人的附件只存档、不搭话」(2026-11-19 定的),
|
||||
但那是针对「群里随手丢文件」。若销售是先/后 @ 了机器人(本次指令窗口内),
|
||||
这条附件就是他明确要求办的事,处理完必须回一句,
|
||||
否则真机表现就是「发文件 + @机器人,BOT 一声不吭」。
|
||||
|
||||
实现:InboundMessage 是 frozen dataclass,用 replace 复制一份并在 raw 里加标记,
|
||||
不改原对象,也不引入新字段(raw 本来就是通道透传字段,序列化不受影响)。
|
||||
|
||||
副作用:无;纯内存复制。
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
raw = dict(message.raw or {})
|
||||
raw["at_burst_explicit"] = True
|
||||
return replace(message, raw=raw)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _group_attach_outbound(chat_id: str) -> Iterator[None]:
|
||||
"""
|
||||
群附件回执用哪个身份发:BOT 真在这个群就走机器人桥,否则走企微应用。
|
||||
|
||||
为什么必须按群判断(2026-11-21 真机):
|
||||
存档群附件原先一律 `AibotReplyClient("")`(机器人桥主动发言)。但
|
||||
「@会话存档机器人」这种群,AIBOT 根本没进群(bot_seen=False),桥主动发言
|
||||
被企微拒:`aibot send msg frequency limit exceeded`(84660)/
|
||||
`websocket request expired`,群里表现就是「发文件 + @机器人,BOT 一声不吭」。
|
||||
同一群的文字兜底走的是应用发群、是通的,所以附件回执也必须跟着走应用。
|
||||
|
||||
参数 chat_id:群 chat_id,用来判断 BOT 是否见于该群。
|
||||
副作用:只改当前线程的出站客户端(ContextVar)与「强制应用」标记,退出即还原。
|
||||
线程:入站处理线程内同步使用,不影响别的工单。
|
||||
"""
|
||||
from agent.redis_coord.group_bot import bot_seen
|
||||
|
||||
in_room = bot_seen(chat_id)
|
||||
from agent.policy.sea_group_ops import force_app_group_client, override_group_client
|
||||
|
||||
if in_room:
|
||||
from agent.channel.aibot.reply import AibotReplyClient
|
||||
|
||||
with override_group_client(AibotReplyClient("")):
|
||||
yield
|
||||
return
|
||||
# BOT 不在群:只能走应用发群;此时禁止被换成机器人桥(走桥必失败)。
|
||||
from agent.policy.sea_text_flow import get_sea_text_flow
|
||||
|
||||
with override_group_client(get_sea_text_flow().group_client()), force_app_group_client():
|
||||
yield
|
||||
|
||||
|
||||
def _replay_pending_media(chat_id: str, line: str) -> int:
|
||||
"""
|
||||
@BOT 一到,就把之前「窗口外先到」的群图片/附件补办一次。
|
||||
|
||||
为什么必须有这一步(2026-11-21 真机):
|
||||
企微群里 Excel/PDF/图片都不能被 @,销售实际习惯是「先发文件,再 @机器人」。
|
||||
只看「先 @ 后发」会把这类真业务整条静默丢掉(真机表现为 BOT 一声不吭)。
|
||||
缓冲内容存在 group_bot:pending_media,由 dispatch 在窗口外丢弃时写入。
|
||||
|
||||
返回:补办的条数(0 表示这次 @ 前面没有待归属材料)。
|
||||
副作用:逐条重放 handler(可能发群消息、写主账附件);单条失败不影响其它条。
|
||||
线程:只在入站处理线程里同步跑,和普通群消息同一条路径,不额外起线程。
|
||||
"""
|
||||
from agent.redis_coord.group_bot import bot_seen, drain_pending_media
|
||||
|
||||
entries = drain_pending_media(chat_id)
|
||||
if not entries:
|
||||
return 0
|
||||
from agent.channel.aibot.reply import AibotReplyClient
|
||||
from agent.policy.sea_group_ops import force_app_group_client, override_group_client
|
||||
|
||||
done = 0
|
||||
# 出站身份跟着群状态走:BOT 在群用桥主动发言,否则用应用发群(同 seat@ 兜底)。
|
||||
bot_in_room = bot_seen(chat_id)
|
||||
for entry in entries:
|
||||
try:
|
||||
msg = InboundMessage.from_dict(entry)
|
||||
except Exception: # noqa: BLE001 - 坏数据跳过,不能挡住后面那条指令
|
||||
logger.warning("dispatch 待归属附件反序列化失败 chat=%s", chat_id, exc_info=True)
|
||||
continue
|
||||
try:
|
||||
# 明确 @ 过才补办的附件:打标记让 handler 处理完必须回一句(不能静默存档)。
|
||||
msg = _mark_explicit_attachment(msg)
|
||||
if bot_in_room:
|
||||
with override_group_client(AibotReplyClient("")):
|
||||
phase = _seat_at_dispatch(msg, line)
|
||||
else:
|
||||
from agent.policy.sea_text_flow import get_sea_text_flow
|
||||
|
||||
with override_group_client(
|
||||
get_sea_text_flow().group_client()
|
||||
), force_app_group_client():
|
||||
phase = _seat_at_dispatch(msg, line)
|
||||
done += 1
|
||||
logger.info(
|
||||
"dispatch pending_media_replay chat=%s kind=%s phase=%s",
|
||||
chat_id,
|
||||
msg.msg_type,
|
||||
phase,
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("dispatch 待归属附件补办失败 chat=%s", chat_id)
|
||||
return done
|
||||
|
||||
|
||||
def _handle_seat_at_fallback(
|
||||
message: InboundMessage,
|
||||
*,
|
||||
chat_id: str,
|
||||
line: str,
|
||||
raw_text: str,
|
||||
wo_in_text: str,
|
||||
) -> str:
|
||||
"""
|
||||
@会话存档账号兜底唤醒(2026-11-19 产品口径)。
|
||||
|
||||
背景:
|
||||
- 企业微信智能机器人(智价通BOT)不能被接口拉进群,每个协同群都得人工拉一次;
|
||||
- 会话存档席位账号(群里显示「会话存档-机器人」)是通讯录成员,建群时自动进群,
|
||||
而且它本来就负责存档,所以 @ 它的文字一定会出现在存档里。
|
||||
|
||||
因此:存档听到「@会话存档账号」,就当作一次明确的任务指令交给 handler。
|
||||
出站通道按群状态二选一(2026-11-19 调整):
|
||||
- BOT 在群 ⇒ 用 BOT 身份回(桥主动发言),群里只有一套回话身份;
|
||||
- BOT 不在群 ⇒ 走企微应用 appchat/send。
|
||||
|
||||
门禁:
|
||||
- 已经 @ 了 BOT 的名字 ⇒ 交给 AIBOT 那条路,本函数不接(避免同一句办两遍);
|
||||
- BOT 在群时也允许 @席位 唤醒:AIBOT 只在自己被 @ 时收到回调,
|
||||
@席位 不会同时触发 BOT,所以不存在双回。
|
||||
|
||||
副作用:可能写当前单关联、调主账、发群消息;都在 handler 内,本函数不额外写状态。
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
from agent.policy.bot_name import strip_bot_mention
|
||||
from agent.redis_coord.group_bot import bot_seen, set_active_work_order
|
||||
|
||||
bot_in_room = bot_seen(chat_id)
|
||||
if wo_in_text:
|
||||
set_active_work_order(chat_id, wo_in_text)
|
||||
|
||||
# 把「@会话存档-机器人」从正文剥掉,避免账号名被当成品名/报价内容抽进字段。
|
||||
clean = strip_bot_mention(raw_text)
|
||||
if not clean:
|
||||
# 只 @ 了个账号、没有任何指令:不当任务,也不回话。
|
||||
logger.info("dispatch seat_at_empty_ignore chat=%s", chat_id)
|
||||
return "seat_at_empty_ignore"
|
||||
body = replace(message, content=clean) if clean != raw_text else message
|
||||
|
||||
from agent.policy.sea_group_ops import (
|
||||
force_app_group_client,
|
||||
override_group_client,
|
||||
)
|
||||
from agent.policy.sea_text_flow import get_sea_text_flow
|
||||
|
||||
app_client = get_sea_text_flow().group_client()
|
||||
try:
|
||||
if bot_in_room:
|
||||
# BOT 已在群:用 BOT 身份回,否则同一个群会出现两套回话身份。
|
||||
from agent.channel.aibot.reply import AibotReplyClient
|
||||
|
||||
with override_group_client(AibotReplyClient("")):
|
||||
phase = _seat_at_dispatch(body, line)
|
||||
else:
|
||||
# BOT 不在群:只能走应用发群;此时禁止被换成机器人桥(走桥必失败)。
|
||||
with override_group_client(app_client), force_app_group_client():
|
||||
phase = _seat_at_dispatch(body, line)
|
||||
except Exception:
|
||||
logger.exception("dispatch seat@ fallback 失败 chat=%s", chat_id)
|
||||
return "seat_at_fallback_error"
|
||||
logger.info(
|
||||
"dispatch seat@ fallback phase=%s chat=%s line=%s bot_in_room=%s",
|
||||
phase,
|
||||
chat_id,
|
||||
line,
|
||||
bot_in_room,
|
||||
)
|
||||
return "seat_at_fallback"
|
||||
|
||||
|
||||
def _seat_at_dispatch(message: InboundMessage, line: str) -> str:
|
||||
"""
|
||||
@席位 兜底:按业务线交给唯一 handler。
|
||||
|
||||
海运/陆运/多式走 group_collab;空运走 air_group_collab。
|
||||
单独抽函数是为了让「出站通道选择」与「业务分发」不搅在一起。
|
||||
"""
|
||||
if line in {"SEA", "LAND", "MULTI"}:
|
||||
return handle_group_collab(message)
|
||||
from agent.handlers.air_group_collab import handle_air_group
|
||||
|
||||
return handle_air_group(message)
|
||||
|
||||
|
||||
def dispatch_inbound(message: InboundMessage, decision: RouteDecision) -> str:
|
||||
"""
|
||||
按 RouteDecision 调用唯一 handler。
|
||||
@@ -228,36 +566,346 @@ def dispatch_inbound(message: InboundMessage, decision: RouteDecision) -> str:
|
||||
_wrap_card(message)
|
||||
return "card_action"
|
||||
source = str((message.raw or {}).get("source") or "").lower()
|
||||
kind = (message.msg_type or "text").lower()
|
||||
chat_id = (message.chat_id or "").strip()
|
||||
from agent.policy.inquiry_copy import extract_work_order_no
|
||||
|
||||
wo_in_text = extract_work_order_no(raw_text) if raw_text else ""
|
||||
from agent.redis_coord.group_bot import (
|
||||
bot_text_handled,
|
||||
clear_active_work_order,
|
||||
clear_at_burst,
|
||||
ensure_group_bot_line,
|
||||
get_active_work_order,
|
||||
group_bot_line,
|
||||
in_at_burst,
|
||||
is_group_bot,
|
||||
mark_at_burst,
|
||||
mark_bot_text_handled,
|
||||
set_active_work_order,
|
||||
)
|
||||
|
||||
# Bot 群标记:新群建群时写业务线;改造前的老群第一次收到 BOT 消息时按主账补齐。
|
||||
line = group_bot_line(chat_id)
|
||||
if source in {"aibot", "aibot_bridge"}:
|
||||
line = ensure_group_bot_line(chat_id)
|
||||
# 收到 AIBOT 回调 = 智价通BOT 确实在本群。
|
||||
# @会话存档账号的兜底唤醒只在「BOT 不在群」时生效(2026-11-19 产品口径),
|
||||
# 这个标记就是判断依据;Redis 只能短存,丢标记会让兜底多管一次,不致回错。
|
||||
try:
|
||||
from agent.redis_coord.group_bot import mark_bot_seen
|
||||
|
||||
mark_bot_seen(chat_id)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("dispatch 记 BOT 在群失败 chat=%s", chat_id, exc_info=True)
|
||||
if wo_in_text:
|
||||
# @BOT 且带工单号:恢复/切换本群当前单关联。
|
||||
set_active_work_order(chat_id, wo_in_text)
|
||||
if source in {"aibot", "aibot_bridge"} and (kind in {"", "text"} or raw_text):
|
||||
# 产品口径(2026-11-21):AIBOT 只在被 @ 时才收到群消息,
|
||||
# 所以收到即代表本群进入「@BOT 指令窗口」,后面的附件/图片算这次的材料。
|
||||
mark_at_burst(chat_id)
|
||||
# 先发文件、再 @BOT 的顺序:把缓冲区里的附件补办掉,再办这句指令。
|
||||
_replay_pending_media(chat_id, line)
|
||||
if raw_text:
|
||||
# 记下这条已由 AIBOT 办过:会话存档会旁听到同一句(空运必现),
|
||||
# 不记就会把同一份摘要/模板发两遍。
|
||||
mark_bot_text_handled(chat_id, raw_text)
|
||||
# 群里 @BOT 带图片:企微只推 mixed(文字+图片),图片是加密临时 URL,本链路不下载。
|
||||
# 只有图没有字时,handler 会把空正文当文字去要工单号,等于对着图片回话;
|
||||
# 产品口径(2026-11-19):这类整条静默,不入库也不提示。
|
||||
if kind in {"mixed", "image", "video", "file"} and not raw_text:
|
||||
logger.info(
|
||||
"dispatch aibot_group_media_ignore chat=%s kind=%s", chat_id, kind
|
||||
)
|
||||
return "aibot_group_media_only_ignore"
|
||||
if line in {"SEA", "LAND", "MULTI"}:
|
||||
if (
|
||||
kind in {"", "text"}
|
||||
and raw_text
|
||||
and not wo_in_text
|
||||
and not get_active_work_order(chat_id)
|
||||
and not _group_bot_text_is_dissolve(raw_text)
|
||||
):
|
||||
_reply_group_need_work_order(message)
|
||||
logger.info("dispatch group_need_work_order chat=%s line=%s", chat_id, line)
|
||||
return "group_need_work_order"
|
||||
from agent.channel.aibot.reply import AibotReplyClient
|
||||
from agent.policy.sea_group_ops import override_group_client
|
||||
|
||||
client = AibotReplyClient(
|
||||
str((message.raw or {}).get("response_url") or ""),
|
||||
callback_req_id=str((message.raw or {}).get("aibot_req_id") or ""),
|
||||
)
|
||||
with override_group_client(client):
|
||||
phase = handle_group_collab(
|
||||
_mark_explicit_attachment(message)
|
||||
if kind in {"file", "image", "video", "mixed"}
|
||||
else message
|
||||
)
|
||||
_allow_archive_retry_if_untrusted(
|
||||
message, chat_id=chat_id, raw_text=raw_text, phase=phase
|
||||
)
|
||||
logger.info(
|
||||
"dispatch group_collab bot phase=%s chat=%s line=%s",
|
||||
phase,
|
||||
chat_id,
|
||||
line,
|
||||
)
|
||||
return "group_collab"
|
||||
# 纯空运群仍走空运 handler;当前单被非 @ 文字打断后,没带号也先提示。
|
||||
if (
|
||||
kind in {"", "text"}
|
||||
and raw_text
|
||||
and not wo_in_text
|
||||
and not get_active_work_order(chat_id)
|
||||
and not _group_bot_text_is_dissolve(raw_text)
|
||||
):
|
||||
_reply_group_need_work_order(message)
|
||||
logger.info("dispatch air_need_work_order chat=%s", chat_id)
|
||||
return "group_need_work_order"
|
||||
from agent.handlers.air_group_collab import handle_air_group
|
||||
|
||||
phase = handle_air_group(message)
|
||||
logger.info("dispatch air_group phase=%s chat=%s", phase, message.chat_id)
|
||||
phase = handle_air_group(
|
||||
_mark_explicit_attachment(message)
|
||||
if kind in {"file", "image", "video", "mixed"}
|
||||
else message
|
||||
)
|
||||
_allow_archive_retry_if_untrusted(
|
||||
message, chat_id=chat_id, raw_text=raw_text, phase=phase
|
||||
)
|
||||
logger.info("dispatch air_group phase=%s chat=%s", phase, chat_id)
|
||||
return "air_group_collab"
|
||||
# 发文件不能 @:空运群附件靠会话存档听见。
|
||||
# 文字本应走 BOT;BOT 没推到时,存档里已经带 @询价小助手 的短句按空运补听。
|
||||
kind = (message.msg_type or "text").lower()
|
||||
air_room = _is_air_collab_room(message)
|
||||
if source == "wshoto_archive" and kind in {"text", ""}:
|
||||
from agent.routing.air_group_intent import is_missed_air_bot_at
|
||||
|
||||
if is_missed_air_bot_at(raw_text, room_already_air=air_room):
|
||||
from agent.handlers.air_group_collab import handle_air_group
|
||||
if source == "wshoto_archive":
|
||||
# 老群升级(2026-11-19 真机):本轮之前建的协同群是应用建的,Redis 里没有
|
||||
# BOT 标记,存档消息会落到下面「应用代答」的旧分支 —— 表现为「没 @ 也主动回话」。
|
||||
# 先按主账绑群关系补标记;补不上(不是本环境的群,如正服群被存档旁听)就整条不回应。
|
||||
if not is_group_bot(chat_id):
|
||||
try:
|
||||
promoted = ensure_group_bot_line(chat_id, fallback="")
|
||||
except Exception: # noqa: BLE001
|
||||
promoted = ""
|
||||
logger.exception("存档群补 BOT 标记失败 chat=%s", chat_id)
|
||||
if promoted:
|
||||
line = promoted
|
||||
if not is_group_bot(chat_id):
|
||||
# 应用只管拉群/解散群,不代答群对话;未绑定工单的群一律静默。
|
||||
logger.info("dispatch archive_unbound_ignore chat=%s", chat_id)
|
||||
return "archive_unbound_ignore"
|
||||
if is_group_bot(chat_id):
|
||||
if kind in {"text", ""}:
|
||||
from agent.policy.bot_name import (
|
||||
text_mentions_archive_seat,
|
||||
text_mentions_bot,
|
||||
)
|
||||
|
||||
phase = handle_air_group(message)
|
||||
logger.info("dispatch air_group archive_at phase=%s chat=%s", phase, message.chat_id)
|
||||
return "air_group_collab"
|
||||
if air_room:
|
||||
if kind in {"file", "image", "video"}:
|
||||
from agent.handlers.air_group_collab import handle_air_group
|
||||
bot_at = text_mentions_bot(raw_text)
|
||||
seat_at = text_mentions_archive_seat(raw_text)
|
||||
if bot_at or seat_at:
|
||||
# 产品口径(2026-11-21):存档听见明文的 @BOT(AIBOT 漏推时)也算
|
||||
# 进入「@BOT 指令窗口」,后面的附件/图片才算这次指令的材料。
|
||||
# @会话存档账号的兜底唤醒同样是明确指令,窗口一并开启,
|
||||
# 否则「喊醒后发文件」这种老用法会被窗口挡掉。
|
||||
mark_at_burst(chat_id)
|
||||
# 「先发文件、再 @机器人」顺序同样成立:把缓冲区里的附件先补办。
|
||||
_replay_pending_media(chat_id, line)
|
||||
# @会话存档账号兜底唤醒:智能机器人不能自动进群,
|
||||
# 这是唯一「不用人工拉 BOT 也能喊醒」的入口。
|
||||
if seat_at and not bot_at:
|
||||
return _handle_seat_at_fallback(
|
||||
message,
|
||||
chat_id=chat_id,
|
||||
line=line,
|
||||
raw_text=raw_text,
|
||||
wo_in_text=wo_in_text,
|
||||
)
|
||||
if not bot_at:
|
||||
# 产品口径(2026-11-20):「解散群」不要求 @BOT;存档听见就走解散。
|
||||
# 其它非 @BOT 文字仍断开当前单关联,且不回应。
|
||||
if _group_bot_text_is_dissolve(raw_text):
|
||||
if line in {"SEA", "LAND", "MULTI"}:
|
||||
from agent.channel.aibot.reply import AibotReplyClient
|
||||
from agent.policy.sea_group_ops import override_group_client
|
||||
|
||||
phase = handle_air_group(message)
|
||||
logger.info("dispatch air_group archive_file phase=%s chat=%s", phase, message.chat_id)
|
||||
return "air_group_collab"
|
||||
logger.info("dispatch 空运群存档文字忽略,须 @ BOT chat=%s", message.chat_id)
|
||||
return "air_archive_text_ignore"
|
||||
with override_group_client(AibotReplyClient("")):
|
||||
phase = handle_group_collab(message)
|
||||
logger.info(
|
||||
"dispatch group_dissolve_no_at archive phase=%s chat=%s",
|
||||
phase,
|
||||
chat_id,
|
||||
)
|
||||
return "group_collab"
|
||||
from agent.handlers.air_group_collab import handle_air_group
|
||||
|
||||
phase = handle_air_group(message)
|
||||
logger.info(
|
||||
"dispatch air_dissolve_no_at archive phase=%s chat=%s",
|
||||
phase,
|
||||
chat_id,
|
||||
)
|
||||
return "air_group_collab"
|
||||
if not bot_text_handled(chat_id, raw_text):
|
||||
# 普通文字(非 @BOT)=这次指令结束:之后的附件必须重新 @BOT。
|
||||
# 存档回声(AIBOT 刚办过的同一句)不算,否则 @ 完立刻被自己清掉。
|
||||
clear_at_burst(chat_id)
|
||||
# 指令已结束,还没被 @ 认领的旧附件也不能留到下一次 @ 再翻出来。
|
||||
from agent.redis_coord.group_bot import drain_pending_media
|
||||
|
||||
drain_pending_media(chat_id)
|
||||
clear_active_work_order(chat_id)
|
||||
logger.info("dispatch group_unbound chat=%s", chat_id)
|
||||
return "group_unbound_ignore"
|
||||
if wo_in_text:
|
||||
set_active_work_order(chat_id, wo_in_text)
|
||||
if line in {"SEA", "LAND", "MULTI"}:
|
||||
# 文字由 AIBOT 回调负责;存档只补附件,避免同一句回两遍。
|
||||
logger.info(
|
||||
"dispatch group_at_archive_ignore chat=%s line=%s", chat_id, line
|
||||
)
|
||||
return "group_at_archive_ignore"
|
||||
# 空运保留「BOT 漏推时存档补听」;当前单断了也先提示。
|
||||
if not wo_in_text and not get_active_work_order(chat_id):
|
||||
_reply_group_need_work_order(message)
|
||||
logger.info("dispatch air_need_work_order archive chat=%s", chat_id)
|
||||
return "group_need_work_order"
|
||||
elif line in {"SEA", "LAND", "MULTI"} and kind == "file":
|
||||
# 附件不能 @:BOT 群附件仍靠会话存档听见,出站改走机器人桥。
|
||||
# 产品口径(2026-11-21):只有「@BOT 指令窗口」内的附件才算这次询价材料;
|
||||
# 窗口外(同事随手丢的报价表、别人的对账单)一律静默,不回话也不识别。
|
||||
if not in_at_burst(chat_id):
|
||||
logger.info(
|
||||
"dispatch group_media_no_at_ignore kind=%s chat=%s line=%s",
|
||||
kind,
|
||||
chat_id,
|
||||
line,
|
||||
)
|
||||
# 产品口径(2026-11-21)「@ 前后」:先发文件、再 @BOT 也算这次指令。
|
||||
# 先静默不回,但把整条入站缓冲下来,等紧接着的 @BOT 认领补办。
|
||||
from agent.redis_coord.group_bot import add_pending_media
|
||||
|
||||
add_pending_media(chat_id, message.to_dict())
|
||||
return "group_media_no_at_ignore"
|
||||
with _group_attach_outbound(chat_id):
|
||||
phase = handle_group_collab(_mark_explicit_attachment(message))
|
||||
logger.info(
|
||||
"dispatch group_collab archive_file phase=%s chat=%s",
|
||||
phase,
|
||||
chat_id,
|
||||
)
|
||||
return "group_collab"
|
||||
elif line in {"SEA", "LAND", "MULTI"}:
|
||||
# 产品口径(2026-11-19 真机):图片/视频不是报价附件,没 @BOT 就不回应。
|
||||
# 以前这里会把图片当附件丢给 handler,回一句「群里只收 Excel 和 PDF」,
|
||||
# 群里随手发张图就被 BOT 搭话。
|
||||
# 2026-11-21 补充:@BOT 指令窗口内的图片属于「这次要发的材料」,
|
||||
# 交回 handler 按附件口径回应(明确告知只收 Excel/PDF),不能整条吞掉。
|
||||
if in_at_burst(chat_id):
|
||||
with _group_attach_outbound(chat_id):
|
||||
phase = handle_group_collab(_mark_explicit_attachment(message))
|
||||
logger.info(
|
||||
"dispatch group_collab archive_media_at phase=%s chat=%s kind=%s",
|
||||
phase,
|
||||
chat_id,
|
||||
kind,
|
||||
)
|
||||
return "group_collab"
|
||||
logger.info(
|
||||
"dispatch group_archive_media_ignore kind=%s chat=%s line=%s",
|
||||
kind,
|
||||
chat_id,
|
||||
line,
|
||||
)
|
||||
# 同上:先静默不回,但缓冲下来等紧接着的 @BOT 认领(图片也可能是这次的材料)。
|
||||
from agent.redis_coord.group_bot import add_pending_media
|
||||
|
||||
add_pending_media(chat_id, message.to_dict())
|
||||
return "group_archive_media_ignore"
|
||||
# 改造前的应用群:维持原逻辑(应用建群、应用发群、存档收报价)。
|
||||
air_room = _is_air_collab_room(message)
|
||||
# 会话存档是公司级数据:测服与正服共用同一企微公司,测服也会捞到正服群
|
||||
# (2026-11-19 11:10 测服对正服空运群连回三条「查不到工单」的事故)。
|
||||
archive_origin = str((message.raw or {}).get("wshoto_origin") or "").strip().lower()
|
||||
if kind in {"text", ""}:
|
||||
from agent.config import get_settings
|
||||
from agent.routing.air_group_intent import is_missed_air_bot_at
|
||||
|
||||
# 测服兜底:存档旁听 + 群没有在测服建单 ⇒ 不是测服的群,不 @ 也不回「查不到」。
|
||||
# 本机 AIBOT 回调(origin 非 archive)不受限,测服自己的协同群仍能补建工单。
|
||||
test_cross_env = (
|
||||
str(getattr(get_settings(), "ytd_env", "") or "").strip().lower() == "test"
|
||||
and archive_origin == "archive"
|
||||
and not air_room
|
||||
and not is_group_bot(chat_id)
|
||||
)
|
||||
missed_at = (
|
||||
is_missed_air_bot_at(raw_text, room_already_air=air_room) and not test_cross_env
|
||||
)
|
||||
if missed_at:
|
||||
# AIBOT 已经办过同一句:存档这条是旁听重复,不能再办一遍。
|
||||
if bot_text_handled(chat_id, raw_text):
|
||||
logger.info(
|
||||
"dispatch air_group archive_dup_ignore chat=%s wo=%s",
|
||||
chat_id,
|
||||
wo_in_text,
|
||||
)
|
||||
return "air_group_archive_dup_ignore"
|
||||
from agent.handlers.air_group_collab import handle_air_group
|
||||
|
||||
phase = handle_air_group(message)
|
||||
logger.info("dispatch air_group archive_at phase=%s chat=%s", phase, chat_id)
|
||||
return "air_group_collab"
|
||||
if air_room:
|
||||
if kind == "file":
|
||||
from agent.handlers.air_group_collab import handle_air_group
|
||||
|
||||
# 产品口径(2026-11-21):BOT 群里的附件必须处在「@BOT 指令窗口」内,
|
||||
# 否则按静默处理;老式应用群(没有 BOT)仍保持存档补收报价的老逻辑。
|
||||
if is_group_bot(chat_id) and not in_at_burst(chat_id):
|
||||
logger.info(
|
||||
"dispatch air_group media_no_at_ignore chat=%s kind=%s",
|
||||
chat_id,
|
||||
kind,
|
||||
)
|
||||
# 同上:空运 BOT 群里先发、后 @ 的附件也要能认领。
|
||||
from agent.redis_coord.group_bot import add_pending_media
|
||||
|
||||
add_pending_media(chat_id, message.to_dict())
|
||||
return "group_media_no_at_ignore"
|
||||
phase = handle_air_group(message)
|
||||
logger.info("dispatch air_group archive_file phase=%s chat=%s", phase, chat_id)
|
||||
return "air_group_collab"
|
||||
if kind in {"image", "video"}:
|
||||
# 图片/视频不是报价附件;没 @BOT 一律不回应(2026-11-19 真机)。
|
||||
logger.info(
|
||||
"dispatch air_group archive_media_ignore kind=%s chat=%s", kind, chat_id
|
||||
)
|
||||
return "air_archive_media_ignore"
|
||||
# 产品口径(2026-11-20):解散群不要求 @BOT。
|
||||
if kind in {"text", ""} and _group_bot_text_is_dissolve(raw_text):
|
||||
from agent.handlers.air_group_collab import handle_air_group
|
||||
|
||||
phase = handle_air_group(message)
|
||||
logger.info(
|
||||
"dispatch air_dissolve_no_at legacy_archive phase=%s chat=%s",
|
||||
phase,
|
||||
chat_id,
|
||||
)
|
||||
return "air_group_collab"
|
||||
logger.info("dispatch 空运群存档文字忽略,须 @ BOT chat=%s", chat_id)
|
||||
return "air_archive_text_ignore"
|
||||
phase = handle_group_collab(message)
|
||||
logger.info("dispatch group_collab phase=%s chat=%s", phase, chat_id)
|
||||
return "group_collab"
|
||||
|
||||
# BOT 群的应用回调只接卡片事件(上面已处理);其它群文字一律不回应。
|
||||
if is_group_bot(chat_id):
|
||||
if kind in {"text", ""}:
|
||||
clear_active_work_order(chat_id)
|
||||
logger.info("dispatch group_non_bot_ignore chat=%s source=%s", chat_id, source or "-")
|
||||
return "group_non_bot_ignore"
|
||||
phase = handle_group_collab(message)
|
||||
logger.info("dispatch group_collab phase=%s chat=%s", phase, message.chat_id)
|
||||
logger.info("dispatch group_collab phase=%s chat=%s", phase, chat_id)
|
||||
return "group_collab"
|
||||
|
||||
if not message.has_sender() and decision.intent != "reject_no_sender":
|
||||
@@ -309,12 +957,31 @@ def dispatch_inbound(message: InboundMessage, decision: RouteDecision) -> str:
|
||||
logger.info("dispatch 图片波次收字 sender=%s", message.sender_id)
|
||||
return "image_wave_follow_text"
|
||||
|
||||
# 未成交原因优先于模型给的「结束询价」。
|
||||
# 为什么(2026-11-17 正服 WO202611170021):销售点完「未成交」后,BOT 正在问
|
||||
# 「请补充未成交原因」,销售回「客户不要了」;DeepSeek A 把这句话听成
|
||||
# 「这单先不算了」,标了 end_inquiry。结束询价 handler 对「未成交」不会改六态,
|
||||
# 但会直接把私聊书签清掉,于是这句原因永远进不了主账,后台一直空着。
|
||||
# 产品口径是「未成交后下一句任意文字即原因」,所以这里把路由结论纠正回询价流程。
|
||||
# 明确口令「结束询价 / 终止询价」已在上面优先返回,不受本保护影响。
|
||||
if kind in {"text", ""} and decision.intent == "end_inquiry":
|
||||
wait = lost_reason_wait_state(message.sender_id)
|
||||
if wait.get("waiting"):
|
||||
logger.info(
|
||||
"dispatch 未成交原因优先:纠正结束询价路由 sender=%s wo=%s",
|
||||
message.sender_id,
|
||||
str(wait.get("work_order_no") or "-"),
|
||||
)
|
||||
handle_text_inquiry(message)
|
||||
return "ordinary_text_inquiry"
|
||||
|
||||
fn = resolve_handler(decision.intent)
|
||||
if fn is None:
|
||||
logger.warning("dispatch 未知意图 intent=%s → noop", decision.intent)
|
||||
_noop(message)
|
||||
return "unknown_intent"
|
||||
|
||||
|
||||
logger.info(
|
||||
"dispatch intent=%s sender=%s msg=%s wo=%s land_confirm=%s",
|
||||
decision.intent,
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
"""
|
||||
空运计费重:只做单位换算与算术投影,不做语义识别。
|
||||
|
||||
产品口径(2026-11-22 拍板):
|
||||
|
||||
体积重 = 体积(CBM)× 166.7(KG/CBM)
|
||||
计费重 = max(毛重, 体积重)
|
||||
|
||||
触发场景:TMS 没有匹配报价,航线人员在协同群用文字手工报价(如「USD11/kg」)。
|
||||
此时整票金额 = 单价 × 计费重,必须由本机按工单里的体积/毛重算出来,
|
||||
既要在群摘要里让销售看见,也要跟着报价版本进报价单。
|
||||
|
||||
为什么单独一个模块:
|
||||
- 三处都要用(群摘要、报价落库、TMS 缺失时的展示),写在某个 policy 里会被反向依赖;
|
||||
- 合同要求「尺寸原文不得在本地代码里解析成体积」,本模块只读已经结构化的
|
||||
「体积」/「毛重」字段,只做去单位与乘加,不认长宽高、不从品名猜货型。
|
||||
|
||||
副作用:无。纯函数,可在任意线程调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Optional
|
||||
|
||||
# 空运体积重系数(KG / CBM)。产品口径固定值,不从 TMS「比例」字段反推:
|
||||
# 比例(如 1:300)是货型/泡重说明,不等于本单计价系数。
|
||||
VOLUME_WEIGHT_DIVISOR = 166.7
|
||||
|
||||
# 允许出现在数字后面的单位后缀。去掉后只留数字,不做其它规范化。
|
||||
_UNIT_SUFFIX = re.compile(
|
||||
r"(?i)\s*(?:CBM|M3|立方米|立方|方|KGS?|KGM|公斤|千克|KG|吨)\s*$"
|
||||
)
|
||||
|
||||
# 「KM」之类不在上面,避免把别的东西吃掉。
|
||||
_TON_SUFFIX = re.compile(r"(?i)\s*(?:吨|TON|TONS)\s*$")
|
||||
|
||||
# 金额行常把币种写在数字前面(USD11.00);币种不是数量,读数字前先剥掉。
|
||||
_CCY_PREFIX = re.compile(r"(?i)^\s*(?:CNY|RMB|USD|EUR|HKD|JPY|GBP|人民币|美元|港币|欧元|日元)\s*")
|
||||
|
||||
# 计费重行的计价单位(大小写、斜杠、口语「每公斤」都认)。
|
||||
_KG_UNITS = frozenset({"KG", "KGS", "KGM", "公斤", "千克"})
|
||||
|
||||
|
||||
def parse_quantity(raw: Any) -> Optional[float]:
|
||||
"""
|
||||
把「1,200」「500KG」「3CBM」「1.5吨」读成数字。
|
||||
|
||||
只去单位、去千分位;读不出正数返回 None(0 也当没填,避免算出 0 计费重)。
|
||||
「吨」按 1000KG 换算,这是确定性的单位投影,不是猜测。
|
||||
"""
|
||||
if raw in (None, ""):
|
||||
return None
|
||||
text = str(raw).strip().replace(",", "").replace(",", "")
|
||||
if not text or text in {"-", "—", "-", "null", "None"}:
|
||||
return None
|
||||
text = _CCY_PREFIX.sub("", text)
|
||||
ton = False
|
||||
if _TON_SUFFIX.search(text):
|
||||
ton = True
|
||||
text = _UNIT_SUFFIX.sub("", text)
|
||||
text = _TON_SUFFIX.sub("", text).strip()
|
||||
# 允许数字后面还留着零星说明(如「500 左右」),只取开头的数字段。
|
||||
hit = re.match(r"(\d+(?:\.\d+)?)", text)
|
||||
if not hit:
|
||||
return None
|
||||
try:
|
||||
value = float(hit.group(1))
|
||||
except ValueError:
|
||||
return None
|
||||
if ton:
|
||||
value *= 1000.0
|
||||
return value if value > 0 else None
|
||||
|
||||
|
||||
def volume_weight_kg(volume_cbm: Optional[float]) -> Optional[float]:
|
||||
"""体积重(KG)= 体积(CBM)× 166.7;没有体积返回 None。"""
|
||||
if volume_cbm is None or volume_cbm <= 0:
|
||||
return None
|
||||
return volume_cbm * VOLUME_WEIGHT_DIVISOR
|
||||
|
||||
|
||||
def format_kg(value: Optional[float]) -> str:
|
||||
"""
|
||||
计费重的写法:最多两位小数,去掉无意义的尾零。
|
||||
|
||||
例:848.87 → "848.87";500.10 → "500.1";500.00 → "500"。
|
||||
报价单与群摘要共用这一种写法,避免同一个数在两个地方长得不一样。
|
||||
"""
|
||||
if value is None:
|
||||
return ""
|
||||
text = f"{float(value):.2f}".rstrip("0").rstrip(".")
|
||||
return text or "0"
|
||||
|
||||
|
||||
def with_kg_unit(raw: Any) -> str:
|
||||
"""计费重展示补 KG;原文已经带单位就原样,不重复写。"""
|
||||
text = str(raw or "").strip()
|
||||
if not text or text in {"-", "—", "-"}:
|
||||
return ""
|
||||
upper = text.upper()
|
||||
if any(upper.endswith(unit) for unit in ("KG", "KGS", "KGM", "公斤", "千克")):
|
||||
return text
|
||||
return f"{text}KG"
|
||||
|
||||
|
||||
# 航线在群里明说「计费重800KG/计费重量 800」:以他说的为准,本机不重算。
|
||||
_DECLARED_CHARGEABLE = re.compile(
|
||||
r"计费重(?:量)?\s*[::]?\s*(\d[\d,]*(?:\.\d+)?)\s*(?:KG|KGS|KGM|公斤|千克)?",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def harvest_declared_chargeable(text: str | None) -> Optional[float]:
|
||||
"""
|
||||
从人工报价原话里读航线点明的计费重。
|
||||
|
||||
只认紧跟「计费重/计费重量」的数字;「计费重按实重」这种没数字的返回 None,
|
||||
交给体积/毛重公式。副作用:无。
|
||||
"""
|
||||
hit = _DECLARED_CHARGEABLE.search(text or "")
|
||||
if not hit:
|
||||
return None
|
||||
try:
|
||||
value = float(hit.group(1).replace(",", ""))
|
||||
except ValueError:
|
||||
return None
|
||||
return value if value > 0 else None
|
||||
|
||||
|
||||
def compute_chargeable(facts: dict[str, Any] | None) -> Optional[dict[str, Any]]:
|
||||
"""
|
||||
按工单事实算一票的计费重。
|
||||
|
||||
取值顺序:
|
||||
1. 事实里已经写明「计费重/计费重量」→ 直接用(航线/模型给了就不覆盖);
|
||||
2. 否则按体积重与毛重取大;只有一边有值就用那一边。
|
||||
|
||||
返回 None 表示体积和毛重都没读到数字——这时不能编一个数出来。
|
||||
返回字段:
|
||||
gross_kg 毛重(KG),可能 None
|
||||
volume_cbm 体积(CBM),可能 None
|
||||
volume_weight_kg 体积重(KG),可能 None
|
||||
chargeable_kg 计费重(KG,正数)
|
||||
basis 内部依据:explicit=事实已写明;volume=体积重大;gross=毛重大。
|
||||
只用于排查与落库(chargeable_weight_basis),
|
||||
产品 2026-11-22 晚确定:对外文字不再展示依据括注。
|
||||
"""
|
||||
src = dict(facts or {})
|
||||
explicit = parse_quantity(src.get("计费重") or src.get("计费重量"))
|
||||
gross = parse_quantity(
|
||||
src.get("毛重")
|
||||
or src.get("重量")
|
||||
or src.get("重量(KG)")
|
||||
or src.get("weight_kg")
|
||||
or src.get("weightKg")
|
||||
)
|
||||
volume = parse_quantity(
|
||||
src.get("体积")
|
||||
or src.get("体积(CBM)")
|
||||
or src.get("volume_cbm")
|
||||
or src.get("volume")
|
||||
)
|
||||
vol_weight = volume_weight_kg(volume)
|
||||
if explicit is not None:
|
||||
return {
|
||||
"gross_kg": gross,
|
||||
"volume_cbm": volume,
|
||||
"volume_weight_kg": vol_weight,
|
||||
"chargeable_kg": explicit,
|
||||
"basis": "explicit",
|
||||
}
|
||||
candidates = [x for x in (gross, vol_weight) if x is not None]
|
||||
if not candidates:
|
||||
return None
|
||||
chargeable = max(candidates)
|
||||
# 两边相等时记「体积重」,只是内部依据(排查/落库用),不写进对外文字。
|
||||
basis = "volume" if vol_weight is not None and vol_weight >= (gross or 0) else "gross"
|
||||
return {
|
||||
"gross_kg": gross,
|
||||
"volume_cbm": volume,
|
||||
"volume_weight_kg": vol_weight,
|
||||
"chargeable_kg": chargeable,
|
||||
"basis": basis,
|
||||
}
|
||||
|
||||
|
||||
def _has_chargeable(quote: dict[str, Any]) -> bool:
|
||||
"""报价对象上是否已经有计费重(TMS 或航线明说的),有就不覆盖。"""
|
||||
for key in ("chargeableWeightKg", "chargeable_weight_kg", "chargeableWeight"):
|
||||
text = str(quote.get(key) or "").strip()
|
||||
if text and text not in {"-", "—", "-"}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_rows(raw: Any) -> tuple[list[dict[str, Any]], bool]:
|
||||
"""
|
||||
费用行统一成 list[dict]。
|
||||
|
||||
返回 (行, 原来是不是 JSON 字符串)。主账回读时 fee_rows 可能是文本,
|
||||
写回时要保持同一种形态,否则模板和卡片读法不一致。
|
||||
"""
|
||||
was_str = False
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
was_str = True
|
||||
except json.JSONDecodeError:
|
||||
return [], False
|
||||
if not isinstance(raw, list):
|
||||
return [], False
|
||||
return [dict(x) for x in raw if isinstance(x, dict)], was_str
|
||||
|
||||
|
||||
def _unit_token(raw: Any) -> str:
|
||||
"""计价单位归一:/KG、每公斤、KGS 都认,其它原样返回。"""
|
||||
text = str(raw or "").strip().upper()
|
||||
for sep in ("/", "每", " "):
|
||||
text = text.replace(sep, "")
|
||||
return text
|
||||
|
||||
|
||||
def _fill_kg_rows(
|
||||
rows: list[dict[str, Any]], chargeable_kg: float
|
||||
) -> int:
|
||||
"""
|
||||
把按 KG 报价、但没写数量的费用行补成「单价 × 计费重」。
|
||||
|
||||
为什么只补没写数量的:航线自己写了「800KG」就说明这票按 800 计,
|
||||
本机不能再按体积重改掉他的意思。
|
||||
副作用:原地改 rows;返回补了几行。
|
||||
"""
|
||||
filled = 0
|
||||
cw_text = format_kg(chargeable_kg)
|
||||
for row in rows:
|
||||
if _unit_token(row.get("unit") or row.get("unitName")) not in _KG_UNITS:
|
||||
continue
|
||||
qty = str(row.get("quantity") or row.get("chargeQuantity") or "").strip()
|
||||
if qty and qty not in {"-", "—", "-"}:
|
||||
continue
|
||||
unit_raw = row.get("unit_price") or row.get("unitPrice") or row.get("price")
|
||||
unit_price = parse_quantity(unit_raw)
|
||||
if unit_price is None:
|
||||
continue
|
||||
# 行金额已经是另一笔整票金额(航线自己算过),不能拿体积重改掉;
|
||||
# 只有「金额=单价」或没有金额时,才说明这只是单价。
|
||||
current_amount = parse_quantity(
|
||||
row.get("amount") or row.get("value") or row.get("salePrice")
|
||||
)
|
||||
if current_amount is not None and abs(current_amount - unit_price) > 1e-6:
|
||||
continue
|
||||
row["quantity"] = cw_text
|
||||
row["amount"] = format_kg(unit_price * chargeable_kg)
|
||||
filled += 1
|
||||
return filled
|
||||
|
||||
|
||||
def _sum_primary_currency(rows: list[dict[str, Any]], fallback_ccy: str = "") -> str:
|
||||
"""
|
||||
按合同重算合计:只加第一行币种,异币种留明细、不折算。
|
||||
|
||||
读不出金额的行(百分比费率等)跳过,不让「1%」把合计算成 0。
|
||||
"""
|
||||
primary = ""
|
||||
for row in rows:
|
||||
ccy = str(row.get("currency") or row.get("currencyCode") or "").strip().upper()
|
||||
if ccy:
|
||||
primary = "CNY" if ccy == "RMB" else ccy
|
||||
break
|
||||
if not primary:
|
||||
primary = str(fallback_ccy or "").strip().upper()
|
||||
total = 0.0
|
||||
has = False
|
||||
for row in rows:
|
||||
raw_amount = str(row.get("amount") or row.get("value") or row.get("salePrice") or "").strip()
|
||||
# 费率/税率是百分比,不是整票金额,不计入合计(合同:合计只加绝对金额)。
|
||||
if "%" in raw_amount or "%" in raw_amount:
|
||||
continue
|
||||
amount = parse_quantity(raw_amount)
|
||||
if amount is None:
|
||||
continue
|
||||
ccy = str(row.get("currency") or row.get("currencyCode") or primary).strip().upper()
|
||||
if ccy == "RMB":
|
||||
ccy = "CNY"
|
||||
if primary and ccy and ccy != primary:
|
||||
continue
|
||||
total += amount
|
||||
has = True
|
||||
if not has:
|
||||
return ""
|
||||
return format_kg(total)
|
||||
|
||||
|
||||
def apply_to_quote(
|
||||
quote: dict[str, Any] | None,
|
||||
facts: dict[str, Any] | None,
|
||||
*,
|
||||
business_line: str = "AIR",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
人工报价落库前补计费重:报价对象 + KG 费用行 + 合计一起补齐。
|
||||
|
||||
只对空运生效:
|
||||
- 海运拼柜按 CBM/重量计费、整柜按箱型,不套 166.7;
|
||||
- 陆运按车型/票,也不套空运体积重。
|
||||
|
||||
不覆盖已有计费重(TMS 带回的、航线明说的都优先);
|
||||
事实里体积和毛重都读不到时原样返回,绝不编数字。
|
||||
返回新 dict,入参不被修改。
|
||||
"""
|
||||
src = dict(quote or {})
|
||||
if business_line and business_line.strip().upper() != "AIR":
|
||||
return src
|
||||
if _has_chargeable(src):
|
||||
return src
|
||||
computed = compute_chargeable(facts)
|
||||
if computed is None:
|
||||
return src
|
||||
chargeable = float(computed["chargeable_kg"])
|
||||
out = dict(src)
|
||||
out["chargeableWeightKg"] = format_kg(chargeable)
|
||||
out["chargeable_weight_kg"] = format_kg(chargeable)
|
||||
if computed.get("volume_weight_kg") is not None:
|
||||
out["volumeWeightKg"] = format_kg(computed["volume_weight_kg"])
|
||||
if computed.get("gross_kg") is not None:
|
||||
out["grossWeightKg"] = format_kg(computed["gross_kg"])
|
||||
out["chargeable_weight_basis"] = str(computed.get("basis") or "")
|
||||
|
||||
raw = out.get("fee_rows") if out.get("fee_rows") not in (None, "") else out.get("fee_lines")
|
||||
rows, was_str = _parse_rows(raw)
|
||||
if rows:
|
||||
filled = _fill_kg_rows(rows, chargeable)
|
||||
if filled:
|
||||
if was_str:
|
||||
text = json.dumps(rows, ensure_ascii=False)
|
||||
out["fee_rows"] = text
|
||||
out["fee_lines"] = text
|
||||
else:
|
||||
out["fee_rows"] = rows
|
||||
out["fee_lines"] = list(rows)
|
||||
# 行金额刚被改成「单价×计费重」,合计必须跟着;否则群里看单价、
|
||||
# 后台却把单价当整票总价(旧缺陷:USD11 当成整票金额)。
|
||||
total = _sum_primary_currency(rows, str(out.get("currency") or ""))
|
||||
if total:
|
||||
out["total"] = total
|
||||
return out
|
||||
@@ -31,6 +31,7 @@ AIR_REQUIRED_FIELDS = (
|
||||
("报价日期", "报价日期"),
|
||||
)
|
||||
# 空运询价非必填:有值收下;贸易条款只记工单,不挡查价。
|
||||
# 客户名称(2026-11-22 产品新增):询价时填写,非必填,有值就落工单事实。
|
||||
# 尺寸/比例:有值才存;尺寸与体积分列(产品口径 A);比例出单写入报价单。
|
||||
AIR_OPTIONAL_FIELDS = (
|
||||
("起运港", "起运地"),
|
||||
@@ -39,6 +40,7 @@ AIR_OPTIONAL_FIELDS = (
|
||||
("提货地址", "提货地址"),
|
||||
("收货地址", "收货地址"),
|
||||
("贸易条款", "贸易条款"),
|
||||
("客户名称", "客户名称"),
|
||||
("added_services", "增值服务"),
|
||||
("尺寸", "尺寸"),
|
||||
("比例", "比例"),
|
||||
@@ -60,7 +62,44 @@ SEA_REQUIRED_FIELDS = (
|
||||
("运输分类", "运输分类"),
|
||||
("报价日期", "报价日期"),
|
||||
)
|
||||
# 海运非必填:提货地址、派送地址、客户名称。内部键沿用提货地址/收货地址(送货/派送同义),
|
||||
# 与空运、陆运共用同一套事实键;只有销售原话出现才保存,缺省不挡查价,
|
||||
# 禁止从起运港/目的港或「门到门」条款反推地址;客户名称同样禁止编造。
|
||||
SEA_OPTIONAL_FIELDS = (
|
||||
("提货地址", "提货地址"),
|
||||
("收货地址", "派送地址"),
|
||||
("客户名称", "客户名称"),
|
||||
)
|
||||
SEA_DISPLAY = {key: label for key, label in SEA_REQUIRED_FIELDS}
|
||||
SEA_DISPLAY.update({key: label for key, label in SEA_OPTIONAL_FIELDS})
|
||||
|
||||
# 「整柜或拼柜」里算拼柜的口语写法。销售侧常写拼箱、散货、LCL。
|
||||
# 注意:判断是「整柜 or 拼柜」这个值,不是字段名本身;含「整柜」不代表拼柜。
|
||||
_SEA_LCL_WORDS = ("拼柜", "拼箱", "散货", "lcl")
|
||||
# 「非拼柜 / 不拼柜 / 无需拼柜」是整柜口径,不能误判成拼柜把箱型箱量隐藏掉。
|
||||
_SEA_NOT_LCL = re.compile(r"(?:非|不|无需|不用|免)\s*拼")
|
||||
|
||||
|
||||
def is_sea_lcl(load: Any) -> bool:
|
||||
"""
|
||||
海运「整柜或拼柜」是否选了拼柜(散货/LCL)。
|
||||
|
||||
用途:拼柜按体积计费,承运人不再指定具体箱型,所以箱型箱量在拼柜下不适用
|
||||
—— 补问不列、核对卡不占行、群摘要不显示、TMS 查价不要求。
|
||||
判定只看销售原文:拼柜 / 拼箱 / 散货 / LCL;「非拼柜」「不拼柜」按整柜处理。
|
||||
未填时返回 False(还不知道,不隐藏)。
|
||||
"""
|
||||
text = str(load or "").strip().lower()
|
||||
if not text:
|
||||
return False
|
||||
# 模型偶尔把字段名本身当值返回(整柜或拼柜 / 整柜/拼柜):这是未定,不当拼柜。
|
||||
if text.replace(" ", "") in {"整柜或拼柜", "整柜/拼柜", "整柜拼柜"}:
|
||||
return False
|
||||
if _SEA_NOT_LCL.search(text):
|
||||
return False
|
||||
if "整柜" in text and not any(word in text for word in ("拼柜", "拼箱", "散货")):
|
||||
return False
|
||||
return any(word in text for word in _SEA_LCL_WORDS)
|
||||
|
||||
# 陆运销售侧名称:卡片写始发站/货物品名;内部仍用合同键起运港/品名。
|
||||
LAND_DISPLAY = {
|
||||
@@ -74,6 +113,7 @@ LAND_DISPLAY = {
|
||||
"体积": "体积(CBM)",
|
||||
"车型/数量": "车型/数量",
|
||||
"通关口岸": "通关口岸",
|
||||
"客户名称": "客户名称",
|
||||
"报价日期": "报价日期",
|
||||
}
|
||||
|
||||
@@ -91,47 +131,41 @@ LAND_COLLAB_DISPLAY = {
|
||||
"HS编码": "海关编码",
|
||||
}
|
||||
# 填写样例允许拉群的类型+线路 → 协同内部键(顺序与规格一致)。
|
||||
# 2026-11-22 产品口径:客户名称改到询价阶段填写(非必填),不再属于任何陆运协同项。
|
||||
_LAND_COLLAB_BY_PAIR: dict[tuple[str, str], tuple[str, ...]] = {
|
||||
("国内运输拼车", "国内长途/零担"): (
|
||||
"客户名称",
|
||||
"包装方式",
|
||||
"货值",
|
||||
"是否为危险品",
|
||||
),
|
||||
("国内运输拼车", "国内城配/拖车/打包"): (
|
||||
"客户名称",
|
||||
"包装方式",
|
||||
"货值",
|
||||
"是否为危险品",
|
||||
),
|
||||
("国内运输整车", "国内长途/零担"): (
|
||||
"客户名称",
|
||||
"货值",
|
||||
"包装方式",
|
||||
"是否为危险品",
|
||||
),
|
||||
("国内运输整车", "国内城配/拖车/打包"): (
|
||||
"客户名称",
|
||||
"货值",
|
||||
"包装方式",
|
||||
"是否为危险品",
|
||||
),
|
||||
("跨境集拼", "中港/中亚/中欧"): (
|
||||
"客户名称",
|
||||
"HS编码",
|
||||
"贸易条款",
|
||||
"包装方式",
|
||||
"是否为危险品",
|
||||
),
|
||||
("跨境集拼", "东南亚"): (
|
||||
"客户名称",
|
||||
"HS编码",
|
||||
"贸易条款",
|
||||
"包装方式",
|
||||
"是否为危险品",
|
||||
),
|
||||
("跨境整车", "中港/中亚/中欧"): (
|
||||
"客户名称",
|
||||
"HS编码",
|
||||
"贸易条款",
|
||||
"货值",
|
||||
@@ -139,7 +173,6 @@ _LAND_COLLAB_BY_PAIR: dict[tuple[str, str], tuple[str, ...]] = {
|
||||
"是否为危险品",
|
||||
),
|
||||
("跨境整车", "东南亚"): (
|
||||
"客户名称",
|
||||
"HS编码",
|
||||
"贸易条款",
|
||||
"货值",
|
||||
@@ -147,7 +180,6 @@ _LAND_COLLAB_BY_PAIR: dict[tuple[str, str], tuple[str, ...]] = {
|
||||
"是否为危险品",
|
||||
),
|
||||
("中港整车", "中港/中亚/中欧"): (
|
||||
"客户名称",
|
||||
"HS编码",
|
||||
"贸易条款",
|
||||
"货值",
|
||||
@@ -155,7 +187,6 @@ _LAND_COLLAB_BY_PAIR: dict[tuple[str, str], tuple[str, ...]] = {
|
||||
"是否为危险品",
|
||||
),
|
||||
("中港零担/集拼", "中港/中亚/中欧"): (
|
||||
"客户名称",
|
||||
"HS编码",
|
||||
"贸易条款",
|
||||
"包装方式",
|
||||
@@ -163,10 +194,11 @@ _LAND_COLLAB_BY_PAIR: dict[tuple[str, str], tuple[str, ...]] = {
|
||||
),
|
||||
}
|
||||
# 意图分类用:海运协同五项 ∪ 贸易条款(陆运跨境仍要)∪ 陆运协同键。
|
||||
# 客户名称已改为询价非必填,不再作为协同意图标签。
|
||||
ALL_COLLAB_KEYS = tuple(
|
||||
dict.fromkeys(
|
||||
list(SEA_COLLAB_FIELDS)
|
||||
+ ["贸易条款", "客户名称", "包装方式", "货值", "是否为危险品", "车型/数量"]
|
||||
+ ["贸易条款", "包装方式", "货值", "是否为危险品", "车型/数量"]
|
||||
)
|
||||
)
|
||||
|
||||
@@ -257,11 +289,19 @@ _ALIASES = {
|
||||
"提货地址": "提货地址",
|
||||
"收货地址": "收货地址",
|
||||
"送货地址": "收货地址",
|
||||
# 产品口语「海运提货地址/海运派送地址」与派送地址都走同一对内网键:
|
||||
# 提货地址仍是提货地址;派送/送货/海运派送都收成收货地址(空运/海运共用)。
|
||||
"派送地址": "收货地址",
|
||||
"海运提货地址": "提货地址",
|
||||
"海运派送地址": "收货地址",
|
||||
"贸易条款": "贸易条款",
|
||||
"货源地(非必填)": "货源地",
|
||||
"货好时间(非必填)": "货好时间",
|
||||
"提货地址(非必填)": "提货地址",
|
||||
"收货地址(非必填)": "收货地址",
|
||||
"派送地址(非必填)": "收货地址",
|
||||
"海运提货地址(非必填)": "提货地址",
|
||||
"海运派送地址(非必填)": "收货地址",
|
||||
"贸易条款(非必填)": "贸易条款",
|
||||
"起运港(非必填)": "起运港",
|
||||
"起运地(非必填)": "起运港",
|
||||
@@ -907,13 +947,22 @@ def _pricing_required_keys(
|
||||
|
||||
合同里偶有「车型数量」等别名键,这里折成 normalize_facts 后的内部键,
|
||||
避免销售已填「车型/数量」仍被判缺。
|
||||
|
||||
海运拼柜(散货/LCL):箱型箱量不适用,从必填里去掉,不挡查价、不进补问。
|
||||
"""
|
||||
_ = facts
|
||||
line = (business_line or "").strip().upper()
|
||||
pricing = contract.get("pricing_required") or {}
|
||||
raw: list[str] = []
|
||||
if line == "SEA":
|
||||
# 合同 always 为主;代码常量再并一刀,避免合同漏「贸易条款/运输分类」时
|
||||
# 补问少项(正服:海运补问只有 7 项、缺运输分类)。
|
||||
raw = list((pricing.get("SEA") or {}).get("always") or [])
|
||||
for key, _label in SEA_REQUIRED_FIELDS:
|
||||
if key != "报价日期" and key not in raw:
|
||||
raw.append(key)
|
||||
# 拼柜不指定箱型:隐藏箱型箱量(产品口径 2026-11-22)。
|
||||
if is_sea_lcl((facts or {}).get("整柜或拼柜")):
|
||||
raw = [k for k in raw if k != "箱型箱量"]
|
||||
elif line == "AIR":
|
||||
raw = list((pricing.get("AIR") or {}).get("always") or [])
|
||||
# 空运选填键不得进首次查价必填:合同与 AIR_OPTIONAL_FIELDS 对齐,避免再逼销售补起运地。
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
"""
|
||||
陆运报价附加条件:未含税 / 含0税 / 未含燃油 / 含燃油费。
|
||||
|
||||
本文件职责(产品 2026-11-22 口径):
|
||||
1. 未含税N% —— 税率写 N%,运输费不动,备注「未含税N%」;
|
||||
2. 未含税 —— 税率留空,运输费不动,不加备注;
|
||||
3. 含0税 —— 税率写 0,运输费不动,备注「含0税」;
|
||||
4. 未含燃油N% —— 燃油费率写 N%,主运费 ×(1+N%),备注「未含燃油N%」;
|
||||
5. 含燃油费N% —— 燃油费率写 N%,主运费不乘,备注「含燃油费N%」。
|
||||
|
||||
为什么单独成模块:
|
||||
- 这五句是陆运产品报价的口语条件,解析、金额换算、备注口径必须一处定义;
|
||||
智能体抽字段(extract_text)和挂段(sea_group_ops)都只调这里,禁止各写一份。
|
||||
- 「未含燃油」的乘法只作用于**主运费**(车型价 / 分档单价 / 运输费、陆运费、运费),
|
||||
提货、送货、报关、过境等杂费不乘;否则客户会被多收一段杂费的燃油。
|
||||
- 模板本轮不改,条件备注走现有 remark 字段;跨境整车没有备注列,
|
||||
由主账出单时追加到模板底部「备注事项」。
|
||||
|
||||
线程:纯函数,无共享可变状态,可在 Worker 槽并发调用。
|
||||
副作用:`apply_to_quote` 会原地修改传入的报价 dict(只改本次入参,不落库)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
# 条件代码:解析结果和日志都用这几个常量,禁止在调用方再写字符串字面量。
|
||||
UNTAXED_RATE = "UNTAXED_RATE" # 未含税N%
|
||||
UNTAXED_BLANK = "UNTAXED_BLANK" # 未含税(无点数)
|
||||
ZERO_TAX = "ZERO_TAX" # 含0税
|
||||
FUEL_EXCLUDED = "FUEL_EXCLUDED" # 未含燃油N%(运费要乘)
|
||||
FUEL_INCLUDED = "FUEL_INCLUDED" # 含燃油费N%(运费不乘)
|
||||
|
||||
# 全角数字/百分号先在入口归一,正则只写半角;否则「未含税13%」会漏。
|
||||
_RE_FUEL_EXCLUDED = re.compile(
|
||||
r"未\s*含\s*燃油(?:附加)?费?\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?"
|
||||
)
|
||||
# 「含燃油费13%」与「未含燃油13%」只差一个字:先匹配未含,命中即返回,
|
||||
# 这里再要求前面不是「未」,避免同句被两种条件同时吃掉。
|
||||
_RE_FUEL_INCLUDED = re.compile(
|
||||
r"(?<!未)含\s*燃油(?:附加)?费?\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?"
|
||||
)
|
||||
_RE_UNTAXED_RATE = re.compile(
|
||||
r"未\s*含\s*税\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?"
|
||||
)
|
||||
# 只写「未含税」不带点数:税率必须留空,禁止退化成 0。
|
||||
_RE_UNTAXED = re.compile(r"未\s*含\s*税(?!\s*[::=]?\s*\d)")
|
||||
_RE_ZERO_TAX = re.compile(r"含\s*0\s*(?:点)?\s*税")
|
||||
|
||||
# 剥条件句用:比识别正则更宽松,连同后面的点数一起拿掉,
|
||||
# 防止「含燃油费13%」被费用行正则当成费目「含燃油费:13」。
|
||||
_RE_STRIP_FUEL = re.compile(
|
||||
r"(?:未\s*含\s*燃油|(?<!未)含\s*燃油)(?:附加)?费?\s*[::=]?\s*\d+(?:\.\d+)?\s*%?"
|
||||
)
|
||||
_RE_STRIP_TAX = re.compile(
|
||||
r"未\s*含\s*税(?:\s*[::=]?\s*\d+(?:\.\d+)?\s*%?)?"
|
||||
)
|
||||
_RE_STRIP_ZERO_TAX = re.compile(r"含\s*0\s*(?:点)?\s*税")
|
||||
|
||||
# 主运费费目:只有这些才乘燃油;含提货/送货/报关等杂费词的一律排除。
|
||||
_MAIN_FREIGHT_WORDS = ("运输费", "陆运费", "运费", "干线费", "拖车费", "车费")
|
||||
_EXTRA_FEE_WORDS = (
|
||||
"提货",
|
||||
"送货",
|
||||
"派送",
|
||||
"报关",
|
||||
"过境",
|
||||
"保险",
|
||||
"仓储",
|
||||
"装卸",
|
||||
"搬运",
|
||||
"燃油",
|
||||
"附加",
|
||||
"税",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LandQuoteCondition:
|
||||
"""
|
||||
一条陆运报价条件(税与燃油可同时存在)。
|
||||
|
||||
code:主条件代码(有燃油取燃油,否则取税),供日志/测试识别;
|
||||
tax_rate/fuel_rate 是展示串(如 "13%"、"0");
|
||||
remark:写进报价单备注的内容(未含税无点数时为空串;两项都有时用「;」拼接);
|
||||
multiply_fuel:只有「未含燃油N%」为 True;
|
||||
clear_tax:写了「未含税」但没点数,必须把税率留空。
|
||||
"""
|
||||
|
||||
code: str
|
||||
tax_rate: str = ""
|
||||
fuel_rate: str = ""
|
||||
remark: str = ""
|
||||
multiply_fuel: bool = False
|
||||
clear_tax: bool = False
|
||||
|
||||
|
||||
def _normalize(text: str) -> str:
|
||||
"""全角转半角、去多余空白;不做金额/城市归一。"""
|
||||
return unicodedata.normalize("NFKC", text or "")
|
||||
|
||||
|
||||
def _rate_text(raw: str) -> str:
|
||||
"""
|
||||
点数展示:去掉无意义的小数零,统一带 %。
|
||||
|
||||
例:13 → 13%;13.0 → 13%;13.50 → 13.5%。
|
||||
"""
|
||||
try:
|
||||
val = Decimal(str(raw).strip())
|
||||
except (InvalidOperation, AttributeError):
|
||||
return ""
|
||||
text = format(val.normalize(), "f")
|
||||
return f"{text}%"
|
||||
|
||||
|
||||
def _parse_fuel_condition(src: str) -> LandQuoteCondition | None:
|
||||
"""只解析燃油条件:未含燃油N%(要乘)/ 含燃油费N%(不乘)。"""
|
||||
fuel_excluded = _RE_FUEL_EXCLUDED.search(src)
|
||||
if fuel_excluded:
|
||||
rate = _rate_text(fuel_excluded.group("rate"))
|
||||
if rate:
|
||||
return LandQuoteCondition(
|
||||
code=FUEL_EXCLUDED,
|
||||
fuel_rate=rate,
|
||||
remark=f"未含燃油{rate}",
|
||||
multiply_fuel=True,
|
||||
)
|
||||
fuel_included = _RE_FUEL_INCLUDED.search(src)
|
||||
if fuel_included:
|
||||
rate = _rate_text(fuel_included.group("rate"))
|
||||
if rate:
|
||||
return LandQuoteCondition(
|
||||
code=FUEL_INCLUDED,
|
||||
fuel_rate=rate,
|
||||
remark=f"含燃油费{rate}",
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _parse_tax_condition(src: str) -> LandQuoteCondition | None:
|
||||
"""只解析税条件:未含税N% / 含0税 / 未含税(无点数)。"""
|
||||
untaxed_rate = _RE_UNTAXED_RATE.search(src)
|
||||
if untaxed_rate:
|
||||
rate = _rate_text(untaxed_rate.group("rate"))
|
||||
if rate:
|
||||
return LandQuoteCondition(
|
||||
code=UNTAXED_RATE,
|
||||
tax_rate=rate,
|
||||
remark=f"未含税{rate}",
|
||||
)
|
||||
zero_tax = _RE_ZERO_TAX.search(src)
|
||||
if zero_tax:
|
||||
# 产品写「含0点税」就保留原话(历史摘要/模板备注一直这么显示);
|
||||
# 写「含0税」时按本轮口径统一成「含0税」。两种都表示税率 0。
|
||||
raw = re.sub(r"\s+", "", zero_tax.group(0))
|
||||
remark = "含0点税" if "点" in raw else "含0税"
|
||||
return LandQuoteCondition(code=ZERO_TAX, tax_rate="0", remark=remark)
|
||||
if _RE_UNTAXED.search(src):
|
||||
# 产品口径:未含税但不给点数 → 税率留空、备注也留空。
|
||||
return LandQuoteCondition(code=UNTAXED_BLANK, clear_tax=True)
|
||||
return None
|
||||
|
||||
|
||||
def parse_land_quote_condition(text: str) -> LandQuoteCondition | None:
|
||||
"""
|
||||
从产品报价原话里识别陆运附加条件(税与燃油可同时出现)。
|
||||
|
||||
为什么两项分开解析再合并:
|
||||
- 产品可能写「运输费3200,未含税13%,未含燃油5%」,税率和燃油都要出单;
|
||||
只取一句会丢掉另一项,模板侧栏就会空一格。
|
||||
- 备注按「税在前、燃油在后」用「;」拼接,销售在群里一眼能读完。
|
||||
|
||||
参数 text:产品报价原话(可含 @机器人、工单号)。
|
||||
返回:条件对象;五项都没出现时返回 None。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
src = _normalize(text)
|
||||
if not src:
|
||||
return None
|
||||
fuel = _parse_fuel_condition(src)
|
||||
tax = _parse_tax_condition(src)
|
||||
if fuel is None and tax is None:
|
||||
return None
|
||||
primary = fuel or tax
|
||||
remarks = [item.remark for item in (tax, fuel) if item and item.remark]
|
||||
return LandQuoteCondition(
|
||||
code=primary.code if primary else "",
|
||||
tax_rate=tax.tax_rate if tax else "",
|
||||
fuel_rate=fuel.fuel_rate if fuel else "",
|
||||
remark=";".join(remarks),
|
||||
multiply_fuel=bool(fuel and fuel.multiply_fuel),
|
||||
clear_tax=bool(tax and tax.code == UNTAXED_BLANK),
|
||||
)
|
||||
|
||||
|
||||
def strip_land_quote_condition(text: str) -> str:
|
||||
"""
|
||||
去掉条件短语后再抽金额/费用行。
|
||||
|
||||
为什么必须剥:
|
||||
- 「含燃油费13%」会被费用行正则认成费目「含燃油费」+ 金额 13;
|
||||
- 「未含税」里的「含税」会被旧备注正则当成含税备注;
|
||||
- 「13%」若留在正文,可能被金额回退抓成运费。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
cleaned = _normalize(text)
|
||||
cleaned = _RE_STRIP_FUEL.sub(" ", cleaned)
|
||||
cleaned = _RE_STRIP_TAX.sub(" ", cleaned)
|
||||
cleaned = _RE_STRIP_ZERO_TAX.sub(" ", cleaned)
|
||||
return cleaned
|
||||
|
||||
|
||||
def is_main_transport_fee(name: str) -> bool:
|
||||
"""
|
||||
这条费目是不是「主运费」(燃油乘法的对象)。
|
||||
|
||||
主运费:运输费/陆运费/运费/干线费/拖车费/车费;
|
||||
杂费:提货、送货、报关、过境、保险、仓储、装卸、搬运、燃油附加、税费 —— 不乘。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
label = _normalize(name).strip()
|
||||
if not label:
|
||||
return False
|
||||
if any(word in label for word in _EXTRA_FEE_WORDS):
|
||||
return False
|
||||
return any(word in label for word in _MAIN_FREIGHT_WORDS)
|
||||
|
||||
|
||||
def _scale_amount(raw: Any, factor: Decimal) -> str:
|
||||
"""
|
||||
金额乘系数,保留两位小数并去掉无意义的零。
|
||||
|
||||
认不出数字(「面议」「-」「含税」)就原样返回,禁止把非金额写成 0。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
text = str(raw or "").strip().replace(",", "")
|
||||
if not text:
|
||||
return str(raw or "")
|
||||
try:
|
||||
val = Decimal(text) * factor
|
||||
except (InvalidOperation, ValueError):
|
||||
return text
|
||||
val = val.quantize(Decimal("0.01"))
|
||||
out = format(val, "f")
|
||||
if "." in out:
|
||||
out = out.rstrip("0").rstrip(".")
|
||||
return out or "0"
|
||||
|
||||
|
||||
def _as_decimal(raw: Any) -> Decimal | None:
|
||||
"""把金额串转 Decimal;失败返回 None(不猜)。"""
|
||||
text = str(raw or "").strip().replace(",", "")
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return Decimal(text)
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _scale_rows(
|
||||
rows: Any,
|
||||
factor: Decimal,
|
||||
*,
|
||||
only_main: bool,
|
||||
delta_currency: str = "",
|
||||
) -> Decimal:
|
||||
"""
|
||||
就地缩放费用行,返回主运费相对原值的增量(用于修正合计)。
|
||||
|
||||
only_main=True:只乘运输费;False:所有非费率行都乘(车型价明细用)。
|
||||
带 % 的费率行永远不乘。
|
||||
delta_currency:合计只统计该币种的行(空行币种视为同币);多币种报价
|
||||
的合计本来就是主币种小计,不能把异币种增量加进去。
|
||||
"""
|
||||
delta = Decimal("0")
|
||||
target_ccy = str(delta_currency or "").strip().upper()
|
||||
if not isinstance(rows, list):
|
||||
return delta
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
amount = str(row.get("amount") or "")
|
||||
if "%" in amount or "%" in str(row.get("unit") or ""):
|
||||
continue
|
||||
if only_main and not is_main_transport_fee(str(row.get("name") or "")):
|
||||
continue
|
||||
row_ccy = str(row.get("currency") or "").strip().upper()
|
||||
count_delta = not target_ccy or not row_ccy or row_ccy == target_ccy
|
||||
before = _as_decimal(amount)
|
||||
if before is None:
|
||||
continue
|
||||
after_text = _scale_amount(amount, factor)
|
||||
after = _as_decimal(after_text)
|
||||
if after is None:
|
||||
continue
|
||||
row["amount"] = after_text
|
||||
if str(row.get("unit_price") or "").strip():
|
||||
row["unit_price"] = _scale_amount(row.get("unit_price"), factor)
|
||||
if count_delta:
|
||||
delta += after - before
|
||||
return delta
|
||||
|
||||
|
||||
def apply_to_quote(quote: dict[str, Any], condition: LandQuoteCondition | None) -> dict[str, Any]:
|
||||
"""
|
||||
把条件写进报价对象:税率/燃油费率/备注,并按需乘主运费。
|
||||
|
||||
写入键同时给 snake_case 和 camelCase,主账与群摘要都能读到。
|
||||
「未含燃油」的乘法范围:
|
||||
* 车型价 vehicleRates / vehicle_rates(全是主运费);
|
||||
* 分档单价 weightPrices[].price 与 price_per_kg;
|
||||
* 费用行里 is_main_transport_fee 命中的行(运输费/陆运费/运费…)。
|
||||
合计修正:
|
||||
* 有车型价/分档价:合计取调整后的第一档(与产品「展示取第一档」一致);
|
||||
* 只有费用行:在原合计上加上主运费增量,提货/报关等杂费不参与乘法。
|
||||
参数 quote:本次入参报价 dict,会被原地修改。
|
||||
返回:同一个 dict,便于调用方链式返回。
|
||||
副作用:改 quote 及其 fee_rows/vehicleRates/weightPrices。线程:调用方各自持有报价副本。
|
||||
"""
|
||||
if not isinstance(quote, dict) or condition is None:
|
||||
return quote
|
||||
|
||||
rate = str(condition.tax_rate or "").strip()
|
||||
if rate:
|
||||
quote["tax_rate"] = rate
|
||||
quote["taxRate"] = rate
|
||||
elif condition.clear_tax:
|
||||
# 未含税无点数:税率必须空着,清掉同句其它规则误抽的税率。
|
||||
quote.pop("tax_rate", None)
|
||||
quote.pop("taxRate", None)
|
||||
|
||||
fuel = str(condition.fuel_rate or "").strip()
|
||||
if fuel:
|
||||
quote["fuel_surcharge_rate"] = fuel
|
||||
quote["fuelSurchargeRate"] = fuel
|
||||
|
||||
# 未含税无点数的备注就是空:不新增,也不抹掉同句里真正单独的「备注:…」。
|
||||
if condition.remark:
|
||||
quote["remark"] = condition.remark
|
||||
_stamp_remark_on_fee_rows(quote.get("fee_rows"), condition.remark)
|
||||
|
||||
if condition.multiply_fuel and fuel:
|
||||
try:
|
||||
factor = Decimal("1") + Decimal(fuel.rstrip("%")) / Decimal("100")
|
||||
except (InvalidOperation, ValueError):
|
||||
factor = Decimal("1")
|
||||
if factor != Decimal("1"):
|
||||
_multiply_main_freight(quote, factor)
|
||||
return quote
|
||||
|
||||
|
||||
def _stamp_remark_on_fee_rows(rows: Any, remark: str) -> None:
|
||||
"""
|
||||
条件备注优先挂到主运费行,其次才挂第一条非费率行。
|
||||
|
||||
为什么优先主运费:跨境整车无 landSegments 时,主账用「运输费」行拼路线行,
|
||||
路线行的 remark 直接读这一行;挂到提货费/报关费上,底部备注会读不到。
|
||||
副作用:改 rows 里的 dict。
|
||||
"""
|
||||
if not isinstance(rows, list):
|
||||
return
|
||||
fallback = None
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
if "%" in str(row.get("amount") or ""):
|
||||
continue
|
||||
if fallback is None:
|
||||
fallback = row
|
||||
if is_main_transport_fee(str(row.get("name") or "")):
|
||||
row["remark"] = remark
|
||||
return
|
||||
if fallback is not None:
|
||||
fallback["remark"] = remark
|
||||
|
||||
|
||||
def _multiply_main_freight(quote: dict[str, Any], factor: Decimal) -> None:
|
||||
"""
|
||||
未含燃油:乘主运费并修正展示合计。
|
||||
|
||||
先算费用行增量,再处理车型/分档价;顺序不影响结果,因为两条路径互斥:
|
||||
多车型价时 fee_rows 只有一行「陆运费」摘要,分档价时 fee_rows 是档位明细。
|
||||
"""
|
||||
total_before = _as_decimal(quote.get("total"))
|
||||
# 分档价的 fee_rows 是「2-500KG / 500KG以上」档位明细,费目名不含「运费」,
|
||||
# 按主运费规则会漏乘;这里先按 weightPrices 判断,档位价与顶层价必须同乘。
|
||||
tiers = quote.get("weightPrices")
|
||||
if isinstance(tiers, list) and tiers:
|
||||
_scale_rows(quote.get("fee_rows"), factor, only_main=False)
|
||||
fee_lines = quote.get("fee_lines")
|
||||
if isinstance(fee_lines, list) and fee_lines is not quote.get("fee_rows"):
|
||||
same_objects = bool(fee_lines) and fee_lines[0] is (quote.get("fee_rows") or [None])[0]
|
||||
if not same_objects:
|
||||
_scale_rows(fee_lines, factor, only_main=False)
|
||||
for tier in tiers:
|
||||
if isinstance(tier, dict) and str(tier.get("price") or "").strip():
|
||||
tier["price"] = _scale_amount(tier.get("price"), factor)
|
||||
first_tier = tiers[0] if isinstance(tiers[0], dict) else {}
|
||||
first = str(first_tier.get("price") or "").strip()
|
||||
if first:
|
||||
quote["total"] = first
|
||||
quote["price_per_kg"] = first
|
||||
return
|
||||
|
||||
delta = _scale_rows(
|
||||
quote.get("fee_rows"),
|
||||
factor,
|
||||
only_main=True,
|
||||
delta_currency=str(quote.get("currency") or ""),
|
||||
)
|
||||
# fee_lines 常与 fee_rows 是同一批 dict;若被复制成两份,再乘一次会翻倍。
|
||||
fee_lines = quote.get("fee_lines")
|
||||
if isinstance(fee_lines, list) and fee_lines is not quote.get("fee_rows"):
|
||||
same_objects = bool(fee_lines) and fee_lines[0] is (quote.get("fee_rows") or [None])[0]
|
||||
if not same_objects:
|
||||
delta += _scale_rows(
|
||||
fee_lines,
|
||||
factor,
|
||||
only_main=True,
|
||||
delta_currency=str(quote.get("currency") or ""),
|
||||
)
|
||||
|
||||
rates = quote.get("vehicleRates") or quote.get("vehicle_rates")
|
||||
if isinstance(rates, dict) and rates:
|
||||
scaled = {
|
||||
str(key): _scale_amount(val, factor)
|
||||
for key, val in rates.items()
|
||||
if str(key).strip()
|
||||
}
|
||||
quote["vehicleRates"] = dict(scaled)
|
||||
quote["vehicle_rates"] = dict(scaled)
|
||||
# 车型价明细也一起乘,群摘要「车型价」才和合计一致。
|
||||
_scale_rows(quote.get("vehicle_fee_rows"), factor, only_main=False)
|
||||
first = next(iter(scaled.values()), "")
|
||||
if first:
|
||||
quote["total"] = first
|
||||
return
|
||||
|
||||
if total_before is not None:
|
||||
quote["total"] = _scale_amount(total_before + delta, Decimal("1"))
|
||||
@@ -9,6 +9,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -160,6 +161,98 @@ def _fee_name(item: dict[str, Any] | None) -> str:
|
||||
).strip()
|
||||
|
||||
|
||||
def is_port_handling_fee(item: dict[str, Any] | None) -> bool:
|
||||
"""
|
||||
是否「口岸海关监管费 + 接驳费」这一项(东南亚整车境外段的固定费目)。
|
||||
|
||||
为什么按名字认:TMS 陆运费目没有单独字段区分这类费,模板行名是
|
||||
「口岸海关监管费+接驳费」,主账 fee_lines 也原样保留 feeName。
|
||||
只认「接驳」或「口岸 + 监管」,避免把运输费、提货费、报关费算进来。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
compact = str(_fee_name(item) or "").replace(" ", "")
|
||||
if not compact:
|
||||
return False
|
||||
if "接驳" in compact:
|
||||
return True
|
||||
return "口岸" in compact and "监管" in compact
|
||||
|
||||
|
||||
def _all_named_fee_rows(quote: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
"""
|
||||
合并 fee_lines 与 feeItems 两处 TMS 费目,按「费名 + 金额」去重。
|
||||
|
||||
为什么两处都看:主账有时只把运输费投影进 fee_lines,口岸监管/接驳费
|
||||
仍留在原始 feeItems;只看 fee_lines 会漏掉这一项。
|
||||
金额数字才收(沿用 _named_from_rows 口径),不编造。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
src = dict(quote or {})
|
||||
rows: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for key in ("fee_lines", "fee_rows", "feeItems", "fee_items"):
|
||||
for row in _named_from_rows(src.get(key)):
|
||||
name = str(row.get("name") or "").strip()
|
||||
amount = str(row.get("amount") or "").strip()
|
||||
mark = (name, amount)
|
||||
if mark in seen:
|
||||
continue
|
||||
seen.add(mark)
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def land_port_handling_fees(
|
||||
quote: dict[str, Any] | None,
|
||||
*,
|
||||
shown_fees: list[dict[str, Any]] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
文字价格明细要单独展示的口岸监管/接驳费(TMS 有才有,非必填)。
|
||||
|
||||
参数:
|
||||
quote TMS 投影后的报价对象(fee_lines / feeItems 任一有即可);
|
||||
shown_fees 已经写在各段下面、无需重复展示的费用行。
|
||||
返回:TMS 原名的费用行列表;名称、金额、币种都照抄 TMS,本地不改写。
|
||||
为什么不放进 land_leg_fee_blocks:那里每段只取一条主运费,且销售调价会写回
|
||||
路段 costPrice;这类附加费不是路段成本,混进去会把整段运价改错。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
shown: set[tuple[str, str]] = set()
|
||||
for fee in list(shown_fees or []):
|
||||
name = str(fee.get("name") or _fee_name(fee) or "").strip()
|
||||
amount = str(fee.get("amount") or "").strip()
|
||||
if name and amount:
|
||||
shown.add((name, amount))
|
||||
src = dict(quote or {})
|
||||
# 已选定线路时,原始 feeItems 仍含其它备选的费目;带段号的只认当前这一条,
|
||||
# 否则会把没选中的线路接驳费也展示出来(费用合计却不含它)。
|
||||
selected = _selected_route_obj(src)
|
||||
want_seq: int | None = None
|
||||
if selected:
|
||||
raw_seq = selected.get("segmentSequence")
|
||||
if raw_seq is None:
|
||||
raw_seq = selected.get("segment_sequence")
|
||||
try:
|
||||
want_seq = int(raw_seq) if raw_seq not in (None, "", "null") else None
|
||||
except (TypeError, ValueError):
|
||||
want_seq = None
|
||||
out: list[dict[str, Any]] = []
|
||||
for fee in _all_named_fee_rows(src):
|
||||
if not is_port_handling_fee(fee):
|
||||
continue
|
||||
name = str(fee.get("name") or "").strip()
|
||||
amount = str(fee.get("amount") or "").strip()
|
||||
if not name or _num(amount) is None:
|
||||
continue
|
||||
if (name, amount) in shown:
|
||||
continue
|
||||
if want_seq is not None and _has_seq(fee) and _seq(fee) != want_seq:
|
||||
continue
|
||||
out.append(fee)
|
||||
return out
|
||||
|
||||
|
||||
def parse_tms_fee_rows(quote: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
"""摊平 TMS feeItems / 已投影的 fee_lines。"""
|
||||
src = dict(quote or {})
|
||||
@@ -167,6 +260,186 @@ def parse_tms_fee_rows(quote: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
return [dict(x) for x in _as_list(raw) if isinstance(x, dict)]
|
||||
|
||||
|
||||
# TMS 陆运把「口岸海关监管+接驳费」塞在费用备注里,不是独立费目。
|
||||
# 原文形如:4、口岸海关监管+接驳费:1.25T/821元、2.5T/821元,…、8T/1093元、40HQ/1380元…
|
||||
# 识别用这句做锚点;对外展示统一用 PORT_HANDLING_FEE_LABEL(报价单模板行名)。
|
||||
PORT_HANDLING_FEE_LABEL = "口岸海关监管费+接驳费"
|
||||
_PORT_FEE_HEAD = re.compile(r"口岸[^\r\n::]{0,16}?监管[^\r\n::]{0,16}?接驳[^\r\n::]{0,4}?[::]")
|
||||
# 一项费率:车型/金额元。车型带字母(T/HQ/M),可能再跟「冷柜」「平板」这类中文尾缀。
|
||||
_PORT_FEE_PAIR = re.compile(
|
||||
r"([0-9]+(?:\.[0-9]+)?\s*[A-Za-z]{1,4}[^\s//、,,;;::]{0,4}?)\s*[//]\s*([0-9]+(?:\.[0-9]+)?)\s*元"
|
||||
)
|
||||
|
||||
|
||||
def _remark_texts(quote: dict[str, Any] | None) -> list[str]:
|
||||
"""
|
||||
收集报价里所有可能带口岸监管费说明的原文。
|
||||
|
||||
来源:各段 landSegments / route_rows 的 remark,以及 fee_lines / feeItems 的 remark。
|
||||
为什么都收:TMS 只把这段说明挂在其中一段的备注上,主账投影后两处都可能出现,
|
||||
只读一处会漏;同文去重后返回。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
src = dict(quote or {})
|
||||
texts: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def _add(raw: Any) -> None:
|
||||
for item in _as_list(raw):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
for key in ("remark", "note", "description", "feeRemark"):
|
||||
text = str(item.get(key) or "").strip()
|
||||
if not text or text in seen:
|
||||
continue
|
||||
seen.add(text)
|
||||
texts.append(text)
|
||||
|
||||
for key in ("landSegments", "land_segments", "route_rows"):
|
||||
_add(src.get(key))
|
||||
for key in ("fee_lines", "fee_rows", "feeItems", "fee_items"):
|
||||
_add(src.get(key))
|
||||
# 整单备注:TMS 有时只把说明挂在报价根节点上。
|
||||
for key in ("remark", "note"):
|
||||
text = str(src.get(key) or "").strip()
|
||||
if text and text not in seen:
|
||||
seen.add(text)
|
||||
texts.append(text)
|
||||
selected = src.get("selected_land_route")
|
||||
if isinstance(selected, dict):
|
||||
_add(selected.get("legs"))
|
||||
return texts
|
||||
|
||||
|
||||
def _port_fee_head(text: str) -> tuple[str, str] | None:
|
||||
"""
|
||||
切出「口岸…监管…接驳…」这句的费名与冒号后的价表。
|
||||
|
||||
返回 (TMS 这句的开头, 价表)。费名仅供内部认句,对外展示统一用模板行名
|
||||
「口岸海关监管费+接驳费」,与报价单模板一致。没有这句返回 None。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
head = _PORT_FEE_HEAD.search(text or "")
|
||||
if not head:
|
||||
return None
|
||||
title = str(head.group(0) or "").rstrip("::").strip()
|
||||
return title, text[head.end():]
|
||||
|
||||
|
||||
def parse_port_handling_rates(quote: dict[str, Any] | None) -> list[tuple[str, str]]:
|
||||
"""
|
||||
从 TMS 备注里抽「口岸海关监管+接驳费」的车型价表。
|
||||
|
||||
返回 [(车型, 金额)],如 [("1.25T", "821"), ("8T", "1093"), ("40HQ", "1380")]。
|
||||
为什么解析备注:TMS 报价回包里这一项没有 feeName/amount,只有这句说明;
|
||||
不解析就永远显示不出来(WO202611220035 实测)。
|
||||
相同车型+金额只留一条;抽不到返回空列表,绝不编数字。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
pairs: list[tuple[str, str]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for text in _remark_texts(quote):
|
||||
split = _port_fee_head(text)
|
||||
if not split:
|
||||
continue
|
||||
clause = split[1]
|
||||
for hit in _PORT_FEE_PAIR.finditer(clause):
|
||||
token = re.sub(r"\s+", "", hit.group(1))
|
||||
amount = hit.group(2)
|
||||
mark = (token, amount)
|
||||
if not token or mark in seen:
|
||||
continue
|
||||
seen.add(mark)
|
||||
pairs.append(mark)
|
||||
return pairs
|
||||
|
||||
|
||||
def _vehicle_token_key(raw: str) -> str:
|
||||
"""车型比较键:去空格、转大写。8t/8T 视为同一车型。"""
|
||||
return re.sub(r"\s+", "", raw or "").upper()
|
||||
|
||||
|
||||
def land_vehicle_type(quote: dict[str, Any] | None, facts: dict[str, Any] | None = None) -> str:
|
||||
"""
|
||||
当前这单的车型,用于对上口岸监管费价表。
|
||||
|
||||
先取已选线路各段的 vehicleType(TMS 原样,如 8T / 40HQ),
|
||||
再退回工单「车型/数量」里斜杠前那段(8T/1 → 8T)。
|
||||
只用于匹配费率,不改写工单字段。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
for leg in _selected_legs(quote):
|
||||
token = str(leg.get("vehicleType") or leg.get("vehicle_type") or "").strip()
|
||||
if token:
|
||||
return token
|
||||
src = dict(facts or {})
|
||||
combo = str(src.get("车型/数量") or src.get("车型") or "").strip()
|
||||
if not combo:
|
||||
return ""
|
||||
return re.split(r"[//xX×**\s]", combo, maxsplit=1)[0].strip()
|
||||
|
||||
|
||||
def land_port_handling_rate(
|
||||
quote: dict[str, Any] | None,
|
||||
facts: dict[str, Any] | None = None,
|
||||
) -> tuple[str, str] | None:
|
||||
"""
|
||||
按当前车型在价表里取「口岸海关监管+接驳费」,取不到返回 None。
|
||||
|
||||
匹配规则:车型规范化后完全相同优先;否则允许一方是另一方前缀
|
||||
(模板写 48RH,TMS 写 48RH冷柜,要能对上)。仍然对不上就返回 None,
|
||||
由调用方把 TMS 原表整段展示,禁止自己挑一个数。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
pairs = parse_port_handling_rates(quote)
|
||||
if not pairs:
|
||||
return None
|
||||
vehicle = _vehicle_token_key(land_vehicle_type(quote, facts))
|
||||
if not vehicle:
|
||||
return None
|
||||
for token, amount in pairs:
|
||||
if _vehicle_token_key(token) == vehicle:
|
||||
return token, amount
|
||||
for token, amount in pairs:
|
||||
key = _vehicle_token_key(token)
|
||||
if key.startswith(vehicle) or vehicle.startswith(key):
|
||||
return token, amount
|
||||
return None
|
||||
|
||||
|
||||
def land_port_handling_clause(quote: dict[str, Any] | None) -> str:
|
||||
"""
|
||||
TMS 备注里「口岸海关监管+接驳费:…」这一句的原文(含冒号后的价表)。
|
||||
|
||||
车型对不上价表时整句展示,销售能自己按车型看费率;抽不到返回空串。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
for text in _remark_texts(quote):
|
||||
split = _port_fee_head(text)
|
||||
if not split:
|
||||
continue
|
||||
# 取到行尾为止,避免把整段备注条款都搬进价格明细。
|
||||
clause = re.split(r"[\r\n]", split[1], maxsplit=1)[0].strip()
|
||||
if clause:
|
||||
return clause
|
||||
return ""
|
||||
|
||||
|
||||
def land_port_handling_title(quote: dict[str, Any] | None) -> str:
|
||||
"""
|
||||
展示用的费目名(报价单模板行名,产品确认口径)。
|
||||
|
||||
固定写「口岸海关监管费+接驳费」,与模板固定行一致;TMS 备注里那句
|
||||
「口岸海关监管+接驳费」只是识别用的锚点,不拿来当展示名。
|
||||
备注里没有这句时返回空串,调用方据此判断这单有没有这一项。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
for text in _remark_texts(quote):
|
||||
if _port_fee_head(text):
|
||||
return PORT_HANDLING_FEE_LABEL
|
||||
return ""
|
||||
|
||||
|
||||
def _named_from_rows(raw: Any) -> list[dict[str, Any]]:
|
||||
"""只要 TMS 费目名。路段名冒充的费用行丢掉。"""
|
||||
rows: list[dict[str, Any]] = []
|
||||
@@ -219,8 +492,14 @@ def _pick_fee_for_leg(
|
||||
lambda f: _leg_no(f) == want_leg and _same_amount(f.get("amount"), want_amt),
|
||||
lambda f: _same_amount(f.get("amount"), want_amt),
|
||||
)
|
||||
# 口岸监管/接驳费也带段号时,不能抢在各段主运费前面被认成「运输费」。
|
||||
# 先试普通费目,再试这类附加费;顺序稳定,命中即止。
|
||||
ordered = sorted(
|
||||
enumerate(fees),
|
||||
key=lambda pair: (1 if is_port_handling_fee(pair[1]) else 0, pair[0]),
|
||||
)
|
||||
for check in checks:
|
||||
for i, fee in enumerate(fees):
|
||||
for i, fee in ordered:
|
||||
if i in used:
|
||||
continue
|
||||
try:
|
||||
@@ -285,11 +564,28 @@ def _quote_fee_dicts(quote: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
return parse_tms_fee_rows(src)
|
||||
|
||||
|
||||
def _selected_route_obj(quote: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
已选线路对象。主账回读时常把它落成 JSON 串,这里统一还原成 dict。
|
||||
|
||||
为什么必须认串:从 inq_quote.payload_json 读出来的 selected_land_route 是字符串,
|
||||
只判断 dict 会让「已选哪条线路」失效,进而把别的备选附加费也算进来。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
raw = dict(quote or {}).get("selected_land_route")
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return dict(raw) if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def _selected_legs(quote: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
"""当前这条线路的各段。多条未选时不编。"""
|
||||
src = dict(quote or {})
|
||||
selected = src.get("selected_land_route")
|
||||
if isinstance(selected, dict):
|
||||
selected = _selected_route_obj(src)
|
||||
if selected:
|
||||
legs = [dict(x) for x in list(selected.get("legs") or []) if isinstance(x, dict)]
|
||||
if legs:
|
||||
return legs
|
||||
@@ -315,7 +611,15 @@ def land_leg_fee_blocks(
|
||||
if not legs:
|
||||
return []
|
||||
fees = _named_tms_fees(quote)
|
||||
fallback_name = next((str(f.get("name") or "").strip() for f in fees if f.get("name")), "")
|
||||
# 附加费(口岸监管/接驳)不能当各段运费的兜底名字,否则整段成本会被标成接驳费。
|
||||
fallback_name = next(
|
||||
(
|
||||
str(f.get("name") or "").strip()
|
||||
for f in fees
|
||||
if f.get("name") and not is_port_handling_fee(f)
|
||||
),
|
||||
"",
|
||||
)
|
||||
# 路段名把 TMS 费目冲掉时,各段成本仍按运输费展示,禁止再用始发→目的冒充费名。
|
||||
if not fallback_name:
|
||||
fallback_name = "运输费"
|
||||
|
||||
@@ -16,6 +16,7 @@ from typing import Any, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_CLOSED = frozenset({"已成交", "未成交", "已关闭", "转人工"})
|
||||
_QUOTED = frozenset({"已报价", "协商中"})
|
||||
|
||||
@@ -29,8 +30,13 @@ _TO_VERBS = (
|
||||
"涨到|升到|加到|减到|调到|增至|变为|变成|改为|改成|调整为|调整成"
|
||||
)
|
||||
_PERCENT_TO = re.compile(rf"({_TO_VERBS})\s*(\d+(?:\.\d+)?)\s*%")
|
||||
# 金额前常带币种(「提高到USD 1330.00」),不能因为中间夹了 USD 就抽不到。
|
||||
_CURRENCY_PREFIX = r"(?:CNY|RMB|USD|EUR|HKD|JPY|GBP|人民币|美元|港币|欧元|日元)"
|
||||
# (?!\d) 防止「增加到110%」回退成「加到11」;(?!\s*%) 把带百分号的留给 _PERCENT_TO。
|
||||
_TARGET = re.compile(rf"({_TO_VERBS})\s*(\d+(?:\.\d+)?)(?!\d)(?!\s*%)")
|
||||
_TARGET = re.compile(
|
||||
rf"({_TO_VERBS})\s*(?:{_CURRENCY_PREFIX}\s*)?(\d+(?:\.\d+)?)(?!\d)(?!\s*%)",
|
||||
re.I,
|
||||
)
|
||||
_DAO_PERCENT = re.compile(rf"(?:{_TO_VERBS})\s*(\d+(?:\.\d+)?)\s*%")
|
||||
_SPLIT = re.compile(r"[,,;;。!!??\n]|和(?=\S)")
|
||||
_FEE_TOKEN = re.compile(r"([\u4e00-\u9fffA-Za-z0-9]{1,16}费)")
|
||||
@@ -191,6 +197,148 @@ def _store_bucket(quote: dict[str, Any], key: str, items: list[dict[str, Any]])
|
||||
quote[alt] = json.dumps(items, ensure_ascii=False)
|
||||
|
||||
|
||||
def _ccy_code(raw: Any) -> str:
|
||||
"""币种归一:RMB 统一成 CNY;空串表示沿用表头。"""
|
||||
code = str(raw or "").strip().upper()
|
||||
return "CNY" if code == "RMB" else code
|
||||
|
||||
|
||||
def _sea_bucket_snapshot(quote: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
调价前先记住每段小计与明细币种。
|
||||
|
||||
为什么必须先记:一旦改了明细行,就再也算不出 TMS 当时用的小计口径
|
||||
(尤其美元段小计是人民币,必须用原小计/原明细和反推,不能编汇率)。
|
||||
"""
|
||||
src = dict(quote or {})
|
||||
header = _ccy_code(src.get("currency") or src.get("currencyCode"))
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for key, _label in _SEA_BUCKETS:
|
||||
sub_text = str(src.get("fee_total_" + key) or "").strip()
|
||||
sub_amt, sub_prefix = parse_money(sub_text)
|
||||
amounts: list[float] = []
|
||||
ccys: set[str] = set()
|
||||
for item in _bucket_items(src, key):
|
||||
amount, prefix = parse_money(
|
||||
item.get("amount") or item.get("value") or item.get("salePrice")
|
||||
)
|
||||
if amount is None:
|
||||
continue
|
||||
amounts.append(amount)
|
||||
ccys.add(_ccy_code(item.get("currency") or prefix or header))
|
||||
out[key] = {
|
||||
"subtotal": sub_amt,
|
||||
"sub_ccy": _ccy_code(sub_prefix or header),
|
||||
"items_total": sum(amounts),
|
||||
"line_ccys": ccys,
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def _set_subtotal_row(
|
||||
rows: list[dict[str, Any]], bucket: str, new_value: float
|
||||
) -> None:
|
||||
"""把算好的小计写回这一行,_write_adjusted_buckets 再落 fee_total_*。"""
|
||||
sub_key = "fee_total_" + bucket
|
||||
text = format_money(new_value)
|
||||
for row in rows:
|
||||
if str(row.get("_subtotal_key") or "") == sub_key:
|
||||
row["amount"] = text
|
||||
return
|
||||
|
||||
|
||||
def recompute_sea_bucket_totals(
|
||||
base: dict[str, Any] | None,
|
||||
new_rows: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
产品按行改价后,按 TMS 原小计口径重算海运三段小计。
|
||||
|
||||
返回:
|
||||
subtotals {bucket: 小数计文本}
|
||||
delta 合计应增加的人民币差额(只含能落到表头币种的小计)
|
||||
bucket_rows 已算进小计的新明细下标,调用方算合计时不能再把这行加一次
|
||||
currency_hint 有外币差额没法落合计时为 True
|
||||
|
||||
为什么不直接加明细:美元段的小计是人民币,TMS 原小计 ÷ 原明细和
|
||||
就是 TMS 自己用的口径;用比例放大差额,不另编汇率。
|
||||
"""
|
||||
src = dict(base or {})
|
||||
snap = _sea_bucket_snapshot(src)
|
||||
rows = [dict(x) for x in (new_rows or []) if isinstance(x, dict)]
|
||||
header = _ccy_code(src.get("currency") or src.get("currencyCode"))
|
||||
used: set[int] = set()
|
||||
subtotals: dict[str, str] = {}
|
||||
bucket_rows: set[int] = set()
|
||||
delta = 0.0
|
||||
currency_hint = False
|
||||
for key, _label in _SEA_BUCKETS:
|
||||
items = _bucket_items(src, key)
|
||||
if not items:
|
||||
continue
|
||||
state = snap.get(key) or {}
|
||||
old_sub = state.get("subtotal")
|
||||
old_rows = items
|
||||
# 先按名称把新明细配回本段原行,和 stamp_prices_for_sheet 用同一套顺序。
|
||||
matched: list[tuple[int, float, float]] = []
|
||||
for item in old_rows:
|
||||
amount, prefix = parse_money(
|
||||
item.get("amount") or item.get("value") or item.get("salePrice")
|
||||
)
|
||||
idx = _match_fee_index(_item_fee_name(item), rows, used)
|
||||
if amount is None or idx < 0:
|
||||
continue
|
||||
new_amount, _ = parse_money(
|
||||
rows[idx].get("amount") or rows[idx].get("value") or rows[idx].get("salePrice")
|
||||
)
|
||||
if new_amount is None:
|
||||
continue
|
||||
used.add(idx)
|
||||
matched.append((idx, amount, new_amount))
|
||||
if not matched:
|
||||
continue
|
||||
native_delta = sum(new - old for _idx, old, new in matched)
|
||||
if old_sub is None:
|
||||
# 没有 TMS 小计:同币种差额直接给合计,外币才提示。
|
||||
line_ccys = {c for c in (state.get("line_ccys") or set()) if c}
|
||||
if not header or not line_ccys or line_ccys == {header}:
|
||||
delta += native_delta
|
||||
bucket_rows.update(idx for idx, _old, _new in matched)
|
||||
else:
|
||||
currency_hint = True
|
||||
continue
|
||||
sub_ccy = _ccy_code(state.get("sub_ccy") or header)
|
||||
if sub_ccy and header and sub_ccy != header:
|
||||
currency_hint = True
|
||||
continue
|
||||
line_ccys = {c for c in (state.get("line_ccys") or set()) if c}
|
||||
if not line_ccys or line_ccys == {sub_ccy}:
|
||||
delta_sub = native_delta
|
||||
elif len(line_ccys) == 1:
|
||||
base_sum = float(state.get("items_total") or 0)
|
||||
if base_sum > 1e-9:
|
||||
delta_sub = native_delta * (old_sub / base_sum)
|
||||
else:
|
||||
currency_hint = True
|
||||
continue
|
||||
else:
|
||||
if len(matched) == 1 and abs(matched[0][1]) > 1e-9:
|
||||
_idx, old_line, new_line = matched[0]
|
||||
delta_sub = old_sub * (new_line / old_line - 1)
|
||||
else:
|
||||
currency_hint = True
|
||||
continue
|
||||
subtotals[key] = format_money(old_sub + delta_sub)
|
||||
bucket_rows.update(idx for idx, _old, _new in matched)
|
||||
delta += delta_sub
|
||||
return {
|
||||
"subtotals": subtotals,
|
||||
"delta": delta,
|
||||
"bucket_rows": bucket_rows,
|
||||
"currency_hint": currency_hint,
|
||||
}
|
||||
|
||||
|
||||
def adjustable_rows(quote: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
"""
|
||||
调价能对上的行:扁平明细,加上海运分段里的费目和小计。
|
||||
@@ -873,6 +1021,20 @@ def _write_price(item: dict[str, Any], plain: str) -> None:
|
||||
item["costPrice"] = plain
|
||||
|
||||
|
||||
def _sync_line_currency(item: dict[str, Any], fee: dict[str, Any]) -> None:
|
||||
"""
|
||||
产品手工报价写了币种时,报价单读的那份副本必须同步行币种。
|
||||
|
||||
为何:模板「币别」列直接取 podCostItems / 舱位费 / 路段行的 currency。
|
||||
旧逻辑只把金额盖进副本、不盖币种,结果 TMS 原币种(CNY)把产品写的 USD
|
||||
吃掉,报价单成了「文件费 CNY 60.00」(2026-11-22 真机)。
|
||||
空币种一律不动:没写币种时沿用原行(通常已从 TMS/表头继承),禁止在这里猜。
|
||||
"""
|
||||
ccy = str(fee.get("currency") or fee.get("currencyCode") or "").strip()
|
||||
if ccy:
|
||||
item["currency"] = ccy
|
||||
|
||||
|
||||
def _match_fee_index(name: str, fees: list[dict[str, Any]], used: set[int]) -> int:
|
||||
return next(
|
||||
(
|
||||
@@ -964,6 +1126,7 @@ def _stamp_fee_items(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None:
|
||||
continue
|
||||
used.add(idx)
|
||||
_write_price(item, _plain_amount(str(fees[idx].get("amount") or "")))
|
||||
_sync_line_currency(item, fees[idx])
|
||||
if not item.get("name"):
|
||||
item["name"] = _fee_title(fees[idx])
|
||||
if not item.get("feeName"):
|
||||
@@ -992,10 +1155,13 @@ def _stamp_one_route(row: dict[str, Any], fees: list[dict[str, Any]]) -> None:
|
||||
"""一段线路:运输费写金额,提货/送货写到对应列。"""
|
||||
if len(fees) == 1:
|
||||
_write_price(row, _plain_amount(str(fees[0].get("amount") or "")))
|
||||
_sync_line_currency(row, fees[0])
|
||||
return
|
||||
transport = [fee for fee in fees if any(word in _fee_title(fee) for word in ("运输", "运费", "陆运"))]
|
||||
if len(transport) == 1:
|
||||
_write_price(row, _plain_amount(str(transport[0].get("amount") or "")))
|
||||
# 路段行只有一个币种格:主运输费点明币种时,路段整段跟它走。
|
||||
_sync_line_currency(row, transport[0])
|
||||
for fee in fees:
|
||||
title = _fee_title(fee)
|
||||
plain = _plain_amount(str(fee.get("amount") or ""))
|
||||
@@ -1015,9 +1181,12 @@ def _stamp_route_list(rows: list[Any], fees: list[dict[str, Any]]) -> None:
|
||||
return
|
||||
if len(legs) == len(fees):
|
||||
for leg, fee in zip(legs, fees):
|
||||
ccy_before = str(leg.get("currency") or "")
|
||||
_write_price(leg, _plain_amount(str(fee.get("amount") or "")))
|
||||
_sync_line_currency(leg, fee)
|
||||
return
|
||||
if len(legs) == 1:
|
||||
ccy_before = str(legs[0].get("currency") or "")
|
||||
_stamp_one_route(legs[0], fees)
|
||||
|
||||
|
||||
@@ -1059,7 +1228,10 @@ def _stamp_buckets(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None:
|
||||
plain = _plain_amount(str(fees[idx].get("amount") or ""))
|
||||
if not plain:
|
||||
continue
|
||||
ccy_before = str(item.get("currency") or "")
|
||||
fee_ccy = str(fees[idx].get("currency") or "")
|
||||
_write_price(item, plain)
|
||||
_sync_line_currency(item, fees[idx])
|
||||
changed = True
|
||||
if changed:
|
||||
_store_bucket(quote, key, items)
|
||||
@@ -1100,7 +1272,9 @@ def _stamp_air_bucket_list(
|
||||
continue
|
||||
used.add(idx)
|
||||
plain = _plain_amount(str(fees[idx].get("amount") or ""))
|
||||
ccy_before = str(charge.get("currency") or "")
|
||||
_write_price(charge, plain)
|
||||
_sync_line_currency(charge, fees[idx])
|
||||
# 单价/数量若调价行有值也盖上,模板按单价×数量重算时才对
|
||||
fee = fees[idx]
|
||||
up = _plain_amount(str(fee.get("unit_price") or fee.get("unitPrice") or ""))
|
||||
@@ -1397,16 +1571,24 @@ def apply_adjust(
|
||||
applied: list[dict[str, Any]] = []
|
||||
unmatched: list[str] = []
|
||||
ambiguous: list[str] = []
|
||||
currency_hint = bool(multi)
|
||||
# 只有真正没法落到合计的外币差额才提示「不做汇率」;海运分段有 TMS 小计可反推,不算换汇。
|
||||
currency_hint = False
|
||||
total_amt, _ = parse_money(src.get("total"))
|
||||
new_total = total_amt
|
||||
total_touched = False
|
||||
total_new_value: Optional[float] = None
|
||||
single_same_ccy = _single_line_same_currency(
|
||||
[row for row in rows if not row.get("_subtotal_key") and not row.get("_is_total")],
|
||||
total_ccy or header,
|
||||
) is not None
|
||||
subtotal_only: dict[str, float] = {}
|
||||
touched_buckets: set[str] = set()
|
||||
single_line_new: Optional[float] = None
|
||||
# 调价前的小计/币种快照:改完明细后再算小计,必须靠它反推 TMS 当时的口径。
|
||||
bucket_snapshot = _sea_bucket_snapshot(src)
|
||||
bucket_line_delta: dict[str, float] = {}
|
||||
bucket_changed_lines: dict[str, list[tuple[float, float]]] = {}
|
||||
explicit_subtotal: dict[str, float] = {}
|
||||
line_delta_total = 0.0
|
||||
target_ccy = total_ccy or header
|
||||
|
||||
for item in extract.items:
|
||||
spoken = (item.fee_name or "").strip()
|
||||
@@ -1477,34 +1659,93 @@ def apply_adjust(
|
||||
any_applied = True
|
||||
bucket = str(row.get("_bucket") or "")
|
||||
if row.get("_is_total"):
|
||||
subtotal_only["__total__"] = new_amt
|
||||
total_touched = True
|
||||
total_new_value = new_amt
|
||||
continue
|
||||
if row.get("_subtotal_key"):
|
||||
# 只改小计数字写回 fee_total_*;明细是否另调看有没有点名费目
|
||||
subtotal_only[bucket] = new_amt - old_amt
|
||||
# 点名小计:小计数字以销售说的为准,明细是否另调看有没有点名费目。
|
||||
explicit_subtotal[bucket] = new_amt
|
||||
continue
|
||||
if single_same_ccy:
|
||||
single_line_new = new_amt
|
||||
if bucket:
|
||||
touched_buckets.add(bucket)
|
||||
if (not multi) and new_total is not None:
|
||||
if single_same_ccy:
|
||||
new_total = new_amt
|
||||
else:
|
||||
new_total = new_total + (new_amt - old_amt)
|
||||
bucket_line_delta[bucket] = bucket_line_delta.get(bucket, 0.0) + (new_amt - old_amt)
|
||||
bucket_changed_lines.setdefault(bucket, []).append((old_amt, new_amt))
|
||||
continue
|
||||
# 非分段行:同币种差额可直接进合计;外币没有可依据的小计,交给提示。
|
||||
line_ccy_code = _ccy_code(line_ccy or prefix)
|
||||
if not target_ccy or not line_ccy_code or line_ccy_code == target_ccy:
|
||||
line_delta_total += new_amt - old_amt
|
||||
else:
|
||||
currency_hint = True
|
||||
if not any_applied:
|
||||
unmatched.append(spoken)
|
||||
|
||||
if (not multi) and new_total is not None:
|
||||
if "__total__" in subtotal_only:
|
||||
# 合计是整单改数;小计差额不再叠进合计,避免「合计×1.1 + 小计差额」重复
|
||||
new_total = subtotal_only.pop("__total__")
|
||||
# 先按段重算小计:TMS 美元段小计是人民币,用「原小计 ÷ 原明细和」反推 TMS 自己的口径,
|
||||
# 不另编汇率;同币种段就是简单差额。
|
||||
subtotal_delta_total = 0.0
|
||||
for bucket, native_delta in bucket_line_delta.items():
|
||||
if bucket in explicit_subtotal:
|
||||
# 小计由销售点名,差额在下面统一算,避免明细差额再叠一次。
|
||||
continue
|
||||
snap = bucket_snapshot.get(bucket) or {}
|
||||
old_sub = snap.get("subtotal")
|
||||
sub_ccy = _ccy_code(snap.get("sub_ccy") or header)
|
||||
if old_sub is None:
|
||||
# 没有 TMS 小计:同币种可进合计,外币只能提示。
|
||||
line_ccys = {c for c in (snap.get("line_ccys") or set()) if c}
|
||||
if not target_ccy or not line_ccys or line_ccys == {target_ccy}:
|
||||
subtotal_delta_total += native_delta
|
||||
else:
|
||||
currency_hint = True
|
||||
continue
|
||||
if sub_ccy and target_ccy and sub_ccy != target_ccy:
|
||||
currency_hint = True
|
||||
continue
|
||||
line_ccys = {c for c in (snap.get("line_ccys") or set()) if c}
|
||||
if not line_ccys or line_ccys == {sub_ccy}:
|
||||
delta_sub = native_delta
|
||||
elif len(line_ccys) == 1:
|
||||
base = float(snap.get("items_total") or 0)
|
||||
if base > 1e-9:
|
||||
delta_sub = native_delta * (old_sub / base)
|
||||
else:
|
||||
currency_hint = True
|
||||
continue
|
||||
else:
|
||||
for bucket, delta in subtotal_only.items():
|
||||
if bucket not in touched_buckets:
|
||||
new_total = new_total + delta
|
||||
elif total_touched and "__total__" in subtotal_only:
|
||||
# 多币种:点名「费用合计」仍改合计数字,不做汇率换算
|
||||
new_total = subtotal_only["__total__"]
|
||||
# 同一段混了多币种:只有单行调整时按该行比例缩放小计;多行无法拆分。
|
||||
changed = bucket_changed_lines.get(bucket) or []
|
||||
if len(changed) == 1 and abs(changed[0][0]) > 1e-9:
|
||||
old_line, new_line = changed[0]
|
||||
delta_sub = old_sub * (new_line / old_line - 1)
|
||||
else:
|
||||
currency_hint = True
|
||||
continue
|
||||
new_sub = old_sub + delta_sub
|
||||
_set_subtotal_row(rows, bucket, new_sub)
|
||||
subtotal_delta_total += delta_sub
|
||||
|
||||
# 点名改小计、但没点名明细的段:小计差额直接进合计。
|
||||
for bucket, new_sub in explicit_subtotal.items():
|
||||
snap = bucket_snapshot.get(bucket) or {}
|
||||
old_sub = snap.get("subtotal")
|
||||
if old_sub is None:
|
||||
continue
|
||||
sub_ccy = _ccy_code(snap.get("sub_ccy") or header)
|
||||
if sub_ccy and target_ccy and sub_ccy != target_ccy:
|
||||
currency_hint = True
|
||||
continue
|
||||
subtotal_delta_total += new_sub - old_sub
|
||||
|
||||
if total_touched and total_new_value is not None:
|
||||
# 销售点名改合计:合计数字以他说的为准,小计仍按明细更新。
|
||||
new_total = total_new_value
|
||||
elif single_same_ccy and single_line_new is not None:
|
||||
# 明细只有一项且与合计同币种:合计跟着这一项走。
|
||||
new_total = single_line_new
|
||||
elif new_total is not None:
|
||||
new_total = new_total + subtotal_delta_total + line_delta_total
|
||||
|
||||
|
||||
out = dict(src)
|
||||
visible = []
|
||||
@@ -1516,7 +1757,7 @@ def apply_adjust(
|
||||
out["fee_rows"] = visible
|
||||
out["fee_lines"] = visible
|
||||
_write_adjusted_buckets(out, rows)
|
||||
if applied and new_total is not None and new_total != total_amt and ((not multi) or total_touched):
|
||||
if applied and new_total is not None and new_total != total_amt:
|
||||
out["total"] = format_money(new_total, sample=str(src.get("total") or ""), currency=total_ccy)
|
||||
if not applied:
|
||||
code = "ambiguous" if ambiguous else "none_matched"
|
||||
|
||||
@@ -24,7 +24,9 @@ _LABELED_TRADE_TERMS = re.compile(
|
||||
)
|
||||
_TRADE_TERMS_LINE = re.compile(r"(?im)^\s*贸易条款")
|
||||
|
||||
# 长词优先,避免 P2P 误伤其它词;门到门不在名单里。
|
||||
# 长词优先,避免 P2P 误伤其它词。
|
||||
# 门到门/门到港/港到门是贸易条款(见 SEA_TRADE_TERMS),不在运输分类名单里;
|
||||
# 港到港两种口径都用(条款简写、也是 Port to Port 的口语),这里仍收成 Port to Port。
|
||||
_ALIASES = (
|
||||
("port to port", "Port to Port"),
|
||||
("港到港", "Port to Port"),
|
||||
@@ -118,14 +120,29 @@ def harvest_sea_class(text: str, current: dict[str, str] | None = None) -> dict[
|
||||
return merged
|
||||
|
||||
|
||||
# 运输分类用语,不能冒充贸易条款。销售原话写了「贸易条款」才保留。
|
||||
_DOOR_TRADE_TERMS = frozenset(
|
||||
{
|
||||
"门到门",
|
||||
# 海运贸易条款销售侧四选一(产品口径 2026-11-22):门到门、港到港、门到港、港到门。
|
||||
# 补问举例、口语收割、去掉模型编造条款都只认这四项;本地仍不因条款原文不在名单里拒绝销售。
|
||||
SEA_TRADE_TERMS = ("门到门", "港到港", "门到港", "港到门")
|
||||
|
||||
# 这四项的英文/缩写别名:整句只回这些词时同样收成中文标准值。
|
||||
# Port to Port 不在此列:它是运输分类的标准值(见 SEA_CLASSES),
|
||||
# 混进条款会让「整句只回 Port to Port」既被当成条款又被当成分类。
|
||||
_TRADE_TERM_ALIASES = {
|
||||
"门到门": ("door to door", "door-to-door", "doortodoor", "d2d"),
|
||||
}
|
||||
|
||||
# 可被模型凭空编造、且原话没出现就要丢掉的条款词(四项中文 + 门到门的英文缩写 + 港到港的英文写法)。
|
||||
# 名字保留「会被冒充的条款」口径:这些词是模型最爱替销售选的值。
|
||||
_INVENTED_TRADE_TERMS = frozenset(
|
||||
set(SEA_TRADE_TERMS)
|
||||
| {
|
||||
"door to door",
|
||||
"door-to-door",
|
||||
"doortodoor",
|
||||
"d2d",
|
||||
"port to port",
|
||||
"porttoport",
|
||||
"p2p",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -135,7 +152,7 @@ def harvest_sea_trade_terms(text: str, facts: dict[str, str] | None = None) -> d
|
||||
海运贸易条款:标签行冒号后原样优先。
|
||||
|
||||
WO202609280012:销售写「贸易条款:Port to Port」,模型却收成「门到门」。
|
||||
有标签行则强制用标签值;门到门是否丢掉仍交给 drop_invented_door_trade_terms。
|
||||
有标签行则强制用标签值;门到门/港到港/门到港/港到门是否丢掉仍交给 drop_invented_door_trade_terms。
|
||||
"""
|
||||
merged = dict(facts or {})
|
||||
labeled = _labeled_value(text or "", _LABELED_TRADE_TERMS)
|
||||
@@ -144,41 +161,47 @@ def harvest_sea_trade_terms(text: str, facts: dict[str, str] | None = None) -> d
|
||||
return merged
|
||||
|
||||
|
||||
# 补问举例让销售直接回这两个词。整句只有其中一个,或长句里写了其中一个,都记成贸易条款。
|
||||
# 补问举例让销售直接回这四项(或门到门的英文写法)。整句只有其中一个时收成贸易条款。
|
||||
# 正则里四项互不为前缀(都是三个字且第二字不同),先写后写都不会截断别人。
|
||||
# 不把 Port to Port 列进来:它整句出现时属于运输分类(见 canonicalize_sea_class)。
|
||||
_SHORT_SEA_TRADE_REPLY = re.compile(
|
||||
r"^\s*(门到门|港到港|door\s*to\s*door|door-to-door|d2d)\s*[.。!!??]?\s*$",
|
||||
r"^\s*(门到门|门到港|港到门|港到港|door\s*to\s*door|door-to-door|d2d)"
|
||||
r"\s*[.。!!??]?\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def short_sea_trade_reply(text: str) -> str:
|
||||
"""
|
||||
销售整句只回门到门或港到港时,收成贸易条款。
|
||||
销售整句只回门到门/港到港/门到港/港到门时,收成贸易条款。
|
||||
|
||||
举例行不算。长句里没写这两个词时,不能从这里编出一个条款。
|
||||
返回「门到门」或「港到港」;对不上返回空串。
|
||||
举例行不算。长句里没写这四项时,不能从这里编出一个条款。
|
||||
Port to Port 不收:那是运输分类,避免同一句被当成两个字段。
|
||||
返回标准中文四项之一;对不上返回空串。
|
||||
"""
|
||||
cleaned = _without_clarify_examples(text or "").strip()
|
||||
hit = _SHORT_SEA_TRADE_REPLY.match(cleaned)
|
||||
if not hit:
|
||||
return ""
|
||||
raw = (hit.group(1) or "").strip()
|
||||
if raw in SEA_TRADE_TERMS:
|
||||
return raw
|
||||
folded = re.sub(r"[\s-]+", "", raw).lower()
|
||||
if raw == "港到港":
|
||||
return "港到港"
|
||||
if raw == "门到门" or folded in {"doortodoor", "d2d"}:
|
||||
return "门到门"
|
||||
for canon, aliases in _TRADE_TERM_ALIASES.items():
|
||||
if any(re.sub(r"[\s-]+", "", alias).lower() == folded for alias in aliases):
|
||||
return canon
|
||||
return ""
|
||||
|
||||
|
||||
def drop_invented_door_trade_terms(text: str, facts: dict[str, str] | None = None) -> dict[str, str]:
|
||||
"""
|
||||
丢掉冒充贸易条款的「门到门」。
|
||||
丢掉模型编造的贸易条款(门到门/港到港/门到港/港到门及英文缩写)。
|
||||
|
||||
测服 WO202609200013:原话没写贸易条款,确认卡却出现「贸易条款:门到门」。
|
||||
门到门只是运输分类说法,不是 FOB/CIF 这类条款;原话没有「贸易条款」四字时不准收下。
|
||||
2026-11 产品口径把门到门也列为正式条款,但「原话说过」这一条不变:
|
||||
原话没出现对应词、也没写「贸易条款」标签时不准收下,避免模型替销售选条款。
|
||||
销售明确写了「贸易条款:门到门」则保留原文,不改六态。
|
||||
若标签行写的是 Port to Port / 港到港等,禁止再用模型的「门到门」盖掉。
|
||||
标签行已写死条款时以标签为准,禁止再用模型编造的词盖掉。
|
||||
"""
|
||||
merged = harvest_sea_trade_terms(text, facts)
|
||||
trade = str(merged.get("贸易条款") or "").strip()
|
||||
@@ -191,30 +214,40 @@ def drop_invented_door_trade_terms(text: str, facts: dict[str, str] | None = Non
|
||||
return merged
|
||||
if "贸易条款" in (text or ""):
|
||||
return merged
|
||||
if trade.lower().replace(" ", "") in {x.replace(" ", "") for x in _DOOR_TRADE_TERMS} or trade in _DOOR_TRADE_TERMS:
|
||||
if trade.lower().replace(" ", "") in {x.replace(" ", "") for x in _INVENTED_TRADE_TERMS} or trade in _INVENTED_TRADE_TERMS:
|
||||
merged.pop("贸易条款", None)
|
||||
return merged
|
||||
|
||||
|
||||
def _spoken_door_in_text(text: str) -> str:
|
||||
def _spoken_trade_in_text(text: str) -> str:
|
||||
"""
|
||||
长句里写了「门到门」或「港到港」就是贸易条款。
|
||||
长句里写了门到门/港到港/门到港/港到门就是贸易条款。
|
||||
|
||||
举例行「(如:门到门、港到港)」先丢掉,不能当成已填。
|
||||
原话没有这两个词时返回空,禁止把模型猜的条款写回去。
|
||||
同一句里两个词都有时,取靠后的那个。
|
||||
「Port to Port」仍是运输分类,不在这里改写成贸易条款。
|
||||
举例行「(如:门到门、港到港、门到港、港到门)」先丢掉,不能当成已填。
|
||||
原话没写这四项时返回空,禁止把模型猜的条款写回去。
|
||||
同一句里出现多个时,取靠后的那个(销售常在句尾改口)。
|
||||
「Port to Port」归运输分类,不在这里改写成贸易条款,也不参与整句短回;
|
||||
避免销售选运输分类时被同时记成条款。
|
||||
「广州港到巴生港」不含「港到港」这三个连续字,不能误收。
|
||||
英文别名(door to door 等)也按出现位置参与「取靠后」。
|
||||
"""
|
||||
cleaned = _without_clarify_examples(text or "")
|
||||
found: list[tuple[int, str]] = []
|
||||
for word in ("门到门", "港到港"):
|
||||
for word in SEA_TRADE_TERMS:
|
||||
idx = cleaned.rfind(word)
|
||||
if idx >= 0:
|
||||
found.append((idx, word))
|
||||
door = re.search(r"door\s*[- ]?to\s*[- ]?door", cleaned, re.I)
|
||||
if door:
|
||||
found.append((door.start(), "门到门"))
|
||||
for canon, aliases in _TRADE_TERM_ALIASES.items():
|
||||
for alias in aliases:
|
||||
# 中文别名已按中文词处理,这里只补英文/缩写形式。
|
||||
if not alias.isascii():
|
||||
continue
|
||||
pattern = r"\s*[-_ ]?\s*".join(re.escape(part) for part in alias.split())
|
||||
hit = None
|
||||
for hit in re.finditer(pattern, cleaned, re.I):
|
||||
pass
|
||||
if hit is not None:
|
||||
found.append((hit.start(), canon))
|
||||
if not found:
|
||||
return ""
|
||||
found.sort(key=lambda item: item[0])
|
||||
@@ -223,12 +256,11 @@ def _spoken_door_in_text(text: str) -> str:
|
||||
|
||||
def apply_spoken_sea_trade_reply(text: str, facts: dict[str, str] | None = None) -> dict[str, str]:
|
||||
"""
|
||||
先丢掉模型冒充的门到门,再按原话收回贸易条款。
|
||||
先丢掉模型冒充的条款,再按原话收回贸易条款。
|
||||
|
||||
整句只回「门到门」或「港到港」要收下。长句里写了其中一个(例如先报货、再回「2」选海运)
|
||||
整句只回四项之一要收下。长句里写了其中一个(例如先报货、再回「2」选海运)
|
||||
也是贸易条款,不能因为原话没有「贸易条款」四个字就丢掉。
|
||||
原话没出现「门到门」时,旧草稿里的门到门继续丢掉(WO202609200013)。
|
||||
原话没出现「港到港」时,模型填的港到港同样丢掉。
|
||||
原话没出现某项时,旧草稿里由模型编的同一项继续丢掉(WO202609200013)。
|
||||
销售已写「贸易条款:…」标签时以标签为准,不用句中的词覆盖。返回新 dict。
|
||||
"""
|
||||
merged = drop_invented_door_trade_terms(text, facts)
|
||||
@@ -238,12 +270,10 @@ def apply_spoken_sea_trade_reply(text: str, facts: dict[str, str] | None = None)
|
||||
if spoken:
|
||||
merged["贸易条款"] = spoken
|
||||
return merged
|
||||
door = _spoken_door_in_text(text)
|
||||
if door:
|
||||
merged["贸易条款"] = door
|
||||
spoken_long = _spoken_trade_in_text(text)
|
||||
if spoken_long:
|
||||
merged["贸易条款"] = spoken_long
|
||||
return merged
|
||||
if str(merged.get("贸易条款") or "").strip() == "港到港":
|
||||
merged.pop("贸易条款", None)
|
||||
return merged
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
本文件职责:核对卡通过后、建单查价前,确认当前运输类型的货物字段能拼出查价正文。
|
||||
带去:运输类型、线路类别、始发/目的/品名/报价日期,以及该类型的体积重量或车型/数量;通关口岸有值才带。
|
||||
出站类型/线路译成 TMS 用的值,线路键名 routeCategory。工单与卡片仍用销售中文。
|
||||
中港整车、中港零担/集拼出站类型按细类原文传。中港整车带车型/数量;仅中港零担/集拼不带。
|
||||
中港整车、中港零担/集拼出站类型按细类原文传。中港整车带车型/数量;
|
||||
中港零担/集拼(销售侧中港集拼)带体积+毛重、不带车型(产品口径 2026-11-22)。
|
||||
禁止:把运输分类放进出站;直连 TMS;改六态。
|
||||
线程:纯函数。
|
||||
"""
|
||||
@@ -21,8 +22,11 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
LCL_TYPES = frozenset({"国内运输拼车", "跨境集拼"})
|
||||
FTL_TYPES = frozenset({"国内运输整车", "跨境整车", "中港整车"})
|
||||
# 仅中港零担/集拼:询价不采车型/数量,出站也不带。
|
||||
# 仅中港零担/集拼:询价不采车型/数量,但按体积与重量计费(产品口径 2026-11-22)。
|
||||
HK_NO_VEHICLE_TYPES = frozenset({"中港零担/集拼"})
|
||||
# 按「体积 + 毛重」查价的陆运类型:拼车、跨境集拼,加上中港集拼。
|
||||
# 中港集拼不采车型,但 TMS 计价要 volumeCbm/weightKg,所以并入同一套货物口径。
|
||||
VOLUME_WEIGHT_TYPES = LCL_TYPES | HK_NO_VEHICLE_TYPES
|
||||
HK_FTL_TYPE = "中港整车" # 兼容旧调用名;现与国内/跨境整车同属 FTL_TYPES
|
||||
CUSTOMS_TYPES = frozenset({"跨境集拼", "跨境整车", "中港整车", "中港零担/集拼"})
|
||||
|
||||
@@ -131,7 +135,8 @@ def assemble_land_query(facts: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"quoteDate": quote_date,
|
||||
}
|
||||
|
||||
if land_type in LCL_TYPES:
|
||||
if land_type in VOLUME_WEIGHT_TYPES:
|
||||
# 拼车/跨境集拼/中港集拼都按体积+毛重查价;中港集拼不采车型(见 HK_NO_VEHICLE_TYPES)。
|
||||
vol = _first_number(src.get("体积") or "")
|
||||
wgt = _first_number(src.get("毛重") or "")
|
||||
if not vol:
|
||||
@@ -142,9 +147,6 @@ def assemble_land_query(facts: dict[str, Any] | None) -> dict[str, Any]:
|
||||
missing.append("毛重")
|
||||
else:
|
||||
outbound["weightKg"] = wgt
|
||||
elif land_type in HK_NO_VEHICLE_TYPES:
|
||||
# 中港零担/集拼:不要车型/数量,也不改要体积毛重
|
||||
pass
|
||||
elif land_type in FTL_TYPES:
|
||||
combo = (
|
||||
src.get("车型/数量")
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
本文件职责:询价卡片出现前,确认海运十项里查出站项能拼出查价正文。
|
||||
港口只带名称,不做港口字典对应;箱型箱量保持原文字段,containerItems 只透传模型投影。
|
||||
贸易条款必带出站;运输分类只留在工单 facts,不进 tms_facts。
|
||||
拼柜(散货/LCL)不要求箱型箱量:按体积计费,承运人不指定箱型。
|
||||
海运提货地址/派送地址(内部键提货地址/收货地址)是非必填:有值就随 tms_facts 出站,
|
||||
不给门到门/门到港/港到门补地址、也不因缺地址拦查价(是否缺由 TMS 1002 回来说)。
|
||||
禁止:本地拆箱型;因对不上港口字典跳过 TMS;改六态。
|
||||
"""
|
||||
|
||||
@@ -13,7 +16,7 @@ import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from agent.schema.field_validate import apply_quote_date_default
|
||||
from agent.schema.field_validate import apply_quote_date_default, is_sea_lcl
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -68,16 +71,21 @@ def assemble_sea_query(facts: dict[str, Any] | None) -> dict[str, Any]:
|
||||
|
||||
missing: list[str] = []
|
||||
missing_display: list[str] = []
|
||||
# 拼柜(散货/LCL)按体积计费,承运人不指定箱型:箱型箱量不适用,
|
||||
# 不列入缺项(产品口径 2026-11-22)。已填的值仍保留在 facts 里,不删数据。
|
||||
lcl = is_sea_lcl(load)
|
||||
pairs = (
|
||||
("起运港", "起运港", origin),
|
||||
("目的港", "目的港", dest),
|
||||
("品名", "品名", cargo),
|
||||
("货量", "货物数量", qty),
|
||||
("整柜或拼柜", "整柜或拼柜", load),
|
||||
("箱型箱量", "箱型箱量", box),
|
||||
("贸易条款", "贸易条款", trade),
|
||||
("报价日期", "报价日期", quote_date),
|
||||
)
|
||||
if not lcl:
|
||||
# 整柜才要箱型;顺序保持原有位置(整柜或拼柜之后、贸易条款之前)。
|
||||
pairs = pairs[:5] + (("箱型箱量", "箱型箱量", box),) + pairs[5:]
|
||||
for key, label, val in pairs:
|
||||
if not val:
|
||||
missing.append(key)
|
||||
|
||||
Reference in New Issue
Block a user