Files
inquiry_robot/inquiry-agent/agent/policy/air_group_ops.py
T
linmianxunandCursor d9b2029c47 协同群改为智价通BOT接管对话,报价单按需生成;补客户名称、计费重与陆运报价条件
为什么改:应用建的协同群只能代答,销售在群里发文件、@人、问报价都对不上人;
本次把群对话交给智价通BOT,应用只负责拉群和解散群,并把几处销售已反馈的口径补齐。

群与身份:
- 新增 group_bot 短协调(Redis 带环境前缀):记录 BOT 已接管群、当前关联工单、
  @BOT 指令窗口与窗口外先到的附件,只做协调不当六态,六态仍在主账。
- 群里没有 @BOT 的文字不回;非 @ 文字断开当前单关联,之后必须重新 @BOT 带工单号。
- 先发文件再 @BOT 也认:窗口外附件先缓冲,等 @BOT 认领后补办。
- 会话存档只补附件、不重复办理 BOT 已办的同一句文字,避免同一条消息回两遍。
- 入站 from.userid 是加密 open_userid 时按官方接口换明文(带 Redis 缓存),
  否则与主账 sales_wecom_id 永远比不上,航线本人会被判成「不是本人」。
- 桥侧只认本群 req_id,不再借用别的群 req_id,避免测服把话发进别的群。

报价单:
- 建群后只发字段摘要和成交卡,Excel/PDF 等群里 @BOT 说「生成报价单」再出;
  多段逐段出,没价出空白表;出表后补推成交跟进不涨 deal_version、不重置等待计时。
- 陆运转人工先选业务类型和报价场景再建群,按选定模板名直取,不再靠关键词猜。
- 空运舱位只回一条时直接出该条报价,不再发选择卡。

字段与金额:
- 客户名称改为海/空/陆询价非必填,有值写回工单列,后台列表、报价单与 factsJson 一致。
- 空运新增计费重投影:体积重=CBM×166.7,计费重=max(毛重,体积重);
  TMS 无价、航线手工按 KG 报价时按计费重×单价算整票金额,群摘要与报价单同公式。
- 陆运报价附加条件统一到 land_quote_condition:未含税/含0税/未含燃油/含燃油费,
  燃油只乘主运费,不乘提货送货报关等杂费;跨境整车无备注列时追加到底部备注事项。
- 海运拼柜不适用箱型箱量:不进必填、不进补问、不出站,改回整柜可再用。
- 海运提货地址/派送地址改为非必填,写了才出站(placeOfReceipt/deliveryAddress),
  禁止从港口或贸易条款反推地址;TMS 查不到价时把 TMS 原话透给销售。
- 中港集拼与跨境集拼同口径:按体积+毛重,不采车型数量;修正被国内拼车别名抢单。
- 报关费区只收报关类费目;口岸海关监管费+接驳费按车型列回填固定行。

主账与后台:
- 看板处理量按协同群处理人统计;下线「平均报价销售额」;处理人搜索先把姓名换回企微 id。
- 「转人工」筛选同时兼容旧六态与新 collab_mode=handoff,新版单不再漏。
- 报价单客户名称、提货/派送地址、空运计费重、拼柜空箱型按新口径填表。
- 新增协同成员查询支持与 AIR_NEED_WO v2 迁移脚本。

文档:04 补海运/空运/陆运必填与地址口径,10 补地址出站规则,12 补测服独立应用 1000015 的部署与切换记录。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-23 14:18:22 +08:00

2411 lines
89 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
空运协同群业务:激活当前工单、补含电含磁、航线报价/附件、成交后再锁舱、成交后仍可取消舱位。
本文件职责:群里副作用(主账 + BOT 回话)。海运应用群仍走 sea_group_ops。
禁止:自动建群/拉人/解散;拿当前工单去猜锁舱工单号。
锁舱按 TMS /air/cabin/lock 拼字段出站;没有 TMS 报价编号也可走 MANUAL。
禁止编造 optionNo;缺舱位编号/航司/计费重时先群里补问,禁止空壳打 TMS。
"""
from __future__ import annotations
import json
import logging
import re
import time
from typing import Any, Optional
from agent.llm.extract_text import extract_air_collab_fields, extract_product_quote
from agent.policy import inquiry_copy as copy
from agent.policy.sea_group_ops import (
_archive_file,
_persist_quote_sheet,
_staff_display_name,
collab_mode_of,
emit_group_deal,
filename_is_excel_pdf,
group_client_of,
halt_closed_group,
hydrate_ticket,
is_handoff_ticket,
is_sales,
is_terminal,
merge_quote_fees,
notify_quote_attachment_saved,
send_filled_sheet,
send_group_text,
ticket_no,
ticket_status,
ticket_view,
)
logger = logging.getLogger(__name__)
def is_handoff_collab(flow: Any, ticket: object) -> bool:
"""
本票是否「销售转人工、产品群内手工报价」。
为什么要单独判:转人工协同的单六态仍是询价中,报价要正常落账;
但它不是系统自动协同,不能再生成交跟进、不要催产品走 TMS 标准价。
判定顺序:会话书签 → 主账工单,两边都没有按 auto。
"""
sess = None
getter = getattr(flow, "session_by_work_order", None)
if callable(getter):
try:
sess = getter(ticket_no(ticket))
except Exception:
sess = None
return collab_mode_of(ticket, sess) == "handoff"
TERMINAL = {"已成交", "未成交", "已关闭", "转人工"}
OPEN_ACTIVATE = {"询价中", "已报价", "协商中"}
AIRLINE_ROLE = "air"
_PENDING_QUOTE = "__pending_air_quote"
_PENDING_LOCK = "__pending_air_lock"
_PENDING_LOCK_OPTION = "__pending_lock_option"
_PENDING_LOCK_AIRLINE = "__pending_lock_airline"
_PENDING_LOCK_FLIGHT = "__pending_lock_flight"
_LOCK_ID = "__air_lock_id"
_LOCK_OPTION = "__air_lock_option"
_LOCK_QUOTE = "__air_lock_quote"
_LOCK_EXEC = "__air_lock_exec"
def _ticket_flight_date(ticket: object) -> str:
"""锁舱 flightDate 用工单报价日期,和主账出站一致。"""
view = ticket_view(ticket)
facts = dict(view.get("facts") or {})
return str(
facts.get("报价日期")
or view.get("quoteDate")
or view.get("quote_date")
or ""
).strip()
def _quote_date_from_lock_instruction(instruction: str) -> str:
"""
锁舱补参句里的报价日期。
先认「报价日期:…」标签,再机读句末 yyyy-MM-dd(产品示例:
AIR-OPT01,南航,航班CZ327,2026-10-18)。不改主账。
"""
from agent.llm.extract_text import labeled_quote_date
from agent.schema.field_validate import _harvest_quote_date
labeled = labeled_quote_date(instruction or "")
if labeled:
return labeled
return _harvest_quote_date(instruction or "")
def _absorb_lock_quote_date(
*,
flow: Any,
ticket: object,
instruction: str,
work_order_no: str,
) -> tuple[object, str, str]:
"""
工单报价日空、锁舱句里又写了日期时,先写入主账再锁。
返回:(最新 ticket, 生效报价日, 本句抽出的日期)。
写失败不挡缺项提示;生效日仍可用本句日期做本地齐套判断。
"""
from agent.schema.field_validate import is_blank_quote_date
current = _ticket_flight_date(ticket)
said = _quote_date_from_lock_instruction(instruction)
if not said:
return ticket, current, ""
if not is_blank_quote_date(current):
return ticket, current, said
writer = getattr(flow.ledger, "update_facts", None)
write_ok = False
if callable(writer):
try:
out = writer(work_order_no=work_order_no, facts={"报价日期": said}) or {}
write_ok = bool(out.get("ok", True))
except Exception:
logger.exception("锁舱句写报价日期失败 wo=%s", work_order_no)
write_ok = False
if write_ok:
getter = getattr(flow.ledger, "get_ticket", None)
reloaded = getter(work_order_no=work_order_no) if callable(getter) else None
ticket2 = hydrate_ticket(flow, reloaded or ticket)
return ticket2, _ticket_flight_date(ticket2) or said, said
return ticket, said, said
def _lock_receipt_fields(
ticket: object,
quote: dict[str, Any],
option_no: str,
airline: str,
) -> tuple[str, str, str, str]:
"""
锁舱成功回执的起运地、目的地、航司、航班日期。
优先级与主账出站一致:舱位三字码/航班日优先,没有再用工单事实。
航司用本次实际锁出去的两位码。不编造。
"""
from agent.schema.air_route_options import airport_code_for_display, option_flight_date
row = _option_row(quote, option_no) or _selected_cabin_row(quote) or {}
facts = dict(ticket_view(ticket).get("facts") or {})
origin = airport_code_for_display(
str(row.get("originAirportCode") or row.get("origin") or facts.get("originCode") or ""),
str(facts.get("起运地") or facts.get("起运港") or ""),
)
destination = airport_code_for_display(
str(
row.get("destinationAirportCode")
or row.get("destination")
or facts.get("destinationCode")
or ""
),
str(facts.get("目的地") or facts.get("目的港") or ""),
)
airline_text = (airline or "").strip().upper()
if not airline_text:
airline_text = str(row.get("airlineCode") or row.get("airline") or "").strip().upper()
flight_date = option_flight_date(row) or _ticket_flight_date(ticket)
return origin, destination, airline_text, flight_date
def is_airline(flow: Any, sender_id: str) -> bool:
"""员工管理岗位=航线·空运且启用。"""
uid = (sender_id or "").strip()
if not uid:
return False
book = getattr(flow, "ledger", None) or getattr(flow, "_ledger", None)
getter = getattr(book, "get_staff_by_wecom_id", None) if book else None
if not callable(getter):
return False
try:
row = getter(wecom_id=uid) or {}
except Exception:
logger.exception("查航线岗失败 wecom=%s", uid)
return False
code = str(row.get("roleCode") or row.get("role_code") or "").strip().lower()
status = str(row.get("status") or "active").strip().lower()
return code == AIRLINE_ROLE and status not in {"disabled", "0", "停用"}
def operator_name(flow: Any, sender_id: str) -> str:
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=sender_id) or {}
name = str(row.get("name") or "").strip()
if name:
return name
except Exception:
logger.warning("取操作人姓名失败 wecom=%s", sender_id)
return (sender_id or "").strip() or "航线"
def is_air_ticket(ticket: object) -> bool:
"""按群找回的工单必须是空运。陆运旧单不能当空运当前单补含电含磁。"""
view = ticket_view(ticket)
line = str(view.get("business_line") or view.get("businessLine") or "").strip().upper()
return not line or line == "AIR"
def can_fill_fields(flow: Any, ticket: object, sender_id: str) -> bool:
return is_sales(ticket, sender_id) or is_airline(flow, sender_id)
def activate_ticket(
*,
flow: Any,
chat_id: str,
work_order_no: str,
speak: bool = True,
) -> tuple[Optional[object], str]:
"""
把本群当前工单切到指定空运未结案单。
返回 (工单, phase)。失败时工单为 None。
已经在成交跟进,或航线/产品价已经落账时,再发工单号只回到成交跟进,不再发工单摘要和模板。
speak 只控制「成功切单后要不要发工单摘要/模板」;失败原因必须回群。
句中已经识别到工单号(成交/补字段/锁舱带的号)时也走这里,静默失败会让销售
以为消息没发出去,所以 ticket_not_found / not_air / terminal / occupied 一律回话。
"""
book = flow.ledger
no = (work_order_no or "").strip()
client = group_client_of(flow)
getter = getattr(book, "activate_air_group", None)
if callable(getter):
out = getter(chat_id=chat_id, work_order_no=no) or {}
else:
out = _activate_fallback(book, chat_id=chat_id, work_order_no=no)
err = str(out.get("error") or "")
if err == "ticket_not_found":
send_group_text(client, chat_id, copy.air_ticket_not_found(no))
return None, "ticket_missing"
if err == "not_air":
send_group_text(client, chat_id, copy.air_ticket_not_air(no))
return None, "not_air"
if err == "terminal":
st = str(out.get("status") or "")
if st == "转人工":
return None, "handoff_ignore"
send_group_text(client, chat_id, copy.air_ticket_closed(no, st))
return None, "ticket_closed"
if err == "occupied":
send_group_text(client, chat_id, copy.air_ticket_occupied(no))
return None, "occupied"
if not out.get("ok"):
send_group_text(client, chat_id, copy.air_ticket_not_found(no))
return None, "ticket_missing"
ticket = hydrate_ticket(flow, _ticket_from_activate(book, no, out))
if is_handoff_ticket(ticket):
return None, "handoff_ignore"
# 先落默认协同,再决定要不要发摘要。发文件切单不说话,工单上仍要有含电/含磁。
_seed_air_activate_collab(flow, ticket)
handoff = is_handoff_collab(flow, ticket)
if speak and not handoff and _air_already_quoted_for_deal(ticket):
view = ticket_view(ticket)
view["collab_chat_id"] = chat_id
emit_group_deal(flow=flow, ticket=view, quote=dict(view.get("quote") or {}))
_watch_archive_room(chat_id, no)
return ticket, "activated_deal"
if speak:
# 激活只发摘要,不自动发空白/填价报价单;要表再说「生成报价单」。
send_air_brief_and_sheet(
flow=flow, ticket=ticket, chat_id=chat_id, include_sheet=False
)
_watch_archive_room(chat_id, no)
if handoff:
# 转人工:产品会直接在群里报价,等到的就是最终报价。
# 不启动自动报价超时监控(那是催系统价用的),也不生成交跟进。
return ticket, "activated_handoff"
from agent.policy.event_exception import WAIT_AIR_QUOTE, start_wait
start_wait(flow.ledger, work_order_no=no, wait_kind=WAIT_AIR_QUOTE)
return ticket, "activated"
def _air_already_quoted_for_deal(ticket: object) -> bool:
"""
再激活应回成交跟进,而不是重发工单摘要和空运模板。
报价单已经发给销售(quoteFileIssued)或主账停在 wait_deal 时,
即使报价来源仍是 TMS 标准价,也已经在成交跟进。
协商中、航线/产品价、销售调价同样只回成交跟进。
报价单还没出、也没在等成交时,仍发模板给航线填。
"""
status = ticket_status(ticket)
if status == "协商中":
return True
view = ticket_view(ticket)
phase = str(view.get("wait_phase") or view.get("waitPhase") or "").strip()
if phase == "wait_deal":
return True
quote = dict(view.get("quote") or {})
if _quote_file_issued(quote):
return True
if status != "已报价":
return False
label = str(quote.get("source_label") or quote.get("sourceLabel") or "")
if "航线" in label or "产品" in label:
return True
return copy.quote_is_sales_adjust(quote)
def _quote_file_issued(quote: dict[str, Any]) -> bool:
"""报价单已发给销售,且没有被作废。作废后重新激活仍要发模板。"""
if _flag_on(quote.get("quoteFileVoided") or quote.get("quote_file_voided")):
return False
return _flag_on(quote.get("quoteFileIssued") or quote.get("quote_file_issued"))
def _flag_on(val: object) -> bool:
"""主账布尔可能是 true / \"true\" / 1。"""
if isinstance(val, str):
return val.strip().lower() in {"1", "true", "yes"}
return bool(val)
def _collab_slot_empty(val: object) -> bool:
"""协同项没写,或只写了横杠。横杠是摘要占位,不能当成已经填过。"""
return str(val or "").strip() in {"", "-", "—", "-"}
def _seed_air_activate_collab(flow: Any, ticket: object) -> dict[str, str]:
"""
空运群激活时预填协同,并记到主账。
私聊已经写过的含电/含磁先带上。
货物品名正好是「普货」、该项还空着,默认否。
群里已经记下的值不覆盖。只补空项。
"""
from agent.schema.field_validate import (
AIR_COLLAB_FIELDS,
air_general_cargo_collab_defaults,
pick_collab_from_facts,
)
view = ticket_view(ticket)
no = ticket_no(ticket)
facts = dict(view.get("facts") or {})
# 主账有时品名在货物名称列,事实里没带「品名」。群摘要仍能看到普货。
if not str(facts.get("品名") or facts.get("货物品名") or "").strip():
cargo = str(view.get("goodsName") or view.get("goods_name") or "").strip()
if cargo:
facts["品名"] = cargo
seeded = pick_collab_from_facts(facts, AIR_COLLAB_FIELDS)
for key, val in air_general_cargo_collab_defaults(facts).items():
if _collab_slot_empty(seeded.get(key)):
seeded[key] = val
collab = dict(view.get("collab_facts") or {})
to_write: dict[str, str] = {}
for key, val in seeded.items():
if val and _collab_slot_empty(collab.get(key)):
collab[key] = val
to_write[key] = val
if to_write:
patcher = getattr(getattr(flow, "ledger", None), "patch_collab_facts", None)
if callable(patcher):
patcher(
work_order_no=no,
facts=to_write,
sender_id=str(view.get("sales_wecom_id") or view.get("salesWecomId") or ""),
)
return collab
def send_air_brief_and_sheet(
*,
flow: Any,
ticket: object,
chat_id: str = "",
quote_override: Optional[dict[str, Any]] = None,
tms_quote: Optional[dict[str, Any]] = None,
product_quote: Optional[dict[str, Any]] = None,
include_sheet: bool = False,
) -> str:
"""
空运群再发一版摘要;可选再发匹配到的空运模板。对齐海运 send_brief_and_sheet。
必须先发出工单信息,模板等摘要发出后再发,禁止后台线程抢先发文件。
默认 include_sheet=False:激活/补字段/有价落定都只发摘要,不自动发 Excel/PDF。
销售/商务/航线说「生成报价单」再出表。调用方若显式传 include_sheet=True 才发模板。
填表报价必须带上 TMS 总销售价:群票上的 latest quote 常只有增点费/拆板费明细,
若直接拿去出单,预估费用会落成明细加总(如 200)而不是 salePrice(如 7918.25)。
调用方刚写回的询价字段(如报价日期)优先,不能被 hydrate 旧快照盖掉。
"""
incoming_view = ticket_view(ticket) if ticket is not None else {}
incoming_facts = dict(incoming_view.get("facts") or {})
ticket = hydrate_ticket(flow, ticket)
view = ticket_view(ticket)
no = ticket_no(ticket)
room = str(chat_id or view.get("collab_chat_id") or view.get("collabChatId") or "").strip()
if room and not view.get("collab_chat_id"):
view["collab_chat_id"] = room
facts = dict(view.get("facts") or {})
# 群里刚补的报价日期等:有值就盖到摘要用的 facts 上。
for key, raw in incoming_facts.items():
val = str(raw or "").strip()
if key and val:
facts[key] = val
view["facts"] = facts
collab = _seed_air_activate_collab(flow, view)
view["collab_facts"] = collab
view_q = dict(view.get("quote") or {})
override = dict(quote_override or {})
tms = dict(tms_quote) if tms_quote is not None else {}
manual = dict(product_quote or {})
if tms_quote is None:
tms = copy.resolve_tms_quote(None, view)
if not tms and view_q and copy.quote_is_tms(view_q):
tms = view_q
if not manual and copy.quote_is_product(override or view_q):
manual = override or view_q
quote = dict(override or view_q or tms or manual)
# 出单专用:把 TMS salePrice 盖回薄报价,避免预估费用=明细 SUM。
sheet_quote = _sheet_quote_with_tms_sale_total(quote, tms=tms, facts=facts)
sales_name, airline_names, mention_ids = resolve_air_mentions(flow, view)
brief_text = copy.air_group_brief(
work_order_no=no,
facts=facts,
quote=quote,
collab_facts=collab,
has_price=bool(tms.get("total") or tms.get("quoteId")),
tms_quote=tms,
product_quote=manual,
sales_name=sales_name,
airline_names=airline_names,
)
send_group_text(
group_client_of(flow),
room,
brief_text,
mention_userids=mention_ids,
)
if include_sheet:
_send_air_activate_sheet(flow=flow, ticket=view, chat_id=room, quote=sheet_quote)
return "brief_and_sheet"
return "brief_only"
def _air_usable_sale_total(quote: Optional[dict[str, Any]]) -> str:
"""
空运出单可用的总销售价:顶层 total / salePrice,或选定/首条线路 salePrice。
「-」与空串不算。
"""
src = dict(quote or {})
for key in ("total", "total_amount", "salePrice", "totalSalePrice"):
val = str(src.get(key) or "").strip()
if val and val != "-":
return val
selected = src.get("selected_air_option") or src.get("selectedAirOption")
if isinstance(selected, dict):
val = str(selected.get("salePrice") or selected.get("sale_price") or "").strip()
if val and val != "-":
return val
raw_opts = src.get("airOptions") or src.get("air_options") or []
if isinstance(raw_opts, list) and raw_opts and isinstance(raw_opts[0], dict):
val = str(raw_opts[0].get("salePrice") or raw_opts[0].get("sale_price") or "").strip()
if val and val != "-":
return val
return ""
def _money_plain_number(text: str) -> Optional[float]:
"""从「CNY 7918.25」类文本抽出数字;解不开返回 None。"""
raw = str(text or "").strip()
if not raw or raw == "-":
return None
digits = "".join(ch if (ch.isdigit() or ch in ".-") else " " for ch in raw).split()
if not digits:
return None
try:
return float(digits[-1].replace(",", ""))
except ValueError:
return None
def _total_matches_fee_row_sum(quote: dict[str, Any], total_text: str) -> bool:
"""
顶层 total 是否只是明细金额相加(如增点费100+拆板费100=200)。
是则说明缺了 TMS 总销售价,不能当真预估费用。
"""
total_num = _money_plain_number(total_text)
if total_num is None:
return False
rows = quote.get("fee_rows") or quote.get("fee_lines") or quote.get("feeItems") or []
if isinstance(rows, str) and rows.strip():
try:
rows = json.loads(rows)
except json.JSONDecodeError:
rows = []
if not isinstance(rows, list) or not rows:
return False
summed = 0.0
hit = 0
for item in rows:
if not isinstance(item, dict):
continue
amt = _money_plain_number(
str(
item.get("amount")
or item.get("value")
or item.get("salePrice")
or item.get("price")
or ""
)
)
if amt is None:
continue
summed += amt
hit += 1
if hit <= 0:
return False
return abs(total_num - summed) < 0.01
def _total_is_thin_vs_tms(cur_total: str, tms_total: str) -> bool:
"""
薄报价:明细加总明显小于 TMS 销售价(WO040:200 << 7918)才盖成销售价。
航线在舱位价上再加增值费/增点费时,total=明细之和会大于 salePrice(如 4966 > 3966),
此时必须保留航线总价,禁止再盖回 TMS。
"""
cur = _money_plain_number(cur_total)
tms = _money_plain_number(tms_total)
if cur is None or tms is None:
return False
return cur + 0.01 < tms
def _sheet_quote_with_tms_sale_total(
quote: dict[str, Any],
*,
tms: Optional[dict[str, Any]] = None,
facts: Optional[dict[str, Any]] = None,
) -> dict[str, Any]:
"""
群填表用的报价包:保留产品/航线改过的明细,但预估费用必须能落到 TMS 总销售价。
协同群 latest quote 常只有 departureCharges 投影出的附加费行,total 空或被加成 200;
销售 1V1 会话里带了 salePrice,所以同一工单两边会不一致。这里出单前对齐。
"""
from agent.schema.air_route_options import project_group_air_quote
out = dict(quote or {})
source = dict(tms or {}) or dict(out)
if not source:
return out
projected = project_group_air_quote(source, dict(facts or {}))
tms_total = _air_usable_sale_total(projected)
cur_total = _air_usable_sale_total(out)
# 补齐线路对象 / 计费重,便于主账从 airOptions.salePrice 再兜底一次。
for key in (
"airOptions",
"air_options",
"selected_air_option",
"selectedAirOption",
"chargeableWeightKg",
"chargeable_weight_kg",
"currency",
"valid_until",
):
cur = out.get(key)
empty = cur in (None, "", "-", [], {})
proj_val = projected.get(key)
if empty and proj_val not in (None, "", "-", [], {}):
out[key] = proj_val
if not tms_total:
return out
# 仅「空/薄报价加总」才盖 TMS;航线加出增值费后 total>salePrice 必须保留。
matches_sum = bool(cur_total) and cur_total != "-" and _total_matches_fee_row_sum(out, cur_total)
thin_vs_tms = matches_sum and _total_is_thin_vs_tms(cur_total, tms_total)
need_tms_total = (not cur_total) or cur_total == "-" or thin_vs_tms
if need_tms_total:
out["total"] = str(projected.get("total") or tms_total).strip()
if projected.get("currency") and not str(out.get("currency") or "").strip():
out["currency"] = projected.get("currency")
return out
def resolve_air_mentions(flow: Any, ticket: object) -> tuple[str, list[str], list[str]]:
"""
空运群摘要 @ 本单销售 + 负责本单线路的航线·空运(按后台 routes 过滤)。
对上海运 @ 销售/@ 产品;禁止再按岗位整表广播。
"""
from agent.policy.deal_followup import air_staff_route_matches
view = ticket_view(ticket)
facts = dict(view.get("facts") or {})
sales_id = str(view.get("sales_wecom_id") or view.get("salesWecomId") or "").strip()
sales_name = str(view.get("sales_name") or view.get("salesName") or "").strip()
if not sales_name or sales_name == "销售":
sales_name = _staff_display_name(flow, sales_id) if sales_id else ""
if not sales_name:
sales_name = sales_id
air_ids: list[str] = []
air_names: list[str] = []
book = getattr(flow, "ledger", None)
lister = getattr(book, "list_staff_by_role", None) if book is not None else None
rows: list[dict[str, Any]] = []
if callable(lister):
try:
rows = list(lister(role_code="air") or [])
except Exception:
logger.exception("列航线岗失败")
matched_rows: list[dict[str, Any]] = []
for row in rows:
if not isinstance(row, dict):
continue
if air_staff_route_matches(routes=str(row.get("routes") or ""), facts=facts):
matched_rows.append(row)
# 对不上具体线路时,只保留「空运全线」,避免再 @ 全岗
if not matched_rows:
for row in rows:
if not isinstance(row, dict):
continue
toks = [
t.strip()
for t in str(row.get("routes") or "").replace(",", ",").replace("、", ",").split(",")
if t.strip()
]
if any(t in {"空运全线", "全线"} for t in toks):
matched_rows.append(row)
for row in matched_rows:
uid = str(row.get("wecomId") or row.get("wecom_id") or "").strip()
name = str(row.get("name") or "").strip() or _staff_display_name(flow, uid)
if not uid:
continue
air_ids.append(uid)
if name and name not in air_names:
air_names.append(name)
mention_ids: list[str] = []
if sales_id:
mention_ids.append(sales_id)
for uid in air_ids:
if uid not in mention_ids:
mention_ids.append(uid)
return sales_name, air_names, mention_ids
def _send_air_activate_sheet(
*,
flow: Any,
ticket: object,
chat_id: str,
quote: dict[str, Any],
) -> None:
"""填匹配到的空运模板并往群里发。失败只补一句,不回滚激活。"""
client = group_client_of(flow)
try:
painted = send_filled_sheet(
flow=flow,
ticket=ticket,
business_line="AIR",
chat_id=chat_id,
quote_override=quote,
) or {}
except Exception:
logger.exception("空运群发模板失败 chat=%s", chat_id)
send_group_text(client, chat_id, copy.group_sheet_send_fail())
return
if painted.get("ok"):
return
err = str(painted.get("error") or "")
if err == "NO_TEMPLATE":
send_group_text(client, chat_id, painted.get("message") or copy.quote_template_missing())
return
if err in {"no_renderer_or_chat", "no_file_client"}:
send_group_text(client, chat_id, copy.group_sheet_send_fail())
def _watch_archive_room(chat_id: str, work_order_no: str) -> None:
"""激活成功后听这个群的存档,否则发文件(不能 @)系统听不见。"""
try:
from agent.channel.wshoto.rooms import watch_collab_room
watch_collab_room(chat_id, work_order_no=work_order_no)
except Exception:
logger.exception("空运群登记存档监听失败 chat=%s wo=%s", chat_id, work_order_no)
def resolve_cabin_ticket(
*,
flow: Any,
chat_id: str,
work_order_no: str,
allow_terminal: bool,
for_lock: bool = False,
) -> tuple[Optional[object], str]:
"""
锁舱/释放按句中工单号取单,不猜当前单。
未结案:激活并切到本群。已在别的群:occupied,不锁不切。
已成交可以锁、也可以取消已锁舱位,不再激活。未成交不能锁,但已有锁仍可取消。
"""
book = flow.ledger
no = (work_order_no or "").strip()
client = group_client_of(flow)
getter = getattr(book, "get_ticket", None)
raw = getter(work_order_no=no) if callable(getter) else None
if raw is None:
send_group_text(client, chat_id, copy.air_ticket_not_found(no))
return None, "ticket_missing"
ticket = hydrate_ticket(flow, raw)
view = ticket_view(ticket)
line = str(view.get("business_line") or view.get("businessLine") or "").upper()
if line and line != "AIR":
send_group_text(client, chat_id, copy.air_ticket_not_air(no))
return None, "not_air"
other = str(view.get("collab_chat_id") or view.get("collabChatId") or "").strip()
if other and other != chat_id:
send_group_text(client, chat_id, copy.air_ticket_occupied(no))
return None, "occupied"
if is_terminal(ticket):
st = ticket_status(ticket)
# 锁舱只在已成交之后办。未成交要能读到单,才能回「不能锁」,而不是「不能再激活」。
if for_lock and st in {"已成交", "未成交"}:
# 已成交不再走普通激活,但要把本群记下,下一句补舱位不用再带工单号。
if st == "已成交":
_bind_deal_cabin_room(flow, chat_id=chat_id, work_order_no=no)
return ticket, "deal_loaded" if st == "已成交" else "lost_loaded"
if allow_terminal:
return ticket, "terminal_loaded"
if st == "转人工":
return None, "handoff_ignore"
send_group_text(client, chat_id, copy.air_ticket_closed(no, st))
return None, "ticket_closed"
return activate_ticket(flow=flow, chat_id=chat_id, work_order_no=no, speak=False)
def apply_air_fields(*, flow: Any, ticket: object, text: str, sender_id: str, chat_id: str) -> str:
"""
补含电/含磁,以及报价日期。
含电含磁走协同字段;报价日期写入询价 facts(主账 quote_date 列)。
货好时间、贸易条款、客户名称不在群里补(产品口径)。
写入后重发群摘要 + 空运模板,不当一句「已记下」。
"""
from agent.llm.extract_text import labeled_quote_date
ticket = hydrate_ticket(flow, ticket)
no = ticket_no(ticket)
client = group_client_of(flow)
fields = extract_air_collab_fields(text, allow_b=True)
quote_date = labeled_quote_date(text)
if not is_air_ticket(ticket):
send_group_text(client, chat_id, copy.air_need_work_order())
return "need_work_order"
stopped = halt_closed_group(flow=flow, ticket=ticket, chat_id=chat_id)
if stopped:
return stopped
if not can_fill_fields(flow, ticket, sender_id):
send_group_text(client, chat_id, copy.air_fields_denied())
return "fields_denied"
if not fields and not quote_date:
send_group_text(client, chat_id, copy.air_fields_not_recognized())
return "fields_empty"
if fields:
flow.ledger.patch_collab_facts(work_order_no=no, facts=fields, sender_id=sender_id)
write_ok = True
if quote_date:
# 只打补丁键:主账侧合并,避免整包 facts 误伤。
patch = {"报价日期": quote_date}
writer = getattr(flow.ledger, "update_facts", None)
if callable(writer):
try:
out = writer(work_order_no=no, facts=patch) or {}
write_ok = bool(out.get("ok", True))
except Exception:
write_ok = False
logger.exception("空运群写报价日期失败 wo=%s", no)
# 必须回读本单。按群再查会拿到同群更早的陆运/海运旧单(测服 WO202609230007)。
getter = getattr(flow.ledger, "get_ticket", None)
reloaded = getter(work_order_no=no) if callable(getter) else None
ticket2 = hydrate_ticket(flow, reloaded or ticket)
view = ticket_view(ticket2)
collab = dict(view.get("collab_facts") or {})
collab.update(fields)
view["collab_facts"] = collab
if quote_date:
facts_view = dict(view.get("facts") or {})
facts_view["报价日期"] = quote_date
view["facts"] = facts_view
view["collab_chat_id"] = chat_id
# 补字段后只刷新摘要,不自动再发报价单 Excel。
send_air_brief_and_sheet(
flow=flow, ticket=view, chat_id=chat_id, include_sheet=False
)
return "fields_saved"
def _harvest_air_manual_airline(text: str) -> str:
"""
航线短句里的裸二字航司码。
例:…卡转、TH、起运地KUL… → TH。
避开 WO、MUST GO 里的 GO、机场对 NKG-KUL、币种词。
运行证据:卡转/MUST GO、TH → 曾误收 GO。
"""
raw = text or ""
blocked = {
"WO",
"KG",
"CB",
"CBM",
"CNY",
"USD",
"RMB",
"HKD",
"EUR",
"JPY",
"GBP",
"GO", # MUST GO 残片,不当航司
"DG",
"TC",
}
cleaned = raw
# 增值服务英文词先挖掉,避免 MUST GO → GO。
cleaned = re.sub(r"(?i)MUST\s*GO", " ", cleaned)
cleaned = re.sub(r"(?i)(?<![A-Za-z])(?:DG|TC)(?![A-Za-z])", " ", cleaned)
# 起运地/目的地标签后的三字码、以及 NKG-KUL 航线对。
cleaned = re.sub(
r"(?:起运地|起运港|目的地|目的港)\s*[A-Za-z]{3}",
" ",
cleaned,
flags=re.I,
)
cleaned = re.sub(r"\b[A-Za-z]{3}\s*[-–—/]\s*[A-Za-z]{3}\b", " ", cleaned)
cleaned = re.sub(r"\bWO\d{12}\b", " ", cleaned, flags=re.I)
for hit in re.finditer(r"(?<![A-Za-z0-9])([A-Z]{2})(?![A-Za-z0-9])", cleaned, re.I):
code = (hit.group(1) or "").upper()
if code in blocked:
continue
return code
return ""
def _harvest_air_manual_route_airports(text: str) -> tuple[str, str]:
"""
短句起运/目的机场。
优先「起运地KUL」标签;否则认「NKG-KUL」「NKG/KUL」航线对。
返回 (起运三字码, 目的三字码),没有则空串。
"""
raw = text or ""
origin = ""
dest = ""
hit = re.search(r"(?:起运地|起运港)\s*([A-Za-z]{3})(?![A-Za-z])", raw, re.I)
if hit:
origin = (hit.group(1) or "").upper()
hit = re.search(r"(?:目的地|目的港)\s*([A-Za-z]{3})(?![A-Za-z])", raw, re.I)
if hit:
dest = (hit.group(1) or "").upper()
if origin and dest:
return origin, dest
pair = re.search(r"\b([A-Za-z]{3})\s*[-–—/]\s*([A-Za-z]{3})\b", raw)
if pair:
left = (pair.group(1) or "").upper()
right = (pair.group(2) or "").upper()
if not origin:
origin = left
if not dest:
dest = right
return origin, dest
def _harvest_air_manual_origin(text: str) -> str:
"""短句起运机场三字码;兼容「起运地KUL」与「NKG-KUL」。"""
origin, _dest = _harvest_air_manual_route_airports(text)
return origin
def _patch_air_manual_side_fields(
*,
flow: Any,
work_order_no: str,
text: str,
quote: dict[str, Any],
sender_id: str,
) -> dict[str, Any]:
"""
手工短句旁路字段写入:增值服务、报价日期、比例、起运地、航司。
航司落到报价对象;其余打主账 facts。不改六态。
"""
from agent.schema.added_services import apply_air_value_added, harvest_added_services
from agent.schema.air_chargeable import format_kg, harvest_declared_chargeable
from agent.schema.field_validate import _harvest_air_ratio, _harvest_quote_date
out = dict(quote or {})
# 航线自己写了「计费重800KG」就照他说的落库,别再按体积×166.7 重算覆盖。
declared = harvest_declared_chargeable(text)
if declared is not None and not (
str(out.get("chargeableWeightKg") or out.get("chargeable_weight_kg") or "").strip()
):
out["chargeableWeightKg"] = format_kg(declared)
out["chargeable_weight_kg"] = format_kg(declared)
out["chargeable_weight_basis"] = "explicit"
airline = _harvest_air_manual_airline(text)
if airline and not (
str(out.get("airlineCode") or out.get("airline") or "").strip()
):
out["airlineCode"] = airline
out["airline"] = airline
patch: dict[str, str] = {}
added_prev = ""
getter = getattr(flow.ledger, "get_ticket", None)
if callable(getter):
try:
raw_ticket = getter(work_order_no=work_order_no)
if raw_ticket is not None:
added_prev = str(
(ticket_view(hydrate_ticket(flow, raw_ticket)).get("facts") or {}).get(
"added_services"
)
or ""
)
except Exception:
added_prev = ""
merged_added = apply_air_value_added(text, {}, previous=added_prev)
if str(merged_added.get("added_services") or "").strip():
patch["added_services"] = str(merged_added["added_services"]).strip()
qdate = _harvest_quote_date(text or "")
if qdate:
patch["报价日期"] = qdate
ratio = _harvest_air_ratio(text or "")
if ratio:
patch["比例"] = ratio
origin, dest = _harvest_air_manual_route_airports(text)
if origin:
patch["起运港"] = origin
patch["起运地"] = origin
if dest:
patch["目的港"] = dest
patch["目的地"] = dest
if patch:
writer = getattr(flow.ledger, "update_facts", None)
if callable(writer):
try:
writer(work_order_no=work_order_no, facts=patch)
except Exception:
logger.exception("空运手工报价旁路字段写入失败 wo=%s", work_order_no)
_ = sender_id
return out
def apply_air_quote(
*,
flow: Any,
ticket: object,
text: str,
sender_id: str,
chat_id: str,
injected_quote: Optional[dict[str, Any]] = None,
) -> str:
"""
航线文字报价。对齐海运产品报价:同句可带含电含磁;有 TMS 价先问怎么用;
落定后重发摘要 + 空运模板 + 成交跟进。
"""
ticket = hydrate_ticket(flow, ticket)
no = ticket_no(ticket)
client = group_client_of(flow)
stopped = halt_closed_group(flow=flow, ticket=ticket, chat_id=chat_id)
if stopped:
return stopped
if not is_airline(flow, sender_id):
send_group_text(client, chat_id, copy.air_airline_only_quote())
return "not_airline"
fields = extract_air_collab_fields(text)
if fields:
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 {})
from agent.policy.sea_group_ops import _quote_currency_hint
quote = injected_quote or extract_product_quote(
text,
business_line="AIR",
transport_mode="空运",
baseline_currency=_quote_currency_hint(current),
) or {}
if quote:
quote = _patch_air_manual_side_fields(
flow=flow,
work_order_no=no,
text=text,
quote=quote,
sender_id=sender_id,
)
if not str(quote.get("source_label") or "").strip():
quote["source_label"] = "航线报价"
elif "产品" in str(quote.get("source_label") or ""):
quote["source_label"] = "航线报价"
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",
)
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"
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"
from agent.schema.quote_adjust import quote_fee_rows
if quote_fee_rows(current):
quote = merge_quote_fees(current, quote)
return _commit_quote(
flow, ticket, quote, chat_id, sender_id, raw_text=text, raw_source="text"
)
def apply_air_file(
*,
flow: Any,
ticket: object,
sender_id: str,
filename: str,
media: dict[str, Any],
chat_id: str,
explicit: bool = False,
) -> str:
"""
空运群附件:对齐海运。只收 Excel/PDF。航线的当正式报价并出成交跟进;别人的只存档。
发文件不能 @,马上回「附件已保存」。不拆文件金额。已有 TMS 报价编号要留下。
参数 explicit:本次指令明确 @ 过机器人;不收的类型也要回一句(2026-11-21)。
"""
ticket = hydrate_ticket(flow, ticket)
no = ticket_no(ticket)
client = group_client_of(flow)
stopped = halt_closed_group(
flow=flow, ticket=ticket, chat_id=chat_id, file=True
)
if stopped:
return stopped
if not filename_is_excel_pdf(filename):
# 与海运同口径(2026-11-19 真机):不 @BOT 的 Word/zip 不搭话。
# 文件名带工单号才说明对方是想归到某张单,才提示「只收 Excel/PDF」。
# 2026-11-21:明确 @ 过机器人时也一定提示,不能让人干等。
if explicit or copy.extract_work_order_no(filename or ""):
send_group_text(client, chat_id, copy.group_only_excel_pdf())
else:
logger.info("air_file_type_silent wo=%s file=%s", no or "-", (filename or "")[:80])
return "file_type_rejected"
_archive_file(flow, no, filename, media, sender_id)
notify_quote_attachment_saved(flow, chat_id, no, count=1)
if not is_airline(flow, sender_id):
return "file_archived"
view = ticket_view(ticket)
handoff = is_handoff_collab(flow, ticket)
quote = dict(view.get("quote") or {})
quote["source_label"] = "航线附件报价"
quote["file_name"] = filename
# 转人工:附件原文件已在上面存档,不再给占位「-」金额,避免后台出现假报价。
if not handoff and not quote.get("total"):
quote["total"] = "-"
saved = flow.ledger.upsert_product_quote(
work_order_no=no,
quote=quote,
to_status="已报价",
raw_text=filename,
raw_source="file",
) or {}
if not saved.get("ok"):
send_group_text(client, chat_id, "主账写入报价失败。")
return "ledger_fail"
view["collab_chat_id"] = chat_id
view["quote"] = quote
from agent.policy.event_exception import clear_wait
clear_wait(flow.ledger, work_order_no=no)
if handoff:
# 转人工附件报价:只留档参考。不提示锁舱(人工协同不走 TMS),也不生成交跟进。
return "airline_file_quote_handoff"
# 附件不拆金额:锁舱常失败。产品口径改为提示航线改发纯文字报价后再锁。
tip = copy.air_attachment_quote_lock_tip(work_order_no=no)
send_group_text(client, chat_id, tip)
emit_group_deal(flow=flow, ticket=view, quote=quote)
return "airline_file_quote"
def bound_air_ticket(flow: Any, chat_id: str) -> Optional[object]:
"""这群当前绑的是空运单才算空运协同群。海运应用群不要走这里。"""
hit = current_ticket(flow, chat_id)
if hit is None:
return None
line = str(ticket_view(hit).get("business_line") or "").upper()
return hit if line == "AIR" else None
def apply_air_tms_choice(
*,
flow: Any,
ticket: object,
sender_id: str,
chat_id: str,
keep_tms: bool,
) -> str:
"""
航线选:在 TMS 上改,或不用 TMS。对齐海运:用刚记下的价出摘要 + 空运模板 + 成交跟进。
"""
ticket = hydrate_ticket(flow, ticket)
client = group_client_of(flow)
no = ticket_no(ticket)
stopped = halt_closed_group(flow=flow, ticket=ticket, chat_id=chat_id)
if stopped:
return stopped
if not is_airline(flow, sender_id):
send_group_text(client, chat_id, copy.air_airline_only_quote())
return "not_airline"
pending = _load_air_pending(ticket, no)
if not pending:
send_group_text(client, chat_id, copy.group_need_price_before_choice())
return "quote_choice_no_pending"
view = ticket_view(ticket)
base = dict(view.get("quote") or {})
if keep_tms:
if pending.get("fee_rows") or pending.get("fee_lines"):
merged = merge_quote_fees(base, pending)
else:
merged = dict(base)
merged.update(pending)
if base.get("quoteId") and not pending.get("quoteId"):
merged["quoteId"] = base.get("quoteId")
if base.get("airOptions") and not pending.get("airOptions"):
merged["airOptions"] = base.get("airOptions")
merged["source_label"] = "航线在TMS上改"
else:
merged = dict(pending)
merged["source_label"] = "航线报价"
_clear_air_pending(flow, no, sender_id)
return _commit_quote(flow, ticket, merged, chat_id, sender_id, tms_quote=base if keep_tms else {})
def apply_air_confirm_tms(*, flow: Any, ticket: object, sender_id: str, chat_id: str) -> str:
"""航线确认沿用 TMS:模板入后台,回附件已保存,再出成交跟进。对齐海运。"""
ticket = hydrate_ticket(flow, ticket)
if not is_airline(flow, sender_id):
send_group_text(group_client_of(flow), chat_id, copy.air_airline_only_quote())
return "not_airline"
view = ticket_view(ticket)
quote = dict(view.get("quote") or {})
if not _has_tms_quote(quote):
send_group_text(group_client_of(flow), chat_id, copy.group_confirm_need_tms())
return "need_tms"
quote["source_label"] = "航线确认TMS"
no = ticket_no(ticket)
_clear_air_pending(flow, no, sender_id)
# 确认 TMS 出单:同样用总销售价,避免只落附加费明细时预估费用=200。
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 {}
if not saved.get("ok"):
send_group_text(group_client_of(flow), chat_id, "主账写入报价失败。")
return "ledger_fail"
view["collab_chat_id"] = chat_id
view["quote"] = sheet_quote
_persist_quote_sheet(
flow=flow,
ticket=view,
sess=None,
quote=sheet_quote,
sender_id=sender_id,
business_line="AIR",
)
notify_quote_attachment_saved(flow, chat_id, no, count=1)
from agent.policy.event_exception import clear_wait
clear_wait(flow.ledger, work_order_no=no)
emit_group_deal(flow=flow, ticket=view, quote=quote)
return "quote_confirmed"
def apply_air_deal(
*,
flow: Any,
ticket: object,
sender_id: str,
outcome: str,
chat_id: str,
text: str = "",
) -> str:
if not is_sales(ticket, sender_id):
send_group_text(group_client_of(flow), chat_id, copy.air_sales_only_deal())
return "not_sales"
view = ticket_view(ticket)
no = ticket_no(ticket)
status_now = ticket_status(ticket)
# 与海运一致:同一终态再确认不刷「不能修改」。
if status_now in {"已成交", "未成交"} and outcome == status_now:
return "deal_already_recorded"
stopped = halt_closed_group(flow=flow, ticket=ticket, chat_id=chat_id)
if stopped:
return stopped
from agent.policy.deal_outcome import finish_deal_outcome, harvest_inline_lost_reason
from agent.policy.sea_group_ops import _quote_fee_rows, facts_of_group
quote = dict(view.get("quote") or {})
usable_total = str(quote.get("total") or "").strip()
if usable_total in {"", "-"}:
usable_total = ""
# 与海运一致:询价中且无报价时先说清原因,禁止笼统「主账状态更新失败」。
if not (usable_total or _quote_fee_rows(quote) or status_now in {"已报价", "协商中"}):
send_group_text(
group_client_of(flow), chat_id, copy.deal_fail_no_quote(work_order_no=no)
)
return "deal_need_quote"
inline = harvest_inline_lost_reason(text) if outcome == "未成交" else ""
result = finish_deal_outcome(
ledger=flow.ledger,
work_order_no=no,
outcome=outcome,
facts=facts_of_group(view),
quote=quote,
business_line="AIR",
sales_name=str(view.get("sales_name") or ""),
lost_reason=inline,
)
if not result.get("ok"):
# 迁态失败且仍无报价时,同样用「没有报价」说明,避免旧笼统句。
err = str(result.get("error") or "")
still_no_quote = not (
usable_total or _quote_fee_rows(quote) or status_now in {"已报价", "协商中"}
)
if still_no_quote or "询价中" in err:
send_group_text(
group_client_of(flow), chat_id, copy.deal_fail_no_quote(work_order_no=no)
)
else:
send_group_text(
group_client_of(flow), chat_id, "主账状态更新失败,成交结果未入账。"
)
return "ledger_fail"
phase = str(result.get("phase") or "done")
ack_reason = inline if phase == "done" and outcome == "未成交" else ""
send_group_text(
group_client_of(flow),
chat_id,
copy.deal_ack(
outcome,
no,
str(result.get("next_followup_at") or ""),
lost_reason=ack_reason,
followup_hours=result.get("negotiate_hours"),
),
)
# 共用回执仍是「已记录为已成交」。催锁只加在空运群,海运陆运不走这里。
if outcome == "已成交" and phase == "done":
prompt_airline_to_lock(flow=flow, ticket=ticket, chat_id=chat_id, work_order_no=no)
return phase
def _bind_deal_cabin_room(flow: Any, *, chat_id: str, work_order_no: str) -> None:
"""已成交锁舱时把工单留在本群。普通激活仍拒绝已成交。失败只记日志,不挡这一句锁舱。"""
book = getattr(flow, "ledger", None)
activator = getattr(book, "activate_air_group", None) if book is not None else None
if not callable(activator):
return
try:
activator(chat_id=chat_id, work_order_no=work_order_no, allow_deal=True)
except TypeError:
logger.warning("主账激活不接受已成交绑群 wo=%s", work_order_no)
except Exception:
logger.exception("已成交锁舱绑群失败 wo=%s", work_order_no)
def prompt_airline_to_lock(
*,
flow: Any,
ticket: object,
chat_id: str,
work_order_no: str = "",
) -> None:
"""
空运单记成已成交后,在协同群点名航线锁舱。
只 @ 岗位为航线·空运的人,不改成交回执。没有群、或多段/海运/陆运,不发。
群消息在调用方线程发出(群回调或私聊成交后的同一轮)。
"""
view = ticket_view(ticket)
no = (work_order_no or ticket_no(ticket)).strip()
room = (chat_id or str(view.get("collab_chat_id") or view.get("collabChatId") or "")).strip()
line = str(view.get("business_line") or view.get("businessLine") or "AIR").strip().upper()
if not no or not room or line != "AIR":
return
_sales_name, airline_names, mention_ids = resolve_air_mentions(flow, ticket)
sales_id = str(view.get("sales_wecom_id") or view.get("salesWecomId") or "").strip()
air_ids = [uid for uid in mention_ids if uid and uid != sales_id]
send_group_text(
group_client_of(flow),
room,
copy.air_lock_ask_airline(work_order_no=no, airline_names=airline_names),
mention_userids=air_ids,
)
def _block_lock_until_deal(flow: Any, ticket: object, chat_id: str) -> str:
"""
未成交的空运单不许锁。已成交返回空串,调用方继续锁。
询价中/已报价:点名本单销售。协商中、未成交、已关闭各说各的。
转人工沿用静默。不打 TMS。
"""
st = ticket_status(ticket)
if st == "已成交":
return ""
no = ticket_no(ticket)
client = group_client_of(flow)
if st == "未成交":
send_group_text(client, chat_id, copy.air_lock_blocked_lost(no))
return "lock_lost"
if st == "协商中":
send_group_text(client, chat_id, copy.air_lock_blocked_negotiating(no))
return "lock_negotiating"
if st == "转人工":
return "handoff_ignore"
if st == "已关闭":
send_group_text(client, chat_id, copy.air_ticket_closed(no, st))
return "ticket_closed"
sales_name, _airline_names, _mention_ids = resolve_air_mentions(flow, ticket)
view = ticket_view(ticket)
sales_id = str(view.get("sales_wecom_id") or view.get("salesWecomId") or "").strip()
send_group_text(
client,
chat_id,
copy.air_lock_need_deal(sales_name=sales_name),
mention_userids=[sales_id] if sales_id else None,
)
return "lock_need_deal"
def apply_air_lock(
*,
flow: Any,
ticket: object,
sender_id: str,
chat_id: str,
instruction: str,
option_no: str = "",
airline: str = "",
flight_no: str = "",
) -> str:
"""
航线锁舱。只有工单已是「已成交」才打主账。
还没回复成交:点名销售先确认。协商中、未成交各用一句,不催销售改口。
话里写的优先,报价里已有的舱位可以补上;补不上也要打主账——
主账会合并历史 TMS / 现拉运价库(产品报价无舱位时不能在智能体侧先挡住)。
主账回 lock_params_incomplete 再群里补问,不标系统异常。
上次锁舱失败标过暂停的,航线再锁仍要打 TMS。锁成功不再推成交跟进。
"""
if not is_airline(flow, sender_id):
send_group_text(group_client_of(flow), chat_id, copy.air_airline_only_cabin())
return "not_airline"
blocked = _block_lock_until_deal(flow, ticket, chat_id)
if blocked:
return blocked
no = ticket_no(ticket)
# 补参句带日期时先写入,避免舱位三项齐了仍反复要报价日期。
ticket, quote_date, _said_quote_date = _absorb_lock_quote_date(
flow=flow,
ticket=ticket,
instruction=instruction,
work_order_no=no,
)
name = operator_name(flow, sender_id)
view_quote = dict(ticket_view(ticket).get("quote") or {})
air_quote = dict((view_quote.get("segment_quotes") or {}).get("AIR") or {})
quote = air_quote or view_quote
quote_id = _quote_id(quote)
facts = dict(ticket_view(ticket).get("collab_facts") or {})
picked, air_code, flight = _resolve_lock_params(
quote,
facts,
option_no=option_no,
airline=airline,
flight_no=flight_no,
instruction=instruction,
)
origin, destination, airline_label, flight_date = _lock_receipt_fields(
ticket, quote, picked, air_code
)
if not quote_date:
quote_date = _ticket_flight_date(ticket)
missing = _missing_lock_labels(picked, air_code, flight, quote_date=quote_date)
if missing and _quote_ready_for_lock(quote):
_remember_partial_lock(
flow,
work_order_no=no,
sender_id=sender_id,
option_no=picked,
airline=air_code,
flight_no=flight,
)
send_group_text(group_client_of(flow), chat_id, copy.air_lock_need_params(missing))
return "wait_lock_params"
locker = getattr(flow.ledger, "lock_cabin", None)
if not callable(locker):
send_group_text(
group_client_of(flow),
chat_id,
copy.air_lock_fail(work_order_no=no, operator=name, reason="主账未开放锁舱"),
)
return "lock_unavailable"
from agent.policy.system_exception import (
STEP_TMS_LOCK,
TYPE_TMS,
SystemExceptionEvent,
call_with_retries,
confirm_system_exception,
)
out = call_with_retries(
lambda: locker(
work_order_no=no,
option_no=picked,
sender_id=sender_id,
operator_name=name,
instruction_text=instruction,
airline=air_code,
flight_no=flight,
)
or {},
is_ok=lambda x: bool((x or {}).get("ok")),
)
if not out.get("ok"):
err_code = str(out.get("error") or "")
if err_code == "no_quote":
send_group_text(group_client_of(flow), chat_id, copy.air_lock_need_quote(no))
return "no_quote"
# 主账再拦一遍成交状态:只回业务句,不当 TMS 故障。
if err_code in {"lock_need_deal", "lock_negotiating", "lock_lost", "ticket_closed"}:
return _block_lock_until_deal(flow, ticket, chat_id) or err_code
# 主账在出站前发现三项不齐:只请补,不当 TMS 故障,不通知 IT。
reason_text = str(out.get("failReason") or "")
if err_code == "lock_params_incomplete" or "锁舱参数不完整" in reason_text:
labels = missing or _labels_from_incomplete_reason(reason_text)
_remember_partial_lock(
flow,
work_order_no=no,
sender_id=sender_id,
option_no=picked,
airline=air_code,
flight_no=flight,
)
send_group_text(group_client_of(flow), chat_id, copy.air_lock_need_params(labels))
return "wait_lock_params"
# 仅「航线附件报价」引导纯文字价。有 TMS / 文字手工价失败不能误进这条
# (旧逻辑用「无匹配报价」关键字,会把 TMS 锁舱失败也拐进文字报价提示)。
src_label = str((quote or {}).get("source_label") or (quote or {}).get("source") or "")
is_attach_quote = "航线附件报价" in src_label
need_text_quote = (
is_attach_quote and err_code in {"lock_incomplete", "lock_fail"}
)
if need_text_quote:
send_group_text(
group_client_of(flow),
chat_id,
copy.air_lock_need_text_quote(
work_order_no=no, operator=name, reason=reason_text
),
)
return "need_text_quote"
if err_code == "lock_incomplete":
send_group_text(
group_client_of(flow),
chat_id,
copy.air_lock_incomplete(
work_order_no=no, operator=name, reason=reason_text
),
)
return "lock_incomplete"
# 多段是产品限制,不是 TMS 故障。只回原因,不标系统异常、不暂停工单。
if err_code == "multi_no_lock":
send_group_text(
group_client_of(flow),
chat_id,
copy.multi_air_lock_unsupported(work_order_no=no, operator=name),
)
return "multi_lock_unsupported"
why = copy.air_cabin_fail_reason(
tms_reason=str(out.get("failReason") or out.get("error") or ""),
flight_date=_ticket_flight_date(ticket),
)
send_group_text(
group_client_of(flow),
chat_id,
copy.air_lock_fail(work_order_no=no, operator=name, reason=why),
)
confirm_system_exception(
event=SystemExceptionEvent(
exception_type=TYPE_TMS,
step=STEP_TMS_LOCK,
reason="空运锁舱接口调用失败",
service="空运锁舱",
error_code=why or "LOCK_FAIL",
work_order_no=no,
ticket_status=ticket_status(ticket),
conversation_kind="group",
conversation_target=chat_id,
extra={
"option_no": picked,
"airline": airline_label or air_code,
"flight_no": flight,
"instruction": instruction,
"sender_id": sender_id,
"operator_name": name,
"flight_date": flight_date,
"origin": origin,
"destination": destination,
},
),
ledger=flow.ledger,
)
return "system_exception"
exec_no = str(out.get("lockId") or out.get("tmsRequestId") or "").strip()
quote_no = str(out.get("quoteId") or quote_id).strip()
flow.ledger.patch_collab_facts(
work_order_no=no,
facts={
_LOCK_ID: exec_no,
_LOCK_OPTION: picked,
_LOCK_QUOTE: quote_no,
_LOCK_EXEC: exec_no,
_PENDING_LOCK: "",
_PENDING_LOCK_OPTION: "",
_PENDING_LOCK_AIRLINE: "",
_PENDING_LOCK_FLIGHT: "",
},
sender_id=sender_id,
)
send_group_text(
group_client_of(flow),
chat_id,
copy.air_lock_ok(
work_order_no=no,
operator=name,
option_no=picked,
exec_no=exec_no,
quote_no=quote_no,
origin=origin,
destination=destination,
airline=airline_label,
flight_date=flight_date,
),
)
from agent.policy.system_exception import clear_system_exception, ticket_is_paused
if ticket_is_paused(ticket):
clear_system_exception(ledger=flow.ledger, work_order_no=no)
return "lock_ok"
def _release_should_push_deal(ticket: object) -> bool:
"""
放舱成功后要不要再推成交跟进。
未成交、已关闭、已成交、转人工:成交结果已经定过,只回释放结果。
还在等销售确认时仍要推一张。
"""
return ticket_status(ticket) not in TERMINAL
def apply_air_release(
*,
flow: Any,
ticket: object,
sender_id: str,
chat_id: str,
instruction: str,
) -> str:
if not is_airline(flow, sender_id):
send_group_text(group_client_of(flow), chat_id, copy.air_airline_only_cabin())
return "not_airline"
# 释放同理:暂停单、已成交单也允许再打 TMS。还没锁过的仍拒绝。
no = ticket_no(ticket)
facts = dict(ticket_view(ticket).get("collab_facts") or {})
lock_id = str(facts.get(_LOCK_ID) or "").strip()
name = operator_name(flow, sender_id)
if not lock_id:
send_group_text(group_client_of(flow), chat_id, copy.air_release_need_lock(no))
return "release_need_lock"
releaser = getattr(flow.ledger, "release_cabin", None)
if not callable(releaser):
send_group_text(
group_client_of(flow),
chat_id,
copy.air_release_fail(work_order_no=no, operator=name, reason="主账未开放取消舱位"),
)
return "release_unavailable"
from agent.policy.system_exception import (
STEP_TMS_RELEASE,
TYPE_TMS,
SystemExceptionEvent,
call_with_retries,
confirm_system_exception,
)
out = call_with_retries(
lambda: releaser(
work_order_no=no,
lock_id=lock_id,
sender_id=sender_id,
operator_name=name,
instruction_text=instruction,
)
or {},
is_ok=lambda x: bool((x or {}).get("ok")),
)
if not out.get("ok"):
why = copy.air_cabin_fail_reason(
tms_reason=str(out.get("failReason") or out.get("error") or ""),
flight_date=_ticket_flight_date(ticket),
)
send_group_text(
group_client_of(flow),
chat_id,
copy.air_release_fail(work_order_no=no, operator=name, reason=why),
)
confirm_system_exception(
event=SystemExceptionEvent(
exception_type=TYPE_TMS,
step=STEP_TMS_RELEASE,
reason="空运取消舱位接口调用失败",
service="空运舱位",
error_code=why or "RELEASE_FAIL",
work_order_no=no,
ticket_status=ticket_status(ticket),
conversation_kind="group",
conversation_target=chat_id,
extra={
"lock_id": lock_id,
"instruction": instruction,
"sender_id": sender_id,
"operator_name": name,
"flight_date": _ticket_flight_date(ticket),
},
),
ledger=flow.ledger,
)
return "system_exception"
exec_no = str(out.get("releaseId") or out.get("tmsRequestId") or lock_id).strip()
send_group_text(
group_client_of(flow),
chat_id,
copy.air_release_ok(
work_order_no=no,
operator=name,
option_no=str(facts.get(_LOCK_OPTION) or ""),
exec_no=exec_no,
quote_no=str(facts.get(_LOCK_QUOTE) or ""),
),
)
from agent.policy.system_exception import clear_system_exception, ticket_is_paused
if ticket_is_paused(ticket):
clear_system_exception(ledger=flow.ledger, work_order_no=no)
if _release_should_push_deal(ticket):
view = ticket_view(ticket)
view["collab_chat_id"] = chat_id
emit_group_deal(flow=flow, ticket=view, quote=dict(view.get("quote") or {}))
return "release_ok"
def current_ticket(flow: Any, chat_id: str) -> Optional[object]:
book = flow.ledger
hit = book.find_by_collab_chat(chat_id=chat_id)
if hit is None:
return None
return hydrate_ticket(flow, hit)
def _commit_quote(
flow: Any,
ticket: object,
quote: dict[str, Any],
chat_id: str,
sender_id: str,
tms_quote: Optional[dict[str, Any]] = None,
raw_text: str = "",
raw_source: str = "",
) -> str:
"""
报价落定:写入主账,重发摘要,再出成交跟进;不自动发 Excel/PDF。
转人工协同单(collab_mode=handoff):报价照常落账,但不再生成交跟进;
成交由销售在后台处理。raw_text 是产品原话,主账只留档参考。
TMS 没有报价、航线按 KG 手工报价时(如「USD11/kg」),这里按工单体积/毛重
算一次计费重(体积重 = CBM×166.7,计费重 = max(毛重, 体积重)):
补进报价对象、把 KG 费用行补成「单价×计费重」并重算合计。
这样群摘要、后台报价版本和报价单看到的是同一个数(产品口径 2026-11-22)。
"""
_ = sender_id
no = ticket_no(ticket)
handoff = is_handoff_collab(flow, ticket)
from agent.schema.air_chargeable import apply_to_quote
facts = dict((ticket_view(ticket) or {}).get("facts") or {})
quote = apply_to_quote(quote, facts, business_line="AIR")
up = flow.ledger.upsert_product_quote(
work_order_no=no,
quote=quote,
to_status="已报价",
raw_text=raw_text,
raw_source=raw_source,
)
if not up.get("ok"):
send_group_text(group_client_of(flow), chat_id, "主账写入报价失败。")
return "ledger_fail"
from agent.policy.event_exception import clear_wait
clear_wait(flow.ledger, work_order_no=no)
ticket2 = current_ticket(flow, chat_id) or ticket
view = ticket_view(ticket2)
view["collab_chat_id"] = chat_id
view["quote"] = quote
send_air_brief_and_sheet(
flow=flow,
ticket=view,
chat_id=chat_id,
quote_override=quote,
tms_quote=tms_quote if tms_quote is not None else {},
product_quote=quote,
include_sheet=False,
)
if handoff:
# 转人工:产品已把价报进群,AI 抓取并回摘要即可。
# 成交跟进由销售线下谈,禁止再发「是否成交」卡。
return "quoted_handoff"
emit_group_deal(flow=flow, ticket=view, quote=quote)
return "quoted"
def peek_air_pending(ticket: object) -> dict[str, Any]:
"""这张单是否还在等航线选怎么用 TMS。"""
return _load_air_pending(ticket, ticket_no(ticket))
def _park_air_pending(flow: Any, work_order_no: str, quote: dict[str, Any], sender_id: str) -> None:
"""先记下航线刚报的价,不写主账报价版本。Redis 正式;协同字段兜底给单测。"""
try:
from agent.redis_coord.pending_quote import save_pending_product_quote
save_pending_product_quote(work_order_no, quote)
except Exception:
logger.exception("待确认航线报价写入失败 wo=%s", work_order_no)
flow.ledger.patch_collab_facts(
work_order_no=work_order_no,
facts={_PENDING_QUOTE: json.dumps(quote, ensure_ascii=False)},
sender_id=sender_id,
)
def _load_air_pending(ticket: object, work_order_no: str) -> dict[str, Any]:
try:
from agent.redis_coord.pending_quote import load_pending_product_quote
parked = load_pending_product_quote(work_order_no)
if parked:
return parked
except Exception:
logger.exception("待确认航线报价读取失败 wo=%s", work_order_no)
raw = str((ticket_view(ticket).get("collab_facts") or {}).get(_PENDING_QUOTE) or "").strip()
if not raw:
return {}
try:
data = json.loads(raw)
except json.JSONDecodeError:
return {}
return dict(data) if isinstance(data, dict) else {}
def _clear_air_pending(flow: Any, work_order_no: str, sender_id: str) -> None:
try:
from agent.redis_coord.pending_quote import clear_pending_product_quote
clear_pending_product_quote(work_order_no)
except Exception:
logger.exception("待确认航线报价清理失败 wo=%s", work_order_no)
flow.ledger.patch_collab_facts(
work_order_no=work_order_no,
facts={_PENDING_QUOTE: ""},
sender_id=sender_id,
)
def _has_tms_quote(quote: dict[str, Any]) -> bool:
"""当前价来自 TMS 才要问;航线/产品/销售调价不再替用户选。"""
src = dict(quote or {})
if not (src.get("total") or src.get("quoteId") or src.get("quote_id")):
return False
return copy.quote_is_tms(src)
def _is_product_quote(quote: dict[str, Any]) -> bool:
src = str(quote.get("source_label") or "")
return "航线" in src or "产品" in src
_OPTION_RE = re.compile(r"AIR-?OPT-?\d+")
_AIRLINE_AFTER_OPTION_RE = re.compile(r"AIR-?OPT-?\d+\s*([A-Z]{2})(?![A-Z0-9])")
_AIRLINE_LABELED_CODE_RE = re.compile(
r"航司(?:代码|二字码)?\s*[::]?\s*(?:是|为)?\s*([A-Z]{2}|[A-Z]\d|\d[A-Z])(?![A-Z0-9])"
)
_AIRLINE_LABELED_NAME_RE = re.compile(
r"航司(?:代码|二字码)?\s*[::]?\s*(?:是|为)?\s*([\u4e00-\u9fffA-Za-z0-9]{2,12})"
)
_FLIGHT_LABELED_RE = re.compile(
r"(?:航班号|航班)\s*[::]?\s*(?:是|为)?\s*([A-Z]{2}\s*\d{2,4}|[A-Z]\d\s*\d{2,4}|\d[A-Z]\s*\d{2,4})"
)
_FLIGHT_TRAIL_RE = re.compile(
r"AIR-?OPT-?\d+\s+(?:[A-Z]{2}\s+)?([A-Z]{2}\s*\d{2,4})"
)
_FLIGHT_LOOSE_RE = re.compile(r"(?<![A-Z0-9])(?!WO)([A-Z]{2}\d{2,4})(?!\d)")
_AIRLINE_CODE_RE = re.compile(r"^(?:[A-Z]{2}|[A-Z]\d|\d[A-Z])$")
_FLIGHT_CODE_RE = re.compile(r"^(?:[A-Z]{2}|[A-Z]\d|\d[A-Z])\d{2,4}$")
# 口语航司名归一成二字码。认不出的原样留下,交给 TMS,不因此再追问。
_AIRLINE_ALIASES = (
("中国南方航空", "CZ"),
("南方航空", "CZ"),
("南航", "CZ"),
("中国国际航空", "CA"),
("国际航空", "CA"),
("国航", "CA"),
("中国东方航空", "MU"),
("东方航空", "MU"),
("东航", "MU"),
("海南航空", "HU"),
("海航", "HU"),
("厦门航空", "MF"),
("厦航", "MF"),
("深圳航空", "ZH"),
("深航", "ZH"),
("四川航空", "3U"),
("川航", "3U"),
("山东航空", "SC"),
("山航", "SC"),
("春秋航空", "9C"),
("吉祥航空", "HO"),
("新加坡航空", "SQ"),
("新航", "SQ"),
("泰国航空", "TG"),
("泰航", "TG"),
("国泰航空", "CX"),
("国泰", "CX"),
("卡塔尔航空", "QR"),
("顺丰航空", "O3"),
)
def lock_params_from_text(text: str) -> tuple[str, str, str]:
"""
从航线原话抽出舱位编号、航司、航班号。
不要求「AIR-OPT01 CZ 航班CZ327」这一种写法。
带「舱位 / 航司 / 航班」的说法、换顺序、航司用中文名,都认。
本地对不上、话里又在补这三项时,再问模型。没说的不猜。
"""
option, airline, flight = _lock_params_local(text)
if option and airline and flight:
return option, airline, flight
if not _should_ask_lock_model(text, option, airline, flight):
return option, airline, flight
got_opt, got_air, got_flight = _lock_params_from_model(text)
return (
option or got_opt,
airline or _normalize_airline(got_air),
flight or _normalize_flight(got_flight),
)
def text_has_lock_supplement(text: str) -> bool:
"""这句话是在补锁舱三项,不是报价或闲聊。凑齐两项,或点名了舱位/航司/航班,都算。"""
option, airline, flight = _lock_params_local(text)
filled = sum(1 for item in (option, airline, flight) if item)
if filled >= 2:
return True
raw = text or ""
if filled < 1 or not any(word in raw for word in ("舱位", "航司", "航班")):
return False
from agent.routing.group_intent import text_is_staff_fee_quote
return not text_is_staff_fee_quote(raw)
def _lock_params_local(text: str) -> tuple[str, str, str]:
"""按原话里的编号、标签和常见航司名收三项。不调模型。"""
raw = text or ""
blob = raw.upper()
option = _option_from_blob(blob)
flight = _flight_from_blob(blob)
airline = _airline_from_text(raw, blob, option=option, flight=flight)
return option, airline, flight
def _option_from_blob(blob: str) -> str:
found = _OPTION_RE.search(blob or "")
if not found:
return ""
raw = found.group(0)
if raw.startswith("AIROPT"):
return "AIR-OPT" + raw[6:]
return raw
def _flight_from_blob(blob: str) -> str:
labeled = _FLIGHT_LABELED_RE.search(blob or "")
if labeled:
return _normalize_flight(labeled.group(1))
trailed = _FLIGHT_TRAIL_RE.search(blob or "")
if trailed:
return _normalize_flight(trailed.group(1))
loose = _FLIGHT_LOOSE_RE.search(blob or "")
if loose:
return _normalize_flight(loose.group(1))
return ""
def _airline_from_text(raw: str, blob: str, *, option: str, flight: str) -> str:
"""航司可以是二字码,也可以是「航司南航」这种说法。"""
labeled = _AIRLINE_LABELED_CODE_RE.search(blob or "")
if labeled:
return labeled.group(1)
named = _AIRLINE_LABELED_NAME_RE.search(raw or "")
if named:
token = named.group(1).strip()
if token.upper() not in {"AIR", "OPT"} and not token.upper().startswith("AIR-OPT"):
return _normalize_airline(token)
after = _AIRLINE_AFTER_OPTION_RE.search(blob or "")
if after:
return after.group(1)
# 没写「航司」二字时,只有这句话已经带了舱位或航班,才从航司名里认,避免报价句子被误伤。
if option or flight:
found = _alias_in_text(raw)
if found:
return found
return ""
def _normalize_flight(value: str) -> str:
compact = re.sub(r"\s+", "", (value or "").upper())
return compact if _FLIGHT_CODE_RE.match(compact) else ""
def _normalize_airline(value: str) -> str:
text = (value or "").strip()
if not text:
return ""
upper = re.sub(r"\s+", "", text.upper())
if _FLIGHT_CODE_RE.match(upper):
return ""
if _AIRLINE_CODE_RE.match(upper):
return upper
alias = _alias_in_text(text)
if alias:
return alias
if re.fullmatch(r"[\u4e00-\u9fffA-Za-z0-9]{2,12}", text) and not text.upper().startswith("AIR"):
return text
return ""
def _alias_in_text(text: str) -> str:
raw = text or ""
for name, code in _AIRLINE_ALIASES:
if name in raw:
return code
return ""
def _airline_ready(airline: str) -> bool:
text = (airline or "").strip()
if _AIRLINE_CODE_RE.match(text.upper()):
return True
return bool(_normalize_airline(text))
def _should_ask_lock_model(text: str, option: str, airline: str, flight: str) -> bool:
"""三项已经齐,或这句话根本没在说舱位,就不要再打模型。"""
if option and airline and flight:
return False
raw = text or ""
if any(word in raw for word in ("舱位", "航司", "航班")):
return True
blob = raw.upper()
return "AIR-OPT" in blob or "AIROPT" in blob
def _lock_params_from_model(text: str) -> tuple[str, str, str]:
"""
模型只抽舱位编号、航司、航班号。
网络未开或调用失败时当没抽到,群里继续按缺项追问。不在请求里猜。
"""
try:
from agent.config import get_settings
from agent.llm.http_client import LlmHttpClient
from agent.llm.modes import LlmMode
settings = get_settings()
if not (
getattr(settings, "llm_allow_network", False)
and getattr(settings, "llm_data_usage_confirmed", False)
):
return "", "", ""
client = LlmHttpClient.from_settings(settings)
data = client.chat(
mode=LlmMode.EXTRACT_FIELDS,
messages=[
{
"role": "system",
"content": (
"从航线这句话抽出锁舱三项。只回复一行 JSON,不要解释。"
'键为 optionNo、airline、flightNo。没有的填空字符串。'
"optionNo 是舱位编号,如 AIR-OPT01;airline 是航司二字码或航司名;"
"flightNo 是航班号,如 CZ327。不要编造原文没有的值。"
),
},
{"role": "user", "content": (text or "")[:500]},
],
)
content = str((data or {}).get("content") or "")
start = content.find("{")
end = content.rfind("}")
if start < 0 or end <= start:
return "", "", ""
payload = json.loads(content[start : end + 1])
if not isinstance(payload, dict):
return "", "", ""
option = _option_from_blob(str(payload.get("optionNo") or "").upper())
airline = _normalize_airline(str(payload.get("airline") or ""))
flight = _normalize_flight(str(payload.get("flightNo") or ""))
return option, airline, flight
except Exception:
logger.exception("锁舱三项模型抽取失败")
return "", "", ""
def _resolve_lock_params(
quote: dict[str, Any],
facts: dict[str, Any],
*,
option_no: str,
airline: str,
flight_no: str,
instruction: str,
) -> tuple[str, str, str]:
"""
拼出锁舱三项。
这一句里写的优先;没写的用上一句暂存的;再没有才用报价上已有的舱位。
TMS 已有舱位明细时(selected_air_option / airOptions):句中未点名也自动带出,
禁止再追问舱位编号/航司/航班号(WO014:航线确认TMS 后直接「锁舱」仍被补问)。
航司写成南航、东方航空这类名字时归一成二字码;归一不了也算已经补充,不再追问。
"""
said_opt, said_air, said_flight = lock_params_from_text(instruction)
option = (option_no or said_opt or str(facts.get(_PENDING_LOCK_OPTION) or "")).strip()
air = _normalize_airline(airline or said_air or str(facts.get(_PENDING_LOCK_AIRLINE) or ""))
flight = _normalize_flight(flight_no or said_flight or str(facts.get(_PENDING_LOCK_FLIGHT) or ""))
chosen = _option_row(quote, option)
if chosen is None and not option:
chosen = _default_cabin_row(quote)
if chosen is not None:
option = str(chosen.get("optionNo") or chosen.get("option_no") or "").strip()
if not _airline_ready(air) and chosen is not None:
air = _normalize_airline(
str(
chosen.get("airlineCode")
or chosen.get("airline")
or chosen.get("airlineName")
or ""
)
)
if not flight and chosen is not None:
flight = _normalize_flight(str(chosen.get("flightNo") or chosen.get("flight_no") or ""))
if not flight:
flight = _normalize_flight(str(quote.get("flightNo") or quote.get("flight_no") or ""))
if not _airline_ready(air):
air = ""
if not air and len(flight) >= 2 and flight[:2].isalpha():
air = flight[:2]
return option, air, flight
def _selected_cabin_row(quote: dict[str, Any]) -> Optional[dict[str, Any]]:
"""报价上已选定的舱位(JSON 字符串或 dict)。"""
selected = (quote or {}).get("selected_air_option") or (quote or {}).get("selectedAirOption")
if isinstance(selected, str) and selected.strip().startswith("{"):
try:
selected = json.loads(selected)
except json.JSONDecodeError:
selected = None
if isinstance(selected, dict) and (
selected.get("optionNo") or selected.get("option_no") or selected.get("flightNo")
):
return selected
return None
def _default_cabin_row(quote: dict[str, Any]) -> Optional[dict[str, Any]]:
"""
句中未点名舱位时的默认行。
优先 selected_air_option;否则单条 airOptions;TMS 多条时取第一条,
避免「已有 TMS 舱位仍追问三项」(WO014)。
"""
selected = _selected_cabin_row(quote)
if selected is not None:
return selected
options = _air_options(quote)
if len(options) == 1:
return options[0]
if len(options) > 1 and _quote_has_tms_cabin(quote):
return options[0]
return None
def _quote_has_tms_cabin(quote: dict[str, Any]) -> bool:
"""本单报价里已有可引用的 TMS 舱位明细。"""
src = dict(quote or {})
qid = str(src.get("quoteId") or src.get("quote_id") or "").strip()
if qid and not qid.upper().startswith("QT-"):
return bool(_air_options(src) or _selected_cabin_row(src))
label = str(src.get("source_label") or src.get("source") or "").upper()
if "TMS" in label:
return bool(_air_options(src) or _selected_cabin_row(src))
return False
def _option_row(quote: dict[str, Any], option_no: str) -> Optional[dict[str, Any]]:
"""按舱位编号找报价里的那一条;对不上返回空。"""
want = (option_no or "").strip().upper()
if not want:
return None
for row in _air_options(quote):
no = str(row.get("optionNo") or row.get("option_no") or "").strip().upper()
if no == want:
return row
selected = _selected_cabin_row(quote)
if selected is not None:
no = str(selected.get("optionNo") or selected.get("option_no") or "").strip().upper()
if no == want:
return selected
return None
def _missing_lock_labels(
option_no: str,
airline: str,
flight_no: str,
*,
quote_date: str = "",
) -> list[str]:
"""
缺的中文名,顺序固定:舱位编号、航司、航班号、报价日期。
报价日期空也要进缺项,避免先只补舱位三项、再被主账单独拦一次。
"""
from agent.schema.field_validate import is_blank_quote_date
missing: list[str] = []
if not (option_no or "").strip():
missing.append("舱位编号")
if not _airline_ready(airline):
missing.append("航司")
if not _FLIGHT_CODE_RE.match((flight_no or "").strip().upper()):
missing.append("航班号")
if is_blank_quote_date(quote_date):
missing.append("报价日期")
return missing
def _labels_from_incomplete_reason(reason: str) -> list[str]:
"""主账回了「缺少:…」时,按中文名收回缺项,丢掉英文字段名。"""
found = [
label
for label in ("舱位编号", "航司", "航班号", "报价日期")
if label in (reason or "")
]
return found or ["舱位编号", "航司", "航班号"]
def _remember_partial_lock(
flow: Any,
*,
work_order_no: str,
sender_id: str,
option_no: str,
airline: str,
flight_no: str,
) -> None:
"""先记下已经说清的项,下一句补齐后接着锁,不用重说。"""
patcher = getattr(flow.ledger, "patch_collab_facts", None)
if not callable(patcher):
return
patcher(
work_order_no=work_order_no,
facts={
_PENDING_LOCK: "1",
_PENDING_LOCK_OPTION: option_no,
_PENDING_LOCK_AIRLINE: airline,
_PENDING_LOCK_FLIGHT: flight_no,
},
sender_id=sender_id,
)
def _quote_id(quote: dict[str, Any]) -> str:
return str(quote.get("quoteId") or quote.get("quote_id") or "").strip()
def _quote_ready_for_lock(quote: dict[str, Any]) -> bool:
"""
有没有可锁的报价:真实 TMS 编号,或人工总价/费用明细。
与内存账本口径一致,禁止把空报价当成「缺舱位」去补问。
"""
src = dict(quote or {})
label = str(src.get("source_label") or src.get("sourceLabel") or "")
if "确认" in label and "TMS" in label.upper():
qid = str(src.get("quoteId") or "").strip()
return bool(qid) and not qid.upper().startswith("QT-")
if str(src.get("total") or "").strip() not in {"", "-"}:
return True
if src.get("fee_rows") or src.get("fee_lines") or src.get("feeItems") or src.get("departureCharges"):
return True
if _air_options(src):
return True
qid = str(src.get("quoteId") or src.get("quote_id") or "").strip()
return bool(qid) and not qid.upper().startswith("QT-WO")
def _picked_option(
options: list[dict[str, Any]], option_no: str
) -> dict[str, Any]:
"""按 optionNo 取舱位;对不上返回空 dict。"""
want = (option_no or "").strip().upper()
if not want:
return {}
for row in options:
no = str(row.get("optionNo") or row.get("option_no") or "").strip().upper()
if no == want:
return row
return {}
def _airline_from_quote_or_option(
quote: dict[str, Any],
options: list[dict[str, Any]],
option_no: str,
) -> str:
"""
锁舱航司:舱位 airlineCode > 报价顶层 > 航班号前两位。
只回两位大写字母;猜不到就空,交给群里补问。
"""
opt = _picked_option(options, option_no)
raw = str(
opt.get("airlineCode")
or opt.get("airline")
or quote.get("airlineCode")
or quote.get("airline")
or ""
).strip().upper()
if len(raw) >= 2 and raw[:2].isalpha():
return raw[:2]
flight = str(
opt.get("flightNo") or opt.get("flight_no") or quote.get("flightNo") or ""
).strip().upper()
if len(flight) >= 2 and flight[0].isalpha() and flight[1].isalpha():
return flight[:2]
name = str(opt.get("airlineName") or quote.get("airlineName") or "").strip()
# 名称里不硬猜二字码,避免「南航」编成乱码。
_ = name
return ""
def _flight_no_from_quote_or_option(
quote: dict[str, Any],
options: list[dict[str, Any]],
option_no: str,
instruction: str = "",
) -> str:
"""航班号:舱位/报价字段,或句中「航班CZ327」「CZ327」形态。"""
import re
opt = _picked_option(options, option_no)
raw = str(opt.get("flightNo") or opt.get("flight_no") or quote.get("flightNo") or "").strip()
if raw:
return raw.upper()
blob = (instruction or "").upper()
m = re.search(r"(?:航班|FLIGHT)\s*([A-Z0-9]{2,8})", blob)
if m:
return m.group(1)
m = re.search(r"\b([A-Z]{2}\d{2,4})\b", blob)
if m:
return m.group(1)
return ""
def _chargeable_weight_kg(
quote: dict[str, Any],
options: list[dict[str, Any]],
option_no: str,
ticket: object,
) -> str:
"""
计费重:舱位 > 报价 > 工单事实「计费重」> 毛重。
有正数才返回;否则空串,门禁会补问。
"""
opt = _picked_option(options, option_no)
candidates = [
opt.get("chargeableWeightKg") or opt.get("chargeable_weight_kg"),
quote.get("chargeableWeightKg") or quote.get("chargeable_weight_kg"),
]
view = ticket_view(ticket)
facts = dict(view.get("facts") or {})
candidates.extend(
[
facts.get("计费重"),
facts.get("计费重量"),
view.get("chargeableWeightKg"),
facts.get("毛重"),
view.get("weightKg") or view.get("weight_kg"),
]
)
for raw in candidates:
text = str(raw or "").strip().replace(",", "")
if not text or text in {"-", "null", "None"}:
continue
# 去掉「公斤」「KGS」等后缀,只留数字。
num = ""
for ch in text:
if ch.isdigit() or ch == ".":
num += ch
elif num:
break
if not num:
continue
try:
if float(num) > 0:
return num
except ValueError:
continue
return ""
def _air_options(quote: dict[str, Any]) -> list[dict[str, Any]]:
raw = quote.get("airOptions") or quote.get("air_options")
if isinstance(raw, str) and raw.strip().startswith("["):
try:
raw = json.loads(raw)
except json.JSONDecodeError:
raw = []
if isinstance(raw, list):
return [x for x in raw if isinstance(x, dict)]
blob = str(quote.get("air_options_json") or "").strip()
if blob.startswith("["):
try:
parsed = json.loads(blob)
except json.JSONDecodeError:
return []
return [x for x in parsed if isinstance(x, dict)]
return []
def _activate_fallback(book: Any, *, chat_id: str, work_order_no: str) -> dict[str, Any]:
"""内存账本未实现 activate 时的兜底,单测应走正式方法。"""
getter = getattr(book, "get_ticket", None)
ticket = getter(work_order_no=work_order_no) if callable(getter) else None
if ticket is None:
return {"ok": False, "error": "ticket_not_found"}
return {"ok": True, "work_order_no": work_order_no}
def _ticket_from_activate(book: Any, no: str, out: dict[str, Any]) -> object:
getter = getattr(book, "get_ticket", None)
if callable(getter):
hit = getter(work_order_no=no)
if hit is not None:
return hit
return out