checkpoint: 提交当前工作区代码(同义词配置初版 + 既有流程改动)
- 新增 inq_synonym 表、62组同义词种子与智能体只读接口 - Python 同义词加载/归一化与 1板/2箱 机读 - 同步当前分支既有协作、报价识别、陆运等改动
This commit is contained in:
@@ -534,10 +534,57 @@ def _handle_bound(
|
||||
)
|
||||
if lost:
|
||||
return lost
|
||||
# 产品 2026-11-24:待确认的报价/调价,成员 @机器人 回「确认/确定」后才落账。
|
||||
from agent.policy.air_group_ops import confirm_pending_air_quote
|
||||
from agent.policy.quote_adjust_ops import confirm_pending_group_adjust
|
||||
|
||||
confirmed = confirm_pending_group_adjust(engine, ticket, message, sess=None)
|
||||
if confirmed:
|
||||
return confirmed
|
||||
confirmed = confirm_pending_air_quote(engine, ticket, message)
|
||||
if confirmed:
|
||||
return confirmed
|
||||
# 待确认报价期间,产品说「航班没了/改为KUL」是纠错,不是锁舱;
|
||||
# 先把线路写回待确认报价并重发回执,别掉进锁舱「请销售先确认已成交」。
|
||||
from agent.policy.air_group_ops import (
|
||||
_explicit_lock_text,
|
||||
apply_air_quote,
|
||||
try_pending_air_correction,
|
||||
)
|
||||
from agent.policy.sea_group_ops import ticket_no
|
||||
from agent.redis_coord.pending_quote_confirm import load_pending_confirm
|
||||
|
||||
corrected = try_pending_air_correction(engine, ticket, message)
|
||||
if corrected:
|
||||
return corrected
|
||||
pending_quote_state = load_pending_confirm(ticket_no(ticket))
|
||||
has_pending_quote = (
|
||||
bool(pending_quote_state) and pending_quote_state.get("kind") == "quote"
|
||||
)
|
||||
skip_lock = has_pending_quote and not _explicit_lock_text(message.content or "")
|
||||
if skip_lock:
|
||||
from agent.llm.extract_text import extract_product_quote
|
||||
|
||||
probe = extract_product_quote(
|
||||
message.content or "", business_line="AIR", transport_mode="空运"
|
||||
)
|
||||
if probe:
|
||||
# 待确认期间产品又发了一条带价报价:按新报价覆盖待确认。
|
||||
return apply_air_quote(
|
||||
flow=engine,
|
||||
ticket=ticket,
|
||||
text=message.content or "",
|
||||
sender_id=message.sender_id,
|
||||
chat_id=chat_id,
|
||||
)
|
||||
facts = dict(ticket_view(ticket).get("collab_facts") or {})
|
||||
pending_lock = str(facts.get("__pending_air_lock") or "") == "1"
|
||||
# 等补舱位时,报价/选线路等意图让路:话里带了舱位、航司或航班号就继续锁。
|
||||
if intent == INTENT_PICK_OPTION or pending_lock or text_has_lock_supplement(message.content or ""):
|
||||
if not skip_lock and (
|
||||
intent == INTENT_PICK_OPTION
|
||||
or pending_lock
|
||||
or text_has_lock_supplement(message.content or "")
|
||||
):
|
||||
option_no, airline, flight_no = lock_params_from_text(message.content or "")
|
||||
if option_no or airline or flight_no:
|
||||
return apply_air_lock(
|
||||
|
||||
@@ -38,6 +38,13 @@ def _pick_card_flow(sender_id: str, payload: dict | None):
|
||||
)
|
||||
from agent.schema.handoff_options import CARD_KIND as LAND_CARD_KIND
|
||||
from agent.schema.land_option_card import CARD_KIND as LAND_OPTIONS_CARD_KIND
|
||||
from agent.schema.land_option_card import MULTI_CARD_KIND
|
||||
|
||||
# 多段补问里的陆运卡:task_id 是 multi_land_options-*。
|
||||
# 必须先于下面的 land_options 判断——event_key 仍是 land_options_submit,
|
||||
# 只按子串认会把这张卡抢去单聊陆运。
|
||||
if MULTI_CARD_KIND in str((payload or {}).get("task_id") or ""):
|
||||
return get_multi_text_flow()
|
||||
|
||||
if LAND_CARD_KIND in raw or LAND_OPTIONS_CARD_KIND in raw:
|
||||
# 这两张卡只有陆运会发,按卡种直取,不再看书签里残留的别的运输线。
|
||||
|
||||
@@ -91,6 +91,16 @@ def handle_group_inbound(
|
||||
classify_group_text(message.content or "", injected=injected_intent)
|
||||
== INTENT_DISSOLVE
|
||||
):
|
||||
conflict = _room_ticket_conflict(book, chat_id)
|
||||
if conflict:
|
||||
# Redis 说本群是某张单的,但那张单主账上绑的是别的群:脏索引。
|
||||
# 按孤儿清群会误踢真实协同群成员,这里只记日志不动手。
|
||||
logger.warning(
|
||||
"group_inbound 房间索引与本群绑群冲突,拒绝孤儿解散 chat=%s room_wo=%s",
|
||||
chat_id,
|
||||
conflict,
|
||||
)
|
||||
return "group_ignored"
|
||||
logger.info(
|
||||
"group_inbound 无工单仍解散 chat=%s sender=%s",
|
||||
chat_id,
|
||||
@@ -300,6 +310,17 @@ def handle_group_inbound(
|
||||
if lost:
|
||||
return lost
|
||||
|
||||
# 产品 2026-11-24:待确认的报价/调价,成员 @机器人 回「确认/确定」后才落账。
|
||||
from agent.policy.quote_adjust_ops import confirm_pending_group_adjust
|
||||
from agent.policy.sea_group_ops import confirm_pending_group_quote
|
||||
|
||||
confirmed = confirm_pending_group_adjust(engine, ticket, message, sess)
|
||||
if confirmed:
|
||||
return confirmed
|
||||
confirmed = confirm_pending_group_quote(engine, ticket, message, sess)
|
||||
if confirmed:
|
||||
return confirmed
|
||||
|
||||
intent = classify_group_text(message.content or "", injected=injected_intent)
|
||||
logger.info(
|
||||
"group_inbound 文字 chat=%s sender=%s intent=%s chars=%s",
|
||||
@@ -407,7 +428,7 @@ def _find_ticket(book: object, chat_id: str):
|
||||
if callable(finder):
|
||||
hit = finder(chat_id=chat_id)
|
||||
if hit is not None:
|
||||
return hit
|
||||
return _ticket_for_room(hit, chat_id)
|
||||
try:
|
||||
from agent.channel.wshoto.rooms import ticket_no_for_room
|
||||
|
||||
@@ -421,13 +442,70 @@ def _find_ticket(book: object, chat_id: str):
|
||||
if callable(getter):
|
||||
hit = getter(work_order_no=no)
|
||||
if hit is not None:
|
||||
return hit
|
||||
return _ticket_for_room(hit, chat_id)
|
||||
getter = getattr(book, "get_for_agent", None)
|
||||
if callable(getter):
|
||||
return getter(work_order_no=no, sender_id="")
|
||||
hit = getter(work_order_no=no, sender_id="")
|
||||
return _ticket_for_room(hit, chat_id) if hit else None
|
||||
return None
|
||||
|
||||
|
||||
def _ticket_for_room(hit: object, chat_id: str):
|
||||
"""
|
||||
反查出来的工单必须确实服务这个群。
|
||||
|
||||
Redis 房间→工单是短索引,售卖给别的工单换群/书签串单时会残留旧号。
|
||||
拿别的群的单在本群回话,就会出现「陆运单的群已解散发进空运群」(2026-11-23 真机):
|
||||
解散语沿用了本次入站群的回复通道,工单号却来自另一张单。
|
||||
绑群号是空的(改造前老群)仍按原逻辑放行;有绑群号且不是本群就整条忽略。
|
||||
"""
|
||||
if hit is None:
|
||||
return None
|
||||
view = ticket_view(hit)
|
||||
bound = str(view.get("collab_chat_id") or "").strip()
|
||||
room = (chat_id or "").strip()
|
||||
if bound and room and bound != room:
|
||||
logger.warning(
|
||||
"group_inbound 群与工单绑群不一致 chat=%s wo=%s bound=%s,忽略该工单",
|
||||
room,
|
||||
ticket_no(hit) or "-",
|
||||
bound,
|
||||
)
|
||||
return None
|
||||
return hit
|
||||
|
||||
|
||||
def _room_ticket_conflict(book: object, chat_id: str) -> str:
|
||||
"""
|
||||
Redis 房间索引把本群指向一张单,但那张单主账上绑的是别的群。
|
||||
|
||||
这种脏索引不能当「本群无主」处理:孤儿解散会按企微实时成员清人,
|
||||
误伤真实协同群。返回冲突的工单号,空串表示没有冲突。
|
||||
"""
|
||||
try:
|
||||
from agent.channel.wshoto.rooms import ticket_no_for_room
|
||||
|
||||
no = str(ticket_no_for_room(chat_id) or "").strip()
|
||||
except Exception:
|
||||
return ""
|
||||
if not no:
|
||||
return ""
|
||||
getter = getattr(book, "get_ticket", None)
|
||||
hit = None
|
||||
if callable(getter):
|
||||
try:
|
||||
hit = getter(work_order_no=no)
|
||||
except Exception:
|
||||
logger.exception("冲突校验读主账失败 wo=%s", no)
|
||||
return ""
|
||||
if hit is None:
|
||||
return ""
|
||||
bound = str(ticket_view(hit).get("collab_chat_id") or "").strip()
|
||||
if bound and bound != (chat_id or "").strip():
|
||||
return no
|
||||
return ""
|
||||
|
||||
|
||||
def _session_of_ticket(engine: object, ticket: object):
|
||||
"""用工单号找回销售侧书签,方便写 collab_facts / deal_version。"""
|
||||
no = ticket_no(ticket)
|
||||
|
||||
@@ -43,6 +43,40 @@ def _mode_from_clarify_labels(text: str) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _multi_land_answer(sess, text: str) -> bool:
|
||||
"""
|
||||
本句是不是在补多段里陆运段的字段(陆运专属标签)。
|
||||
|
||||
用于本句同时点名了运输方式、又写了业务类型/车型/数量这类陆运专属字段的情况。
|
||||
"""
|
||||
if sess is None:
|
||||
return False
|
||||
from agent.policy.multi_segments import (
|
||||
is_land_segment_answer,
|
||||
segments_from_payload,
|
||||
)
|
||||
|
||||
segments = segments_from_payload((getattr(sess, "quote", None) or {}).get("multi_segments"))
|
||||
return is_land_segment_answer(segments, text)
|
||||
|
||||
|
||||
def _multi_supplement_answer(sess, text: str) -> bool:
|
||||
"""
|
||||
本句是不是在补多段里某一段的字段(含选项卡发不出去时的复制清单回复)。
|
||||
|
||||
没有段标也要留在多段:否则会落到单段流程反问运输方式,或另开一张单。
|
||||
"""
|
||||
if sess is None:
|
||||
return False
|
||||
from agent.policy.multi_segments import (
|
||||
is_multi_supplement_answer,
|
||||
segments_from_payload,
|
||||
)
|
||||
|
||||
segments = segments_from_payload((getattr(sess, "quote", None) or {}).get("multi_segments"))
|
||||
return is_multi_supplement_answer(segments, text)
|
||||
|
||||
|
||||
def _front_bookmark(sess) -> bool:
|
||||
"""补问/核对手稿优先于已出票旧书签。还没定运输方式的草稿不算当前询价,避免抢走另一条已在补问的单。已转人工的票也不再当当前询价。"""
|
||||
if sess is None:
|
||||
@@ -351,6 +385,13 @@ def _pick_text_flow(*, sender_id: str, text: str, injected_mode: str = "", prefe
|
||||
)
|
||||
if multi_waiting and is_multi_continuation(text):
|
||||
return multi
|
||||
if (
|
||||
multi_draft is not None
|
||||
and (multi_draft.phase or "") in {"clarify", "sensitive_block"}
|
||||
and _multi_land_answer(multi_draft, text)
|
||||
):
|
||||
# 点名方式但写的是陆运专属字段(业务类型/车型/数量…):仍是在补多段陆运段。
|
||||
return multi
|
||||
if multi_waiting:
|
||||
# 本句是新开单段:让位前丢掉多段草稿,避免下一句补字段又被多段接走。
|
||||
# 只丢当前书签,已出号的工单仍按工单号留在主账。
|
||||
@@ -392,6 +433,13 @@ def _pick_text_flow(*, sender_id: str, text: str, injected_mode: str = "", prefe
|
||||
return multi
|
||||
if is_multi_continuation(text):
|
||||
return multi
|
||||
# 复制清单回填没有段标,也不能让位给单段,
|
||||
# 否则会丢掉多段草稿、反问运输方式或另开一张单。
|
||||
if (
|
||||
(multi_sess.phase or "") in {"clarify", "sensitive_block"}
|
||||
and _multi_supplement_answer(multi_sess, text)
|
||||
):
|
||||
return multi
|
||||
multi.drop_current_bookmark(sender_id)
|
||||
logger.info(
|
||||
"text_inquiry 旧多段草稿让位 owner=LABEL_OR_SINGLE multi_phase=%s sender=%s",
|
||||
|
||||
@@ -112,6 +112,15 @@ class LedgerApiShell:
|
||||
"""
|
||||
return self.client.request_json("GET", "/inquiry/agent/botReply/listEnabled")
|
||||
|
||||
def list_synonyms(self) -> LedgerResponse:
|
||||
"""
|
||||
已启用询价同义词。
|
||||
|
||||
正式路径:GET /inquiry/agent/synonym/listEnabled
|
||||
只读;IT 在 inq_synonym 维护,停用项不在列表里。
|
||||
"""
|
||||
return self.client.request_json("GET", "/inquiry/agent/synonym/listEnabled")
|
||||
|
||||
def wake_agent_ack(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -648,12 +648,15 @@ class HttpLedger:
|
||||
kind: str = "",
|
||||
raw_text: str = "",
|
||||
raw_source: str = "",
|
||||
sender_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
手工报价 / 销售调价写入主账新版本。
|
||||
|
||||
幂等键带合计和备注,避免连续调价被同一把钥匙吞掉。
|
||||
raw_text:产品群内原话,主账只留档参考,不参与金额解析。
|
||||
sender_id:本次报价人企微 userid。主账据此记「处理人」互动快照,
|
||||
转人工拉群时只被拉进来、没报价的人不该出现在处理人列。
|
||||
"""
|
||||
src = dict(quote or {})
|
||||
note = (remark or "").strip()
|
||||
@@ -662,6 +665,8 @@ class HttpLedger:
|
||||
"quote": src,
|
||||
"toStatus": to_status,
|
||||
}
|
||||
if (sender_id or "").strip():
|
||||
body["senderWecomId"] = sender_id.strip()
|
||||
if note:
|
||||
body["remark"] = note
|
||||
if (kind or "").strip():
|
||||
|
||||
@@ -52,6 +52,8 @@ class MemoryTicket:
|
||||
collab_chat_id: str = ""
|
||||
collab_facts: dict[str, str] = field(default_factory=dict)
|
||||
collab_member_ids: list[str] = field(default_factory=list)
|
||||
# 有报价/补字段等互动的产品/航线;处理人列只认这份,不认全部群成员。
|
||||
collab_actor_ids: list[str] = field(default_factory=list)
|
||||
product_ids: list[str] = field(default_factory=list)
|
||||
product_names: list[str] = field(default_factory=list)
|
||||
collab_ended: bool = False
|
||||
@@ -792,6 +794,7 @@ class MemoryLedger:
|
||||
kind: str = "",
|
||||
raw_text: str = "",
|
||||
raw_source: str = "",
|
||||
sender_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""手工报价 / 销售调价盖 TMS 价。remark/kind 只给 HTTP 主账记流水。"""
|
||||
_ = remark, kind
|
||||
@@ -799,7 +802,7 @@ class MemoryLedger:
|
||||
work_order_no=work_order_no, quote=quote, to_status=to_status
|
||||
)
|
||||
# 单测里也要能回看产品原话;主账落 inq_quote.raw_text,内存票落在 quote 快照。
|
||||
if out.get("ok") and (raw_text or raw_source):
|
||||
if out.get("ok") and (raw_text or raw_source or sender_id):
|
||||
with self._lock:
|
||||
ticket = self._tickets.get(work_order_no)
|
||||
if ticket is not None:
|
||||
@@ -807,6 +810,9 @@ class MemoryLedger:
|
||||
ticket.quote["raw_text"] = raw_text
|
||||
if raw_source:
|
||||
ticket.quote["raw_source"] = raw_source
|
||||
uid = (sender_id or "").strip()
|
||||
if uid and uid not in ticket.collab_actor_ids:
|
||||
ticket.collab_actor_ids.append(uid)
|
||||
return out
|
||||
|
||||
def patch_collab_facts(
|
||||
@@ -817,11 +823,13 @@ class MemoryLedger:
|
||||
sender_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""合并协同字段。不改六态、不写报价版本。"""
|
||||
_ = sender_id
|
||||
with self._lock:
|
||||
ticket = self._tickets.get(work_order_no)
|
||||
if ticket is None:
|
||||
return {"ok": False, "error": "ticket_not_found"}
|
||||
uid = (sender_id or "").strip()
|
||||
if uid and uid not in ticket.collab_actor_ids:
|
||||
ticket.collab_actor_ids.append(uid)
|
||||
for key, raw in (facts or {}).items():
|
||||
name = str(key or "").strip()
|
||||
if not name:
|
||||
|
||||
@@ -121,6 +121,10 @@ _NUMBERED_ITEM = re.compile(r"(?m)^\s*\d+[\.、.]\s+\S")
|
||||
_CLARIFY_EXAMPLE_LINE = re.compile(r"^\s*[((]如\s*[::]")
|
||||
_CLARIFY_INDEX = re.compile(r"^\s*\d+[\.、.]\s*")
|
||||
_CLARIFY_DECOR = re.compile(r"((?:KG|CBM|kg|cbm|必填|非必填))|\((?:KG|CBM|必填|非必填)\)", re.I)
|
||||
# 值前面误留的装饰词:「(非必填):马尼拉」只取马尼拉。
|
||||
_CLARIFY_DECOR_LEADING = re.compile(
|
||||
r"^\s*[((](?:KG|CBM|必填|非必填)[))]\s*[::]?\s*", re.I
|
||||
)
|
||||
_CLARIFY_NAMES = frozenset(
|
||||
{
|
||||
"起运地",
|
||||
@@ -160,6 +164,7 @@ _CLARIFY_NAMES = frozenset(
|
||||
"派送地址",
|
||||
"通关口岸",
|
||||
"始发站",
|
||||
"客户名称",
|
||||
"增值服务",
|
||||
"尺寸",
|
||||
"货物尺寸",
|
||||
@@ -241,6 +246,9 @@ _TIGHTEN_LABELS = tuple(
|
||||
)
|
||||
)
|
||||
_FEE_NAME = re.compile(r"^\*?[\u4e00-\u9fffA-Za-z0-9]{1,12}费$")
|
||||
# 地名后面贴的运费词由 field_validate.strip_place_fee_tail 统一剥掉。
|
||||
# 见该函数:北京运输费 → 北京;操作费/文件费不剥,仍按费用栏丢掉。
|
||||
|
||||
# 识图/标签错位:报价编号、工单号、长数字进了起运地/目的地。三字码航线不动。
|
||||
_QUOTE_LIKE_PLACE = re.compile(
|
||||
r"^(?:"
|
||||
@@ -614,15 +622,26 @@ def apply_cargo_handover_synonym(
|
||||
|
||||
|
||||
def _drop_fee_place_values(facts: dict[str, str]) -> dict[str, str]:
|
||||
"""起运地/目的地收成「操作费、文件费」时丢掉。那是费用栏,不是港口。"""
|
||||
"""
|
||||
起运地/目的地收成「操作费、文件费」时丢掉。那是费用栏,不是港口。
|
||||
|
||||
「目的地北京运输费」这类地名后面带运费词的,先剥运费词留地名(北京),
|
||||
不能把整段当成费用栏一起丢掉,否则销售写了目的地仍被补问。
|
||||
"""
|
||||
from agent.schema.field_validate import strip_place_fee_tail
|
||||
|
||||
out = dict(facts or {})
|
||||
for key in ("起运港", "起运地", "目的港", "目的地"):
|
||||
val = str(out.get(key) or "").strip()
|
||||
if not val:
|
||||
continue
|
||||
bits = [p.strip(" *::\t") for p in re.split(r"[\n/、,,]+", val) if p.strip()]
|
||||
if bits and all(_FEE_NAME.match(p) for p in bits):
|
||||
kept = [cleaned for cleaned in (strip_place_fee_tail(p) for p in bits) if cleaned]
|
||||
if not kept or all(_FEE_NAME.match(p) for p in kept):
|
||||
out.pop(key, None)
|
||||
continue
|
||||
if kept != bits:
|
||||
out[key] = "、".join(kept)
|
||||
return out
|
||||
|
||||
|
||||
@@ -684,6 +703,25 @@ def _drop_quote_like_place_values(
|
||||
return out
|
||||
|
||||
|
||||
def strip_clarify_prompt_noise(text: str) -> str:
|
||||
"""
|
||||
去掉整段复制补问清单带回来的示例行和提示语。
|
||||
|
||||
「(如:马尼拉)」「请复制粘贴以下内容…」「请确认并补充以下信息:」都不是字段值。
|
||||
模型会把示例行当成收货地址;本地解析也会把下一栏编号并进上一栏。
|
||||
只删整行,不动销售真正填的值。副作用:无。
|
||||
"""
|
||||
kept: list[str] = []
|
||||
for line in (text or "").splitlines():
|
||||
body = (line or "").strip()
|
||||
if _CLARIFY_EXAMPLE_LINE.match(body):
|
||||
continue
|
||||
if is_clarify_ui_prompt(body):
|
||||
continue
|
||||
kept.append(line)
|
||||
return "\n".join(kept)
|
||||
|
||||
|
||||
def extract_inquiry_snapshot(
|
||||
text: str,
|
||||
*,
|
||||
@@ -721,6 +759,9 @@ def extract_inquiry_snapshot(
|
||||
facts = _drop_fee_place_values(_clip_sheet_inquiry_facts(facts))
|
||||
facts = _drop_quote_like_place_values(facts, source_text=text)
|
||||
facts = _apply_air_added_services(text, facts, mode)
|
||||
from agent.policy.synonym import apply_value_synonyms
|
||||
|
||||
facts = apply_value_synonyms(facts, mode)
|
||||
subtype = str(facts.get("运输类型") or "").strip()
|
||||
return {
|
||||
"business_line": mode,
|
||||
@@ -730,6 +771,9 @@ def extract_inquiry_snapshot(
|
||||
}
|
||||
# 附件常是整张报价单。先丢掉费用明细和条款,再抽询价栏。
|
||||
text = prepare_sheet_oral(text)
|
||||
# 整段复制补问清单回来时,示例行/提示语不是销售填的值:
|
||||
# 模型曾把「(如:马尼拉)」抽成收货地址,本地也曾把「10.客户名称」并进贸易条款。
|
||||
text = strip_clarify_prompt_noise(text)
|
||||
mode = detect_transport_mode(text)
|
||||
facts = parse_labeled_facts(text)
|
||||
source = "labeled_or_mode"
|
||||
@@ -781,6 +825,9 @@ def extract_inquiry_snapshot(
|
||||
facts = _drop_quote_like_place_values(facts, source_text=text)
|
||||
facts = _apply_air_added_services(text, facts, mode)
|
||||
facts = separate_air_size_from_volume(facts)
|
||||
from agent.policy.synonym import apply_value_synonyms
|
||||
|
||||
facts = apply_value_synonyms(facts, mode)
|
||||
land_subtype = str((b_payload or {}).get("land_subtype") or facts.get("运输类型") or "").strip()
|
||||
if land_subtype and not str(facts.get("运输类型") or "").strip():
|
||||
facts["运输类型"] = land_subtype
|
||||
@@ -854,6 +901,7 @@ def clip_inquiry_value(raw: str) -> str:
|
||||
text = (raw or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
text = _CLARIFY_DECOR_LEADING.sub("", text).strip()
|
||||
text = re.sub(r"[((]如\s*[::][^))]*[))]?\s*$", "", text).strip()
|
||||
if _CLARIFY_EXAMPLE_LINE.match(text):
|
||||
return ""
|
||||
@@ -879,9 +927,26 @@ def clip_inquiry_value(raw: str) -> str:
|
||||
# 复制补问清单时空着的下一行是「4.提货地址」。切到下一栏后只剩编号,不能当成货好时间。
|
||||
if re.fullmatch(r"\d+[\.、.]", text):
|
||||
return ""
|
||||
# 空栏只剩「(非必填):」「(必填):」这类装饰词时仍是没填。
|
||||
# 运行证据:整段复制补问清单回来,客户名称被赋成「(非必填):」。
|
||||
if is_blank_field_decoration(text):
|
||||
return ""
|
||||
return text
|
||||
|
||||
|
||||
def is_blank_field_decoration(raw: str) -> bool:
|
||||
"""
|
||||
值是否只剩「(必填):」「(非必填):」「(CBM):」这类空栏装饰。
|
||||
|
||||
整段复制补问清单回来时,空栏后面紧接着下一栏标签;只剥装饰词再判,
|
||||
有真值的(如「收货地址(非必填):马尼拉」)仍保留。副作用:无。
|
||||
"""
|
||||
text = (raw or "").strip()
|
||||
if not text:
|
||||
return True
|
||||
return not _CLARIFY_DECOR.sub("", text).strip(" \t::,,、;;")
|
||||
|
||||
|
||||
def _starts_with_inquiry_label(text: str) -> bool:
|
||||
"""
|
||||
值是否以「另一询价栏目标签」开头(可带补问编号、冒号、必填标记)。
|
||||
@@ -1106,7 +1171,12 @@ def _harvest_labels(text: str, labels: tuple[str, ...]) -> dict[str, str]:
|
||||
same_line_body = re.sub(r"^[\s::,,、]+", "", same_line).strip()
|
||||
# 冒号后本行为空 = 未填。禁止跨行把下一栏「目的地:吉隆坡」收成起运地。
|
||||
# 核对卡无换行粘贴时「起运地(非必填): 目的地(必填):CRK」也视为未填。
|
||||
if not same_line_body or _starts_with_inquiry_label(same_line_body):
|
||||
# 只剩「(非必填):」装饰词同样是空栏,不能把下一栏编号并进本栏。
|
||||
if (
|
||||
not same_line_body
|
||||
or is_blank_field_decoration(same_line_body)
|
||||
or _starts_with_inquiry_label(same_line_body)
|
||||
):
|
||||
chunk = ""
|
||||
else:
|
||||
chunk = re.sub(r"^[\s::,,、]+", "", chunk)
|
||||
@@ -1165,7 +1235,9 @@ def extract_collab_fields(
|
||||
val = (merged.get(key) or "").strip()
|
||||
if val:
|
||||
out[key] = val
|
||||
return out
|
||||
from agent.policy.synonym import apply_value_synonyms
|
||||
|
||||
return apply_value_synonyms(out)
|
||||
|
||||
|
||||
def extract_air_collab_fields(
|
||||
@@ -1236,12 +1308,12 @@ _RE_VEHICLE_RATE_ITEM = re.compile(
|
||||
)
|
||||
# 多车型价后的口语备注(非「备注:」格式)
|
||||
_RE_VEHICLE_QUOTE_REMARK = re.compile(
|
||||
r"(含\s*0\s*点\s*税?|含\s*0\s*点|国六车提货|不含税|含税)",
|
||||
r"(?:含)?\s*0\s*(?:点|个点)?\s*税|零\s*税|含\s*0\s*点|国六车提货|不含税|含税",
|
||||
re.I,
|
||||
)
|
||||
# 「都是含0点税」= 税率 0。单独拎出来是因为它还能填税率字段,不只是备注。
|
||||
# 只认 0 点税;「含税/不含税」看不出具体点数,仍只进备注,不许猜成 0 或 13。
|
||||
_RE_ZERO_TAX_WORD = re.compile(r"含\s*0\s*点\s*税?", re.I)
|
||||
# 「含0税/0税/零税」= 税率 0。单独拎出来是因为它还能填税率字段,不只是备注。
|
||||
# 「含税/不含税」看不出具体点数,仍只进备注,不许猜成 0 或 13。
|
||||
_RE_ZERO_TAX_WORD = re.compile(r"(?:含)?\s*0\s*(?:点|个点)?\s*税|零\s*税", re.I)
|
||||
_RE_FUEL_SURCHARGE_RATE = re.compile(
|
||||
r"燃油附加费率\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?",
|
||||
re.I,
|
||||
@@ -1281,7 +1353,9 @@ _RE_AMOUNT_IS_VEHICLE_UNIT = re.compile(r"^\s*(?:T|吨|HQ|GP|尺)\b", re.I)
|
||||
# 分不清是整车价还是每公斤价(测服 WO202611220002 的反馈)。
|
||||
# 必须带 / 或「每」才算单位:「1000元」只是币种后缀,不是计价单位。
|
||||
_RE_AMOUNT_UOM_SUFFIX = re.compile(
|
||||
r"^\s*(?:(?:元|块|RMB|CNY)\s*)?(?:/|每)\s*"
|
||||
# 币种可能写在金额和「/车」之间:「1700HKD/车」。旧名单只认 RMB/CNY,
|
||||
# 港币/美元报价的 /车 会被整段丢掉,摘要只剩 1700 分不清整车还是按票。
|
||||
rf"^\s*(?:(?:元|块|{_CCY_TOKEN})\s*)?(?:/|每)\s*"
|
||||
r"(?P<uom>次/人|小时/人|板数|页数|箱数|单数|票数|公里数|货值|计重|立方|平方米|平方|千克|"
|
||||
r"KGS|KG|CBM|M3|柜|票|板|点|次|人|天|个|份|张|台|件|卷|车|月|趟|周|批|项|托|套|袋|包|箱|吨|T)",
|
||||
re.I,
|
||||
@@ -1294,10 +1368,16 @@ def _amount_uom_suffix(after_amount: str) -> str:
|
||||
|
||||
参数 after_amount 是原文里紧跟在金额数字之后的那一段。
|
||||
返回空串表示没写单位,调用方就不落 unit(禁止本地猜 KG/车)。
|
||||
另外认产品口语「1700车」「1000台」:没有斜杠也按 /车、/台 处理。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
hit = _RE_AMOUNT_UOM_SUFFIX.match(after_amount or "")
|
||||
return (hit.group("uom") or "").strip() if hit else ""
|
||||
if hit:
|
||||
return (hit.group("uom") or "").strip()
|
||||
bare = re.match(
|
||||
r"^\s*(车|台|趟)(?![一-鿿A-Za-z0-9])", after_amount or ""
|
||||
)
|
||||
return bare.group(1) if bare else ""
|
||||
|
||||
# 「压夜按运费80%」「压日按运费100%」是比例,禁止落成 HKD 80/100 再加进合计。
|
||||
_RE_FEE_OF_FREIGHT_PCT = re.compile(
|
||||
@@ -1653,6 +1733,9 @@ def _parse_fee_rows(text: str, baseline_currency: str = "") -> list[dict[str, st
|
||||
amt = _ascii_amount(hit.group("amount") or "")
|
||||
if not name or not amt:
|
||||
continue
|
||||
# 压夜/压日/超时等条款的百分比不是费目;整段已由 split_land_clause 进备注。
|
||||
if _RE_LAND_CLAUSE_FEE_NAME.search(name):
|
||||
continue
|
||||
_add(name, f"{amt}%", "")
|
||||
priced_hits = 0
|
||||
for hit in _RE_FEE_PRICED.finditer(raw):
|
||||
@@ -1688,14 +1771,18 @@ def _parse_fee_rows(text: str, baseline_currency: str = "") -> list[dict[str, st
|
||||
for hit in _RE_FEE_LINE.finditer(raw):
|
||||
amount = _ascii_amount(hit.group("amount") or "")
|
||||
after_amount = raw[hit.end("amount") :]
|
||||
name = (hit.group("name") or "").strip()
|
||||
# 吨位/柜型数字不能当金额(运费10T:… 已被车型价规则吃掉;这里再挡漏网)。
|
||||
if _RE_AMOUNT_IS_VEHICLE_UNIT.match(after_amount):
|
||||
continue
|
||||
# 压夜按运费80%/压日按运费100% 是条件,不是费目;整段已进备注,不再显示成费用行。
|
||||
if re.match(r"\s*%", after_amount or "") and _RE_LAND_CLAUSE_FEE_NAME.search(name):
|
||||
continue
|
||||
# 「80%」保留百分号,合计时只加绝对金额。
|
||||
if re.match(r"\s*%", after_amount or ""):
|
||||
amount = f"{amount}%"
|
||||
_add(
|
||||
(hit.group("name") or "").strip(),
|
||||
name,
|
||||
amount,
|
||||
hit.group("ccy1") or hit.group("ccy2") or "",
|
||||
# 产品自己写的计价单位(1000/车、13元/KG)必须留着,出单和摘要都要用。
|
||||
@@ -2003,13 +2090,24 @@ def extract_product_quote(
|
||||
stripped = strip_land_quote_condition(stripped_all)
|
||||
else:
|
||||
stripped = stripped_all
|
||||
# 陆运附条款(超时/等候/压夜/压日/查验/实报实销)是备注条件,不是费用行。
|
||||
# 有「备注:」标签时按原逻辑整段当备注;没有标签才把句末条款整段切走,
|
||||
# 避免「按运费80%」「200/小时」被费用行正则抽成金额。
|
||||
clause_remark = ""
|
||||
if is_land and not _extract_quote_remark(raw):
|
||||
stripped, clause_remark = split_land_clause(stripped)
|
||||
# 整句只有「压夜按运费80%,压日按运费100%」时切完正文为空;
|
||||
# 后面多处用 `stripped or raw` 回退原文,这里用空格占位,
|
||||
# 否则条款会从原文再被金额回退抽成 80/100。
|
||||
if not stripped.strip():
|
||||
stripped = " "
|
||||
compact = stripped.replace(" ", "").replace(" ", "")
|
||||
if re.fullmatch(r"WO\d{12}", compact, re.I):
|
||||
return {}
|
||||
# 只补报价日期/有效期/时效要求时直接空:年份、天数不能当费用金额。
|
||||
if is_quote_date_only_message(raw) or is_non_fee_meta_only_message(raw):
|
||||
return {}
|
||||
quote_remark = _extract_quote_remark(stripped or raw)
|
||||
quote_remark = _extract_quote_remark(stripped or raw) or clause_remark
|
||||
# 多车型整车价必须先于普通费用行:否则「40HQ/45HQ:19500」会被抽成 HQ=19500。
|
||||
vehicle = _parse_vehicle_rates_quote(
|
||||
stripped or raw, baseline_currency=base_ccy, allow_single=is_land
|
||||
@@ -2113,6 +2211,10 @@ def extract_product_quote(
|
||||
if wb_raw:
|
||||
out["weight_break"] = wb_raw
|
||||
out.update(_extract_rate_fields(raw))
|
||||
# 普通费用行路径也把备注放到顶层:车型价路径一直有,摘要/出单/后台都读这个键,
|
||||
# 只有陆运附条款(超时/压夜)时也要能显示「备注:…」。
|
||||
if is_land and quote_remark and not str(out.get("remark") or "").strip():
|
||||
out["remark"] = quote_remark
|
||||
_attach_land_vehicle_type(out, raw, business_line)
|
||||
return _finalize_land_quote_condition(out, condition)
|
||||
# 剥掉报价日期后只剩空白时,禁止回退到原文再抽金额(否则年份 2026 会当空运费)。
|
||||
@@ -2160,6 +2262,8 @@ def extract_product_quote(
|
||||
"fee_lines": list(rows),
|
||||
}
|
||||
out.update(_extract_rate_fields(raw))
|
||||
if is_land and quote_remark and not str(out.get("remark") or "").strip():
|
||||
out["remark"] = quote_remark
|
||||
_attach_land_vehicle_type(out, raw, business_line)
|
||||
return _finalize_land_quote_condition(out, condition)
|
||||
|
||||
@@ -2271,6 +2375,42 @@ _RE_LAND_CLAUSE_LEAD = re.compile(
|
||||
rf"^\s*(?:{_CCY_TOKEN})?\s*(?:/\s*(?:车|台|趟))?\s*[,,;;。]?\s*",
|
||||
re.I,
|
||||
)
|
||||
# 附条款是「条件句」还是「一笔绝对费用」:
|
||||
# 「压夜按运费80%」「免等候2小时,超出按200/小时」「实报实销」是条件,整段进备注;
|
||||
# 只写「超时费500元」这种绝对金额的,不在这里吞掉,仍按费用行处理。
|
||||
_RE_LAND_CLAUSE_CONDITION = re.compile(
|
||||
r"按\s*运费\s*\d+(?:\.\d+)?\s*%|免\s*等候|超出按|实报实销|实报实|滞柜|滞港",
|
||||
re.I,
|
||||
)
|
||||
# 费用行里命中这些名字的比例条款(压夜/压日/超时/等候/查验/实报实/按运费)
|
||||
# 一律不当费目:金额是百分比,不是整票金额(产品 2026-11-23 口径)。
|
||||
_RE_LAND_CLAUSE_FEE_NAME = re.compile(
|
||||
r"超时|等候|压夜|压日|滞柜|滞港|查验|实报实|按运费",
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
def split_land_clause(text: str) -> tuple[str, str]:
|
||||
"""
|
||||
把陆运报价末尾的附条款整段切开:返回 (正文, 条款)。
|
||||
|
||||
「运费1700HKD/车。超时费:免等候2小时…压夜按运费80%,压日按运费100%…」
|
||||
超时/等候/压夜/压日/查验/实报实销是备注条件,不是另一笔费用;
|
||||
切走后正文只剩主运费,条款整段进 remark,避免 80%/200 被当金额抽出来。
|
||||
只有命中条件词才切;「超时费500元」这种绝对金额原样留在正文。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
raw = text or ""
|
||||
hit = _RE_LAND_CLAUSE_HINT.search(raw)
|
||||
if not hit:
|
||||
return raw, ""
|
||||
tail = raw[hit.start():]
|
||||
if not _RE_LAND_CLAUSE_CONDITION.search(tail):
|
||||
return raw, ""
|
||||
head = raw[: hit.start()].rstrip(" \t\r\n,,;;。::")
|
||||
tail = re.sub(r"^[\s,,;;。::]+", "", tail)
|
||||
tail = re.sub(r"\s+", " ", tail).strip()
|
||||
return head, tail
|
||||
|
||||
|
||||
def _vehicle_label_after_freight_fee(raw: str, start: int) -> bool:
|
||||
@@ -2312,6 +2452,23 @@ def _land_vehicle_clause_remark(raw: str, end: int) -> str:
|
||||
return tail
|
||||
|
||||
|
||||
def _land_tail_has_absolute_fee(raw: str, end: int) -> bool:
|
||||
"""
|
||||
车型价后面除了条款比例,是否还有别的绝对金额费用行。
|
||||
|
||||
例:「运费10T:1700HKD/车 报关费300CNY」里 300 是另一笔费用,
|
||||
不能整单落成车型价把报关费吞掉;这时退回带费名的费用行路径。
|
||||
「压夜按运费80%」是比例条件,不算绝对金额。副作用:无。
|
||||
"""
|
||||
tail = (raw or "")[end:]
|
||||
if not tail.strip():
|
||||
return False
|
||||
for row in _parse_fee_rows(tail):
|
||||
if "%" not in str(row.get("amount") or ""):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_vehicle_rates_quote(
|
||||
text: str, baseline_currency: str = "", *, allow_single: bool = False
|
||||
) -> dict[str, Any]:
|
||||
@@ -2370,7 +2527,11 @@ def _parse_vehicle_rates_quote(
|
||||
if not prev:
|
||||
continue
|
||||
if prev.isalnum() or "\u4e00" <= prev <= "\u9fff":
|
||||
if _vehicle_label_after_freight_fee(raw, start):
|
||||
# 紧贴主运费费名且后面只有条款比例/说明时,才按车型价落;
|
||||
# 后面还写着「报关费300」这类绝对金额,退回费用行,别把杂费吞掉。
|
||||
if _vehicle_label_after_freight_fee(raw, start) and not (
|
||||
_land_tail_has_absolute_fee(raw, hit.end())
|
||||
):
|
||||
continue
|
||||
single_ok = False
|
||||
break
|
||||
@@ -2379,7 +2540,7 @@ def _parse_vehicle_rates_quote(
|
||||
# 「运费10T:1700HKD/车」后面的超时费/压夜压日/实报实销整段是备注条件,
|
||||
# 不是另一笔费用;不抽成费用行,避免 80/100 被当 HKD 再加进合计。
|
||||
clause_remark = ""
|
||||
if allow_single and hits:
|
||||
if allow_single and len(rates) == 1 and hits:
|
||||
last = hits[-1]
|
||||
if _vehicle_label_after_freight_fee(raw, last.start("label")):
|
||||
clause_remark = _land_vehicle_clause_remark(raw, last.end())
|
||||
|
||||
@@ -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, "")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
|
||||
@@ -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}
|
||||
@@ -208,29 +208,35 @@ def ensure_group_bot_line(chat_id: str, fallback: str = "AIR") -> str:
|
||||
return line
|
||||
|
||||
|
||||
def _text_fingerprint(text: str) -> str:
|
||||
def _text_fingerprint(text: str, sender_id: str = "") -> str:
|
||||
"""
|
||||
群文字指纹:去空白后取 sha1 前 20 位。
|
||||
群文字指纹:发送人 + 去空白正文,取 sha1 前 20 位。
|
||||
|
||||
为什么要去空白:同一句在 AIBOT 回调与会话存档里,换行/空格可能被平台改写,
|
||||
原样比较会漏判,导致同一句被办两遍。
|
||||
为什么要带发送人:同群两个不同的人发同一句话不是同一条消息。
|
||||
2026-11-23 真机:林绵勋发报价被拒「只有航线能报」后,吴季林发同一句,
|
||||
旧指纹只看正文,把吴季林那条当成重复静默吞掉,群里表现为「没响应」。
|
||||
"""
|
||||
compact = "".join(str(text or "").split())
|
||||
return hashlib.sha1(compact.encode("utf-8")).hexdigest()[:20]
|
||||
sender = str(sender_id or "").strip()
|
||||
blob = f"{sender}|{compact}" if sender else compact
|
||||
return hashlib.sha1(blob.encode("utf-8")).hexdigest()[:20]
|
||||
|
||||
|
||||
def mark_bot_text_handled(chat_id: str, text: str) -> None:
|
||||
def mark_bot_text_handled(chat_id: str, text: str, sender_id: str = "") -> None:
|
||||
"""
|
||||
记下「这条群文字已由 AIBOT 回调办过」。
|
||||
|
||||
用途:会话存档会旁听到同一句 @BOT(尤其空运),若再走一遍 handler
|
||||
就会把同一份工单摘要/模板发两遍(2026-11-19 测服真机复现)。
|
||||
sender_id 参与指纹:不同人发同一句不能被当成重复。
|
||||
TTL 5 分钟只覆盖存档延迟窗口,过期即失效,不当业务状态用。
|
||||
"""
|
||||
_write_handled(chat_id, text, retry_archive=False)
|
||||
_write_handled(chat_id, text, retry_archive=False, sender_id=sender_id)
|
||||
|
||||
|
||||
def allow_archive_retry(chat_id: str, text: str) -> None:
|
||||
def allow_archive_retry(chat_id: str, text: str, sender_id: str = "") -> None:
|
||||
"""
|
||||
撤销「这句已办过」的去重,允许会话存档那条(明文身份)再办一遍。
|
||||
|
||||
@@ -240,17 +246,19 @@ def allow_archive_retry(chat_id: str, text: str) -> None:
|
||||
结果是销售明明本人点成交,群里却一直回「只有负责该工单的销售可以确认成交状态」。
|
||||
身份换不成明文时,AIBOT 那条的结论不可信,必须让存档补办。
|
||||
"""
|
||||
_write_handled(chat_id, text, retry_archive=True)
|
||||
_write_handled(chat_id, text, retry_archive=True, sender_id=sender_id)
|
||||
|
||||
|
||||
def _write_handled(chat_id: str, text: str, *, retry_archive: bool) -> None:
|
||||
def _write_handled(
|
||||
chat_id: str, text: str, *, retry_archive: bool, sender_id: str = ""
|
||||
) -> None:
|
||||
"""
|
||||
写「已办」标记。retry_archive=True 时打上 `#retry` 后缀,读侧据此不再去重。
|
||||
|
||||
存储值形如 `abcdef0123456789ab`(去重生效)或 `abcdef0123456789ab#retry`(放行存档)。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
fingerprint = _text_fingerprint(text)
|
||||
fingerprint = _text_fingerprint(text, sender_id)
|
||||
if not room or not fingerprint:
|
||||
return
|
||||
value = fingerprint + _RETRY_SUFFIX if retry_archive else fingerprint
|
||||
@@ -265,15 +273,15 @@ def _write_handled(chat_id: str, text: str, *, retry_archive: bool) -> None:
|
||||
logger.warning("group_bot 记 AIBOT 已办文字失败 chat=%s", room, exc_info=True)
|
||||
|
||||
|
||||
def bot_text_handled(chat_id: str, text: str) -> bool:
|
||||
def bot_text_handled(chat_id: str, text: str, sender_id: str = "") -> bool:
|
||||
"""
|
||||
这条群文字是否已经被 AIBOT 回调办过(同群 5 分钟内同文)。
|
||||
这条群文字是否已经被 AIBOT 回调办过(同群同人 5 分钟内同文)。
|
||||
|
||||
带 `#retry` 后缀表示「AIBOT 那条身份不可信,允许存档补办」,这里返回 False。
|
||||
Redis 不可用时退回进程内记录;两者都没有就返回 False,让存档按老逻辑补听。
|
||||
"""
|
||||
room = (chat_id or "").strip()
|
||||
fingerprint = _text_fingerprint(text)
|
||||
fingerprint = _text_fingerprint(text, sender_id)
|
||||
if not room or not fingerprint:
|
||||
return False
|
||||
with _guard:
|
||||
|
||||
@@ -55,6 +55,8 @@ WSHOTO_ROOM_TICKET = "wshoto:room_ticket"
|
||||
QUOTE_FILE_READY = "quote_file_ready"
|
||||
# 产品刚报价、等选「在TMS上改 / 不用TMS」:短协调,不当六态
|
||||
PENDING_PRODUCT_QUOTE = "pending_product_quote"
|
||||
# 产品报价/销售调价先回识别回执,等成员@机器人回「确认/确定」后再出价格方案/改价
|
||||
PENDING_QUOTE_CONFIRM = "pending_quote_confirm"
|
||||
# 陆运核对卡已出、等确定查价:短协调,不当六态、不当工单号
|
||||
PENDING_LAND_CONFIRM = "pending_land_confirm"
|
||||
# 空运群问过「是否需要取消舱位」:短协调,不当六态
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
待确认的报价/调价:机器人先回识别回执,等成员@机器人回「确认/确定」后再出价格方案/改价。
|
||||
|
||||
短协调,不当六态、不当 checkpoint。Redis 正式;进程内兜底给单测和 Redis 不可用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from agent.redis_coord.keys import PENDING_QUOTE_CONFIRM
|
||||
from agent.redis_coord.runtime import get_redis_runtime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 两天:跨夜也能确认;过期就当没有待确认。
|
||||
_TTL_SEC = 2 * 24 * 3600
|
||||
_local: dict[str, dict[str, Any]] = {}
|
||||
|
||||
|
||||
def _no(work_order_no: str) -> str:
|
||||
return (work_order_no or "").strip()
|
||||
|
||||
|
||||
def save_pending_confirm(work_order_no: str, payload: dict[str, Any]) -> None:
|
||||
"""记下刚抽出的报价/调价,等成员确认。"""
|
||||
no = _no(work_order_no)
|
||||
if not no or not isinstance(payload, dict) or not payload:
|
||||
return
|
||||
data = dict(payload)
|
||||
data["_ts"] = time.time()
|
||||
_local[no] = data
|
||||
try:
|
||||
client = get_redis_runtime().client
|
||||
client.raw.set(
|
||||
client.key(PENDING_QUOTE_CONFIRM, no),
|
||||
json.dumps(data, ensure_ascii=False),
|
||||
ex=_TTL_SEC,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("写待确认报价失败 wo=%s", no)
|
||||
|
||||
|
||||
def load_pending_confirm(work_order_no: str) -> dict[str, Any]:
|
||||
"""取出待确认报价/调价。没有或过期返回空。"""
|
||||
no = _no(work_order_no)
|
||||
if not no:
|
||||
return {}
|
||||
local = _local.get(no)
|
||||
if local:
|
||||
return dict(local)
|
||||
try:
|
||||
client = get_redis_runtime().client
|
||||
raw = client.raw.get(client.key(PENDING_QUOTE_CONFIRM, no))
|
||||
if not raw:
|
||||
return {}
|
||||
if isinstance(raw, bytes):
|
||||
raw = raw.decode("utf-8")
|
||||
data = json.loads(raw)
|
||||
return dict(data) if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
logger.exception("读待确认报价失败 wo=%s", no)
|
||||
return {}
|
||||
|
||||
|
||||
def clear_pending_confirm(work_order_no: str) -> None:
|
||||
"""确认/覆盖/作废后清掉,避免下一句误用旧价。"""
|
||||
no = _no(work_order_no)
|
||||
if not no:
|
||||
return
|
||||
_local.pop(no, None)
|
||||
try:
|
||||
client = get_redis_runtime().client
|
||||
client.raw.delete(client.key(PENDING_QUOTE_CONFIRM, no))
|
||||
except Exception:
|
||||
logger.exception("清待确认报价失败 wo=%s", no)
|
||||
@@ -306,7 +306,7 @@ def _allow_archive_retry_if_untrusted(
|
||||
return
|
||||
from agent.redis_coord.group_bot import allow_archive_retry
|
||||
|
||||
allow_archive_retry(chat_id, raw_text)
|
||||
allow_archive_retry(chat_id, raw_text, message.sender_id)
|
||||
logger.info(
|
||||
"dispatch 身份不可信被拒,放行存档补办 chat=%s phase=%s", chat_id, phase
|
||||
)
|
||||
@@ -610,7 +610,7 @@ def dispatch_inbound(message: InboundMessage, decision: RouteDecision) -> str:
|
||||
if raw_text:
|
||||
# 记下这条已由 AIBOT 办过:会话存档会旁听到同一句(空运必现),
|
||||
# 不记就会把同一份摘要/模板发两遍。
|
||||
mark_bot_text_handled(chat_id, raw_text)
|
||||
mark_bot_text_handled(chat_id, raw_text, message.sender_id)
|
||||
# 群里 @BOT 带图片:企微只推 mixed(文字+图片),图片是加密临时 URL,本链路不下载。
|
||||
# 只有图没有字时,handler 会把空正文当文字去要工单号,等于对着图片回话;
|
||||
# 产品口径(2026-11-19):这类整条静默,不入库也不提示。
|
||||
@@ -745,7 +745,7 @@ def dispatch_inbound(message: InboundMessage, decision: RouteDecision) -> str:
|
||||
chat_id,
|
||||
)
|
||||
return "air_group_collab"
|
||||
if not bot_text_handled(chat_id, raw_text):
|
||||
if not bot_text_handled(chat_id, raw_text, message.sender_id):
|
||||
# 普通文字(非 @BOT)=这次指令结束:之后的附件必须重新 @BOT。
|
||||
# 存档回声(AIBOT 刚办过的同一句)不算,否则 @ 完立刻被自己清掉。
|
||||
clear_at_burst(chat_id)
|
||||
@@ -843,7 +843,7 @@ def dispatch_inbound(message: InboundMessage, decision: RouteDecision) -> str:
|
||||
)
|
||||
if missed_at:
|
||||
# AIBOT 已经办过同一句:存档这条是旁听重复,不能再办一遍。
|
||||
if bot_text_handled(chat_id, raw_text):
|
||||
if bot_text_handled(chat_id, raw_text, message.sender_id):
|
||||
logger.info(
|
||||
"dispatch air_group archive_dup_ignore chat=%s wo=%s",
|
||||
chat_id,
|
||||
|
||||
@@ -621,6 +621,20 @@ def harvest_oral_measures(text: str, facts: dict[str, str] | None = None) -> dic
|
||||
pack = _harvest_packaging(raw)
|
||||
if pack:
|
||||
merged["包装方式"] = pack
|
||||
# 「1板 / 2箱 / 3托」:件数保留原文,包装方式写标准值。
|
||||
# 主账不可用时用内置兜底;异常不能挡住询价。
|
||||
try:
|
||||
from agent.policy.synonym import harvest_package_count
|
||||
|
||||
package_count = harvest_package_count(raw)
|
||||
except Exception:
|
||||
package_count = {}
|
||||
if package_count:
|
||||
if not str(merged.get("件数") or "").strip():
|
||||
merged["件数"] = str(package_count.get("件数") or "")
|
||||
std_pack = str(package_count.get("包装方式") or "").strip()
|
||||
if std_pack:
|
||||
merged["包装方式"] = std_pack
|
||||
labeled_date = _quote_date_labeled_value(raw)
|
||||
if labeled_date:
|
||||
merged["报价日期"] = labeled_date
|
||||
@@ -978,25 +992,58 @@ def _pricing_required_keys(
|
||||
|
||||
_PLACE_KEYS = ("起运港", "目的港")
|
||||
_PACK_IN_PLACE = ("散货", "纸箱", "木箱", "托盘", "卡板", "木托")
|
||||
_PRICE_TAIL = re.compile(r"(的价格|的报价|价格|报价)$")
|
||||
# 地名后面紧贴的运费词:「目的地北京运输费」「吉隆坡运费」。
|
||||
# 运费词是销售在说「查这段运费」,不是地名。只剥运输/空运/陆运/货运的「…费」和
|
||||
# 「运费」,不能把「操作费」「文件费」剥成「操作」「文件」当地名。
|
||||
# 不把「海运」整词列进来:地名为「上海」时,上海运费必须先剥「运费」变上海,
|
||||
# 不能剥「海运费」只剩下「上」。剥完只剩「海/空/陆/货」的,按纯运费词丢。
|
||||
_RE_PLACE_FEE_TAIL = re.compile(
|
||||
r"(?:(?:运输|空运|陆运|货运)费(?:用)?|运费(?:用)?|(?:的)?(?:价格|报价|询价|查价))$"
|
||||
)
|
||||
_PLACE_FEE_REMNANTS = frozenset(
|
||||
{"海", "空", "陆", "货", "运", "空运", "海运", "陆运", "货运", "运输"}
|
||||
)
|
||||
|
||||
|
||||
def strip_place_fee_tail(raw: str) -> str:
|
||||
"""
|
||||
地名后面贴的运费词剥掉,只留地名:北京运输费 → 北京、上海运费 → 上海。
|
||||
|
||||
「运输费用」「运费」「的价格」「报价」可连续出现,剥到不变为止。
|
||||
整段就是运费词时返回空串,调用方按费用栏丢掉。
|
||||
不剥「操作费」「文件费」:那不是地名的尾巴,调用方仍会整段丢弃。
|
||||
副作用:无。
|
||||
"""
|
||||
text = (raw or "").strip()
|
||||
while text:
|
||||
cleaned = _RE_PLACE_FEE_TAIL.sub("", text).strip(" \t,,。;;、::")
|
||||
if cleaned == text:
|
||||
break
|
||||
text = cleaned
|
||||
return "" if text in _PLACE_FEE_REMNANTS else text
|
||||
|
||||
|
||||
def peel_trailing_place_clauses(facts: dict[str, str] | None) -> dict[str, str]:
|
||||
"""
|
||||
起运地/目的地只留逗号前的地名。
|
||||
起运地/目的地只留逗号前的地名,并剥掉贴在地名后的运费词。
|
||||
|
||||
口语「目的地吉隆坡,普货,散货的价格」会被抽成一整串目的地。
|
||||
逗号后面的品名、包装、价格不是地名,拆回去;已有品名/包装不覆盖。
|
||||
「目的地北京运输费」没有逗号时也要剥成北京,否则会被当成整段费用丢掉。
|
||||
"""
|
||||
merged = dict(facts or {})
|
||||
for key in _PLACE_KEYS:
|
||||
raw = (merged.get(key) or "").strip()
|
||||
parts = [p.strip() for p in re.split(r"[,,、]", raw) if p.strip()]
|
||||
if len(parts) <= 1:
|
||||
if not raw:
|
||||
continue
|
||||
place = parts[0]
|
||||
parts = [p.strip() for p in re.split(r"[,,、]", raw) if p.strip()]
|
||||
if not parts:
|
||||
merged.pop(key, None)
|
||||
continue
|
||||
# 地名本身也剥运费词:「北京运输费」不留逗号也照样只留北京。
|
||||
place = strip_place_fee_tail(parts[0])
|
||||
for part in parts[1:]:
|
||||
part = _PRICE_TAIL.sub("", part).strip()
|
||||
part = strip_place_fee_tail(part)
|
||||
if not part or part in {"价格", "报价", "查价"}:
|
||||
continue
|
||||
if part in _PACK_IN_PLACE and not (merged.get("包装方式") or "").strip():
|
||||
@@ -1004,7 +1051,11 @@ def peel_trailing_place_clauses(facts: dict[str, str] | None) -> dict[str, str]:
|
||||
continue
|
||||
if not (merged.get("品名") or "").strip() and not looks_like_container_spec(part):
|
||||
merged["品名"] = part
|
||||
merged[key] = place
|
||||
if place:
|
||||
merged[key] = place
|
||||
else:
|
||||
# 整段就是「运输费/价格」时,这一栏其实是空的,不能当地名往下查价。
|
||||
merged.pop(key, None)
|
||||
return merged
|
||||
|
||||
|
||||
|
||||
@@ -59,6 +59,12 @@ MAX_OPTIONS_PER_QUESTION = 10
|
||||
# 点卡回调靠它认出「这是陆运补问卡」,不按书签里残留的其它运输线去猜。
|
||||
CARD_KIND = "land_options"
|
||||
|
||||
# 多段联运里的陆运补问卡。卡种必须独立:
|
||||
# 回调路由按 task_id 认卡种,普通 land_options 归单聊陆运;
|
||||
# 多段这张要回多段草稿,否则会被单聊陆运当成过期卡或另开一单。
|
||||
# 提交按钮仍复用 land_options_submit,动作枚举不用再加一条。
|
||||
MULTI_CARD_KIND = "multi_land_options"
|
||||
|
||||
# 合并后的两个问题键。回调按 QuestionKey 原样回传,必须与出卡一致。
|
||||
QUESTION_BIZ = "biz_type"
|
||||
QUESTION_SCENARIO = "quote_scenario"
|
||||
@@ -258,6 +264,7 @@ def land_option_card_payload(
|
||||
facts: Mapping[str, Any] | None = None,
|
||||
note: str = "",
|
||||
cargo_missing: Optional[bool] = None,
|
||||
card_kind: str = CARD_KIND,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""
|
||||
陆运补问卡载荷(业务类型 + 报价场景 两项)。
|
||||
@@ -270,6 +277,8 @@ def land_option_card_payload(
|
||||
cargo_missing 货物品名是否还缺。缺就把它排进「待补充」清单里一起说,
|
||||
不再单独写一句「提交后回复货物品名」。
|
||||
传 None(默认)时按 facts 里的品名自动判断,调用方忘了传也不会漏。
|
||||
card_kind 卡种前缀。单聊陆运用默认值;多段联运传 MULTI_CARD_KIND,
|
||||
回调按 task_id 认回多段草稿。
|
||||
|
||||
返回:企微 template_card 载荷;两种情况返回 None,由调用方回落到文字:
|
||||
1. 两项都齐、只缺品名——卡片收不了自由文字,空卡只会让销售白点一次提交;
|
||||
@@ -332,7 +341,7 @@ def land_option_card_payload(
|
||||
"template_card": {
|
||||
"card_type": "multiple_interaction",
|
||||
"source": {"desc": "陆运补问", "desc_color": 0},
|
||||
"task_id": copy.card_task_id(CARD_KIND, token),
|
||||
"task_id": copy.card_task_id(card_kind or CARD_KIND, token),
|
||||
"main_title": {"title": head, "desc": desc},
|
||||
"select_list": select_list,
|
||||
"submit_button": {
|
||||
|
||||
@@ -49,7 +49,8 @@ _RE_UNTAXED_RATE = re.compile(
|
||||
)
|
||||
# 只写「未含税」不带点数:税率必须留空,禁止退化成 0。
|
||||
_RE_UNTAXED = re.compile(r"未\s*含\s*税(?!\s*[::=]?\s*\d)")
|
||||
_RE_ZERO_TAX = re.compile(r"含\s*0\s*(?:点)?\s*税")
|
||||
# 「含0税」「含0点税」,以及口语「0税」「0点税」「零税」都算税率 0。
|
||||
_RE_ZERO_TAX = re.compile(r"(?:含)?\s*0\s*(?:点|个点)?\s*税|零\s*税")
|
||||
|
||||
# 剥条件句用:比识别正则更宽松,连同后面的点数一起拿掉,
|
||||
# 防止「含燃油费13%」被费用行正则当成费目「含燃油费:13」。
|
||||
@@ -59,7 +60,7 @@ _RE_STRIP_FUEL = re.compile(
|
||||
_RE_STRIP_TAX = re.compile(
|
||||
r"未\s*含\s*税(?:\s*[::=]?\s*\d+(?:\.\d+)?\s*%?)?"
|
||||
)
|
||||
_RE_STRIP_ZERO_TAX = re.compile(r"含\s*0\s*(?:点)?\s*税")
|
||||
_RE_STRIP_ZERO_TAX = re.compile(r"(?:含)?\s*0\s*(?:点|个点)?\s*税|零\s*税")
|
||||
|
||||
# 主运费费目:只有这些才乘燃油;含提货/送货/报关等杂费词的一律排除。
|
||||
_MAIN_FREIGHT_WORDS = ("运输费", "陆运费", "运费", "干线费", "拖车费", "车费")
|
||||
|
||||
@@ -871,6 +871,112 @@ def extract_adjust(
|
||||
)
|
||||
|
||||
|
||||
# 调价尝试的粗筛词:只要句子里出现这些,就算销售在试图调价。
|
||||
# 不能把「价格」「报价」单独放进来,否则「这个价格再谈谈」也会被当调价。
|
||||
_ADJUST_ATTEMPT_HINTS = re.compile(
|
||||
r"上调|下调|上涨|下降|上浮|下浮|提高|提升|降低|增加|减少|"
|
||||
r"调整|改[成为到]|调到|涨到|升到|加到|减到|增至|变为|变成|"
|
||||
r"加\s*\d|减\s*\d|\d+(?:\.\d+)?\s*[%%]|[一二三四五六七八九十]\s*成"
|
||||
)
|
||||
# 「加一成」的口语:一=10%,二=20%…十=100%。
|
||||
_CHENG_NUM = {
|
||||
"一": 10, "二": 20, "三": 30, "四": 40, "五": 50,
|
||||
"六": 60, "七": 70, "八": 80, "九": 90, "十": 100,
|
||||
}
|
||||
|
||||
|
||||
def inspect_adjust_recognition(
|
||||
text: str,
|
||||
extract: AdjustExtract,
|
||||
*,
|
||||
fee_names: list[str] | None = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""
|
||||
判断这句话是不是调价尝试,以及识别程度。
|
||||
|
||||
返回 None:不像调价,调用方按原流程继续,禁止乱回调价提示。
|
||||
返回 {"status": full/partial/none, "recognized": [...], "missing": [...]}。
|
||||
「部分」= 有费用名没幅度、有幅度没费用名、或只写了「改成」没写值。
|
||||
副作用:无。线程:纯函数。
|
||||
"""
|
||||
raw = (text or "").strip()
|
||||
if not raw:
|
||||
return None
|
||||
names = [str(n).strip() for n in (fee_names or []) if str(n).strip()]
|
||||
items = list(getattr(extract, "items", []) or [])
|
||||
wants_total = bool(getattr(extract, "wants_total", False))
|
||||
# 完整的调价:至少一项有值,且点名了费用(或明确只改总价)。
|
||||
complete = bool(getattr(extract, "is_adjust", False)) and any(
|
||||
float(it.value or 0) > 0
|
||||
and (str(it.fee_name or "").strip() or wants_total)
|
||||
for it in items
|
||||
)
|
||||
looks = bool(getattr(extract, "is_adjust", False)) or bool(
|
||||
_ADJUST_ATTEMPT_HINTS.search(raw)
|
||||
)
|
||||
if not looks:
|
||||
return None
|
||||
if complete:
|
||||
return {"status": "full", "recognized": [], "missing": []}
|
||||
|
||||
recognized: list[str] = []
|
||||
missing: list[str] = []
|
||||
hit_name = ""
|
||||
for name in sorted(names, key=len, reverse=True):
|
||||
if name and name in raw:
|
||||
hit_name = name
|
||||
break
|
||||
if not hit_name:
|
||||
for word in _TOTAL_WORDS:
|
||||
if word in raw:
|
||||
hit_name = word
|
||||
break
|
||||
if hit_name:
|
||||
recognized.append(f"费用名:{hit_name}")
|
||||
else:
|
||||
missing.append("费用名")
|
||||
|
||||
pct = ""
|
||||
for rx in (_PERCENT_UP, _PERCENT_DOWN, _PERCENT_TO):
|
||||
hit = rx.search(raw)
|
||||
if hit:
|
||||
pct = hit.group(0).replace(" ", "")
|
||||
break
|
||||
if not pct:
|
||||
cheng = re.search(r"([一二三四五六七八九十])\s*成", raw)
|
||||
if cheng:
|
||||
pct = f"{cheng.group(1)}成({_CHENG_NUM.get(cheng.group(1), '')}%)"
|
||||
if pct:
|
||||
recognized.append(f"调整幅度:{pct}")
|
||||
else:
|
||||
target = _TARGET.search(raw)
|
||||
if target:
|
||||
recognized.append(f"目标金额:{target.group(0).replace(' ', '')}")
|
||||
else:
|
||||
missing.append("调整幅度或目标金额")
|
||||
|
||||
direction = ""
|
||||
if _PERCENT_DOWN.search(raw) or any(
|
||||
x in raw for x in ("下调", "下降", "降低", "减", "降")
|
||||
):
|
||||
direction = "下调"
|
||||
elif _PERCENT_UP.search(raw) or any(
|
||||
x in raw
|
||||
for x in ("上调", "上涨", "上升", "上浮", "提高", "提升", "加", "涨", "升")
|
||||
):
|
||||
direction = "上调"
|
||||
elif re.search(r"改[成为到]|调整[到成]|调到", raw):
|
||||
direction = "改为"
|
||||
if direction:
|
||||
recognized.append(f"调整方式:{direction}")
|
||||
|
||||
return {
|
||||
"status": "partial" if recognized else "none",
|
||||
"recognized": recognized,
|
||||
"missing": list(dict.fromkeys(missing)),
|
||||
}
|
||||
|
||||
|
||||
def _local_fee_items(raw: str, names_sorted: list[str]) -> list[AdjustItem]:
|
||||
"""按分句把点名费目/小计抽成调价项。提升/上调等口令都认。"""
|
||||
items: list[AdjustItem] = []
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
"""
|
||||
报价识别分级:完整 / 部分 / 全无。
|
||||
|
||||
产品 2026-11-23 口径:
|
||||
* 标准话术完整:解析字段入工单,原话进「原始报价参考」;
|
||||
* 只识别到一部分:回「我识别内容为…,请确认是否正确」;
|
||||
* 全无:回「我无法识别您的内容,请按格式重新报价」,原话仍留档。
|
||||
|
||||
本模块只判断识别程度、生成回执和格式样例;不写主账、不发企微。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Optional
|
||||
|
||||
# 空运航线对:NKG-KUL / NKG/KUL / NKG—KUL。
|
||||
_AIR_ROUTE = re.compile(r"\b([A-Za-z]{3})\s*[-–—/]\s*([A-Za-z]{3})\b")
|
||||
# 空运标签写法:起运地NKG、目的港KUL。
|
||||
_AIR_ROUTE_LABEL = re.compile(
|
||||
r"(?:起运地|起运港|目的地|目的港)\s*([A-Za-z]{3})(?![A-Za-z])", re.I
|
||||
)
|
||||
# 陆运线路:东莞-春疆、深圳--香港、东莞到春疆。
|
||||
_LAND_ROUTE = re.compile(
|
||||
r"(?P<o>[一-鿿]{2,12})\s*(?:--|—|-|-|到|至)\s*(?P<d>[一-鿿]{2,12})"
|
||||
)
|
||||
# 陆运车型:10T、45HQ、7.6米、40GP、45尺柜。
|
||||
_LAND_VEHICLE = re.compile(r"\d+(?:\.\d+)?\s*(?:尺柜|T|吨|HQ|GP|尺|米)", re.I)
|
||||
|
||||
|
||||
def business_line_of(business_line: str = "", transport_mode: str = "") -> str:
|
||||
"""统一成 AIR / LAND / SEA;认不出返回空串。"""
|
||||
line = (business_line or "").strip().upper()
|
||||
if line in {"AIR", "LAND", "SEA"}:
|
||||
return line
|
||||
mode = (transport_mode or "").strip()
|
||||
if mode in {"空运", "AIR", "air"}:
|
||||
return "AIR"
|
||||
if mode in {"陆运", "LAND", "land"}:
|
||||
return "LAND"
|
||||
if mode in {"海运", "SEA", "sea"}:
|
||||
return "SEA"
|
||||
return ""
|
||||
|
||||
|
||||
def quote_format_hint(business_line: str = "", transport_mode: str = "") -> str:
|
||||
"""
|
||||
该业务线要求产品按什么格式重报。
|
||||
|
||||
空运/陆运用产品 2026-11-23 定的样例;海运暂无标准话术,
|
||||
用「费用名+金额+币种」兜底,后续定了再换。
|
||||
"""
|
||||
line = business_line_of(business_line, transport_mode)
|
||||
if line == "AIR":
|
||||
return "工单号,USD11/kg、TH、NKG-KUL、11月2日"
|
||||
if line == "LAND":
|
||||
return "东莞-春疆,危险品,45HQ,CNY18500;都是含0点税"
|
||||
return "费用名+金额+币种,例如“码头操作费100CNY,报关费300CNY”"
|
||||
|
||||
|
||||
def _has_price(quote: dict[str, Any]) -> bool:
|
||||
"""报价里有没有可入账的金额(费用行/车型价/分档价/合计)。"""
|
||||
if not quote:
|
||||
return False
|
||||
if quote.get("vehicleRates") or quote.get("vehicle_rates"):
|
||||
return True
|
||||
if quote.get("weightPrices") or quote.get("weight_prices"):
|
||||
return True
|
||||
for row in quote.get("fee_rows") or quote.get("fee_lines") or []:
|
||||
if isinstance(row, dict) and str(row.get("amount") or "").strip():
|
||||
return True
|
||||
return str(quote.get("total") or "").strip() not in {"", "-", "—", "-"}
|
||||
|
||||
|
||||
def _air_price_line(quote: dict[str, Any]) -> str:
|
||||
"""空运回执的价格行:空运费:USD11/kg。"""
|
||||
ccy = str(quote.get("currency") or "").strip()
|
||||
for row in quote.get("fee_rows") or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
name = str(row.get("name") or "空运费").strip() or "空运费"
|
||||
amount = str(row.get("unit_price") or row.get("amount") or "").strip()
|
||||
unit = str(row.get("unit") or "").strip()
|
||||
if not amount:
|
||||
continue
|
||||
if unit.upper() in {"KG", "KGS"}:
|
||||
return f"{name}:{ccy}{amount}/{unit.lower()}"
|
||||
return f"{name}:{ccy}{amount}"
|
||||
total = str(quote.get("total") or "").strip()
|
||||
return f"空运费:{ccy}{total}" if total else ""
|
||||
|
||||
|
||||
def _land_price_lines(quote: dict[str, Any]) -> list[str]:
|
||||
"""陆运回执的价格行:车型价逐档,或普通费用行逐项。"""
|
||||
out: list[str] = []
|
||||
ccy = str(quote.get("currency") or "").strip()
|
||||
rates = quote.get("vehicleRates") or quote.get("vehicle_rates")
|
||||
if isinstance(rates, dict) and rates:
|
||||
for model, amount in rates.items():
|
||||
model_text = str(model or "").strip()
|
||||
amount_text = str(amount or "").strip()
|
||||
if not model_text or not amount_text:
|
||||
continue
|
||||
out.append(f"车型/数量:{model_text}")
|
||||
out.append(f"运输费:{ccy}{amount_text}")
|
||||
return out
|
||||
for row in quote.get("fee_rows") or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
name = str(row.get("name") or "").strip()
|
||||
amount = str(row.get("amount") or "").strip()
|
||||
row_ccy = str(row.get("currency") or ccy).strip()
|
||||
unit = str(row.get("unit") or "").strip()
|
||||
if name and amount:
|
||||
out.append(f"{name}:{row_ccy}{amount}{('/' + unit) if unit else ''}")
|
||||
return out
|
||||
|
||||
|
||||
def _land_route_in_text(text: str) -> tuple[str, str]:
|
||||
"""从原话里认「起运地-目的地」。认不出返回空串,不去猜。"""
|
||||
for hit in _LAND_ROUTE.finditer(text or ""):
|
||||
origin = (hit.group("o") or "").strip()
|
||||
dest = (hit.group("d") or "").strip()
|
||||
if not origin or not dest:
|
||||
continue
|
||||
# 排除「2026-11-23」这类被中文包住的时间片段(虽然正则已要求中文)。
|
||||
if any(x in origin for x in ("月", "日", "点", "税", "价")):
|
||||
continue
|
||||
if any(x in dest for x in ("月", "日", "点", "税", "价")):
|
||||
continue
|
||||
return origin, dest
|
||||
return "", ""
|
||||
|
||||
|
||||
def _fact(facts: dict[str, Any], *keys: str) -> str:
|
||||
for key in keys:
|
||||
val = str(facts.get(key) or "").strip()
|
||||
if val:
|
||||
return val
|
||||
return ""
|
||||
|
||||
|
||||
# 其它字段的展示名:从原话里能认到的都列进回执(产品 2026-11-24:尽可能识别)。
|
||||
_EXTRA_LABELS = {
|
||||
"件数": "件数",
|
||||
"毛重": "毛重",
|
||||
"重量": "毛重",
|
||||
"体积": "体积",
|
||||
"包装方式": "包装类型",
|
||||
"包装类型": "包装类型",
|
||||
"品名": "品名",
|
||||
"是否为危险品": "是否为危险品",
|
||||
"是否含电": "是否含电",
|
||||
"是否含磁": "是否含磁",
|
||||
"是否含油": "是否含油",
|
||||
"货好时间": "货好时间",
|
||||
"HS编码": "HS编码",
|
||||
"商品海关编码": "HS编码",
|
||||
"贸易条款": "贸易条款",
|
||||
"货值": "货值",
|
||||
"车型/数量": "车型/数量",
|
||||
"计费重": "计费重",
|
||||
}
|
||||
|
||||
|
||||
def inspect_quote_recognition(
|
||||
text: str,
|
||||
quote: Optional[dict[str, Any]] = None,
|
||||
*,
|
||||
business_line: str = "",
|
||||
transport_mode: str = "",
|
||||
facts: Optional[dict[str, Any]] = None,
|
||||
extra_facts: Optional[dict[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
判断这句话的报价识别程度。
|
||||
|
||||
参数:
|
||||
text:产品原话(已剥 @ 机器人的)。
|
||||
quote:extract_product_quote 的结果;可以传空,用来识别「只有字段没价格」。
|
||||
facts:工单询价字段,用于把话术没写、但工单已有的线路/车型/日期标成「按工单」。
|
||||
|
||||
返回:
|
||||
{"status": "full"|"partial"|"none",
|
||||
"recognized": [回执行], "missing": [缺项名], "hint": 格式样例}
|
||||
|
||||
「部分」以**话术本身**为准:线路/车型/日期没写在原话里,即使工单已有,
|
||||
也算部分识别,回执里标「按工单」,请产品确认。
|
||||
"""
|
||||
raw = (text or "").strip()
|
||||
src = dict(quote or {})
|
||||
facts = dict(facts or {})
|
||||
line = business_line_of(business_line, transport_mode)
|
||||
recognized: list[str] = []
|
||||
missing: list[str] = []
|
||||
in_text = 0
|
||||
|
||||
if line == "AIR":
|
||||
from agent.policy.air_group_ops import _harvest_air_manual_airline
|
||||
from agent.schema.field_validate import _harvest_quote_date
|
||||
|
||||
price = _has_price(src)
|
||||
airline = (
|
||||
str(src.get("airlineCode") or src.get("airline") or "").strip()
|
||||
or _harvest_air_manual_airline(raw)
|
||||
)
|
||||
origin = dest = ""
|
||||
labels = _AIR_ROUTE_LABEL.findall(raw)
|
||||
pair = _AIR_ROUTE.search(raw)
|
||||
if pair:
|
||||
origin, dest = pair.group(1).upper(), pair.group(2).upper()
|
||||
if len(labels) >= 2:
|
||||
origin, dest = labels[0].upper(), labels[1].upper()
|
||||
date = _harvest_quote_date(raw)
|
||||
|
||||
if price:
|
||||
in_text += 1
|
||||
price_line = _air_price_line(src)
|
||||
if price_line:
|
||||
recognized.append(price_line)
|
||||
else:
|
||||
missing.append("单价")
|
||||
# 比例 / 重量等级 / 增值服务也是产品原话里识别到的内容,回执要列全。
|
||||
from agent.schema.added_services import harvest_added_services
|
||||
from agent.schema.field_validate import _harvest_air_ratio
|
||||
|
||||
ratio = _harvest_air_ratio(raw)
|
||||
weight_break = str(src.get("weight_break") or "").strip()
|
||||
if not weight_break:
|
||||
try:
|
||||
from agent.llm.extract_text import _harvest_air_weight_break
|
||||
|
||||
weight_break = _harvest_air_weight_break(raw)
|
||||
except Exception:
|
||||
weight_break = ""
|
||||
added = harvest_added_services(raw)
|
||||
if ratio:
|
||||
in_text += 1
|
||||
recognized.append(f"比例:{ratio}")
|
||||
if weight_break:
|
||||
in_text += 1
|
||||
recognized.append(f"重量等级:{weight_break}")
|
||||
if added:
|
||||
in_text += 1
|
||||
recognized.append("增值服务:" + "/".join(added))
|
||||
if airline:
|
||||
in_text += 1
|
||||
recognized.append(f"航司:{airline}")
|
||||
else:
|
||||
missing.append("航司")
|
||||
if origin and dest:
|
||||
in_text += 1
|
||||
recognized.append(f"线路:{origin}-{dest}")
|
||||
else:
|
||||
origin_fact = _fact(facts, "起运港", "起运地", "始发站")
|
||||
dest_fact = _fact(facts, "目的港", "目的地", "收货地址", "送货地址")
|
||||
if origin_fact and dest_fact:
|
||||
recognized.append(f"线路:{origin_fact}-{dest_fact}")
|
||||
else:
|
||||
missing.append("线路")
|
||||
if date:
|
||||
in_text += 1
|
||||
recognized.append(f"航线日期:{date}")
|
||||
else:
|
||||
date_fact = _fact(facts, "报价日期")
|
||||
if date_fact:
|
||||
recognized.append(f"航线日期:{date_fact}")
|
||||
else:
|
||||
missing.append("报价日期")
|
||||
|
||||
full = price and bool(airline) and bool(origin and dest) and bool(date)
|
||||
status = "full" if full else ("partial" if in_text > 0 else "none")
|
||||
|
||||
elif line == "LAND":
|
||||
price = _has_price(src)
|
||||
origin, dest = _land_route_in_text(raw)
|
||||
vehicle_hit = _LAND_VEHICLE.search(raw)
|
||||
vehicle_in_text = bool(vehicle_hit) or "车型" in raw
|
||||
|
||||
if origin and dest:
|
||||
in_text += 1
|
||||
recognized.append(f"起运地:{origin}")
|
||||
recognized.append(f"目的地:{dest}")
|
||||
else:
|
||||
origin_fact = _fact(facts, "起运港", "始发站", "起运地", "提货地址")
|
||||
dest_fact = _fact(facts, "目的港", "目的地", "收货地址", "送货地址")
|
||||
if origin_fact and dest_fact:
|
||||
recognized.append(f"起运地/目的地:{origin_fact}-{dest_fact}")
|
||||
else:
|
||||
missing.append("线路")
|
||||
if vehicle_in_text:
|
||||
in_text += 1
|
||||
label = (vehicle_hit.group(0) if vehicle_hit else "车型").strip()
|
||||
recognized.insert(0, f"车型/数量:{label}")
|
||||
else:
|
||||
vehicle_fact = _fact(facts, "车型/数量", "车型", "车型数量")
|
||||
if vehicle_fact:
|
||||
recognized.append(f"车型/数量:{vehicle_fact}")
|
||||
else:
|
||||
missing.append("车型/数量")
|
||||
if price:
|
||||
in_text += 1
|
||||
recognized.extend(_land_price_lines(src))
|
||||
else:
|
||||
missing.append("价格")
|
||||
tax = str(src.get("tax_rate") or src.get("taxRate") or "").strip()
|
||||
if tax:
|
||||
recognized.append(f"税率:{tax}")
|
||||
remark = str(src.get("remark") or "").strip()
|
||||
if remark:
|
||||
recognized.append(f"备注:{remark}")
|
||||
|
||||
full = price and bool(origin and dest) and bool(vehicle_in_text)
|
||||
status = "full" if full else ("partial" if in_text > 0 else "none")
|
||||
|
||||
else:
|
||||
# 海运暂无标准话术:有价就算完整,没价且没字段就是全无。
|
||||
price = _has_price(src)
|
||||
if price:
|
||||
recognized.extend(_land_price_lines(src))
|
||||
else:
|
||||
missing.append("价格")
|
||||
status = "full" if price else "none"
|
||||
|
||||
# 其它从原话里识别到的字段(件数/毛重/体积/包装/品名/危险品/含电含磁/计费重…)。
|
||||
for key, val in (extra_facts or {}).items():
|
||||
text_val = str(val or "").strip().strip(",,;;。")
|
||||
if not text_val or text_val in {"-", "—", "-"}:
|
||||
continue
|
||||
label = _EXTRA_LABELS.get(str(key))
|
||||
if not label:
|
||||
continue
|
||||
recognized.append(f"{label}:{text_val}")
|
||||
in_text += 1
|
||||
|
||||
# 车型行可能同时来自「车型在话术里」和车型价明细,去重后回执才不重复。
|
||||
deduped = list(dict.fromkeys(x for x in recognized if x))
|
||||
return {
|
||||
"status": status,
|
||||
"recognized": deduped,
|
||||
"missing": list(dict.fromkeys(x for x in missing if x)),
|
||||
"hint": quote_format_hint(line),
|
||||
}
|
||||
@@ -178,13 +178,24 @@ def volume_cbm_number(raw: str) -> str:
|
||||
|
||||
|
||||
def resolve_airport_code(raw: str) -> str:
|
||||
"""销售原文是地名或三字码时,给出 TMS originCode/destinationCode。"""
|
||||
"""
|
||||
销售原文是地名或三字码时,给出 TMS originCode/destinationCode。
|
||||
|
||||
先查后台 inq_synonym(IT 可维护城市/三字码),查不到再回退本文件 _AIRPORTS。
|
||||
三字码原文优先,禁止把 SZX 再翻成深圳。
|
||||
"""
|
||||
text = (raw or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
if _IATA.match(text):
|
||||
return text.upper()
|
||||
return _AIRPORTS.get(text, "")
|
||||
try:
|
||||
from agent.policy.synonym import airport_code
|
||||
|
||||
code = airport_code(text)
|
||||
except Exception:
|
||||
code = ""
|
||||
return code or _AIRPORTS.get(text, "")
|
||||
|
||||
|
||||
def harvest_named_air_route(text: str, facts: dict[str, str] | None = None) -> dict[str, str]:
|
||||
@@ -248,6 +259,13 @@ def assemble_air_query(facts: dict[str, Any] | None) -> dict[str, Any]:
|
||||
包装只看销售是否说了,散货等原文原样保留。
|
||||
"""
|
||||
src = dict(facts or {})
|
||||
# 最后一层兜底:工单/旧快照里的卡板、40尺高柜等折成标准值;配置不可用时原样。
|
||||
try:
|
||||
from agent.policy.synonym import apply_value_synonyms
|
||||
|
||||
src = apply_value_synonyms(src, "AIR")
|
||||
except Exception:
|
||||
pass
|
||||
# 摘要占位「-」当空:不能拿去 resolve 机场,否则 TMS 回 1003 起飞机场无法匹配。
|
||||
_dash = frozenset({"-", "—", "-"})
|
||||
origin = str(src.get("起运港") or src.get("起运地") or "").strip()
|
||||
|
||||
@@ -104,14 +104,22 @@ def assemble_land_query(facts: dict[str, Any] | None) -> dict[str, Any]:
|
||||
src = apply_quote_date_default(
|
||||
normalize_facts({str(k): v for k, v in dict(facts or {}).items() if v is not None})
|
||||
)
|
||||
# 最后一层兜底:国内整车→国内运输整车、9米6/1→9.6高栏/1、东兴口岸→东兴。
|
||||
try:
|
||||
from agent.policy.synonym import apply_value_synonyms
|
||||
|
||||
src = apply_value_synonyms(src, "LAND")
|
||||
except Exception:
|
||||
pass
|
||||
raw = {str(k): str(v).strip() for k, v in dict(facts or {}).items() if v is not None}
|
||||
land_type = (raw.get("运输类型") or src.get("运输类型") or "").strip()
|
||||
route = (raw.get("线路类别") or src.get("线路类别") or "").strip()
|
||||
# 标准值优先,原文只兜底:否则「东南亚整车」会绕开同义词表直接出站。
|
||||
land_type = (src.get("运输类型") or raw.get("运输类型") or "").strip()
|
||||
route = (src.get("线路类别") or raw.get("线路类别") or "").strip()
|
||||
origin = (src.get("起运港") or "").strip()
|
||||
dest = (src.get("目的港") or "").strip()
|
||||
cargo = (src.get("品名") or "").strip()
|
||||
quote_date = (src.get("报价日期") or "").strip()
|
||||
customs = (raw.get("通关口岸") or src.get("通关口岸") or "").strip()
|
||||
customs = (src.get("通关口岸") or raw.get("通关口岸") or "").strip()
|
||||
|
||||
missing: list[str] = []
|
||||
if not land_type:
|
||||
|
||||
@@ -59,6 +59,13 @@ def assemble_sea_query(facts: dict[str, Any] | None) -> dict[str, Any]:
|
||||
src = apply_quote_date_default(
|
||||
{str(k): str(v) for k, v in dict(facts or {}).items() if v is not None}
|
||||
)
|
||||
# 最后一层兜底:40尺高柜→40HQ、门到门等标准值;配置不可用时原样。
|
||||
try:
|
||||
from agent.policy.synonym import apply_value_synonyms
|
||||
|
||||
src = apply_value_synonyms(src, "SEA")
|
||||
except Exception:
|
||||
pass
|
||||
origin = str(src.get("起运港") or "").strip()
|
||||
dest = str(src.get("目的港") or "").strip()
|
||||
cargo = str(src.get("品名") or "").strip()
|
||||
|
||||
Reference in New Issue
Block a user