协同群改为智价通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:
@@ -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"
|
||||
Reference in New Issue
Block a user