checkpoint: 提交当前工作区代码(同义词配置初版 + 既有流程改动)

- 新增 inq_synonym 表、62组同义词种子与智能体只读接口
- Python 同义词加载/归一化与 1板/2箱 机读
- 同步当前分支既有协作、报价识别、陆运等改动
This commit is contained in:
linmianxun
2026-11-24 16:26:49 +08:00
parent d9b2029c47
commit 04e00f0cfc
69 changed files with 7126 additions and 395 deletions
+460 -20
View File
@@ -964,6 +964,321 @@ def _patch_air_manual_side_fields(
return out
def confirm_pending_air_quote(flow: Any, ticket: object, message: Any) -> str:
"""
群里成员 @机器人 回「确认/确定」:把待确认的空运报价正式落账并出价格方案。
返回空串表示不是确认/没有待确认,调用方继续原流程。
只有航线岗能确认;其他人回确认只提示,不清待确认。
"""
from agent.policy.quote_confirm import (
can_confirm_quote,
is_confirm_text,
quote_confirm_enabled,
)
from agent.redis_coord.pending_quote_confirm import (
clear_pending_confirm,
load_pending_confirm,
)
if not quote_confirm_enabled():
return ""
no = ticket_no(ticket)
pending = load_pending_confirm(no)
if not pending or pending.get("kind") != "quote":
return ""
if not is_confirm_text(getattr(message, "content", "") or ""):
return ""
chat_id = getattr(message, "chat_id", "") or ""
sender_id = getattr(message, "sender_id", "") or ""
if not can_confirm_quote(flow, ticket, sender_id, business_line="AIR"):
send_group_text(group_client_of(flow), chat_id, "只有本单销售或产品/航线可以确认报价。")
return "confirm_not_allowed"
clear_pending_confirm(no)
quote = dict(pending.get("quote") or {})
raw = str(pending.get("raw_text") or "")
airline = str(pending.get("airline_override") or "").strip()
if airline:
quote["airlineCode"] = airline
quote["airline"] = airline
# 纠错过的线路(「改为KUL」)在确认时再写一次,确保出摘要用的是新目的港。
route = dict(pending.get("route_override") or {})
if route.get("dest"):
writer = getattr(flow.ledger, "update_facts", None)
if callable(writer):
patch = {"目的港": route["dest"], "目的地": route["dest"]}
if route.get("origin"):
patch.update({"起运港": route["origin"], "起运地": route["origin"]})
try:
writer(work_order_no=no, facts=patch)
except Exception:
logger.exception("空运报价确认写纠错线路失败 wo=%s", no)
ticket = current_ticket(flow, chat_id) or ticket
return _commit_quote(
flow,
ticket,
quote,
chat_id,
sender_id,
raw_text=raw,
raw_source="text",
)
_ROUTE_CHANGE_WORDS = (
"改为",
"改成",
"调整",
"换到",
"换成",
"航线",
"航司",
"航班",
"目的地",
"目的港",
"起运地",
"起运港",
"重量等级",
)
_AIR_CODE_BLOCK = frozenset(
{"USD", "CNY", "RMB", "HKD", "EUR", "JPY", "GBP", "KGS", "CBM", "AIR"}
)
# 纠错句里出现这些价格线索,才是改价/新报价;否则「比例改为1:200」「车型改为45HQ」
# 里的数字不能被当成空运费/运费。
_PRICE_CUES = (
"USD", "CNY", "RMB", "HKD", "EUR", "JPY", "GBP", "美元", "人民币", "港币",
"欧元", "日元", "英镑", "运费", "运输费", "空运费", "陆运费", "海运费",
"单价", "总价", "费用合计", "报价", "元", "块", "/kg", "/KG",
)
_CORRECT_VERBS = ("改为", "改成", "调整为", "调整成", "调到", "换成", "换到", "变为", "变成")
_AIR_CORRECT_LABELS = (
"比例", "泡比", "航线日期", "报价日期", "日期", "计费重", "件数", "毛重",
"重量", "体积", "包装", "品名", "增值服务", "服务",
)
def _is_air_field_correction(text: str) -> bool:
"""改的是比例/日期/计费重/件数毛重体积/包装/品名等字段,不是改价。"""
raw = text or ""
return (
any(v in raw for v in _CORRECT_VERBS)
and any(w in raw for w in _AIR_CORRECT_LABELS)
and not any(p in raw for p in _PRICE_CUES)
)
def _explicit_lock_text(text: str) -> bool:
"""这句话是不是明确在锁舱/释放舱位,不是报价纠错。"""
raw = text or ""
return any(w in raw for w in ("锁舱", "锁仓", "舱位", "释放", "取消舱位", "选舱"))
def _pending_air_route_origin(pending: dict[str, Any], facts: dict[str, str]) -> str:
"""待确认报价里的起运地:优先回执里的线路,再退回工单事实。"""
for item in pending.get("recognized") or []:
line = str(item or "")
if line.startswith("线路:"):
body = line[3:].split("(")[0]
if "-" in body:
return body.split("-")[0].strip()
if line.startswith("起运地:"):
return line[4:].strip()
return str(
facts.get("起运港") or facts.get("起运地") or facts.get("始发地") or ""
).strip()
def try_pending_air_correction(flow: Any, ticket: object, message: Any) -> str:
"""
待确认报价期间,产品发的「重量等级/比例/日期/航司/线路改了」这类纠错。
不跑锁舱分支(否则会误回「请销售先确认已成交」),也不把纠错里的数字当新报价;
一句里有多项纠错(如「重量等级改为+300,航司改为KUL」)会一次全部更新,
重发一份完整回执,继续等确认。返回空串表示不是纠错,调用方继续原流程。
"""
from agent.policy.quote_confirm import (
is_confirm_text,
quote_confirm_enabled,
sender_display_name,
)
from agent.redis_coord.pending_quote_confirm import (
load_pending_confirm,
save_pending_confirm,
)
if not quote_confirm_enabled():
return ""
raw = getattr(message, "content", "") or ""
if not raw.strip() or is_confirm_text(raw):
return ""
no = ticket_no(ticket)
pending = load_pending_confirm(no)
if not pending or pending.get("kind") != "quote":
return ""
if _explicit_lock_text(raw):
return ""
chat_id = getattr(message, "chat_id", "") or ""
client = group_client_of(flow)
at_name = sender_display_name(flow, ticket, getattr(message, "sender_id", "") or "")
book = getattr(flow, "ledger", None)
facts_writer = getattr(book, "update_facts", None) if book else None
facts = dict(ticket_view(ticket).get("facts") or {})
codes_all = [
c.upper()
for c in re.findall(
r"(?<![A-Za-z0-9])([A-Za-z]{2,3})(?![A-Za-z0-9])", raw
)
if c.upper() not in _AIR_CODE_BLOCK
]
codes3 = [c for c in codes_all if len(c) == 3]
airline_change = "航司" in raw or "航空公司" in raw
route_change = any(
w in raw for w in ("航线", "线路", "目的地", "目的港", "起运地", "起运港")
)
recognized = [str(x) for x in (pending.get("recognized") or [])]
quote = dict(pending.get("quote") or {})
facts_patch: dict[str, str] = {}
overrides: dict[str, Any] = {}
changed = False
def _replace_line(prefix: str, new_line: str, before: tuple[str, ...]) -> None:
nonlocal recognized
recognized = [x for x in recognized if not x.startswith(prefix)]
idx = next(
(i for i, x in enumerate(recognized) if any(x.startswith(p) for p in before)),
len(recognized),
)
recognized.insert(idx, new_line)
# 重量等级:「重量等级改为+300」
wb_hit = re.search(
r"(?:重量等级|等级)\s*(?:改为|改成|调整为|调整成|调到|变为|变成)\s*(\+?\d{2,4})",
raw,
)
if wb_hit:
val = wb_hit.group(1)
if not val.startswith("+"):
val = "+" + val
quote["weight_break"] = val
for row in quote.get("fee_rows") or []:
if isinstance(row, dict):
row["weight_break"] = val
_replace_line("重量等级:", f"重量等级:{val}", ("增值服务:", "航司:"))
overrides["weight_break_override"] = val
changed = True
# 比例:「比例改为1:200」
ratio_hit = re.search(
r"(?:比例|泡比)\s*(?:改为|改成|调整为|调整成|调到|换成|换到)\s*(\d+\s*[::]\s*\d+)",
raw,
)
if ratio_hit:
val = re.sub(r"\s+", "", ratio_hit.group(1)).replace(":", ":")
_replace_line("比例:", f"比例:{val}", ("重量等级:", "增值服务:", "航司:"))
facts_patch["比例"] = val
overrides["ratio_override"] = val
changed = True
# 日期:「航线日期改为11月25日」
date_hit = re.search(
r"(?:航线日期|报价日期|日期)\s*(?:改为|改成|调整为|调整成|调到|换成|换到)\s*"
r"(\d{1,2}\s*月\s*\d{1,2}\s*日|\d{4}[-/]\d{1,2}[-/]\d{1,2})",
raw,
)
if date_hit:
from agent.schema.field_validate import _harvest_quote_date
raw_date = date_hit.group(1)
val = _harvest_quote_date(raw_date) or raw_date
_replace_line("航线日期:", f"航线日期:{val}", ())
facts_patch["报价日期"] = val
overrides["date_override"] = val
changed = True
# 航司:「航司改为KUL」——KUL 不是常见航司码也照收,按原话更新。
if airline_change:
airline = ""
hit = re.search(
r"(?:航司|航空公司)[^\n]{0,12}?([A-Za-z]{2,3})(?![A-Za-z0-9])", raw
)
if hit:
airline = hit.group(1).upper()
elif codes_all:
airline = codes_all[-1]
if airline in _AIR_CODE_BLOCK:
airline = ""
if airline:
quote["airlineCode"] = airline
quote["airline"] = airline
_replace_line("航司:", f"航司:{airline}", ("线路:", "航线日期:"))
overrides["airline_override"] = airline
changed = True
# 线路/目的地:「目的地改为KUL」
if route_change:
origin, dest = _harvest_air_manual_route_airports(raw)
if not (origin and dest):
dest = codes3[-1] if codes3 else ""
origin = _pending_air_route_origin(pending, facts)
if dest:
route_line = f"线路:{origin}-{dest}" if origin else f"目的地:{dest}"
_replace_line("线路:", route_line, ("航线日期:",))
recognized = [x for x in recognized if not x.startswith("目的地:")]
facts_patch["目的港"] = dest
facts_patch["目的地"] = dest
if origin:
facts_patch["起运港"] = origin
facts_patch["起运地"] = origin
overrides["route_override"] = {"origin": origin, "dest": dest}
changed = True
if not changed:
# 未支持的字段纠错先提示;带价的新报价交给 apply_air_quote 覆盖旧待确认。
if _is_air_field_correction(raw):
send_group_text(
client,
chat_id,
"请先确认上一条报价,或按标准格式重新报价。",
)
return "quote_pending_hint"
if extract_product_quote(raw, business_line="AIR", transport_mode="空运"):
return ""
if any(w in raw for w in _ROUTE_CHANGE_WORDS):
send_group_text(
client,
chat_id,
"请先确认上一条报价,或按标准格式重新报价。",
)
return "quote_pending_hint"
return ""
updated = dict(pending)
updated["quote"] = quote
updated["recognized"] = recognized
updated.update(overrides)
updated["raw_text"] = (
str(pending.get("raw_text") or "").strip() + "\n" + raw.strip()
).strip()
save_pending_confirm(no, updated)
if facts_patch and callable(facts_writer):
try:
facts_writer(work_order_no=no, facts=facts_patch)
except Exception:
logger.exception("空运报价纠错写字段失败 wo=%s", no)
send_group_text(
client,
chat_id,
copy.quote_partial_recognized(
recognized,
[],
business_line="AIR",
work_order_no=no,
at_name=at_name,
),
)
return "quote_confirm_pending"
def apply_air_quote(
*,
flow: Any,
@@ -991,6 +1306,7 @@ def apply_air_quote(
flow.ledger.patch_collab_facts(work_order_no=no, facts=fields, sender_id=sender_id)
view = ticket_view(ticket)
current = dict(view.get("quote") or {})
facts = dict(view.get("facts") or {})
from agent.policy.sea_group_ops import _quote_currency_hint
quote = injected_quote or extract_product_quote(
@@ -1011,31 +1327,136 @@ def apply_air_quote(
quote["source_label"] = "航线报价"
elif "产品" in str(quote.get("source_label") or ""):
quote["source_label"] = "航线报价"
# 识别程度:完整 / 部分 / 全无。产品 2026-11-24:原话里能认到的字段尽量都识别。
from agent.llm.extract_text import extract_inquiry_snapshot
from agent.schema.air_chargeable import (
format_kg,
harvest_declared_chargeable,
with_kg_unit,
)
from agent.schema.quote_recognition import inspect_quote_recognition
snap_facts = dict(
(extract_inquiry_snapshot(text, allow_b=False) or {}).get("facts") or {}
)
extra_facts: dict[str, str] = {}
for key in ("件数", "毛重", "体积", "包装方式", "品名", "是否为危险品"):
val = str(snap_facts.get(key) or "").strip().strip(",,;;。")
if val:
extra_facts[key] = val
extra_facts.update(extract_air_collab_fields(text))
declared = harvest_declared_chargeable(text)
if declared is not None:
extra_facts["计费重"] = with_kg_unit(format_kg(declared))
writer = getattr(flow.ledger, "update_facts", None)
if callable(writer):
patch = {
k: v
for k, v in extra_facts.items()
if k in ("件数", "毛重", "体积", "包装方式", "品名", "是否为危险品")
}
if patch:
try:
writer(work_order_no=no, facts=patch)
except Exception:
logger.exception("空运报价补询价字段失败 wo=%s", no)
recognition = inspect_quote_recognition(
text,
quote,
business_line="AIR",
transport_mode="空运",
facts=facts,
extra_facts=extra_facts,
)
from agent.policy.quote_confirm import sender_display_name
at_name = sender_display_name(flow, ticket, sender_id)
if not quote:
if is_handoff_collab(flow, ticket):
# 转人工:产品可能发的是「一个40HQ 2800美金含码头费」这类非模板话术。
# 解析不出金额不能编,但原话必须留档;六态保持询价中,等产品补标准报价。
flow.ledger.upsert_product_quote(
work_order_no=no,
quote={"raw_text": (text or "").strip()},
to_status="询价中",
raw_text=text,
raw_source="nonstandard",
# 非模板话术:产品可能发的是「一个40HQ 2800美金含码头费」这类话。
# 解析不出金额不能编,但原话必须留档;六态保持询价中,再按格式提示重报。
flow.ledger.upsert_product_quote(
work_order_no=no,
quote={"raw_text": (text or "").strip()},
to_status="询价中",
raw_text=text,
raw_source="nonstandard",
sender_id=sender_id,
)
if recognition["status"] == "partial":
send_group_text(
client,
chat_id,
copy.quote_partial_recognized(
recognition["recognized"],
recognition["missing"],
business_line="AIR",
work_order_no=no,
at_name=at_name,
),
)
send_group_text(client, chat_id, copy.handoff_raw_quote_saved(work_order_no=no))
return "quote_raw_saved"
send_group_text(client, chat_id, copy.air_quote_not_recognized())
return "quote_empty"
return "quote_partial_saved"
send_group_text(
client,
chat_id,
copy.quote_not_recognized(business_line="AIR", at_name=at_name),
)
return "quote_raw_saved"
if _has_tms_quote(current) and not _is_product_quote(current):
_park_air_pending(flow, no, quote, sender_id)
send_group_text(client, chat_id, copy.group_ask_tms_or_product())
return "wait_tms_choice"
# 产品 2026-11-24:报价先回识别回执,成员@机器人回「确认/确定」后才出价格方案。
from agent.policy.quote_confirm import quote_confirm_enabled
from agent.redis_coord.pending_quote_confirm import save_pending_confirm
if quote_confirm_enabled():
save_pending_confirm(
no,
{
"kind": "quote",
"quote": dict(quote),
"raw_text": text,
"raw_source": "text",
"line": "AIR",
"recognized": list(recognition["recognized"]),
"chat_id": chat_id,
"sender_id": sender_id,
},
)
send_group_text(
client,
chat_id,
copy.quote_partial_recognized(
recognition["recognized"],
[],
business_line="AIR",
work_order_no=no,
at_name=at_name,
),
)
return "quote_confirm_pending"
from agent.schema.quote_adjust import quote_fee_rows
if quote_fee_rows(current):
quote = merge_quote_fees(current, quote)
note = ""
if recognition["status"] == "partial":
note = copy.quote_partial_recognized(
recognition["recognized"],
recognition["missing"],
business_line="AIR",
work_order_no=no,
at_name=at_name,
)
return _commit_quote(
flow, ticket, quote, chat_id, sender_id, raw_text=text, raw_source="text"
flow,
ticket,
quote,
chat_id,
sender_id,
raw_text=text,
raw_source="text",
recognition_note=note,
)
@@ -1064,11 +1485,19 @@ def apply_air_file(
if stopped:
return stopped
if not filename_is_excel_pdf(filename):
# 与海运同口径(2026-11-19 真机):不 @BOT 的 Word/zip 不搭话。
# 文件名带工单号才说明对方是想归到某张单,才提示「只收 Excel/PDF」。
# 2026-11-21:明确 @ 过机器人时也一定提示,不能让人干等。
# 产品 2026-11-24:图片/其它文件不能读,按「无法识别」提示用文字重报。
if explicit or copy.extract_work_order_no(filename or ""):
send_group_text(client, chat_id, copy.group_only_excel_pdf())
from agent.policy.quote_confirm import sender_display_name
send_group_text(
client,
chat_id,
copy.quote_not_recognized(
business_line="AIR",
at_name=sender_display_name(flow, ticket, sender_id),
text_format=True,
),
)
else:
logger.info("air_file_type_silent wo=%s file=%s", no or "-", (filename or "")[:80])
return "file_type_rejected"
@@ -1090,6 +1519,7 @@ def apply_air_file(
to_status="已报价",
raw_text=filename,
raw_source="file",
sender_id=sender_id,
) or {}
if not saved.get("ok"):
send_group_text(client, chat_id, "主账写入报价失败。")
@@ -1180,7 +1610,12 @@ def apply_air_confirm_tms(*, flow: Any, ticket: object, sender_id: str, chat_id:
sheet_quote = _sheet_quote_with_tms_sale_total(
quote, tms=quote, facts=dict(view.get("facts") or {})
)
saved = flow.ledger.upsert_product_quote(work_order_no=no, quote=sheet_quote, to_status="已报价") or {}
saved = flow.ledger.upsert_product_quote(
work_order_no=no,
quote=sheet_quote,
to_status="已报价",
sender_id=sender_id,
) or {}
if not saved.get("ok"):
send_group_text(group_client_of(flow), chat_id, "主账写入报价失败。")
return "ledger_fail"
@@ -1709,6 +2144,7 @@ def _commit_quote(
tms_quote: Optional[dict[str, Any]] = None,
raw_text: str = "",
raw_source: str = "",
recognition_note: str = "",
) -> str:
"""
报价落定:写入主账,重发摘要,再出成交跟进;不自动发 Excel/PDF。
@@ -1721,7 +2157,6 @@ def _commit_quote(
补进报价对象、把 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
@@ -1734,6 +2169,7 @@ def _commit_quote(
to_status="已报价",
raw_text=raw_text,
raw_source=raw_source,
sender_id=sender_id,
)
if not up.get("ok"):
send_group_text(group_client_of(flow), chat_id, "主账写入报价失败。")
@@ -1741,6 +2177,10 @@ def _commit_quote(
from agent.policy.event_exception import clear_wait
clear_wait(flow.ledger, work_order_no=no)
# 部分识别回执放在价已入账之后、摘要/成交跟进之前:
# 产品先看到「我识别内容为…」,成交卡仍是最新一条,不会被回执顶上去。
if (recognition_note or "").strip():
send_group_text(group_client_of(flow), chat_id, recognition_note)
ticket2 = current_ticket(flow, chat_id) or ticket
view = ticket_view(ticket2)
view["collab_chat_id"] = chat_id
@@ -300,6 +300,33 @@ def has_collab_group(sess: Any) -> bool:
return bool(str(getattr(sess, "collab_chat_id", "") or "").strip())
def chat_serves_work_order(ledger: Any, chat_id: str, work_order_no: str) -> bool:
"""
这个群是否确实在服务这张工单。
书签按销售存,上一单的群会被带到下一单;复用它会把本单的 BOT 业务线写进
别人的群(陆运标记写到空运群),之后群消息全部走错 handler,解散语也会串群。
主账查不到绑定(老群/绑群失败)时按原逻辑放行,不能凭猜拦截正常复用。
"""
chat = (chat_id or "").strip()
no = (work_order_no or "").strip().upper()
if not chat or not no:
return True
finder = getattr(ledger, "find_by_collab_chat", None)
if not callable(finder):
return True
try:
hit = finder(chat_id=chat)
except Exception:
logger.exception("校验协同群归属失败 chat=%s", chat)
return True
if hit is None:
return True
from agent.policy.sea_group_ops import ticket_no
return (ticket_no(hit) or "").strip().upper() == no
def transport_label(business_line: str) -> str:
code = (business_line or "").strip().upper()
return {"SEA": "海运", "AIR": "空运", "LAND": "陆运"}.get(code, "")
+266 -79
View File
@@ -122,6 +122,12 @@ _SEA_CLARIFY = tuple(
# 文字按钮(销售点卡或原样回复均可)
BTN_SKIP_COLLAB = "不需要协同,直接生成报价单"
# 模板卡主标题:企微 button_interaction 强制要求 main_title.title,留空会 40058 回落成文字。
# 产品口径(2026-11-23):不再把工单号重复一遍,价格卡只写「价格明细」,
# 无价卡只写结论「未查到合适报价」。
CARD_PRICE_TITLE = "价格明细"
CARD_MISS_TITLE = "未查到合适报价"
CARD_SCHEME_TITLE = "报价方案"
BTN_SKIP_COLLAB_OLD = "不需要协同,直接生成基础报价单"
# 海运/陆运已有 TMS 报价时价格明细卡用短文案;空运仍用上面长文案。点卡 EventKey 不变。
BTN_SKIP_COLLAB_TMS = "直接生成报价单"
@@ -424,20 +430,77 @@ def _land_cargo_keys(land_type: str, facts: dict[str, str] | None = None) -> tup
return _LAND_LCL_KEYS
def land_biz_scenario_labels(
facts: dict[str, str] | None,
*,
biz_type_label: str = "",
quote_scenario: str = "",
) -> tuple[str, str]:
"""
陆运汇总里的「业务类型 / 报价场景」两项,取卡片按钮文字。
产品口径(2026-11-23):汇总信息不再对销售展示内部的运输类型/线路类别/运输分类,
统一说卡片上的业务类型和报价场景。内部三项仍要留给 TMS、模板和超时编码用。
取值顺序(认不到就不猜):
业务类型:调用方带下来的标签 → 会话事实「陆运业务类型」→
运输类型+线路类别配对反查 → 运输类型唯一命中(历史单只有类型时)
报价场景:调用方带下来的标签 → 会话事实「报价场景」→ 运输分类收回标准场景
返回空串表示这一项还没选,由调用方决定写「-」还是省略。不修改入参。
"""
from agent.schema.handoff_options import (
BUSINESS_TYPES,
biz_by_key,
biz_for_pair,
scenario_by_key,
)
from agent.schema.land_options import (
canonicalize_land_biz,
canonicalize_land_class,
canonicalize_route,
canonicalize_transport_type,
)
src = dict(facts or {})
biz = biz_by_key((biz_type_label or "").strip())
if biz is None:
# 历史事实可能存产品全称(中港/中亚/中欧整车),先收回卡面简写再认。
biz = biz_by_key(
canonicalize_land_biz(str(src.get("陆运业务类型") or ""))
)
if biz is None:
transport = canonicalize_transport_type(str(src.get("运输类型") or ""))
route = canonicalize_route(str(src.get("线路类别") or ""))
biz = biz_for_pair(transport, route)
if biz is None and transport:
# 旧单只留了运输类型:能把 7 项唯一收窄的才认,国内整车/城配无法区分就不猜。
hits = [b for b in BUSINESS_TYPES if b.transport_type == transport]
if len(hits) == 1:
biz = hits[0]
scenario = scenario_by_key((quote_scenario or "").strip())
if scenario is None:
scenario = scenario_by_key(str(src.get("报价场景") or ""))
if scenario is None:
scenario = scenario_by_key(
canonicalize_land_class(str(src.get("运输分类") or ""))
)
return (biz.label if biz is not None else "", scenario.label if scenario is not None else "")
def land_confirm_card(facts: dict[str, str] | None) -> str:
"""
确定查价前的核对卡。没有工单号。
行列出运输类型/线路/分类和该类型货物字段。
行列出业务类型/报价场景(与补问卡按钮一致)和该类型货物字段。
国内不出现通关口岸;跨境/中港通关口岸非必填,没填留空行。
不再单独列出中港装载方式。
"""
src = dict(facts or {})
land_type = (src.get("运输类型") or "").strip()
biz_label, scenario_label = land_biz_scenario_labels(src)
lines = [
f"运输类型(必填):{land_type}",
f"线路类别(必填):{(src.get('线路类别') or '').strip()}",
f"运输分类(必填):{(src.get('运输分类') or '').strip()}",
f"业务类型(必填):{biz_label}",
f"报价场景(必填):{scenario_label}",
]
for key in _land_cargo_keys(land_type, src):
label = LAND_DISPLAY.get(key, key)
@@ -572,13 +635,14 @@ def ask_land_fields(
missing = ["品名"] + [k for k in missing if k != "品名"]
land_type = (land_subtype or src.get("运输类型") or "").strip()
optional = _land_optional_keys(land_type)
# 产品口径(2026-11-23):汇总只出现卡片上的业务类型/报价场景,
# 内部运输类型、线路类别、运输分类不再对销售展示。
biz_label, scenario_label = land_biz_scenario_labels(src)
lines = ["请确认并补充以下信息:", "运输方式:陆运"]
if land_type:
lines.append(f"运输类型:{land_type}")
for key in ("线路类别", "运输分类"):
val = (src.get(key) or "").strip()
if val:
lines.append(_land_field_line(key, val, required=True))
if biz_label:
lines.append(f"业务类型(必填):{biz_label}")
if scenario_label:
lines.append(f"报价场景(必填):{scenario_label}")
for key in _land_cargo_keys(land_type, src):
if key == "品名":
val = land_cargo_name(src)
@@ -985,12 +1049,13 @@ def inquiry_field_lines(
return lines
if mode == "陆运":
land_type = (facts.get("运输类型") or "").strip()
# 产品口径(2026-11-23):群摘要与核对卡同一套字段,只写业务类型/报价场景。
biz_label, scenario_label = land_biz_scenario_labels(facts)
lines = [
f"工单号:{work_order_no}",
f"运输方式:{transport_mode}",
f"运输类型:{land_type or '-'}",
f"线路类别:{(facts.get('线路类别') or '-').strip() or '-'}",
f"运输分类:{(facts.get('运输分类') or '-').strip() or '-'}",
f"业务类型:{biz_label or '-'}",
f"报价场景:{scenario_label or '-'}",
]
for key in _land_cargo_keys(land_type, facts):
label = LAND_DISPLAY.get(key, key)
@@ -2301,7 +2366,10 @@ def quote_detail_lines(
if note:
lines.append(note)
if not _is_air_surface(business_line=business_line, transport_mode=transport_mode):
lines.append(f"时效:{tms_eta_display(src)}")
# 陆运分段费用里已经写了该段时效时,合计后再写同一条就是重复。
eta_line = f"时效:{tms_eta_display(src)}"
if eta_line not in lines:
lines.append(eta_line)
lines.append(f"报价有效期:{tms_valid_until_display(src)}")
return lines
@@ -2388,39 +2456,25 @@ def tms_hit_wecom_payload(
status: str = "已报价",
) -> dict[str, Any]:
"""
一张价格卡,销售侧顺序:
一张价格卡,销售侧只剩卡片名称 + 协同说明 + 按钮。
价格明细
┌ 引用条:空运费 / 其它费用 / 总销售价
报价有效期(空运不写时效)
协同说明(普通文字,贴按钮上方)
按钮
产品口径(2026-11-23):卡片名称「TMS标准报价」保留;主标题只留「价格明细」,
不再带工单号;引用条(费用合计/共几项)和报价有效期不再展示——价格明细
文字已在上一条,卡片重复一遍就是冗余。企微 button_interaction 强制要求
main_title.title,留空会 40058 回落成文字,所以这里必须给短标题。
相同询价内容检索对销售隐藏;first_or_same 只兼容调用方,不展示。
企微 quote_area.title 只能很短,超长会被整段藏掉。报价必须放 quote_text。
不用 horizontal:它会排到副标题后面,把费用挤到按钮前。
"""
_ = first_or_same, history_work_order_no
src = dict(quote or {})
source = str(src.get("source_label") or "TMS标准报价").replace(" ", "")
meta = "\n".join(
[
f"报价有效期:{tms_valid_until_display(src)}",
"",
collab_hint(work_order_no),
]
)
return {
"msgtype": "template_card",
"template_card": {
"card_type": "button_interaction",
"source": {"desc": source, "desc_color": 0},
"main_title": {"title": f"{work_order_no}价格明细"},
"quote_area": {
"type": 0,
"quote_text": quote_area_safe_text(src, business_line="AIR"),
},
"sub_title_text": meta,
"main_title": {"title": CARD_PRICE_TITLE},
"sub_title_text": collab_hint(work_order_no),
"task_id": card_task_id("quote", work_order_no),
"button_list": [
{
@@ -2559,8 +2613,10 @@ def tms_miss_wecom_payload(
"""
TMS 已查过、确认没价:一张文本通知卡(对齐现网图)。
询价工单号 / 灰字无价说明 / 建单说明 / 工单状态与查价结果。
不要「来源」行、不要按钮。企微 text_notice 必须带可信域名 card_action。
产品口径(2026-11-23):卡片名称「TMS查价结果」保留;主标题只写结论
「未查到合适报价」,不再重复工单号和 missingFields 原因——工单号在上一条消息里,
原因在「查价结果」一行里,卡片头再重复一遍是冗余。只留建单说明、两行状态和跳转。
不要按钮。企微 text_notice 必须带可信域名 card_action。
copy_url 忽略:不再跳复制页。
reason 为 TMS 回包 remark 原文(如「陆运报价条件无法匹配系统字典,请修正后重试」),
有值时「查价结果」直接展示它;没有才写「暂无匹配报价」。
@@ -2570,10 +2626,7 @@ def tms_miss_wecom_payload(
card: dict[str, Any] = {
"card_type": "text_notice",
"source": {"desc": "TMS查价结果", "desc_color": 0},
"main_title": {
"title": f"询价工单 {no}",
"desc": tms_miss_hint(),
},
"main_title": {"title": CARD_MISS_TITLE},
"sub_title_text": tms_miss_body(),
"horizontal_content_list": [
{"keyname": "工单状态", "value": "询价中"},
@@ -2611,9 +2664,13 @@ def sea_collab_ask() -> str:
return "是否拉产品人员进群协同?"
# 无价卡协同问句去掉「未查到合适报价」前缀的版本:主标题已经写了结论,副标题不再重复。
MISS_ASK_PLAIN = "是否需要拉内部产品人员进群,进行手工协同报价?"
def sea_miss_ask() -> str:
"""海运无价卡协同问句。"""
return "未查到合适报价,是否需要拉内部产品人员进群,进行手工协同报价?"
return "未查到合适报价," + MISS_ASK_PLAIN
def sea_tms_hit_card(
@@ -2654,14 +2711,19 @@ def sea_tms_hit_wecom_payload(
status: str = "已报价",
business_line: str = "SEA",
) -> dict[str, Any]:
"""海运/陆运有价企微卡:价格明细 + 问句 + 拉群 / 跳过协同。"""
_ = first_or_same, history_work_order_no, status
"""
海运/陆运有价企微卡:卡片名称 + 时效 + 问句 + 拉群 / 跳过协同。
与空运同口径(2026-11-23):卡片名称保留;主标题只留「价格明细」;费用合计
引用条、报价有效期不再展示,完整明细在上一条文字里。海运/陆运的时效不在
明细文字里,保留。企微 button_interaction 强制要求 main_title.title。
"""
_ = first_or_same, history_work_order_no, status, business_line
src = dict(quote or {})
source = str(src.get("source_label") or "TMS标准报价").replace(" ", "")
meta = "\n".join(
[
f"时效:{tms_eta_display(src)}",
f"报价有效期:{tms_valid_until_display(src)}",
"",
sea_collab_ask(),
]
@@ -2671,11 +2733,7 @@ def sea_tms_hit_wecom_payload(
"template_card": {
"card_type": "button_interaction",
"source": {"desc": source, "desc_color": 0},
"main_title": {"title": f"{work_order_no}价格明细"},
"quote_area": {
"type": 0,
"quote_text": quote_area_safe_text(src, business_line=business_line or "SEA"),
},
"main_title": {"title": CARD_PRICE_TITLE},
"sub_title_text": meta,
"task_id": card_task_id("quote", work_order_no),
"button_list": [
@@ -2713,10 +2771,13 @@ def sea_tms_miss_wecom_payload(
*, work_order_no: str, action_url: str = "", reason: str = ""
) -> dict[str, Any]:
"""
海运/陆运无价一张卡:工单号、暂无匹配、询价中、拉群问句、一个按钮。
海运/陆运无价一张卡:建单说明、拉群问句、状态两行、一个按钮。
产品口径(2026-11-23):卡片名称「TMS查价结果」保留;主标题只写结论
「未查到合适报价」,不再重复工单号和 missingFields 原因(原因在「查价结果」行里)。
企微 button_interaction 强制要求 main_title.title,不能留空。
禁止再写「请手动拉人到原有群」。
reason 为 TMS 回包 remark 原文:有值时标题下与「查价结果」都展示它,
reason 为 TMS 回包 remark 原文:「查价结果」直接展示它,
销售能直接看到「目的地无法匹配系统地址编码」这类原因,而不是只有一句无价。
"""
no = (work_order_no or "").strip()
@@ -2724,14 +2785,11 @@ def sea_tms_miss_wecom_payload(
card: dict[str, Any] = {
"card_type": "button_interaction",
"source": {"desc": "TMS查价结果", "desc_color": 0},
"main_title": {
"title": f"询价工单 {no}",
"desc": result,
},
"main_title": {"title": CARD_MISS_TITLE},
"sub_title_text": "\n".join(
[
"需求已解析并创建工单。",
sea_miss_ask(),
MISS_ASK_PLAIN,
]
),
"horizontal_content_list": [
@@ -2755,6 +2813,8 @@ def sea_tms_miss_wecom_payload(
MULTI_CONFIRM_TAIL = "请回复「确定」创建工单,内容有误时,请重新发内容。"
MULTI_SAME_MODE = "同一运输方式出现了两段,请拆开再发。"
# 多段补问里陆运的业务类型/报价场景改由卡片收集;正文只留这一句点卡提示。
MULTI_LAND_OPTIONS_ON_CARD = "业务类型、报价场景请在卡片中点选,选好后点「提交选项」。"
# 核对卡已取消时效,不再对销售发送此句。
MULTI_CONFIRM_EXPIRED = "刚才的多段核对已过期,请把多段需求再发一次,出核对后再回复确定。"
@@ -2981,7 +3041,8 @@ def handoff_group_brief(
biz_type_label / quote_scenario:陆运卡片带下来的业务类型与报价场景。
这两项只有陆运卡才有:海运/空运摘要里出现「业务类型:-、报价场景:-」,
产品会以为是漏填,所以非陆运一律不输出这两行(2026-11 真机反馈)。
quote_deadline:陆运卡片的报价时效(如「2小时」);海空运不传,不显示该行。
陆运的这两行由 inquiry_field_lines 与其余询价字段排在一起;
`quote_deadline`(如「2小时」)另起一行,海空运不传则不显示。
"""
from agent.policy.handoff_human import collab_keys_for_handoff, transport_label
from agent.schema.field_validate import collab_display_name
@@ -3002,6 +3063,13 @@ def handoff_group_brief(
names.append(n.strip())
at = " ".join(f"@{n}" for n in names)
src = dict(facts or {})
if line == "LAND":
# 卡片带下来的两项优先:建单时主账事实可能还没回写,摘要要按销售刚选的显示。
# 写进 src 供 inquiry_field_lines 统一取业务类型/报价场景两行。
if (biz_type_label or "").strip():
src["陆运业务类型"] = biz_type_label.strip()
if (quote_scenario or "").strip():
src["报价场景"] = quote_scenario.strip()
field_lines = inquiry_field_lines(work_order_no=no, facts=src, transport_mode=mode)
body = field_lines[1:] if field_lines else []
lines: list[str] = []
@@ -3010,13 +3078,9 @@ def handoff_group_brief(
lines.append(f"{no}转人工")
lines.append("询价字段:")
lines.extend(body)
if line == "LAND":
# 只有陆运卡片才有业务类型/报价场景;海运、空运出这两行会让产品以为漏填。
if line == "LAND" and (quote_deadline or "").strip():
lines.append("")
lines.append(f"业务类型:{(biz_type_label or '').strip() or '-'}")
lines.append(f"报价场景:{(quote_scenario or '').strip() or '-'}")
if (quote_deadline or "").strip():
lines.append(f"报价时效:{quote_deadline.strip()}")
lines.append(f"报价时效:{quote_deadline.strip()}")
lines.append("")
lines.append("协同补充字段:")
for key in collab_keys_for_handoff(src, line):
@@ -3616,12 +3680,14 @@ def scheme_wecom_payload(
transport_mode: str = "空运",
) -> dict[str, Any]:
"""
一张报价方案卡:标题带工单号、引用条、字段、三个短按钮。
一张报价方案卡:只留卡片名称 + 短标题 + 三个按钮。
产品口径(2026-11-24):工单号、费用合计引用条和全部字段行都不再在卡上重复,
完整信息在上一条报价明细文字里。企微 button_interaction 强制要求
main_title.title,所以保留短标题「报价方案」。
按钮文案必须短:生成Excel / 生成PDF / 不采用。长文案横排会被裁。
海运/空运/陆运字段分开,禁止陆运卡再出箱型或空运件数包装。
"""
_ = status
_ = status, facts, transport_mode
src = dict(quote or {})
source = str(src.get("source_label") or "TMS标准报价").replace(" ", "")
return {
@@ -3629,18 +3695,7 @@ def scheme_wecom_payload(
"template_card": {
"card_type": "button_interaction",
"source": {"desc": source, "desc_color": 0},
"main_title": {"title": f"{work_order_no}报价方案"},
"quote_area": {
"type": 0,
# 空运/海运/陆运引用条一律只留总价,费用在上一条明细。
"quote_text": quote_area_safe_text(src, transport_mode=transport_mode),
},
"horizontal_content_list": scheme_horizontal_rows(
work_order_no=work_order_no,
facts=facts,
quote=src,
transport_mode=transport_mode,
),
"main_title": {"title": CARD_SCHEME_TITLE},
"task_id": card_task_id("scheme", work_order_no),
"button_list": [
{
@@ -3688,6 +3743,85 @@ def adjust_ledger_remark(applied: list[dict[str, Any]]) -> str:
return "销售调价:" + (";".join(bits) if bits else "已改价")
# 销售调价的格式样例:产品 2026-11-23 要求调价也走「识别到部分/全无」提示。
ADJUST_FORMAT_HINT = (
"费用名+调整方式,例如“海运费上调10%”“报关费改为300CNY”或“总价改为18000”"
)
def adjust_partial_recognized(
recognized: list[str] | tuple[str, ...],
missing: list[str] | tuple[str, ...] = (),
) -> str:
"""调价只识别到一部分:列已识别内容 + 缺项 + 格式样例。"""
lines = ["我识别内容为:"]
lines.extend(str(x).strip() for x in (recognized or []) if str(x).strip())
if missing:
lines.append("未识别:" + "、".join(str(x).strip() for x in missing if str(x).strip()))
lines.append("请确认是否正确;请按格式调整报价:")
lines.append(ADJUST_FORMAT_HINT)
return "\n".join(lines)
def adjust_not_recognized() -> str:
"""调价完全认不出:给格式样例让销售重发。"""
return "我无法识别您的内容,请按格式调整报价:\n" + ADJUST_FORMAT_HINT
def adjust_confirm_not_allowed() -> str:
"""不是发起调价的销售、也不是产品/航线,不能点确认。"""
return "只有发起调价的销售或产品/航线可以确认。"
def _adjust_item_how(item: dict[str, Any]) -> str:
"""调价项的中文说法:上调10% / 改为300 / 改为原价的110%。"""
kind = str(item.get("kind") or "percent").strip()
direction = str(item.get("direction") or "up").strip()
raw_value = item.get("value")
try:
num = float(raw_value)
num_text = str(int(num)) if num == int(num) else f"{num:g}"
except (TypeError, ValueError):
num_text = str(raw_value or "").strip()
if kind == "percent":
if direction == "down":
return f"下调{num_text}%"
if direction == "set":
return f"改为原价的{num_text}%"
return f"上调{num_text}%"
if direction == "set":
return f"改为{num_text}"
if direction == "down":
return f"减少{num_text}"
return f"增加{num_text}"
def adjust_confirm_receipt(
items: list[dict[str, Any]] | tuple[dict[str, Any], ...],
*,
work_order_no: str = "",
) -> str:
"""
调价先回识别回执,等成员确认后再改价(产品 2026-11-24 口径)。
例:
WO202611240001 我识别内容为:
海运费:上调10%
请确认是否正确。
"""
no = str(work_order_no or "").strip()
lines = [f"{no} 我识别内容为:" if no else "我识别内容为:"]
for item in items or []:
if not isinstance(item, dict):
continue
name = str(item.get("fee_name") or item.get("name") or "").strip() or "费用合计"
lines.append(f"{name}:{_adjust_item_how(item)}")
if len(lines) == 1:
lines.append("调价内容:未识别")
lines.append("请确认是否正确。")
return "\n".join(lines)
def adjust_need_fee() -> str:
return "请说明要调哪一项费用明细,例如「提货费加 10%」。只说报价或总价,系统不会改价。"
@@ -3997,6 +4131,59 @@ def group_quote_not_recognized() -> str:
return "没有识别到报价,请产品再发一次价格或 Excel/PDF"
def quote_partial_recognized(
recognized: list[str] | tuple[str, ...],
missing: list[str] | tuple[str, ...] = (),
*,
business_line: str = "",
work_order_no: str = "",
at_name: str = "",
) -> str:
"""
产品 2026-11-23:只识别到一部分时的回执。
结构固定:工单号 +「我识别内容为」,最后请产品确认(产品 2026-11-24)。
部分识别不重复贴格式样例,也不显示「未识别」缺项;
missing 仍由 inspect_quote_recognition 返回给流程判断用,这里不拼进群消息。
business_line 参数保留是为了调用方统一,不再参与拼句。
副作用:无。线程:纯函数。
"""
_ = business_line
_ = missing
no = str(work_order_no or "").strip()
lines: list[str] = []
at = str(at_name or "").strip()
if at:
# 产品 2026-11-24:回执要 @ 当前报价人员,避免他 @ 了存档席看不到要确认。
lines.append(f"@{at}")
lines.append(f"{no} 我识别内容为:" if no else "我识别内容为:")
lines.extend(str(x).strip() for x in (recognized or []) if str(x).strip())
lines.append("请确认是否正确。")
return "\n".join(lines)
def quote_not_recognized(
*, business_line: str = "", at_name: str = "", text_format: bool = False
) -> str:
"""
产品 2026-11-23:整句完全认不出时的回执。
原话仍会留档到工单「原始报价参考」,六态保持询价中;
群里只回格式样例(产品 2026-11-23 晚确认不再附留档说明)。
at_name:当前报价人员,回执第一行 @ 他,避免漏看。
副作用:无。线程:纯函数。
"""
from agent.schema.quote_recognition import quote_format_hint
at = f"@{str(at_name).strip()}\n" if str(at_name or "").strip() else ""
intro = (
"我无法识别您的内容,请按文字格式重新报价:\n"
if text_format
else "我无法识别您的内容,请按以下格式重新报价:\n"
)
return at + intro + f"{quote_format_hint(business_line)}"
def group_fields_not_recognized(
keys: tuple[str, ...] | None = None,
business_line: str = "",
@@ -1259,6 +1259,7 @@ class LandTextInquiryFlow(SeaTextInquiryFlow):
"""
from agent.policy.handoff_human import (
COLLAB_MODE_HANDOFF,
chat_serves_work_order,
ensure_formal_ticket_for_handoff,
is_virtual_no,
)
@@ -1275,6 +1276,19 @@ class LandTextInquiryFlow(SeaTextInquiryFlow):
# ① 幂等:已有群就直接回执。重复点提交/连点都不能建出第二个群。
existing = (sess.collab_chat_id or "").strip()
if existing and not chat_serves_work_order(
self._ledger,
existing,
(sess.handoff_work_order_no or sess.work_order_no or "").strip(),
):
# 书签上的群是另一张单的:复用会把陆运 BOT 标记写到空运群,之后整群消息走错 handler。
logger.warning(
"陆运转人工旧群不属于本单,改新建 chat=%s wo=%s",
existing,
(sess.handoff_work_order_no or sess.work_order_no or "-"),
)
existing = ""
sess.collab_chat_id = ""
if existing:
sess.collab_mode = COLLAB_MODE_HANDOFF
sess.handoff_committed = True
+244 -12
View File
@@ -205,11 +205,20 @@ def apply_multi_file(
client = group_client_of(flow)
name = (filename or "").strip()
if not filename_is_excel_pdf(name):
# 与海运/空运同口径(2026-11-19 真机):文件名不带工单号的非 Excel/PDF 一律静默,
# 避免群里随手丢个 Word/zip 就被机器搭话;带号才提示一句。
# 2026-11-21:本次指令明确 @ 过机器人时也一定提示(附件的本体仍不入库)。
# 产品 2026-11-24:图片/其它文件不能读,按「无法识别」提示用文字重报。
if explicit or copy.extract_work_order_no(name or ""):
send_group_text(client, room, copy.group_only_excel_pdf())
from agent.policy.quote_confirm import sender_display_name
line = str(sender_mode(flow, sender_id) or "").upper()
send_group_text(
client,
room,
copy.quote_not_recognized(
business_line=line,
at_name=sender_display_name(flow, ticket, sender_id),
text_format=True,
),
)
else:
logger.info("multi_file_type_silent wo=%s file=%s", no or "-", (name or "")[:80])
return "file_type_rejected"
@@ -240,6 +249,100 @@ def apply_multi_file(
quote=quote,
sheet_fn=None,
skip_sheet=True,
sender_id=sender_id,
)
def _segment_note(segment: Segment, text: str) -> str:
"""多段群回执前缀:让产品知道这句提示说的是哪一段。"""
return f"段{segment.index}:{segment.word()}\n{text}"
def _save_raw_segment_quote(
*, flow: Any, ticket: object, segment: Segment, text: str, sender_id: str = ""
) -> None:
"""
非话术/全无:原话按段落档,进「原始报价参考」,六态保持询价中。
不写 total/fee_rows,_has_money 为假,不会把这一段当已报价;
后续产品重报标准价时同一段会被覆盖。副作用:写主账。线程:Worker。
"""
no = ticket_no(ticket)
stored = segment_quotes(ticket)
raw = (text or "").strip()
stored[segment.mode] = {"raw_text": raw, "source_label": "产品群原话"}
payload = {
"segment_quotes": stored,
"source_label": "分段报价",
"raw_text": raw,
"raw_source": "nonstandard",
"deal_version": int(
dict(ticket_view(ticket).get("quote") or {}).get("deal_version") or 0
),
}
writer = getattr(flow.ledger, "upsert_product_quote", None)
if not callable(writer):
return
try:
writer(
work_order_no=no,
quote=payload,
to_status="询价中",
remark="分段原话",
kind="product",
raw_text=text,
raw_source="nonstandard",
sender_id=sender_id,
)
except TypeError:
writer(work_order_no=no, quote=payload, to_status="询价中")
def confirm_pending_multi(
*, flow: Any, ticket: object, chat_id: str, sender_id: str, text: str
) -> str:
"""
多段群成员 @机器人 回「确认/确定」:把待确认那一段报价正式落账。
返回空串表示不是确认/没有待确认,调用方继续原流程。
"""
from agent.policy.quote_confirm import (
can_confirm_quote,
is_confirm_text,
quote_confirm_enabled,
)
from agent.redis_coord.pending_quote_confirm import (
clear_pending_confirm,
load_pending_confirm,
)
if not quote_confirm_enabled():
return ""
no = ticket_no(ticket)
pending = load_pending_confirm(no)
if not pending or pending.get("kind") != "quote":
return ""
if not is_confirm_text(text or ""):
return ""
seg_mode = str(pending.get("segment_mode") or pending.get("line") or "").upper()
segments = load_segments(ticket)
target = next((s for s in segments if str(s.mode).upper() == seg_mode), None)
if target is None:
return ""
if not can_confirm_quote(flow, ticket, sender_id, business_line=seg_mode):
send_group_text(group_client_of(flow), chat_id, "只有本单销售或产品/航线可以确认报价。")
return "confirm_not_allowed"
clear_pending_confirm(no)
return _save_segment_quote(
flow=flow,
ticket=ticket,
chat_id=chat_id,
segment=target,
segments=segments,
quote=dict(pending.get("quote") or {}),
sheet_fn=None,
skip_sheet=True,
sender_id=sender_id,
)
@@ -266,6 +369,11 @@ def handle_multi_inbound(
if not segments:
send_group_text(group_client_of(flow), room, f"工单{no}没有可报价的运输段。")
return "multi_no_segments"
confirmed = confirm_pending_multi(
flow=flow, ticket=ticket, chat_id=room, sender_id=sender_id, text=text or ""
)
if confirmed:
return confirmed
only_no = copy.extract_work_order_no(text or "") == no and _only_work_order(text or "")
if only_no or not (ticket_view(ticket).get("collab_chat_id") or ""):
_bind_room(flow, ticket, room, sender_id)
@@ -295,26 +403,147 @@ def handle_multi_inbound(
baseline = _quote_currency_hint((segment_quotes(ticket) or {}).get(target.mode) or {})
if not baseline:
baseline = _quote_currency_hint(dict(ticket_view(ticket).get("quote") or {}))
seg_mode = str(mode or "").upper()
seg_transport = (
"陆运" if seg_mode == "LAND" else ("空运" if seg_mode == "AIR" else "海运")
)
# 待确认期间改车型/税率/线路等字段,不能把数字当新报价。
from agent.policy.quote_confirm import quote_confirm_enabled, sender_display_name
from agent.policy.sea_group_ops import _is_group_field_correction
from agent.redis_coord.pending_quote_confirm import load_pending_confirm
if quote_confirm_enabled():
pending = load_pending_confirm(no)
if (
pending
and pending.get("kind") == "quote"
and _is_group_field_correction(text or "", seg_mode)
):
at_name = sender_display_name(flow, ticket, sender_id)
prefix = f"@{at_name}\n" if at_name else ""
send_group_text(
group_client_of(flow),
room,
prefix + "请先确认上一条报价,或按标准格式重新报价。",
)
return "quote_pending_hint"
quote = extract_product_quote(
text or "",
injected=injected_quote,
business_line=str(mode or "").upper(),
transport_mode=(
"陆运" if str(mode or "").upper() == "LAND"
else ("空运" if str(mode or "").upper() == "AIR" else "海运")
),
business_line=seg_mode,
transport_mode=seg_transport,
baseline_currency=baseline,
)
from agent.schema.quote_recognition import inspect_quote_recognition
recognition = inspect_quote_recognition(
text or "",
quote,
business_line=seg_mode,
transport_mode=seg_transport,
facts=dict(getattr(target, "facts", {}) or {}) if target is not None else {},
extra_facts=dict(fields),
)
from agent.policy.quote_confirm import sender_display_name
at_name = sender_display_name(flow, ticket, sender_id)
client = group_client_of(flow)
if not quote:
if fields:
return "multi_collab_saved"
if is_sales(ticket, sender_id):
return _maybe_deal(flow, ticket, sender_id, text)
send_group_text(group_client_of(flow), room, copy.group_quote_not_recognized())
return "quote_not_recognized"
if target is None:
# 对不上段时无法归段,只能整体提示重报,不写段价。
send_group_text(
client,
room,
copy.quote_not_recognized(business_line=seg_mode, at_name=at_name),
)
return "quote_raw_saved"
# 非话术/全无:原话按段落档,六态保持询价中;再按段回识别回执。
_save_raw_segment_quote(
flow=flow, ticket=ticket, segment=target, text=text or "", sender_id=sender_id
)
if recognition["status"] == "partial":
send_group_text(
client,
room,
_segment_note(
target,
copy.quote_partial_recognized(
recognition["recognized"],
recognition["missing"],
business_line=seg_mode,
work_order_no=no,
at_name=at_name,
),
),
)
return "quote_partial_saved"
send_group_text(
client,
room,
_segment_note(
target,
copy.quote_not_recognized(business_line=seg_mode, at_name=at_name),
),
)
return "quote_raw_saved"
if target is None:
send_group_text(group_client_of(flow), room, "没有对上你负责的运输段,请让对应岗位报价。")
send_group_text(client, room, "没有对上你负责的运输段,请让对应岗位报价。")
return "quote_wrong_role"
# 产品 2026-11-24:报价先回识别回执,成员@机器人回「确认/确定」后才落段价。
from agent.policy.quote_confirm import quote_confirm_enabled
from agent.redis_coord.pending_quote_confirm import save_pending_confirm
if quote_confirm_enabled():
save_pending_confirm(
no,
{
"kind": "quote",
"quote": dict(quote),
"raw_text": text or "",
"raw_source": "text",
"line": seg_mode,
"segment_mode": seg_mode,
"recognized": list(recognition["recognized"]),
"chat_id": room,
"sender_id": sender_id,
},
)
send_group_text(
client,
room,
_segment_note(
target,
copy.quote_partial_recognized(
recognition["recognized"],
[],
business_line=seg_mode,
work_order_no=no,
at_name=at_name,
),
),
)
return "quote_confirm_pending"
# 部分识别回执:先告诉产品识别到了什么,再落段价/发成交跟进,
# 成交卡保持最新一条,不会被回执顶到上面。
if recognition["status"] == "partial":
send_group_text(
client,
room,
_segment_note(
target,
copy.quote_partial_recognized(
recognition["recognized"],
recognition["missing"],
business_line=seg_mode,
work_order_no=no,
at_name=at_name,
),
),
)
# 文字段报价:只落价,不自动发报价单;销售/商务/航线再说「生成报价单」。
return _save_segment_quote(
flow=flow,
@@ -325,6 +554,7 @@ def handle_multi_inbound(
quote=quote,
sheet_fn=sheet_fn,
skip_sheet=True,
sender_id=sender_id,
)
@@ -390,6 +620,7 @@ def _save_segment_quote(
quote: dict[str, Any],
sheet_fn: Optional[SheetFn],
skip_sheet: bool = False,
sender_id: str = "",
) -> str:
"""写入这一段报价并发该段报价单。其他段未齐时不发成交跟进。"""
no = ticket_no(ticket)
@@ -415,6 +646,7 @@ def _save_segment_quote(
to_status="已报价" if all_ready else "询价中",
remark="分段报价",
kind="product",
sender_id=sender_id,
)
else:
writer = getattr(flow.ledger, "upsert_quote", None)
+262 -17
View File
@@ -10,7 +10,7 @@ from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any
from typing import Any, Optional
from agent.policy import inquiry_copy as copy
from agent.schema.field_validate import (
@@ -24,6 +24,7 @@ from agent.schema.land_options import (
drop_land_prompt_echo,
harvest_land_options,
land_cargo_name,
land_option_gaps,
option_prompt,
scrub_land_placeholder_ports,
validate_land_options,
@@ -293,12 +294,181 @@ def _segment_required_check(seg: Segment) -> tuple[dict[str, Any], dict[str, str
return check, facts
def refresh_segments(segments: list[Segment]) -> tuple[bool, list[Segment], str]:
def land_option_card_segment(segments: list[Segment]) -> Optional[Segment]:
"""
多段里还缺业务类型/报价场景的陆运段。
切段时同一种运输方式出现两次已被拒(same_mode),所以最多一段陆运;
这里仍只返回第一个,脏书签也不会让同一张卡问两遍。
副作用:无,不改入参。
"""
for seg in segments:
if seg.mode == "LAND" and land_option_gaps(seg.facts):
return seg
return None
def segment_gap_body(seg: Segment, *, options_on_card: bool = False) -> str:
"""
单段缺口正文。出卡流程用它判断除陆运段外是否还有别的段要补。
与 refresh_segments 共用 _segment_required_check/_segment_clarify,
不另写一套必填口径。副作用:无,不改入参。
"""
check, _ = _segment_required_check(seg)
return _segment_clarify(seg, check, options_on_card=options_on_card)
# 只可能属于陆运段的字段标签。销售补字段常不写段号,只看这些词就能落到陆运段。
# 不含「目的港/目的地/体积/重量」:海运和空运也在用,认了会把单段询价抢回多段。
_LAND_ANSWER_LABELS = ("业务类型", "报价场景", "车型/数量", "通关口岸", "始发站", "货物品名")
# 只在某一种运输方式的补问里出现的字段标签。混合回填时按它把一句话拆给两段:
# 「车型/数量:3T + 体积:2cbm + 包装类型:托盘」应拆成陆运和空运各一份。
_EXCLUSIVE_MODE_LABELS = (
("LAND", _LAND_ANSWER_LABELS),
(
"AIR",
(
"起运地",
"包装类型",
"包装方式",
"件数",
"增值服务",
"added_services",
"比例",
"尺寸",
"货源地",
"货好时间",
"收货地址",
),
),
("SEA", ("货物数量", "整柜或拼柜", "箱型箱量", "派送地址")),
)
def _exclusive_mode(label: str) -> str:
"""这个字段标签是否只属于一种运输方式;都属于或都不属于时返回空串。"""
base = re.sub(r"[((](?:非)?必填[))]$", "", (label or "").strip()).strip()
if not base:
return ""
for mode, labels in _EXCLUSIVE_MODE_LABELS:
if base in labels:
return mode
return ""
def is_land_segment_answer(segments: list[Segment], text: str) -> bool:
"""
本句是不是在补多段里陆运段的字段。
只认陆运专属标签(业务类型/报价场景/车型/数量…):这些词不会是在说海运/空运。
陆运段已齐时不拦,避免把新开的单段询价粘在旧草稿上。副作用:无,只读段。
"""
raw = (text or "").strip()
if not raw:
return False
land = next((seg for seg in segments if seg.mode == "LAND"), None)
if land is None:
return False
if not any(label in raw for label in _LAND_ANSWER_LABELS):
return False
return bool(segment_gap_body(land, options_on_card=False).strip())
def _reply_label_keys(text: str) -> list[str]:
"""回复里显式写出的字段名(原词,不归一)。"""
return [
str(key).strip()
for key in parse_labeled_facts(text or "")
if str(key).strip()
]
def _label_in_prompt(label: str, body: str) -> bool:
"""
回复里的字段名是否出现在该段的补问正文里。
中文标签要求左侧不是汉字:避免「品名」误命中「货物品名」。
副作用:无。
"""
base = re.sub(r"[((](?:非)?必填[))]$", "", (label or "").strip()).strip()
if not base:
return False
return re.search(rf"(?<![一-鿿]){re.escape(base)}", body or "") is not None
def segments_matching_supplement_prompt(
segments: list[Segment], text: str
) -> list[Segment]:
"""
回复里的字段名能对上哪些「还缺字段」的段补问。
补问正文就是那一段刚问销售的东西:字段名全部出现在正文里,才算这一段的答案。
用原词而不归一是因为「始发站/货物品名」归一后会变成海运也用的「起运港/品名」,
会把陆运的补句错落到海运段。副作用:无,只读段。
"""
keys = _reply_label_keys(text)
if not keys:
return []
matched: list[Segment] = []
for seg in segments:
body = segment_gap_body(seg, options_on_card=False)
if not body.strip():
continue
if all(_label_in_prompt(key, body) for key in keys):
matched.append(seg)
return matched
def is_multi_supplement_answer(segments: list[Segment], text: str) -> bool:
"""
本句是不是在补多段里某一段的字段(不写段号也认)。
为什么需要(2026-11-23/24 正服截图):多段补问发出后,销售把复制清单填好回传,
或只回「车型/数量:8T」「贸易条款:门到门」,不写段号;选流把多段草稿让掉后
落到单段,反问「请告知我运输方式」。
判定只用显式「字段名:值」,纯口语/纯数字仍让位给单段,避免把新询价粘在旧草稿上。
先看字段名能不能对上某一段的补问正文;对不上再按字段归属兜底。
2026-11-23 的事故里销售其实是在另开海运单,多段里没有可落的海运段,因此不会被拦。
副作用:无,只读段。
"""
raw = (text or "").strip()
if not raw:
return False
raw_labels = parse_labeled_facts(raw)
# 先归一:货物品名→品名、始发站→起运港,才能和段的内部键对上。
parsed = normalize_facts(raw_labels)
if not parsed:
# 陆运选项卡的兜底清单用「业务类型/报价场景」,不在通用标签表里。
return is_land_segment_answer(segments, raw)
if segments_matching_supplement_prompt(segments, raw):
return True
if is_land_segment_answer(segments, raw):
return True
# 专属字段指向的运输方式在多段里存在(哪怕该段已齐,也可能是改正)。
modes = {seg.mode for seg in segments}
if any(_exclusive_mode(key) in modes for key in raw_labels):
return True
targets = _indexes_for_supplement(segments, parsed)
if len(targets) != 1:
return False
return targets[0] in _lacking_indexes(segments)
def refresh_segments(
segments: list[Segment],
*,
options_on_card: bool = False,
) -> tuple[bool, list[Segment], str]:
"""
按各段运输方式校验必填,并把默认报价日期写回。
返回:是否已齐、更新后的段、缺口文案。缺口一条消息说完,不套群摘要。
待补充的举例与单聊相同:字段名一行,下一行「(如:茶叶)」。
options_on_card=True 时,陆运段的业务类型/报价场景由调用方发卡收集,
正文只留一句点卡提示;卡发不出去时调用方仍用 option_prompt 兜底。
"""
updated: list[Segment] = []
blocks: list[str] = []
@@ -307,7 +477,7 @@ def refresh_segments(segments: list[Segment]) -> tuple[bool, list[Segment], str]
check, facts = _segment_required_check(seg)
filled = Segment(index=seg.index, mode=seg.mode, facts=facts, source=seg.source)
updated.append(filled)
body = _segment_clarify(filled, check)
body = _segment_clarify(filled, check, options_on_card=options_on_card)
if body:
ready = False
blocks.append(f"段{filled.index}:{filled.word()}\n{body}")
@@ -348,24 +518,88 @@ def merge_supplement(
if str(val or "").strip():
target.facts[key] = str(val).strip()
return out
parsed = _unlabeled_supplement_facts(text, extra_facts)
# 先归一:逐字段认领拿到的内部键才能和 handled 对上(包装类型→包装方式等)。
parsed = normalize_facts(_unlabeled_supplement_facts(text, extra_facts))
if not parsed:
return segments
lacking = _lacking_indexes(segments)
if len(lacking) == 1:
targets = lacking
else:
# 核对后改海运格子、或两段都缺时只补海运字段:按字段归属落到唯一一段。
targets = _indexes_for_supplement(segments, parsed)
if len(targets) != 1:
return segments
out = [Segment(index=s.index, mode=s.mode, facts=dict(s.facts)) for s in segments]
for seg in out:
if seg.index != targets[0]:
by_index = {seg.index: seg for seg in out}
# ① 先按字段逐项认领:同一句可能同时在补两段。
# 例:「车型/数量:3T、体积:2cbm、包装类型:托盘」——
# 车型/数量进陆运,包装类型进空运,体积两段都把它当自己的字段时只补空着的。
raw_facts = parse_labeled_facts(text)
exclusive_modes = {mode for key in raw_facts if (mode := _exclusive_mode(key))}
bodies = {
seg.index: segment_gap_body(seg, options_on_card=False) for seg in out
}
handled: set[str] = set()
for raw_key, raw_val in raw_facts.items():
token = str(raw_val or "").strip()
if not token:
continue
for key, val in parsed.items():
internal = normalize_facts({raw_key: token})
if not internal:
continue
mode = _exclusive_mode(raw_key)
owners = [
seg
for seg in out
if bodies.get(seg.index, "").strip()
and _label_in_prompt(raw_key, bodies[seg.index])
]
if not owners:
# 专属字段指向的段已齐时也收下:销售可能是在改正已经填过的值。
if mode:
owners = [seg for seg in out if seg.mode == mode]
if not owners:
continue
if mode:
owned = [seg for seg in owners if seg.mode == mode]
if owned:
owners = owned
elif exclusive_modes:
# 共享字段(体积/贸易条款等)优先给本句里写到专属字段的那一段。
preferred = [seg for seg in owners if seg.mode in exclusive_modes]
if preferred:
owners = preferred
# 共享字段落到多段时只填空:这句话未必是在改另一段已有的值。
# 只落到唯一一段(含按专属字段收窄后)就允许覆盖,销售可能是在改这个值。
multi_owner = len(owners) > 1
for seg in owners:
for key, val in internal.items():
value = str(parsed.get(key) or val).strip()
if not value:
continue
if not mode and multi_owner and str(seg.facts.get(key) or "").strip():
continue
seg.facts[key] = value
handled.update(internal)
# ② 剩下的是没有显式标签的字段(陆运选项、口语机量、LLM 注入),沿用单段归属。
remaining = {key: val for key, val in parsed.items() if key not in handled}
if remaining:
matched = [
seg.index for seg in segments_matching_supplement_prompt(segments, text)
]
if len(matched) == 1:
targets = matched
elif is_land_segment_answer(segments, text):
# 陆运展示名(始发站/货物品名)归一后会撞上海运键,先按陆运专属词认。
targets = [seg.index for seg in segments if seg.mode == "LAND"]
else:
lacking = _lacking_indexes(segments)
if len(lacking) == 1:
targets = lacking
else:
# 核对后改海运格子、或两段都缺时只补海运字段:按字段归属落到唯一一段。
targets = _indexes_for_supplement(segments, remaining)
if len(targets) != 1:
return out
target = by_index[targets[0]]
for key, val in remaining.items():
if str(val or "").strip():
seg.facts[key] = str(val).strip()
target.facts[key] = str(val).strip()
return out
@@ -515,11 +749,18 @@ def includes_air(segments: list[Segment]) -> bool:
return any(seg.mode == "AIR" for seg in segments)
def _segment_clarify(seg: Segment, check: dict[str, Any]) -> str:
def _segment_clarify(
seg: Segment,
check: dict[str, Any],
*,
options_on_card: bool = False,
) -> str:
"""
一段的补问正文,格式对齐单聊:已识别 + 待补充带举例。
不要再写一遍「请确认并补充」和运输方式,外层已经有段号。
options_on_card=True 时,陆运还缺业务类型/报价场景只留点卡提示,
不再把复制清单塞进多段正文(清单留给卡发不出去时的兜底)。
"""
if check.get("ok") and not check.get("need_land_subtype"):
return ""
@@ -527,6 +768,10 @@ def _segment_clarify(seg: Segment, check: dict[str, Any]) -> str:
if seg.mode == "LAND" and (
check.get("need_land_subtype") or check.get("need_land_options")
):
# 缺业务类型/报价场景:多段由调用方发卡,正文只留一句点卡提示。
# 选项已齐、只缺品名时仍留在这张复制清单里,只问品名,不进始发站待填。
if options_on_card and land_option_gaps(seg.facts):
return copy.MULTI_LAND_OPTIONS_ON_CARD
# 和单聊同一张清单:类型、线路、分类、货物品名。已填的留在复制框上面。
return option_prompt(current=seg.facts)
if seg.mode == "LAND":
+155 -9
View File
@@ -2,6 +2,7 @@
多段联运私聊:补问、核对、建单、拉群。
本文件职责:一段一段收齐必填后才建一张工单;不去 TMS 查价。
陆运段缺业务类型/报价场景时发选项卡(与单聊同一张卡),卡发不出去仍回落复制清单。
不含空运时,销售点「拉产品进群」后按各段线路把人拉进同一个群,并发群摘要。
含空运时只提示手动拉人到原有群。报价和成交跟进不在本文件。
调用:文字询价 Handler 在 Worker 线程;禁止回调线程同步跑。
@@ -29,8 +30,10 @@ from agent.policy.multi_segments import (
confirm_text,
group_brief,
includes_air,
land_option_card_segment,
merge_supplement,
refresh_segments,
segment_gap_body,
segments_from_payload,
segments_to_payload,
split_segments,
@@ -117,11 +120,19 @@ class MultiTextInquiryFlow:
card_meta: Optional[dict[str, Any]] = None,
) -> str:
"""
处理多段拉群卡。错工单/未允许直接丢弃,不改主账。
处理多段卡片。错工单/未允许直接丢弃,不改主账。
新增陆运补问卡(multi_land_options):把点选的业务类型/报价场景写回陆运段,
再交给 _open 重新核缺口;卡过期只回过期话术,不写半截值。
副作用:点「拉产品进群协同」时建一个群并发摘要、各段模板。
调用:卡片 Handler,HTTP 回调线程只入队后由 Worker/本流程执行;本函数会打企微建群。
"""
if action == copy.BTN_LAND_OPTIONS:
return self._submit_land_options_card(
sender_id=sender_id,
reply=reply,
card_meta=card_meta,
)
sess = self.session_for_action(sender_id, card_meta)
card_wo = copy.work_order_from_card_meta(card_meta)
if not sess or action not in (sess.allowed or ()):
@@ -357,22 +368,155 @@ class MultiTextInquiryFlow:
)
if refused:
return refused
ready, updated, gaps = refresh_segments(filled)
# 陆运缺业务类型/报价场景时改发选项卡;正文只留点卡提示。
options_on_card = land_option_card_segment(filled) is not None
ready, updated, gaps = refresh_segments(filled, options_on_card=options_on_card)
if not ready:
self._reply_gaps(updated, gaps, reply)
# 先落书签再出卡:销售点得很快时,回调要靠这份 facts 找回当前草稿。
self._save(self._draft(sender_id, updated, phase="clarify", immutable=immutable))
self._reply_gaps(updated, gaps, reply, sender_id=sender_id)
return "clarify"
reply(confirm_text(updated))
self._save(self._draft(sender_id, updated, phase="wait_confirm", immutable=immutable))
return "wait_confirm"
def _reply_gaps(self, segments: list[Segment], gaps: str, reply: ReplyFn) -> None:
def _reply_gaps(
self,
segments: list[Segment],
gaps: str,
reply: ReplyFn,
*,
sender_id: str,
) -> None:
"""
补问正文。陆运选项走复制清单,不再另发填写样例图。
补问正文。陆运缺业务类型/报价场景时另发一张选项卡。
副作用:出站文字。只在 Worker 里调。
一个出站只能带一张卡:除陆运段外还有别的段要补时,先发文字摘要,
再单独发卡;只有陆运段缺选项时直接发卡,正文留给卡发不出去时兜底。
卡发不出去(出站回落成 content)时是完整的复制清单,销售仍可按编号回文字。
副作用:出站文字/卡片。只在 Worker 里调。
"""
reply(gaps)
target = land_option_card_segment(segments)
if target is None:
reply(gaps)
return
from agent.schema import land_option_card as loc
from agent.schema.land_options import option_prompt
card = loc.land_option_card_payload(
task_token=sender_id,
facts=target.facts,
note=f"段{target.index}:{target.word()}",
card_kind=loc.MULTI_CARD_KIND,
)
if card is None:
reply(gaps)
return
# 只有陆运段一个缺口时不再单独发摘要:卡片本身就是这条补问。
others = [
seg
for seg in segments
if seg.index != target.index
and segment_gap_body(seg, options_on_card=True).strip()
]
if others:
reply(gaps)
# 卡发不出去时,这条 content 就是销售的兜底正文,要和摘要同一口径自成一个补问。
fallback = (
"请确认并补充以下信息:\n\n"
f"段{target.index}:{target.word()}\n"
f"{option_prompt(current=target.facts)}"
)
reply(fallback.strip(), card)
def _submit_land_options_card(
self,
*,
sender_id: str,
reply: ReplyFn,
card_meta: Optional[dict[str, Any]] = None,
) -> str:
"""
多段补问里的陆运选项卡提交:把点选项写回陆运段,再往前推一步。
只认还在 clarify 的多段草稿。已出号、已核对、卡过期都只回过期话术,
不写半截值、不新建空单。只选了一项也算数:_open 会把还缺的那项重新问出来。
"""
from agent.schema import land_option_card as loc
from agent.schema.land_options import apply_option_pick
payload = dict(card_meta or {})
sess = self.session_for_action(sender_id, payload)
phase = (sess.phase if sess is not None else "") or ""
if (
sess is None
or (sess.business_line or "").upper() != "MULTI"
or phase != "clarify"
):
logger.info(
"multi.land_options.expired sender=%s phase=%s",
sender_id,
phase or "-",
)
reply(copy.land_options_session_expired())
return "land_options_expired"
segments = self._segments(sess)
target = land_option_card_segment(segments)
if target is None:
logger.info("multi.land_options.no_gap sender=%s", sender_id)
reply(copy.land_options_session_expired())
return "land_options_expired"
selected = payload.get("selected_items") or {}
pick = loc.resolve_option_pick(selected if isinstance(selected, dict) else {})
if not (pick.biz_label or pick.transport_type or pick.route or pick.land_class):
logger.info(
"multi.land_options.empty sender=%s selected=%s", sender_id, selected
)
reply(copy.land_options_incomplete())
return self._open(
sender_id, segments, reply, immutable=sess.immutable_text or ""
)
if pick.error == "mismatch":
# 仅旧三项卡兼容:不写搭不上的组合,清掉线路让销售重选业务类型。
logger.info(
"multi.land_options.mismatch sender=%s type=%s route=%s",
sender_id,
pick.transport_type,
pick.route,
)
target.facts = {
k: v for k, v in target.facts.items() if k != "线路类别"
}
reply(
copy.land_option_pair_mismatch(
transport_type=pick.transport_type, route=pick.route
)
)
return self._open(
sender_id, segments, reply, immutable=sess.immutable_text or ""
)
target.facts = apply_option_pick(
target.facts,
biz_label=pick.biz_label,
transport_type=pick.transport_type,
route=pick.route,
land_class=pick.land_class,
)
logger.info(
"multi.land_options.submit sender=%s biz=%s type=%s route=%s scene=%s",
sender_id,
target.facts.get("陆运业务类型") or "-",
target.facts.get("运输类型") or "-",
target.facts.get("线路类别") or "-",
target.facts.get("运输分类") or "-",
)
return self._open(
sender_id, segments, reply, immutable=sess.immutable_text or ""
)
def _enrich_segments(
self,
@@ -507,12 +651,14 @@ class MultiTextInquiryFlow:
)
if refused:
return refused
ready, updated, gaps = refresh_segments(segments)
options_on_card = land_option_card_segment(segments) is not None
ready, updated, gaps = refresh_segments(segments, options_on_card=options_on_card)
if not ready:
self._reply_gaps(updated, gaps, reply)
# 先落书签再出卡:卡回调要靠这份 facts 找回当前草稿。
sess.phase = "clarify"
self._put_segments(sess, updated)
self._save(sess)
self._reply_gaps(updated, gaps, reply, sender_id=sess.sender_id)
return "clarify"
payload = segments_to_payload(updated, keep_prompt_echo=False)
created = self._ledger.create_ticket(
+276 -45
View File
@@ -15,6 +15,7 @@ from agent.schema.quote_adjust import (
adjustable_rows,
apply_adjust,
extract_adjust,
inspect_adjust_recognition,
private_session_can_adjust,
quote_fee_rows,
)
@@ -158,9 +159,92 @@ def try_private_adjust(
if not session_quoted(sess):
return None
names = [str(r.get("name") or "") for r in adjustable_rows(getattr(sess, "quote", None))]
# 产品 2026-11-24:调价先回识别回执;这里接「确认/确定」并真正改价。
from agent.policy.quote_confirm import is_confirm_text, quote_confirm_enabled
from agent.redis_coord.pending_quote_confirm import (
clear_pending_confirm,
load_pending_confirm,
)
if quote_confirm_enabled():
no = str(getattr(sess, "work_order_no", "") or "")
pending = load_pending_confirm(no)
if pending.get("kind") == "adjust" and is_confirm_text(text):
if str(getattr(sess, "sender_id", "") or "") != str(
pending.get("sender_id") or ""
):
reply(copy.adjust_confirm_not_allowed())
return "adjust_confirm_not_allowed"
clear_pending_confirm(no)
confirmed = extract_adjust(
text, injected=pending.get("adjust") or {}, allow_model=False
)
return _apply_private_adjust(flow, sess, confirmed, reply, names)
extract = extract_adjust(text, fee_names=names, injected=injected_adjust)
# 调价也走分级提示:只说了费用名没说幅度、只说了幅度没点名费用,
# 或「改成」后面没写值,都先回「我识别内容为…」;完全不像调价才让原流程继续。
attempt = inspect_adjust_recognition(text, extract, fee_names=names)
if attempt is not None and attempt["status"] in {"partial", "none"}:
reason = private_session_can_adjust(
str(getattr(sess, "status", "") or ""),
bool(quote_fee_rows(getattr(sess, "quote", None))),
str(getattr(sess, "collab_chat_id", "") or ""),
)
if reason:
reply(copy.adjust_ineligible(reason))
return "adjust_blocked"
if attempt["status"] == "partial":
reply(copy.adjust_partial_recognized(attempt["recognized"], attempt["missing"]))
return "adjust_partial_recognized"
reply(copy.adjust_not_recognized())
return "adjust_not_recognized"
if not extract.is_adjust:
return None
# 产品 2026-11-24:调价先回识别回执,成员@机器人回「确认/确定」后才改价。
from agent.policy.quote_confirm import quote_confirm_enabled
from agent.redis_coord.pending_quote_confirm import save_pending_confirm
if quote_confirm_enabled():
payload = _adjust_payload(extract)
save_pending_confirm(
str(getattr(sess, "work_order_no", "") or ""),
{
"kind": "adjust",
"adjust": payload,
"text": text,
"line": str(getattr(sess, "business_line", "") or ""),
"sender_id": str(getattr(sess, "sender_id", "") or ""),
},
)
reply(
copy.adjust_confirm_receipt(
payload.get("items") or [],
work_order_no=str(getattr(sess, "work_order_no", "") or ""),
)
)
return "adjust_confirm_pending"
return _apply_private_adjust(flow, sess, extract, reply, names)
def _adjust_payload(extract: Any) -> dict[str, Any]:
"""把 AdjustExtract 收成可落 Redis 的 JSON。"""
return {
"is_adjust": bool(getattr(extract, "is_adjust", False)),
"wants_total": bool(getattr(extract, "wants_total", False)),
"items": [
{
"fee_name": str(getattr(it, "fee_name", "") or ""),
"kind": str(getattr(it, "kind", "") or "percent"),
"direction": str(getattr(it, "direction", "") or "up"),
"value": float(getattr(it, "value", 0) or 0),
}
for it in (getattr(extract, "items", None) or [])
],
}
def _apply_private_adjust(flow: Any, sess: Any, extract: Any, reply, names: list[str]) -> Optional[str]:
"""私聊调价真正改价:资格、算价、写主账、出新卡。确认前后共用。"""
reason = private_session_can_adjust(
str(getattr(sess, "status", "") or ""),
bool(quote_fee_rows(getattr(sess, "quote", None))),
@@ -228,6 +312,149 @@ def try_private_adjust(
return "wait_collab"
def _apply_group_adjust_math(
*,
flow: Any,
ticket: object,
no: str,
view: dict[str, Any],
current: dict[str, Any],
names: list[str],
extract: Any,
sess: Any,
sender_id: str,
room: str,
client: Any,
) -> str:
"""群内调价真正改价:算价、写主账、发全量文本 + 成交跟进。确认前后共用。"""
from agent.policy.sea_group_ops import (
_save_product_quote,
emit_group_deal,
send_group_text,
ticket_view,
)
result = apply_adjust(
current,
extract,
business_line=str(view.get("business_line") or getattr(sess, "business_line", "") or ""),
tms_cost=_baselines(current)[0],
tms_sale=_baselines(current)[1],
)
if result.code == "need_fee":
send_group_text(client, room, copy.adjust_need_fee())
return "adjust_need_fee"
if result.code == "need_lines":
send_group_text(client, room, copy.adjust_need_lines())
return "adjust_need_lines"
if result.code == "none_matched":
send_group_text(client, room, copy.adjust_unmatched(result.unmatched, names))
return "adjust_none"
if not result.ok:
send_group_text(client, room, copy.adjust_unmatched(result.unmatched or ["该项"], names))
return "adjust_none"
copy.remember_tms_quote(sess, current)
_save_product_quote(
flow,
no,
result.quote,
sess,
remark=copy.adjust_ledger_remark(result.applied),
kind="adjust",
sender_id=sender_id,
)
ticket2 = ticket_view(ticket)
ticket2["quote"] = result.quote
ticket2["status"] = "已报价"
ticket2["work_order_no"] = no
parts = [copy.adjust_confirm(result.applied)]
if result.unmatched:
parts.append(copy.adjust_unmatched(result.unmatched, [str(r.get("name") or "") for r in quote_fee_rows(result.quote)]))
if result.lines_hint:
parts.append(copy.adjust_need_lines())
if result.currency_hint:
parts.append(copy.adjust_currency_hint())
line = str(view.get("business_line") or getattr(sess, "business_line", "") or "SEA")
parts.append(copy.adjust_group_body(result.quote, business_line=line))
send_group_text(client, room, "\n".join(parts))
# 调价只更新文字与成交跟进;Excel/PDF 等「生成报价单」指令。
emit_group_deal(flow=flow, ticket=ticket2, sess=sess, quote=result.quote)
logger.info("group_adjust wo=%s applied=%s", no, [x.get("name") for x in result.applied])
return "group_adjusted"
def confirm_pending_group_adjust(
flow: Any,
ticket: object,
message: Any,
sess: Any = None,
) -> str:
"""
群里成员 @机器人 回「确认/确定」:把待确认的调价真正改价。
发起调价的销售本人,或产品/航线岗可以确认。
"""
from agent.policy.quote_confirm import (
can_confirm_adjust,
is_confirm_text,
quote_confirm_enabled,
)
from agent.redis_coord.pending_quote_confirm import (
clear_pending_confirm,
load_pending_confirm,
)
if not quote_confirm_enabled():
return ""
from agent.policy.sea_group_ops import (
_current_quote,
group_client_of,
hydrate_ticket,
send_group_text,
ticket_no,
ticket_status,
ticket_view,
)
ticket = hydrate_ticket(flow, ticket)
no = ticket_no(ticket)
pending = load_pending_confirm(no)
if not pending or pending.get("kind") != "adjust":
return ""
text = getattr(message, "content", "") or ""
if not is_confirm_text(text):
return ""
sender_id = getattr(message, "sender_id", "") or ""
room = getattr(message, "chat_id", "") or ""
client = group_client_of(flow)
if not can_confirm_adjust(
flow, ticket, sender_id, pending_sender=str(pending.get("sender_id") or "")
):
send_group_text(client, room, copy.adjust_confirm_not_allowed())
return "adjust_confirm_not_allowed"
if ticket_status(ticket) not in {"已报价", "协商中"}:
send_group_text(client, room, copy.adjust_ineligible("no_quote"))
return "adjust_blocked"
clear_pending_confirm(no)
view = ticket_view(ticket)
current = _current_quote(view, sess)
names = [str(r.get("name") or "") for r in adjustable_rows(current)]
extract = extract_adjust(text, injected=pending.get("adjust") or {}, allow_model=False)
return _apply_group_adjust_math(
flow=flow,
ticket=ticket,
no=no,
view=view,
current=current,
names=names,
extract=extract,
sess=sess,
sender_id=sender_id,
room=room,
client=client,
)
def apply_group_adjust(
*,
flow: Any,
@@ -283,51 +510,55 @@ def apply_group_adjust(
current = _current_quote(view, sess)
names = [str(r.get("name") or "") for r in adjustable_rows(current)]
extract = extract_adjust(text, fee_names=names, injected=injected_adjust)
# 调价分级提示:部分识别先回「我识别内容为…」,完全不像调价才静默。
attempt = inspect_adjust_recognition(text, extract, fee_names=names)
if attempt is not None and attempt["status"] in {"partial", "none"}:
if attempt["status"] == "partial":
send_group_text(
client,
room,
copy.adjust_partial_recognized(
attempt["recognized"], attempt["missing"]
),
)
return "adjust_partial_recognized"
send_group_text(client, room, copy.adjust_not_recognized())
return "adjust_not_recognized"
if not extract.is_adjust:
return "not_adjust"
result = apply_adjust(
current,
extract,
business_line=str(view.get("business_line") or getattr(sess, "business_line", "") or ""),
tms_cost=_baselines(current)[0],
tms_sale=_baselines(current)[1],
# 产品 2026-11-24:调价先回识别回执,成员@机器人回「确认/确定」后才改价。
from agent.policy.quote_confirm import quote_confirm_enabled
from agent.redis_coord.pending_quote_confirm import save_pending_confirm
if quote_confirm_enabled():
payload = _adjust_payload(extract)
save_pending_confirm(
no,
{
"kind": "adjust",
"adjust": payload,
"text": text,
"line": str(view.get("business_line") or ""),
"sender_id": sender_id,
"chat_id": room,
},
)
send_group_text(
client,
room,
copy.adjust_confirm_receipt(payload.get("items") or [], work_order_no=no),
)
return "adjust_confirm_pending"
return _apply_group_adjust_math(
flow=flow,
ticket=ticket,
no=no,
view=view,
current=current,
names=names,
extract=extract,
sess=sess,
sender_id=sender_id,
room=room,
client=client,
)
if result.code == "need_fee":
send_group_text(client, room, copy.adjust_need_fee())
return "adjust_need_fee"
if result.code == "need_lines":
send_group_text(client, room, copy.adjust_need_lines())
return "adjust_need_lines"
if result.code == "none_matched":
send_group_text(client, room, copy.adjust_unmatched(result.unmatched, names))
return "adjust_none"
if not result.ok:
send_group_text(client, room, copy.adjust_unmatched(result.unmatched or ["该项"], names))
return "adjust_none"
copy.remember_tms_quote(sess, current)
_save_product_quote(
flow,
no,
result.quote,
sess,
remark=copy.adjust_ledger_remark(result.applied),
kind="adjust",
)
ticket2 = ticket_view(ticket)
ticket2["quote"] = result.quote
ticket2["status"] = "已报价"
ticket2["work_order_no"] = no
parts = [copy.adjust_confirm(result.applied)]
if result.unmatched:
parts.append(copy.adjust_unmatched(result.unmatched, [str(r.get("name") or "") for r in quote_fee_rows(result.quote)]))
if result.lines_hint:
parts.append(copy.adjust_need_lines())
if result.currency_hint:
parts.append(copy.adjust_currency_hint())
line = str(view.get("business_line") or getattr(sess, "business_line", "") or "SEA")
parts.append(copy.adjust_group_body(result.quote, business_line=line))
send_group_text(client, room, "\n".join(parts))
# 调价只更新文字与成交跟进;Excel/PDF 等「生成报价单」指令。
emit_group_deal(flow=flow, ticket=ticket2, sess=sess, quote=result.quote)
logger.info("group_adjust wo=%s applied=%s", no, [x.get("name") for x in result.applied])
return "group_adjusted"
+151
View File
@@ -0,0 +1,151 @@
"""
报价/调价先回识别回执,等成员@机器人回「确认/确定」后再出价格方案/改价。
产品 2026-11-24 口径:
* 产品报价:先回「我识别内容为…请确认是否正确」;
* 销售调价:先回「我识别内容为…请确认是否正确」;
* 只有产品/航线岗回确认才算数;
* 确认后才写主账/出价格方案/改价。
本模块只做开关、确认话术和身份判断;不写主账、不发企微。
"""
from __future__ import annotations
import os
from typing import Any
from agent.policy.bot_name import strip_mention_keep_layout
# 整句就是确认才算。口令不写死整段长句,但也不把含价格的话当确认。
_CONFIRM_TEXTS = frozenset(
{
"确认",
"确定",
"正确",
"确认无误",
"确认正确",
"正确无误",
"对的",
"对",
"是",
"是的",
"没问题",
"无误",
"同意",
"可以",
"好的",
"好",
"ok",
"确认一下",
"确认报价",
"确认该报价",
"确认这个报价",
}
)
def quote_confirm_enabled() -> bool:
"""
是否启用「先回执、后确认」流程。默认开;单测可用 QUOTE_CONFIRM_ENABLED=false 关掉。
"""
raw = str(os.environ.get("QUOTE_CONFIRM_ENABLED", "true")).strip().lower()
return raw not in {"0", "false", "no", "off"}
def is_confirm_text(text: str) -> bool:
"""
整句只是确认/确定/正确等(去掉 @机器人 和标点后)。
为什么用 strip_mention_keep_layout 而不是 strip_bot_mention:
群里显示名可能比后台配置名长(测服真机:「智价通AIQ测试」),
后者只按配置名剥会留下「测试」,把「@… 正确」变成「测试正确」判不成确认。
"""
blob = strip_mention_keep_layout(text or "").replace(" ", "").replace(" ", "")
blob = blob.strip("。.!!,,;;::").lower()
return blob in _CONFIRM_TEXTS
def sender_display_name(flow: Any, ticket: object, sender_id: str) -> str:
"""回执里 @ 当前报价人员:优先员工管理姓名,再工单销售/产品名单,最后 userid。"""
uid = (sender_id or "").strip()
if not uid:
return ""
book = getattr(flow, "ledger", None) or getattr(flow, "_ledger", None)
getter = getattr(book, "get_staff_by_wecom_id", None) if book else None
if callable(getter):
try:
row = getter(wecom_id=uid) or {}
name = str(row.get("name") or "").strip()
if name:
return name
except Exception:
pass
try:
from agent.policy.sea_group_ops import ticket_view
view = ticket_view(ticket or {})
except Exception:
view = {}
sales = str(view.get("sales_wecom_id") or view.get("salesWecomId") or "").strip()
if uid == sales:
name = str(view.get("sales_name") or view.get("salesName") or "").strip()
if name:
return name
ids = [str(x) for x in (view.get("product_ids") or [])]
names = [str(x) for x in (view.get("product_names") or [])]
if uid in ids:
idx = ids.index(uid)
if idx < len(names) and names[idx]:
return names[idx]
return uid
def can_confirm_quote(
flow: Any, ticket: object, sender_id: str, *, business_line: str = ""
) -> bool:
"""
确认报价的人:本单销售本人,或产品/航线岗。
产品 2026-11-24:销售本人也能点确认,不用非等产品。
business_line 传段落方式(MULTI 群按目标段传 AIR/LAND/SEA)。
"""
from agent.policy.sea_group_ops import is_sales
if is_sales(ticket, sender_id):
return True
line = (business_line or "").strip().upper()
if line == "AIR":
from agent.policy.air_group_ops import is_airline
return is_airline(flow, sender_id)
from agent.policy.sea_group_ops import is_product
return is_product(ticket, sender_id, flow=flow)
def can_confirm_adjust(
flow: Any,
ticket: object,
sender_id: str,
*,
pending_sender: str = "",
) -> bool:
"""
确认调价的人:发起调价的本人(销售),或产品/航线岗。
私聊调价只有销售本人,不能要求产品来点;群里销售发起后也允许本人确认。
"""
if pending_sender and (sender_id or "").strip() == (pending_sender or "").strip():
return True
from agent.policy.sea_group_ops import is_sales
if is_sales(ticket, sender_id):
return True
from agent.policy.air_group_ops import is_airline
if is_airline(flow, sender_id):
return True
from agent.policy.sea_group_ops import is_product
return is_product(ticket, sender_id, flow=flow)
+362 -14
View File
@@ -1046,6 +1046,98 @@ def apply_collab_update(
return "collab_field_saved"
def confirm_pending_group_quote(
flow: Any,
ticket: object,
message: Any,
sess: Any = None,
) -> str:
"""
群里成员 @机器人 回「确认/确定」:把待确认的海运/陆运报价正式落账并出价格方案。
返回空串表示不是确认/没有待确认,调用方继续原流程。
只有产品/航线能确认;其他人回确认只提示,不清待确认。
"""
from agent.policy.quote_confirm import (
can_confirm_quote,
is_confirm_text,
quote_confirm_enabled,
)
from agent.redis_coord.pending_quote_confirm import (
clear_pending_confirm,
load_pending_confirm,
)
if not quote_confirm_enabled():
return ""
ticket = hydrate_ticket(flow, ticket)
no = ticket_no(ticket)
pending = load_pending_confirm(no)
if not pending or pending.get("kind") != "quote":
return ""
if not is_confirm_text(getattr(message, "content", "") or ""):
return ""
line = str(pending.get("line") or "").strip().upper()
chat_id = getattr(message, "chat_id", "") or ""
sender_id = getattr(message, "sender_id", "") or ""
if not can_confirm_quote(flow, ticket, sender_id, business_line=line):
send_group_text(group_client_of(flow), chat_id, "只有本单销售或产品/航线可以确认报价。")
return "confirm_not_allowed"
clear_pending_confirm(no)
view = ticket_view(ticket)
base = _current_quote(view, sess)
quote = dict(pending.get("quote") or {})
quote = _attach_land_weight_band_segment(quote, view)
quote = _attach_land_vehicle_rates_segment(quote, view)
if (
_quote_fee_rows(base)
and not (quote.get("weightPrices") or [])
and not (quote.get("vehicleRates") or quote.get("vehicle_rates") or [])
):
base = _align_wrong_default_freight(base, quote, business_line=line)
quote = merge_quote_fees(base, quote)
_save_product_quote(flow, no, quote, sess, sender_id=sender_id)
ticket2 = _reload(flow, chat_id, no) or ticket
send_brief_and_sheet(
flow=flow,
ticket=ticket2,
sess=sess,
quote_override=quote,
tms_quote={},
product_quote=quote,
persist_attachment=False,
include_sheet=False,
)
emit_group_deal(flow=flow, ticket=ticket2, sess=sess, quote=quote)
return "product_quote_sent"
# 陆运/海运字段纠错:有这些标签且没有价格线索时,数字不能当运费。
_GROUP_CORRECT_VERBS = ("改为", "改成", "调整为", "调整成", "调到", "换成", "换到", "变为", "变成")
_GROUP_CORRECT_LABELS = (
"起运地", "起运港", "始发站", "目的地", "目的港", "线路", "车型", "车型/数量",
"税率", "燃油费率", "燃油附加费率", "备注", "品名", "毛重", "重量", "体积",
"件数", "包装", "HS", "海关编码", "商品海关编码", "贸易条款", "货值",
"危险品", "是否含电", "是否含磁", "是否含油", "货好时间",
)
_GROUP_PRICE_CUES = (
"USD", "CNY", "RMB", "HKD", "EUR", "JPY", "GBP", "美元", "人民币", "港币",
"欧元", "日元", "英镑", "运费", "运输费", "空运费", "陆运费", "海运费",
"单价", "总价", "费用合计", "报价", "元", "块", "/kg", "/KG",
)
def _is_group_field_correction(text: str, line: str = "") -> bool:
"""改的是线路/车型/税率/备注等字段,不是改价。"""
_ = line
raw = text or ""
return (
any(v in raw for v in _GROUP_CORRECT_VERBS)
and any(w in raw for w in _GROUP_CORRECT_LABELS)
and not any(p in raw for p in _GROUP_PRICE_CUES)
)
def apply_product_quote(
*,
flow: Any,
@@ -1085,25 +1177,124 @@ def apply_product_quote(
merged.update(fields)
sess.collab_facts = merged
line = str(view.get("business_line") or view.get("businessLine") or "").strip().upper()
mode = "陆运" if line == "LAND" else ("海运" if line == "SEA" else "")
facts = dict(view.get("facts") or {})
base = _current_quote(view, sess)
baseline_ccy = _quote_currency_hint(base)
# 产品 2026-11-24:待确认期间改车型/税率/线路等字段,不能把数字当新报价。
from agent.policy.quote_confirm import quote_confirm_enabled, sender_display_name
from agent.redis_coord.pending_quote_confirm import load_pending_confirm
at_name = sender_display_name(flow, ticket, sender_id)
if quote_confirm_enabled():
pending = load_pending_confirm(no)
if (
pending
and pending.get("kind") == "quote"
and _is_group_field_correction(text, line)
):
prefix = f"@{at_name}\n" if at_name else ""
send_group_text(
client,
chat_id,
prefix + "请先确认上一条报价,或按标准格式重新报价。",
)
return "quote_pending_hint"
quote = extract_product_quote(
text,
injected=injected_quote,
business_line=line,
transport_mode="陆运" if line == "LAND" else ("海运" if line == "SEA" else ""),
transport_mode=mode,
baseline_currency=baseline_ccy,
)
# 识别程度:完整 / 部分 / 全无。部分识别不阻塞,价照常入账,回复里回执。
from agent.schema.quote_recognition import inspect_quote_recognition
recognition = inspect_quote_recognition(
text,
quote,
business_line=line,
transport_mode=mode,
facts=facts,
extra_facts=dict(fields),
)
# 回执 @ 当前报价人员(at_name 在上面已算好)。
if not quote:
logger.info("产品报价未识别 wo=%s text=%s", no, (text or "")[:200])
send_group_text(client, chat_id, copy.group_quote_not_recognized())
return "quote_not_recognized"
# 非话术/全无:原话先留档到「原始报价参考」,六态保持询价中,再按格式提示重报。
writer = getattr(flow.ledger, "upsert_product_quote", None)
if callable(writer):
try:
writer(
work_order_no=no,
quote={"raw_text": (text or "").strip()},
to_status="询价中",
raw_text=text,
raw_source="nonstandard",
sender_id=sender_id,
)
except TypeError:
writer(
work_order_no=no,
quote={"raw_text": (text or "").strip()},
to_status="询价中",
)
if recognition["status"] == "partial":
send_group_text(
client,
chat_id,
copy.quote_partial_recognized(
recognition["recognized"],
recognition["missing"],
business_line=line,
work_order_no=no,
at_name=at_name,
),
)
return "quote_partial_saved"
send_group_text(
client,
chat_id,
copy.quote_not_recognized(business_line=line, at_name=at_name),
)
return "quote_raw_saved"
extracted_quote = dict(quote)
quote = _attach_land_weight_band_segment(quote, view)
quote = _attach_land_vehicle_rates_segment(quote, view)
if _has_tms_quote(base):
_park_pending_quote(no, quote, sess, flow)
send_group_text(client, chat_id, copy.group_ask_tms_or_product())
return "wait_tms_choice"
# 产品 2026-11-24:报价先回识别回执,成员@机器人回「确认/确定」后才出价格方案。
from agent.policy.quote_confirm import quote_confirm_enabled
from agent.redis_coord.pending_quote_confirm import save_pending_confirm
if quote_confirm_enabled():
save_pending_confirm(
no,
{
"kind": "quote",
"quote": extracted_quote,
"raw_text": text,
"raw_source": "text",
"line": line,
"recognized": list(recognition["recognized"]),
"chat_id": chat_id,
"sender_id": sender_id,
},
)
send_group_text(
client,
chat_id,
copy.quote_partial_recognized(
recognition["recognized"],
[],
business_line=line,
work_order_no=no,
at_name=at_name,
),
)
return "quote_confirm_pending"
# 分档单价 / 多车型价表是完整人工价,禁止和旧错误行相加。
# 旧错默认「海运费」的陆运产品价:重报时按本单默认运费对齐后再盖,避免海运费+陆运费并排。
if (
@@ -1113,7 +1304,20 @@ def apply_product_quote(
):
base = _align_wrong_default_freight(base, quote, business_line=line)
quote = merge_quote_fees(base, quote)
_save_product_quote(flow, no, quote, sess)
_save_product_quote(flow, no, quote, sess, sender_id=sender_id)
# 部分识别回执放在价已入账之后、摘要/成交跟进之前:
# 成交卡保持最新一条,不会被回执顶到上面。
if recognition["status"] == "partial":
send_group_text(
client,
chat_id,
copy.quote_partial_recognized(
recognition["recognized"],
recognition["missing"],
business_line=line,
work_order_no=no,
),
)
ticket2 = _reload(flow, chat_id, no) or ticket
# 有价后只发摘要 + 成交跟进;Excel/PDF 等销售/商务/航线说「生成报价单」再出。
# 为什么不自发表:产品每改一次价就甩一个 xlsx,群里全是中间稿,后台附件也堆满。
@@ -1167,7 +1371,7 @@ def apply_tms_quote_choice(
quote.setdefault("source_label", "产品报价")
overlay = dict(pending)
_clear_pending_quote(no, sess, flow)
_save_product_quote(flow, no, quote, sess)
_save_product_quote(flow, no, quote, sess, sender_id=sender_id)
ticket2 = _reload(flow, chat_id, no) or ticket
# 有价落定:摘要 + 成交卡;不自动发表,要表说「生成报价单」。
send_brief_and_sheet(
@@ -1214,7 +1418,7 @@ def apply_confirm_tms_quote(
_clear_pending_quote(no, sess, flow)
confirmed = dict(quote)
confirmed["source_label"] = "产品确认TMS"
_save_product_quote(flow, no, confirmed, sess)
_save_product_quote(flow, no, confirmed, sess, sender_id=sender_id)
_persist_quote_sheet(
flow=flow,
ticket=ticket,
@@ -1330,12 +1534,20 @@ def handle_group_file(
if stopped:
return stopped
if not filename_is_excel_pdf(filename):
# 产品口径(2026-11-19 真机):群里没 @BOT 的 Word/zip 不要搭话。
# 只有文件名里明确带工单号(WO/VT+12 位)才提示一句「只收 Excel/PDF」,
# 其余不支持的类型静默丢弃;文件本体仍可由会话存档旁听,不在这里报错。
# 2026-11-21:若这次是明确 @ 了机器人才发的,就一定要提示,不能装看不见。
# 产品 2026-11-24:图片/其它文件不能读,就按「无法识别」提示产品用文字重报,
# 不再回「只收 Excel 和 PDF」。没 @BOT 的随手文件仍静默,不搭话。
if explicit or copy.extract_work_order_no(filename or ""):
send_group_text(client, chat_id, copy.group_only_excel_pdf())
from agent.policy.quote_confirm import sender_display_name
line = str(view.get("business_line") or view.get("businessLine") or "").upper()
at_name = sender_display_name(flow, ticket, sender_id)
send_group_text(
client,
chat_id,
copy.quote_not_recognized(
business_line=line, at_name=at_name, text_format=True
),
)
else:
logger.info("group_file_type_silent wo=%s file=%s", no or "-", (filename or "")[:80])
return "file_type_rejected"
@@ -1347,7 +1559,7 @@ def handle_group_file(
"file_name": filename,
"total": str((view.get("quote") or {}).get("total") or "-"),
}
_save_product_quote(flow, no, quote, sess)
_save_product_quote(flow, no, quote, sess, sender_id=sender_id)
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"
@@ -1489,7 +1701,35 @@ 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 "")
ticket_chat = str(view.get("collab_chat_id") or "").strip()
sess_chat = str(getattr(sess, "collab_chat_id", "") or "").strip() if sess is not None else ""
# 主账绑群是权威:书签按销售存,可能还停在上一个工单的群。
# 反过来优先书签时,A 单的「群已解散」会沿着书签的群发到 B 单群里。
chat_id = ticket_chat or sess_chat
if ticket_chat and sess_chat and ticket_chat != sess_chat:
logger.warning(
"解散群书签群与主账绑群不一致 wo=%s ticket_chat=%s session_chat=%s,按主账发",
no or "-",
ticket_chat,
sess_chat,
)
if not ticket_chat and chat_id and no:
# 主账没绑群时只能信书签,但 Redis 房间索引对不上别的单就要停手:
# 宁可这次不发,也不能把别的群的成员当成本单群清掉。
try:
from agent.channel.wshoto.rooms import ticket_no_for_room
room_no = str(ticket_no_for_room(chat_id) or "").strip()
except Exception:
room_no = ""
if room_no and room_no.upper() != no.upper():
logger.warning(
"解散群目标群属于其它工单 wo=%s chat=%s room_wo=%s,拒绝发送",
no,
chat_id,
room_no,
)
return "group_ignored"
# 解散群归应用:成员读取与移人都用 appchat 客户端;群内告别语可走 BOT。
client = app_group_client(flow)
members = list(view.get("collab_member_ids") or view.get("memberIds") or [])
@@ -2225,6 +2465,108 @@ def _attach_land_weight_band_segment(
return src
# 陆运主运费的常见费名。只有这些名字才允许「一条运费 + 工单车型」合成车型价。
_LAND_MAIN_FREIGHT_NAMES = frozenset(
{"运费", "运输费", "陆运费", "车费", "拖车费", "干线费"}
)
# 工单询价字段里的车型键:合同归一是「车型/数量」,老数据可能只有「车型」。
_LAND_VEHICLE_FACT_KEYS = ("车型/数量", "车型", "车型数量")
def _land_vehicle_from_view(view: dict[str, Any]) -> str:
"""
工单询价字段里的车型/数量(如 10T)。
产品群里报价常只写「运费1700HKD/车」,车型在首查已填好;
摘要要显示「车型/数量:10T」必须从这里取,不能猜。副作用:无。
"""
facts = dict((view or {}).get("facts") or {})
for key in _LAND_VEHICLE_FACT_KEYS:
val = str(facts.get(key) or "").strip()
if val:
return val
return ""
def _attach_ticket_vehicle_to_single_freight(
quote: dict[str, Any], view: dict[str, Any]
) -> dict[str, Any]:
"""
陆运报价只有一条主运费、原话没写车型时,用工单询价字段的车型补成车型价。
为什么:产品常发「运费1700HKD/车 + 超时/压夜条款」,车型 10T 只在询价字段里。
旧实现把它当普通费用行,摘要出「运费 HKD 1700 + 费用合计」,看不到车型;
产品 2026-11-23 要求显示成「车型/数量:10T / 运输费:1700HKD/车」。
只有一条主运费、且没有其它绝对金额费目时才转换;有报关费等分项时仍保留费用行。
副作用:返回新 dict,不改入参、不落库。线程:纯函数。
"""
src = dict(quote or {})
# 只对陆运生效:海运/空运单即使误带车型字段,也不能把海运费改成车型价。
line = str(
(view or {}).get("business_line") or (view or {}).get("businessLine") or ""
).strip().upper()
if line and line != "LAND":
return src
if (
src.get("vehicleRates")
or src.get("vehicle_rates")
or src.get("vehicleType")
or src.get("vehicle_type")
or src.get("weightPrices")
or src.get("weight_prices")
):
return src
vehicle = _land_vehicle_from_view(view)
if not vehicle:
return src
rows = _quote_fee_rows(src)
money = [
r
for r in rows
if str(r.get("amount") or "").strip()
and "%" not in str(r.get("amount") or "")
]
main = [
r
for r in money
if str(r.get("name") or "").strip() in _LAND_MAIN_FREIGHT_NAMES
]
if len(money) != 1 or len(main) != 1:
return src
amount = str(main[0].get("amount") or "").strip()
if not amount:
return src
ccy = str(main[0].get("currency") or src.get("currency") or "CNY").strip()
unit = str(main[0].get("unit") or "").strip()
if not unit and "/车" in str(src.get("raw_text") or ""):
unit = "车"
# 超时/压夜条款可能在费用行 remark 上(extract 会挂到第一行),
# 转成车型价后顶层 remark 必须跟着走,否则摘要「备注」行会消失。
remark = str(src.get("remark") or main[0].get("remark") or "").strip()
out = dict(src)
out["vehicleRates"] = {vehicle: amount}
out["vehicle_rates"] = {vehicle: amount}
out["vehicleType"] = vehicle
out["vehicle_type"] = vehicle
fee_row: dict[str, Any] = {
"name": vehicle,
"amount": amount,
"currency": ccy,
"unit_price": amount,
}
if unit:
fee_row["unit"] = unit
if remark:
fee_row["remark"] = remark
out["remark"] = remark
out["vehicle_fee_rows"] = [fee_row]
out["fee_rows"] = []
out["fee_lines"] = []
out["total"] = amount
out["currency"] = ccy
return out
def _land_od_from_view(view: dict[str, Any]) -> tuple[str, str]:
"""
工单询价事实里的起运/目的。
@@ -2269,7 +2611,9 @@ def _attach_land_vehicle_rates_segment(
出单侧栏(税率/燃油)和备注列直接读段,不再靠顶层字段兜底。
不写裸 salePrice 冒充单车型,避免多列表头误灌同一价。
"""
src = dict(quote or {})
# 原话没写车型、只写「运费1700HKD/车」时,用工单询价字段的车型补成车型价;
# 这样摘要走竖排版式,不会只显示一条「运费 + 费用合计」。
src = _attach_ticket_vehicle_to_single_freight(dict(quote or {}), view)
rates = src.get("vehicleRates") or src.get("vehicle_rates")
clean: dict[str, str] = {}
if isinstance(rates, dict) and rates:
@@ -2327,6 +2671,7 @@ def _save_product_quote(
*,
remark: str = "",
kind: str = "",
sender_id: str = "",
) -> None:
writer = getattr(flow.ledger, "upsert_product_quote", None) or getattr(
flow.ledger, "upsert_quote", None
@@ -2348,6 +2693,9 @@ def _save_product_quote(
extras["remark"] = remark
if kind:
extras["kind"] = kind
# 报价人一并入主账:后台「处理人」只显示真报价的人,不显示整组被拉进群的产品。
if (sender_id or "").strip():
extras["sender_id"] = sender_id.strip()
try:
saved = writer(work_order_no=no, quote=persist, to_status="已报价", **extras) or {}
except TypeError:
@@ -1184,12 +1184,26 @@ class SeaTextInquiryFlow(AirTextInquiryFlow):
"""
from agent.policy.handoff_human import (
COLLAB_MODE_HANDOFF,
chat_serves_work_order,
ensure_formal_ticket_for_handoff,
is_virtual_no,
)
# ① 幂等:会话里或主账上已经有群,就不再建第二个。
existing = (sess.collab_chat_id or "").strip()
if existing and not chat_serves_work_order(
self._ledger,
existing,
(sess.handoff_work_order_no or sess.work_order_no or "").strip(),
):
# 书签群是另一张单的:复用会把它写进本单的存档索引,解散/报价都会串群。
logger.warning(
"海运转人工旧群不属于本单,改新建 chat=%s wo=%s",
existing,
(sess.handoff_work_order_no or sess.work_order_no or "-"),
)
existing = ""
sess.collab_chat_id = ""
if not existing:
probe_no = (sess.handoff_work_order_no or "").strip()
getter = getattr(self._ledger, "get_ticket", None)
+409
View File
@@ -0,0 +1,409 @@
"""
同义词配置:从主账 inq_synonym 读取,做值归一化与“数量+包装”机读。
本文件职责:
* 60 秒短缓存 GET /inquiry/agent/synonym/listEnabled;
* 按 field_key + transport_mode 精确/最长子串匹配,把卡板→托盘、40尺高柜→40HQ;
* 从「1板 / 2箱 / 3托」同时写件数与包装方式;
* 空运三字码优先查表,查不到再回退代码内 _AIRPORTS。
禁止:
* 全文字符串 replace;单字同义词必须数字紧邻;
* 用同义词覆盖带数量的车型字段(9米6/1 必须保留 /1);
* 主账失败时清空旧缓存;失败保留旧值,从未加载成功则回退代码默认。
线程:进程内锁刷新;与 bot_reply 一致,不同工单共享一份缓存。
"""
from __future__ import annotations
import logging
import os
import re
import threading
import time
import unicodedata
from typing import Any, Optional
logger = logging.getLogger(__name__)
# 后台改词后最多这么久生效;不当 checkpoint。
_TTL_SECONDS = 60.0
_lock = threading.Lock()
_loaded_at = 0.0
_rows: list[dict[str, Any]] = []
_index: dict[tuple[str, str], dict[str, dict[str, Any]]] = {}
_override: Optional[list[dict[str, Any]]] = None
# 主账不可用时仍保证「1板/2箱」能识别,避免上线前行为倒退。
_DEFAULT_PACK = (
("托盘", ("托盘", "托", "板", "卡板", "栈板", "PALLET", "PALLETS", "PLT", "PLTS", "SKID")),
("纸箱", ("纸箱", "箱", "CARTON", "CARTONS", "CTN", "CTNS", "CBOX")),
("木箱", ("木箱", "WOODEN BOX", "WOODEN CASE", "WOODEN CRATE")),
("散货", ("散货", "散件", "散装", "散杂", "LOOSE", "BULK")),
)
# 单字包装后面接这些字不算包装:箱型箱量、1板车。
_BAD_AFTER = ("型", "量", "体", "码", "规", "单", "柜", "车")
def override_catalog(rows: Optional[list[dict[str, Any]]]) -> None:
"""单测注入同义词行;传 None 清掉注入并重新走主账。"""
global _override, _loaded_at, _rows
with _lock:
_override = [dict(r) for r in rows] if rows is not None else None
_loaded_at = 0.0
if rows is None:
_rows = []
def normalize_key(value: Any) -> str:
"""匹配键:全半角统一、去空白、去引号、转大写。"""
text = unicodedata.normalize("NFKC", str(value or ""))
for ch in ("'", '"', "’", "‘", "“", "”", "`"):
text = text.replace(ch, "")
text = "".join(text.split())
return text.upper()
def _unwrap_rows(data: Any) -> list[Any]:
"""解开 Jeecg Result 列表。"""
if isinstance(data, list):
return data
if not isinstance(data, dict):
return []
inner = data.get("result")
if isinstance(inner, list):
return inner
if isinstance(inner, dict):
rec = inner.get("records")
if isinstance(rec, list):
return rec
rec = data.get("records") or data.get("data")
if isinstance(rec, list):
return rec
return []
def _fetch() -> Optional[list[dict[str, Any]]]:
"""
GET /inquiry/agent/synonym/listEnabled。
未配主账地址/内存后端返回空列表,避免每次空打;失败返回 None 保留旧缓存。
"""
try:
from agent.config import get_settings
cfg = get_settings()
backend = str(
os.environ.get("LEDGER_BACKEND") or getattr(cfg, "ledger_backend", "") or ""
).strip().lower()
if backend in {"memory", "mem", "stub"}:
return []
if not str(getattr(cfg, "biz_api_base_url", "") or "").strip():
return []
from agent.ledger import LedgerClient
from agent.ledger.api_shell import LedgerApiShell
client = LedgerClient.from_settings()
client.timeout_seconds = min(float(client.timeout_seconds or 10), 3.0)
resp = LedgerApiShell(client=client).list_synonyms()
if not resp.ok:
logger.warning("synonym listEnabled fail status=%s err=%s", resp.status_code, resp.error)
return None
out: list[dict[str, Any]] = []
for row in _unwrap_rows(resp.data):
if isinstance(row, dict):
out.append(row)
return out
except Exception:
logger.warning("synonym listEnabled 异常,保留旧缓存", exc_info=True)
return None
def _build_index(rows: list[dict[str, Any]]) -> dict[tuple[str, str], dict[str, dict[str, Any]]]:
"""(field, mode) → norm → row;同键保留 priority 大的。"""
index: dict[tuple[str, str], dict[str, dict[str, Any]]] = {}
for raw in rows:
if not isinstance(raw, dict):
continue
if int(raw.get("enabled") if raw.get("enabled") is not None else 1) != 1:
continue
field = str(raw.get("fieldKey") or raw.get("field_key") or "").strip()
mode = str(raw.get("transportMode") or raw.get("transport_mode") or "ALL").strip().upper()
syn = str(raw.get("synonym") or "").strip()
if not field or not syn:
continue
key = str(raw.get("synonymNorm") or raw.get("synonym_norm") or "").strip() or normalize_key(syn)
row = dict(raw)
row["_field"] = field
row["_mode"] = mode
row["_norm"] = key
row["_priority"] = int(raw.get("priority") or 100)
bucket = index.setdefault((field, mode), {})
old = bucket.get(key)
if old is None or row["_priority"] >= int(old.get("_priority") or 0):
bucket[key] = row
return index
def _disabled() -> bool:
"""紧急回滚开关:INQUIRY_SYNONYM_DISABLED=1 时完全不走同义词。"""
return str(os.environ.get("INQUIRY_SYNONYM_DISABLED") or "").strip().lower() in {
"1", "true", "yes", "on",
}
def _ensure_loaded() -> None:
global _loaded_at, _rows, _index
if _disabled():
return
now = time.monotonic()
with _lock:
if _override is not None:
return
if _loaded_at > 0 and (now - _loaded_at) < _TTL_SECONDS:
return
fresh = _fetch()
with _lock:
if _override is not None:
return
if fresh is not None:
_rows = fresh
_index = _build_index(fresh)
_loaded_at = time.monotonic()
elif not _rows:
_loaded_at = time.monotonic()
def _buckets(field: str, mode: str) -> list[dict[str, dict[str, Any]]]:
if _disabled():
return []
_ensure_loaded()
mode = (mode or "").strip().upper()
with _lock:
if _override is not None:
index = _build_index(_override)
else:
index = _index
out = []
for m in (mode, "ALL"):
if not m:
continue
bucket = index.get((field, m))
if bucket and all(bucket is not seen for seen in out):
out.append(bucket)
return out
def _negative_hit(row: dict[str, Any], text: str) -> bool:
"""negative_words 命中任一就不映射。"""
raw = str(row.get("negativeWords") or row.get("negative_words") or "").strip()
if not raw:
return False
for word in re.split(r"[,,、]", raw):
word = word.strip()
if word and word in text:
return True
return False
def lookup(field: str, value: Any, mode: str = "", *, substring: bool = True) -> Optional[dict[str, Any]]:
"""
按字段取值对应的同义词行。
先精确,再最长子串(只认长度≥2、非单字)。单字 requires_number 不在值里直接命中,
由 harvest_package_count 按「数字+包装」处理。
substring=False 用于箱型箱量:2个40尺高柜 / 40HQ*2 必须留给 TMS 解析器拆箱量,
不能被「40HQ」整串替换掉数量。
"""
text = str(value or "").strip()
if not text:
return None
norm = normalize_key(text)
buckets = _buckets(field, mode)
for bucket in buckets:
hit = bucket.get(norm)
if hit is not None and not _negative_hit(hit, text):
return hit
if not substring:
return None
# 最长子串:避免「包装纸箱」漏掉;单字不参与。
best: Optional[dict[str, Any]] = None
best_len = 1
for bucket in buckets:
for synonym, row in bucket.items():
if int(row.get("requiresNumber") or row.get("requires_number") or 0) == 1:
continue
if len(synonym) < 2 or synonym not in norm:
continue
if _negative_hit(row, text):
continue
if len(synonym) > best_len:
best = row
best_len = len(synonym)
return best
def _lookup_with_aliases(
field: str, value: Any, mode: str = "", *, substring: bool = True
) -> Optional[dict[str, Any]]:
"""起运港/目的港先查自身字段,再查城市(空运/陆运)或港口(海运)。"""
hit = lookup(field, value, mode, substring=substring)
if hit is not None:
return hit
if field in {"起运港", "起运地", "目的港", "目的地"}:
return (
lookup("城市", value, mode, substring=substring)
or lookup("港口", value, mode, substring=substring)
)
return None
# 内部键 → 配置字段键;包装类型与包装方式共用一套。
_FIELD_ALIASES = {
"包装类型": "包装方式",
"起运地": "起运港",
"目的地": "目的港",
"车型数量": "车型/数量",
"货物数量": "货量",
}
def apply_value_synonyms(
facts: dict[str, Any] | None,
business_line: str = "",
) -> dict[str, Any]:
"""
把事实里的值折成标准值。只改 VALUE 类型;UNIT/LABEL/INTENT/RULE 不动。
只处理字符串值;added_services / containerItems 这类列表或数字原样保留。
车型/数量 特殊处理:只归一车型部分,保留 /1 这类台数。
返回新 dict,不改入参。
"""
src = {str(k): v for k, v in dict(facts or {}).items() if v is not None}
out = dict(src)
mode = (business_line or "").strip().upper()
for key, raw_val in src.items():
if not isinstance(raw_val, str):
continue
val = raw_val.strip()
if not val:
continue
field = _FIELD_ALIASES.get(key, key)
if field == "车型/数量":
out[key] = _normalize_vehicle_qty(val, mode)
continue
hit = _lookup_with_aliases(
field, val, mode, substring=field not in {"箱型箱量"}
)
if hit is None:
continue
if str(hit.get("synonymType") or hit.get("synonym_type") or "VALUE").upper() != "VALUE":
continue
std = str(hit.get("standardValue") or hit.get("standard_value") or "").strip()
if std and std != val:
out[key] = std
# 「中亚零担」「东南亚整车」这类一个说法同时决定运输类型+线路类别;
# 销售只写了其中一个字段时,把另一个补出来。
if "运输类型" in src and not str(out.get("线路类别") or "").strip():
hit = lookup("线路类别", src["运输类型"], mode)
if hit is not None and _is_value(hit):
std = str(hit.get("standardValue") or hit.get("standard_value") or "").strip()
if std:
out["线路类别"] = std
if "线路类别" in src and not str(out.get("运输类型") or "").strip():
hit = lookup("运输类型", src["线路类别"], mode)
if hit is not None and _is_value(hit):
std = str(hit.get("standardValue") or hit.get("standard_value") or "").strip()
if std:
out["运输类型"] = std
return out
def _is_value(hit: dict[str, Any]) -> bool:
return str(hit.get("synonymType") or hit.get("synonym_type") or "VALUE").upper() == "VALUE"
def _normalize_vehicle_qty(value: str, mode: str) -> str:
"""9米6/1 → 9.6高栏/1;拆不出台数就只归一车型。"""
text = (value or "").strip()
if not text:
return text
parts = re.split(r"\s*[/xX×**]\s*", text, maxsplit=1)
vehicle = parts[0].strip()
hit = lookup("车型/数量", vehicle, mode or "LAND")
if hit is None:
return text
if str(hit.get("synonymType") or hit.get("synonym_type") or "VALUE").upper() != "VALUE":
return text
std = str(hit.get("standardValue") or hit.get("standard_value") or "").strip()
if not std:
return text
if len(parts) == 2 and parts[1].strip():
return f"{std}/{parts[1].strip()}"
return std
def airport_code(value: Any) -> str:
"""地名 → 空运三字码;查不到返回空串,调用方回退 _AIRPORTS。"""
hit = lookup("城市", value, "AIR")
if hit is None:
return ""
return str(hit.get("targetCode") or hit.get("target_code") or "").strip().upper()
def harvest_package_count(text: str) -> dict[str, str]:
"""
从「1板 / 2箱 / 3托」取件数与包装方式。
件数保留销售原文(1板);包装写标准值(托盘)。单字后面接
型/量/体/码/规/单/柜/车 不算包装。主账无配置时用内置兜底。
"""
if _disabled():
return {}
raw = unicodedata.normalize("NFKC", str(text or ""))
if not raw:
return {}
pairs: list[tuple[str, str]] = []
seen: set[str] = set()
for bucket in _buckets("包装方式", ""):
for synonym, row in bucket.items():
std = str(row.get("standardValue") or row.get("standard_value") or "").strip()
if not std or synonym in seen:
continue
# 原始写法优先;匹配键只用于去重。
syn = str(row.get("synonym") or "").strip() or synonym
pairs.append((syn, std))
seen.add(synonym)
for std, syns in _DEFAULT_PACK:
for syn in syns:
key = normalize_key(syn)
if key in seen:
continue
pairs.append((syn, std))
seen.add(key)
if not pairs:
return {}
# 长词优先,避免「托盘」被「托」抢先。
pairs.sort(key=lambda x: len(x[0]), reverse=True)
branches = "|".join(re.escape(s) for s, _ in pairs)
std_by_norm = {normalize_key(s): std for s, std in pairs}
# 数字紧邻;后面接 型/量/体/码/规/单/柜/车 时不算。
pattern = re.compile(
rf"(?<![\d.])(\d+(?:\.\d+)?)\s*({branches})(?![A-Za-z0-9])",
re.IGNORECASE,
)
found: dict[str, str] = {}
last = None
for match in pattern.finditer(raw):
unit = match.group(2)
after = raw[match.end():match.end() + 1]
if after in _BAD_AFTER:
continue
std = std_by_norm.get(normalize_key(unit))
if not std:
continue
last = (match.group(1), unit, std)
if last is None:
return {}
num, unit, std = last
return {"件数": f"{num}{unit}", "包装方式": std}