Files
inquiry_robot/inquiry-agent/tests/test_quote_adjust.py
T
linmianxun bcaaf5d50d 空运按计费重改价不再把整票金额当单价,陆运多段费用行按段补线路名
- 空运调价:无数量时单价留空,避免出单按「单价×计费重」再乘一遍(WO202611250038 金额被放大)
- 报价模板:unit_price 只取单价字段,amount 仅作行合计,不再回退成单价
- 陆运一条线路多段时,同名费用行按段号/腿号补「起运 → 目的」展示名,后台与前端一致,不改金额与原名匹配
- 同义词扫描先剥掉补问清单示例行,避免示例车型/口岸覆盖销售实填值;车型正则补平板/高栏/厢车/冷藏等后缀
- 补空运计费重、报价行、陆运线路标签相关单测
2026-12-06 09:25:35 +08:00

1720 lines
75 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
调价规则单测:比例、改到金额、币种合计、盖价、利润点。
不连企微 / TMS / 主账。
"""
from __future__ import annotations
import json
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.policy import inquiry_copy as copy
from agent.schema.quote_adjust import (
AdjustExtract,
AdjustItem,
adjustable_rows,
apply_adjust,
effective_quote,
extract_adjust,
parse_money,
private_session_can_adjust,
total_price_label,
)
def _quote(*rows, total="", currency="CNY"):
lines = [{"name": n, "amount": a, "currency": c} for n, a, c in rows]
return {
"total": total,
"currency": currency,
"fee_lines": lines,
"fee_rows": lines,
}
class QuoteAdjustTests(unittest.TestCase):
def test_percent_up_single_currency_updates_total(self) -> None:
src = _quote(("提货费", "1000", "CNY"), ("送货费", "200", "CNY"), total="1200")
ext = extract_adjust("提货费加 10%", fee_names=["提货费", "送货费"])
got = apply_adjust(src, ext, business_line="SEA", tms_cost="1200", tms_sale="1200")
self.assertTrue(got.ok)
self.assertEqual(got.code, "applied")
self.assertEqual(got.quote["fee_rows"][0]["amount"], "1100.00")
self.assertEqual(str(got.quote["total"]), "1300.00")
self.assertFalse(got.currency_hint)
def test_increase_to_percent_is_set_not_up(self) -> None:
"""「运输费用增加到110%」= 原价×1.1,不是上调 110%(×2.1)。"""
src = _quote(("运输费", "CNY 7500.00", "CNY"), total="CNY 7500.00")
ext = extract_adjust(
"运输费用增加到110%",
fee_names=["运输费"],
allow_model=False,
)
self.assertTrue(ext.is_adjust)
self.assertEqual(len(ext.items), 1)
self.assertEqual(ext.items[0].kind, "percent")
self.assertEqual(ext.items[0].direction, "set")
self.assertEqual(ext.items[0].value, 110.0)
got = apply_adjust(src, ext, business_line="LAND", tms_cost="7500")
self.assertTrue(got.ok)
self.assertEqual(got.quote["fee_rows"][0]["amount"], "CNY 8250.00")
self.assertEqual(str(got.quote["total"]), "CNY 8250.00")
self.assertIn("调到 110%", got.applied[0]["how"])
def test_spoken_yunfei_matches_yunshufei(self) -> None:
"""陆运只有「运输费」,销售说「运费CNY1000」:明细和合计都改(需求例①)。"""
src = _quote(("运输费", "110", "CNY"), total="110")
ext = extract_adjust(
"运费CNY1000", fee_names=["运输费"], allow_model=False, allow_bare=True
)
self.assertTrue(ext.is_adjust)
self.assertEqual(ext.items[0].fee_name, "运费")
got = apply_adjust(src, ext, business_line="LAND")
self.assertTrue(got.ok)
self.assertEqual(got.quote["fee_rows"][0]["amount"], "1000.00")
self.assertEqual(str(got.quote["total"]), "1000.00")
def test_bare_fee_amount_is_not_adjust_in_intent_precheck(self) -> None:
"""群意图预判不开 allow_bare:产品写「码头操作费100CNY」是报价,不是调价。"""
ext = extract_adjust(
"码头操作费100CNY", fee_names=["码头操作费"], allow_model=False
)
self.assertFalse(ext.is_adjust)
def test_sea_yunfei_matches_haiyunfei_and_uses_fx(self) -> None:
"""海运只有一个运费项目时,「运费USD1000」对上海运费,按 TMS 汇率重算合计。"""
src = _quote(
("海运费", "900", "USD"),
("文件费", "200", "CNY"),
total="7200",
currency="CNY",
)
src["fxRates"] = [{"fromCurrency": "USD", "toCurrency": "CNY", "rate": "7.0"}]
ext = extract_adjust(
"运费USD1000", fee_names=["海运费", "文件费"], allow_model=False, allow_bare=True
)
got = apply_adjust(src, ext, business_line="SEA")
self.assertTrue(got.ok)
names = {r["name"]: r["amount"] for r in got.quote["fee_rows"]}
self.assertEqual(names["海运费"], "1000.00")
self.assertEqual(str(got.quote["total"]), "7900.00")
self.assertFalse(got.currency_hint)
def test_two_rows_both_match_yunfei_asks_which(self) -> None:
"""两项都能简化成「运费」时,必须列出项目名反问。"""
src = _quote(
("海运费", "1000", "USD"),
("空运费", "300", "USD"),
total="9100",
currency="CNY",
)
ext = extract_adjust(
"运费USD1000", fee_names=["海运费", "空运费"], allow_model=False, allow_bare=True
)
got = apply_adjust(src, ext, business_line="SEA")
self.assertFalse(got.ok)
self.assertEqual(got.code, "choose_item")
self.assertEqual([c["name"] for c in got.choices], ["海运费", "空运费"])
def test_foreign_line_delta_uses_tms_fx(self) -> None:
"""外币明细差额按 TMS 汇率折进人民币合计。"""
src = _quote(
("提货费", "100", "USD"),
("空运费", "2000", "CNY"),
total="2700",
currency="CNY",
)
src["fxRates"] = [{"fromCurrency": "USD", "toCurrency": "CNY", "rate": "7.0"}]
ext = extract_adjust("提货费加 10%", fee_names=["提货费", "空运费"], allow_model=False)
got = apply_adjust(src, ext, business_line="AIR")
self.assertTrue(got.ok)
names = {r["name"]: r["amount"] for r in got.quote["fee_rows"]}
self.assertEqual(names["提货费"], "110.00")
self.assertEqual(names["空运费"], "2000")
self.assertEqual(str(got.quote["total"]), "2770.00")
self.assertFalse(got.currency_hint)
def test_air_unit_price_percent_keeps_per_kg_not_line_total(self) -> None:
"""空运「单价增加到110%」:单价 19→20.9,行金额=20.9×162;禁止把合计写进单价。"""
src = {
"currency": "CNY",
"total": "3438",
"fee_rows": [
{
"name": "空运费",
"amount": "3078",
"currency": "CNY",
"unit": "KG",
"unit_price": "19",
"quantity": "162",
},
{
"name": "人工费",
"amount": "200",
"currency": "CNY",
"unit": "人",
"unit_price": "200",
"quantity": "1",
},
{
"name": "打板费",
"amount": "160",
"currency": "CNY",
"unit": "个",
"unit_price": "160",
"quantity": "1",
},
],
}
ext = extract_adjust(
"空运费单价增加到110%/KG",
fee_names=["空运费", "人工费", "打板费"],
allow_model=False,
)
got = apply_adjust(src, ext, business_line="AIR")
self.assertTrue(got.ok)
air = next(r for r in got.quote["fee_rows"] if r["name"] == "空运费")
self.assertEqual(air["amount"], "3385.80")
self.assertEqual(str(air.get("unit_price") or ""), "20.90")
self.assertNotEqual(str(air.get("unit_price") or ""), "3385.80")
def test_air_unit_percent_uses_chargeable_weight_when_qty_missing(self) -> None:
"""费用行无 quantity 时,用工单计费重:单价15→16.5,禁止把行合计写进单价。"""
src = {
"currency": "CNY",
"total": "38757.75",
"chargeableWeightKg": "2583.85",
"fee_rows": [
{
"name": "空运费",
"amount": "38757.75",
"currency": "CNY",
"unit": "KG",
"unit_price": "15",
"unitPrice": "15",
}
],
"selected_air_option": {
"chargeableWeightKg": 2583.85,
"airlineCode": "TH",
"feeItems": [
{
"chargeName": "空运费",
"unitPrice": 15,
"amount": 38757.75,
"unit": "KG",
"currency": "CNY",
}
],
},
}
ext = extract_adjust(
"空运费单价增加到110%/KG",
fee_names=["空运费"],
allow_model=False,
)
got = apply_adjust(src, ext, business_line="AIR")
self.assertTrue(got.ok)
air = next(r for r in got.quote["fee_rows"] if r["name"] == "空运费")
self.assertEqual(str(air.get("unit_price") or ""), "16.50")
self.assertNotEqual(str(air.get("unit_price") or ""), "42633.53")
amt, _ = parse_money(air.get("amount"))
self.assertAlmostEqual(float(amt or 0), 42633.525, places=2)
def test_air_total_only_uses_chargeable_weight_for_unit_price(self) -> None:
"""只改费用合计(空运只有一行):单价按计费重反算,禁止把费用合计写进单价。"""
src = {
"currency": "CNY",
"total": "9700",
"chargeableWeightKg": "833.5",
"fee_rows": [
{
"name": "空运费",
"amount": "9700",
"currency": "CNY",
"unit": "KG",
"unit_price": "12",
}
],
}
ext = AdjustExtract(
is_adjust=True,
wants_total=True,
items=[AdjustItem("", "target", "set", 10543.77)],
)
got = apply_adjust(src, ext, business_line="AIR")
self.assertTrue(got.ok)
air = next(r for r in got.quote["fee_rows"] if r["name"] == "空运费")
self.assertEqual(air["amount"], "10543.77")
self.assertEqual(str(air.get("quantity") or ""), "833.5")
self.assertEqual(str(air.get("unit_price") or ""), "12.65")
self.assertNotEqual(str(air.get("unit_price") or ""), "10543.77")
def test_air_total_only_without_quantity_leaves_unit_price_blank(self) -> None:
"""报价没有计费重:只改合计时单价留空,交给出单按体积重反算,不写行合计。"""
src = {
"currency": "CNY",
"total": "9700",
"fee_rows": [
{
"name": "空运费",
"amount": "9700",
"currency": "CNY",
"unit": "KG",
"unit_price": "12",
}
],
}
ext = AdjustExtract(
is_adjust=True,
wants_total=True,
items=[AdjustItem("", "target", "set", 10543.77)],
)
got = apply_adjust(src, ext, business_line="AIR")
self.assertTrue(got.ok)
air = next(r for r in got.quote["fee_rows"] if r["name"] == "空运费")
self.assertEqual(air["amount"], "10543.77")
self.assertFalse(str(air.get("unit_price") or "").strip())
self.assertFalse(str(air.get("unitPrice") or "").strip())
def test_air_named_target_without_quantity_keeps_total_out_of_unit_price(self) -> None:
"""点名改空运费但拿不到计费重:金额照改,单价不能变成整票金额。"""
src = {
"currency": "CNY",
"total": "9700",
"fee_rows": [
{
"name": "空运费",
"amount": "9700",
"currency": "CNY",
"unit": "KG",
"unit_price": "12",
}
],
}
ext = AdjustExtract(
is_adjust=True,
items=[AdjustItem("空运费", "target", "set", 10543.77)],
)
got = apply_adjust(src, ext, business_line="AIR")
self.assertTrue(got.ok)
air = next(r for r in got.quote["fee_rows"] if r["name"] == "空运费")
self.assertEqual(air["amount"], "10543.77")
self.assertFalse(str(air.get("unit_price") or "").strip())
def test_air_merge_fee_derives_unit_price_from_quantity(self) -> None:
"""群里航线报「空运费 10543.77」:有计费重时单价=金额÷计费重,不写整票金额。"""
from agent.policy.sea_group_ops import merge_quote_fees
base = {
"source": "TMS",
"currency": "CNY",
"total": "9700",
"chargeableWeightKg": "833.5",
"fee_rows": [
{
"name": "空运费",
"amount": "9700",
"currency": "CNY",
"unit": "KG",
"unit_price": "12",
"quantity": "833.5",
}
],
}
merged = merge_quote_fees(
base,
{"fee_lines": [{"name": "空运费", "amount": "10543.77"}], "source_label": "航线报价"},
business_line="AIR",
)
air = next(r for r in merged["fee_rows"] if r["name"] == "空运费")
self.assertEqual(air["amount"], "10543.77")
self.assertEqual(str(air.get("unit_price") or ""), "12.65")
self.assertNotEqual(str(air.get("unit_price") or ""), "10543.77")
def test_air_merge_fee_without_quantity_leaves_unit_price_blank(self) -> None:
"""群里航线只报整票金额、行上没有计费重:单价留空,出单再按计费重反算。"""
from agent.policy.sea_group_ops import merge_quote_fees
base = {
"source": "TMS",
"currency": "CNY",
"total": "9700",
"fee_rows": [
{"name": "空运费", "amount": "9700", "currency": "CNY", "unit": "KG", "unit_price": "12"}
],
}
merged = merge_quote_fees(
base,
{"fee_lines": [{"name": "空运费", "amount": "10543.77"}], "source_label": "航线报价"},
business_line="AIR",
)
air = next(r for r in merged["fee_rows"] if r["name"] == "空运费")
self.assertEqual(air["amount"], "10543.77")
self.assertFalse(str(air.get("unit_price") or "").strip())
def test_model_up_coerced_when_text_says_to_percent(self) -> None:
"""模型误抽成 up 时,按原话「增加到X%」纠正为 set。"""
src = _quote(("运输费", "7500", "CNY"), total="7500")
injected = {
"is_adjust": True,
"wants_total": False,
"items": [{"fee_name": "运输费", "kind": "percent", "direction": "up", "value": 110}],
}
ext = extract_adjust(
"运输费用增加到110%",
fee_names=["运输费"],
injected=injected,
allow_model=False,
)
self.assertEqual(ext.items[0].direction, "set")
got = apply_adjust(src, ext, business_line="LAND")
self.assertEqual(got.quote["fee_rows"][0]["amount"], "8250.00")
def test_to_percent_phrase_variants(self) -> None:
"""调整到/涨到/升到/增至/变为/上浮到 X% 一律按改到原价比例。"""
src = _quote(("运输费", "CNY 7500.00", "CNY"), total="CNY 7500.00")
phrases = (
"运输费调整到110%",
"运输费涨到110%",
"运输费升到110%",
"运输费增至110%",
"运输费变为110%",
"运输费上浮到110%",
)
for text in phrases:
with self.subTest(text=text):
ext = extract_adjust(text, fee_names=["运输费"], allow_model=False)
self.assertTrue(ext.is_adjust, text)
self.assertEqual(ext.items[0].kind, "percent", text)
self.assertEqual(ext.items[0].direction, "set", text)
got = apply_adjust(src, ext, business_line="LAND")
self.assertTrue(got.ok, text)
self.assertEqual(got.quote["fee_rows"][0]["amount"], "CNY 8250.00", text)
def test_percent_down_and_target_in_one_sentence(self) -> None:
src = _quote(("提货费", "1000", "CNY"), ("送货费", "200", "CNY"), total="1200")
ext = extract_adjust("提货费减 5%,送货费提升到 180 元", fee_names=["提货费", "送货费"])
got = apply_adjust(src, ext, business_line="LAND", tms_cost="1200")
self.assertTrue(got.ok)
names = {r["name"]: r["amount"] for r in got.quote["fee_rows"]}
self.assertEqual(names["提货费"], "950.00")
self.assertEqual(names["送货费"], "180.00")
def test_unspecified_quote_does_not_change(self) -> None:
src = _quote(("提货费", "1000", "CNY"), total="1000")
ext = extract_adjust("报价加 10%", fee_names=["提货费"])
got = apply_adjust(src, ext, business_line="AIR")
self.assertFalse(got.ok)
self.assertEqual(got.code, "need_fee")
self.assertEqual(src["fee_rows"][0]["amount"], "1000")
def test_single_line_same_currency_total_moves_line(self) -> None:
"""明细只有一项且币种与总价一致:改总价也改明细,不看出价是否相等。"""
src = _quote(("运输费", "110", "CNY"), total="200")
ext = extract_adjust("总销售价改为180CNY", fee_names=["运输费"], allow_model=False)
got = apply_adjust(src, ext, business_line="LAND")
self.assertTrue(got.ok)
self.assertEqual(str(got.quote["total"]), "180.00")
self.assertEqual(got.quote["fee_rows"][0]["amount"], "180.00")
self.assertFalse(got.lines_hint)
def test_single_line_same_currency_line_moves_total(self) -> None:
src = _quote(("运输费", "110", "CNY"), total="200")
ext = extract_adjust("运输费提升到 180", fee_names=["运输费"], allow_model=False)
got = apply_adjust(src, ext, business_line="LAND")
self.assertTrue(got.ok)
self.assertEqual(got.quote["fee_rows"][0]["amount"], "180.00")
self.assertEqual(str(got.quote["total"]), "180.00")
def test_single_line_other_currency_does_not_sync(self) -> None:
src = _quote(("运输费", "110", "USD"), total="200", currency="CNY")
ext = extract_adjust("总销售价改为180CNY", fee_names=["运输费"], allow_model=False)
got = apply_adjust(src, ext, business_line="LAND")
self.assertTrue(got.ok)
self.assertEqual(str(got.quote["total"]), "180.00")
self.assertEqual(got.quote["fee_rows"][0]["amount"], "110")
self.assertTrue(got.currency_hint)
self.assertFalse(got.lines_hint)
def test_multi_line_total_asks_which_item(self) -> None:
"""多项明细时只改合计:不替销售分摊,反问改哪一项(产品 2026-11-25)。"""
src = _quote(("提货费", "1000", "CNY"), ("送货费", "200", "CNY"), total="1200")
ext = extract_adjust("总销售价改为180CNY", fee_names=["提货费", "送货费"], allow_model=False)
got = apply_adjust(src, ext, business_line="LAND")
self.assertFalse(got.ok)
self.assertEqual(got.code, "choose_item")
self.assertEqual(len(got.choices), 2)
self.assertEqual(src["fee_rows"][0]["amount"], "1000")
self.assertEqual(str(src["total"]), "1200")
def test_multi_currency_named_usd_does_not_change_cny_total(self) -> None:
src = _quote(
("提货费", "100", "USD"),
("空运费", "2000", "CNY"),
total="2000",
currency="CNY",
)
ext = extract_adjust("提货费加 10%", fee_names=["提货费", "空运费"])
got = apply_adjust(src, ext, business_line="AIR", tms_sale="2000")
self.assertTrue(got.ok)
names = {r["name"]: r["amount"] for r in got.quote["fee_rows"]}
self.assertEqual(names["提货费"], "110.00")
self.assertEqual(names["空运费"], "2000")
self.assertEqual(str(got.quote["total"]), "2000")
self.assertTrue(got.currency_hint)
def test_multi_currency_same_ccy_line_updates_total(self) -> None:
"""总价是 CNY 时,改 CNY 行可以进合计;外币行才需要提示不做汇率。"""
src = _quote(
("提货费", "100", "USD"),
("空运费", "2000", "CNY"),
total="2000",
currency="CNY",
)
ext = extract_adjust("空运费加 10%", fee_names=["提货费", "空运费"], allow_model=False)
got = apply_adjust(src, ext, business_line="AIR")
self.assertTrue(got.ok)
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"]), "2200.00")
self.assertFalse(got.currency_hint)
def test_multi_currency_total_only_asks_which_item(self) -> None:
src = _quote(
("提货费", "100", "USD"),
("空运费", "2000", "CNY"),
total="2000",
currency="CNY",
)
ext = extract_adjust("总销售价改为180CNY", fee_names=["提货费", "空运费"], allow_model=False)
got = apply_adjust(src, ext, business_line="AIR")
self.assertFalse(got.ok)
self.assertEqual(got.code, "choose_item")
self.assertEqual(len(got.choices), 2)
def test_single_line_foreign_total_uses_tms_fx(self) -> None:
"""只有一项外币明细:改合计时按 TMS fxRates 反算明细,不再提示「不做汇率」。"""
src = _quote(("运输费", "100", "USD"), total="700", currency="CNY")
src["fxRates"] = [{"fromCurrency": "USD", "toCurrency": "CNY", "rate": "7.0"}]
ext = extract_adjust("总销售价改为1050CNY", fee_names=["运输费"], allow_model=False)
got = apply_adjust(src, ext, business_line="LAND")
self.assertTrue(got.ok)
self.assertEqual(got.quote["fee_rows"][0]["amount"], "150.00")
self.assertEqual(str(got.quote["total"]), "1050.00")
self.assertFalse(got.currency_hint)
def test_partial_unmatched_still_applies_matched(self) -> None:
src = _quote(("卸货费", "300", "CNY"), total="300")
ext = extract_adjust("卸货费加 10%,报关费减 5%", fee_names=["卸货费"])
got = apply_adjust(src, ext, business_line="SEA")
self.assertTrue(got.ok)
self.assertIn("报关费", got.unmatched)
self.assertEqual(got.quote["fee_rows"][0]["amount"], "330.00")
def test_none_matched(self) -> None:
src = _quote(("卸货费", "300", "CNY"), total="300")
ext = extract_adjust("报关费减 5%", fee_names=["卸货费"])
got = apply_adjust(src, ext, business_line="SEA")
self.assertFalse(got.ok)
self.assertEqual(got.code, "none_matched")
def test_sea_subtotal_and_bucket_lines(self) -> None:
src = {
"currency": "CNY",
"total": "2000",
"fee_lines": [
{"name": "操作费", "amount": "1000", "currency": "CNY"},
{"name": "箱单费", "amount": "200", "currency": "CNY"},
],
"polCostItems": [
{"name": "操作费", "amount": "1000", "currency": "CNY"},
{"name": "箱单费", "amount": "200", "currency": "CNY"},
],
"fee_total_polCostItems": "1200",
}
ext = AdjustExtract(
is_adjust=True,
items=[
AdjustItem("操作费", "percent", "up", 10),
AdjustItem("箱单费", "percent", "up", 5),
AdjustItem("始发港费用小计", "percent", "up", 12),
],
)
got = apply_adjust(src, ext, business_line="SEA")
self.assertTrue(got.ok)
self.assertEqual(got.unmatched, [])
names = {row["name"]: row["amount"] for row in got.quote["polCostItems"]}
self.assertEqual(names["操作费"], "1100.00")
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 = {
"currency": "CNY",
"total": "14300",
"fee_lines": [
{"name": "操作费", "amount": "1220", "currency": "CNY"},
{"name": "海运费", "amount": "USD 1250", "currency": "USD"},
],
"polCostItems": [
{"name": "操作费", "amount": "1220", "currency": "CNY"},
{"name": "箱单费", "amount": "50", "currency": "CNY"},
],
"oceanCostItems": [
{"name": "海运费", "amount": "1250", "currency": "USD"},
],
"podCostItems": [
{"name": "操作费", "amount": "240", "currency": "USD"},
],
"fee_total_polCostItems": "2335",
"fee_total_oceanCostItems": "8778.75",
"fee_total_podCostItems": "2985",
}
names = [str(r.get("name") or "") for r in adjustable_rows(src)]
text = "将始发港费用小计提升10%\n费用合计提升10%"
ext = extract_adjust(text, fee_names=names, allow_model=False)
self.assertTrue(ext.is_adjust)
fee_names = [x.fee_name for x in ext.items]
self.assertIn("始发港费用小计", fee_names)
self.assertIn("费用合计", fee_names)
# 即使模型误标 wants_total,有点名费目时也不能只改合计
ext.wants_total = True
got = apply_adjust(src, ext, business_line="SEA")
self.assertTrue(got.ok)
self.assertEqual(got.quote["fee_total_polCostItems"], "2568.50")
self.assertEqual(got.quote["total"], "15730.00")
body = copy.adjust_group_body(got.quote, business_line="SEA")
self.assertIn("始发港费用小计", body)
self.assertIn("海运费小计", body)
self.assertIn("目的港费用小计", body)
def test_same_fee_name_two_rows_asks_which(self) -> None:
"""同名两行(450/50):不能把两行一起改,先反问。"""
src = {
"currency": "USD",
"total": "500",
"fee_lines": [
{"name": "文件费", "amount": "450", "currency": "USD"},
{"name": "文件费", "amount": "50", "currency": "USD"},
],
"polCostItems": [
{"name": "文件费", "amount": "450", "currency": "USD"},
{"name": "文件费", "amount": "50", "currency": "USD"},
],
}
ext = AdjustExtract(is_adjust=True, items=[AdjustItem("文件费", "percent", "up", 10)])
got = apply_adjust(src, ext, business_line="SEA")
self.assertFalse(got.ok)
self.assertEqual(got.code, "choose_item")
self.assertEqual(len(got.choices), 2)
labels = " ".join(c["label"] for c in got.choices)
self.assertIn("450", labels)
self.assertIn("50", labels)
def test_picked_row_updates_only_that_row(self) -> None:
"""销售选第 2 项后,只改 50 那一行,另一行不动。"""
src = {
"currency": "USD",
"total": "500",
"fee_lines": [
{"name": "文件费", "amount": "450", "currency": "USD"},
{"name": "文件费", "amount": "50", "currency": "USD"},
],
"polCostItems": [
{"name": "文件费", "amount": "450", "currency": "USD"},
{"name": "文件费", "amount": "50", "currency": "USD"},
],
}
asked = apply_adjust(
src,
AdjustExtract(is_adjust=True, items=[AdjustItem("文件费", "percent", "up", 10)]),
business_line="SEA",
)
chosen = asked.choices[1]
got = apply_adjust(
src,
AdjustExtract(
is_adjust=True,
items=[AdjustItem("文件费", "percent", "up", 10, chosen["key"])],
),
business_line="SEA",
)
self.assertTrue(got.ok)
amounts = [row["amount"] for row in got.quote["polCostItems"]]
self.assertEqual(amounts, ["450", "55.00"])
self.assertEqual(got.quote["total"], "505.00")
def test_land_same_name_legs_ask_which_leg(self) -> None:
"""陆运两段都叫运输费:禁止两段一起改,反问是哪一段(WO202611220035)。"""
src = {
"business_line": "LAND",
"currency": "CNY",
"total": "10000",
"fee_lines": [
{"name": "运输费", "amount": "7000", "currency": "CNY"},
{"name": "运输费", "amount": "3000", "currency": "CNY"},
],
"landSegments": [
{"origin": "上海", "destination": "谅山", "costPrice": "7000", "segmentSequence": 1, "routeLegSequence": 1},
{"origin": "谅山", "destination": "河内", "costPrice": "3000", "segmentSequence": 1, "routeLegSequence": 2},
],
}
ext = AdjustExtract(is_adjust=True, items=[AdjustItem("运输费", "percent", "up", 10)])
got = apply_adjust(src, ext, business_line="LAND")
self.assertFalse(got.ok)
self.assertEqual(got.code, "choose_item")
labels = [c["label"] for c in got.choices]
self.assertEqual(len(labels), 2)
self.assertIn("上海 → 谅山", labels[0])
self.assertIn("谅山 → 河内", labels[1])
def test_land_picked_leg_updates_only_that_leg_and_total(self) -> None:
src = {
"business_line": "LAND",
"currency": "CNY",
"total": "10000",
"fee_lines": [
{"name": "运输费", "amount": "7000", "currency": "CNY"},
{"name": "运输费", "amount": "3000", "currency": "CNY"},
],
"landSegments": [
{"origin": "上海", "destination": "谅山", "costPrice": "7000", "segmentSequence": 1, "routeLegSequence": 1},
{"origin": "谅山", "destination": "河内", "costPrice": "3000", "segmentSequence": 1, "routeLegSequence": 2},
],
}
asked = apply_adjust(
src,
AdjustExtract(is_adjust=True, items=[AdjustItem("运输费", "percent", "up", 10)]),
business_line="LAND",
)
chosen = asked.choices[0]
got = apply_adjust(
src,
AdjustExtract(
is_adjust=True,
items=[AdjustItem("运输费", "percent", "up", 10, chosen["key"])],
),
business_line="LAND",
)
self.assertTrue(got.ok)
amounts = sorted(row["amount"] for row in got.quote["fee_lines"])
self.assertEqual(amounts, ["3000", "7700.00"])
costs = [leg["costPrice"] for leg in got.quote["landSegments"]]
self.assertEqual(costs, ["7700.00", "3000"])
self.assertEqual(got.quote["total"], "10700.00")
def test_line_and_total_together_is_rejected(self) -> None:
"""大原则:细项和费用合计不能同时调整。"""
src = _quote(("运输费", "1000", "CNY"), total="1000")
ext = AdjustExtract(
is_adjust=True,
items=[
AdjustItem("运输费", "target", "set", 900),
AdjustItem("费用合计", "target", "set", 900),
],
)
got = apply_adjust(src, ext, business_line="LAND")
self.assertFalse(got.ok)
self.assertEqual(got.code, "conflict")
def test_overlay_manual_wins(self) -> None:
tms = _quote(("运输费", "1000", "CNY"), ("卸货费", "200", "CNY"), total="1200")
manual = _quote(("卸货费", "300", "CNY"), ("配送费", "20", "CNY"), total="320")
merged = effective_quote(tms, manual)
names = {r["name"]: r["amount"] for r in merged["fee_rows"]}
self.assertEqual(names["运输费"], "1000")
self.assertEqual(names["卸货费"], "300")
self.assertEqual(names["配送费"], "20")
ext = extract_adjust("卸货费加 10%", fee_names=list(names))
got = apply_adjust(merged, ext, business_line="SEA", tms_cost="1200")
after = {r["name"]: r["amount"] for r in got.quote["fee_rows"]}
self.assertEqual(after["卸货费"], "330.00")
self.assertEqual(after["运输费"], "1000")
self.assertEqual(after["配送费"], "20")
def test_profit_sea_uses_cost(self) -> None:
src = _quote(("运输费", "1000", "CNY"), total="1000")
ext = extract_adjust("运输费提升到 1300 元", fee_names=["运输费"])
got = apply_adjust(src, ext, business_line="SEA", tms_cost="1000", tms_sale="1100")
self.assertAlmostEqual(got.profit_point or 0, 30.0)
def test_profit_air_uses_sale(self) -> None:
src = _quote(("空运费", "1000", "CNY"), total="1000")
ext = extract_adjust("空运费提升到 1100 元", fee_names=["空运费"])
got = apply_adjust(src, ext, business_line="AIR", tms_cost="800", tms_sale="1000")
self.assertAlmostEqual(got.profit_point or 0, 10.0)
def test_profit_uses_manual_not_tms_when_manual_exists(self) -> None:
"""有手工报价:利润点对手工价,不对 TMS。"""
src = _quote(("运输费", "800", "CNY"), total="800")
ext = extract_adjust("运输费提升到 1040 元", fee_names=["运输费"])
got = apply_adjust(src, ext, business_line="SEA", tms_cost="1000", tms_sale="1100")
self.assertAlmostEqual(got.profit_point or 0, 30.0)
def test_profit_air_manual_uses_manual(self) -> None:
src = _quote(("空运费", "2000", "CNY"), total="2000")
ext = extract_adjust("空运费提升到 2200 元", fee_names=["空运费"])
got = apply_adjust(src, ext, business_line="AIR", tms_cost="800", tms_sale="1000")
self.assertAlmostEqual(got.profit_point or 0, 10.0)
def test_profit_second_adjust_keeps_first_baseline(self) -> None:
src = _quote(("运输费", "1000", "CNY"), total="1000")
first = apply_adjust(
src,
extract_adjust("运输费提升到 1100 元", fee_names=["运输费"]),
business_line="LAND",
tms_cost="1000",
)
second = apply_adjust(
first.quote,
extract_adjust("运输费提升到 1300 元", fee_names=["运输费"]),
business_line="LAND",
)
self.assertAlmostEqual(second.profit_point or 0, 30.0)
def test_total_label_is_fee_total_for_every_line(self) -> None:
"""销售侧汇总一律叫费用合计,空运/海运/陆运、TMS/调价都一样。"""
self.assertEqual(total_price_label("AIR"), "费用合计")
self.assertEqual(total_price_label("SEA"), "费用合计")
self.assertEqual(total_price_label("LAND"), "费用合计")
self.assertEqual(total_price_label("", transport_mode="空运"), "费用合计")
self.assertEqual(total_price_label("", transport_mode="陆运"), "费用合计")
tms = {"source": "TMS", "source_label": "TMS标准报价"}
self.assertEqual(total_price_label("LAND", quote=tms), "费用合计")
self.assertEqual(total_price_label("SEA", quote={"source": "PRODUCT"}), "费用合计")
self.assertEqual(total_price_label("LAND", quote={"source": "SALES_ADJUST"}), "费用合计")
self.assertEqual(total_price_label("AIR", quote=tms), "费用合计")
def test_tms_land_card_uses_cost_not_sale(self) -> None:
q = _quote(("运输费", "121.00", "CNY"), total="121.00")
q["source"] = "TMS"
q["source_label"] = "TMS标准报价"
detail = copy.sea_tms_hit_wecom_payload(
work_order_no="WO202609200005", quote=q, business_line="LAND"
)
card = detail["template_card"]
self.assertEqual(card["source"]["desc"], "TMS标准报价")
# 卡片不再放费用合计引用条,总价口径由文字明细保证。
self.assertNotIn("quote_area", card)
text = copy.sea_quote_detail_text(
work_order_no="WO202609200005", quote=q, business_line="LAND"
)
self.assertIn("费用合计:CNY 121.00", text)
self.assertNotIn("总销售价", text)
scheme = copy.scheme_wecom_payload(
work_order_no="WO202609200005",
facts={"origin": "泉州市", "destination": "南京市"},
quote=q,
transport_mode="陆运",
)
self.assertEqual(scheme["template_card"]["source"]["desc"], "TMS标准报价")
# 方案卡不再放引用条或字段行,只留短标题和三个按钮。
self.assertNotIn("quote_area", scheme["template_card"])
self.assertNotIn("horizontal_content_list", scheme["template_card"])
deal = copy.deal_horizontal_rows(quote=q, business_line="LAND")
self.assertEqual(deal[0]["keyname"], "费用合计")
def test_adjust_confirm_uses_sale_total_name(self) -> None:
src = _quote(("运输费", "110", "CNY"), total="110")
land = apply_adjust(
src,
extract_adjust("总成本价改为100CNY", fee_names=["运输费"], allow_model=False),
business_line="LAND",
)
self.assertTrue(land.ok)
names = [x.get("name") for x in land.applied]
self.assertIn("费用合计", names)
self.assertNotIn("总销售价", names)
self.assertNotIn("总成本价", names)
text = copy.adjust_confirm(land.applied)
self.assertIn("费用合计在当前报价基础上", text)
body = copy.adjust_group_body(land.quote, business_line="LAND")
self.assertIn("费用合计:", body)
air = apply_adjust(
src,
extract_adjust("总销售价改为100CNY", fee_names=["运输费"], allow_model=False),
business_line="AIR",
)
self.assertIn("费用合计", [x.get("name") for x in air.applied])
note = copy.adjust_ledger_remark(land.applied)
self.assertTrue(note.startswith("销售调价:"))
self.assertIn("费用合计", note)
def test_quote_copy_uses_line_and_source_total_name(self) -> None:
sea = {
"total": "2287.65",
"currency": "CNY",
"source": "TMS",
"fee_rows": [{"name": "海运费", "amount": "100", "currency": "USD"}],
}
air = {
"total": "722.5",
"currency": "CNY",
"source": "TMS",
"fee_rows": [{"name": "空运费", "amount": "700", "currency": "CNY"}],
}
self.assertIn("费用合计:CNY 2287.65", copy.quote_area_fee_text(sea, business_line="SEA"))
self.assertIn("费用合计:CNY 722.5", copy.quote_area_fee_text(air, business_line="AIR"))
self.assertNotIn("总销售价合计", copy.quote_area_fee_text(air, business_line="AIR"))
self.assertNotIn("总销售价", copy.quote_area_fee_text(sea, business_line="SEA"))
self.assertNotIn("总成本价", copy.quote_area_fee_text(sea, business_line="SEA"))
self.assertIn("费用合计:CNY 2287.65", "\n".join(copy.quote_detail_lines(sea, business_line="SEA")))
rows = copy.deal_horizontal_rows(quote=air, business_line="AIR")
self.assertEqual(rows[0]["keyname"], "费用合计")
self.assertNotIn("时效", [x["keyname"] for x in rows])
land_rows = copy.deal_horizontal_rows(quote=sea, business_line="LAND")
self.assertEqual(land_rows[0]["keyname"], "费用合计")
self.assertIn("时效", [x["keyname"] for x in land_rows])
def test_adjust_cards_use_sales_adjust_not_tms(self) -> None:
"""调价后价格明细卡、方案卡必须写销售调价,禁止再套 TMS 标准报价。"""
q = _quote(("运输费", "121.00", "CNY"), total="121.00")
q["source"] = "SALES_ADJUST"
q["source_label"] = "销售调价"
detail = copy.sea_tms_hit_wecom_payload(
work_order_no="WO202609200004", quote=q, business_line="LAND"
)
card = detail["template_card"]
self.assertEqual(card["source"]["desc"], "销售调价")
self.assertNotIn("quote_area", card)
text = copy.sea_quote_detail_text(
work_order_no="WO202609200004", quote=q, business_line="LAND"
)
self.assertIn("费用合计:CNY 121.00", text)
self.assertNotIn("总成本价", text)
scheme = copy.scheme_wecom_payload(
work_order_no="WO202609200004",
facts={"origin": "泉州市", "destination": "南京市"},
quote=q,
transport_mode="陆运",
)
self.assertEqual(scheme["template_card"]["source"]["desc"], "销售调价")
self.assertNotIn("quote_area", scheme["template_card"])
self.assertNotIn("horizontal_content_list", scheme["template_card"])
def test_private_eligibility(self) -> None:
self.assertEqual(private_session_can_adjust("已报价", True, ""), "")
self.assertEqual(private_session_can_adjust("协商中", True, ""), "")
self.assertEqual(private_session_can_adjust("已报价", True, "chat1"), "already_collab")
self.assertEqual(private_session_can_adjust("已成交", True, ""), "closed")
self.assertEqual(private_session_can_adjust("询价中", False, ""), "no_quote")
def test_oral_aliases_not_hardcoded_phrase(self) -> None:
src = _quote(("提货费", "1000", "CNY"), total="1000")
ext = extract_adjust("提货费在现有报价基础上上调 8%", fee_names=["提货费"])
self.assertTrue(ext.is_adjust)
got = apply_adjust(src, ext, business_line="SEA")
self.assertEqual(got.quote["fee_rows"][0]["amount"], "1080.00")
def test_model_phrasing_not_in_local_fallback(self) -> None:
"""口令不写死:模型抽「往上抬一成」也能算;没注入时本地不得靠固定词硬认。"""
spoken = "把运费往上抬一成"
local = extract_adjust(spoken, fee_names=["运输费"], allow_model=False)
self.assertFalse(local.is_adjust)
ext = extract_adjust(
spoken,
fee_names=["运输费"],
injected={
"is_adjust": True,
"items": [{"fee_name": "运输费", "kind": "percent", "direction": "up", "value": 10}],
},
)
got = apply_adjust(_quote(("运输费", "1000", "CNY"), total="1000"), ext, business_line="LAND")
self.assertTrue(got.ok)
self.assertEqual(got.quote["fee_rows"][0]["amount"], "1100.00")
def test_a_route_contract_accepts_quote_adjust(self) -> None:
from agent.routing.deepseek_a import DeepSeekARouter
from agent.routing.ordered_actions import ACTION_INTENTS, parse_ordered_actions_arguments
self.assertEqual(ACTION_INTENTS.get("QUOTE_ADJUST"), "quote_adjust")
parsed = parse_ordered_actions_arguments(
{
"decision_id": "d-adj",
"intent": "quote_adjust",
"ordered_action": {
"action_type": "QUOTE_ADJUST",
"order": 1,
"target": {"work_order_no": "WO202609200002"},
"evidence": {"source_ref": "inbound:u1", "content_digest": "a" * 64},
},
}
)
self.assertEqual(parsed.to_route_decision().intent, "quote_adjust")
router = DeepSeekARouter.from_settings()
sys_msg, user_msg = router.build_messages(
text="报价上升10%",
sender_id="u1",
session_quoted=True,
fee_names=["运输费"],
work_order_no="WO202609200002",
)
self.assertIn("quote_adjust", sys_msg["content"])
self.assertIn("口令不写死", sys_msg["content"])
self.assertIn("session_quoted=true", user_msg["content"])
self.assertIn("运输费", user_msg["content"])
self.assertIn("WO202609200002", user_msg["content"])
def test_private_adjust_stamps_sales_adjust_on_session_quote(self) -> None:
"""书签和出卡必须带销售调价;不能只改主账、卡片仍用 TMS 来源。"""
from agent.policy.quote_adjust_ops import try_private_adjust
class _Sess:
status = "已报价"
phase = "wait_collab"
work_order_no = "WO202609200004"
business_line = "LAND"
collab_chat_id = ""
wait_version = 1
first_or_same = "first"
history_work_order_no = ""
quote = _quote(("运输费", "121.00", "CNY"), total="121.00")
tms_quote = {}
class _Flow:
def __init__(self) -> None:
self.emitted = None
self.saved = None
class _Ledger:
def upsert_product_quote(self, **kwargs):
_Flow.last = kwargs
return {"ok": True}
self.ledger = _Ledger()
def _save(self, sess) -> None:
self.saved = dict(sess.quote or {})
def _emit_sea_hit(self, reply, **kwargs) -> None:
self.emitted = kwargs
_Sess.quote["source"] = "TMS"
_Sess.quote["source_label"] = "TMS标准报价"
sess = _Sess()
flow = _Flow()
replies: list[str] = []
out = try_private_adjust(
flow,
sess,
"运输费提升到 150",
replies.append,
injected_adjust={
"is_adjust": True,
"items": [{"fee_name": "运输费", "kind": "target", "direction": "up", "value": 150}],
},
)
self.assertEqual(out, "wait_collab")
self.assertEqual(sess.quote.get("source_label"), "销售调价")
self.assertEqual(sess.quote.get("source"), "SALES_ADJUST")
self.assertEqual(flow.saved.get("source_label"), "销售调价")
self.assertEqual(flow.last["quote"].get("source_label"), "销售调价")
self.assertEqual(flow.last.get("kind"), "adjust")
self.assertEqual(flow.emitted["quote"].get("source_label"), "销售调价")
self.assertNotIn("TMS", str(flow.emitted["quote"].get("source_label") or ""))
self.assertEqual(str(sess.tms_quote.get("total") or ""), "121.00")
self.assertTrue(copy.quote_is_tms(sess.tms_quote))
self.assertFalse(copy.quote_is_tms(sess.quote))
def _private_adjust_sess(self):
class _Sess:
status = "已报价"
phase = "wait_collab"
work_order_no = "WO202611230001"
business_line = "LAND"
collab_chat_id = ""
wait_version = 1
first_or_same = "first"
history_work_order_no = ""
quote = _quote(("运输费", "1700.00", "CNY"), total="1700.00")
tms_quote = {}
class _Flow:
def __init__(self) -> None:
class _Ledger:
def upsert_product_quote(self, **kwargs):
return {"ok": True}
self.ledger = _Ledger()
def _save(self, sess) -> None:
pass
def _emit_sea_hit(self, reply, **kwargs) -> None:
pass
return _Sess(), _Flow()
def test_private_adjust_waits_for_confirm(self) -> None:
"""产品 2026-11-24:调价先回识别回执,回「确认」后才改价。"""
import os
os.environ["QUOTE_CONFIRM_ENABLED"] = "true"
try:
from agent.policy.quote_adjust_ops import try_private_adjust
sess, flow = self._private_adjust_sess()
sess.sender_id = "u_sales"
replies: list[str] = []
out = try_private_adjust(flow, sess, "运输费提升到150", replies.append)
self.assertEqual(out, "adjust_confirm_pending")
self.assertIn("我识别内容为", "\n".join(replies))
self.assertEqual(float(str(sess.quote.get("total"))), 1700.0)
replies2: list[str] = []
out2 = try_private_adjust(flow, sess, "确认", replies2.append)
self.assertEqual(out2, "wait_collab")
self.assertEqual(float(str(sess.quote.get("total"))), 150.0)
finally:
os.environ["QUOTE_CONFIRM_ENABLED"] = "false"
def test_private_adjust_partial_recognized_prompts_format(self) -> None:
"""「运输费上调」没说幅度:回「我识别内容为…」并给调价格式。"""
from agent.policy.quote_adjust_ops import try_private_adjust
sess, flow = self._private_adjust_sess()
replies: list[str] = []
out = try_private_adjust(flow, sess, "运输费上调", replies.append)
self.assertEqual(out, "adjust_partial_recognized")
body = "\n".join(replies)
self.assertIn("我识别内容为", body)
self.assertIn("费用名:运输费", body)
self.assertIn("调整方式:上调", body)
self.assertIn("调整幅度或目标金额", body)
self.assertIn("海运费上调10%", body)
def test_private_adjust_none_recognized_prompts_format(self) -> None:
"""「报价调整一下」完全没信息:回无法识别 + 调价格式。"""
from agent.policy.quote_adjust_ops import try_private_adjust
sess, flow = self._private_adjust_sess()
replies: list[str] = []
out = try_private_adjust(flow, sess, "报价调整一下", replies.append)
self.assertEqual(out, "adjust_not_recognized")
self.assertIn("我无法识别您的内容", replies[-1])
self.assertIn("海运费上调10%", replies[-1])
def test_private_adjust_chatter_still_falls_through(self) -> None:
"""「这个价格再谈谈」不是调价,不能乱回调价提示。"""
from agent.policy.quote_adjust_ops import try_private_adjust
sess, flow = self._private_adjust_sess()
replies: list[str] = []
out = try_private_adjust(flow, sess, "这个价格再谈谈", replies.append)
self.assertIsNone(out)
self.assertEqual(replies, [])
def test_private_air_adjust_emits_facts_so_cargo_not_blank(self) -> None:
"""空运私聊调价出卡必须带 sess.facts,否则起运地/品名会整段变「-」。"""
from agent.policy.quote_adjust_ops import try_private_adjust
class _Sess:
status = "已报价"
phase = "wait_collab"
work_order_no = "WO202610280072"
business_line = "AIR"
collab_chat_id = ""
wait_version = 1
first_or_same = "first"
history_work_order_no = ""
facts = {
"起运地": "南京",
"目的地": "吉隆坡",
"品名": "普货",
"件数": "15",
"毛重": "2403",
"体积": "15.5",
"包装类型": "托盘",
}
quote = {
"currency": "CNY",
"total": "38757.75",
"chargeableWeightKg": "2583.85",
"fee_rows": [
{
"name": "空运费",
"amount": "38757.75",
"currency": "CNY",
"unit": "KG",
"unit_price": "15",
}
],
}
tms_quote = {}
class _Flow:
def __init__(self) -> None:
self.emitted = None
class _Ledger:
def upsert_product_quote(self, **kwargs):
return {"ok": True}
self.ledger = _Ledger()
def _save(self, sess) -> None:
return None
def _emit_air_hit(self, reply, **kwargs) -> None:
self.emitted = kwargs
sess = _Sess()
flow = _Flow()
out = try_private_adjust(
flow,
sess,
"空运费单价增加到110%/KG",
lambda *_a, **_k: None,
injected_adjust={
"is_adjust": True,
"items": [
{
"fee_name": "空运费",
"kind": "percent",
"direction": "set",
"value": 110,
}
],
},
)
self.assertEqual(out, "wait_collab")
self.assertIsNotNone(flow.emitted)
facts = dict(flow.emitted.get("facts") or {})
self.assertEqual(facts.get("起运地"), "南京")
self.assertEqual(facts.get("品名"), "普货")
air = next(r for r in sess.quote["fee_rows"] if r["name"] == "空运费")
self.assertEqual(str(air.get("unit_price") or ""), "16.50")
def test_group_brief_keeps_tms_when_current_is_adjust(self) -> None:
"""拉群摘要:TMS 段必须是原价,调后价另写销售调价,禁止替换。"""
tms = _quote(("运输费", "110.00", "CNY"), total="110.00")
tms["source"] = "TMS"
tms["source_label"] = "TMS标准报价"
adj = _quote(("运输费", "100.00", "CNY"), total="100.00")
adj["source"] = "SALES_ADJUST"
adj["source_label"] = "销售调价"
text = copy.sea_group_brief(
work_order_no="WO202609200006",
facts={"起运地": "泉州市", "目的地": "南京市", "品名": "普货"},
quote=adj,
collab_facts={},
sales_name="销售",
product_names=["产品"],
has_price=True,
tms_quote=tms,
transport_mode="陆运",
)
tms_block = text.split("TMS报价:", 1)[1]
self.assertIn("费用合计:CNY 110.00", tms_block.split("销售调价:", 1)[0])
self.assertIn("销售调价:", text)
self.assertIn("费用合计:CNY 100.00", text.split("销售调价:", 1)[1])
self.assertNotIn("费用合计:CNY 100.00", tms_block.split("销售调价:", 1)[0])
def test_group_brief_adjust_alone_does_not_become_tms(self) -> None:
"""没单独传入 TMS 时,调后价也不能写进 TMS 段。"""
adj = _quote(("运输费", "100.00", "CNY"), total="100.00")
adj["source"] = "SALES_ADJUST"
adj["source_label"] = "销售调价"
text = copy.sea_group_brief(
work_order_no="WO202609200006",
facts={"起运地": "泉州市", "目的地": "南京市"},
quote=adj,
collab_facts={},
sales_name="销售",
product_names=[],
has_price=True,
transport_mode="陆运",
)
self.assertIn("TMS报价:\nTMS 暂无匹配报价,请产品人工文字补充报价", text)
self.assertNotIn("纯文字", text)
self.assertIn("销售调价:", text)
self.assertIn("费用合计:CNY 100.00", text.split("销售调价:", 1)[1])
class SheetPriceStampTests(unittest.TestCase):
"""报价单读的是线路表和舱位明细,不是只读 fee_lines。"""
def test_sales_adjust_writes_land_route_copies(self) -> None:
src = {
"source": "TMS",
"source_label": "TMS标准报价",
"currency": "CNY",
"total": "CNY 16500",
"fee_lines": [{"name": "运输费", "amount": "16500.00", "currency": "CNY"}],
"feeItems": [{"feeName": "运输费", "amount": 16500.0, "currency": "CNY"}],
"landSegments": [
{"origin": "上海", "destination": "谅山", "costPrice": 16500.0, "currency": "CNY"}
],
"route_rows": [
{
"origin": "上海",
"destination": "谅山",
"costPrice": "16500.00",
"amount": "16500.00",
}
],
"selected_land_route": json.dumps(
{"legs": [{"origin": "上海", "destination": "谅山", "costPrice": 16500.0}]},
ensure_ascii=False,
),
}
got = apply_adjust(
src,
extract_adjust("运输费改为28150", fee_names=["运输费"], allow_model=False),
business_line="LAND",
tms_cost="16500",
tms_sale="16500",
)
self.assertTrue(got.ok)
self.assertIn("28150", str(got.quote["route_rows"][0]["amount"]))
self.assertIn("28150", str(got.quote["route_rows"][0]["costPrice"]))
self.assertIn("28150", str(got.quote["landSegments"][0]["costPrice"]))
selected = json.loads(got.quote["selected_land_route"])
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
base = {
"source": "TMS",
"source_label": "TMS标准报价",
"currency": "CNY",
"total": "16500",
"fee_lines": [{"name": "运输费", "amount": "16500", "currency": "CNY"}],
"route_rows": [{"costPrice": "16500", "amount": "16500"}],
"oceanCostItems": [{"name": "海运费", "amount": "100", "currency": "USD"}],
}
merged = merge_quote_fees(
base,
{"fee_lines": [{"name": "运输费", "amount": "18000"}], "source_label": "产品报价"},
)
self.assertIn("18000", str(merged["route_rows"][0]["amount"]))
self.assertEqual(merged["source_label"], "产品报价")
air = stamp_prices_for_sheet(
{
"source_label": "航线报价",
"total": "900",
"currency": "CNY",
"fee_lines": [{"name": "空运费", "amount": "900", "currency": "CNY"}],
"airOptions": [
{
"salePrice": "7918.25",
"departureCharges": [
{"chargeName": "空运费", "unitPrice": "1000", "amount": "1000"}
],
}
],
}
)
self.assertEqual(air["airOptions"][0]["salePrice"], "900")
self.assertIn("900", str(air["airOptions"][0]["departureCharges"][0]["amount"]))
kept = stamp_prices_for_sheet(
{
"source_label": "航线确认TMS",
"total": "200",
"fee_lines": [{"name": "增点费", "amount": "200"}],
"airOptions": [
{
"salePrice": "7918.25",
"departureCharges": [{"chargeName": "增点费", "unitPrice": "100", "amount": "100"}],
}
],
}
)
self.assertEqual(kept["airOptions"][0]["salePrice"], "7918.25")
self.assertEqual(kept["airOptions"][0]["departureCharges"][0]["amount"], "100")
def test_air_fee_items_copy_uses_adjusted_unit_price(self) -> None:
"""顶层 feeItems 也是出单来源:调价后金额和每 KG 单价都要同步。"""
from agent.schema.quote_adjust import stamp_prices_for_sheet
quote = {
"source_label": "销售调价",
"total": "10543.77",
"currency": "CNY",
"fee_lines": [
{
"name": "空运费",
"amount": "10543.77",
"currency": "CNY",
"unit": "KG",
"quantity": "833.5",
"unit_price": "12.65",
}
],
"feeItems": [
{
"name": "空运费",
"amount": "9700",
"currency": "CNY",
"unit": "KG",
"quantity": "833.5",
"unitPrice": "12",
}
],
}
out = stamp_prices_for_sheet(quote)
item = out["feeItems"][0]
self.assertEqual(str(item["amount"]), "10543.77")
self.assertEqual(str(item.get("unitPrice")), "12.65")
self.assertEqual(str(item.get("unit_price")), "12.65")
def test_air_fee_items_copy_drops_total_when_unit_price_unknown(self) -> None:
"""计费重未知时费用行没有单价:顶层 feeItems 不能把整票金额当单价。"""
from agent.schema.quote_adjust import stamp_prices_for_sheet
quote = {
"source_label": "销售调价",
"total": "10543.77",
"currency": "CNY",
"fee_lines": [
{
"name": "空运费",
"amount": "10543.77",
"currency": "CNY",
"unit": "KG",
}
],
"feeItems": [
{
"name": "空运费",
"amount": "9700",
"currency": "CNY",
"unit": "KG",
"unitPrice": "12",
}
],
}
out = stamp_prices_for_sheet(quote)
item = out["feeItems"][0]
self.assertEqual(str(item["amount"]), "10543.77")
self.assertFalse(str(item.get("unitPrice") or "").strip())
self.assertFalse(str(item.get("unit_price") or "").strip())
def test_air_option_fee_items_follow_adjusted_fee(self) -> None:
"""舱位 feeItems 也是出单来源:调价后金额和每 KG 单价都要跟着改。"""
from agent.schema.quote_adjust import stamp_prices_for_sheet
quote = {
"source_label": "销售调价",
"total": "10543.77",
"currency": "CNY",
"fee_lines": [
{
"name": "空运费",
"amount": "10543.77",
"currency": "CNY",
"unit": "KG",
"quantity": "833.5",
"unit_price": "12.65",
}
],
"airOptions": [
{
"chargeableWeightKg": 833.5,
"feeItems": [
{
"feeName": "空运费",
"amount": 9700,
"unitPrice": 12,
"unit": "KG",
"quantity": 833.5,
"currency": "CNY",
}
],
}
],
}
out = stamp_prices_for_sheet(quote)
item = out["airOptions"][0]["feeItems"][0]
self.assertEqual(str(item["amount"]), "10543.77")
self.assertEqual(str(item.get("unitPrice")), "12.65")
self.assertEqual(str(item.get("unit_price")), "12.65")
def test_air_option_fee_items_drop_total_when_unit_price_unknown(self) -> None:
"""计费重未知:舱位副本金额照改,但不能把整票金额留着当单价。"""
from agent.schema.quote_adjust import stamp_prices_for_sheet
quote = {
"source_label": "销售调价",
"total": "10543.77",
"currency": "CNY",
"fee_lines": [
{
"name": "空运费",
"amount": "10543.77",
"currency": "CNY",
"unit": "KG",
}
],
"airOptions": [
{
"chargeableWeightKg": 833.5,
"feeItems": [
{
"feeName": "空运费",
"amount": 9700,
"unitPrice": 12,
"unit": "KG",
"quantity": 833.5,
"currency": "CNY",
}
],
}
],
}
out = stamp_prices_for_sheet(quote)
item = out["airOptions"][0]["feeItems"][0]
self.assertEqual(str(item["amount"]), "10543.77")
self.assertFalse(str(item.get("unitPrice") or "").strip())
self.assertFalse(str(item.get("unit_price") or "").strip())
class AdjustPickTests(unittest.TestCase):
"""反问「改哪一项」之后,销售回序号/段名的接续。"""
def _land_quote(self) -> dict:
return {
"business_line": "LAND",
"currency": "CNY",
"total": "18600",
"fee_lines": [
{"name": "运输费", "amount": "9000", "currency": "CNY"},
{"name": "运输费", "amount": "9600", "currency": "CNY"},
],
"landSegments": [
{"origin": "上海", "destination": "凉山-春疆货场", "costPrice": "9000", "segmentSequence": 1, "routeLegSequence": 1},
{"origin": "凉山-春疆货场", "destination": "胡志明", "costPrice": "9600", "segmentSequence": 1, "routeLegSequence": 2},
],
}
def test_choice_index_accepts_number_and_segment(self) -> None:
from agent.policy.quote_adjust_ops import _choice_index
src = self._land_quote()
got = apply_adjust(
src,
AdjustExtract(is_adjust=True, items=[AdjustItem("运输费", "target", "set", 8000)]),
business_line="LAND",
)
choices = got.choices
self.assertEqual(_choice_index("1", choices), 0)
self.assertEqual(_choice_index("第二项", choices), 1)
self.assertEqual(_choice_index("上海那段运输费", choices), 0)
self.assertEqual(_choice_index("胡志明", choices), 1)
# 只说「运输费」两个候选都命中,不能猜。
self.assertIsNone(_choice_index("运输费", choices))
def test_resume_pick_targets_chosen_leg(self) -> None:
from agent.policy.quote_adjust_ops import _resume_adjust_pick
src = self._land_quote()
asked = apply_adjust(
src,
AdjustExtract(is_adjust=True, items=[AdjustItem("运输费", "target", "set", 8000)]),
business_line="LAND",
)
pending = {
"kind": "adjust_pick",
"adjust": {
"is_adjust": True,
"wants_total": False,
"items": [
{"fee_name": "运输费", "kind": "target", "direction": "set", "value": 8000}
],
},
"item_index": 0,
"choices": asked.choices,
}
resumed, chosen = _resume_adjust_pick(pending, "1")
self.assertIsNotNone(resumed)
self.assertEqual(chosen["name"], "运输费")
self.assertEqual(resumed.items[0].target_key, asked.choices[0]["key"])
got = apply_adjust(src, resumed, business_line="LAND")
self.assertTrue(got.ok)
amounts = sorted(row["amount"] for row in got.quote["fee_lines"])
self.assertEqual(amounts, ["8000.00", "9600"])
self.assertEqual(got.quote["total"], "17600.00")
def test_choose_copy_lists_numbered_labels(self) -> None:
src = self._land_quote()
got = apply_adjust(
src,
AdjustExtract(is_adjust=True, items=[AdjustItem("运输费", "target", "set", 8000)]),
business_line="LAND",
)
text = copy.adjust_choose_item(got.choices, name="运输费")
self.assertIn("请具体告知要调整哪一项的价格", text)
self.assertIn("1. 上海 → 凉山-春疆货场 运输费", text)
self.assertIn("2. 凉山-春疆货场 → 胡志明 运输费", text)
if __name__ == "__main__":
unittest.main()