From bcaaf5d50d201d2d1e66d0fae26a275324544292 Mon Sep 17 00:00:00 2001 From: linmianxun <634841751@qq.com> Date: Sun, 6 Dec 2026 09:25:35 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A9=BA=E8=BF=90=E6=8C=89=E8=AE=A1=E8=B4=B9?= =?UTF-8?q?=E9=87=8D=E6=94=B9=E4=BB=B7=E4=B8=8D=E5=86=8D=E6=8A=8A=E6=95=B4?= =?UTF-8?q?=E7=A5=A8=E9=87=91=E9=A2=9D=E5=BD=93=E5=8D=95=E4=BB=B7=EF=BC=8C?= =?UTF-8?q?=E9=99=86=E8=BF=90=E5=A4=9A=E6=AE=B5=E8=B4=B9=E7=94=A8=E8=A1=8C?= =?UTF-8?q?=E6=8C=89=E6=AE=B5=E8=A1=A5=E7=BA=BF=E8=B7=AF=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 空运调价:无数量时单价留空,避免出单按「单价×计费重」再乘一遍(WO202611250038 金额被放大) - 报价模板:unit_price 只取单价字段,amount 仅作行合计,不再回退成单价 - 陆运一条线路多段时,同名费用行按段号/腿号补「起运 → 目的」展示名,后台与前端一致,不改金额与原名匹配 - 同义词扫描先剥掉补问清单示例行,避免示例车型/口岸覆盖销售实填值;车型正则补平板/高栏/厢车/冷藏等后缀 - 补空运计费重、报价行、陆运线路标签相关单测 --- inquiry-agent/agent/policy/air_group_ops.py | 4 +- inquiry-agent/agent/policy/sea_group_ops.py | 58 +++- inquiry-agent/agent/policy/synonym.py | 20 +- inquiry-agent/agent/schema/field_validate.py | 7 +- inquiry-agent/agent/schema/quote_adjust.py | 164 ++++++++--- inquiry-agent/tests/test_quote_adjust.py | 277 ++++++++++++++++++ inquiry-agent/tests/test_synonym.py | 27 ++ .../support/InquiryQuoteLineSupport.java | 234 ++++++++++++++- .../template/QuoteTemplateExcelSupport.java | 18 +- .../support/InquiryQuoteLineSupportTest.java | 61 ++++ .../template/AirChargeableWeightTest.java | 33 +++ .../src/views/inquiry/workOrder/index.vue | 6 +- .../views/inquiry/workOrder/quoteFeeLines.ts | 147 ++++++++++ inquiry-backend/tests/quoteFeeLines.spec.ts | 92 ++++++ 14 files changed, 1087 insertions(+), 61 deletions(-) create mode 100644 inquiry-backend/src/views/inquiry/workOrder/quoteFeeLines.ts create mode 100644 inquiry-backend/tests/quoteFeeLines.spec.ts diff --git a/inquiry-agent/agent/policy/air_group_ops.py b/inquiry-agent/agent/policy/air_group_ops.py index 3fafda8..911e7e6 100644 --- a/inquiry-agent/agent/policy/air_group_ops.py +++ b/inquiry-agent/agent/policy/air_group_ops.py @@ -1594,7 +1594,7 @@ def apply_air_quote( from agent.schema.quote_adjust import quote_fee_rows if quote_fee_rows(current): - quote = merge_quote_fees(current, quote) + quote = merge_quote_fees(current, quote, business_line="AIR") note = "" if recognition["status"] == "partial": note = copy.quote_partial_recognized( @@ -1732,7 +1732,7 @@ def apply_air_tms_choice( base = dict(view.get("quote") or {}) if keep_tms: if pending.get("fee_rows") or pending.get("fee_lines"): - merged = merge_quote_fees(base, pending) + merged = merge_quote_fees(base, pending, business_line="AIR") else: merged = dict(base) merged.update(pending) diff --git a/inquiry-agent/agent/policy/sea_group_ops.py b/inquiry-agent/agent/policy/sea_group_ops.py index ca26795..0faff36 100644 --- a/inquiry-agent/agent/policy/sea_group_ops.py +++ b/inquiry-agent/agent/policy/sea_group_ops.py @@ -2240,12 +2240,41 @@ def _match_fee_row(name: str, rows: list[dict[str, Any]]) -> int: return -1 -def _apply_fee_amount(row: dict[str, Any], amount: str) -> None: +_WEIGHT_UNITS = frozenset({"KG", "KGS", "KGM", "公斤", "千克"}) +_AIR_WEIGHT_NAMES = frozenset({"空运费", "空运费用", "空运运费", "空运"}) + + +def _is_air_weight_row(row: dict[str, Any]) -> bool: + """空运按计费重计价的行:单位 KG,或费目就是「空运费」。""" + unit = str(row.get("unit") or row.get("unitName") or row.get("chargeUnit") or "").strip().upper() + unit = unit.replace("/", "").replace("每", "") + if unit in _WEIGHT_UNITS: + return True + return str(row.get("name") or "").replace(" ", "") in _AIR_WEIGHT_NAMES + + +def _apply_fee_amount(row: dict[str, Any], amount: str, *, air_weight: bool = False) -> None: """ 产品改的是这一行卖价。金额、单价、salePrice 一起覆盖,避免报价单单价列还留着 TMS 旧价。 + + 空运计费行(air_weight)单价必须=金额÷数量:整票金额直接写进单价, + 出单会按「单价×计费重」再乘一遍(WO 截图的 8788232.30)。 + 数量未知时单价留空,交给出单按计费重反算。 """ row["amount"] = amount - row["unit_price"] = amount + if air_weight: + qty = _parse_fee_quantity(row.get("quantity") or row.get("chargeQuantity")) + amt = _parse_fee_amount(amount) + if qty is not None and abs(qty) > 1e-9 and amt is not None: + from agent.schema.quote_adjust import format_money + + row["unit_price"] = format_money(amt / qty) + row["unitPrice"] = row["unit_price"] + else: + row.pop("unit_price", None) + row.pop("unitPrice", None) + else: + row["unit_price"] = amount if row.get("salePrice") not in (None, ""): row["salePrice"] = amount if row.get("price") not in (None, ""): @@ -2254,6 +2283,16 @@ def _apply_fee_amount(row: dict[str, Any], amount: str) -> None: row["value"] = amount +def _parse_fee_quantity(raw: Any) -> float | None: + text = str(raw if raw not in (None, "") else "").strip().replace(",", "") + if not text or text == "-": + return None + try: + return float(text) + except ValueError: + return None + + def _parse_fee_amount(raw: Any) -> float | None: """抽出金额数字。带 USD/CNY 前缀或千分位也能读,读不了当没有。""" text = str(raw or "").strip().replace(",", "") @@ -2394,16 +2433,23 @@ def _align_wrong_default_freight( return out -def merge_quote_fees(base: dict[str, Any] | None, overlay: dict[str, Any] | None) -> dict[str, Any]: +def merge_quote_fees( + base: dict[str, Any] | None, + overlay: dict[str, Any] | None, + *, + business_line: str = "", +) -> dict[str, Any]: """ 产品按行改价盖到原 TMS 明细上。没点名的费用原样保留。 单价和金额一起改:模板先写 unit_price,只改 amount 的话报价单上看着还是旧价。 + 空运按计费重计价的行不能把整票金额写进单价(business_line=AIR 时按数量反算)。 合计按原 TMS 总价加减改过的行,不用产品两行之和冒充全单。 不编时效和有效期。 """ incoming = dict(overlay or {}) rows = _quote_fee_rows(base) + line = (business_line or str(incoming.get("business_line") or "")).upper() for item in incoming.get("fee_rows") or incoming.get("fee_lines") or []: if not isinstance(item, dict): continue @@ -2416,7 +2462,11 @@ def merge_quote_fees(base: dict[str, Any] | None, overlay: dict[str, Any] | None rows.append(dict(item)) continue old = dict(rows[idx]) - _apply_fee_amount(old, amount) + _apply_fee_amount( + old, + amount, + air_weight=(line == "AIR" and _is_air_weight_row(old)), + ) if item.get("currency"): old["currency"] = item.get("currency") # 盖价时一并写入单位/数量/分段:否则旧行默认「票」会盖住新抽到的「板」、 diff --git a/inquiry-agent/agent/policy/synonym.py b/inquiry-agent/agent/policy/synonym.py index 43664ca..5b6ffb0 100644 --- a/inquiry-agent/agent/policy/synonym.py +++ b/inquiry-agent/agent/policy/synonym.py @@ -674,6 +674,22 @@ def _value_pairs( return pairs +def _strip_prompt_examples(text: str) -> str: + """ + 补问清单里的示例行((如:…))不是销售填的值,原话扫描前先剥掉。 + + 运行证据:销售把补问清单整段复制回来、只在冒号后填值,示例行 + 「(如:9米6/1)」还在时,车型候选会把 18米平板 覆盖成 9.6高栏; + 通关口岸同理,示例里的友谊关会被当成真实候选。只影响扫描副本。 + """ + try: + from agent.schema.field_validate import _without_clarify_examples + + return _without_clarify_examples(text) + except Exception: + return text + + def _field_hits( field: str, text: str, @@ -684,7 +700,7 @@ def _field_hits( """字段命中的 (结束位置, internal);长词优先,数据和负向词由表控制。""" if _disabled(): return [] - raw = unicodedata.normalize("NFKC", str(text or "")) + raw = _strip_prompt_examples(unicodedata.normalize("NFKC", str(text or ""))) if not raw: return [] hits: list[tuple[int, str]] = [] @@ -780,7 +796,7 @@ def harvest_port_group(text: str, mode: str = "LAND") -> str: 组行由 inq_synonym 维护:通关口岸 VALUE,synonym 含「/」,internal 为组值。 长词优先;整组命中后不再拆成两个单口岸。 """ - raw = unicodedata.normalize("NFKC", str(text or "")) + raw = _strip_prompt_examples(unicodedata.normalize("NFKC", str(text or ""))) if not raw: return "" best_syn = "" diff --git a/inquiry-agent/agent/schema/field_validate.py b/inquiry-agent/agent/schema/field_validate.py index 88eb128..8eae62d 100644 --- a/inquiry-agent/agent/schema/field_validate.py +++ b/inquiry-agent/agent/schema/field_validate.py @@ -1073,7 +1073,12 @@ _RE_LAND_VEHICLE = re.compile( r"(?i)(?:" r"(?:20|40|45)\s*(?:HQ|GP|HC|NOR|RH|高柜|平柜)" r"(?:\s*[((][^))]{1,24}[))])?" - r"|(?:\d+(?:\.\d+)?)\s*米\s*[0-9六]?(?:\s*[//xX×*]\s*\d+)?" + # 米数后面紧跟中文车型词时必须一起收(18米平板、9.6米高栏), + # 否则只截到「18米」,核对卡和 TMS 都丢了平板。 + r"|(?:\d+(?:\.\d+)?)\s*米\s*[0-9六]?" + r"(?:\s*(?:低平板|平板|高栏|厢车|冷藏车?|气垫车?|尾板车?))?" + r"(?:\s*[((](?:带尾板|尾板|冷藏|危险品)[))])?" + r"(?:\s*[//xX×*]\s*\d+)?" r"|(?:\d+(?:\.\d+)?)\s*厢车" r"|(? None: +_WEIGHT_UNITS = frozenset({"KG", "KGS", "KGM", "公斤", "千克"}) +_AIR_WEIGHT_NAMES = frozenset({"空运费", "空运费用", "空运运费", "空运"}) + + +def _is_air_weight_fee(row: dict[str, Any]) -> bool: + """空运按计费重计价的运费行:单位 KG,或费目就是「空运费」。""" + unit = str(row.get("unit") or row.get("unitName") or row.get("chargeUnit") or "").strip().upper() + unit = unit.replace("/", "").replace("每", "") + if unit in _WEIGHT_UNITS: + return True + return _fee_key(str(row.get("name") or "")) in _AIR_WEIGHT_NAMES + + +def _apply_amount( + row: dict[str, Any], + amount: str, + *, + quantity: Any = None, + weight_priced: bool = False, +) -> None: """ 写入行金额;有数量时单价=金额÷数量,禁止把行合计原样塞进单价。 空运 KG:调价后金额是单价×计费重,展示读 unit_price;无数量(按票等)才单价=金额。 + weight_priced=True(空运计费行)且数量未知时:单价留空,交给出单按 + 金额÷计费重 反算。禁止把整票金额写进单价,否则出单会按 单价×计费重 再乘一遍。 """ row["amount"] = amount qty_raw = row.get("quantity") if qty_raw in (None, ""): qty_raw = row.get("chargeQuantity") + if qty_raw in (None, "") and quantity not in (None, ""): + qty_raw = quantity qty_num: Optional[float] = None if qty_raw not in (None, ""): try: @@ -877,6 +900,10 @@ def _apply_amount(row: dict[str, Any], amount: str) -> None: unit_plain = _plain_amount(unit_plain) row["unit_price"] = unit_plain row["unitPrice"] = unit_plain + elif weight_priced and _is_air_weight_fee(row): + # 计费重可能要等出单才按体积重补算:这里留空,别把行合计冒充「每KG」。 + row.pop("unit_price", None) + row.pop("unitPrice", None) else: row["unit_price"] = amount if row.get("unitPrice") not in (None, ""): @@ -1419,57 +1446,77 @@ def _fee_air_project(fee: dict[str, Any]) -> str: return "起运港" +def _fee_price_fields(fee: dict[str, Any]) -> dict[str, str]: + """ + 费用行写进舱位/汇总副本的单价、数量、单位。 + + 单价有原值就用原值;否则有数量时按 金额÷数量 反算;两者都没有时不写单价, + 交给出单按计费重反算。禁止把整票金额回填成单价。 + """ + up = _plain_amount(str(fee.get("unit_price") or fee.get("unitPrice") or "")) + qty = str(fee.get("quantity") or fee.get("chargeQuantity") or "").strip() + amount = _plain_amount(str(fee.get("amount") or "")) + amount_num, _ = parse_money(amount) + qty_num = _parse_qty(qty) + if not up and amount_num is not None and qty_num is not None and abs(qty_num) > 1e-9: + up = _plain_amount(format_money(amount_num / qty_num)) + out: dict[str, str] = {} + if up: + out["unit_price"] = up + if qty: + out["quantity"] = qty + unit = str(fee.get("unit") or fee.get("unitName") or "").strip() + if unit: + out["unit"] = unit + return out + + def _fee_as_air_charge(fee: dict[str, Any], *, quote: dict[str, Any]) -> dict[str, Any]: """扁平 fee_lines 转舱位 departureCharges / feeItems 会读的结构。""" title = _fee_title(fee) plain = _plain_amount(str(fee.get("amount") or "")) - unit_price = _plain_amount( - str(fee.get("unit_price") or fee.get("unitPrice") or fee.get("amount") or "") - ) + fields = _fee_price_fields(fee) + unit_price = fields.get("unit_price") or "" out: dict[str, Any] = { "chargeName": title, "feeName": title, "name": title, "amount": plain or unit_price, - "unitPrice": unit_price or plain, "currency": fee.get("currency") or quote.get("currency") or "", "project": _fee_air_project(fee), } - unit = str(fee.get("unit") or fee.get("unitName") or "").strip() - if unit: - out["unit"] = unit - qty = str(fee.get("quantity") or fee.get("chargeQuantity") or "").strip() - if qty: - out["quantity"] = qty + if unit_price: + out["unitPrice"] = unit_price + out["unit_price"] = unit_price + for key in ("quantity", "unit"): + if fields.get(key): + out[key] = fields[key] return out def _stamp_fee_items(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None: raw, was_str = _json_struct(quote.get("feeItems")) items = [dict(x) for x in raw if isinstance(x, dict)] if isinstance(raw, list) else [] + + def _new_item(fee: dict[str, Any]) -> dict[str, Any]: + item: dict[str, Any] = { + "name": _fee_title(fee), + "feeName": _fee_title(fee), + "amount": _plain_amount(str(fee.get("amount") or "")), + "currency": fee.get("currency") or quote.get("currency") or "", + } + item.update(_fee_price_fields(fee)) + return item + if not items: items = [ - { - "name": _fee_title(fee), - "feeName": _fee_title(fee), - "amount": _plain_amount(str(fee.get("amount") or "")), - "currency": fee.get("currency") or quote.get("currency") or "", - } + _new_item(fee) for fee in fees if _fee_title(fee) and _fee_air_project(fee) == "空运段" ] if not items: # 无空运段费目时仍按原逻辑铺全量,避免只有起运附加费时整表空掉 - items = [ - { - "name": _fee_title(fee), - "feeName": _fee_title(fee), - "amount": _plain_amount(str(fee.get("amount") or "")), - "currency": fee.get("currency") or quote.get("currency") or "", - } - for fee in fees - if _fee_title(fee) - ] + items = [_new_item(fee) for fee in fees if _fee_title(fee)] else: used: set[int] = set() for item in items: @@ -1477,12 +1524,25 @@ def _stamp_fee_items(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None: if idx < 0: continue used.add(idx) - _write_price(item, _plain_amount(str(fees[idx].get("amount") or ""))) - _sync_line_currency(item, fees[idx]) + fee = fees[idx] + _write_price(item, _plain_amount(str(fee.get("amount") or ""))) + _sync_line_currency(item, fee) + # 单价/数量按费用行同步;空运计费行没有单价时不能留整票金额, + # 否则模板会按「单价×计费重」再乘一遍。 + fields = _fee_price_fields(fee) + if fields.get("unit_price"): + item["unitPrice"] = fields["unit_price"] + item["unit_price"] = fields["unit_price"] + elif _is_air_weight_fee(fee): + item.pop("unitPrice", None) + item.pop("unit_price", None) + for key in ("quantity", "unit"): + if fields.get(key): + item[key] = fields[key] if not item.get("name"): - item["name"] = _fee_title(fees[idx]) + item["name"] = _fee_title(fee) if not item.get("feeName"): - item["feeName"] = _fee_title(fees[idx]) + item["feeName"] = _fee_title(fee) # 调价新增的空运段费目也要进 feeItems,否则模板只读舱位桶时看不到 for i, fee in enumerate(fees): if i in used or _fee_air_project(fee) != "空运段": @@ -1490,14 +1550,7 @@ def _stamp_fee_items(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None: title = _fee_title(fee) if not title: continue - items.append( - { - "name": title, - "feeName": title, - "amount": _plain_amount(str(fee.get("amount") or "")), - "currency": fee.get("currency") or quote.get("currency") or "", - } - ) + items.append(_new_item(fee)) used.add(i) if items: _put_struct(quote, "feeItems", items, was_str) @@ -1633,6 +1686,11 @@ def _stamp_air_bucket_list( if up: charge["unitPrice"] = up charge["unit_price"] = up + elif _is_air_weight_fee(fee): + # _write_price 刚把整票金额写进 unitPrice;空运计费行留空, + # 出单按计费重反算,避免「单价×计费重」再乘一遍。 + charge.pop("unitPrice", None) + charge.pop("unit_price", None) qty = str(fee.get("quantity") or "").strip() if qty: charge["quantity"] = qty @@ -1653,7 +1711,7 @@ def _stamp_air_bucket_list( def _stamp_air_copies(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None: - """空运报价单读舱位 departureCharges 和 salePrice,不读改过的 fee_lines。""" + """空运报价单读舱位 feeItems/departureCharges/salePrice,不读改过的 fee_lines。""" total_plain = _plain_amount(str(quote.get("total") or "")) for key in ("airOptions", "air_options", "selected_air_option", "selectedAirOption"): raw, was_str = _json_struct(quote.get(key)) @@ -1683,6 +1741,18 @@ def _stamp_air_copies(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None projects={"目的地"}, quote=quote, ) + # 空运段运费在 feeItems;不同步的话调价后报价单仍读舱位旧价。 + # 放在起运/目的地之后:旧 payload 把「空运费」放在 departureCharges 时, + # 先按原桶盖价,避免同一条费用被挪到 feeItems 而漏掉原桶。 + _stamp_air_bucket_list( + opt, + "feeItems", + "fee_items", + fees, + used, + projects={"空运段"}, + quote=quote, + ) if total_plain: if opt.get("salePrice") not in (None, ""): opt["salePrice"] = total_plain @@ -1847,9 +1917,16 @@ def _apply_total_only( } ] if line_amt is not None: + # 与普通调价通道一致:行上没有数量时先补报价/舱位计费重, + # 否则空运会拿整票合计当「每KG」单价(报价单再乘一次计费重)。 + qty_num = _row_or_quote_qty(row, src) + if qty_num is not None and abs(qty_num) > 1e-9 and row.get("quantity") in (None, ""): + row["quantity"] = f"{qty_num:.10g}" _apply_amount( row, format_money(line_amt, sample=str(row.get("amount") or ""), currency=line_ccy), + quantity=qty_num, + weight_priced=(business_line or str(src.get("business_line") or "")).upper() == "AIR", ) rows[idx] = row applied.append( @@ -2133,7 +2210,12 @@ def apply_adjust( how = f"上调 {item.value:g}%" if qty_num is not None and row.get("quantity") in (None, ""): row["quantity"] = f"{qty_num:.10g}" - _apply_amount(row, format_money(new_amt, sample=str(row.get("amount") or ""), currency=line_ccy or prefix)) + _apply_amount( + row, + format_money(new_amt, sample=str(row.get("amount") or ""), currency=line_ccy or prefix), + quantity=qty_num, + weight_priced=(business_line or str(src.get("business_line") or "")).upper() == "AIR", + ) rows[idx] = row applied.append({"name": row_display_label(row, src), "how": how, "amount": row["amount"]}) bucket = str(row.get("_bucket") or "") diff --git a/inquiry-agent/tests/test_quote_adjust.py b/inquiry-agent/tests/test_quote_adjust.py index f440c5d..6f83217 100644 --- a/inquiry-agent/tests/test_quote_adjust.py +++ b/inquiry-agent/tests/test_quote_adjust.py @@ -228,6 +228,138 @@ class QuoteAdjustTests(unittest.TestCase): 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") @@ -1358,6 +1490,151 @@ class SheetPriceStampTests(unittest.TestCase): 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): """反问「改哪一项」之后,销售回序号/段名的接续。""" diff --git a/inquiry-agent/tests/test_synonym.py b/inquiry-agent/tests/test_synonym.py index ed422fb..baf90ff 100644 --- a/inquiry-agent/tests/test_synonym.py +++ b/inquiry-agent/tests/test_synonym.py @@ -711,6 +711,33 @@ class SynonymTests(unittest.TestCase): kept = harvest_oral_land_vehicle("陆运,品名:衣服", {"车型/数量": "5T"}) self.assertEqual(kept["车型/数量"], "5T") + def test_clarify_example_lines_not_harvested(self) -> None: + """复制补问清单时留下的 (如:…) 示例不能顶掉销售填的值。""" + paste = ( + "4.车型/数量(必填):18米平板\n" + "(如:9米6/1)\n" + "5.通关口岸(非必填):天保\n" + "(如:友谊关)\n" + ) + # 示例行里的 9米6 不能变成 9.6高栏 候选,覆盖 18米平板。 + self.assertEqual( + synonym.harvest_field_candidates("车型/数量", paste, "LAND"), [] + ) + self.assertEqual( + harvest_oral_land_vehicle(paste, {}).get("车型/数量"), "18米平板" + ) + # 示例行里的友谊关不能变成真实口岸候选。 + self.assertEqual( + synonym.harvest_field_candidates("通关口岸", paste, "LAND"), ["天保"] + ) + self.assertEqual( + synonym.harvest_field_value("通关口岸", paste, "LAND"), + {"通关口岸": "天保"}, + ) + snap = extract_inquiry_snapshot(paste, injected_mode="LAND", allow_b=False) + self.assertEqual(snap["facts"].get("车型/数量"), "18米平板") + self.assertEqual(snap["facts"].get("通关口岸"), "天保") + def test_land_business_label_and_internal_value(self) -> None: facts = synonym.apply_value_synonyms({"运输类型": "东南亚整车"}, "LAND") self.assertEqual(facts["运输类型"], "跨境整车") diff --git a/inquiry-api/jeecg-module-inquiry/src/main/java/org/jeecg/modules/inquiry/support/InquiryQuoteLineSupport.java b/inquiry-api/jeecg-module-inquiry/src/main/java/org/jeecg/modules/inquiry/support/InquiryQuoteLineSupport.java index 4ad7079..19094ca 100644 --- a/inquiry-api/jeecg-module-inquiry/src/main/java/org/jeecg/modules/inquiry/support/InquiryQuoteLineSupport.java +++ b/inquiry-api/jeecg-module-inquiry/src/main/java/org/jeecg/modules/inquiry/support/InquiryQuoteLineSupport.java @@ -11,8 +11,12 @@ import org.jeecg.modules.inquiry.entity.InquiryTicket; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** * 后台成本价 / 销售价 / 利润点逐行。 @@ -181,6 +185,10 @@ public final class InquiryQuoteLineSupport { if (StringUtils.isNotBlank(item.currency)) { old.currency = item.currency; } + // 展示名以 TMS 那段为准;TMS 没认出段时才用盖价行的。 + if (StringUtils.isBlank(old.displayName) && StringUtils.isNotBlank(item.displayName)) { + old.displayName = item.displayName; + } rows.set(idx, old); } return rows; @@ -230,18 +238,35 @@ public final class InquiryQuoteLineSupport { List lines = new ArrayList(); if (fees != null) { for (FeeRow fee : fees) { - lines.add(line(fee.name, "0%")); + lines.add(line(fee.shownName(), "0%")); } } lines.add(line(TOTAL_NAME, "0%")); return lines; } + /** + * 展示名:某一侧带线路后缀就用它,另一侧没后缀时跟过去, + * 避免成本、销售、利润三列同一条费用出现不同标签。 + */ + private static String shownName(FeeRow primary, FeeRow fallback) { + if (primary != null && primary.hasLabel()) { + return primary.shownName(); + } + if (fallback != null && fallback.hasLabel()) { + return fallback.shownName(); + } + if (primary != null) { + return primary.shownName(); + } + return fallback == null ? "" : fallback.shownName(); + } + private static List moneyLines(List fees, String totalText) { List lines = new ArrayList(); if (fees != null) { for (FeeRow fee : fees) { - lines.add(line(fee.name, fee.text)); + lines.add(line(fee.shownName(), fee.text)); } } if (StringUtils.isNotBlank(totalText)) { @@ -254,7 +279,8 @@ public final class InquiryQuoteLineSupport { List lines = new ArrayList(); for (Aligned row : rows) { FeeRow side = costSide ? row.left : row.right; - lines.add(line(row.name, side == null ? "" : side.text)); + FeeRow other = costSide ? row.right : row.left; + lines.add(line(shownName(side, other), side == null ? "" : side.text)); } if (StringUtils.isNotBlank(totalText)) { lines.add(line(TOTAL_NAME, totalText)); @@ -276,7 +302,7 @@ public final class InquiryQuoteLineSupport { if (idx >= 0) { used[idx] = true; } - lines.add(line(row.name, percentOf(base, row))); + lines.add(line(shownName(row, base), percentOf(base, row))); } } if (StringUtils.isNotBlank(totalProfit)) { @@ -288,7 +314,7 @@ public final class InquiryQuoteLineSupport { private static List profitFromAligned(List rows, String totalProfit) { List lines = new ArrayList(); for (Aligned row : rows) { - lines.add(line(row.name, percentOf(row.left, row.right))); + lines.add(line(shownName(row.left, row.right), percentOf(row.left, row.right))); } if (StringUtils.isNotBlank(totalProfit)) { lines.add(line(TOTAL_NAME, totalProfit)); @@ -422,9 +448,175 @@ public final class InquiryQuoteLineSupport { } } } + // 陆运一条线路多段时,两行「运输费」靠段号/腿号补上起止地,仅影响展示名。 + applyLandLegLabels(rows, payload); return rows; } + /** + * 陆运同名费用行按段补线路名(仅展示)。 + *

+ * 为何:TMS 一条线路含中转时会出现两行「运输费」,fee_lines 只带 + * segmentSequence / routeLegSequence,后台摊平后看不出各是哪一段。 + * 起止地只从 landSegments / route_rows 原文取,认不回段时按行序兜底。 + * 不改 name:手工盖价、销售调价、模板取费仍按原名匹配。 + */ + private static void applyLandLegLabels(List rows, JSONObject payload) { + if (rows == null || rows.size() < 2) { + return; + } + List legs = readLandLegs(payload); + if (legs.size() < 2) { + return; + } + Map> groups = new LinkedHashMap>(); + for (int i = 0; i < rows.size(); i++) { + String name = StringUtils.trimToEmpty(rows.get(i).name); + if (name.isEmpty()) { + continue; + } + List group = groups.get(name); + if (group == null) { + group = new ArrayList(); + groups.put(name, group); + } + group.add(i); + } + for (Map.Entry> entry : groups.entrySet()) { + List group = entry.getValue(); + if (group.size() < 2) { + continue; + } + boolean[] used = new boolean[legs.size()]; + int[] assigned = new int[group.size()]; + Arrays.fill(assigned, -1); + // 先按段号 + 腿号认回;认不回的再按行序补给没用过的段。 + for (int n = 0; n < group.size(); n++) { + FeeRow row = rows.get(group.get(n)); + if (StringUtils.isBlank(row.seg) || StringUtils.isBlank(row.leg)) { + continue; + } + for (int li = 0; li < legs.size(); li++) { + Leg leg = legs.get(li); + if (!used[li] && row.seg.equals(leg.seg) && row.leg.equals(leg.leg)) { + used[li] = true; + assigned[n] = li; + break; + } + } + } + int cursor = 0; + for (int n = 0; n < group.size(); n++) { + if (assigned[n] >= 0) { + continue; + } + while (cursor < legs.size() && used[cursor]) { + cursor++; + } + if (cursor < legs.size()) { + used[cursor] = true; + assigned[n] = cursor; + } + } + for (int n = 0; n < group.size(); n++) { + int li = assigned[n]; + if (li < 0) { + continue; + } + String title = legs.get(li).title; + if (StringUtils.isNotBlank(title)) { + rows.get(group.get(n)).displayName = entry.getKey() + "(" + title + ")"; + } + } + } + } + + /** + * 取陆运各段:优先已选线路 landSegments,缺了再看 route_rows。 + * 只读 payload,不写库。 + */ + private static List readLandLegs(JSONObject payload) { + if (payload == null) { + return Collections.emptyList(); + } + for (String key : new String[]{"landSegments", "land_segments", "route_rows", "routeRows"}) { + List legs = legsFromArray(asArray(payload.get(key))); + if (!legs.isEmpty()) { + return legs; + } + } + JSONObject selected = asObject(payload.get("selected_land_route")); + if (selected == null) { + selected = asObject(payload.get("selectedLandRoute")); + } + if (selected != null) { + return legsFromArray(asArray(selected.get("legs"))); + } + return Collections.emptyList(); + } + + /** 腿数组 → 按段号/腿号排好并补上展示标题。 */ + private static List legsFromArray(JSONArray array) { + if (array == null || array.isEmpty()) { + return Collections.emptyList(); + } + List legs = new ArrayList(); + for (int i = 0; i < array.size(); i++) { + JSONObject item = asObject(array.get(i)); + if (item == null) { + continue; + } + Leg leg = new Leg(); + leg.seg = firstText(item, "segmentSequence", "segment_sequence", "sequence"); + leg.leg = firstText(item, "routeLegSequence", "route_leg_sequence", "legSequence"); + leg.origin = placeName(item, "origin", "originName"); + leg.destination = placeName(item, "destination", "destinationName"); + leg.order = i; + legs.add(leg); + } + if (legs.isEmpty()) { + return legs; + } + Collections.sort(legs, new Comparator() { + @Override + public int compare(Leg left, Leg right) { + int seg = Integer.compare(intOr(left.seg, 1), intOr(right.seg, 1)); + if (seg != 0) { + return seg; + } + int leg = Integer.compare(intOr(left.leg, 0), intOr(right.leg, 0)); + if (leg != 0) { + return leg; + } + return Integer.compare(left.order, right.order); + } + }); + for (int i = 0; i < legs.size(); i++) { + Leg leg = legs.get(i); + leg.title = StringUtils.isNotBlank(leg.origin) && StringUtils.isNotBlank(leg.destination) + ? leg.origin + " → " + leg.destination + : "第" + (i + 1) + "段"; + } + return legs; + } + + /** 站名只取 TMS 原文;「-」「null」当没有,回退成第 N 段。 */ + private static String placeName(JSONObject item, String... keys) { + String text = StringUtils.trimToEmpty(firstText(item, keys)); + if ("-".equals(text) || "null".equalsIgnoreCase(text)) { + return ""; + } + return text; + } + + private static int intOr(String raw, int fallback) { + try { + return Integer.parseInt(StringUtils.trimToEmpty(raw)); + } catch (NumberFormatException ignored) { + return fallback; + } + } + private static Object firstPresent(JSONObject obj, String... keys) { for (String key : keys) { if (obj.get(key) != null) { @@ -475,6 +667,9 @@ public final class InquiryQuoteLineSupport { } FeeRow row = new FeeRow(); row.name = name; + row.displayName = name; + row.seg = firstText(item, "segmentSequence", "segment_sequence"); + row.leg = firstText(item, "routeLegSequence", "route_leg_sequence"); row.text = text; row.currency = StringUtils.isNotBlank(currency) ? currency : currencyOf(text); row.amount = InquiryTicketPriceSupport.parseAmount(text); @@ -600,16 +795,33 @@ public final class InquiryQuoteLineSupport { return row; } - /** 一条费用的展示金额。amount 是比利润用的数字,text 是原样带币种的写法。 */ + /** + * 一条费用。name 是匹配用的原名,displayName 只给后台展示(可带线路), + * amount 是比利润用的数字,text 是原样带币种的写法。 + */ static final class FeeRow { private String name; + private String displayName; + private String seg; + private String leg; private String text; private String currency; private BigDecimal amount; + private String shownName() { + return StringUtils.isNotBlank(displayName) ? displayName : name; + } + + private boolean hasLabel() { + return StringUtils.isNotBlank(displayName) && !displayName.equals(name); + } + private FeeRow copy() { FeeRow row = new FeeRow(); row.name = name; + row.displayName = displayName; + row.seg = seg; + row.leg = leg; row.text = text; row.currency = currency; row.amount = amount; @@ -617,6 +829,16 @@ public final class InquiryQuoteLineSupport { } } + /** 陆运一条线路里的一段:段号 + 腿号 + 起止地标题。 */ + private static final class Leg { + private String seg; + private String leg; + private String origin; + private String destination; + private String title; + private int order; + } + /** 成本侧与销售侧对上的一行。某一侧没有时为 null。 */ private static final class Aligned { private final String name; diff --git a/inquiry-api/jeecg-module-inquiry/src/main/java/org/jeecg/modules/inquiry/template/QuoteTemplateExcelSupport.java b/inquiry-api/jeecg-module-inquiry/src/main/java/org/jeecg/modules/inquiry/template/QuoteTemplateExcelSupport.java index 3474168..ecd15df 100644 --- a/inquiry-api/jeecg-module-inquiry/src/main/java/org/jeecg/modules/inquiry/template/QuoteTemplateExcelSupport.java +++ b/inquiry-api/jeecg-module-inquiry/src/main/java/org/jeecg/modules/inquiry/template/QuoteTemplateExcelSupport.java @@ -7519,17 +7519,27 @@ public final class QuoteTemplateExcelSupport { continue; } String name = firstNonBlank(ch.getString("chargeName"), ch.getString("feeName"), ch.getString("name")); + // amount 是行合计,不是单价:只有明确给了单价字段才填 unit_price。 + // 旧逻辑回退成 amount,调价把整票金额写进 amount 时会被当成「每KG」 + // 再乘一次计费重(WO202611250038:10543.77 × 833.5 = 8788232.30)。 String unitPrice = firstNonBlank(ch.getString("unitPrice"), ch.getString("unit_price"), - ch.getString("salePrice"), ch.getString("amount")); - if (StringUtils.isBlank(name) || StringUtils.isBlank(unitPrice)) { + ch.getString("salePrice")); + String amountRaw = StringUtils.trimToEmpty(ch.getString("amount")); + if (StringUtils.isBlank(amountRaw)) { + // 只有单价的旧行:金额按单价落 + amountRaw = unitPrice; + } + if (StringUtils.isBlank(name) + || (StringUtils.isBlank(unitPrice) && StringUtils.isBlank(amountRaw))) { continue; } String project = firstNonBlank(ch.getString("project"), airProjectForBucket(ch.getString("_airBucket"))); - String amountRaw = firstNonBlank(ch.getString("amount"), unitPrice); Map line = new LinkedHashMap<>(); line.put("name", name); line.put("amount", amountRaw); - line.put("unit_price", unitPrice); + if (StringUtils.isNotBlank(unitPrice)) { + line.put("unit_price", unitPrice); + } line.put("project", project); if (StringUtils.isNotBlank(ch.getString("_airBucket"))) { line.put("source_bucket", ch.getString("_airBucket")); diff --git a/inquiry-api/jeecg-module-inquiry/src/test/java/org/jeecg/modules/inquiry/support/InquiryQuoteLineSupportTest.java b/inquiry-api/jeecg-module-inquiry/src/test/java/org/jeecg/modules/inquiry/support/InquiryQuoteLineSupportTest.java index 2a09235..e16cc74 100644 --- a/inquiry-api/jeecg-module-inquiry/src/test/java/org/jeecg/modules/inquiry/support/InquiryQuoteLineSupportTest.java +++ b/inquiry-api/jeecg-module-inquiry/src/test/java/org/jeecg/modules/inquiry/support/InquiryQuoteLineSupportTest.java @@ -178,6 +178,67 @@ public class InquiryQuoteLineSupportTest { assertLines(ticket.getProfitLines(), "运输费", "10%", "运输费", "10%", "费用合计", "10%"); } + @Test + public void landDuplicateFeeNamesShowLegEndpoints() { + InquiryTicket ticket = ticket("LAND"); + InquiryTicketPriceSupport.apply(ticket, Collections.singletonList(quote( + "TMS", "TMS标准报价", "CNY 18600.00", + "{\"currency\":\"CNY\",\"total\":\"18600\",\"fee_lines\":[" + + "{\"name\":\"运输费\",\"amount\":\"9000\",\"currency\":\"CNY\"," + + "\"segmentSequence\":1,\"routeLegSequence\":1}," + + "{\"name\":\"运输费\",\"amount\":\"9600\",\"currency\":\"CNY\"," + + "\"segmentSequence\":1,\"routeLegSequence\":2}]," + + "\"landSegments\":[" + + "{\"origin\":\"上海\",\"destination\":\"凭祥\"," + + "\"segmentSequence\":1,\"routeLegSequence\":1}," + + "{\"origin\":\"凭祥\",\"destination\":\"胡志明\"," + + "\"segmentSequence\":1,\"routeLegSequence\":2}]}"))); + assertLines(ticket.getCostLines(), + "运输费(上海 → 凭祥)", "CNY 9000", + "运输费(凭祥 → 胡志明)", "CNY 9600", + "费用合计", "CNY 18600.00"); + assertLines(ticket.getProfitLines(), + "运输费(上海 → 凭祥)", "0%", + "运输费(凭祥 → 胡志明)", "0%", + "费用合计", "0%"); + } + + @Test + public void landDuplicateFeeNamesWithoutSegmentsPairByOrder() { + InquiryTicket ticket = ticket("LAND"); + InquiryTicketPriceSupport.apply(ticket, Collections.singletonList(quote( + "TMS", "TMS标准报价", "CNY 18600.00", + "{\"currency\":\"CNY\",\"total\":\"18600\",\"fee_lines\":[" + + "{\"name\":\"运输费\",\"amount\":\"9000\",\"currency\":\"CNY\"}," + + "{\"name\":\"运输费\",\"amount\":\"9600\",\"currency\":\"CNY\"}]," + + "\"route_rows\":[" + + "{\"origin\":\"上海\",\"destination\":\"凭祥\",\"routeLegSequence\":1}," + + "{\"origin\":\"凭祥\",\"destination\":\"胡志明\",\"routeLegSequence\":2}]}"))); + assertLines(ticket.getCostLines(), + "运输费(上海 → 凭祥)", "CNY 9000", + "运输费(凭祥 → 胡志明)", "CNY 9600", + "费用合计", "CNY 18600.00"); + } + + @Test + public void landDuplicateFeeNamesFallBackToSelectedRouteLegs() { + InquiryTicket ticket = ticket("LAND"); + InquiryTicketPriceSupport.apply(ticket, Collections.singletonList(quote( + "TMS", "TMS标准报价", "CNY 18600.00", + "{\"currency\":\"CNY\",\"total\":\"18600\",\"fee_lines\":[" + + "{\"name\":\"运输费\",\"amount\":\"9000\",\"currency\":\"CNY\"}," + + "{\"name\":\"运输费\",\"amount\":\"9600\",\"currency\":\"CNY\"}]," + + "\"selected_land_route\":\"{\\\"segmentSequence\\\":1,\\\"legs\\\":[" + + "{\\\"origin\\\":\\\"上海\\\",\\\"destination\\\":\\\"凭祥\\\"," + + "\\\"routeLegSequence\\\":1}," + + "{\\\"origin\\\":\\\"凭祥\\\",\\\"destination\\\":\\\"胡志明\\\"," + + "\\\"routeLegSequence\\\":2}]}\"}"))); + assertLines(ticket.getCostLines(), + "运输费(上海 → 凭祥)", "CNY 9000", + "运输费(凭祥 → 胡志明)", "CNY 9600", + "费用合计", "CNY 18600.00"); + } + @Test public void manualOverlayKeepsUntouchedTmsFee() { InquiryTicket ticket = ticket("SEA"); diff --git a/inquiry-api/jeecg-module-inquiry/src/test/java/org/jeecg/modules/inquiry/template/AirChargeableWeightTest.java b/inquiry-api/jeecg-module-inquiry/src/test/java/org/jeecg/modules/inquiry/template/AirChargeableWeightTest.java index 01e4fb4..699ae1a 100644 --- a/inquiry-api/jeecg-module-inquiry/src/test/java/org/jeecg/modules/inquiry/template/AirChargeableWeightTest.java +++ b/inquiry-api/jeecg-module-inquiry/src/test/java/org/jeecg/modules/inquiry/template/AirChargeableWeightTest.java @@ -1,5 +1,6 @@ package org.jeecg.modules.inquiry.template; +import com.alibaba.fastjson.JSONArray; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -76,6 +77,38 @@ public class AirChargeableWeightTest { assertEquals("8800", row.get("amount")); } + /** + * 舱位费只有 amount、没有单价:amount 是整票金额,必须扣除计费重后保留, + * 禁止把 amount 回填成单价再乘一次(WO202611250038:10543.77×833.5=8788232.30)。 + */ + @Test + public void amountOnlyAirChargeKeepsLineTotal() { + String airOptions = "[{\"optionNo\":\"AIR-OPT01\",\"salePrice\":10543.77," + + "\"currency\":\"CNY\",\"chargeableWeightKg\":833.5," + + "\"feeItems\":[{\"feeName\":\"空运费\",\"amount\":10543.77," + + "\"unit\":\"KG\",\"currency\":\"CNY\"}]}]"; + JSONArray rows = QuoteTemplateExcelSupport.parseAirDepartureChargeRows( + airOptions, null, "833.5", "CNY"); + assertEquals(1, rows.size()); + assertEquals("10543.77", rows.getJSONObject(0).getString("amount")); + assertTrue(rows.getJSONObject(0).getString("unit_price").startsWith("12.650"), + "单价应按 金额÷计费重 反算,实际=" + rows.getJSONObject(0).getString("unit_price")); + } + + /** 调价后已给每 KG 单价:行金额保持调后价,不能被 单价×计费重 覆盖。 */ + @Test + public void airChargeWithUnitPriceKeepsAdjustedTotal() { + String airOptions = "[{\"optionNo\":\"AIR-OPT01\",\"salePrice\":10543.77," + + "\"currency\":\"CNY\",\"chargeableWeightKg\":833.5," + + "\"feeItems\":[{\"feeName\":\"空运费\",\"amount\":10543.77," + + "\"unitPrice\":12.65,\"unit\":\"KG\",\"currency\":\"CNY\"}]}]"; + JSONArray rows = QuoteTemplateExcelSupport.parseAirDepartureChargeRows( + airOptions, null, "833.5", "CNY"); + assertEquals(1, rows.size()); + assertEquals("10543.77", rows.getJSONObject(0).getString("amount")); + assertEquals("12.65", rows.getJSONObject(0).getString("unit_price")); + } + /** 起运港固定费(增点费等)不乘计费重。 */ @Test public void departureFixedFeeIsNotMultiplied() { diff --git a/inquiry-backend/src/views/inquiry/workOrder/index.vue b/inquiry-backend/src/views/inquiry/workOrder/index.vue index 1ee220a..ea6306d 100644 --- a/inquiry-backend/src/views/inquiry/workOrder/index.vue +++ b/inquiry-backend/src/views/inquiry/workOrder/index.vue @@ -30,6 +30,7 @@ import { type MultiSegmentView, } from "/@/views/inquiry/workOrder/demandFields"; import { stripMentionFromRawQuote } from "/@/views/inquiry/workOrder/quoteRawText"; +import { applyLandLegLabels } from "/@/views/inquiry/workOrder/quoteFeeLines"; import { usePermission } from "/@/hooks/web/usePermission"; import { InquiryBtnPerm } from "/@/views/inquiry/shared/inquiryPagePerms"; @@ -353,6 +354,8 @@ function parseQuoteFees(q: any): TicketQuoteFee[] { pushRows(asFeeArray(payload[key] || payload[bucket])); } } + // 陆运一条线路多段时,重名费用行补「起运 → 目的」,避免两行运输费分不清。 + applyLandLegLabels(out, payload); // 陆运 TMS:燃油附加费率 / 税率挂在线路段上,不是金额费目行。 for (const extra of parseLandRateFees(payload)) { if (!out.some((x) => x.name === extra.name && x.amount === extra.amount)) { @@ -367,7 +370,8 @@ function parseQuoteFees(q: any): TicketQuoteFee[] { * 只读 payload,不写库。海运/空运没有这些键则不出行。 */ function parseLandRateFees(payload: Record): TicketQuoteFee[] { - const rows = asFeeArray(payload.route_rows || payload.landSegments || payload.land_segments); + // 优先已选线路 landSegments;route_rows 可能还带着未选备选线路的腿。 + const rows = asFeeArray(payload.landSegments || payload.land_segments || payload.route_rows); const out: TicketQuoteFee[] = []; const seen = new Set(); for (const row of rows) { diff --git a/inquiry-backend/src/views/inquiry/workOrder/quoteFeeLines.ts b/inquiry-backend/src/views/inquiry/workOrder/quoteFeeLines.ts new file mode 100644 index 0000000..80642a7 --- /dev/null +++ b/inquiry-backend/src/views/inquiry/workOrder/quoteFeeLines.ts @@ -0,0 +1,147 @@ +/** + * 后台「TMS标准报价」费用行展示:陆运同名费用补上线路名。 + * + * 主账 quote.payload_json 的 fee_lines 只有 segmentSequence / routeLegSequence, + * 起止地只在 landSegments / route_rows 里。TMS 一条线路含中转时会出现两行 + * 「运输费」,直接摊平就看不出各是哪一段;这里按段号 + 腿号关联出 + * 「上海 → 凭祥」,段号缺失时按行序兜底。只改展示名,不改金额、不写库。 + */ + +function asArray(raw: any): any[] { + if (raw == null) return []; + if (Array.isArray(raw)) return raw; + if (typeof raw === 'string' && raw.trim()) { + try { + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) return parsed; + if (typeof parsed === 'string') { + const again = JSON.parse(parsed); + return Array.isArray(again) ? again : []; + } + } catch { + return []; + } + } + return []; +} + +function asObject(raw: any): any { + if (raw && typeof raw === 'object' && !Array.isArray(raw)) return raw; + if (typeof raw === 'string' && raw.trim()) { + try { + const parsed = JSON.parse(raw); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed; + } catch { + return null; + } + } + return null; +} + +function text(raw: any): string { + return String(raw ?? '').trim(); +} + +function seqOf(row: any): number { + return num(row?.segmentSequence ?? row?.segment_sequence, 1); +} + +function legNoOf(row: any): number { + return num(row?.routeLegSequence ?? row?.route_leg_sequence, 0); +} + +function num(raw: any, fallback: number): number { + const n = Number(String(raw ?? '').trim()); + return Number.isFinite(n) ? n : fallback; +} + +/** + * 陆运各段:优先已选线路 landSegments,缺了再看 route_rows。 + * 与后台成本列一致,避免多备选场景读到未选线路的段。 + */ +export function landLegRows(payload: any): any[] { + const src = payload || {}; + for (const key of ['landSegments', 'land_segments', 'route_rows', 'routeRows']) { + const rows = sortLegs(asArray(src[key]).filter((x) => x && typeof x === 'object')); + if (rows.length) return rows; + } + const selected = asObject(src.selected_land_route) || asObject(src.selectedLandRoute); + return selected ? sortLegs(asArray(selected.legs).filter((x) => x && typeof x === 'object')) : []; +} + +function sortLegs(rows: any[]): any[] { + if (!rows.length) return []; + return rows + .map((row, index) => ({ row, index })) + .sort((a, b) => seqOf(a.row) - seqOf(b.row) || legNoOf(a.row) - legNoOf(b.row) || a.index - b.index) + .map((x) => x.row); +} + +/** 一段的标题:起止地都有才拼「上海 → 凭祥」,否则退回第 N 段。 */ +function legTitle(leg: any, index: number): string { + const origin = place(leg?.origin ?? leg?.originName); + const destination = place(leg?.destination ?? leg?.destinationName); + if (origin && destination) return `${origin} → ${destination}`; + return `第${index + 1}段`; +} + +function place(raw: any): string { + const s = text(raw); + return s === '-' || s.toLowerCase() === 'null' ? '' : s; +} + +/** + * 同一报价里重名的费用行按段补线路名(原地改 name)。 + * + * 只有重名且至少两段时才补,单段或费用名唯一时保持原样。 + */ +export function applyLandLegLabels(fees: any[], payload: any): void { + if (!Array.isArray(fees) || fees.length < 2) return; + const legs = landLegRows(payload); + if (legs.length < 2) return; + + const groups = new Map(); + fees.forEach((fee, index) => { + const name = text(fee?.name); + if (!name) return; + const group = groups.get(name); + if (group) group.push(index); + else groups.set(name, [index]); + }); + + groups.forEach((idxs, name) => { + if (idxs.length < 2) return; + const used = new Array(legs.length).fill(false); + const assigned = new Array(idxs.length).fill(-1); + // 先按段号 + 腿号认回;认不回的再按行序补给没用过的段。 + idxs.forEach((feeIndex, n) => { + const fee = fees[feeIndex]; + const seg = text(fee.segmentSequence ?? fee.segment_sequence); + const leg = text(fee.routeLegSequence ?? fee.route_leg_sequence); + if (!seg || !leg) return; + const hit = legs.findIndex( + (row, li) => + !used[li] && text(row.segmentSequence ?? row.segment_sequence) === seg && text(row.routeLegSequence ?? row.route_leg_sequence) === leg + ); + if (hit >= 0) { + used[hit] = true; + assigned[n] = hit; + } + }); + let cursor = 0; + idxs.forEach((_feeIndex, n) => { + if (assigned[n] >= 0) return; + while (cursor < legs.length && used[cursor]) cursor++; + if (cursor < legs.length) { + used[cursor] = true; + assigned[n] = cursor; + } + }); + idxs.forEach((feeIndex, n) => { + const li = assigned[n]; + if (li < 0) return; + const title = legTitle(legs[li], li); + if (title) fees[feeIndex].name = `${name}(${title})`; + }); + }); +} diff --git a/inquiry-backend/tests/quoteFeeLines.spec.ts b/inquiry-backend/tests/quoteFeeLines.spec.ts new file mode 100644 index 0000000..c36ea8a --- /dev/null +++ b/inquiry-backend/tests/quoteFeeLines.spec.ts @@ -0,0 +1,92 @@ +/** + * 后台「TMS标准报价」费用行:陆运同名运输费要能看出是哪一段。 + */ +import { applyLandLegLabels, landLegRows } from '/@/views/inquiry/workOrder/quoteFeeLines'; + +function fees() { + return [ + { name: '运输费', amount: 'CNY 9000', segmentSequence: 1, routeLegSequence: 1 }, + { name: '运输费', amount: 'CNY 9600', segmentSequence: 1, routeLegSequence: 2 }, + ]; +} + +const payload = { + landSegments: [ + { origin: '上海', destination: '凭祥', segmentSequence: 1, routeLegSequence: 1 }, + { origin: '凭祥', destination: '胡志明', segmentSequence: 1, routeLegSequence: 2 }, + ], +}; + +test('按段号+腿号补起止地', () => { + const rows = fees(); + applyLandLegLabels(rows, payload); + expect(rows.map((x) => x.name)).toEqual(['运输费(上海 → 凭祥)', '运输费(凭祥 → 胡志明)']); +}); + +test('费用行没有段号时按行序配对', () => { + const rows = [ + { name: '运输费', amount: 'CNY 9000' }, + { name: '运输费', amount: 'CNY 9600' }, + ]; + applyLandLegLabels(rows, { + route_rows: JSON.stringify([ + { origin: '上海', destination: '凭祥', routeLegSequence: 1 }, + { origin: '凭祥', destination: '胡志明', routeLegSequence: 2 }, + ]), + }); + expect(rows.map((x) => x.name)).toEqual(['运输费(上海 → 凭祥)', '运输费(凭祥 → 胡志明)']); +}); + +test('只有 selected_land_route 时也读它下面的 legs', () => { + const rows = [ + { name: '运输费', amount: 'CNY 9000' }, + { name: '运输费', amount: 'CNY 9600' }, + ]; + applyLandLegLabels(rows, { + selected_land_route: JSON.stringify({ + segmentSequence: 1, + legs: [ + { origin: '上海', destination: '凭祥', routeLegSequence: 1 }, + { origin: '凭祥', destination: '胡志明', routeLegSequence: 2 }, + ], + }), + }); + expect(rows.map((x) => x.name)).toEqual(['运输费(上海 → 凭祥)', '运输费(凭祥 → 胡志明)']); +}); + +test('费用名不重复或只有一段时不改展示名', () => { + const unique = [ + { name: '运输费', amount: 'CNY 9000' }, + { name: '报关费', amount: 'CNY 300' }, + ]; + applyLandLegLabels(unique, payload); + expect(unique.map((x) => x.name)).toEqual(['运输费', '报关费']); + + const oneLeg = [ + { name: '运输费', amount: 'CNY 9000' }, + { name: '运输费', amount: 'CNY 9600' }, + ]; + applyLandLegLabels(oneLeg, { landSegments: [payload.landSegments[0]] }); + expect(oneLeg.map((x) => x.name)).toEqual(['运输费', '运输费']); +}); + +test('landSegments 是 JSON 串也能读,缺站名时退回第 N 段', () => { + const rows = landLegRows({ + landSegments: JSON.stringify([ + { segmentSequence: 1, routeLegSequence: 1 }, + { segmentSequence: 1, routeLegSequence: 2 }, + ]), + }); + expect(rows).toHaveLength(2); + const labeled = [ + { name: '运输费', amount: 'CNY 9000' }, + { name: '运输费', amount: 'CNY 9600' }, + ]; + applyLandLegLabels(labeled, { + landSegments: JSON.stringify([ + { segmentSequence: 1, routeLegSequence: 1 }, + { segmentSequence: 1, routeLegSequence: 2 }, + ]), + }); + expect(labeled.map((x) => x.name)).toEqual(['运输费(第1段)', '运输费(第2段)']); +});