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