协同群改为智价通BOT接管对话,报价单按需生成;补客户名称、计费重与陆运报价条件

为什么改:应用建的协同群只能代答,销售在群里发文件、@人、问报价都对不上人;
本次把群对话交给智价通BOT,应用只负责拉群和解散群,并把几处销售已反馈的口径补齐。

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

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

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

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

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

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
linmianxun
2026-11-23 14:18:22 +08:00
co-authored by Cursor
parent b3637f3fc4
commit d9b2029c47
102 changed files with 11216 additions and 870 deletions
+256
View File
@@ -0,0 +1,256 @@
"""
空运计费重单测:体积重 = 体积(CBM) × 166.7,计费重 = max(毛重, 体积重)。
覆盖场景(产品口径 2026-11-22):
- TMS 没有报价、航线按 KG 手工报价时,由工单体积/毛重算出计费重;
- 计费重进报价对象、KG 费用行按「单价×计费重」落金额、合计跟着重算;
- 群里和报价单都看得到同一个数;
- 读不到体积也读不到毛重时绝不编数字;
- 海运/陆运不套空运体积重。
线程:纯函数单测,不碰网络与 DB。
"""
from __future__ import annotations
import unittest
from agent.schema.air_chargeable import (
apply_to_quote,
compute_chargeable,
format_kg,
harvest_declared_chargeable,
parse_quantity,
volume_weight_kg,
)
class ParseQuantityTest(unittest.TestCase):
"""数字解析只去单位,不做语义猜测。"""
def test_strips_weight_and_volume_units(self) -> None:
self.assertEqual(parse_quantity("1,200KG"), 1200.0)
self.assertEqual(parse_quantity("500KGS"), 500.0)
self.assertEqual(parse_quantity("3CBM"), 3.0)
self.assertEqual(parse_quantity("2.5 立方米"), 2.5)
def test_ton_is_projected_to_kg(self) -> None:
# 1.5 吨 = 1500KG,确定性单位投影,不是猜货型。
self.assertEqual(parse_quantity("1.5吨"), 1500.0)
def test_currency_prefix_is_not_a_quantity(self) -> None:
self.assertEqual(parse_quantity("USD 11.00"), 11.0)
def test_blank_and_garbage_return_none(self) -> None:
for raw in (None, "", "-", "—", "左右", "电放"):
self.assertIsNone(parse_quantity(raw), raw)
class ChargeableFormulaTest(unittest.TestCase):
"""体积重与取大规则。"""
def test_volume_weight_uses_166_7(self) -> None:
self.assertAlmostEqual(volume_weight_kg(1.0) or 0, 166.7, places=4)
self.assertAlmostEqual(volume_weight_kg(3.0) or 0, 500.1, places=4)
def test_volume_heavier_than_gross(self) -> None:
out = compute_chargeable({"体积": "3", "毛重": "500"})
self.assertIsNotNone(out)
assert out is not None
self.assertAlmostEqual(out["chargeable_kg"], 500.1, places=4)
self.assertEqual(out["basis"], "volume")
self.assertEqual(format_kg(out["chargeable_kg"]), "500.1")
def test_gross_heavier_than_volume(self) -> None:
out = compute_chargeable({"体积": "1", "毛重": "500"})
assert out is not None
self.assertAlmostEqual(out["chargeable_kg"], 500.0, places=4)
self.assertEqual(out["basis"], "gross")
def test_only_one_side_still_works(self) -> None:
only_volume = compute_chargeable({"体积": "2"})
assert only_volume is not None
self.assertAlmostEqual(only_volume["chargeable_kg"], 333.4, places=4)
only_weight = compute_chargeable({"毛重": "800"})
assert only_weight is not None
self.assertAlmostEqual(only_weight["chargeable_kg"], 800.0, places=4)
def test_explicit_fact_wins(self) -> None:
out = compute_chargeable({"计费重": "800", "体积": "10", "毛重": "100"})
assert out is not None
self.assertAlmostEqual(out["chargeable_kg"], 800.0, places=4)
self.assertEqual(out["basis"], "explicit")
def test_no_numbers_returns_none(self) -> None:
self.assertIsNone(compute_chargeable({}))
self.assertIsNone(compute_chargeable({"体积": "-", "毛重": "待定"}))
class DeclaredChargeableTextTest(unittest.TestCase):
"""航线在群里明说计费重:以他说的为准,且不能被抽成费用行。"""
def test_declared_number_is_harvested(self) -> None:
self.assertEqual(harvest_declared_chargeable("计费重800KG,USD11/kg"), 800.0)
self.assertEqual(harvest_declared_chargeable("计费重量:1,200.5 公斤"), 1200.5)
self.assertIsNone(harvest_declared_chargeable("计费重按实重"))
def test_declared_chargeable_is_not_a_fee_row(self) -> None:
from agent.llm.extract_text import extract_product_quote
quote = extract_product_quote(
"计费重800KG,空运费USD11/kg", business_line="AIR", transport_mode="空运"
)
names = [str(row.get("name") or "") for row in quote.get("fee_rows") or []]
self.assertIn("空运费", names)
self.assertNotIn("计费", names)
class ApplyToQuoteTest(unittest.TestCase):
"""报价对象补齐:计费重 + 行金额 + 合计。"""
def _manual_quote(self) -> dict:
# 与 extract_product_quote("USD11/kg") 的产出同形:只有单价,没有数量。
return {
"total": "11",
"currency": "USD",
"fee_rows": [
{"name": "空运费", "amount": "11", "currency": "USD", "unit": "KG", "unit_price": "11"}
],
"fee_lines": [
{"name": "空运费", "amount": "11", "currency": "USD", "unit": "KG", "unit_price": "11"}
],
}
def test_kg_row_becomes_unit_price_times_chargeable(self) -> None:
out = apply_to_quote(self._manual_quote(), {"体积": "3", "毛重": "500"})
self.assertEqual(str(out.get("chargeableWeightKg")), "500.1")
self.assertEqual(str(out.get("volumeWeightKg")), "500.1")
row = dict((out.get("fee_rows") or [])[0])
self.assertEqual(row.get("quantity"), "500.1")
self.assertAlmostEqual(float(row.get("amount")), 5501.1, places=4)
self.assertEqual(str(out.get("total")), "5501.1")
# 币种不能被计费重改动。
self.assertEqual(str(out.get("currency")), "USD")
def test_total_only_sums_same_currency(self) -> None:
quote = self._manual_quote()
quote["fee_rows"].append({"name": "报关费", "amount": "400", "currency": "CNY"})
quote["fee_lines"] = list(quote["fee_rows"])
out = apply_to_quote(quote, {"毛重": "500"})
# 合计只加第一行币种(USD),CNY 报关费留在明细里不折算。
self.assertEqual(str(out.get("total")), "5500")
def test_existing_chargeable_is_not_overwritten(self) -> None:
quote = self._manual_quote()
quote["chargeableWeightKg"] = "800"
out = apply_to_quote(quote, {"体积": "10", "毛重": "100"})
self.assertEqual(str(out.get("chargeableWeightKg")), "800")
self.assertIn((out.get("fee_rows") or [])[0].get("quantity"), (None, ""))
def test_airline_total_without_qty_is_kept(self) -> None:
# 「空运费 USD8800,单价 11/kg」:航线给了整票金额,不能按体积重覆盖。
quote = {
"total": "8800",
"currency": "USD",
"fee_rows": [
{"name": "空运费", "amount": "8800", "currency": "USD", "unit": "KG", "unit_price": "11"}
],
"fee_lines": [],
}
quote["fee_lines"] = list(quote["fee_rows"])
out = apply_to_quote(quote, {"体积": "3", "毛重": "500"})
self.assertEqual(str((out.get("fee_rows") or [])[0].get("amount")), "8800")
self.assertEqual(str(out.get("total")), "8800")
def test_non_air_lines_are_untouched(self) -> None:
for line in ("SEA", "LAND"):
out = apply_to_quote(self._manual_quote(), {"体积": "3", "毛重": "500"}, business_line=line)
self.assertNotIn("chargeableWeightKg", out)
def test_no_facts_keeps_quote_as_is(self) -> None:
out = apply_to_quote(self._manual_quote(), {})
self.assertEqual(str(out.get("total")), "11")
self.assertNotIn("chargeableWeightKg", out)
class AirManualLayoutChargeableTest(unittest.TestCase):
"""会话界面:人工报价版式里要有计费重。"""
def test_layout_prints_chargeable_without_basis(self) -> None:
"""
计费重只写数字。
产品 2026-11-22 晚在空运协同群核对:人工报价里「计费重:500KG(按实重)」
「计费重:333.4KG(按体积重)」的括注要全部去掉,销售只看 KG 数。
"""
from agent.policy import inquiry_copy as copy
quote = {
"currency": "USD",
"fee_rows": [
{"name": "空运费", "amount": "11", "currency": "USD", "unit": "KG", "unit_price": "11"}
],
"fee_lines": [],
}
quote["fee_lines"] = list(quote["fee_rows"])
facts = {"毛重": "500", "体积": "3", "起运港": "NKG", "目的港": "KUL"}
text = "\n".join(
copy._manual_quote_lines(quote, business_line="AIR", facts=facts, layout="manual")
)
self.assertIn("计费重:500.1KG", text)
self.assertNotIn("按体积重", text)
self.assertNotIn("按实重", text)
def test_stored_basis_never_leaks_hint(self) -> None:
"""
报价对象上已落库 chargeable_weight_basis(volume/gross)时也不能把括注写出来。
这是本次 BUG 的原始路径:落库时写了依据,渲染时又拿依据拼括注。
依据只留在数据里供排查,不参与对外文字。
"""
from agent.policy import inquiry_copy as copy
quote = {
"currency": "USD",
"chargeableWeightKg": "333.4",
"chargeable_weight_basis": "volume",
"fee_rows": [
{"name": "空运费", "amount": "11", "currency": "USD", "unit": "KG", "unit_price": "11"}
],
}
text = "\n".join(
copy._manual_quote_lines(quote, business_line="AIR", facts={}, layout="manual")
)
self.assertIn("计费重:333.4KG", text)
self.assertNotIn("按体积重", text)
self.assertNotIn("按实重", text)
def test_layout_prints_explicit_chargeable_without_hint(self) -> None:
from agent.policy import inquiry_copy as copy
quote = {
"currency": "USD",
"chargeableWeightKg": "800",
"fee_rows": [{"name": "空运费", "amount": "11", "currency": "USD", "unit": "KG"}],
}
text = "\n".join(
copy._manual_quote_lines(quote, business_line="AIR", facts={}, layout="manual")
)
self.assertIn("计费重:800KG", text)
self.assertNotIn("按体积重", text)
def test_no_facts_no_chargeable_line(self) -> None:
from agent.policy import inquiry_copy as copy
quote = {
"currency": "USD",
"fee_rows": [{"name": "空运费", "amount": "11", "currency": "USD", "unit": "KG"}],
}
text = "\n".join(
copy._manual_quote_lines(quote, business_line="AIR", facts={}, layout="manual")
)
self.assertNotIn("计费重", text)
if __name__ == "__main__":
unittest.main()
+16 -6
View File
@@ -70,14 +70,24 @@ class AirFieldContractTests(unittest.TestCase):
self.assertEqual(out["facts"]["尺寸"], "1.1*1.2*3")
self.assertEqual(out["facts"]["比例"], "1:212")
self.assertEqual(out["facts"]["volume_ratio"], "1:212")
# 确定后建单摘要须带回尺寸/比例(有值才显示)
card = copy.inquiry_card(work_order_no="WO1", facts=out["facts"], transport_mode="空运")
# 尺寸/比例有值必须占行(展示在核对卡/拉群摘要这套 inquiry_field_lines 上)
card = "\n".join(
copy.inquiry_field_lines(
work_order_no="WO1", facts=out["facts"], transport_mode="空运"
)
)
self.assertIn("尺寸:1.1*1.2*3", card)
self.assertIn("比例:1:212", card)
bare = copy.inquiry_card(
work_order_no="WO2",
facts={k: v for k, v in out["facts"].items() if k not in {"尺寸", "比例", "volume_ratio"}},
transport_mode="空运",
bare = "\n".join(
copy.inquiry_field_lines(
work_order_no="WO2",
facts={
k: v
for k, v in out["facts"].items()
if k not in {"尺寸", "比例", "volume_ratio"}
},
transport_mode="空运",
)
)
self.assertNotIn("尺寸:", bare)
self.assertNotIn("比例:", bare)
+2 -2
View File
@@ -86,7 +86,7 @@ class AirGroupWorkOrderHintTests(unittest.TestCase):
)
def test_no_work_order_teaches_task_format(self) -> None:
"""没识别到工单号:回固定句式,两种写法都要出现。"""
"""没识别到工单号:只教一种写法「已成交WO****@机器人」。"""
phase = handle_air_group(
self._message("@智报通AIQ 帮我处理一下"),
flow=self.flow,
@@ -95,7 +95,7 @@ class AirGroupWorkOrderHintTests(unittest.TestCase):
self.assertEqual(phase, "need_work_order")
body = self._sent_text()
self.assertIn("已成交WO****@", body)
self.assertIn("WO****已成交@", body)
self.assertNotIn("WO****已成交@", body)
self.assertIn("下达任务", body)
def test_work_order_present_does_not_ask_work_order(self) -> None:
+65 -10
View File
@@ -105,7 +105,8 @@ class AirTextInquiryTests(unittest.TestCase):
self.assertNotIn("重量:(如:", text)
self.assertIn("货源地(非必填):\n(如:东莞)", text)
def test_inquiry_card_matches_sales_format(self) -> None:
def test_inquiry_card_after_confirm_only_keeps_wo_and_tail(self) -> None:
"""产品口径 2026-11-22:确定后只发工单号 + 正在查询TMS报价,字段段不再重复。"""
text = copy.inquiry_card(
work_order_no="WO202609110080",
facts={
@@ -126,19 +127,23 @@ class AirTextInquiryTests(unittest.TestCase):
"\n".join(
[
"工单号:WO202609110080",
"运输方式:空运",
"起运地:珠海",
"目的地:克拉克",
"品名:茶叶",
"件数:10件",
"重量(KG):1",
"体积(CBM):8",
"包装类型:托盘",
"报价日期:2026-09-12",
"工单已创建,正在查询TMS报价。",
]
),
)
# 字段已在对确定前的核对卡逐项确认,建单后不能再发一遍。
for label in (
"运输方式:",
"起运地:",
"目的地:",
"品名:",
"件数:",
"重量(KG):",
"体积(CBM):",
"包装类型:",
"报价日期:",
):
self.assertNotIn(label, text)
def test_air_quote_date_stays_blank_and_not_in_missing(self) -> None:
"""空运没说报价日期不填当天,也不拿来补问。海运、陆运仍默认当天。"""
@@ -883,6 +888,56 @@ class AirTextInquiryTests(unittest.TestCase):
"请手动拉相关人员和智能体到原有群,并在群聊发送工单编号WO202606160008",
)
def test_tms_miss_card_shows_tms_remark(self) -> None:
"""
查价失败时「查价结果」必须展示 TMS 回包 remark 原文。
为何:主账已把 data.remark 透出(如「陆运报价条件无法匹配系统字典,请修正后重试」),
若卡片只写「暂无匹配报价」,销售看不出哪条条件对不上,只能拉产品进群。
"""
reason = "陆运报价条件无法匹配系统字典,请修正后重试"
tms = {
"ok": True,
"has_price": False,
"classification": "TMS_NO_QUOTE_1002",
"code": 1003,
"message": "需补充字段",
"remark": reason,
}
self.assertEqual(copy.tms_miss_reason(tms), reason)
card = copy.tms_miss_wecom_payload(
work_order_no="WO202606160008", reason=reason
)["template_card"]
rows = {x["keyname"]: x["value"] for x in card["horizontal_content_list"]}
self.assertEqual(rows["查价结果"], reason)
self.assertIn(reason, copy.tms_miss(work_order_no="WO202606160008", reason=reason))
# 海运/陆运同一张卡同样展示原文。
sea_card = copy.sea_tms_miss_wecom_payload(
work_order_no="WO202606160008", reason=reason
)["template_card"]
sea_rows = {x["keyname"]: x["value"] for x in sea_card["horizontal_content_list"]}
self.assertEqual(sea_rows["查价结果"], reason)
def test_tms_miss_reason_falls_back_to_missing_fields(self) -> None:
"""remark 缺失时用 TMS 点名的 missingFields.reason,不让销售只看到无价。"""
tms = {
"ok": True,
"has_price": False,
"code": 1003,
"message": "需补充字段",
"missingFields": [
{"field": "segments[0].destination", "reason": "目的地无法匹配系统地址编码"},
{"field": "segments[0].vehicleType", "reason": "车型无法匹配BMS车辆型号"},
],
}
self.assertEqual(
copy.tms_miss_reason(tms),
"目的地无法匹配系统地址编码;车型无法匹配BMS车辆型号",
)
# 业务码标题不含原因,不能当原因展示。
self.assertEqual(copy.tms_miss_reason({"message": "需补充字段"}), "")
self.assertEqual(copy.tms_miss_result_text(""), "暂无匹配报价")
def test_quote_card_payload_has_clickable_button(self) -> None:
payload = copy.tms_hit_wecom_payload(
work_order_no="WO202609140001",
+8
View File
@@ -36,6 +36,14 @@ class BotDisplayNameTests(unittest.TestCase):
self.assertIn("询价小助手", bot_mention_names())
self.assertIn(DEFAULT_BOT_DISPLAY_NAME, bot_mention_names())
def test_need_wo_default_copy_uses_new_name(self) -> None:
"""后台没有 inquiring.air_need_wo 时,兜底句也只能出现「智价通AIQ」。"""
override_catalog({})
self.assertEqual(
copy.air_need_work_order(),
"请以“已成交WO****@智价通AIQ”方式给智价通AIQ下达任务",
)
def test_override_from_admin(self) -> None:
override_catalog({REPLY_CODE: "测试助手名"})
self.assertEqual(bot_display_name(), "测试助手名")
+3 -3
View File
@@ -108,12 +108,12 @@ class BotReplyRenderTests(unittest.TestCase):
named = copy.system_exception_fallback(copy.TYPE_GROUP, names=["张三"])
self.assertIn("张三", named)
def test_air_need_wo_teaches_both_task_formats(self) -> None:
"""没识别到工单号:默认句要同时给出两种下达任务的写法。"""
def test_air_need_wo_teaches_one_task_format(self) -> None:
"""没识别到工单号:只教一种写法「已成交WO****@机器人」。"""
override_catalog({})
text = copy.air_need_work_order()
self.assertIn("已成交WO****@", text)
self.assertIn("WO****已成交@", text)
self.assertNotIn("WO****已成交@", text)
self.assertIn("下达任务", text)
self.assertNotIn("{{", text)
@@ -0,0 +1,202 @@
"""
客户名称:海运/空运/陆运询价时的非必填字段,且必须落库。
业务口径(2026-11-22):
- 陆运:客户名称从「协同阶段填写」改为「询价时填写」,非必填;
- 海运、空运:询价新增「客户名称」,非必填;
- 三条线都要把销售原话里的客户名称记进工单事实,供后台/报价单使用。
本文件只跑纯函数与内存主账,不连企微 / TMS / MySQL。
"""
from __future__ import annotations
import os
import sys
import unittest
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
from agent.ledger.memory_ledger import MemoryLedger
from agent.llm.extract_text import extract_inquiry_snapshot
from agent.llm.mode_extract_fields import parse_extract_payload
from agent.policy import inquiry_copy as copy
from agent.schema.field_validate import (
AIR_OPTIONAL_FIELDS,
SEA_OPTIONAL_FIELDS,
land_collab_fields,
validate_required_fields,
)
SEA_FACTS = {
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "整柜",
"箱型箱量": "1x40HQ",
"贸易条款": "门到门",
"运输分类": "Port to Port",
"报价日期": "2026-11-22",
}
AIR_FACTS = {
"目的港": "吉隆坡",
"品名": "茶叶",
"件数": "10件",
"毛重": "100KG",
"体积": "2CBM",
"包装方式": "纸箱",
}
LAND_FACTS = {
"运输类型": "国内运输拼车",
"线路类别": "国内长途/零担",
"运输分类": "急件",
"起运港": "广州",
"目的港": "深圳",
"品名": "衣服",
"体积": "100CBM",
"毛重": "50KG",
"报价日期": "2026-11-22",
}
class CustomerNameContractTest(unittest.TestCase):
"""字段合同:客户名称在海/空是询价非必填,在陆运不再属于协同项。"""
def test_b_extract_accepts_customer_name(self):
"""DeepSeek B 的 tool 必须能返回客户名称,否则口语询价会丢客户。"""
parsed = parse_extract_payload(
{
"transport_mode": "SEA",
"fields": {"起运港": "上海", "客户名称": "华为"},
}
)
self.assertTrue(parsed["ok"], parsed)
self.assertEqual(parsed["facts"].get("客户名称"), "华为")
def test_sea_customer_name_is_optional_inquiry_field(self):
self.assertIn("客户名称", dict(SEA_OPTIONAL_FIELDS))
self.assertTrue(validate_required_fields(facts=SEA_FACTS, business_line="SEA")["ok"])
def test_air_customer_name_is_optional_inquiry_field(self):
self.assertIn("客户名称", dict(AIR_OPTIONAL_FIELDS))
self.assertTrue(validate_required_fields(facts=AIR_FACTS, business_line="AIR")["ok"])
def test_land_collab_no_longer_requires_customer_name(self):
"""陆运六套协同名单都不能再有客户名称。"""
pairs = (
("国内运输拼车", "国内长途/零担"),
("国内运输拼车", "国内城配/拖车/打包"),
("国内运输整车", "国内长途/零担"),
("国内运输整车", "国内城配/拖车/打包"),
("跨境集拼", "中港/中亚/中欧"),
("跨境集拼", "东南亚"),
("跨境整车", "中港/中亚/中欧"),
("跨境整车", "东南亚"),
("中港整车", "中港/中亚/中欧"),
("中港零担/集拼", "中港/中亚/中欧"),
)
for land_type, route in pairs:
keys = land_collab_fields(land_type, route)
self.assertNotIn("客户名称", keys, f"{land_type}/{route}")
def test_land_inquiry_ok_with_customer_name(self):
check = validate_required_fields(facts=LAND_FACTS, business_line="LAND")
self.assertTrue(check["ok"], check)
class CustomerNameCopyTest(unittest.TestCase):
"""销售可见:核对卡、建单摘要都要出现「客户名称(非必填)」。"""
def test_sea_confirm_card_shows_customer_name(self):
card = copy.sea_confirm_card({**SEA_FACTS, "客户名称": "华为"})
self.assertIn("客户名称(非必填):华为", card)
def test_air_confirm_card_shows_customer_name(self):
card = copy.air_confirm_card({**AIR_FACTS, "客户名称": "华为"})
self.assertIn("客户名称(非必填):华为", card)
def test_land_confirm_card_shows_customer_name(self):
card = copy.land_confirm_card({**LAND_FACTS, "客户名称": "华为"})
self.assertIn("客户名称(非必填):华为", card)
def test_land_clarify_offers_customer_name_as_optional(self):
"""陆运补问时,客户名称以(非必填)列出,销售不回也能继续。"""
text = copy.ask_land_fields(
facts={
"运输类型": "国内运输拼车",
"线路类别": "国内长途/零担",
"运输分类": "急件",
},
missing_keys=["品名"],
land_subtype="国内运输拼车",
)
self.assertIn("客户名称(非必填)", text)
def test_sea_inquiry_lines_keep_customer_name(self):
lines = copy.inquiry_field_lines(
work_order_no="WO202611220001",
facts={**SEA_FACTS, "客户名称": "华为"},
transport_mode="海运",
)
self.assertIn("客户名称:华为", lines)
def test_air_inquiry_lines_keep_customer_name(self):
lines = copy.inquiry_field_lines(
work_order_no="WO202611220002",
facts={**AIR_FACTS, "客户名称": "华为"},
transport_mode="空运",
)
self.assertIn("客户名称:华为", lines)
def test_land_inquiry_lines_keep_customer_name(self):
lines = copy.inquiry_field_lines(
work_order_no="WO202611220003",
facts={**LAND_FACTS, "客户名称": "华为"},
transport_mode="陆运",
)
self.assertIn("客户名称:华为", lines)
class CustomerNameExtractionTest(unittest.TestCase):
"""销售原话里的客户名称要进询价事实。"""
def test_sea_labeled_customer_name_in_snapshot(self):
snap = extract_inquiry_snapshot(
"客户名称:华为",
injected_facts=SEA_FACTS,
injected_mode="SEA",
)
self.assertEqual(snap["facts"].get("客户名称"), "华为")
def test_land_labeled_customer_name_in_snapshot(self):
snap = extract_inquiry_snapshot(
"客户名称华为",
injected_facts={
"运输类型": "国内运输拼车",
"线路类别": "国内长途/零担",
},
injected_mode="LAND",
)
self.assertEqual(snap["facts"].get("客户名称"), "华为")
class CustomerNamePersistenceTest(unittest.TestCase):
"""建单后工单事实必须带客户名称。"""
def test_ticket_facts_record_customer_name(self):
ledger = MemoryLedger()
result = ledger.create_ticket(
sender_id="sales-customer",
business_line="SEA",
facts={**SEA_FACTS, "客户名称": "华为"},
)
self.assertTrue(result.get("ok"), result)
ticket = ledger.get_ticket(work_order_no=result["work_order_no"])
self.assertEqual((ticket.facts or {}).get("客户名称"), "华为")
if __name__ == "__main__":
unittest.main()
+76
View File
@@ -132,6 +132,82 @@ class EndInquiryHandlerTests(unittest.TestCase):
self.assertIn(wo, self.store.out[-1]["content"])
self.assertIn("已关闭", self.store.out[-1]["content"])
def test_dispatch_end_inquiry_intent_while_waiting_lost_reason(self) -> None:
"""
未成交原因是「客户不要了」时,A 误标 end_inquiry 也不能清上下文。
2026-11-17 正服 WO202611170021:BOT 问完未成交原因,销售回「客户不要了」,
A 标成 end_inquiry;结束询价对未成交不改六态,但会把书签清掉,原因丢账。
"""
from agent.channel.queue import get_message_store, reset_message_store_for_tests
from agent.routing.decision import RouteDecision
created = self.ledger.create_ticket(
sender_id="lost-guard",
business_line="AIR",
facts={"起运地": "PVG", "目的地": "LAX", "品名": "配件"},
)
wo = created["work_order_no"]
self.ledger.transition(work_order_no=wo, to_status="已报价")
self.ledger.transition(work_order_no=wo, to_status="未成交")
self.flow._save(
FlowSession(
sender_id="lost-guard",
thread_id="lost-guard",
phase="wait_lost_reason",
business_line="AIR",
facts={"起运地": "PVG", "目的地": "LAX", "品名": "配件"},
work_order_no=wo,
status="未成交",
quote={"total": "CNY 6666.0"},
wait_version=2,
)
)
reset_message_store_for_tests()
msg = InboundMessage(sender_id="lost-guard", content="客户不要了", message_id="m-lost-guard")
intent = dispatch_inbound(msg, RouteDecision(intent="end_inquiry"))
# 纠正回询价流程,不能走 end_inquiry。
self.assertEqual(intent, "ordinary_text_inquiry")
ticket = self.ledger.get_ticket(work_order_no=wo)
self.assertEqual(ticket.status, "未成交")
self.assertEqual(ticket.lost_reason, "客户不要了")
sess = self.flow.session_of("lost-guard")
self.assertIsNotNone(sess)
self.assertEqual(sess.phase, "done")
out = list(get_message_store()._outbox.values())
self.assertIn("已记下未成交原因:客户不要了", out[-1].content)
def test_dispatch_explicit_end_command_still_ends_while_waiting(self) -> None:
"""明确「结束询价」口令优先于未成交原因,不能把口令当原因记下来。"""
from agent.routing.decision import RouteDecision
created = self.ledger.create_ticket(
sender_id="lost-end",
business_line="AIR",
facts={"起运地": "PVG", "目的地": "LAX"},
)
wo = created["work_order_no"]
self.ledger.transition(work_order_no=wo, to_status="已报价")
self.ledger.transition(work_order_no=wo, to_status="未成交")
self.flow._save(
FlowSession(
sender_id="lost-end",
thread_id="lost-end",
phase="wait_lost_reason",
business_line="AIR",
facts={"起运地": "PVG", "目的地": "LAX"},
work_order_no=wo,
status="未成交",
wait_version=1,
)
)
msg = InboundMessage(sender_id="lost-end", content="结束询价", message_id="m-lost-end")
intent = dispatch_inbound(msg, RouteDecision(intent="ordinary_text_inquiry"))
self.assertEqual(intent, "end_inquiry")
self.assertIsNone(self.flow.session_of("lost-end"))
ticket = self.ledger.get_ticket(work_order_no=wo)
self.assertEqual(ticket.lost_reason, "")
def test_dispatch_end_inquiry(self) -> None:
self.flow._save(
FlowSession(
@@ -628,5 +628,72 @@ class TestDealOutcomeStopsTimeout(unittest.TestCase):
self.assertEqual(groups, [])
class TestDefaultSendGroupRouting(unittest.TestCase):
"""
超时话术出站选路:应用 appchat 群不能走 BOT 桥。
2026-11-21 测服事故:陆运协同群建群时就写了 group_bot 标记,
旧判断 is_group_bot 把它当成 BOT 群;桥又拿不到本群 req_id,
最终话术被投递到最后 @ 机器人的空运群。
"""
def _run(self, *, bot_seen: bool, line: str) -> dict:
import importlib.util
import types
from unittest.mock import patch
path = os.path.join(ROOT, "agent", "jobs", "event_exception_poll.py")
spec = importlib.util.spec_from_file_location("ee_poll_routing", path)
self.assertIsNotNone(spec)
self.assertIsNotNone(spec.loader)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
calls: dict = {}
class FakeApp:
def __init__(self, **kwargs) -> None:
_ = kwargs
def send_group(self, *, chat_id: str, content: str) -> dict:
calls["appchat"] = {"chat_id": chat_id, "content": content}
return {"ok": True}
class FakeBot:
def send_group(self, *, chat_id: str, content: str) -> dict:
calls["aibot"] = {"chat_id": chat_id, "content": content}
return {"ok": True}
settings = types.SimpleNamespace(wecom_corp_id="corp", wecom_secret="sec", wecom_agent_id="1")
with patch("agent.redis_coord.group_bot.bot_seen", return_value=bot_seen), patch(
"agent.channel.outbox.sender.WeComAppClient", FakeApp
), patch("agent.channel.aibot.reply.AibotReplyClient", FakeBot), patch(
"agent.config.get_settings", return_value=settings
):
ok = mod._default_send_group(
chat_id="wr-land-app-group", content="产品响应超时", business_line=line
)
calls["ok"] = ok
return calls
def test_appchat_group_without_bot_callback_uses_appchat_send(self) -> None:
calls = self._run(bot_seen=False, line="LAND")
self.assertTrue(calls["ok"])
self.assertIn("appchat", calls)
self.assertNotIn("aibot", calls)
def test_group_that_really_received_bot_callback_uses_bridge(self) -> None:
calls = self._run(bot_seen=True, line="SEA")
self.assertTrue(calls["ok"])
self.assertIn("aibot", calls)
self.assertNotIn("appchat", calls)
def test_air_group_always_uses_bridge(self) -> None:
calls = self._run(bot_seen=False, line="AIR")
self.assertTrue(calls["ok"])
self.assertIn("aibot", calls)
self.assertNotIn("appchat", calls)
if __name__ == "__main__":
unittest.main()
+29 -6
View File
@@ -204,7 +204,7 @@ class OralExtractTests(unittest.TestCase):
assembled = assemble_air_query(
{**first, "originCode": "NKG", "destinationCode": "KUL", "件数": "10"}
)
card = copy.inquiry_card(work_order_no="WO1", facts=assembled["facts"])
card = "\n".join(copy.inquiry_field_lines(work_order_no="WO1", facts=assembled["facts"]))
self.assertIn("起运地:南京", card)
self.assertIn("目的地:吉隆坡", card)
self.assertNotIn("起运地:NKG", card)
@@ -217,7 +217,7 @@ class OralExtractTests(unittest.TestCase):
self.assertEqual(again["facts"]["起运港"], "北京")
self.assertEqual(again["facts"]["originCode"], "PEK")
self.assertEqual(again["facts"]["destinationCode"], "KUL")
shown = copy.inquiry_card(work_order_no="WO2", facts=again["facts"])
shown = "\n".join(copy.inquiry_field_lines(work_order_no="WO2", facts=again["facts"]))
self.assertIn("起运地:北京", shown)
self.assertNotIn("起运地:NKG", shown)
self.assertNotIn("起运地:南京", shown)
@@ -246,7 +246,7 @@ class OralExtractTests(unittest.TestCase):
)
self.assertEqual(assembled["facts"]["originCode"], "SZX")
self.assertEqual(assembled["facts"]["destinationCode"], "CGK")
card = copy.inquiry_card(work_order_no="WO1", facts=assembled["facts"])
card = "\n".join(copy.inquiry_field_lines(work_order_no="WO1", facts=assembled["facts"]))
self.assertIn("起运地:SZX", card)
self.assertIn("目的地:CGK", card)
self.assertNotIn("深圳", card)
@@ -328,9 +328,11 @@ class OralExtractTests(unittest.TestCase):
facts = harvest_oral_measures("从南京飞吉隆坡,茶叶,1.5KG,4.2cbm,托盘", {})
self.assertEqual(facts["毛重"], "1.5KG")
shown = copy.inquiry_card(
work_order_no="WO1",
facts={**facts, "起运港": "南京", "目的港": "吉隆坡", "品名": "茶叶", "件数": "10"},
shown = "\n".join(
copy.inquiry_field_lines(
work_order_no="WO1",
facts={**facts, "起运港": "南京", "目的港": "吉隆坡", "品名": "茶叶", "件数": "10"},
)
)
self.assertIn("重量(KG):1.5KG", shown)
self.assertNotIn("1.5KGS", shown)
@@ -612,6 +614,27 @@ class SeaSheetHeaderClipTests(unittest.TestCase):
oral = extract_inquiry_snapshot("空运 发货日期9月15日", allow_b=False)
self.assertEqual(oral["facts"].get("报价日期"), "2026-09-15")
def test_sea_pickup_and_delivery_address_labels(self) -> None:
"""
海运提货地址、海运派送地址是非必填(产品口径 2026-11-22)。
销售用「海运提货地址/海运派送地址」或补问卡上的「提货地址/派送地址」写法都要收;
内部键沿用提货地址/收货地址,派送与送货同义;没写就不出现,禁止从港口反推。
"""
variants = (
"海运提货地址:深圳坪山仓库\n海运派送地址:洛杉矶仓",
"提货地址:深圳坪山仓库\n派送地址:洛杉矶仓",
"提货地址(非必填):深圳坪山仓库\n派送地址(非必填):洛杉矶仓",
"提货地址:深圳坪山仓库\n送货地址:洛杉矶仓",
)
for body in variants:
facts = extract_inquiry_snapshot(f"海运\n{body}", allow_b=False)["facts"]
self.assertEqual(facts.get("提货地址"), "深圳坪山仓库", body)
self.assertEqual(facts.get("收货地址"), "洛杉矶仓", body)
empty = extract_inquiry_snapshot("海运 上海到洛杉矶 普货", allow_b=False)["facts"]
self.assertNotIn("提货地址", empty)
self.assertNotIn("收货地址", empty)
# 测服 2026-10-05:空运报价单整表被抽进补问,费用和条款进了起运地、货好时间。
AIR_QUOTE_SHEET = """
@@ -0,0 +1,308 @@
"""
协同群 BOT 口径:@ 才唤醒(解散群除外)、非 @ 文字断开工单关联、附件仍走存档。
不连企微 / Redis / 主账;用进程内兜底和 patch。
"""
from __future__ import annotations
import os
import sys
import unittest
from unittest.mock import patch
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
os.environ.setdefault("YTD_ENV", "test")
os.environ.setdefault("REDIS_BACKEND", "memory")
os.environ.setdefault("CHECKPOINT_BACKEND", "memory")
os.environ.setdefault("MESSAGE_STORE_BACKEND", "memory")
os.environ.setdefault("LLM_DATA_USAGE_CONFIRMED", "false")
os.environ.setdefault("LLM_ALLOW_NETWORK", "false")
os.environ.setdefault("LEDGER_BACKEND", "memory")
from agent.channel.wecom.models import InboundMessage
from agent.policy import inquiry_copy as copy
from agent.redis_coord.group_bot import (
clear_at_burst,
clear_active_work_order,
get_active_work_order,
in_at_burst,
is_group_bot,
mark_at_burst,
mark_group_bot,
)
from agent.routing.decision import RouteDecision
from agent.routing.dispatch import dispatch_inbound
def _msg(
*,
chat_id: str,
content: str = "",
msg_type: str = "text",
source: str = "aibot",
sender: str = "u1",
) -> InboundMessage:
"""构造一条群入站;raw.source 决定走 AIBOT 还是会话存档。"""
return InboundMessage(
sender_id=sender,
message_id=f"mid-{chat_id}-{msg_type}-{len(content)}",
content=content,
msg_type=msg_type,
chat_id=chat_id,
chat_type="group",
raw={"source": source},
)
class GroupBotStateTests(unittest.TestCase):
def test_mark_seeds_active_then_clear_only_breaks_active(self) -> None:
chat = "wr_bot_state_1"
mark_group_bot(chat, "SEA", "WO202611190001")
self.assertTrue(is_group_bot(chat))
self.assertEqual(get_active_work_order(chat), "WO202611190001")
clear_active_work_order(chat)
# BOT 接管标记保留;只断开当前单关联。
self.assertTrue(is_group_bot(chat))
self.assertEqual(get_active_work_order(chat), "")
class GroupBotDispatchTests(unittest.TestCase):
def test_non_at_archive_text_breaks_active_and_does_not_reply(self) -> None:
chat = "wr_bot_dispatch_1"
mark_group_bot(chat, "SEA", "WO202611190001")
with patch("agent.routing.dispatch.handle_group_collab") as handler:
result = dispatch_inbound(
_msg(chat_id=chat, content="大家看一下这个", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_unbound_ignore")
self.assertFalse(handler.called)
self.assertEqual(get_active_work_order(chat), "")
def test_dissolve_without_at_still_goes_to_group_handler(self) -> None:
"""产品口径:解散群不要求 @BOT;存档听见「解散群」就走解散。"""
chat = "wr_bot_dispatch_dissolve"
mark_group_bot(chat, "SEA", "WO202611190099")
with patch(
"agent.routing.dispatch.handle_group_collab", return_value="group_dissolved"
) as handler:
result = dispatch_inbound(
_msg(chat_id=chat, content="解散群", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_collab")
self.assertTrue(handler.called)
def test_at_without_active_work_order_sends_one_sentence_prompt(self) -> None:
chat = "wr_bot_dispatch_2"
mark_group_bot(chat, "SEA", "WO202611190001")
clear_active_work_order(chat)
sent: list[tuple[str, str]] = []
def fake_send(self, *, chat_id, content, mention_userids=None):
sent.append((chat_id, content))
return {"ok": True}
with patch(
"agent.channel.aibot.reply.AibotReplyClient.send_group", fake_send
), patch("agent.routing.dispatch.handle_group_collab") as handler:
result = dispatch_inbound(
_msg(chat_id=chat, content="帮我报个价", source="aibot"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_need_work_order")
self.assertFalse(handler.called)
self.assertEqual(sent, [(chat, copy.air_need_work_order())])
# 产品口径:只教一种写法。
self.assertIn("已成交WO****@", sent[0][1])
self.assertNotIn("WO****已成交@", sent[0][1])
def test_at_with_active_work_order_goes_to_group_handler(self) -> None:
chat = "wr_bot_dispatch_3"
mark_group_bot(chat, "SEA", "WO202611190001")
with patch(
"agent.routing.dispatch.handle_group_collab", return_value="group_done"
) as handler:
result = dispatch_inbound(
_msg(chat_id=chat, content="成交", source="aibot"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_collab")
self.assertTrue(handler.called)
def test_at_with_work_order_restores_active_and_goes_to_handler(self) -> None:
chat = "wr_bot_dispatch_4"
mark_group_bot(chat, "SEA", "WO202611190001")
clear_active_work_order(chat)
with patch(
"agent.routing.dispatch.handle_group_collab", return_value="group_done"
) as handler:
result = dispatch_inbound(
_msg(chat_id=chat, content="WO202611190001 成交", source="aibot"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_collab")
self.assertTrue(handler.called)
self.assertEqual(get_active_work_order(chat), "WO202611190001")
def test_archive_at_text_is_left_to_bot_to_avoid_double_reply(self) -> None:
chat = "wr_bot_dispatch_5"
mark_group_bot(chat, "SEA", "WO202611190001")
with patch("agent.routing.dispatch.handle_group_collab") as handler:
result = dispatch_inbound(
_msg(
chat_id=chat,
content="@智报通AIQ 成交",
source="wshoto_archive",
),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_at_archive_ignore")
self.assertFalse(handler.called)
def test_archive_file_without_at_window_is_silent(self) -> None:
"""产品口径(2026-11-21):没有 @BOT 窗口的群附件一律静默,不识别不建单。"""
chat = "wr_bot_dispatch_6"
mark_group_bot(chat, "SEA", "WO202611190001")
clear_at_burst(chat)
with patch("agent.routing.dispatch.handle_group_collab") as handler:
result = dispatch_inbound(
_msg(
chat_id=chat,
content="产品报价.pdf",
msg_type="file",
source="wshoto_archive",
),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_media_no_at_ignore")
self.assertFalse(handler.called)
def test_archive_file_in_at_window_handled_with_bot_client(self) -> None:
"""@BOT 之后到下一句普通文字之前:附件算这次指令的材料,照旧交给 handler。"""
chat = "wr_bot_dispatch_6b"
mark_group_bot(chat, "SEA", "WO202611190001")
mark_at_burst(chat)
captured: dict[str, object] = {}
def fake_handler(message):
from agent.policy.sea_group_ops import _outbound_client
captured["client"] = _outbound_client.get()
return "file_done"
with patch("agent.routing.dispatch.handle_group_collab", fake_handler):
result = dispatch_inbound(
_msg(
chat_id=chat,
content="产品报价.pdf",
msg_type="file",
source="wshoto_archive",
),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_collab")
self.assertIsNotNone(captured.get("client"))
def test_plain_archive_text_closes_at_window(self) -> None:
"""窗口边界:@ 之后遇到普通文字就结束,后面的附件必须重新 @BOT。"""
chat = "wr_bot_dispatch_8"
mark_group_bot(chat, "SEA", "WO202611190001")
mark_at_burst(chat)
self.assertTrue(in_at_burst(chat))
dispatch_inbound(
_msg(chat_id=chat, content="这个价格我晚点确认", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertFalse(in_at_burst(chat))
def test_archive_image_in_at_window_goes_to_handler(self) -> None:
"""窗口内图片:交给 handler 按附件口径回应,不再整条吞掉。"""
chat = "wr_bot_dispatch_9"
mark_group_bot(chat, "SEA", "WO202611190001")
mark_at_burst(chat)
with patch(
"agent.routing.dispatch.handle_group_collab", return_value="image_done"
) as handler:
result = dispatch_inbound(
_msg(chat_id=chat, msg_type="image", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_collab")
self.assertTrue(handler.called)
def test_archive_image_without_at_window_is_silent(self) -> None:
chat = "wr_bot_dispatch_10"
mark_group_bot(chat, "SEA", "WO202611190001")
clear_at_burst(chat)
with patch("agent.routing.dispatch.handle_group_collab") as handler:
result = dispatch_inbound(
_msg(chat_id=chat, msg_type="image", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_archive_media_ignore")
self.assertFalse(handler.called)
def test_file_then_bare_seat_at_replays_attachment(self) -> None:
"""真机口径(2026-11-21):「先发 Excel、再 @会话存档机器人」也算这次指令。"""
chat = "wr_bot_dispatch_11"
mark_group_bot(chat, "SEA", "WO202611190001")
clear_at_burst(chat)
with patch(
"agent.routing.dispatch.handle_group_collab", return_value="file_done"
) as handler:
first = dispatch_inbound(
_msg(chat_id=chat, msg_type="file", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(first, "group_media_no_at_ignore")
self.assertFalse(handler.called)
second = dispatch_inbound(
_msg(chat_id=chat, content="@会话存档机器人", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
# 附件在 @ 到来时被补办一次;@ 本身只有账号名,不额外回话。
self.assertEqual(second, "seat_at_empty_ignore")
self.assertEqual(handler.call_count, 1)
replayed = handler.call_args[0][0]
self.assertEqual(replayed.msg_type, "file")
def test_pending_attachment_dropped_when_plain_text_ends_burst(self) -> None:
"""普通文字结束这次指令后,之前没被 @ 认领的附件不能再翻出来重放。"""
chat = "wr_bot_dispatch_12"
mark_group_bot(chat, "SEA", "WO202611190001")
clear_at_burst(chat)
with patch("agent.routing.dispatch.handle_group_collab") as handler:
dispatch_inbound(
_msg(chat_id=chat, msg_type="file", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
dispatch_inbound(
_msg(chat_id=chat, content="这个价格我晚点确认", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
result = dispatch_inbound(
_msg(chat_id=chat, content="@会话存档机器人", source="wshoto_archive"),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "seat_at_empty_ignore")
self.assertFalse(handler.called)
def test_app_source_in_bot_group_is_silent(self) -> None:
chat = "wr_bot_dispatch_7"
mark_group_bot(chat, "SEA", "WO202611190001")
with patch("agent.routing.dispatch.handle_group_collab") as handler:
result = dispatch_inbound(
_msg(chat_id=chat, content="成交", source=""),
RouteDecision(intent="ordinary_text_other"),
)
self.assertEqual(result, "group_non_bot_ignore")
self.assertFalse(handler.called)
if __name__ == "__main__":
unittest.main()
+6 -7
View File
@@ -101,7 +101,9 @@ class HandoffCoreTests(unittest.TestCase):
self.assertIn("WO202609190018转人工", text)
self.assertNotIn("工单号:", text.split("转人工")[0][-6:])
self.assertIn("货物品名:-", text)
self.assertIn("客户名称:-", text)
# 客户名称已改询价阶段,不在转人工协同兜底里。
self.assertNotIn("客户名称:-", text)
self.assertIn("海关编码:-", text)
self.assertNotIn("TMS报价", text)
def test_already_collab_copy(self) -> None:
@@ -203,12 +205,9 @@ class HandoffFlowOfferTests(unittest.TestCase):
self.assertNotIn(copy.BTN_PULL_COLLAB, joined)
self.assertTrue(self.groups.created)
self.assertTrue(self.groups.created[0]["name"].startswith("WO"))
brief = self.groups.sent[0]["content"]
self.assertIn("转人工", brief)
# 业务类型/报价场景只有陆运卡才有,海运摘要里出现这两行产品会以为漏填。
self.assertNotIn("业务类型:", brief)
self.assertNotIn("报价场景:", brief)
self.assertNotIn("TMS报价", brief)
# 产品口径(2026-11-20):建群后立即发字段摘要;不自动推空白表。
texts = [x.get("content") or "" for x in self.groups.sent]
self.assertTrue(any("询价字段" in t or "转人工" in t for t in texts))
sess = self.flow.session_of("s1")
self.assertTrue(sess.handoff_committed)
self.assertEqual(sess.collab_mode, "handoff")
+29 -14
View File
@@ -338,9 +338,11 @@ class HandoffLandFlowTests(unittest.TestCase):
# 不再出选卡:只应有文字回执,没有任何 template_card。
self.assertEqual(out.payloads, [], msg="已选业务类型/报价场景时不能再弹选卡")
self.assertEqual(len(self.groups.created), 1, msg="应直接建群")
brief = self.groups.sent[0]["content"]
self.assertIn("业务类型:国内整车", brief)
self.assertIn("报价场景:普件(常用线路)", brief)
# 建群后立即发字段摘要;业务类型/报价场景写进会话事实和工单。
texts = [x.get("content") or "" for x in self.groups.sent]
self.assertTrue(any("询价字段" in t or "转人工" in t for t in texts))
self.assertEqual(sess.facts.get("陆运业务类型"), "国内整车")
self.assertEqual(sess.facts.get("报价场景"), "普件(常用线路)")
def test_offer_handoff_skips_card_after_ticket_created(self) -> None:
"""
@@ -475,15 +477,15 @@ class HandoffLandFlowTests(unittest.TestCase):
# 只拉城配线路的产品(马涛),不拉中港(陈柏成)。
self.assertIn("land_prod_1", self.groups.created[0]["userids"])
self.assertNotIn("land_prod_2", self.groups.created[0]["userids"])
brief = self.groups.sent[0]["content"]
self.assertIn("业务类型:国内城配/打包", brief)
self.assertIn("报价场景:普件(涉及中欧、中亚)", brief)
self.assertIn("报价时效:24小时", brief)
# 建群不自动推空白模板:报价单要群里说「生成报价单」才出。
# 建群后立即发字段摘要;不自动推空白模板。
texts = [x.get("content") or "" for x in self.groups.sent]
self.assertTrue(any("询价字段" in t or "转人工" in t for t in texts))
self.assertEqual(self.groups.files, [])
self.assertNotIn("空白报价模板", out.joined)
self.assertIn("生成报价单", out.joined)
sess = self.flow.session_of("s1")
self.assertEqual(sess.facts.get("陆运业务类型"), "国内城配/打包")
self.assertEqual(sess.facts.get("报价场景"), "普件(涉及中欧、中亚)")
self.assertTrue(sess.handoff_committed)
self.assertEqual(sess.collab_mode, "handoff")
self.assertEqual(sess.facts.get("运输类型"), "国内运输整车")
@@ -517,9 +519,12 @@ class HandoffLandFlowTests(unittest.TestCase):
phase = self.flow.on_text(sender_id="s1", text="1 3", reply=out)
self.assertEqual(phase, "handoff_done")
self.assertEqual(len(self.groups.created), 1)
brief = self.groups.sent[0]["content"]
self.assertIn("业务类型:国内整车", brief)
self.assertIn("报价场景:普件(涉及中欧、中亚)", brief)
# 建群后立即发字段摘要;业务类型/报价场景写进会话事实和工单。
texts = [x.get("content") or "" for x in self.groups.sent]
self.assertTrue(any("询价字段" in t or "转人工" in t for t in texts))
sess = self.flow.session_of("s1")
self.assertEqual(sess.facts.get("陆运业务类型"), "国内整车")
self.assertEqual(sess.facts.get("报价场景"), "普件(涉及中欧、中亚)")
def test_resubmit_does_not_create_second_group(self) -> None:
self._start()
@@ -667,8 +672,14 @@ class LandCardTimeoutAndTemplateTests(unittest.TestCase):
can_request_quote_sheet(flow=None, ticket=snake, sender_id="land_prod_2")
)
def test_ondemand_sheet_still_blocks_product_in_auto_group(self) -> None:
"""自动协同群口径不变:产品只能说价,出表仍要销售/商务/航线喊。"""
def test_ondemand_sheet_open_to_any_group_member(self) -> None:
"""
2026-11-22 产品口径:群内任何成员都能要报价单,产品不再被拦。
为什么改:真机里产品在协同群要 PDF 报价单,被回「只有销售、商务或航线
可以说」;产品本来就是看价、对价的人,要表不该看岗位。非群成员仍由
group_collab 入口的 _sender_allowed 先拦,不归本函数管。
"""
from agent.policy.group_quote_sheet import can_request_quote_sheet
auto = {
@@ -677,12 +688,16 @@ class LandCardTimeoutAndTemplateTests(unittest.TestCase):
"collab_mode": "auto",
"collab_member_ids": ["sales1", "prod1"],
}
self.assertFalse(
# 产品、销售都能要表;没有发送人(私聊/系统事件)仍不放行。
self.assertTrue(
can_request_quote_sheet(flow=None, ticket=auto, sender_id="prod1")
)
self.assertTrue(
can_request_quote_sheet(flow=None, ticket=auto, sender_id="sales1")
)
self.assertFalse(
can_request_quote_sheet(flow=None, ticket=auto, sender_id=" ")
)
class CardRoutingTests(unittest.TestCase):
@@ -26,15 +26,15 @@ from agent.schema.field_validate import (
class LandCollabFieldsTest(unittest.TestCase):
def test_domestic_ltl_keys(self):
keys = land_collab_fields("国内运输拼车", "国内长途/零担")
self.assertEqual(keys, ("客户名称", "包装方式", "货值", "是否为危险品"))
self.assertEqual(keys, ("包装方式", "货值", "是否为危险品"))
def test_domestic_ftl_longhaul_keys(self):
keys = land_collab_fields("国内运输整车", "国内长途/零担")
self.assertEqual(keys, ("客户名称", "货值", "包装方式", "是否为危险品"))
self.assertEqual(keys, ("货值", "包装方式", "是否为危险品"))
def test_domestic_ftl_order(self):
keys = land_collab_fields("国内运输整车", "国内城配/拖车/打包")
self.assertEqual(keys, ("客户名称", "货值", "包装方式", "是否为危险品"))
self.assertEqual(keys, ("货值", "包装方式", "是否为危险品"))
def test_cross_ftl_no_vehicle(self):
keys = land_collab_fields("跨境整车", "东南亚")
@@ -42,10 +42,11 @@ class LandCollabFieldsTest(unittest.TestCase):
self.assertNotIn("车型/数量", keys)
def test_hk_ftl_vehicle_is_inquiry_not_collab(self):
"""中港整车车型/数量已改到询价必填,协同不再要。"""
"""中港整车车型/数量已改到询价必填,协同不再要;客户名称也改到询价。"""
keys = land_collab_fields("中港整车", "中港/中亚/中欧")
self.assertNotIn("车型/数量", keys)
self.assertEqual(keys[0], "客户名称")
self.assertNotIn("客户名称", keys)
self.assertEqual(keys[0], "HS编码")
self.assertIn("HS编码", keys)
def test_unlisted_pair_empty(self):
@@ -77,12 +78,13 @@ class LandCollabFieldsTest(unittest.TestCase):
self.assertEqual(harvest_oral_collab("不是危险品")["是否为危险品"], "否")
def test_labeled_without_colon(self):
"""客户名称已改询价阶段,群协同不再收;剩下包装/货值照常。"""
allowed = land_collab_fields("国内运输拼车", "国内长途/零担")
got = extract_collab_fields(
"客户名称张三 包装方式编织袋 货值 10万",
allowed_keys=allowed,
)
self.assertEqual(got.get("客户名称"), "张三")
self.assertNotIn("客户名称", got)
self.assertEqual(got.get("包装方式"), "编织袋")
self.assertEqual(got.get("货值"), "10万")
@@ -93,7 +95,7 @@ class LandCollabFieldsTest(unittest.TestCase):
def test_trade_terms_filtered_for_ltl(self):
allowed = land_collab_fields("国内运输拼车", "国内长途/零担")
got = extract_collab_fields("客户名称张三,贸易条款 FOB", allowed_keys=allowed)
self.assertEqual(got, {"客户名称": "张三"})
self.assertEqual(got, {})
def test_sea_labeled_still_works(self):
got = extract_collab_fields("贸易条款:FOB")
+82 -21
View File
@@ -53,7 +53,7 @@ class LandCopyTest(unittest.TestCase):
)
self.assertIn("通关口岸(非必填):", text)
def test_hk_lcl_hides_vehicle_not_load_field(self):
def test_hk_lcl_shows_volume_weight_not_vehicle(self):
text = copy.land_confirm_card(
{
"运输类型": "中港零担/集拼",
@@ -62,11 +62,16 @@ class LandCopyTest(unittest.TestCase):
"起运港": "广州",
"目的港": "香港",
"品名": "衣服",
"体积": "20CBM",
"毛重": "3000KG",
"车型/数量": "9米6/1",
"报价日期": "2026-09-17",
}
)
self.assertIn("运输类型(必填):中港零担/集拼", text)
# 中港集拼按体积+毛重计费(与跨境集拼一致),不展示车型/数量。
self.assertIn("体积(CBM)(必填):20CBM", text)
self.assertIn("重量(KG)(必填):3000KG", text)
self.assertNotIn("车型/数量", text)
self.assertNotIn("中港装载方式", text)
self.assertIn("通关口岸(非必填)", text)
@@ -205,28 +210,38 @@ class LandCopyTest(unittest.TestCase):
self.assertIn("1.体积(CBM)(必填)", pending)
def test_inquiry_card_lists_land_fields_and_wo(self):
facts = {
"运输类型": "国内运输拼车",
"线路类别": "国内长途/零担",
"运输分类": "急件",
"起运港": "广州",
"目的港": "深圳",
"品名": "衣服",
"体积": "100CBM",
"毛重": "50kg",
"报价日期": "2026-09-17",
}
text = copy.inquiry_card(
work_order_no="WO202609170006",
facts={
"运输类型": "国内运输拼车",
"线路类别": "国内长途/零担",
"运输分类": "急件",
"起运港": "广州",
"目的港": "深圳",
"品名": "衣服",
"体积": "100CBM",
"毛重": "50kg",
"报价日期": "2026-09-17",
},
facts=facts,
transport_mode="陆运",
)
self.assertIn("工单号:WO202609170006", text)
self.assertIn("运输方式:陆运", text)
self.assertIn("运输类型:国内运输拼车", text)
self.assertIn("始发站:广州", text)
self.assertIn("货物品名:衣服", text)
self.assertIn("工单已创建,正在查询TMS报价。", text)
self.assertNotIn("件数", text)
# 产品口径 2026-11-22:确定后只保留工单号 + 正在查询TMS报价,字段段不重复。
self.assertEqual(
text,
"工单号:WO202609170006\n工单已创建,正在查询TMS报价。",
)
# 陆运字段展示仍在核对卡 / 拉群摘要这条链路上(inquiry_field_lines)。
fields = "\n".join(
copy.inquiry_field_lines(
work_order_no="WO202609170006", facts=facts, transport_mode="陆运"
)
)
self.assertIn("运输方式:陆运", fields)
self.assertIn("运输类型:国内运输拼车", fields)
self.assertIn("始发站:广州", fields)
self.assertIn("货物品名:衣服", fields)
self.assertNotIn("件数", fields)
def test_scheme_card_uses_land_fields_not_sea(self):
facts = {
@@ -321,7 +336,8 @@ class LandCopyTest(unittest.TestCase):
transport_mode="陆运",
)
self.assertIn("包装方式:纸箱", text)
self.assertIn("客户名称:-", text)
# 客户名称已改到询价阶段(非必填),协同段不再出现。
self.assertNotIn("客户名称", text)
self.assertIn("货值:-", text)
self.assertIn("是否为危险品:-", text)
self.assertNotIn("贸易条款", text)
@@ -349,10 +365,55 @@ class LandCopyTest(unittest.TestCase):
transport_mode="陆运",
)
collab = text.split("协同补充字段")[1]
self.assertLess(collab.find("客户名称"), collab.find("货值"))
self.assertNotIn("客户名称", collab)
self.assertLess(collab.find("货值"), collab.find("包装方式"))
self.assertLess(collab.find("包装方式"), collab.find("是否为危险品"))
self.assertNotIn("贸易条款", text)
def test_hk_lcl_brief_collab_same_as_cross_border_lcl(self):
"""中港集拼群摘要:协同项与跨境集拼一致,询价字段带体积/重量、不带车型。"""
text = copy.sea_group_brief(
work_order_no="WO3",
facts={
"运输类型": "中港零担/集拼",
"线路类别": "中港/中亚/中欧",
"运输分类": "普件(东南亚、中港常用线路/常规车型)",
"起运港": "广州",
"目的港": "香港",
"品名": "衣服",
"体积": "20CBM",
"毛重": "3000KG",
"报价日期": "2026-09-18",
"客户名称": "华为",
},
quote=None,
collab_facts={},
sales_name="销",
product_names=["产"],
has_price=False,
transport_mode="陆运",
)
inquiry = text.split("协同补充字段")[0]
self.assertIn("体积(CBM):20CBM", inquiry)
self.assertIn("重量(KG):3000KG", inquiry)
# 客户名称进询价字段,不再进协同段。
self.assertIn("客户名称:华为", inquiry)
self.assertNotIn("车型/数量", inquiry)
collab = text.split("协同补充字段")[1]
for label in ("海关编码:-", "贸易条款:-", "包装方式:-", "是否为危险品:-"):
self.assertIn(label, collab)
self.assertNotIn("客户名称", collab)
# 与跨境集拼同一套:只这五项,不能多出海运的含油/含电/含磁。
self.assertNotIn("是否含油", collab)
self.assertNotIn("是否含电", collab)
self.assertNotIn("是否含磁", collab)
from agent.schema.field_validate import land_collab_fields
self.assertEqual(
land_collab_fields("中港零担/集拼", "中港/中亚/中欧"),
land_collab_fields("跨境集拼", "中港/中亚/中欧"),
)
def test_land_unrecognized_lists_keys(self):
keys = ("客户名称", "包装方式", "货值", "是否为危险品")
text = copy.group_fields_not_recognized(keys=keys, business_line="LAND")
@@ -31,9 +31,9 @@ class LandFieldValidateTest(unittest.TestCase):
self.assertFalse(got["ok"])
self.assertIn("体积", got["missing"])
def test_hk_lcl_skips_vehicle(self):
"""中港零担/集拼:询价不要车型/数量。"""
got = validate_required_fields(
def test_hk_lcl_requires_volume_weight_not_vehicle(self):
"""中港零担/集拼(中港集拼):必填体积+毛重,不要求车型/数量。"""
missing = validate_required_fields(
facts={
"起运港": "广州",
"目的港": "香港",
@@ -42,10 +42,25 @@ class LandFieldValidateTest(unittest.TestCase):
business_line="LAND",
land_subtype="中港零担/集拼",
)
self.assertFalse(missing["ok"])
self.assertIn("体积", missing["missing"])
self.assertIn("毛重", missing["missing"])
self.assertNotIn("车型/数量", missing["missing"])
got = validate_required_fields(
facts={
"起运港": "广州",
"目的港": "香港",
"品名": "衣服",
"体积": "20CBM",
"毛重": "3000KG",
},
business_line="LAND",
land_subtype="中港零担/集拼",
)
self.assertTrue(got["ok"])
self.assertNotIn("车型/数量", got["missing"])
self.assertNotIn("体积", got["missing"])
self.assertNotIn("毛重", got["missing"])
self.assertEqual(got["facts"]["体积"], "20CBM")
self.assertEqual(got["facts"]["毛重"], "3000KG")
def test_hk_full_truck_requires_vehicle(self):
"""中港整车:询价必填车型/数量。"""
+34 -13
View File
@@ -97,6 +97,18 @@ class LandGroupCollabTests(unittest.TestCase):
def _group_texts(self) -> str:
return "\n".join(x.get("content") or "" for x in self.groups.sent if x.get("kind") == "text")
def _resend_brief(self, wo: str) -> None:
"""再发一版字段摘要(不发表);建群时已自动发过,单测复测报价改写时用。"""
from agent.policy.sea_group_ops import send_brief_and_sheet
ticket = self.ledger.get_ticket(work_order_no=wo)
send_brief_and_sheet(
flow=self.flow,
ticket=ticket,
sess=self.flow.session_of("u1"),
include_sheet=False,
)
def _open(
self,
*,
@@ -142,13 +154,15 @@ class LandGroupCollabTests(unittest.TestCase):
)
def test_ltl_brief_only_four_collab_and_prefill_pack(self) -> None:
self._open(
wo, _ = self._open(
option_text="国内运输拼车 国内长途/零担 急件 包装方式纸箱",
extra_facts={"包装方式": "纸箱"},
)
self._resend_brief(wo)
brief = self._group_texts()
self.assertIn("包装方式:纸箱", brief)
self.assertIn("客户名称:-", brief)
# 客户名称已改询价阶段(非必填),协同段不再出现。
self.assertNotIn("客户名称:-", brief)
self.assertIn("货值:-", brief)
self.assertIn("是否为危险品:-", brief)
self.assertNotIn("贸易条款", brief)
@@ -156,19 +170,20 @@ class LandGroupCollabTests(unittest.TestCase):
self.assertNotIn("海关编码", brief)
def test_domestic_ftl_longhaul_can_pull_and_brief_order(self) -> None:
"""国内整车配长途:允许拉群;协同顺序是客户名称、货值、包装方式、是否为危险品。"""
self._open(
"""国内整车配长途:允许拉群;协同顺序是货值、包装方式、是否为危险品。"""
wo, _ = self._open(
option_text="国内运输整车 国内长途/零担 急件",
cargo={"车型/数量": "9米/1"},
)
self.assertTrue(self.groups.created)
self._resend_brief(wo)
brief = self._group_texts()
collab_part = brief.split("协同补充字段")[1]
self.assertIn("客户名称:-", collab_part)
# 只看第一段协同块,避免把后面重发摘要的询价字段算进来。
collab_part = brief.split("协同补充字段")[1].split("\n\n")[0]
self.assertNotIn("客户名称", collab_part)
self.assertIn("货值:-", collab_part)
self.assertIn("包装方式:-", collab_part)
self.assertIn("是否为危险品:-", collab_part)
self.assertLess(collab_part.find("客户名称"), collab_part.find("货值"))
self.assertLess(collab_part.find("货值"), collab_part.find("包装方式"))
self.assertLess(collab_part.find("包装方式"), collab_part.find("是否为危险品"))
self.assertNotIn("贸易条款", brief)
@@ -185,9 +200,12 @@ class LandGroupCollabTests(unittest.TestCase):
"车型/数量": "9米/1",
},
)
self._resend_brief(wo)
brief = self._group_texts()
self.assertIn("车型/数量:9米/1", brief.split("协同补充字段")[0])
self.assertNotIn("车型/数量", brief.split("协同补充字段")[1])
# 只看第一段协同块:后面重发的摘要会把询价字段的车型带进整串。
collab_part = brief.split("协同补充字段")[1].split("\n\n")[0]
self.assertNotIn("车型/数量", collab_part)
self.groups.sent.clear()
phase = handle_group_collab(
self._msg(sender="u1", text="车型/数量 12米/1", mid="v1"),
@@ -210,6 +228,7 @@ class LandGroupCollabTests(unittest.TestCase):
option_text="中港整车 中港/中亚/中欧 急件",
cargo={"目的港": "香港", "车型/数量": "13米/1"},
)
self._resend_brief(wo)
self.assertIn("车型/数量:13米/1", self._group_texts())
self.groups.sent.clear()
phase = handle_group_collab(
@@ -233,10 +252,13 @@ class LandGroupCollabTests(unittest.TestCase):
)
self.assertEqual(phase, "collab_not_recognized")
text = self._group_texts()
self.assertIn("客户名称", text)
self.assertIn("包装方式", text)
self.assertNotIn("货好时间", text)
# 客户名称已改询价阶段,不在这张协同提示里。
self.assertNotIn("客户名称", text)
def test_ltl_keeps_name_drops_trade_terms(self) -> None:
def test_ltl_customer_name_not_saved_as_collab(self) -> None:
"""客户名称改询价后,群里再写不再进协同快照。"""
wo, _ = self._open(option_text="国内运输拼车 国内长途/零担 急件")
self.groups.sent.clear()
phase = handle_group_collab(
@@ -245,11 +267,10 @@ class LandGroupCollabTests(unittest.TestCase):
ledger=self.ledger,
injected_intent=INTENT_FIELDS,
)
self.assertEqual(phase, "collab_field_saved")
self.assertEqual(phase, "collab_not_recognized")
ticket = self.ledger.get_ticket(work_order_no=wo)
self.assertEqual(ticket.collab_facts.get("客户名称"), "张三")
self.assertNotIn("客户名称", ticket.collab_facts or {})
self.assertFalse(ticket.collab_facts.get("贸易条款"))
self.assertIn("客户名称:张三", self._group_texts())
def test_dg_and_value_and_bare_pack(self) -> None:
wo, _ = self._open(option_text="国内运输拼车 国内长途/零担 急件")
@@ -0,0 +1,277 @@
"""
陆运报价附加条件回归:未含税 / 含0税 / 未含燃油 / 含燃油费。
产品 2026-11-22 口径:
1. 未含税N%:税率 N%,运输费不动,备注「未含税N%」;
2. 未含税:税率空,运输费不动,备注空;
3. 含0税:税率 0,运输费不动,备注「含0税」;
4. 未含燃油N%:燃油费率 N%,主运费 ×(1+N%),备注「未含燃油N%」;
5. 含燃油费N%:燃油费率 N%,主运费不乘,备注「含燃油费N%」。
涉及模板:跨境整车、跨境集拼、国内整车、国内拼车、中港集拼。
本文件只测解析/挂段/摘要,不连企微、TMS、主账。
"""
from __future__ import annotations
import os
import sys
import unittest
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
os.environ.setdefault("YTD_ENV", "test")
os.environ.setdefault("REDIS_BACKEND", "memory")
os.environ.setdefault("CHECKPOINT_BACKEND", "memory")
os.environ.setdefault("MESSAGE_STORE_BACKEND", "memory")
os.environ.setdefault("LLM_DATA_USAGE_CONFIRMED", "false")
os.environ.setdefault("LLM_ALLOW_NETWORK", "false")
os.environ.setdefault("LEDGER_BACKEND", "memory")
from agent.llm.extract_text import extract_product_quote
from agent.policy.inquiry_copy import _manual_land_vehicle_lines, _manual_quote_lines
from agent.policy.sea_group_ops import (
_attach_land_vehicle_rates_segment,
_attach_land_weight_band_segment,
)
from agent.schema.land_quote_condition import (
FUEL_EXCLUDED,
FUEL_INCLUDED,
UNTAXED_BLANK,
UNTAXED_RATE,
ZERO_TAX,
parse_land_quote_condition,
strip_land_quote_condition,
)
LAND = dict(business_line="LAND", transport_mode="陆运")
class ParseConditionTest(unittest.TestCase):
"""五句口语条件必须各归各的代码。"""
def test_fuel_excluded(self) -> None:
cond = parse_land_quote_condition("运输费USD3200,未含燃油13%")
self.assertIsNotNone(cond)
self.assertEqual(cond.code, FUEL_EXCLUDED)
self.assertEqual(cond.fuel_rate, "13%")
self.assertEqual(cond.remark, "未含燃油13%")
self.assertTrue(cond.multiply_fuel)
def test_fuel_excluded_with_full_width(self) -> None:
cond = parse_land_quote_condition("运输费USD3200,未含燃油13%")
self.assertIsNotNone(cond)
self.assertEqual(cond.fuel_rate, "13%")
def test_fuel_included(self) -> None:
cond = parse_land_quote_condition("运输费12000,含燃油费13%")
self.assertIsNotNone(cond)
self.assertEqual(cond.code, FUEL_INCLUDED)
self.assertEqual(cond.fuel_rate, "13%")
self.assertEqual(cond.remark, "含燃油费13%")
self.assertFalse(cond.multiply_fuel)
def test_untaxed_rate(self) -> None:
cond = parse_land_quote_condition("运输费12000,未含税13%")
self.assertIsNotNone(cond)
self.assertEqual(cond.code, UNTAXED_RATE)
self.assertEqual(cond.tax_rate, "13%")
self.assertEqual(cond.remark, "未含税13%")
self.assertFalse(cond.multiply_fuel)
def test_untaxed_blank(self) -> None:
cond = parse_land_quote_condition("运输费12000,未含税")
self.assertIsNotNone(cond)
self.assertEqual(cond.code, UNTAXED_BLANK)
self.assertEqual(cond.tax_rate, "")
self.assertEqual(cond.remark, "")
def test_zero_tax(self) -> None:
cond = parse_land_quote_condition("运输费12000,含0税")
self.assertIsNotNone(cond)
self.assertEqual(cond.code, ZERO_TAX)
self.assertEqual(cond.tax_rate, "0")
self.assertEqual(cond.remark, "含0税")
def test_strip_removes_token(self) -> None:
stripped = strip_land_quote_condition("运输费12000,含燃油费13%")
self.assertNotIn("含燃油费", stripped)
self.assertNotIn("13", stripped)
self.assertIn("运输费12000", stripped)
def test_tax_and_fuel_can_coexist(self) -> None:
# 产品一句里同时写税和燃油:两项都要出单,不能只取后出现的一项。
cond = parse_land_quote_condition("运输费3200,未含税13%,未含燃油5%")
self.assertIsNotNone(cond)
self.assertEqual(cond.tax_rate, "13%")
self.assertEqual(cond.fuel_rate, "5%")
self.assertEqual(cond.remark, "未含税13%;未含燃油5%")
self.assertTrue(cond.multiply_fuel)
class ExtractLandConditionTest(unittest.TestCase):
"""条件进报价对象:税率/燃油/备注正确,只有未含燃油乘主运费。"""
def test_fuel_excluded_multiplies_transport(self) -> None:
quote = extract_product_quote("运输费USD3200,未含燃油13%", **LAND)
self.assertEqual(quote["fee_rows"][0]["name"], "运输费")
self.assertEqual(quote["fee_rows"][0]["amount"], "3616")
self.assertEqual(quote["total"], "3616")
self.assertEqual(quote["fuel_surcharge_rate"], "13%")
self.assertEqual(quote["remark"], "未含燃油13%")
self.assertEqual(quote["fee_rows"][0]["remark"], "未含燃油13%")
def test_fuel_included_keeps_transport(self) -> None:
quote = extract_product_quote("运输费12000,含燃油费13%", **LAND)
self.assertEqual(quote["fee_rows"][0]["amount"], "12000")
self.assertEqual(float(quote["total"]), 12000.0)
self.assertEqual(quote["fuel_surcharge_rate"], "13%")
self.assertEqual(quote["remark"], "含燃油费13%")
def test_untaxed_rate_keeps_transport(self) -> None:
quote = extract_product_quote("运输费12000,未含税13%", **LAND)
self.assertEqual(quote["fee_rows"][0]["amount"], "12000")
self.assertEqual(quote["tax_rate"], "13%")
self.assertEqual(quote["remark"], "未含税13%")
self.assertNotIn("fuel_surcharge_rate", quote)
def test_untaxed_blank_leaves_tax_empty(self) -> None:
quote = extract_product_quote("运输费12000,未含税", **LAND)
self.assertEqual(quote["fee_rows"][0]["amount"], "12000")
self.assertNotIn("tax_rate", quote)
self.assertNotIn("remark", quote)
def test_zero_tax(self) -> None:
quote = extract_product_quote("运输费12000,含0税", **LAND)
self.assertEqual(quote["fee_rows"][0]["amount"], "12000")
self.assertEqual(quote["tax_rate"], "0")
self.assertEqual(quote["remark"], "含0税")
def test_fuel_multiplies_only_main_transport_rows(self) -> None:
quote = extract_product_quote(
"运输费1000USD,提货费200USD,报关费100USD,未含燃油10%", **LAND
)
amounts = {row["name"]: row["amount"] for row in quote["fee_rows"]}
self.assertEqual(amounts.get("运输费"), "1100")
self.assertEqual(amounts.get("提货费"), "200")
self.assertEqual(amounts.get("报关费"), "100")
self.assertEqual(quote["total"], "1400")
def test_remark_goes_to_main_transport_row(self) -> None:
# 跨境整车无 landSegments 时,主账用运输费行拼路线行;备注必须在运输费行。
quote = extract_product_quote(
"提货费200USD,运输费1000USD,未含燃油10%", **LAND
)
rows = {row["name"]: row for row in quote["fee_rows"]}
self.assertEqual(rows["运输费"]["amount"], "1100")
self.assertEqual(rows["运输费"]["remark"], "未含燃油10%")
self.assertNotIn("remark", rows["提货费"])
def test_tax_and_fuel_combined_applies_both(self) -> None:
quote = extract_product_quote(
"运输费1000USD,未含税13%,未含燃油5%", **LAND
)
self.assertEqual(quote["fee_rows"][0]["amount"], "1050")
self.assertEqual(quote["total"], "1050")
self.assertEqual(quote["tax_rate"], "13%")
self.assertEqual(quote["fuel_surcharge_rate"], "5%")
self.assertEqual(quote["remark"], "未含税13%;未含燃油5%")
def test_mixed_currency_total_not_corrupted(self) -> None:
# 合计只统计主币种小计;异币种主运费不能把增量加进 USD 合计。
quote = extract_product_quote(
"运输费1000USD,报关费100CNY,未含燃油10%", **LAND
)
amounts = {row["name"]: row["amount"] for row in quote["fee_rows"]}
self.assertEqual(amounts.get("运输费"), "1100")
self.assertEqual(amounts.get("报关费"), "100")
self.assertEqual(quote["total"], "1100")
def test_fuel_multiplies_vehicle_rates(self) -> None:
quote = extract_product_quote(
"东莞-春疆,7.6米CNY13000元;9.6米CNY14000;未含燃油10%", **LAND
)
self.assertEqual(quote["vehicleRates"]["7.6米"], "14300")
self.assertEqual(quote["vehicleRates"]["9.6米"], "15400")
self.assertEqual(quote["total"], "14300")
self.assertEqual(quote["fuel_surcharge_rate"], "10%")
self.assertEqual(quote["remark"], "未含燃油10%")
def test_fuel_multiplies_weight_prices(self) -> None:
quote = extract_product_quote(
"2-500KG 单价CNY990,未含燃油10%", **LAND
)
self.assertEqual(quote["weightPrices"][0]["price"], "1089")
self.assertEqual(quote["total"], "1089")
self.assertEqual(quote["price_per_kg"], "1089")
def test_non_land_ignores_condition(self) -> None:
quote = extract_product_quote(
"海运费1000USD,未含燃油13%", business_line="SEA", transport_mode="海运"
)
self.assertEqual(quote["fee_rows"][0]["amount"], "1000")
self.assertNotIn("fuel_surcharge_rate", quote)
def test_injected_quote_also_applies_condition(self) -> None:
# 上层预抽取报价不能绕过乘法,否则出单有燃油费率却没有乘运费。
quote = extract_product_quote(
"运输费3200,未含燃油13%",
injected={
"total": "3200",
"currency": "USD",
"fee_rows": [{"name": "运输费", "amount": "3200", "currency": "USD"}],
},
**LAND,
)
self.assertEqual(quote["fee_rows"][0]["amount"], "3616")
self.assertEqual(quote["total"], "3616")
self.assertEqual(quote["remark"], "未含燃油13%")
class AttachSegmentTest(unittest.TestCase):
"""条件要随 landSegments 进主账,模板备注列/税率列才有值。"""
def _view(self) -> dict:
return {"facts": {"起运地": "东莞", "目的地": "春疆"}}
def test_vehicle_segment_carries_condition(self) -> None:
quote = extract_product_quote(
"东莞-春疆,7.6米CNY13000元;9.6米CNY14000;未含燃油10%", **LAND
)
quote = _attach_land_vehicle_rates_segment(quote, self._view())
seg = quote["landSegments"][0]
self.assertEqual(seg["fuel_surcharge_rate"], "10%")
self.assertEqual(seg["remark"], "未含燃油10%")
self.assertEqual(seg["vehicleRates"]["7.6米"], "14300")
def test_weight_segment_carries_condition(self) -> None:
quote = extract_product_quote("2-500KG 单价CNY990,未含税13%", **LAND)
quote = _attach_land_weight_band_segment(quote, self._view())
seg = quote["landSegments"][0]
self.assertEqual(seg["tax_rate"], "13%")
self.assertEqual(seg["remark"], "未含税13%")
self.assertEqual(seg["weightPrices"][0]["price"], "990")
class SummaryCopyTest(unittest.TestCase):
"""群摘要要露出燃油/备注,销售才知道运费是否已乘燃油。"""
def test_vehicle_lines_show_fuel_and_remark(self) -> None:
quote = extract_product_quote(
"东莞-春疆,7.6米CNY13000元;9.6米CNY14000;未含燃油10%", **LAND
)
text = "\n".join(_manual_land_vehicle_lines(quote))
self.assertIn("燃油费率:10%", text)
self.assertIn("备注:未含燃油10%", text)
def test_single_fee_lines_show_fuel_and_remark(self) -> None:
quote = extract_product_quote("运输费USD3200,未含燃油13%", **LAND)
text = "\n".join(_manual_quote_lines(quote, **LAND, layout="manual"))
self.assertIn("燃油费率:13%", text)
self.assertIn("备注:未含燃油13%", text)
if __name__ == "__main__":
unittest.main()
@@ -281,6 +281,243 @@ class LandRouteOptionsTests(unittest.TestCase):
self.assertNotIn("运输费", card)
self.assertNotIn(dest, card)
def test_cross_border_ftl_shows_port_handling_fee_from_tms(self) -> None:
"""东南亚整车:TMS 回的口岸海关监管费+接驳费单独展示,不挤掉各段运输费。"""
from agent.policy import inquiry_copy as copy
quote = _single_with_transfer()
quote["source"] = "TMS"
quote["source_label"] = "TMS标准报价"
quote["currency"] = "CNY"
quote["valid_until"] = "2026-12-31"
quote["fee_lines"] = _tms_land_fees(
(1, 1, "运输费", 7500),
(1, 2, "运输费", 9600),
) + [
# 模板固定行名:TMS 有就显示,没有就不出现(非必填)。
{
"feeName": "口岸海关监管费+接驳费",
"name": "口岸海关监管费+接驳费",
"amount": 600,
"currency": "CNY",
"segmentSequence": 1,
"routeLegSequence": 2,
}
]
projected = project_selected_route(quote, group_land_routes(quote)[0])
projected["total"] = "17700"
text = copy.sea_quote_detail_text(
work_order_no="WO202612220001",
quote=projected,
business_line="LAND",
)
# 两段主运费都在;附加费不能把第二段运费顶掉。
self.assertIn("运输费:CNY 7500", text)
self.assertIn("运输费:CNY 9600", text)
self.assertIn("口岸海关监管费+接驳费:CNY 600", text)
fee_pos = text.find("口岸海关监管费+接驳费")
self.assertGreater(fee_pos, text.find("运输费:CNY 9600"))
self.assertLess(fee_pos, text.find("费用合计:"))
self.assertIn("费用合计:CNY 17700", text)
card = copy.quote_area_safe_text(projected, business_line="LAND")
self.assertIn("共3项费用", card)
def test_port_handling_fee_ignores_unselected_route(self) -> None:
"""选定线路后,原始 feeItems 里别的备选接驳费不能跟着展示。"""
from agent.policy import inquiry_copy as copy
quote = _three_routes()
quote["source"] = "TMS"
quote["source_label"] = "TMS标准报价"
quote["currency"] = "CNY"
quote["fee_lines"] = _tms_land_fees(
(1, 1, "运输费", 7500),
(1, 2, "运输费", 9600),
(2, 1, "运输费", 7500),
(2, 2, "运输费", 9600),
(3, 1, "运输费", 7500),
(3, 2, "运输费", 9600),
)
quote["feeItems"] = list(quote["fee_lines"]) + [
{
"feeName": "口岸海关监管费+接驳费",
"amount": 600,
"currency": "CNY",
"segmentSequence": 1,
"routeLegSequence": 2,
}
]
projected = project_selected_route(quote, group_land_routes(quote)[1])
text = copy.sea_quote_detail_text(
work_order_no="WO202612220002",
quote=projected,
business_line="LAND",
)
self.assertIn("运输费:", text)
self.assertNotIn("口岸海关监管费+接驳费", text)
def test_wo035_port_fee_parsed_from_tms_remark_by_vehicle(self) -> None:
"""TMS 只在备注里写价表(WO202611220035):按 8T 取 1093,写在合计下面并标另计。"""
from agent.policy import inquiry_copy as copy
clause = (
"4、口岸海关监管+接驳费:1.25T/821元、2.5T/821元,3.5T/821元、5T/944元、"
"8T/1093元、10T/1143元、40HQ/1380元、45HQ/1691元、48RH冷柜/1691元、18M平板/2000元。"
)
quote = {
"source": "TMS",
"source_label": "TMS标准报价",
"currency": "CNY",
"total": "18600",
"valid_until": "2026-10-31",
"isMulti": "1",
"landSegments": [
{
"segmentSequence": "1",
"routeLegSequence": "1",
"origin": "上海",
"destination": "谅山-春疆货场",
"vehicleType": "8T",
"costPrice": "9000.00",
"currency": "CNY",
"transitDays": "N+3",
},
{
"segmentSequence": "1",
"routeLegSequence": "2",
"origin": "谅山-春疆货场",
"destination": "胡志明",
"vehicleType": "8T",
"costPrice": "9600.00",
"currency": "CNY",
"transitDays": "N+3",
"remark": clause,
},
],
"fee_lines": [
{
"name": "运输费",
"amount": "9000.00",
"currency": "CNY",
"unit": "车",
"segmentSequence": "1",
"routeLegSequence": "1",
},
{
"name": "运输费",
"amount": "9600.00",
"currency": "CNY",
"unit": "台",
"segmentSequence": "1",
"routeLegSequence": "2",
"remark": clause,
},
],
}
projected = project_selected_route(quote, group_land_routes(quote)[0])
text = copy.sea_quote_detail_text(
work_order_no="WO202611220035",
quote=projected,
business_line="LAND",
)
self.assertIn("运输费:CNY 9000.00/车", text)
self.assertIn("运输费:CNY 9600.00/台", text)
self.assertIn("口岸海关监管费+接驳费:CNY 1093(8T,另计)", text)
# 另计费在合计之后,销售才不会以为 18600 已含接驳费。
fee_pos = text.find("口岸海关监管费+接驳费")
self.assertGreater(fee_pos, text.find("费用合计:CNY 18600"))
self.assertLess(fee_pos, text.find("报价有效期:"))
card = copy.quote_area_safe_text(projected, business_line="LAND")
self.assertIn("费用合计:CNY 18600", card)
def test_port_fee_remark_unknown_vehicle_shows_raw_clause(self) -> None:
"""车型对不上价表时展示 TMS 原句,禁止替他挑一个数。"""
from agent.policy import inquiry_copy as copy
clause = "4、口岸海关监管+接驳费:1.25T/821元、8T/1093元。"
quote = {
"source": "TMS",
"currency": "CNY",
"total": "9600",
"landSegments": [
{
"segmentSequence": 1,
"routeLegSequence": 1,
"origin": "太原",
"destination": "越南北宁",
"vehicleType": "53尺",
"costPrice": 9600,
"currency": "CNY",
}
],
"fee_lines": [{"name": "运输费", "amount": "9600", "currency": "CNY"}],
"remark": clause,
}
note = copy.land_port_handling_note(quote)
self.assertIn("口岸海关监管费+接驳费:", note)
self.assertIn("1.25T/821元", note)
self.assertIn("按车型", note)
def test_port_fee_note_works_with_ledger_json_strings(self) -> None:
"""主账回读的 payload 全是 JSON 串:车型和备注仍能取到,价表按车型对上。"""
from agent.policy import inquiry_copy as copy
clause = "4、口岸海关监管+接驳费:1.25T/821元、8T/1093元、40HQ/1380元。"
legs = [
{
"segmentSequence": "1",
"routeLegSequence": "1",
"origin": "上海",
"destination": "谅山-春疆货场",
"vehicleType": "8T",
"costPrice": "9000.00",
"currency": "CNY",
"transitDays": "N+3",
},
{
"segmentSequence": "1",
"routeLegSequence": "2",
"origin": "谅山-春疆货场",
"destination": "胡志明",
"vehicleType": "8T",
"costPrice": "9600.00",
"currency": "CNY",
"transitDays": "N+3",
"remark": clause,
},
]
fees = [
{
"name": "运输费",
"amount": "9000.00",
"currency": "CNY",
"unit": "车",
"segmentSequence": "1",
"routeLegSequence": "1",
},
{
"name": "运输费",
"amount": "9600.00",
"currency": "CNY",
"unit": "台",
"segmentSequence": "1",
"routeLegSequence": "2",
},
]
quote = {
"source": "TMS",
"currency": "CNY",
"total": "18600",
"valid_until": "2026-10-31",
"landSegments": json.dumps(legs, ensure_ascii=False),
"fee_lines": json.dumps(fees, ensure_ascii=False),
"selected_land_route": json.dumps(
{"segmentSequence": 1, "legs": legs}, ensure_ascii=False
),
}
note = copy.land_port_handling_note(quote)
self.assertEqual(note, "口岸海关监管费+接驳费:CNY 1093(8T,另计)")
def test_land_detail_and_group_use_selected_route_valid_until(self) -> None:
"""选定广西这条后:私聊明细和群 TMS 段同一套正文,不摊开没选的线路。"""
from agent.policy import inquiry_copy as copy
@@ -736,6 +973,201 @@ class LandRouteOptionsTests(unittest.TestCase):
self.assertIn("jsapi-signature", ok)
self.assertNotIn("closeWindow", dead)
def test_detail_shows_tms_unit_after_amount(self) -> None:
"""TMS 带计价单位时,明细行金额后补「/单位」,如运输费:CNY 13.00/KG。"""
from agent.channel.h5.land_route_page import render_land_route_page
from agent.policy import inquiry_copy as copy
quote = {
"source": "TMS",
"source_label": "TMS标准报价",
"currency": "CNY",
"valid_until": "2026-12-31",
"landSegments": [
{
"segmentSequence": 1,
"routeLegSequence": 1,
"origin": "上海",
"destination": "苏州",
"costPrice": 13.0,
"currency": "CNY",
"transitDays": "N+1",
}
],
"fee_lines": [
{"name": "运输费", "amount": "13.00", "currency": "CNY", "unit": "KGS", "quantity": 1}
],
}
projected = project_selected_route(quote, group_land_routes(quote)[0])
text = copy.sea_quote_detail_text(
work_order_no="WO202611220001",
quote=projected,
business_line="LAND",
)
# KGS 归一成 KG;金额仍是 TMS 原文,只在后面补单位。
self.assertIn("运输费:CNY 13.00/KG", text)
page = render_land_route_page({"work_order_no": "WO202611220001", "quote": quote})
self.assertIn("CNY 13.00/KG", page)
def test_detail_keeps_amount_only_when_tms_has_no_unit(self) -> None:
"""TMS 没给计价单位时不补「/」,与改动前完全一致,禁止本地猜 KG。"""
from agent.policy import inquiry_copy as copy
quote = {
"source": "TMS",
"source_label": "TMS标准报价",
"currency": "CNY",
"valid_until": "2026-12-31",
"landSegments": [
{
"segmentSequence": 1,
"routeLegSequence": 1,
"origin": "上海",
"destination": "苏州",
"costPrice": 7500,
"currency": "CNY",
"transitDays": "N+1",
}
],
"fee_lines": [{"name": "运输费", "amount": "7500.00", "currency": "CNY"}],
}
projected = project_selected_route(quote, group_land_routes(quote)[0])
text = copy.sea_quote_detail_text(
work_order_no="WO202611220002",
quote=projected,
business_line="LAND",
)
self.assertIn("运输费:CNY 7500.00", text)
self.assertNotIn("/KG", text)
self.assertNotIn("/台", text)
def test_fee_unit_normalizes_common_tms_spellings(self) -> None:
"""单位归一:公斤/KGS/元/KG → KG;认不出的原样给,空值不加单位。"""
from agent.policy.inquiry_copy import fee_amount_text, fee_unit
self.assertEqual(fee_unit("KG"), "KG")
self.assertEqual(fee_unit("KGS"), "KG")
self.assertEqual(fee_unit("公斤"), "KG")
self.assertEqual(fee_unit("元/KG"), "KG")
self.assertEqual(fee_unit("台"), "台")
self.assertEqual(fee_unit("板数"), "板")
self.assertEqual(fee_unit(""), "")
# 行金额是整段总额、另有单价时按单价展示,避免「6500/KG」。
self.assertEqual(
fee_amount_text(
{"name": "运输费", "amount": "6500", "currency": "CNY", "unit": "KG", "unit_price": "13"}
),
"CNY 13/KG",
)
# 单价与金额相同(零担按公斤报价,行金额本身就是单价)时保留金额原文。
self.assertEqual(
fee_amount_text(
{"name": "运输费", "amount": "13.00", "currency": "CNY", "unit": "KG", "unit_price": "13"}
),
"CNY 13.00/KG",
)
# 费率行不加单位,避免「1%/KG」。
self.assertEqual(
fee_amount_text({"name": "燃油附加费率", "amount": "1", "unit": "KG"}),
"1",
)
# 产品手工报价传 prefer_unit_price=False:金额是产品敲的数,不能被单价顶掉。
self.assertEqual(
fee_amount_text(
{"name": "陆运费", "amount": "1000", "currency": "CNY", "unit": "车", "unit_price": "1000"},
prefer_unit_price=False,
),
"CNY 1000/车",
)
def test_manual_quote_keeps_unit_typed_by_product(self) -> None:
"""产品文字报价自己写了单位(1000/车、13元/KG)时,摘要必须带上,不能只留金额。"""
from agent.llm.extract_text import extract_product_quote
from agent.policy.inquiry_copy import quote_fee_lines
per_truck = extract_product_quote("陆运费1000元/车", business_line="LAND")
self.assertEqual(quote_fee_lines(per_truck), [("陆运费", "CNY 1000/车")])
per_kg = extract_product_quote("运输费13元/KG", business_line="LAND")
self.assertEqual(quote_fee_lines(per_kg), [("运输费", "CNY 13/KG")])
per_shipment = extract_product_quote("报关费300元/票", business_line="LAND")
self.assertEqual(quote_fee_lines(per_shipment), [("报关费", "CNY 300/票")])
def test_manual_quote_without_unit_stays_plain_amount(self) -> None:
"""产品只敲了金额(TMS 也没价)时没有单位可写,禁止本地猜 /车 或 /KG。"""
from agent.llm.extract_text import extract_product_quote
from agent.policy.inquiry_copy import quote_fee_lines
bare = extract_product_quote("1000", business_line="LAND")
self.assertEqual(quote_fee_lines(bare), [("陆运费", "1000")])
named = extract_product_quote("陆运费1000", business_line="LAND")
self.assertEqual(quote_fee_lines(named), [("陆运费", "1000")])
# 「元」只是币种后缀,不是计价单位。
with_ccy = extract_product_quote("陆运费1000元", business_line="LAND")
self.assertEqual(quote_fee_lines(with_ccy), [("陆运费", "CNY 1000")])
def test_manual_land_ftl_defaults_to_per_truck(self) -> None:
"""整车人工报价产品没写单位时补「/车」(产品拍板);零担/拼车不补。"""
from agent.policy import inquiry_copy as copy
quote = {
"source": "PRODUCT",
"source_label": "产品报价",
"currency": "CNY",
"total": "1000",
"fee_rows": [{"name": "陆运费", "amount": "1000", "currency": "CNY"}],
}
lines = copy._manual_quote_lines(
quote,
transport_mode="陆运",
facts={"运输类型": "国内运输整车", "车型/数量": "9米6/1"},
)
self.assertIn("陆运费:CNY 1000/车", lines)
# 零担/拼车不补:按公斤算出来的总额不能写成像整票价。
lcl = copy._manual_quote_lines(
quote,
transport_mode="陆运",
facts={"运输类型": "国内运输拼车", "线路类别": "国内长途/零担"},
)
self.assertIn("陆运费:CNY 1000", lcl)
self.assertNotIn("陆运费:CNY 1000/车", lcl)
# 没有工单事实时不猜。
self.assertIn("陆运费:CNY 1000", copy._manual_quote_lines(quote, transport_mode="陆运"))
# 产品自己写了单位,以产品为准,不被默认「/车」覆盖。
per_kg = {
"source": "PRODUCT",
"currency": "CNY",
"total": "13",
"fee_rows": [{"name": "运输费", "amount": "13", "currency": "CNY", "unit": "KG"}],
}
self.assertIn(
"运输费:CNY 13/KG",
copy._manual_quote_lines(
per_kg, transport_mode="陆运", facts={"运输类型": "国内运输整车"}
),
)
def test_tms_land_quote_never_gets_default_truck_unit(self) -> None:
"""TMS 陆运价不受「整车补 /车」影响:TMS 没给单位就只显示金额。"""
from agent.policy import inquiry_copy as copy
tms = {
"source": "TMS",
"currency": "CNY",
"total": "1000",
"fee_rows": [{"name": "运输费", "amount": "1000", "currency": "CNY"}],
}
text = copy.quote_area_fee_text(
tms, business_line="LAND", facts={"运输类型": "国内运输整车"}
)
self.assertIn("运输费:CNY 1000", text)
self.assertNotIn("/车", text)
if __name__ == "__main__":
unittest.main()
+34 -12
View File
@@ -114,8 +114,8 @@ class LandTextInquiryFrontTests(unittest.TestCase):
self.assertEqual(sess.facts.get("运输类型"), "国内运输拼车")
self.assertEqual(sess.facts.get("线路类别"), "东南亚")
def test_hk_lcl_skips_vehicle(self) -> None:
"""中港零担/集拼:不补问车型/数量,齐字段后直接出核对卡。"""
def test_hk_lcl_requires_volume_weight_before_confirm(self) -> None:
"""中港集拼:缺体积/毛重先补问,不要求车型;补齐后才出核对卡。"""
phase = self.flow.on_text(
sender_id="u1",
text="中港零担/集拼 中港/中亚/中欧 急件",
@@ -127,9 +127,24 @@ class LandTextInquiryFrontTests(unittest.TestCase):
},
injected_mode="LAND",
)
self.assertEqual(phase, "clarify")
text = self._joined()
self.assertIn("1.体积", text)
self.assertIn("2.重量(KG)", text)
self.assertNotIn("车型/数量", text)
self.assertEqual(self.ledger.create_calls, 0)
self.replies.clear()
phase = self.flow.on_text(
sender_id="u1",
text="体积:20CBM;毛重:3000KG",
reply=self._reply,
)
self.assertEqual(phase, "wait_confirm")
self.assertNotIn("车型/数量", self._joined())
self.assertIn("通关口岸(非必填)", self._joined())
text = self._joined()
self.assertIn("体积(CBM)(必填):20CBM", text)
self.assertIn("重量(KG)(必填):3000KG", text)
self.assertNotIn("车型/数量", text)
self.assertIn("通关口岸(非必填)", text)
self.assertEqual(self.ledger.create_calls, 0)
def test_hk_full_truck_skips_vehicle(self) -> None:
@@ -375,11 +390,19 @@ class LandTextConfirmTests(unittest.TestCase):
self.assertEqual(ticket.facts.get("线路类别"), "国内长途/零担")
joined = "\n".join(self.replies)
self.assertIn("工单号:" + self.ledger.last_created_no, joined)
self.assertIn("运输方式:陆运", joined)
self.assertIn("运输类型:国内运输拼车", joined)
self.assertIn("始发站:广州", joined)
self.assertIn("工单已创建,正在查询TMS报价。", joined)
self.assertNotIn("工单已创建:" + self.ledger.last_created_no, joined)
# 产品口径 2026-11-22:确定后只发工单号 + 正在查询TMS报价,字段段不再重复。
# 字段核对在确定前的核对卡完成,建单确认这一条不能夹带字段行。
self.assertEqual(
self.replies[0],
"\n".join(
[
"工单号:" + self.ledger.last_created_no,
"工单已创建,正在查询TMS报价。",
]
),
)
def test_tms_fail_then_confirm_retries_same_ticket(self) -> None:
class Flaky(CountingLedger):
@@ -638,11 +661,10 @@ class LandTextPullTests(unittest.TestCase):
userids = self.groups.created[0]["userids"]
self.assertIn("p_dom", userids)
self.assertNotIn("p_sea", userids)
brief = "\n".join(x.get("content") or "" for x in self.groups.sent if x.get("kind") == "text")
self.assertIn("运输类型", brief)
self.assertIn("国内运输拼车", brief)
self.assertIn("国内长途/零担", brief)
self.assertIn("急件", brief)
# 产品口径(2026-11-20):建群后立即发字段摘要;不自动发表。
texts = [x.get("content") or "" for x in self.groups.sent if x.get("kind") == "text"]
self.assertTrue(texts, "拉群后应立即发字段摘要")
self.assertFalse(any(x.get("kind") == "file" for x in self.groups.sent))
def test_pull_no_staff(self) -> None:
self.ledger.set_land_staff([])
@@ -0,0 +1,80 @@
"""
陆运查价参数(TMS 出站)单测:中港集拼按体积+毛重,不带车型/数量。
不连真实 TMS、不读 Redis、不写主账。只校验 assemble_land_query 的拼参与拦网。
"""
from __future__ import annotations
import os
import sys
import unittest
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
from agent.schema.tms_land_query import assemble_land_query
class LandTmsQueryTest(unittest.TestCase):
def _hk_facts(self, **extra: str) -> dict[str, str]:
facts = {
"运输类型": "中港零担/集拼",
"线路类别": "中港/中亚/中欧",
"起运港": "广州",
"目的港": "香港",
"品名": "衣服",
}
facts.update(extra)
return facts
def test_hk_lcl_requires_volume_and_weight(self) -> None:
"""中港集拼没有体积/毛重时,出站拦网必须报缺项,且不要求车型/数量。"""
got = assemble_land_query(self._hk_facts(车型数量="9米6/1"))
self.assertFalse(got["ok"])
self.assertIn("体积", got["missing"])
self.assertIn("毛重", got["missing"])
self.assertNotIn("车型/数量", got["missing"])
def test_hk_lcl_sends_volume_weight_not_vehicle(self) -> None:
"""中港集拼齐字段后按体积+毛重出站,车型/数量不进出站。"""
got = assemble_land_query(
self._hk_facts(体积="20CBM", 毛重="3000KG", **{"车型/数量": "9米6/1"})
)
self.assertTrue(got["ok"], got["missing"])
out = got["outbound"]
self.assertEqual(out["landTransportType"], "中港零担/集拼")
self.assertEqual(out["routeCategory"], "CN_HK_CA_EU")
self.assertEqual(out["volumeCbm"], "20")
self.assertEqual(out["weightKg"], "3000")
self.assertNotIn("vehicleType", out)
self.assertNotIn("quantity", out)
def test_hk_lcl_keeps_customs_when_present(self) -> None:
"""通关口岸仍是非必填,有值才带出站。"""
got = assemble_land_query(
self._hk_facts(体积="20", 毛重="3000", 通关口岸="皇岗")
)
self.assertEqual(got["outbound"].get("customsPort"), "皇岗")
def test_cross_border_lcl_unchanged(self) -> None:
"""跨境集拼口径不变,避免改中港时把既有拼车查价带坏。"""
got = assemble_land_query(
{
"运输类型": "跨境集拼",
"线路类别": "东南亚",
"起运港": "广州",
"目的港": "河内",
"品名": "衣服",
"体积": "100CBM",
"毛重": "50kg",
}
)
self.assertTrue(got["ok"], got["missing"])
self.assertEqual(got["outbound"]["volumeCbm"], "100")
self.assertEqual(got["outbound"]["weightKg"], "50")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,520 @@
"""
人工报价格式回归:空运短句、陆运米长车型、陆运多币种。
对应产品给的三个样例(2026-11-22):
1. 空运:「1:300,+500,USD11/kg,卡转/MUST GO、TH、NKG-KUL、11月2日」
2. 陆运:「东莞-春疆,危险品,7.6米CNY13000元;9.6米CNY14000;45HQ,CNY18500;都是含0点税」
3. 陆运:「春疆-罗勇,45HQ,运输费USD3200,燃油费USD300,过境费USD70,报关费cny1400」
本文件只测解析与挂段,不连企微/TMS/主账。
禁止把这三种写法退化回「7.6 当运费」或「USD+CNY 相加成 4970」。
"""
from __future__ import annotations
import os
import sys
import unittest
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
os.environ.setdefault("YTD_ENV", "test")
os.environ.setdefault("REDIS_BACKEND", "memory")
os.environ.setdefault("CHECKPOINT_BACKEND", "memory")
os.environ.setdefault("MESSAGE_STORE_BACKEND", "memory")
os.environ.setdefault("LLM_DATA_USAGE_CONFIRMED", "false")
os.environ.setdefault("LLM_ALLOW_NETWORK", "false")
os.environ.setdefault("LEDGER_BACKEND", "memory")
from agent.llm.extract_text import extract_product_quote
from agent.policy.sea_group_ops import _attach_land_vehicle_rates_segment
AIR_SAMPLE = "工单号、1:300,+500,USD11/kg,卡转/MUST GO、TH、NKG-KUL、11月2日"
LAND_VEHICLE_SAMPLE = (
"东莞-春疆,危险品,7.6米CNY13000元;9.6米CNY14000;45HQ,CNY18500;都是含0点税"
)
LAND_MULTI_CCY_SAMPLE = (
"春疆-罗勇,45HQ,运输费USD3200,燃油费USD300,过境费USD70,报关费cny1400"
)
class ManualQuoteAirTest(unittest.TestCase):
"""空运短句:单价按 KG、+500 只作重量分档,不冒充附加费。"""
def test_unit_price_and_weight_break(self) -> None:
quote = extract_product_quote(AIR_SAMPLE, business_line="AIR", transport_mode="空运")
rows = list(quote.get("fee_rows") or [])
self.assertEqual(len(rows), 1)
row = rows[0]
self.assertEqual(row.get("name"), "空运费")
self.assertEqual(row.get("unit"), "KG")
self.assertEqual(row.get("unit_price"), "11")
self.assertEqual(row.get("currency"), "USD")
self.assertEqual(row.get("weight_break"), "+500")
# 只有单价没有数量时合计就是单价,摘要显示「单价USD11/KG(+500)」。
self.assertEqual(str(quote.get("total") or ""), "11")
def test_side_fields_are_harvested(self) -> None:
from agent.policy.air_group_ops import _harvest_air_manual_airline
from agent.schema.added_services import harvest_added_services
from agent.schema.field_validate import _harvest_air_ratio, _harvest_quote_date
self.assertEqual(_harvest_air_manual_airline(AIR_SAMPLE), "TH")
self.assertEqual(harvest_added_services(AIR_SAMPLE), ["卡转", "MUST GO"])
self.assertEqual(_harvest_air_ratio(AIR_SAMPLE), "1:300")
self.assertTrue(_harvest_quote_date(AIR_SAMPLE).endswith("-11-02"))
class ManualQuoteLandVehicleTest(unittest.TestCase):
"""陆运多车型价:米长与柜型都是车型键,米长数字绝不能当运费。"""
def test_mile_and_container_labels_become_rates(self) -> None:
quote = extract_product_quote(
LAND_VEHICLE_SAMPLE, business_line="LAND", transport_mode="陆运"
)
rates = dict(quote.get("vehicleRates") or {})
self.assertEqual(rates.get("7.6米"), "13000")
self.assertEqual(rates.get("9.6米"), "14000")
self.assertEqual(rates.get("45HQ"), "18500")
self.assertEqual(str(quote.get("currency") or ""), "CNY")
# 备注由 land_quote_condition 归一成「含0税」;旧写法「含0点税」也算通过,
# 两条并行改动谁先落地都不该让用例红。
self.assertIn(str(quote.get("remark") or ""), {"含0点税", "含0税"})
self.assertEqual(str(quote.get("tax_rate") or ""), "0")
# 旧缺陷:整句只剩一行「陆运费 7.6」。
for row in quote.get("fee_rows") or []:
self.assertNotIn(str(row.get("amount") or ""), {"7.6", "9.6"})
def test_rates_attach_to_segment_and_clear_fee_rows(self) -> None:
quote = extract_product_quote(
LAND_VEHICLE_SAMPLE, business_line="LAND", transport_mode="陆运"
)
out = _attach_land_vehicle_rates_segment(
quote, {"facts": {"起运港": "东莞", "目的港": "春疆"}}
)
segs = list(out.get("landSegments") or [])
self.assertEqual(len(segs), 1)
self.assertEqual(segs[0].get("origin"), "东莞")
self.assertEqual(segs[0].get("destination"), "春疆")
self.assertEqual((segs[0].get("vehicleRates") or {}).get("45HQ"), "18500")
# 多车型价只走矩阵列,费目行清空,避免车型名被当成费目写进起始地。
self.assertEqual(list(out.get("fee_rows") or []), [])
class ManualQuoteLandMultiCurrencyTest(unittest.TestCase):
"""陆运跨境:美元运费 + 人民币报关费,各行保币种,合计不跨币种相加。"""
def test_rows_keep_their_own_currency(self) -> None:
quote = extract_product_quote(
LAND_MULTI_CCY_SAMPLE, business_line="LAND", transport_mode="陆运"
)
rows = list(quote.get("fee_rows") or [])
self.assertEqual([r.get("name") for r in rows], ["运输费", "燃油费", "过境费", "报关费"])
self.assertEqual([r.get("currency") for r in rows], ["USD", "USD", "USD", "CNY"])
def test_total_is_not_cross_currency_sum(self) -> None:
quote = extract_product_quote(
LAND_MULTI_CCY_SAMPLE, business_line="LAND", transport_mode="陆运"
)
# 3200+300+70 = 3570 USD;报关费 1400 CNY 另计,绝不加进 USD 合计。
self.assertEqual(str(quote.get("total") or ""), "3570.0")
self.assertEqual(str(quote.get("currency") or ""), "USD")
self.assertTrue(quote.get("mixed_currency"))
def test_vehicle_type_without_price_keeps_fees(self) -> None:
quote = extract_product_quote(
LAND_MULTI_CCY_SAMPLE, business_line="LAND", transport_mode="陆运"
)
self.assertEqual(str(quote.get("vehicleType") or ""), "45HQ")
out = _attach_land_vehicle_rates_segment(
quote, {"facts": {"起运港": "春疆", "目的港": "罗勇"}}
)
seg = (out.get("landSegments") or [{}])[0]
self.assertEqual(seg.get("vehicleType"), "45HQ")
# 只有车型没有价矩阵:费用明细必须保留,不能因挂车型被清空。
self.assertEqual(len(out.get("fee_lines") or []), 4)
class ManualQuoteSummaryTest(unittest.TestCase):
"""销售侧摘要:三档车型价和备注必须露出来,不能只回一个合计。"""
def test_vehicle_matrix_and_remark_are_shown(self) -> None:
from agent.policy import inquiry_copy as copy
quote = extract_product_quote(
LAND_VEHICLE_SAMPLE, business_line="LAND", transport_mode="陆运"
)
out = _attach_land_vehicle_rates_segment(
quote, {"facts": {"起运港": "东莞", "目的港": "春疆"}}
)
text = "\n".join(copy._manual_quote_lines(out, business_line="LAND", transport_mode="陆运"))
self.assertIn("车型价:7.6米 CNY 13000;9.6米 CNY 14000;45HQ CNY 18500", text)
self.assertIn("备注:含0", text)
self.assertIn("此处取第一档", text)
def test_multi_currency_lines_keep_currency(self) -> None:
from agent.policy import inquiry_copy as copy
quote = extract_product_quote(
LAND_MULTI_CCY_SAMPLE, business_line="LAND", transport_mode="陆运"
)
out = _attach_land_vehicle_rates_segment(
quote, {"facts": {"起运港": "春疆", "目的港": "罗勇"}}
)
text = "\n".join(copy._manual_quote_lines(out, business_line="LAND", transport_mode="陆运"))
self.assertIn("运输费:USD 3200", text)
self.assertIn("报关费:CNY 1400", text)
self.assertIn("费用合计:USD 3570.0", text)
# 不再出现把美元和人民币加在一起的假数。
self.assertNotIn("4970", text)
class ManualQuoteSeaRegressionTest(unittest.TestCase):
"""海运单币种仍照旧加总,别被多币种改动带偏。"""
def test_sea_single_currency_still_sums(self) -> None:
quote = extract_product_quote(
"码头操作费100CNY,报关费300CNY", business_line="SEA", transport_mode="海运"
)
self.assertEqual(str(quote.get("currency") or ""), "CNY")
self.assertEqual(str(quote.get("total") or ""), "400.0")
self.assertFalse(quote.get("mixed_currency"))
class ManualQuoteAirLayoutTest(unittest.TestCase):
"""空运人工报价对外版式(产品 2026-11-22 定稿):比例/重量等级/舱位信息 + 价格。"""
def _text(self) -> str:
from agent.policy import inquiry_copy as copy
quote = extract_product_quote(AIR_SAMPLE, business_line="AIR", transport_mode="空运")
quote["source"] = "PRODUCT"
quote["source_label"] = "航线报价"
quote["airlineCode"] = "TH"
quote["airline"] = "TH"
facts = {
"起运港": "NKG",
"目的港": "KUL",
"品名": "普货",
"件数": "10",
"毛重": "500",
"体积": "3",
"包装方式": "纸箱",
"比例": "1:300",
"报价日期": "2026-11-02",
"added_services": "卡转、MUST GO",
}
return "\n".join(
copy._manual_quote_lines(
quote, business_line="AIR", facts=facts, layout="manual"
)
)
def test_full_block_matches_product_layout(self) -> None:
self.assertEqual(
self._text(),
"\n".join(
[
"价格方案如下:",
"比例:1:300",
"重量等级:+500",
# 体积 3CBM × 166.7 = 500.1KG > 毛重 500KG → 取体积重;
# 产品 2026-11-22 晚确定只写数字,不括注依据。
"计费重:500.1KG",
"舱位信息:TH,NKG-KUL,2026-11-2起(包含航司、线路、班期、舱位日期哪天起),具体根据放舱情况而定",
"",
"价格",
"空运费:USD11/kg",
"报价有效期:2026-11-2",
"原始报价参考:" + AIR_SAMPLE,
]
),
)
def test_missing_facts_do_not_print_dashes(self) -> None:
from agent.policy import inquiry_copy as copy
quote = extract_product_quote(AIR_SAMPLE, business_line="AIR", transport_mode="空运")
text = "\n".join(
copy._manual_quote_lines(quote, business_line="AIR", facts={}, layout="manual")
)
# 没有报价日期就不写有效期,不拿「-」占位、不编日期。
self.assertNotIn("报价有效期", text)
self.assertNotIn(":-", text)
def test_cabin_scope_note_is_never_dropped(self) -> None:
"""
「(包含航司、线路、班期、舱位日期哪天起)」是产品要求保留的说明。
只有航司、没有线路和日期时也必须带上;四样全缺才整行不写。
"""
from agent.policy import inquiry_copy as copy
quote = extract_product_quote(AIR_SAMPLE, business_line="AIR", transport_mode="空运")
quote["airlineCode"] = "TH"
text = "\n".join(
copy._manual_quote_lines(quote, business_line="AIR", facts={}, layout="manual")
)
self.assertIn(
"舱位信息:TH(包含航司、线路、班期、舱位日期哪天起),具体根据放舱情况而定",
text,
)
empty = extract_product_quote(AIR_SAMPLE, business_line="AIR", transport_mode="空运")
empty.pop("airlineCode", None)
empty.pop("airline", None)
bare = "\n".join(
copy._manual_quote_lines(empty, business_line="AIR", facts={}, layout="manual")
)
self.assertNotIn("舱位信息", bare)
class ManualQuoteLandLayoutTest(unittest.TestCase):
"""陆运多车型人工报价竖排版式:一段一价 + 税率 + 原始报价参考。"""
def _text(self) -> str:
from agent.policy import inquiry_copy as copy
quote = extract_product_quote(
LAND_VEHICLE_SAMPLE, business_line="LAND", transport_mode="陆运"
)
out = _attach_land_vehicle_rates_segment(
quote, {"facts": {"起运港": "东莞", "目的港": "春疆"}}
)
out["raw_text"] = LAND_VEHICLE_SAMPLE
return "\n".join(
copy._manual_quote_lines(out, business_line="LAND", layout="manual")
)
def test_vehicle_matrix_is_vertical(self) -> None:
self.assertEqual(
self._text(),
"\n".join(
[
"车型/数量:7.6米",
"运输费:CNY13000元",
"车型/数量:9.6米",
"运输费:CNY14000元",
"车型/数量:45HQ",
"运输费:CNY18500元",
"税率:0",
"原始报价参考:" + LAND_VEHICLE_SAMPLE,
]
),
)
def test_group_brief_drops_tms_miss_block_when_product_quoted(self) -> None:
"""
产品 2026-11-22 口径:TMS 没查到价、产品已经在群里报了多车型价时,
摘要不再出现「TMS报价:TMS 暂无匹配报价 + 请另报」这一段,直接进「人工报价:」。
图 WO202611220022 就是这种场景:销售看到红框里的无价空话会以为报价没生效。
"""
from agent.policy import inquiry_copy as copy
quote = extract_product_quote(
LAND_VEHICLE_SAMPLE, business_line="LAND", transport_mode="陆运"
)
manual = _attach_land_vehicle_rates_segment(
quote, {"facts": {"起运港": "东莞", "目的港": "春疆"}}
)
brief = copy.sea_group_brief(
work_order_no="WO202611220022",
facts={"起运港": "东莞", "目的港": "春疆", "品名": "危险品"},
quote=None,
collab_facts={},
sales_name="罗小华",
product_names=[],
has_price=False,
tms_quote={},
product_quote=manual,
transport_mode="陆运",
)
self.assertNotIn("TMS报价:", brief)
self.assertNotIn("TMS 暂无匹配报价", brief)
self.assertNotIn("产品人员可通过“纯文字”告知新报价", brief)
# TMS 段整段去掉后上面没有小标题,必须补「人工报价:」才知道这是产品报的价。
self.assertIn(
"人工报价:\n车型/数量:7.6米\n运输费:CNY13000元", brief
)
def test_group_brief_keeps_tms_block_when_tms_priced(self) -> None:
"""TMS 有价时照旧保留 TMS 段,手工补的价另起「人工报价:」,两段不混。"""
from agent.policy import inquiry_copy as copy
tms = {
"total": "CNY 20000",
"currency": "CNY",
"source": "TMS",
"source_label": "TMS标准报价",
"fee_lines": [{"name": "海运费", "amount": "20000.00", "currency": "CNY"}],
}
brief = copy.sea_group_brief(
work_order_no="WO202611220023",
facts={"起运港": "上海", "目的港": "海防", "品名": "机器设备"},
quote=tms,
collab_facts={},
sales_name="罗小华",
product_names=["林绵勋"],
has_price=True,
tms_quote=tms,
product_quote={
"source_label": "产品报价",
"fee_lines": [
{"name": "燃油附加费", "amount": "150.00", "currency": "USD"}
],
},
transport_mode="海运",
)
self.assertIn("TMS报价:", brief)
self.assertNotIn("TMS 暂无匹配报价", brief)
self.assertIn("人工报价:", brief)
def test_zero_tax_word_becomes_tax_rate(self) -> None:
quote = extract_product_quote(
LAND_VEHICLE_SAMPLE, business_line="LAND", transport_mode="陆运"
)
# 「都是含0点税」= 税率 0;备注归一为「含0税」后仍留着给报价单备注列。
self.assertEqual(str(quote.get("tax_rate") or ""), "0")
self.assertIn(str(quote.get("remark") or ""), {"含0点税", "含0税"})
def test_plain_tax_word_does_not_invent_rate(self) -> None:
# 「含税」看不出点数,禁止猜成 0 或 13。
quote = extract_product_quote(
"东莞-春疆,7.6米CNY13000元;9.6米CNY14000;含税",
business_line="LAND",
transport_mode="陆运",
)
self.assertEqual(str(quote.get("tax_rate") or ""), "")
def test_multi_currency_fees_keep_ref_line(self) -> None:
from agent.policy import inquiry_copy as copy
quote = extract_product_quote(
LAND_MULTI_CCY_SAMPLE, business_line="LAND", transport_mode="陆运"
)
out = _attach_land_vehicle_rates_segment(
quote, {"facts": {"起运港": "春疆", "目的港": "罗勇"}}
)
text = "\n".join(
copy._manual_quote_lines(out, business_line="LAND", layout="manual")
)
# 逐项费用写法保持原样,只多一行原话参考。
self.assertIn("运输费:USD 3200", text)
self.assertIn("报关费:CNY 1400", text)
self.assertIn("原始报价参考:" + LAND_MULTI_CCY_SAMPLE, text)
class ManualQuoteLandSingleVehicleTest(unittest.TestCase):
"""单档车型价:群里「8T CNY990」不能把 8 当运费(WO202611100043)。"""
def test_single_vehicle_rate_keeps_model_and_price(self) -> None:
quote = extract_product_quote(
"产品报价:8T CNY990", business_line="LAND", transport_mode="陆运"
)
# 8T 是车型、990 才是费用;旧实现丢掉单档车型价后在金额回退里抽到 8。
self.assertEqual(dict(quote.get("vehicleRates") or {}), {"8T": "990"})
self.assertEqual(str(quote.get("total") or ""), "990")
self.assertEqual(str(quote.get("currency") or ""), "CNY")
for row in quote.get("fee_rows") or []:
self.assertNotEqual(str(row.get("amount") or "").strip(), "8")
def test_single_vehicle_rate_summary_shows_model_and_money(self) -> None:
from agent.policy import inquiry_copy as copy
quote = extract_product_quote(
"8T CNY990", business_line="LAND", transport_mode="陆运"
)
out = _attach_land_vehicle_rates_segment(
quote, {"facts": {"起运港": "深圳", "目的港": "香港"}}
)
text = "\n".join(
copy._manual_quote_lines(
out, business_line="LAND", transport_mode="陆运", layout="manual"
)
)
self.assertIn("车型/数量:8T", text)
self.assertIn("运输费:CNY990元", text)
self.assertNotIn("CNY8元", text)
def test_fee_name_glued_vehicle_rate_shows_tonnage_and_unit(self) -> None:
"""「运费10T:1700HKD/车」:摘要要出车型 10T、1700/车,条款进备注(WO202610300015)。"""
from agent.policy import inquiry_copy as copy
text = (
"深圳--香港元朗运费10T:1700HKD/车\n"
"超时费:免等候2小时,超出按200/小时收取;如遇海关查验,查验等候免3小时,"
"超过了200/小时,压夜按运费80%,压日按运费100%以上港币报价,不含保,杂费实报实"
)
quote = extract_product_quote(
text, business_line="LAND", transport_mode="陆运"
)
out = _attach_land_vehicle_rates_segment(
quote, {"facts": {"起运港": "深圳", "目的港": "香港"}}
)
lines = copy._manual_quote_lines(
out, business_line="LAND", transport_mode="陆运", layout="manual"
)
self.assertIn("车型/数量:10T", lines)
self.assertIn("运输费:HKD1700/车", lines)
self.assertTrue(any(line.startswith("备注:超时费:免等候2小时") for line in lines))
self.assertFalse(any("HKD10" in line for line in lines))
self.assertFalse(any(line.startswith("压夜按运费:") for line in lines))
def test_non_land_single_rate_keeps_old_two_tier_guard(self) -> None:
"""非陆运不改旧口径:没写「车型」且只有一档时仍不当车型矩阵。"""
quote = extract_product_quote(
"8T CNY990", business_line="SEA", transport_mode="海运"
)
self.assertFalse(dict(quote.get("vehicleRates") or {}))
self.assertEqual(str(quote.get("total") or ""), "990")
class ManualQuoteRefMentionTest(unittest.TestCase):
"""原始报价参考不能把「@机器人」当报价内容(2026-11-22 产品反馈)。"""
def _line(self, raw: str) -> str:
from agent.policy import inquiry_copy as copy
return copy._raw_quote_ref_line({"raw_text": raw})
def test_at_bot_is_stripped(self) -> None:
# 群里报价常以「@机器人」开头;参考行只留产品原话。
self.assertEqual(
self._line("@智价通AIQ " + AIR_SAMPLE), "原始报价参考:" + AIR_SAMPLE
)
def test_bot_name_with_spaces_is_stripped(self) -> None:
# 企微显示名可能被 @ 成中间带空格,不能只认写死的一整串。
self.assertEqual(
self._line("@智价通 AIQ " + AIR_SAMPLE), "原始报价参考:" + AIR_SAMPLE
)
def test_longer_group_display_name_is_stripped(self) -> None:
# 测服真机:后台配置名「智价通AIQ」,群里显示名是「智价通AIQ测试」。
# 只按配置名部分替换会留下「测试」两个残字,必须整体剥掉整个称呼。
raw = (
"@智价通AIQ测试 1:300,+500,USD11/kg,卡转/MUST GO、"
"TH、NKG-KUL、11月23日"
)
self.assertEqual(
self._line(raw),
"原始报价参考:1:300,+500,USD11/kg,卡转/MUST GO、TH、NKG-KUL、11月23日",
)
def test_archive_seat_mention_is_stripped(self) -> None:
# 兜底唤醒 @ 的是会话存档席位账号,同样不是报价内容。
self.assertEqual(
self._line("@会话存档-机器人 " + AIR_SAMPLE), "原始报价参考:" + AIR_SAMPLE
)
def test_extraction_drops_mention_from_raw_text(self) -> None:
# 新写入主账的原话也不该带 @机器人,历史单子由上面展示层兜底。
quote = extract_product_quote(
"@智价通AIQ " + AIR_SAMPLE, business_line="AIR", transport_mode="空运"
)
self.assertEqual(str(quote.get("raw_text") or ""), AIR_SAMPLE)
if __name__ == "__main__":
unittest.main()
@@ -90,6 +90,31 @@ class SplitTests(unittest.TestCase):
"single",
)
def test_shanghai_yunshu_is_not_sea_segment(self) -> None:
"""正服:…运输… 里的「海/空/陆+运」不能误切成运输方式段。"""
oral = "陆运北京到上海运输费"
self.assertEqual(classify_multi_text(oral), "single")
self.assertFalse(split_segments(oral).ok)
# 前缀不是「上」:威海/航空/大陆 + 运输 同样不能假切。
self.assertEqual(classify_multi_text("陆运威海运输费"), "single")
self.assertEqual(classify_multi_text("询价航空运输费"), "single")
self.assertEqual(classify_multi_text("询价大陆运输到上海"), "single")
# 真海运仍要认:「上海港海运」里的海运不是假阳性。
self.assertEqual(classify_multi_text("陆运北京\n海运上海港到洛杉矶"), "multi")
def test_mode_after_route_without_punct(self) -> None:
"""以往口语:A到B 后紧贴方式、不打标点,仍要精准认出单段。"""
from agent.llm.extract_text import detect_transport_mode
self.assertEqual(detect_transport_mode("广州到深圳陆运衣服100方"), "LAND")
self.assertEqual(detect_transport_mode("上海到汉堡海运20GP"), "SEA")
self.assertEqual(
detect_transport_mode("上海到洛杉矶空运,3件180kg,下周三前到"),
"AIR",
)
self.assertEqual(classify_multi_text("广州到深圳陆运衣服100方"), "single")
self.assertEqual(classify_multi_text("上海到汉堡海运20GP"), "single")
def test_explicit_markers_ignore_mode_words_in_body(self) -> None:
"""文件名先标了段,表里再写「运输方式:海运」不能当成又一段海运。"""
oral = (
+158 -3
View File
@@ -266,7 +266,8 @@ class QuoteAdjustTests(unittest.TestCase):
self.assertEqual(str(got.quote["total"]), "2000")
self.assertTrue(got.currency_hint)
def test_multi_currency_line_does_not_change_total(self) -> None:
def test_multi_currency_same_ccy_line_updates_total(self) -> None:
"""总价是 CNY 时,改 CNY 行可以进合计;外币行才需要提示不做汇率。"""
src = _quote(
("提货费", "100", "USD"),
("空运费", "2000", "CNY"),
@@ -279,8 +280,8 @@ class QuoteAdjustTests(unittest.TestCase):
names = {r["name"]: r["amount"] for r in got.quote["fee_rows"]}
self.assertEqual(names["空运费"], "2200.00")
self.assertEqual(names["提货费"], "100")
self.assertEqual(str(got.quote["total"]), "2000")
self.assertTrue(got.currency_hint)
self.assertEqual(str(got.quote["total"]), "2200.00")
self.assertFalse(got.currency_hint)
def test_multi_currency_total_only_changes_total(self) -> None:
src = _quote(
@@ -344,6 +345,61 @@ class QuoteAdjustTests(unittest.TestCase):
self.assertEqual(names["箱单费"], "210.00")
self.assertEqual(got.quote["fee_total_polCostItems"], "1344.00")
def test_sea_bucket_lines_recompute_subtotals_and_total(self) -> None:
"""海运混币种:改美元海运费后,人民币小计与合计都要自动增长。"""
src = {
"currency": "CNY",
"total": "6952.77",
"fee_lines": [
{"name": "订舱费(DCF)", "amount": "500.00", "currency": "CNY"},
{"name": "操作费", "amount": "520.00", "currency": "CNY"},
{"name": "舱单", "amount": "50.00", "currency": "CNY"},
{"name": "海运费", "amount": "1250.00", "currency": "USD"},
{"name": "文件费", "amount": "450.00", "currency": "CNY"},
{"name": "设备费", "amount": "30.00", "currency": "CNY"},
],
"polCostItems": [
{"name": "订舱费(DCF)", "amount": "500.00", "currency": "CNY"},
{"name": "操作费", "amount": "520.00", "currency": "CNY"},
{"name": "舱单", "amount": "50.00", "currency": "CNY"},
],
"oceanCostItems": [
{"name": "海运费", "amount": "1250.00", "currency": "USD"},
],
"podCostItems": [
{"name": "文件费", "amount": "450.00", "currency": "CNY"},
{"name": "设备费", "amount": "30.00", "currency": "CNY"},
],
"fee_total_polCostItems": "1070.00",
# TMS 口径:USD 1250 × 7.023 = 8778.75 CNY
"fee_total_oceanCostItems": "8778.75",
"fee_total_podCostItems": "480.00",
}
ext = AdjustExtract(
is_adjust=True,
items=[
AdjustItem("订舱费(DCF)", "target", "set", 585),
AdjustItem("海运费", "target", "set", 1330),
],
)
got = apply_adjust(src, ext, business_line="SEA")
self.assertTrue(got.ok)
self.assertEqual(got.quote["fee_total_polCostItems"], "1155.00")
self.assertEqual(got.quote["fee_total_oceanCostItems"], "9340.59")
self.assertEqual(got.quote["fee_total_podCostItems"], "480.00")
self.assertEqual(got.quote["total"], "7599.61")
self.assertFalse(got.currency_hint)
def test_local_extract_accepts_currency_before_target_amount(self) -> None:
"""「提高到CNY 585.00」本地回退也要能抽,不能因为币种夹在动词和数字中间就放弃。"""
names = ["订舱费(DCF)", "操作费", "舱单", "海运费", "文件费", "设备费"]
text = "始发港费用\n订舱费(DCF)提高到CNY 585.00\n海运费\n海运费提高到USD 1330.00"
got = extract_adjust(text, fee_names=names, allow_model=False)
self.assertTrue(got.is_adjust)
items = {(x.fee_name, x.kind, x.value) for x in got.items}
self.assertIn(("订舱费(DCF)", "target", 585.0), items)
self.assertIn(("海运费", "target", 1330.0), items)
def test_sea_pol_subtotal_and_total_up_ten_percent(self) -> None:
"""协同话术:始发港费用小计 + 费用合计 各提升 10%。"""
src = {
@@ -888,6 +944,105 @@ class SheetPriceStampTests(unittest.TestCase):
self.assertIn("28150", str(selected["legs"][0]["costPrice"]))
self.assertIn("28150", str(got.quote["feeItems"][0]["amount"]))
def test_product_merge_recomputes_sea_subtotals_and_total(self) -> None:
"""产品按行改海运混币种价:三段小计和合计都要跟销售调价一样自动增长。"""
from agent.policy.sea_group_ops import merge_quote_fees
base = {
"source": "TMS",
"source_label": "TMS标准报价",
"business_line": "SEA",
"currency": "CNY",
"total": "6952.77",
"fee_lines": [
{"name": "订舱费(DCF)", "amount": "500.00", "currency": "CNY"},
{"name": "操作费", "amount": "520.00", "currency": "CNY"},
{"name": "舱单", "amount": "50.00", "currency": "CNY"},
{"name": "海运费", "amount": "1250.00", "currency": "USD"},
{"name": "文件费", "amount": "450.00", "currency": "CNY"},
{"name": "设备费", "amount": "30.00", "currency": "CNY"},
],
"polCostItems": [
{"name": "订舱费(DCF)", "amount": "500.00", "currency": "CNY"},
{"name": "操作费", "amount": "520.00", "currency": "CNY"},
{"name": "舱单", "amount": "50.00", "currency": "CNY"},
],
"oceanCostItems": [
{"name": "海运费", "amount": "1250.00", "currency": "USD"},
],
"podCostItems": [
{"name": "文件费", "amount": "450.00", "currency": "CNY"},
{"name": "设备费", "amount": "30.00", "currency": "CNY"},
],
"fee_total_polCostItems": "1070.00",
"fee_total_oceanCostItems": "8778.75",
"fee_total_podCostItems": "480.00",
}
got = merge_quote_fees(
base,
{
"source_label": "产品报价",
"currency": "CNY",
"fee_lines": [
{"name": "订舱费(DCF)", "amount": "585.00", "currency": "CNY"},
{"name": "海运费", "amount": "1330.00", "currency": "USD"},
],
},
)
self.assertEqual(got["fee_total_polCostItems"], "1155.00")
self.assertEqual(got["fee_total_oceanCostItems"], "9340.59")
self.assertEqual(got["fee_total_podCostItems"], "480.00")
self.assertEqual(got["total"], "7599.61")
def test_manual_currency_follows_into_sheet_copies(self) -> None:
"""2026-11-22 真机:产品报「文件费USD 60」,报价单副本必须写 USD,不能留 TMS 的 CNY。"""
from agent.policy.sea_group_ops import merge_quote_fees
from agent.schema.quote_adjust import stamp_prices_for_sheet
base = {
"source": "TMS",
"currency": "CNY",
"total": "480",
"fee_lines": [{"name": "文件费", "amount": "450", "currency": "CNY"}],
"podCostItems": [{"name": "文件费", "amount": "450", "currency": "CNY"}],
"fee_total_podCostItems": "450",
}
merged = merge_quote_fees(
base,
{
"source_label": "产品报价",
"currency": "USD",
"fee_lines": [{"name": "文件费", "amount": "60.00", "currency": "USD"}],
},
)
pod = [x for x in merged["podCostItems"] if x.get("name") == "文件费"]
self.assertEqual(pod[0]["currency"], "USD")
self.assertEqual(pod[0]["amount"], "60.00")
air = stamp_prices_for_sheet(
{
"source_label": "产品报价",
"currency": "USD",
"total": "60",
"fee_lines": [{"name": "文件费", "amount": "60", "currency": "USD"}],
"airOptions": [
{"departureCharges": [{"chargeName": "文件费", "amount": "450", "currency": "CNY"}]}
],
}
)
self.assertEqual(air["airOptions"][0]["departureCharges"][0]["currency"], "USD")
land = stamp_prices_for_sheet(
{
"source_label": "产品报价",
"currency": "USD",
"total": "60",
"fee_lines": [{"name": "运输费", "amount": "60", "currency": "USD"}],
"landSegments": [{"origin": "A", "destination": "B", "costPrice": "450", "currency": "CNY"}],
}
)
self.assertEqual(land["landSegments"][0]["currency"], "USD")
def test_product_and_airline_sheet_copies_follow_new_fee(self) -> None:
from agent.policy.sea_group_ops import merge_quote_fees
from agent.schema.quote_adjust import stamp_prices_for_sheet
@@ -249,6 +249,41 @@ class QuoteTemplateMatchTests(unittest.TestCase):
self.assertEqual(hit.match_type, "keyword")
self.assertEqual(hit.name, "陆运国内运输拼车报价单")
def test_hk_ltl_not_stolen_by_domestic_ltl_aliases(self) -> None:
"""
中港零担/集拼不得被国内拼车模板的「零担/集拼」别名抢走(WO202611180001)。
"""
hit = pick_quote_template(
templates=[
{
"templateId": "dom",
"name": "陆运国内拼车报价单",
"bizType": "陆运",
"keywords": ["国内拼车", "国内零担", "拼车", "零担", "集拼"],
"isDefault": True,
},
{
"templateId": "hk",
"name": "陆运中港/亚/欧拼车报价模板",
"bizType": "陆运",
"keywords": ["中港拼车", "中港零担", "中港集拼"],
"isDefault": False,
},
],
business_line="LAND",
facts={
"运输类型": "中港零担/集拼",
"线路类别": "中港/中亚/中欧",
"运输分类": "普件(涉及国内+国外段)",
"起运港": "北京",
"目的港": "香港",
"品名": "茶叶",
},
)
self.assertIsNotNone(hit)
self.assertEqual(hit.name, "陆运中港/亚/欧拼车报价模板")
self.assertEqual(hit.match_type, "keyword")
def test_land_none_without_default(self) -> None:
hit = pick_quote_template(
templates=[
+346 -59
View File
@@ -137,7 +137,7 @@ class SeaTextInquiryTests(unittest.TestCase):
def test_handoff_word_creates_group_without_confirm_card(self) -> None:
"""
海运销售只说一句「转人工」:直接建正式单 + 建群 + 摘要。
海运销售只说一句「转人工」:直接建正式单 + 建群;群内摘要等 @BOT。
为什么测:改版前先回一张「是否拉产品人员进群协同」的确认卡,销售以为已经转好,
产品却还在等通知,报价就卡在私聊里。这条用例锁住「说了就算」,不再要求点按钮。
@@ -187,9 +187,10 @@ class SeaTextInquiryTests(unittest.TestCase):
self.assertTrue(created["name"].startswith("WO"), created["name"])
self.assertIn("p_sea_1", created["userids"])
self.assertIn("s-h-say", created["userids"])
# 群内要有摘要;私聊要有回执。
self.assertTrue(self.groups.sent)
self.assertIn("转人工", self.groups.sent[0]["content"])
# 产品口径(2026-11-20):建群后立即发字段摘要;不自动发表。
texts = [x.get("content") or "" for x in self.groups.sent if x.get("kind") == "text"]
self.assertTrue(any("询价字段" in t or "转人工" in t for t in texts))
self.assertFalse(any(x.get("kind") == "file" for x in self.groups.sent))
self.assertTrue(sess.handoff_committed)
self.assertEqual(sess.collab_chat_id, self.groups.next_chat_id)
@@ -351,9 +352,65 @@ class SeaTextInquiryTests(unittest.TestCase):
missing_keys=check["missing"],
transport_mode="海运",
)
self.assertIn("贸易条款(必填):\n(如:门到门、港到港)", text)
self.assertIn("贸易条款(必填):\n(如:门到门、港到港、门到港、港到门)", text)
self.assertNotIn("如:FOB", text)
def test_sea_trade_terms_list_has_four_options(self) -> None:
"""海运贸易条款四项(产品口径 2026-11-22):补问举例要全列,不能只列两项。"""
from agent.schema.sea_options import SEA_TRADE_TERMS, short_sea_trade_reply
self.assertEqual(SEA_TRADE_TERMS, ("门到门", "港到港", "门到港", "港到门"))
for term in SEA_TRADE_TERMS:
self.assertEqual(short_sea_trade_reply(term), term)
def test_sea_port_to_port_reply_is_class_not_trade_terms(self) -> None:
"""整句回 Port to Port 是运输分类,不能再被记成贸易条款(否则条款永远「已填」)。"""
from agent.schema.sea_options import short_sea_trade_reply
self.assertEqual(short_sea_trade_reply("Port to Port"), "")
self.assertEqual(short_sea_trade_reply("p2p"), "")
def test_sea_door_to_port_reply_becomes_trade_terms(self) -> None:
"""补问后只回门到港/港到门,同样记成贸易条款,运输分类不许被它顶掉。"""
first = dict(COMPLETE_SEA)
first.pop("贸易条款")
phase = drive_sea(
self.flow,
sender_id="s-door-port",
text="先缺条款",
reply=self._reply,
injected_facts=first,
injected_mode="SEA",
)
self.assertEqual(phase, "clarify")
self.replies.clear()
phase = drive_sea(self.flow, sender_id="s-door-port", text="门到港", reply=self._reply)
self.assertEqual(phase, "wait_collab")
sess = self.flow.session_of("s-door-port")
self.assertEqual(sess.facts.get("贸易条款"), "门到港")
self.assertEqual(sess.facts.get("运输分类"), "Port to Port")
def test_sea_port_to_door_in_long_sentence_and_optional_addresses(self) -> None:
"""一句话里有港到门和提货/派送地址:条款收下,地址是非必填但不丢。"""
facts = dict(COMPLETE_SEA)
facts.pop("贸易条款")
facts["提货地址"] = "深圳坪山仓库"
facts["收货地址"] = "洛杉矶仓"
text = "海运,上海到洛杉矶,条款港到门,提货地址:深圳坪山仓库,派送地址:洛杉矶仓"
phase = drive_sea(
self.flow,
sender_id="s-port-door",
text=text,
reply=self._reply,
injected_facts=facts,
injected_mode="SEA",
)
self.assertEqual(phase, "wait_collab")
sess = self.flow.session_of("s-port-door")
self.assertEqual(sess.facts.get("贸易条款"), "港到门")
self.assertEqual(sess.facts.get("提货地址"), "深圳坪山仓库")
self.assertEqual(sess.facts.get("收货地址"), "洛杉矶仓")
def test_sea_rejects_door_to_door_class(self) -> None:
facts = {
"起运港": "上海",
@@ -407,6 +464,146 @@ class SeaTextInquiryTests(unittest.TestCase):
self.assertLess(text.index("箱型箱量"), text.index("贸易条款"))
self.assertLess(text.index("贸易条款"), text.index("运输分类"))
def test_sea_confirm_card_hides_empty_optional_addresses(self) -> None:
"""海运核对卡:提货地址/派送地址非必填,没写不占行(不能出现空「非必填」行)。"""
text = copy.sea_confirm_card(
{
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "整柜",
"箱型箱量": "1x40HQ",
"贸易条款": "门到门",
"运输分类": "Port to Port",
"报价日期": "2026-11-22",
}
)
self.assertIn("贸易条款(必填):门到门", text)
self.assertNotIn("提货地址(非必填):", text)
self.assertNotIn("派送地址(非必填):", text)
self.assertIn(copy.SEA_CONFIRM_TAIL, text)
def test_sea_confirm_card_shows_filled_addresses(self) -> None:
"""写了地址就展示,方便销售核对门到门口径;派送地址对外就是这个叫法。"""
text = copy.sea_confirm_card(
{
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "整柜",
"箱型箱量": "1x40HQ",
"贸易条款": "港到门",
"运输分类": "Port to Port",
"报价日期": "2026-11-22",
"提货地址": "深圳坪山仓库",
"收货地址": "洛杉矶仓",
}
)
self.assertIn("提货地址(非必填):深圳坪山仓库", text)
self.assertIn("派送地址(非必填):洛杉矶仓", text)
self.assertNotIn("收货地址(非必填)", text)
def test_sea_clarify_echoes_addresses_without_requiring_them(self) -> None:
"""补问只「必填」才拦:已填地址只回显,未填的按(非必填)列在必填之后。"""
text = copy.ask_clarify(
facts={
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "整柜",
"箱型箱量": "1x40HQ",
"贸易条款": "门到港",
"提货地址": "深圳坪山仓库",
},
missing_keys=["运输分类"],
transport_mode="海运",
)
self.assertIn("提货地址(非必填):深圳坪山仓库", text)
self.assertIn("1.运输分类(必填)", text)
self.assertNotIn("派送地址(必填)", text)
self.assertNotIn("提货地址(必填)", text)
# 没填的派送地址与空运同口径,以(非必填)列在必填之后,不逼回复。
self.assertIn("2.派送地址(非必填):", text)
self.assertNotIn("2.派送地址(必填)", text)
def test_sea_clarify_lists_empty_addresses_as_optional(self) -> None:
"""产品口径(2026-11-22):海运补问要像空运一样把没填的提货/派送地址列出来。
位置在必填缺口之后,编号接着排,标「(非必填)」;示例单独一行且不算已填。
销售只回 1、2 两项必填也能通过校验(非必填不挡查价)。
"""
text = copy.ask_clarify(
facts={
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "整柜",
"箱型箱量": "1x40HQ",
"报价日期": "2026-11-22",
},
missing_keys=["贸易条款", "运输分类"],
transport_mode="海运",
)
self.assertIn("1.贸易条款(必填):", text)
self.assertIn("2.运输分类(必填):", text)
self.assertIn("3.提货地址(非必填):", text)
self.assertIn("4.派送地址(非必填):", text)
self.assertIn("(如:深圳坪山仓库)", text)
self.assertIn("(如:洛杉矶仓库)", text)
# 非必填不能写成必填,否则销售会以为不填就不给查价。
self.assertNotIn("提货地址(必填)", text)
self.assertNotIn("派送地址(必填)", text)
# 必填都在非必填之前,避免销售漏看。
self.assertLess(text.index("贸易条款(必填)"), text.index("提货地址(非必填)"))
# 只补两个必填,非必填留空照样能出核对卡。
out = validate_required_fields(
facts={
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "整柜",
"箱型箱量": "1x40HQ",
"贸易条款": "门到门",
"运输分类": "其他",
"报价日期": "2026-11-22",
},
business_line="SEA",
)
self.assertTrue(out["ok"], out.get("missing"))
def test_sea_inquiry_card_optional_address_lines(self) -> None:
"""建单摘要(也是群摘要正文):地址有值才多一行。"""
facts = {
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "整柜",
"箱型箱量": "1x40HQ",
"贸易条款": "门到门",
"运输分类": "Port to Port",
"报价日期": "2026-11-22",
}
text = "\n".join(copy.inquiry_field_lines(work_order_no="WO1", facts=facts, transport_mode="海运"))
self.assertNotIn("提货地址", text)
self.assertNotIn("派送地址", text)
text2 = "\n".join(
copy.inquiry_field_lines(
work_order_no="WO1",
facts={**facts, "提货地址": "深圳坪山仓库", "收货地址": "洛杉矶仓"},
transport_mode="海运",
)
)
self.assertIn("提货地址:深圳坪山仓库", text2)
self.assertIn("派送地址:洛杉矶仓", text2)
self.assertNotIn("提货地址:-", text2)
def test_clarify_asks_class_as_two_options(self) -> None:
text = copy.ask_clarify(
facts={
@@ -491,7 +688,9 @@ class SeaTextInquiryTests(unittest.TestCase):
)
self.assertEqual(phase, "wait_collab")
joined = "\n".join(self.replies)
self.assertIn("贸易条款:门到门", joined)
# 补问答案要落到会话事实里(字段只在核对卡展示,建单确认不再回显字段段)。
self.assertEqual(self.flow.session_of("s-door-reply").facts.get("贸易条款"), "门到门")
self.assertIn("正在查询TMS报价", joined)
self.assertNotIn("参数提取不全", joined)
def test_door_in_sentence_kept_after_choosing_sea(self) -> None:
@@ -631,8 +830,9 @@ class SeaTextInquiryTests(unittest.TestCase):
)
self.assertEqual(phase, "wait_collab")
joined = "\n".join(self.replies)
self.assertIn("运输分类:Port to Port", joined)
self.assertIn("贸易条款:FOB", joined)
# 补问答案要落到会话事实里(字段只在核对卡展示,建单确认不再回显字段段)。
self.assertEqual(self.flow.session_of("s-class").facts.get("运输分类"), "Port to Port")
self.assertIn("正在查询TMS报价", joined)
def test_complete_sea_inquiry_card_uses_ten_fields(self) -> None:
phase = drive_sea(self.flow,
@@ -644,18 +844,18 @@ class SeaTextInquiryTests(unittest.TestCase):
)
self.assertEqual(phase, "wait_collab")
joined = "\n".join(self.replies)
self.assertIn("运输方式:海运", joined)
self.assertIn("起运港:上海", joined)
self.assertIn("目的港:洛杉矶", joined)
self.assertIn("货物数量:20吨", joined)
self.assertIn("整柜或拼柜:整柜", joined)
self.assertIn("箱型箱量:1x40HQ", joined)
self.assertIn("贸易条款:FOB", joined)
self.assertIn("运输分类:Port to Port", joined)
self.assertIn("正在查询TMS报价", joined)
self.assertNotIn("件数:", joined.split("正在查询TMS报价")[0])
self.assertNotIn("本轮先开通空运", joined)
# 产品口径 2026-11-22:确定后只发工单号 + 正在查询TMS报价,
# 十项字段只在确定前的核对卡看,不再在建单确认里重复一遍。
sess = self.flow.session_of("s1")
cards = [r for r in self.replies if "工单已创建,正在查询TMS报价。" in r]
self.assertEqual(
cards[0],
f"工单号:{sess.work_order_no}\n工单已创建,正在查询TMS报价。",
)
self.assertNotIn("起运港:", cards[0])
self.assertNotIn("件数:", cards[0])
self.assertNotIn("本轮先开通空运", joined)
self.assertEqual(sess.business_line, "SEA")
self.assertEqual(sess.status, "已报价")
@@ -736,6 +936,80 @@ class SeaTmsCardTests(unittest.TestCase):
self.assertEqual(ready["missing"], [])
self.assertNotIn("件数", ready.get("missing") or [])
def test_sea_lcl_does_not_require_container_spec(self) -> None:
"""拼柜(散货/LCL)按体积计费:箱型箱量既不算缺项,也不进补问和核对卡。"""
facts = {
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "拼柜",
"贸易条款": "FOB",
"运输分类": "Port to Port",
"报价日期": "2026-11-22",
}
check = validate_required_fields(facts=facts, business_line="SEA")
self.assertTrue(check["ok"], check)
self.assertNotIn("箱型箱量", check["missing"])
ready = assemble_sea_query(check["facts"])
self.assertTrue(ready["ok"], ready)
self.assertNotIn("箱型箱量", ready["missing"])
card = copy.sea_confirm_card(check["facts"])
self.assertNotIn("箱型箱量", card)
self.assertIn("整柜或拼柜(必填):拼柜", card)
lines = copy.inquiry_field_lines(
work_order_no="WO202611220001", facts=check["facts"], transport_mode="海运"
)
self.assertFalse(any(line.startswith("箱型箱量") for line in lines))
# 回显也不出现箱型箱量这一栏
text = copy.ask_clarify(
facts={**check["facts"], "贸易条款": ""},
missing_keys=["贸易条款"],
transport_mode="海运",
)
self.assertNotIn("箱型箱量", text)
def test_sea_lcl_words_and_negation(self) -> None:
"""拼柜口语(拼箱/散货/LCL)都算拼柜;「非拼柜」按整柜,仍要箱型箱量。"""
from agent.schema.field_validate import is_sea_lcl
for load in ("拼柜", "拼箱", "散货", "LCL", "lcl 拼箱"):
self.assertTrue(is_sea_lcl(load), load)
for load in ("整柜", "非拼柜", "不拼柜", "", "FCL"):
self.assertFalse(is_sea_lcl(load), load)
facts = {
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "整柜",
"贸易条款": "FOB",
"运输分类": "Port to Port",
}
check = validate_required_fields(facts=facts, business_line="SEA")
self.assertFalse(check["ok"])
self.assertIn("箱型箱量", check["missing"])
def test_sea_fcl_switch_to_lcl_drops_stale_container(self) -> None:
"""先写 1x40HQ 又改口拼柜:箱型不挡查价,也不带进 TMS 出站。"""
facts = {
"起运港": "上海",
"目的港": "洛杉矶",
"品名": "普货",
"货量": "20吨",
"整柜或拼柜": "拼柜",
"箱型箱量": "1x40HQ",
"贸易条款": "FOB",
"运输分类": "Port to Port",
"报价日期": "2026-11-22",
}
check = validate_required_fields(facts=facts, business_line="SEA")
self.assertTrue(check["ok"], check)
ready = assemble_sea_query(check["facts"])
self.assertTrue(ready["ok"], ready)
self.assertNotIn("箱型箱量", ready["missing"])
self.assertNotIn("箱型箱量", copy.sea_confirm_card(check["facts"]))
def test_assemble_requires_trade_terms_not_class(self) -> None:
src = {
"起运港": "上海",
@@ -1053,20 +1327,10 @@ class SeaSkipAndPullTests(unittest.TestCase):
self.assertIn("prod1", self.groups.created[0]["userids"])
self.assertIn("s1", self.groups.created[0]["userids"])
self.assertNotIn("AI001", self.groups.created[0]["userids"])
self.assertTrue(self.groups.sent)
group_text = self.groups.sent[0]["content"]
# 激活建群只发摘要:空白/填价模板要销售或商务说「生成报价单」才出,
# 避免后台附件列堆满空表,也和空运激活口径一致。
# 产品口径(2026-11-20):建群后立即发字段摘要;不发空白模板。
texts = [x.get("content") or "" for x in self.groups.sent if x.get("kind") == "text"]
self.assertTrue(texts, "拉群后应立即发字段摘要")
self.assertFalse(any(x.get("kind") == "file" for x in self.groups.sent))
self.assertIn(wo, group_text)
self.assertIn("起运港", group_text)
self.assertIn("贸易条款", group_text)
collab_block = group_text.split("协同补充字段:", 1)[-1].split("TMS报价:", 1)[0]
self.assertNotIn("贸易条款", collab_block)
self.assertIn("货好时间", collab_block)
self.assertIn("商品海关编码", group_text)
self.assertNotIn("HS编码", group_text)
self.assertIn("TMS", group_text)
sess = self.flow.session_of("s1")
self.assertNotIn(copy.BTN_PULL_COLLAB, sess.allowed)
self.assertNotIn(copy.BTN_SKIP_COLLAB, sess.allowed)
@@ -1103,13 +1367,14 @@ class SeaSkipAndPullTests(unittest.TestCase):
action=copy.BTN_PULL_COLLAB,
reply=self._reply,
)
group_text = "\n".join(
x.get("content") or "" for x in self.groups.sent if x.get("kind") == "text"
)
self.assertIn("是否含电:否", group_text)
# 建群立即发摘要;口播里的「是否含电:否」仍要写进协同字段。
texts = [x.get("content") or "" for x in self.groups.sent if x.get("kind") == "text"]
self.assertTrue(any("是否含电" in t for t in texts))
sess = self.flow.session_of("s1")
self.assertEqual(str((sess.collab_facts or {}).get("是否含电") or ""), "否")
def test_pull_sends_brief_without_sheet(self) -> None:
"""测服正式路径不注入 group_client:拉群仍要发出摘要,但激活不发模板。"""
"""测服正式路径不注入 group_client:拉群后发字段摘要,不发模板。"""
from unittest.mock import patch
live = FakeGroupClient()
@@ -1139,7 +1404,8 @@ class SeaSkipAndPullTests(unittest.TestCase):
reply=self._reply,
)
self.assertEqual(phase, "collab_group")
self.assertTrue(any(x.get("kind") == "text" for x in live.sent))
texts = [x.get("content") or "" for x in live.sent if x.get("kind") == "text"]
self.assertTrue(texts, "拉群后应立即发字段摘要")
self.assertFalse(any(x.get("kind") == "file" for x in live.sent))
def test_pull_group_includes_archive_bot(self) -> None:
@@ -1245,13 +1511,12 @@ class SeaSkipAndPullTests(unittest.TestCase):
action=copy.BTN_PULL_COLLAB,
reply=self._reply,
)
self.assertTrue(self.groups.sent)
group_text = self.groups.sent[0]["content"]
self.assertIn("TMS 暂无匹配报价", group_text)
self.assertNotIn("未查到合适报价", group_text)
self.assertIn("\n\n协同补充字段:\n", group_text)
self.assertIn("\n\nTMS报价:\n", group_text)
self.assertNotIn("确认报价", group_text)
# 建群发字段摘要;无价港也不能把 TMS 无价写成一张报价表。
texts = [x.get("content") or "" for x in self.groups.sent if x.get("kind") == "text"]
self.assertTrue(texts)
self.assertFalse(any(x.get("kind") == "file" for x in self.groups.sent))
ticket = self.ledger.get_ticket(work_order_no=self.flow.session_of("s1").work_order_no)
self.assertFalse(getattr(ticket, "quote", {}))
class SeaGroupCollabFieldTests(unittest.TestCase):
@@ -1437,7 +1702,7 @@ class SeaGroupCollabFieldTests(unittest.TestCase):
self.assertEqual(str(rows["燃油附加费"].get("amount") or ""), "15.00")
def test_land_hk_vehicle_tonnage_not_freight_amount(self) -> None:
"""中港陆运「运费10T:1700HKD」不能抽成运费=10;压夜/压日按运费比例不能进合计。"""
"""中港陆运「运费10T:1700HKD」落车型 10T + 运输费 1700/车;条款进备注。"""
from agent.llm.extract_text import extract_product_quote
text = (
@@ -1448,13 +1713,23 @@ class SeaGroupCollabFieldTests(unittest.TestCase):
quote = extract_product_quote(
text, business_line="LAND", transport_mode="陆运", baseline_currency="HKD"
)
rows = {str(x.get("name") or ""): x for x in (quote.get("fee_rows") or [])}
freight = rows.get("深圳--香港元朗运费") or {}
self.assertEqual(str(freight.get("amount") or ""), "1700")
self.assertEqual(str(freight.get("currency") or ""), "HKD")
self.assertEqual(str(rows.get("压夜按运费", {}).get("amount") or ""), "80%")
self.assertEqual(str(rows.get("压日按运费", {}).get("amount") or ""), "100%")
self.assertEqual(float(quote.get("total") or 0), 1700.0)
# 10T 是车型,1700 才是这台车的运费;不能把吨位 10 当运费。
self.assertEqual(dict(quote.get("vehicleRates") or {}), {"10T": "1700"})
self.assertEqual(str(quote.get("currency") or ""), "HKD")
self.assertEqual(str(quote.get("total") or ""), "1700")
rows = {
str(x.get("name") or ""): x for x in (quote.get("vehicle_fee_rows") or [])
}
self.assertEqual(str(rows.get("10T", {}).get("amount") or ""), "1700")
self.assertEqual(str(rows.get("10T", {}).get("unit") or ""), "车")
# 超时费/压夜压日/实报实销整段是备注条件,不能拆成 HKD 80/100 的费用行。
remark = str(quote.get("remark") or "")
self.assertIn("超时费:免等候2小时", remark)
self.assertIn("压夜按运费80%", remark)
self.assertIn("杂费实报实", remark)
fee_names = {str(x.get("name") or "") for x in (quote.get("fee_rows") or [])}
self.assertNotIn("压夜按运费", fee_names)
self.assertNotIn("压日按运费", fee_names)
self.assertNotEqual(str(quote.get("total") or ""), "190.0")
def test_land_multi_vehicle_rates_not_hq_fee(self) -> None:
@@ -1963,8 +2238,11 @@ class SeaGroupCopyTests(unittest.TestCase):
],
},
)
self.assertIn("TMS报价:\nTMS 暂无匹配报价", text)
self.assertIn("产品人员可通过“纯文字”告知新报价,或直接将新报价excel表发给智能体。", text)
# 产品 2026-11-22:TMS 无价但产品已手工报价,整段 TMS 无价空话不再出现,
# 直接出「人工报价:」,销售看到的就是实价。
self.assertNotIn("TMS报价:", text)
self.assertNotIn("TMS 暂无匹配报价", text)
self.assertNotIn("产品人员可通过“纯文字”告知新报价", text)
self.assertIn("人工报价:\n海运费:USD 100.00\n燃油附加费:USD 15.00", text)
self.assertNotIn("确认报价", text)
self.assertNotIn("总销售价合计:USD 100.00", text)
@@ -2404,6 +2682,8 @@ class SeaGroupOpsTests(unittest.TestCase):
content="成交",
chat_id=chat,
chat_type="group",
# 建群时已建立当前单关联;BOT 群文字从 AIBOT 回调进入。
raw={"source": "aibot"},
),
RouteDecision(intent="ordinary_text_other"),
)
@@ -2671,8 +2951,8 @@ class SeaGroupOpsTests(unittest.TestCase):
self.assertEqual(str(names["码头操作费"].get("amount") or ""), "100")
self.assertEqual(str(names["海运费"].get("amount") or ""), "100.00")
def test_product_text_on_miss_is_manual_not_tms(self) -> None:
"""TMS 无价时产品文字报价:摘要 TMS 仍是暂无,人工报价两行齐全。"""
def test_product_text_on_miss_replaces_tms_block(self) -> None:
"""TMS 无价时产品文字报价:摘要不再说无价,直接给人工报价两行。"""
facts = dict(COMPLETE_SEA)
facts["目的港"] = "无价港"
drive_sea(self.flow,
@@ -2701,9 +2981,16 @@ class SeaGroupOpsTests(unittest.TestCase):
ledger=self.ledger,
)
self.assertEqual(phase, "product_quote_sent")
briefs = [x.get("content") or "" for x in self.groups.sent if x.get("kind") == "text"]
text = "\n".join(briefs)
self.assertIn("TMS 暂无匹配报价", text)
# 拉群那一刻还没人报价,那条「TMS 暂无匹配报价」摘要本身是对的;后面还有成交跟进等文字,
# 所以只挑最后一条带「询价字段:」的摘要来验。
briefs = [
x.get("content") or ""
for x in self.groups.sent
if x.get("kind") == "text" and "询价字段:" in (x.get("content") or "")
]
text = briefs[-1]
# 产品已在群里报了价:摘要只给人工报价,不再重复「TMS 暂无匹配报价」。
self.assertNotIn("TMS 暂无匹配报价", text)
self.assertIn("人工报价:", text)
self.assertIn("海运费:USD 100.00", text)
self.assertIn("燃油附加费:USD 15.00", text)