Files
inquiry_robot/inquiry-agent/agent/schema/quote_adjust.py
T
linmianxun 9d7bc2b787 员工岗位与数据范围权限上线,企微群机器人接入与报价回执去重
- 新增员工岗位(InquiryStaffRole)实体、服务与后台页面,数据范围默认按岗位,看板由「仅本人」切换为岗位范围,补充业务负责人与角色说明迁移
- 新增企微群 webhook 通道、access_gate/staff_roles 鉴权与智价通/双 BOT 回复配置
- 报价回执增加去重防抖(quote_receipt_debounce),询价原文落库并补单测
- 同义词补陆运类型修正与地名通配 v2,更新种子生成脚本
- 空运/陆运/海运询价流程、报价单按需生成、转人工与多段处理调整
- 后台工单需求字段、BOT 显示名、站点标题与看板配套更新
2026-12-04 20:16:28 +08:00

2308 lines
86 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.
"""
调价规则:抽项结构、费用对齐、比例/改到、币种合计、利润点。
本文件职责:只算新价,不发企微、不改六态、不写主账。
模型只负责「是不是调价、调哪几项」;金额必须走这里,禁止模型改价。
调用:私聊/群 Worker 槽;禁止回调线程同步跑。
"""
from __future__ import annotations
import json
import logging
import re
from dataclasses import dataclass, field
from typing import Any, Optional
logger = logging.getLogger(__name__)
_CLOSED = frozenset({"已成交", "未成交", "已关闭", "转人工"})
_QUOTED = frozenset({"已报价", "协商中"})
_PERCENT_UP = re.compile(
r"(上调|上涨|上升|上浮|提高|提升|加|涨|升)\s*(\d+(?:\.\d+)?)\s*%"
)
_PERCENT_DOWN = re.compile(r"(下调|下降|降低|减|降)\s*(\d+(?:\.\d+)?)\s*%")
# 「增加到/调整到/涨到 110%」= 改到原价的 110%,不是上调 110%。必须先于绝对金额与相对上调。
_TO_VERBS = (
"增加到|提高到|提升到|减少到|上调到|下调到|调整到|上浮到|上涨到|上升到|"
"涨到|升到|加到|减到|调到|增至|变为|变成|改为|改成|调整为|调整成"
)
_PERCENT_TO = re.compile(rf"({_TO_VERBS})\s*(\d+(?:\.\d+)?)\s*%")
# 金额前常带币种(「提高到USD 1330.00」),不能因为中间夹了 USD 就抽不到。
_CURRENCY_PREFIX = r"(?:CNY|RMB|USD|EUR|HKD|JPY|GBP|人民币|美元|港币|欧元|日元)"
# (?!\d) 防止「增加到110%」回退成「加到11」;(?!\s*%) 把带百分号的留给 _PERCENT_TO。
_TARGET = re.compile(
rf"({_TO_VERBS})\s*(?:{_CURRENCY_PREFIX}\s*)?(\d+(?:\.\d+)?)(?!\d)(?!\s*%)",
re.I,
)
_DAO_PERCENT = re.compile(rf"(?:{_TO_VERBS})\s*(\d+(?:\.\d+)?)\s*%")
# 不带动词的改价:「运费CNY1000」「运输费1000元/车」。金额必须在句尾(可带元/块/单位),
# 避免把「运输费2段」这种描述当成改价。
_BARE_AMOUNT = re.compile(
rf"(?:{_CURRENCY_PREFIX}\s*)?(\d+(?:\.\d+)?)\s*(?:元|块)?"
r"(?:\s*[/每]\s*[^\s,,。;;]{1,6})?\s*$",
re.I,
)
_SPLIT = re.compile(r"[,,;;。!!??\n]|和(?=\S)")
_FEE_TOKEN = re.compile(r"([\u4e00-\u9fffA-Za-z0-9]{1,16}费)")
_TOTAL_WORDS = ("费用合计", "合计", "总价", "汇总价", "总销售价", "总成本价")
_QUOTE_WORD = "报价"
@dataclass
class AdjustItem:
"""
一条抽出来的调价项。kind=percent 时 value 是比例;kind=target 时 value 是金额。
target_key:销售从候选里选了哪一行时,记下该行的稳定键;
None/空串表示还没定向,仍按费用名匹配(同名多行会要求先选)。
"""
fee_name: str
kind: str
direction: str
value: float
target_key: str = ""
@dataclass
class AdjustExtract:
"""一句话抽完的调价意图。wants_total=只动合计数字,不改明细。"""
is_adjust: bool
items: list[AdjustItem] = field(default_factory=list)
wants_total: bool = False
@dataclass
class ApplyResult:
"""规则算完的结果。quote 是新副本,入参原报价不被改。"""
ok: bool
code: str
quote: dict[str, Any]
applied: list[dict[str, Any]] = field(default_factory=list)
unmatched: list[str] = field(default_factory=list)
ambiguous: list[str] = field(default_factory=list)
currency_hint: bool = False
lines_hint: bool = False
profit_point: Optional[float] = None
# code=choose_item 时的候选:[{label, name, key}],按卡片顺序。
choices: list[dict[str, str]] = field(default_factory=list)
@dataclass
class AdjustPreview:
"""只做定向判断,不算价。ops 在回「识别回执」之前用它拦住歧义指令。"""
code: str
choices: list[dict[str, str]] = field(default_factory=list)
item_index: int = 0
unmatched: list[str] = field(default_factory=list)
def private_session_can_adjust(status: str, has_quote: bool, collab_chat_id: str) -> str:
"""
私聊能不能按未协同套走。空串=可以。
already_collab / closed / no_quote 给话术用。
"""
if (collab_chat_id or "").strip():
return "already_collab"
st = (status or "").strip()
if st in _CLOSED:
return "closed"
if st not in _QUOTED or not has_quote:
return "no_quote"
return ""
def _fee_key(name: str) -> str:
raw = (name or "").replace(" ", "").replace("(", "(").replace(")", ")")
for sep in ("/", "/"):
if sep in raw:
raw = raw.split(sep, 1)[0]
return raw.strip()
_TOTAL_ALIASES = frozenset({"费用合计", "总销售价", "总成本价", "汇总价", "总价"})
def fee_name_same(left: str, right: str) -> bool:
"""费用名对齐:海运费=海运费用;操作费 ≠ 码头操作费。汇总行的旧称呼也算同一行。"""
a = _fee_key(left)
b = _fee_key(right)
if not a or not b:
return False
if a in _TOTAL_ALIASES and b in _TOTAL_ALIASES:
return True
if a == b:
return True
if a == b + "用" or a == b + "费用" or b == a + "用" or b == a + "费用":
return True
if a + "费" == b or b + "费" == a:
return True
if len(a) >= 3 and len(a) == len(b) and a[:-1] == b[:-1] and (a.endswith("费") or b.endswith("费")):
return True
return False
# 费用名口语简称:只参与调价定向,不参与卡片/报价单展示。
# 产品口径(2026-11-25):TMS 只有「运输费」时,销售说「运费」要能对上;
# 海运多项目说「运费」时,命中多项就反问,不替销售猜。
_FEE_ALIASES: dict[str, tuple[str, ...]] = {
"运费": ("运输费", "海运费", "空运费", "陆运费"),
"运输费": ("运费", "陆运费"),
"陆运费": ("运输费", "运费"),
"海运费": ("运费", "海运费用"),
"空运费": ("运费", "空运费用"),
"报关": ("报关费",),
"报关费": ("报关",),
"拖车": ("拖车费", "拖车费(含税)"),
"拖车费": ("拖车",),
}
def _fee_alias_group(name: str) -> set[str]:
"""把费用名扩成同义组(两跳,别名表很小)。空名返回空集。"""
key = _fee_key(name)
if not key:
return set()
out = {key}
for _ in range(2):
for canon, group in _FEE_ALIASES.items():
values = {canon, *group}
if out & values:
out |= values
return out
def _name_matches_exact(spoken: str, row_name: str) -> bool:
"""精确/简称级匹配。不包含子串兜底(避免「操作费」吃掉「码头操作费」)。"""
if fee_name_same(spoken, row_name):
return True
return bool(_fee_alias_group(spoken) & _fee_alias_group(row_name))
def match_fee_rows(
spoken: str,
rows: list[dict[str, Any]],
*,
target_key: str = "",
) -> list[int]:
"""
一句话里的费用名对上当前报价的哪些**行**。
返回行下标。0/1/多条都原样返回,由调用方决定改还是反问。
同名多行必须返回多个下标:陆运两段都叫「运输费」时,禁止把两段一起改。
"""
raw = (spoken or "").strip()
key_hint = (target_key or "").strip()
if key_hint:
for i, row in enumerate(rows):
if str(row.get("_row_key") or "") == key_hint:
return [i]
# 报价已变、旧键对不上:退回按名字匹配,宁可多问一次。
if raw:
idxs = [
i
for i, row in enumerate(rows)
if _name_matches_exact(raw, str(row.get("name") or ""))
]
if idxs:
return idxs
spoken_key = _fee_key(raw)
if not spoken_key:
return []
return [
i
for i, row in enumerate(rows)
if _fee_key(str(row.get("name") or ""))
and (
spoken_key in _fee_key(str(row.get("name") or ""))
or _fee_key(str(row.get("name") or "")) in spoken_key
)
]
def match_fee_names(spoken: str, rows: list[dict[str, Any]]) -> list[str]:
"""对上当前明细里的费用名(去重);保留给旧调用方。"""
hits: list[str] = []
for idx in match_fee_rows(spoken, rows):
name = str(rows[idx].get("name") or "").strip()
if name and name not in hits:
hits.append(name)
return hits
_BUCKET_LABELS = {
"polCostItems": "始发港",
"oceanCostItems": "海运",
"podCostItems": "目的港",
}
def row_display_label(row: dict[str, Any], quote: dict[str, Any] | None = None) -> str:
"""
反问「改哪一项」时的可区分标签:段名 + 费用名 + 金额。
陆运两段同名运输费、海运两段同名操作费,必须靠段名区分;
否则销售看到「运输费、运输费」无法选择(2026-11-25 截图 WO202611220035)。
"""
src = dict(row or {})
name = str(src.get("name") or "").strip()
prefix = ""
leg = src.get("_land_leg")
if isinstance(leg, int):
try:
from agent.schema.land_route_options import land_leg_fee_blocks
blocks = land_leg_fee_blocks(quote)
if 0 <= leg < len(blocks):
prefix = str(blocks[leg][0] or "").strip()
except Exception:
prefix = ""
if not prefix:
prefix = _BUCKET_LABELS.get(str(src.get("_bucket") or ""), "")
if not prefix:
prefix = str(src.get("project") or "").strip()
body = f"{prefix} {name}".strip() if prefix else name
amount = str(src.get("amount") or "").strip()
if amount and amount != "-":
ccy = str(src.get("currency") or "").strip()
upper = amount.upper()
money = f"{ccy} {amount}".strip() if ccy and not upper.startswith(ccy.upper()) else amount
body = f"{body}({money})"
return body
def _row_choice(row: dict[str, Any], quote: dict[str, Any] | None = None) -> dict[str, str]:
"""候选:给人看的 label + 回选时用的稳定键。"""
return {
"label": row_display_label(row, quote),
"name": str(row.get("name") or "").strip(),
"key": str(row.get("_row_key") or ""),
}
def _row_key(row: dict[str, Any]) -> str:
"""一行的稳定标识:名字 + 路段/分段 + 原始金额 + 币种。"""
leg = row.get("_land_leg")
return "|".join(
[
_fee_key(str(row.get("name") or "")),
"" if leg is None else str(leg),
str(row.get("_bucket") or ""),
str(row.get("_origin") or row.get("amount") or "").strip(),
str(row.get("currency") or "").strip().upper(),
]
)
def _fx_rates(quote: dict[str, Any] | None) -> list[dict[str, Any]]:
"""
读 TMS 透传的 fxRates[](fromCurrency/toCurrency/rate)。
主账有时给 JSON 字符串。读不了返回空表:调用方按「没有汇率」处理,禁止编汇率。
"""
raw = (quote or {}).get("fxRates")
if raw in (None, ""):
raw = (quote or {}).get("fx_rates")
if isinstance(raw, str) and raw.strip():
try:
raw = json.loads(raw)
except json.JSONDecodeError:
return []
if not isinstance(raw, list):
return []
out: list[dict[str, Any]] = []
for row in raw:
if not isinstance(row, dict):
continue
from_ccy = _ccy_code(
row.get("fromCurrency") or row.get("from_currency") or row.get("from")
)
to_ccy = _ccy_code(
row.get("toCurrency") or row.get("to_currency") or row.get("to")
)
try:
rate = float(row.get("rate"))
except (TypeError, ValueError):
continue
if from_ccy and to_ccy and rate > 0:
out.append({"from": from_ccy, "to": to_ccy, "rate": rate})
return out
def convert_amount(
amount: float,
from_ccy: str,
to_ccy: str,
rates: list[dict[str, Any]] | None,
) -> Optional[float]:
"""按 TMS 汇率换算;同币种原样返回;没有可用汇率返回 None(不编)。"""
value = float(amount)
src = _ccy_code(from_ccy)
dst = _ccy_code(to_ccy)
if not dst or not src or src == dst:
return value
table = rates or []
for row in table:
if row.get("from") == src and row.get("to") == dst:
return value * float(row["rate"])
for row in table:
if row.get("from") == dst and row.get("to") == src:
return value / float(row["rate"])
return None
# 海运卡按三段展示。小计是卡上的一行,不在扁平 fee_lines 里。
_SEA_BUCKETS = (
("polCostItems", "始发港费用小计"),
("oceanCostItems", "海运费小计"),
("podCostItems", "目的港费用小计"),
)
def _bucket_items(quote: dict[str, Any], key: str) -> list[dict[str, Any]]:
"""读海运分段。主账有时给列表,有时给 JSON 字符串。"""
raw = quote.get(key)
if raw in (None, ""):
raw = quote.get("fee_rows_" + key)
if isinstance(raw, str) and raw.strip():
try:
raw = json.loads(raw)
except json.JSONDecodeError:
return []
if not isinstance(raw, list):
return []
return [dict(row) for row in raw if isinstance(row, dict)]
def _item_fee_name(item: dict[str, Any]) -> str:
return str(item.get("name") or item.get("label") or item.get("feeName") or "").strip()
def _same_money(left: Any, right: Any) -> bool:
"""两条金额是否同一笔,用来把同名费用配回原来那一行。"""
a, _ = parse_money(left)
b, _ = parse_money(right)
if a is None or b is None:
return False
return abs(a - b) < 0.0001
def _plain_amount(amount: str) -> str:
"""写回分段时去掉币种前缀,避免小计被展示成 CNY CNY。"""
text = str(amount or "").strip()
for prefix in ("USD", "CNY", "EUR", "HKD", "JPY", "GBP", "RMB"):
if text.upper().startswith(prefix):
return text[len(prefix) :].strip()
return text
def _store_bucket(quote: dict[str, Any], key: str, items: list[dict[str, Any]]) -> None:
"""分段和 fee_rows_ 键一起改,卡和模板读的是这两处。"""
if key in quote or quote.get(key) not in (None, ""):
quote[key] = items
alt = "fee_rows_" + key
if alt in quote or quote.get(alt) not in (None, ""):
quote[alt] = json.dumps(items, ensure_ascii=False)
def _ccy_code(raw: Any) -> str:
"""币种归一:RMB 统一成 CNY;空串表示沿用表头。"""
code = str(raw or "").strip().upper()
return "CNY" if code == "RMB" else code
def _sea_bucket_snapshot(quote: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
"""
调价前先记住每段小计与明细币种。
为什么必须先记:一旦改了明细行,就再也算不出 TMS 当时用的小计口径
(尤其美元段小计是人民币,必须用原小计/原明细和反推,不能编汇率)。
"""
src = dict(quote or {})
header = _ccy_code(src.get("currency") or src.get("currencyCode"))
out: dict[str, dict[str, Any]] = {}
for key, _label in _SEA_BUCKETS:
sub_text = str(src.get("fee_total_" + key) or "").strip()
sub_amt, sub_prefix = parse_money(sub_text)
amounts: list[float] = []
ccys: set[str] = set()
for item in _bucket_items(src, key):
amount, prefix = parse_money(
item.get("amount") or item.get("value") or item.get("salePrice")
)
if amount is None:
continue
amounts.append(amount)
ccys.add(_ccy_code(item.get("currency") or prefix or header))
out[key] = {
"subtotal": sub_amt,
"sub_ccy": _ccy_code(sub_prefix or header),
"items_total": sum(amounts),
"line_ccys": ccys,
}
return out
def _set_subtotal_row(
rows: list[dict[str, Any]], bucket: str, new_value: float
) -> None:
"""把算好的小计写回这一行,_write_adjusted_buckets 再落 fee_total_*。"""
sub_key = "fee_total_" + bucket
text = format_money(new_value)
for row in rows:
if str(row.get("_subtotal_key") or "") == sub_key:
row["amount"] = text
return
def recompute_sea_bucket_totals(
base: dict[str, Any] | None,
new_rows: list[dict[str, Any]],
) -> dict[str, Any]:
"""
产品按行改价后,按 TMS 原小计口径重算海运三段小计。
返回:
subtotals {bucket: 小数计文本}
delta 合计应增加的人民币差额(只含能落到表头币种的小计)
bucket_rows 已算进小计的新明细下标,调用方算合计时不能再把这行加一次
currency_hint 有外币差额没法落合计时为 True
为什么不直接加明细:美元段的小计是人民币,TMS 原小计 ÷ 原明细和
就是 TMS 自己用的口径;用比例放大差额,不另编汇率。
"""
src = dict(base or {})
snap = _sea_bucket_snapshot(src)
rows = [dict(x) for x in (new_rows or []) if isinstance(x, dict)]
header = _ccy_code(src.get("currency") or src.get("currencyCode"))
used: set[int] = set()
subtotals: dict[str, str] = {}
bucket_rows: set[int] = set()
delta = 0.0
currency_hint = False
for key, _label in _SEA_BUCKETS:
items = _bucket_items(src, key)
if not items:
continue
state = snap.get(key) or {}
old_sub = state.get("subtotal")
old_rows = items
# 先按名称把新明细配回本段原行,和 stamp_prices_for_sheet 用同一套顺序。
matched: list[tuple[int, float, float]] = []
for item in old_rows:
amount, prefix = parse_money(
item.get("amount") or item.get("value") or item.get("salePrice")
)
idx = _match_fee_index(_item_fee_name(item), rows, used)
if amount is None or idx < 0:
continue
new_amount, _ = parse_money(
rows[idx].get("amount") or rows[idx].get("value") or rows[idx].get("salePrice")
)
if new_amount is None:
continue
used.add(idx)
matched.append((idx, amount, new_amount))
if not matched:
continue
native_delta = sum(new - old for _idx, old, new in matched)
if old_sub is None:
# 没有 TMS 小计:同币种差额直接给合计,外币才提示。
line_ccys = {c for c in (state.get("line_ccys") or set()) if c}
if not header or not line_ccys or line_ccys == {header}:
delta += native_delta
bucket_rows.update(idx for idx, _old, _new in matched)
else:
currency_hint = True
continue
sub_ccy = _ccy_code(state.get("sub_ccy") or header)
if sub_ccy and header and sub_ccy != header:
currency_hint = True
continue
line_ccys = {c for c in (state.get("line_ccys") or set()) if c}
if not line_ccys or line_ccys == {sub_ccy}:
delta_sub = native_delta
elif len(line_ccys) == 1:
base_sum = float(state.get("items_total") or 0)
if base_sum > 1e-9:
delta_sub = native_delta * (old_sub / base_sum)
else:
currency_hint = True
continue
else:
if len(matched) == 1 and abs(matched[0][1]) > 1e-9:
_idx, old_line, new_line = matched[0]
delta_sub = old_sub * (new_line / old_line - 1)
else:
currency_hint = True
continue
subtotals[key] = format_money(old_sub + delta_sub)
bucket_rows.update(idx for idx, _old, _new in matched)
delta += delta_sub
return {
"subtotals": subtotals,
"delta": delta,
"bucket_rows": bucket_rows,
"currency_hint": currency_hint,
}
def adjustable_rows(quote: dict[str, Any] | None) -> list[dict[str, Any]]:
"""
调价能对上的行:扁平明细,加上海运分段里的费目和小计。
小计只用来对「始发港费用小计」这类话,不写进 fee_lines。
"""
src = dict(quote or {})
rows = [dict(x) for x in quote_fee_rows(src)]
for row in rows:
row["_origin"] = str(row.get("amount") or "")
header = str(src.get("currency") or src.get("currencyCode") or "").strip()
for key, sub_label in _SEA_BUCKETS:
used: set[int] = set()
for item in _bucket_items(src, key):
name = _item_fee_name(item)
amount = str(item.get("amount") or item.get("value") or item.get("salePrice") or "").strip()
if not name or not amount:
continue
idx = next(
(
i
for i, row in enumerate(rows)
if i not in used
and not row.get("_subtotal_key")
and not row.get("_is_total")
and fee_name_same(name, str(row.get("name") or ""))
and _same_money(row.get("_origin"), amount)
),
-1,
)
if idx < 0:
rows.append(
{
"name": name,
"amount": amount,
"currency": item.get("currency") or header,
"_bucket": key,
"_origin": amount,
}
)
used.add(len(rows) - 1)
else:
rows[idx]["_bucket"] = key
used.add(idx)
subtotal = str(src.get("fee_total_" + key) or "").strip()
if subtotal and subtotal != "-":
rows.append(
{
"name": sub_label,
"amount": subtotal,
"currency": header,
"_subtotal_key": "fee_total_" + key,
"_bucket": key,
}
)
_attach_land_legs(src, rows)
total = str(src.get("total") or "").strip()
if total and total != "-":
rows.append(
{
"name": total_price_label(
str(src.get("business_line") or ""),
quote=src,
),
"amount": total,
"currency": header,
"_is_total": True,
}
)
# 稳定键:反问后销售回选序号/项目名时,下一次按它定向到同一行。
for row in rows:
row["_row_key"] = _row_key(row)
return rows
def real_fee_rows(rows: list[dict[str, Any]]) -> list[int]:
"""真正的费用细项下标:不含小计行和费用合计行。"""
return [
i
for i, row in enumerate(rows)
if not row.get("_subtotal_key") and not row.get("_is_total")
]
def _attach_land_legs(quote: dict[str, Any], rows: list[dict[str, Any]]) -> None:
"""陆运卡按段展示。同名费用每段一行,改价要写回路段成本。"""
from agent.schema.land_route_options import land_leg_fee_blocks
used: set[int] = set()
for index, (_title, fees, _eta) in enumerate(land_leg_fee_blocks(quote)):
for fee in fees:
name = str(fee.get("name") or "").strip()
amount = str(fee.get("amount") or "").strip()
if not name or not amount:
continue
idx = next(
(
i
for i, row in enumerate(rows)
if i not in used
and not row.get("_subtotal_key")
and not row.get("_is_total")
and fee_name_same(name, str(row.get("name") or ""))
and str(row.get("amount") or "") == amount
),
-1,
)
if idx < 0:
rows.append(
{
"name": name,
"amount": amount,
"currency": fee.get("currency") or quote.get("currency") or "",
"_land_leg": index,
}
)
used.add(len(rows) - 1)
else:
rows[idx]["_land_leg"] = index
used.add(idx)
def _write_adjusted_buckets(quote: dict[str, Any], rows: list[dict[str, Any]]) -> None:
"""把改过的费目和小计写回海运分段,价格卡才看得到。"""
for key, _label in _SEA_BUCKETS:
items = _bucket_items(quote, key)
changed = False
used: set[int] = set()
for item in items:
name = _item_fee_name(item)
origin = str(item.get("amount") or item.get("value") or item.get("salePrice") or "")
hit_i = next(
(
i
for i, row in enumerate(rows)
if i not in used
and row.get("_bucket") == key
and not row.get("_subtotal_key")
and fee_name_same(name, str(row.get("name") or ""))
and _same_money(row.get("_origin"), origin)
),
-1,
)
if hit_i < 0:
continue
used.add(hit_i)
plain = _plain_amount(str(rows[hit_i].get("amount") or ""))
if not plain:
continue
item["amount"] = plain
if item.get("name"):
item["name"] = name
for field_name in ("salePrice", "value", "unit_price"):
if item.get(field_name) not in (None, ""):
item[field_name] = plain
changed = True
if changed:
_store_bucket(quote, key, items)
for row in rows:
sub_key = str(row.get("_subtotal_key") or "")
if sub_key:
quote[sub_key] = _plain_amount(str(row.get("amount") or ""))
_write_land_legs(quote, rows)
def _write_land_legs(quote: dict[str, Any], rows: list[dict[str, Any]]) -> None:
"""路段成本改掉,下次出卡才不会又按旧成本显示。"""
from agent.schema.land_route_options import _selected_legs
legs = _selected_legs(quote)
if not legs:
return
for row in rows:
index = row.get("_land_leg")
if index is None or not isinstance(index, int) or index >= len(legs):
continue
plain = _plain_amount(str(row.get("amount") or ""))
if not plain:
continue
leg = legs[index]
leg["costPrice"] = plain
leg["cost_price"] = plain
if leg.get("salePrice") not in (None, ""):
leg["salePrice"] = plain
selected = quote.get("selected_land_route")
if isinstance(selected, dict):
selected["legs"] = legs
quote["selected_land_route"] = selected
if quote.get("landSegments") or quote.get("land_segments"):
quote["landSegments"] = legs
def quote_fee_rows(quote: dict[str, Any] | None) -> list[dict[str, Any]]:
"""抽出费用行。TMS 常把 fee_lines 存成 JSON 字符串。"""
src = dict(quote or {})
raw = src.get("fee_rows") or src.get("fee_lines") or src.get("feeItems") or []
if isinstance(raw, str) and raw.strip():
try:
raw = json.loads(raw)
except json.JSONDecodeError:
raw = []
if not isinstance(raw, list):
return []
rows: list[dict[str, Any]] = []
for item in raw:
if not isinstance(item, dict):
continue
name = str(item.get("name") or item.get("label") or "").strip()
amount = str(item.get("amount") or item.get("value") or item.get("salePrice") or "").strip()
if name and amount:
row = dict(item)
row["name"] = name
row["amount"] = amount
rows.append(row)
return rows
def parse_money(raw: Any) -> tuple[Optional[float], str]:
"""抽出金额和币种前缀。读不了返回 (None, '')。"""
text = str(raw if raw not in (None, "") else "").strip()
if not text or text == "-":
return None, ""
ccy = ""
upper = text.upper().replace(",", "")
for prefix in ("USD", "CNY", "EUR", "HKD", "JPY", "GBP", "RMB"):
if upper.startswith(prefix):
ccy = "CNY" if prefix == "RMB" else prefix
text = text[len(prefix) :].strip()
break
cleaned = text.replace(",", "")
try:
return float(cleaned), ccy
except ValueError:
return None, ccy
def format_money(value: float, *, sample: str = "", currency: str = "") -> str:
"""金额写法跟原行对齐:有小数留两位,整数也写两位方便对账。"""
body = f"{value:.2f}"
code = (currency or "").strip().upper()
if code == "RMB":
code = "CNY"
sample_text = str(sample or "")
if code and (sample_text.upper().startswith(code) or sample_text.upper().startswith("RMB")):
return f"{code} {body}"
return body
def row_currency(row: dict[str, Any] | None, fallback: str = "") -> str:
src = dict(row or {})
code = str(src.get("currency") or src.get("currencyCode") or fallback or "").strip().upper()
if code == "RMB":
return "CNY"
if code:
return code
_, prefix = parse_money(src.get("amount"))
return prefix or (fallback or "").strip().upper().replace("RMB", "CNY")
def _parse_qty(raw: Any) -> Optional[float]:
"""数量/计费重转浮点;读不了返回 None。"""
if raw in (None, ""):
return None
try:
return float(str(raw).replace(",", "").strip())
except ValueError:
return None
def _row_or_quote_qty(row: dict[str, Any], quote: dict[str, Any] | None = None) -> Optional[float]:
"""
费用行数量;行上没有时用工单/舱位计费重兜底。
空运调价常只有 unitPrice+amount,quantity 在 chargeableWeightKg。
"""
qty = _parse_qty(row.get("quantity"))
if qty is not None:
return qty
qty = _parse_qty(row.get("chargeQuantity"))
if qty is not None:
return qty
src = dict(quote or {})
for key in ("chargeableWeightKg", "chargeable_weight_kg", "chargeableWeight"):
qty = _parse_qty(src.get(key))
if qty is not None:
return qty
opt = src.get("selected_air_option") or src.get("selectedAirOption")
if isinstance(opt, str) and opt.strip():
try:
opt = json.loads(opt)
except json.JSONDecodeError:
opt = None
if isinstance(opt, dict):
for key in ("chargeableWeightKg", "chargeable_weight_kg", "chargeableWeight"):
qty = _parse_qty(opt.get(key))
if qty is not None:
return qty
return None
def _apply_amount(row: dict[str, Any], amount: str) -> None:
"""
写入行金额;有数量时单价=金额÷数量,禁止把行合计原样塞进单价。
空运 KG:调价后金额是单价×计费重,展示读 unit_price;无数量(按票等)才单价=金额。
"""
row["amount"] = amount
qty_raw = row.get("quantity")
if qty_raw in (None, ""):
qty_raw = row.get("chargeQuantity")
qty_num: Optional[float] = None
if qty_raw not in (None, ""):
try:
qty_num = float(str(qty_raw).replace(",", "").strip())
except ValueError:
qty_num = None
amt_num, _ = parse_money(amount)
if qty_num is not None and abs(qty_num) > 1e-9 and amt_num is not None:
# 有计费数量:单价从行金额反推,避免 3385.8 被当成「每KG」
unit_plain = format_money(amt_num / qty_num, sample=str(row.get("unit_price") or row.get("unitPrice") or ""))
unit_plain = _plain_amount(unit_plain)
row["unit_price"] = unit_plain
row["unitPrice"] = unit_plain
else:
row["unit_price"] = amount
if row.get("unitPrice") not in (None, ""):
row["unitPrice"] = amount
for key in ("salePrice", "price", "value"):
if row.get(key) not in (None, ""):
row[key] = amount
def effective_quote(tms: dict[str, Any] | None, overlay: dict[str, Any] | None) -> dict[str, Any]:
"""
人工盖 TMS:同名用人工,没有的项保留 TMS,人工新增的补上。
合计先沿用 TMS,再按同币种差额加减。不做汇率。
"""
base = dict(tms or {})
rows = [dict(x) for x in quote_fee_rows(base)]
incoming = dict(overlay or {})
for item in quote_fee_rows(incoming):
name = str(item.get("name") or "").strip()
if not name:
continue
idx = next((i for i, r in enumerate(rows) if fee_name_same(name, str(r.get("name") or ""))), -1)
if idx < 0:
rows.append(dict(item))
continue
old = dict(rows[idx])
_apply_amount(old, str(item.get("amount") or ""))
if item.get("currency"):
old["currency"] = item.get("currency")
# 与 merge_quote_fees 一致:盖价保留新行的单位/数量/分段,禁止旧默认「票」残留。
for key in ("unit", "unit_price", "unitPrice", "quantity", "project", "segment"):
val = item.get(key)
if val not in (None, ""):
old[key] = val
rows[idx] = old
out = dict(base)
out["fee_rows"] = rows
out["fee_lines"] = rows
header = str(out.get("currency") or incoming.get("currency") or "").strip()
base_total, _ = parse_money(base.get("total"))
if base_total is not None:
total_ccy = row_currency({"currency": header, "amount": base.get("total")}, header)
old_rows = quote_fee_rows(base)
delta = 0.0
for new_row in rows:
new_amt, _ = parse_money(new_row.get("amount"))
if new_amt is None:
continue
line_ccy = row_currency(new_row, total_ccy)
if line_ccy and total_ccy and line_ccy != total_ccy:
continue
idx = next(
(i for i, r in enumerate(old_rows) if fee_name_same(str(new_row.get("name") or ""), str(r.get("name") or ""))),
-1,
)
if idx < 0:
delta += new_amt
continue
old_amt, _ = parse_money(old_rows[idx].get("amount"))
if old_amt is None:
continue
delta += new_amt - old_amt
out["total"] = format_money(base_total + delta, sample=str(base.get("total") or ""), currency=header)
return out
def text_has_relative_adjust(text: str) -> bool:
"""
这句话是在按比例改价:加10%、减5%、上调、上浮、加一成。
这种是销售调价,不是航线/产品报一个新金额。不打模型。
"""
raw = text or ""
if _PERCENT_UP.search(raw) or _PERCENT_DOWN.search(raw):
return True
blob = raw.replace(" ", "").replace(" ", "")
return any(phrase in blob for phrase in ("加一成", "减一成", "往上抬", "往下压", "上浮", "下浮"))
def text_has_total_only_adjust(text: str) -> bool:
"""
只动总价/总销售价/费用合计,没有点名某一项费用。
「总销售价改为180」仍是销售调价。点了「空运费」「报关费」则不是。不打模型。
"""
raw = text or ""
if not (
_TARGET.search(raw)
or _PERCENT_TO.search(raw)
or _PERCENT_UP.search(raw)
or _PERCENT_DOWN.search(raw)
):
return False
if not any(word in raw for word in _TOTAL_WORDS) and "报价" not in raw:
return False
real: list[str] = []
for name in _FEE_TOKEN.findall(raw):
if name in {"费用", "费用合计"}:
continue
if any(word in name for word in ("合计", "总价", "汇总")):
continue
real.append(name)
return not real
def extract_adjust(
text: str,
*,
fee_names: list[str] | None = None,
injected: AdjustExtract | dict[str, Any] | None = None,
allow_model: Optional[bool] = None,
chat_fn: Any = None,
allow_bare: bool = False,
) -> AdjustExtract:
"""
从一句话抽出调价项。单测可注入;正式优先 DeepSeek B。
本地回退只给无网/模型失败用,不是正式识别。
allow_model=False 时禁止打模型。
allow_bare=True 时「运费CNY1000」这种不带动词的费用名+金额也算改价;
只供私聊/群里的调价入口用,意图预判(报价 vs 调价)不能开。
"""
raw = (text or "").strip()
if injected is not None:
if isinstance(injected, AdjustExtract):
return _coerce_dao_percent(raw, injected)
items = []
for row in injected.get("items") or []:
if not isinstance(row, dict):
continue
items.append(
AdjustItem(
fee_name=str(row.get("fee_name") or "").strip(),
kind=str(row.get("kind") or "percent"),
direction=str(row.get("direction") or "up"),
value=float(row.get("value") or 0),
target_key=str(row.get("target_key") or "").strip(),
)
)
return _coerce_dao_percent(
raw,
AdjustExtract(
is_adjust=bool(injected.get("is_adjust")),
items=items,
wants_total=bool(injected.get("wants_total")),
),
)
if not raw:
return AdjustExtract(is_adjust=False)
names = [str(x).strip() for x in (fee_names or []) if str(x).strip()]
names_sorted = sorted(names, key=len, reverse=True)
use_model = allow_model
if use_model is None:
try:
from agent.config import get_settings
settings = get_settings()
use_model = bool(
getattr(settings, "llm_allow_network", False)
and getattr(settings, "llm_data_usage_confirmed", False)
)
except Exception:
use_model = False
if use_model or chat_fn is not None:
try:
from agent.llm.mode_extract_adjust import invoke_extract_adjust
modeled = invoke_extract_adjust(
raw,
fee_names=names,
allow_network=bool(use_model),
chat_fn=chat_fn,
)
if modeled is not None:
if modeled.wants_total and not modeled.items:
op = _item_from_chunk(raw, "")
if op:
modeled.items = [op]
# 模型常只抽出「费用合计」:本地再扫点名小计/费目,避免「始发港费用小计提升10%」被丢掉
local_items = _local_fee_items(raw, names_sorted, allow_bare=allow_bare)
if local_items:
seen = {
str(x.fee_name or "").strip()
for x in (modeled.items or [])
if str(x.fee_name or "").strip()
}
merged = list(modeled.items or [])
for it in local_items:
key = str(it.fee_name or "").strip()
if key and key not in seen:
merged.append(it)
seen.add(key)
modeled = AdjustExtract(
is_adjust=True,
items=merged,
wants_total=bool(modeled.wants_total),
)
return _coerce_dao_percent(raw, modeled)
except Exception:
logger.exception("调价模型抽取失败,回退本地")
total_hit = any(w in raw for w in _TOTAL_WORDS)
has_op = bool(
_PERCENT_UP.search(raw)
or _PERCENT_DOWN.search(raw)
or _PERCENT_TO.search(raw)
or _TARGET.search(raw)
)
fee_in_text = [n for n in names_sorted if n and n in raw]
if total_hit and has_op and not fee_in_text:
op = _item_from_chunk(raw, "")
return AdjustExtract(is_adjust=True, wants_total=True, items=[op] if op else [])
if _QUOTE_WORD in raw and has_op and not fee_in_text and not total_hit:
return AdjustExtract(is_adjust=True, wants_total=False)
items = _local_fee_items(raw, names_sorted, allow_bare=allow_bare)
if not items and has_op:
# 说了费用口语但和名单不完全一致:整句再扫一次
item = _item_from_chunk(raw, "")
if item:
items.append(item)
return _coerce_dao_percent(
raw, AdjustExtract(is_adjust=bool(items or has_op), items=items)
)
# 调价尝试的粗筛词:只要句子里出现这些,就算销售在试图调价。
# 不能把「价格」「报价」单独放进来,否则「这个价格再谈谈」也会被当调价。
_ADJUST_ATTEMPT_HINTS = re.compile(
r"上调|下调|上涨|下降|上浮|下浮|提高|提升|降低|增加|减少|"
r"调整|改[成为到]|调到|涨到|升到|加到|减到|增至|变为|变成|"
r"加\s*\d|减\s*\d|\d+(?:\.\d+)?\s*[%%]|[一二三四五六七八九十]\s*成"
)
# 「加一成」的口语:一=10%,二=20%…十=100%。
_CHENG_NUM = {
"一": 10, "二": 20, "三": 30, "四": 40, "五": 50,
"六": 60, "七": 70, "八": 80, "九": 90, "十": 100,
}
def inspect_adjust_recognition(
text: str,
extract: AdjustExtract,
*,
fee_names: list[str] | None = None,
) -> Optional[dict[str, Any]]:
"""
判断这句话是不是调价尝试,以及识别程度。
返回 None:不像调价,调用方按原流程继续,禁止乱回调价提示。
返回 {"status": full/partial/none, "recognized": [...], "missing": [...]}。
「部分」= 有费用名没幅度、有幅度没费用名、或只写了「改成」没写值。
副作用:无。线程:纯函数。
"""
raw = (text or "").strip()
if not raw:
return None
names = [str(n).strip() for n in (fee_names or []) if str(n).strip()]
items = list(getattr(extract, "items", []) or [])
wants_total = bool(getattr(extract, "wants_total", False))
# 完整的调价:至少一项有值,且点名了费用(或明确只改总价)。
complete = bool(getattr(extract, "is_adjust", False)) and any(
float(it.value or 0) > 0
and (str(it.fee_name or "").strip() or wants_total)
for it in items
)
looks = bool(getattr(extract, "is_adjust", False)) or bool(
_ADJUST_ATTEMPT_HINTS.search(raw)
)
if not looks:
return None
if complete:
return {"status": "full", "recognized": [], "missing": []}
recognized: list[str] = []
missing: list[str] = []
hit_name = ""
for name in sorted(names, key=len, reverse=True):
if name and name in raw:
hit_name = name
break
if not hit_name:
for word in _TOTAL_WORDS:
if word in raw:
hit_name = word
break
if hit_name:
recognized.append(f"费用名:{hit_name}")
else:
missing.append("费用名")
pct = ""
for rx in (_PERCENT_UP, _PERCENT_DOWN, _PERCENT_TO):
hit = rx.search(raw)
if hit:
pct = hit.group(0).replace(" ", "")
break
if not pct:
cheng = re.search(r"([一二三四五六七八九十])\s*成", raw)
if cheng:
pct = f"{cheng.group(1)}成({_CHENG_NUM.get(cheng.group(1), '')}%)"
if pct:
recognized.append(f"调整幅度:{pct}")
else:
target = _TARGET.search(raw)
if target:
recognized.append(f"目标金额:{target.group(0).replace(' ', '')}")
else:
missing.append("调整幅度或目标金额")
direction = ""
if _PERCENT_DOWN.search(raw) or any(
x in raw for x in ("下调", "下降", "降低", "减", "降")
):
direction = "下调"
elif _PERCENT_UP.search(raw) or any(
x in raw
for x in ("上调", "上涨", "上升", "上浮", "提高", "提升", "加", "涨", "升")
):
direction = "上调"
elif re.search(r"改[成为到]|调整[到成]|调到", raw):
direction = "改为"
if direction:
recognized.append(f"调整方式:{direction}")
return {
"status": "partial" if recognized else "none",
"recognized": recognized,
"missing": list(dict.fromkeys(missing)),
}
def _local_fee_items(
raw: str, names_sorted: list[str], *, allow_bare: bool = False
) -> list[AdjustItem]:
"""按分句把点名费目/小计抽成调价项。提升/上调等口令都认。"""
items: list[AdjustItem] = []
for part in _SPLIT.split(raw) or [raw]:
chunk = (part or "").strip()
if not chunk:
continue
spoken = ""
for name in names_sorted:
if name and name in chunk:
spoken = name
break
if not spoken:
found = _FEE_TOKEN.findall(chunk)
spoken = found[-1] if found else ""
if not spoken:
# 「费用合计提升10%」:名单里有费用合计时上面已命中;否则用合计词
if any(w in chunk for w in _TOTAL_WORDS):
spoken = "费用合计"
else:
continue
item = _item_from_chunk(chunk, spoken, allow_bare=allow_bare)
if item:
items.append(item)
return items
def _coerce_dao_percent(text: str, extract: AdjustExtract) -> AdjustExtract:
"""
「增加到110%」纠正为 percent/set。
模型常抽成 percent/up;本地旧正则会抽成绝对金额 target。两种都不能当上调。
"""
hit = _DAO_PERCENT.search(text or "")
if not hit or not extract.items:
return extract
val = float(hit.group(1))
fixed: list[AdjustItem] = []
changed = False
for item in extract.items:
same_num = abs(float(item.value) - val) < 1e-9
if item.kind == "percent" and item.direction in {"up", "down"} and same_num:
fixed.append(AdjustItem(item.fee_name, "percent", "set", val, item.target_key))
changed = True
elif item.kind == "target" and item.direction == "set" and same_num:
fixed.append(AdjustItem(item.fee_name, "percent", "set", val, item.target_key))
changed = True
else:
fixed.append(item)
if not changed:
return extract
return AdjustExtract(is_adjust=extract.is_adjust, items=fixed, wants_total=extract.wants_total)
def _item_from_chunk(chunk: str, fee_name: str, *, allow_bare: bool = False) -> Optional[AdjustItem]:
to_pct = _PERCENT_TO.search(chunk)
up = _PERCENT_UP.search(chunk)
down = _PERCENT_DOWN.search(chunk)
target = _TARGET.search(chunk)
if to_pct:
return AdjustItem(fee_name=fee_name, kind="percent", direction="set", value=float(to_pct.group(2)))
if target:
return AdjustItem(fee_name=fee_name, kind="target", direction="set", value=float(target.group(2)))
if up:
return AdjustItem(fee_name=fee_name, kind="percent", direction="up", value=float(up.group(2)))
if down:
return AdjustItem(fee_name=fee_name, kind="percent", direction="down", value=float(down.group(2)))
# 「运费CNY1000」「运费1000元/车」:点名费用+金额、不带动词,也算改到该金额。
# 只在实际调价入口开(allow_bare),否则群里的「码头操作费100CNY」会被误判成调价。
if (allow_bare and fee_name) or (
not fee_name and any(word in chunk for word in _TOTAL_WORDS)
):
bare = _BARE_AMOUNT.search(chunk)
if bare:
return AdjustItem(
fee_name=fee_name,
kind="target",
direction="set",
value=float(bare.group(1)),
)
return None
def total_price_label(
business_line: str = "",
transport_mode: str = "",
quote: dict[str, Any] | None = None,
) -> str:
"""
销售在企微看到的汇总行名称,一律叫费用合计。
不区分空运/海运/陆运,也不区分 TMS 还是销售调价。
后台成本价、销售价不走这里。Excel/PDF 报价单模板也不走这里。
"""
_ = business_line, transport_mode, quote
return "费用合计"
def _mark_sales_adjust(quote: dict[str, Any]) -> None:
"""算价成功后这版就是销售调价,卡片和后台都按销售价展示。"""
quote["source"] = "SALES_ADJUST"
quote["source_label"] = "销售调价"
def _sheet_follows_adjusted_fees(quote: dict[str, Any]) -> bool:
"""
产品、航线、销售改过的价,报价单必须跟着这份走。
航线只是确认沿用 TMS 时不改写舱位明细,避免把附加费之和当成总价。
"""
label = str(quote.get("source_label") or quote.get("sourceLabel") or "").replace(" ", "")
if "确认TMS" in label:
return False
code = str(quote.get("source") or "").strip().upper()
if code == "SALES_ADJUST" or "销售调价" in label:
return True
if code == "PRODUCT":
return True
return any(word in label for word in ("产品", "航线", "手工"))
def _json_struct(value: Any) -> tuple[Any, bool]:
"""字符串 JSON 先解开。返回 (对象, 原来是不是字符串)。"""
if isinstance(value, str) and value.strip()[:1] in {"{", "["}:
try:
return json.loads(value), True
except json.JSONDecodeError:
return value, False
return value, False
def _put_struct(quote: dict[str, Any], key: str, value: Any, was_str: bool) -> None:
quote[key] = json.dumps(value, ensure_ascii=False) if was_str else value
def _fee_title(item: dict[str, Any]) -> str:
return str(
item.get("name") or item.get("feeName") or item.get("chargeName") or item.get("label") or ""
).strip()
def _write_price(item: dict[str, Any], plain: str) -> None:
"""同一笔钱写进报价单会读的金额字段。单价有值也一起改,否则模板仍按旧单价重算。"""
if not plain:
return
for key in (
"amount",
"costPrice",
"cost_price",
"salePrice",
"sale_price",
"unitPrice",
"unit_price",
"value",
"price",
):
if item.get(key) not in (None, ""):
item[key] = plain
item["amount"] = plain
if item.get("costPrice") not in (None, "") or item.get("cost_price") not in (None, "") or "costPrice" in item:
item["costPrice"] = plain
def _sync_line_currency(item: dict[str, Any], fee: dict[str, Any]) -> None:
"""
产品手工报价写了币种时,报价单读的那份副本必须同步行币种。
为何:模板「币别」列直接取 podCostItems / 舱位费 / 路段行的 currency。
旧逻辑只把金额盖进副本、不盖币种,结果 TMS 原币种(CNY)把产品写的 USD
吃掉,报价单成了「文件费 CNY 60.00」(2026-11-22 真机)。
空币种一律不动:没写币种时沿用原行(通常已从 TMS/表头继承),禁止在这里猜。
"""
ccy = str(fee.get("currency") or fee.get("currencyCode") or "").strip()
if ccy:
item["currency"] = ccy
def _match_fee_index(name: str, fees: list[dict[str, Any]], used: set[int]) -> int:
return next(
(
i
for i, fee in enumerate(fees)
if i not in used and fee_name_same(name, _fee_title(fee))
),
-1,
)
def _fee_air_project(fee: dict[str, Any]) -> str:
"""
空运费用落到哪一段:有 project 跟 project;否则空运费进空运段,其余进起运港。
与主账 mergeAirBucketRowsWithFlatManualFees 兜底一致,避免增值费进不了起运港。
"""
project = str(fee.get("project") or fee.get("segment") or "").strip()
if project in {"空运段", "空运"}:
return "空运段"
if project in {"起运港", "起运地"}:
return "起运港"
if project in {"目的地", "目的港"}:
return "目的地"
if project in {"其它", "其他"}:
return "其它"
name = _fee_title(fee)
if "空运" in name and "增值" not in name and "增点" not in name:
return "空运段"
return "起运港"
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 "")
)
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
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 []
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) 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)
]
else:
used: set[int] = set()
for item in items:
idx = _match_fee_index(_fee_title(item), fees, used)
if idx < 0:
continue
used.add(idx)
_write_price(item, _plain_amount(str(fees[idx].get("amount") or "")))
_sync_line_currency(item, fees[idx])
if not item.get("name"):
item["name"] = _fee_title(fees[idx])
if not item.get("feeName"):
item["feeName"] = _fee_title(fees[idx])
# 调价新增的空运段费目也要进 feeItems,否则模板只读舱位桶时看不到
for i, fee in enumerate(fees):
if i in used or _fee_air_project(fee) != "空运段":
continue
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 "",
}
)
used.add(i)
if items:
_put_struct(quote, "feeItems", items, was_str)
def _stamp_one_route(row: dict[str, Any], fees: list[dict[str, Any]]) -> None:
"""一段线路:运输费写金额,提货/送货写到对应列。"""
if len(fees) == 1:
_write_price(row, _plain_amount(str(fees[0].get("amount") or "")))
_sync_line_currency(row, fees[0])
return
transport = [fee for fee in fees if any(word in _fee_title(fee) for word in ("运输", "运费", "陆运"))]
if len(transport) == 1:
_write_price(row, _plain_amount(str(transport[0].get("amount") or "")))
# 路段行只有一个币种格:主运输费点明币种时,路段整段跟它走。
_sync_line_currency(row, transport[0])
for fee in fees:
title = _fee_title(fee)
plain = _plain_amount(str(fee.get("amount") or ""))
if not plain:
continue
if "提货" in title:
row["pickup_fee"] = plain
row["pickupFee"] = plain
elif "送货" in title or "派送" in title:
row["delivery_fee"] = plain
row["deliveryFee"] = plain
def _stamp_route_list(rows: list[Any], fees: list[dict[str, Any]]) -> None:
legs = [row for row in rows if isinstance(row, dict)]
if not legs or not fees:
return
if len(legs) == len(fees):
for leg, fee in zip(legs, fees):
ccy_before = str(leg.get("currency") or "")
_write_price(leg, _plain_amount(str(fee.get("amount") or "")))
_sync_line_currency(leg, fee)
return
if len(legs) == 1:
ccy_before = str(legs[0].get("currency") or "")
_stamp_one_route(legs[0], fees)
def _stamp_route_copies(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None:
"""陆运报价单优先读 route_rows,不读已经改过的 fee_lines。"""
for key in ("route_rows", "landSegments", "land_segments"):
raw, was_str = _json_struct(quote.get(key))
if not isinstance(raw, list) or not raw:
continue
copied = [dict(x) if isinstance(x, dict) else x for x in raw]
_stamp_route_list(copied, fees)
_put_struct(quote, key, copied, was_str)
for key in ("selected_land_route", "selectedLandRoute"):
raw, was_str = _json_struct(quote.get(key))
if not isinstance(raw, dict):
continue
selected = dict(raw)
legs = [dict(x) if isinstance(x, dict) else x for x in list(selected.get("legs") or [])]
if not legs:
continue
_stamp_route_list(legs, fees)
selected["legs"] = legs
_put_struct(quote, key, selected, was_str)
def _stamp_buckets(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None:
"""海运报价单按始发港/海运/目的港三段读,不能只改扁平费用行。"""
for key, _label in _SEA_BUCKETS:
items = _bucket_items(quote, key)
if not items:
continue
used: set[int] = set()
changed = False
for item in items:
idx = _match_fee_index(_item_fee_name(item), fees, used)
if idx < 0:
continue
used.add(idx)
plain = _plain_amount(str(fees[idx].get("amount") or ""))
if not plain:
continue
ccy_before = str(item.get("currency") or "")
fee_ccy = str(fees[idx].get("currency") or "")
_write_price(item, plain)
_sync_line_currency(item, fees[idx])
changed = True
if changed:
_store_bucket(quote, key, items)
def _stamp_air_bucket_list(
opt: dict[str, Any],
key_primary: str,
key_alt: str,
fees: list[dict[str, Any]],
used: set[int],
*,
projects: set[str],
quote: dict[str, Any],
) -> None:
"""
更新舱位某一费用桶,并把 fee_lines 里多出来的同段费用追加进去。
为何:调价/产品报价常只改扁平明细;模板读 departureCharges,不追加就会缺「增值费」行。
"""
charge_key = key_primary if key_primary in opt or key_alt not in opt else key_alt
if charge_key not in opt and key_primary not in opt and key_alt not in opt:
# 舱位从未带过该桶:只要有待追加费用就新建,否则不动
if not any(i not in used and _fee_air_project(fees[i]) in projects for i in range(len(fees))):
return
charge_key = key_primary
charges, charges_str = [], False
else:
charges, charges_str = _json_struct(opt.get(charge_key))
if not isinstance(charges, list):
charges = []
copied = [dict(x) if isinstance(x, dict) else x for x in charges]
for charge in copied:
if not isinstance(charge, dict):
continue
idx = _match_fee_index(_fee_title(charge), fees, used)
if idx < 0:
continue
used.add(idx)
plain = _plain_amount(str(fees[idx].get("amount") or ""))
ccy_before = str(charge.get("currency") or "")
_write_price(charge, plain)
_sync_line_currency(charge, fees[idx])
# 单价/数量若调价行有值也盖上,模板按单价×数量重算时才对
fee = fees[idx]
up = _plain_amount(str(fee.get("unit_price") or fee.get("unitPrice") or ""))
if up:
charge["unitPrice"] = up
charge["unit_price"] = up
qty = str(fee.get("quantity") or "").strip()
if qty:
charge["quantity"] = qty
unit = str(fee.get("unit") or "").strip()
if unit:
charge["unit"] = unit
for i, fee in enumerate(fees):
if i in used:
continue
if _fee_air_project(fee) not in projects:
continue
title = _fee_title(fee)
if not title:
continue
copied.append(_fee_as_air_charge(fee, quote=quote))
used.add(i)
opt[charge_key] = json.dumps(copied, ensure_ascii=False) if charges_str else copied
def _stamp_air_copies(quote: dict[str, Any], fees: list[dict[str, Any]]) -> None:
"""空运报价单读舱位 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))
single = isinstance(raw, dict)
options = [dict(raw)] if single else [dict(x) if isinstance(x, dict) else x for x in raw] if isinstance(raw, list) else []
if not options:
continue
for opt in options:
if not isinstance(opt, dict):
continue
used: set[int] = set()
_stamp_air_bucket_list(
opt,
"departureCharges",
"departure_charges",
fees,
used,
projects={"起运港", "其它"},
quote=quote,
)
_stamp_air_bucket_list(
opt,
"destinationCharges",
"destination_charges",
fees,
used,
projects={"目的地"},
quote=quote,
)
if total_plain:
if opt.get("salePrice") not in (None, ""):
opt["salePrice"] = total_plain
if opt.get("sale_price") not in (None, ""):
opt["sale_price"] = total_plain
if single:
_put_struct(quote, key, options[0], was_str)
else:
_put_struct(quote, key, options, was_str)
def stamp_prices_for_sheet(quote: dict[str, Any] | None) -> dict[str, Any]:
"""
把当前生效费用写进报价单实际读取的每一份副本。
销售调价、产品报价、航线报价都会改 fee_lines,但陆运单读 route_rows,
海运单读三段费用,空运单读舱位 departureCharges。这些副本不跟着改,
报价单上就还是 TMS 原价。TMS 原价和「确认沿用 TMS」不改写这些副本。
"""
src = dict(quote or {})
if not _sheet_follows_adjusted_fees(src):
return src
fees = [dict(row) for row in quote_fee_rows(src)]
if not fees:
return src
src["fee_lines"] = fees
src["fee_rows"] = fees
_stamp_fee_items(src, fees)
_stamp_route_copies(src, fees)
_stamp_buckets(src, fees)
_stamp_air_copies(src, fees)
return src
def compute_profit(*, x: Optional[float], baseline: str) -> Optional[float]:
"""
只在销售调价后算一个利润点。
基准=调价前生效价:有手工报价用手工,没有才用 TMS。
"""
if x is None:
return None
base, _ = parse_money(baseline)
if base is None or abs(base) < 1e-9:
return None
return (x - base) / base * 100.0
def _profit_baseline(
src: dict[str, Any],
*,
tms_cost: str,
tms_sale: str,
business_line: str,
) -> str:
"""第一次调价锁住基准;之后连续调仍对这一档。"""
stored = str(src.get("profit_baseline") or "").strip()
if stored:
return stored
current = str(src.get("total") or "").strip()
if current:
return current
line = (business_line or "").upper()
if line == "AIR":
return str(tms_sale or "").strip()
return str(tms_cost or tms_sale or "").strip()
def _attach_profit(
out: dict[str, Any],
src: dict[str, Any],
*,
x: Optional[float],
tms_cost: str,
tms_sale: str,
business_line: str,
) -> Optional[float]:
"""写入利润点和锁定基准。原报价没有利润点,销售没调过就不算。"""
baseline = _profit_baseline(src, tms_cost=tms_cost, tms_sale=tms_sale, business_line=business_line)
profit = compute_profit(x=x, baseline=baseline)
if profit is not None:
out["profit_point"] = profit
if baseline:
out.setdefault("profit_baseline", baseline)
line = (business_line or str(src.get("business_line") or "")).upper()
if line:
out["business_line"] = line
return profit
def _visible_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""落库/回卡的扁平明细:去掉小计、合计和内部标记字段。"""
out: list[dict[str, Any]] = []
for row in rows:
if row.get("_subtotal_key") or row.get("_is_total"):
continue
out.append({k: v for k, v in row.items() if not str(k).startswith("_")})
return out
def _apply_total_only(
src: dict[str, Any],
extract: AdjustExtract,
*,
total_ccy: str,
business_line: str,
tms_cost: str,
tms_sale: str,
rows: list[dict[str, Any]],
fx: list[dict[str, Any]],
) -> ApplyResult:
"""
只改了「费用合计/总价」,没有点名费用细项。
细项只有 1 项:合计与细项绑定,明细跟着改(跨币种按 TMS 汇率换算)。
细项 ≥2 项:不能替销售分摊,反问改哪一项(产品 2026-11-25 口径)。
"""
real = real_fee_rows(rows)
if len(real) > 1:
return ApplyResult(
ok=False,
code="choose_item",
quote=src,
choices=[_row_choice(rows[i], src) for i in real],
)
item = next((x for x in extract.items if x is not None), None)
old_total, prefix = parse_money(src.get("total"))
if item is None or old_total is None or not real:
return ApplyResult(ok=False, code="need_fee", quote=src)
if item.kind == "target":
new_amt = float(item.value)
how = f"改到 {item.value:g}"
elif item.kind == "percent" and item.direction == "set":
# 「费用合计增加到110%」= 改到原合计的 110%,不是上调 110%
new_amt = old_total * (float(item.value) / 100.0)
how = f"调到 {item.value:g}%"
elif item.direction == "down":
new_amt = old_total * (1 - float(item.value) / 100.0)
how = f"下调 {item.value:g}%"
else:
new_amt = old_total * (1 + float(item.value) / 100.0)
how = f"上调 {item.value:g}%"
out = dict(src)
idx = real[0]
row = dict(rows[idx])
line_ccy = row_currency(row, total_ccy) or prefix
currency_hint = False
line_amt: Optional[float] = new_amt
if line_ccy and total_ccy and _ccy_code(line_ccy) != _ccy_code(total_ccy):
line_amt = convert_amount(new_amt, total_ccy, line_ccy, fx)
if line_amt is None:
# 没有可用汇率:合计可以改,明细不动,并提示不能换算。
currency_hint = True
label = total_price_label(business_line, quote={"source": "SALES_ADJUST"})
applied = [
{
"name": label,
"how": how,
"amount": format_money(
new_amt, sample=str(src.get("total") or ""), currency=total_ccy or prefix
),
}
]
if line_amt is not None:
_apply_amount(
row,
format_money(line_amt, sample=str(row.get("amount") or ""), currency=line_ccy),
)
rows[idx] = row
applied.append(
{"name": row_display_label(row, src), "how": how, "amount": row["amount"]}
)
out["fee_rows"] = _visible_rows(rows)
out["fee_lines"] = _visible_rows(rows)
_write_adjusted_buckets(out, rows)
# 单项目也可能带海运小计:小计跟着这一项走,卡面才不会一个数、合计另一个数。
recomputed = recompute_sea_bucket_totals(src, _visible_rows(rows))
for bucket, text in (recomputed.get("subtotals") or {}).items():
out["fee_total_" + bucket] = _plain_amount(text)
out["total"] = format_money(
new_amt, sample=str(src.get("total") or ""), currency=total_ccy or prefix
)
profit = _attach_profit(
out,
src,
x=new_amt,
tms_cost=tms_cost or str(src.get("tms_baseline_cost") or ""),
tms_sale=tms_sale or str(src.get("tms_baseline_sale") or ""),
business_line=business_line,
)
_mark_sales_adjust(out)
# 报价单副本(海运三段/陆运路段/空运舱位)跟着这一项走,Excel 才不是旧价。
out = stamp_prices_for_sheet(out)
return ApplyResult(
ok=True,
code="applied",
quote=out,
applied=applied,
currency_hint=currency_hint,
profit_point=profit,
)
def _fold_total_into_items(
extract: AdjustExtract,
*,
business_line: str = "",
quote: dict[str, Any] | None = None,
) -> AdjustExtract:
"""
合计与费目小计写在同一条指令里时:取消 wants_total 独占,把合计并进 items。
为何:wants_total 只改 total,海运「始发港费用小计」不会动,Excel 汇总仍是旧数。
"""
if not extract.wants_total:
return extract
named = [x for x in (extract.items or []) if str(x.fee_name or "").strip()]
if not named:
return extract
label = total_price_label(business_line, quote=quote)
has_total = any(fee_name_same(str(x.fee_name or ""), label) for x in named)
items = list(named)
if not has_total:
seed = named[0]
for raw in extract.items or []:
if not str(raw.fee_name or "").strip():
seed = raw
break
items.append(
AdjustItem(
fee_name=label,
kind=seed.kind,
direction=seed.direction,
value=seed.value,
)
)
return AdjustExtract(is_adjust=True, wants_total=False, items=items)
def _is_total_name(name: str) -> bool:
"""费用合计/总价/总销售价…都算合计行名称。"""
return _fee_key(name) in _TOTAL_ALIASES or fee_name_same(name, "费用合计")
def preview_adjust(
quote: dict[str, Any] | None,
extract: AdjustExtract,
*,
business_line: str = "",
rows: list[dict[str, Any]] | None = None,
) -> AdjustPreview:
"""
只判断这句话能不能唯一落到位,不改价。
返回:
ok 每一项都能对上唯一一行(未匹配项放 unmatched,仍按旧口径部分应用)
choose_item 同名多行 / 多项改合计:必须反问改哪一项,choices 带段名标签
conflict 同一句既点名细项又改费用合计(大原则:不能同时调整)
need_fee 没点名、也没有可改的细项
none_matched 点名了费用,但卡上没有
ops 在回识别回执之前先调这里,避免「先让确认、再问指哪一项」。
"""
src = dict(quote or {})
rows = adjustable_rows(src) if rows is None else rows
named = [
item
for item in (extract.items or [])
if str(item.fee_name or "").strip() and not _is_total_name(item.fee_name)
]
explicit_total = any(
_is_total_name(str(item.fee_name or "")) for item in (extract.items or [])
)
if explicit_total and named:
# 只有「真费用细项 + 费用合计」才算冲突;小计+合计是同一句里配套改的,放行。
for item in named:
hits = match_fee_rows(
str(item.fee_name or ""), rows, target_key=item.target_key
)
if any(
not rows[i].get("_subtotal_key") and not rows[i].get("_is_total")
for i in hits
):
return AdjustPreview("conflict")
# 点名的是小计/其它合计别名:按明细项正常处理。
if (extract.wants_total or explicit_total) and not named:
real = real_fee_rows(rows)
if not real:
return AdjustPreview("need_fee")
if len(real) > 1:
return AdjustPreview(
"choose_item",
choices=[_row_choice(rows[i], src) for i in real],
)
return AdjustPreview("ok")
if not extract.items:
return AdjustPreview("need_fee")
unmatched: list[str] = []
for index, item in enumerate(extract.items):
spoken = str(item.fee_name or "").strip()
if not spoken:
if extract.wants_total:
continue
unmatched.append("未点名费用")
continue
if _is_total_name(spoken):
continue
hits = match_fee_rows(spoken, rows, target_key=item.target_key)
if len(hits) > 1:
return AdjustPreview(
"choose_item",
choices=[_row_choice(rows[i], src) for i in hits],
item_index=index,
)
if not hits:
unmatched.append(spoken)
if unmatched and len(unmatched) >= len(named):
return AdjustPreview("none_matched", unmatched=unmatched)
return AdjustPreview("ok", unmatched=unmatched)
def apply_adjust(
quote: dict[str, Any] | None,
extract: AdjustExtract,
*,
business_line: str = "",
tms_cost: str = "",
tms_sale: str = "",
) -> ApplyResult:
"""
按抽项改当前生效报价副本。
定向规则(产品 2026-11-25):
* 费用名唯一对上一行 → 改该行,并按 TMS 汇率重算小计/合计;
* 同名多行 / 多项时只改合计 → 返回 choose_item,反问改哪一项,一个数字都不改;
* 同一句既点名细项又改费用合计 → 返回 conflict(大原则:不能同时调整)。
副作用:无。原 quote 不被修改。海运小计按卡上的「始发港费用小计」改。
"""
src = dict(quote or {})
rows = adjustable_rows(src)
if not extract.is_adjust:
return ApplyResult(ok=False, code="not_adjust", quote=src)
# 先定向:同名多行、多项改合计、细项+合计混说,都在这拦住,一个数字都不改。
preview = preview_adjust(src, extract, business_line=business_line, rows=rows)
if preview.code in {"choose_item", "conflict", "need_fee"}:
return ApplyResult(
ok=False,
code=preview.code,
quote=src,
choices=preview.choices,
unmatched=preview.unmatched,
)
# 同时说了小计和「费用合计」时:不能只走合计通道,否则小计不改、Excel 汇总也不动。
extract = _fold_total_into_items(extract, business_line=business_line, quote=src)
header = str(src.get("currency") or "").strip()
total_ccy = row_currency({"currency": header, "amount": src.get("total")}, header)
fx = _fx_rates(src)
if extract.wants_total:
return _apply_total_only(
src,
extract,
total_ccy=total_ccy,
business_line=business_line,
tms_cost=tms_cost,
tms_sale=tms_sale,
rows=rows,
fx=fx,
)
if not extract.items:
return ApplyResult(ok=False, code="need_fee", quote=src)
applied: list[dict[str, Any]] = []
unmatched: list[str] = []
ambiguous: list[str] = []
# 只有真正没法落到合计的外币差额才提示汇率;有 fxRates 就按 TMS 汇率折算。
currency_hint = False
total_amt, _ = parse_money(src.get("total"))
new_total = total_amt
total_touched = False
total_new_value: Optional[float] = None
real_idx = real_fee_rows(rows)
single_line = len(real_idx) == 1
single_line_idx = real_idx[0] if single_line else -1
single_line_new: Optional[float] = None
single_line_new_ccy = ""
# 调价前的小计/币种快照:改完明细后再算小计,必须靠它反推 TMS 当时的口径。
bucket_snapshot = _sea_bucket_snapshot(src)
bucket_line_delta: dict[str, float] = {}
bucket_changed_lines: dict[str, list[tuple[float, float]]] = {}
explicit_subtotal: dict[str, float] = {}
line_delta_total = 0.0
target_ccy = total_ccy or header
for item in extract.items:
spoken = (item.fee_name or "").strip()
if not spoken:
unmatched.append(spoken or "未点名费用")
continue
hits = match_fee_rows(spoken, rows, target_key=item.target_key)
if len(hits) > 1:
# preview 已拦;这里兜底,绝不把同名多行一起改。
ambiguous.append(spoken)
continue
if not hits:
unmatched.append(spoken)
continue
idx = hits[0]
row = dict(rows[idx])
old_amt, prefix = parse_money(row.get("amount"))
if old_amt is None:
unmatched.append(spoken)
continue
line_ccy = row_currency(row, header) or prefix
old_up, _ = parse_money(row.get("unit_price") or row.get("unitPrice"))
qty_num = _row_or_quote_qty(row, src)
# 有单价且有计费重:比例调价按「单价」缩放,再算行金额=单价×数量。
# 否则会把行合计×110% 后整笔写进单价(15→42633.53)。
scale_by_unit = (
item.kind == "percent"
and old_up is not None
and qty_num is not None
and abs(qty_num) > 1e-9
and abs(old_up - old_amt) > 1e-6
)
if scale_by_unit:
if item.direction == "set":
new_up = old_up * (float(item.value) / 100.0)
how = f"调到 {item.value:g}%"
elif item.direction == "down":
new_up = old_up * (1 - float(item.value) / 100.0)
how = f"下调 {item.value:g}%"
else:
new_up = old_up * (1 + float(item.value) / 100.0)
how = f"上调 {item.value:g}%"
new_amt = new_up * qty_num
if row.get("quantity") in (None, ""):
row["quantity"] = f"{qty_num:.10g}"
elif item.kind == "target":
new_amt = float(item.value)
how = f"改到 {item.value:g}"
elif item.kind == "percent" and item.direction == "set":
# 「运输费增加到110%」= 原价 × 110%,不是上调 110%(×210%)
new_amt = old_amt * (float(item.value) / 100.0)
how = f"调到 {item.value:g}%"
elif item.direction == "down":
new_amt = old_amt * (1 - float(item.value) / 100.0)
how = f"下调 {item.value:g}%"
else:
new_amt = old_amt * (1 + float(item.value) / 100.0)
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))
rows[idx] = row
applied.append({"name": row_display_label(row, src), "how": how, "amount": row["amount"]})
bucket = str(row.get("_bucket") or "")
if row.get("_is_total"):
total_touched = True
total_new_value = new_amt
continue
if row.get("_subtotal_key"):
# 点名小计:小计数字以销售说的为准,明细是否另调看有没有点名费目。
explicit_subtotal[bucket] = new_amt
continue
if idx == single_line_idx:
single_line_new = new_amt
single_line_new_ccy = line_ccy or prefix
if bucket:
bucket_line_delta[bucket] = bucket_line_delta.get(bucket, 0.0) + (new_amt - old_amt)
bucket_changed_lines.setdefault(bucket, []).append((old_amt, new_amt))
continue
# 非分段行:同币种差额直接进合计;外币按 TMS 汇率折算,没有汇率才提示。
line_ccy_code = _ccy_code(line_ccy or prefix)
if not target_ccy or not line_ccy_code or line_ccy_code == target_ccy:
line_delta_total += new_amt - old_amt
else:
converted = convert_amount(new_amt - old_amt, line_ccy_code, target_ccy, fx)
if converted is None:
currency_hint = True
else:
line_delta_total += converted
# 按段重算小计:优先用 TMS 返回的 fxRates 把外币差额折成小计币种;
# 没回汇率时退回 TMS 自己的口径(原小计 ÷ 原明细和),禁止另编汇率。
subtotal_delta_total = 0.0
for bucket, native_delta in bucket_line_delta.items():
if bucket in explicit_subtotal:
# 小计由销售点名,差额在下面统一算,避免明细差额再叠一次。
continue
snap = bucket_snapshot.get(bucket) or {}
old_sub = snap.get("subtotal")
sub_ccy = _ccy_code(snap.get("sub_ccy") or header)
line_ccys = {c for c in (snap.get("line_ccys") or set()) if c}
if old_sub is None:
# 没有 TMS 小计:能折算就折算进合计,折不了才提示。
if not target_ccy or not line_ccys or line_ccys == {target_ccy}:
subtotal_delta_total += native_delta
elif len(line_ccys) == 1:
one = next(iter(line_ccys))
conv = convert_amount(native_delta, one, target_ccy, fx)
if conv is None:
currency_hint = True
else:
subtotal_delta_total += conv
else:
# 同段混币种又没有小计口径:不猜,提示。
currency_hint = True
continue
if not line_ccys or line_ccys == {sub_ccy}:
delta_sub = native_delta
elif len(line_ccys) == 1:
one = next(iter(line_ccys))
conv = convert_amount(native_delta, one, sub_ccy, fx) if one != sub_ccy else native_delta
if conv is not None:
delta_sub = conv
else:
base = float(snap.get("items_total") or 0)
if base > 1e-9:
delta_sub = native_delta * (old_sub / base)
else:
currency_hint = True
continue
else:
# 同一段混了多币种:只有单行调整时按该行比例缩放小计;多行无法拆分。
changed = bucket_changed_lines.get(bucket) or []
if len(changed) == 1 and abs(changed[0][0]) > 1e-9:
old_line, new_line = changed[0]
delta_sub = old_sub * (new_line / old_line - 1)
else:
currency_hint = True
continue
new_sub = old_sub + delta_sub
_set_subtotal_row(rows, bucket, new_sub)
if sub_ccy and target_ccy and sub_ccy != target_ccy:
conv = convert_amount(delta_sub, sub_ccy, target_ccy, fx)
if conv is None:
currency_hint = True
else:
subtotal_delta_total += conv
else:
subtotal_delta_total += delta_sub
# 点名改小计、但没点名明细的段:小计差额直接进合计。
for bucket, new_sub in explicit_subtotal.items():
snap = bucket_snapshot.get(bucket) or {}
old_sub = snap.get("subtotal")
if old_sub is None:
continue
sub_ccy = _ccy_code(snap.get("sub_ccy") or header)
delta_sub = new_sub - old_sub
if sub_ccy and target_ccy and sub_ccy != target_ccy:
conv = convert_amount(delta_sub, sub_ccy, target_ccy, fx)
if conv is None:
currency_hint = True
continue
subtotal_delta_total += conv
else:
subtotal_delta_total += delta_sub
if total_touched and total_new_value is not None:
# 销售点名改合计:合计数字以他说的为准,小计仍按明细更新。
new_total = total_new_value
elif single_line and single_line_new is not None:
# 明细只有一项:合计跟着这一项走;跨币种按 TMS 汇率折算。
if target_ccy and single_line_new_ccy and _ccy_code(single_line_new_ccy) != target_ccy:
conv = convert_amount(single_line_new, single_line_new_ccy, target_ccy, fx)
if conv is None:
currency_hint = True
else:
new_total = conv
else:
new_total = single_line_new
elif new_total is not None:
new_total = new_total + subtotal_delta_total + line_delta_total
out = dict(src)
visible = _visible_rows(rows)
out["fee_rows"] = visible
out["fee_lines"] = visible
_write_adjusted_buckets(out, rows)
if applied and new_total is not None and new_total != total_amt:
out["total"] = format_money(new_total, sample=str(src.get("total") or ""), currency=total_ccy)
if not applied:
code = "ambiguous" if ambiguous else "none_matched"
return ApplyResult(
ok=False,
code=code,
quote=src,
unmatched=unmatched,
ambiguous=ambiguous,
)
sale_now, _ = parse_money(out.get("total"))
profit = _attach_profit(
out,
src,
x=sale_now,
tms_cost=tms_cost or str(src.get("tms_baseline_cost") or ""),
tms_sale=tms_sale or str(src.get("tms_baseline_sale") or ""),
business_line=business_line,
)
if tms_cost and "tms_baseline_cost" not in out:
out["tms_baseline_cost"] = tms_cost
if tms_sale and "tms_baseline_sale" not in out:
out["tms_baseline_sale"] = tms_sale
_mark_sales_adjust(out)
out = stamp_prices_for_sheet(out)
logger.info(
"quote_adjust applied=%s unmatched=%s hint=%s profit=%s",
[x.get("name") for x in applied],
unmatched,
currency_hint,
profit,
)
return ApplyResult(
ok=True,
code="applied",
quote=out,
applied=applied,
unmatched=unmatched,
ambiguous=ambiguous,
currency_hint=currency_hint,
profit_point=profit,
)