- 新增员工岗位(InquiryStaffRole)实体、服务与后台页面,数据范围默认按岗位,看板由「仅本人」切换为岗位范围,补充业务负责人与角色说明迁移 - 新增企微群 webhook 通道、access_gate/staff_roles 鉴权与智价通/双 BOT 回复配置 - 报价回执增加去重防抖(quote_receipt_debounce),询价原文落库并补单测 - 同义词补陆运类型修正与地名通配 v2,更新种子生成脚本 - 空运/陆运/海运询价流程、报价单按需生成、转人工与多段处理调整 - 后台工单需求字段、BOT 显示名、站点标题与看板配套更新
356 lines
13 KiB
Python
356 lines
13 KiB
Python
"""
|
||
空运计费重:只做单位换算与算术投影,不做语义识别。
|
||
|
||
产品口径(2026-11-22 拍板):
|
||
|
||
体积重 = 体积(CBM)× 166.7(KG/CBM)
|
||
计费重 = max(毛重, 体积重)
|
||
|
||
触发场景:TMS 没有匹配报价,航线人员在协同群用文字手工报价(如「USD11/kg」)。
|
||
此时整票金额 = 单价 × 计费重,必须由本机按工单里的体积/毛重算出来,
|
||
既要在群摘要里让销售看见,也要跟着报价版本进报价单。
|
||
|
||
为什么单独一个模块:
|
||
- 三处都要用(群摘要、报价落库、TMS 缺失时的展示),写在某个 policy 里会被反向依赖;
|
||
- 合同要求「尺寸原文不得在本地代码里解析成体积」,本模块只读已经结构化的
|
||
「体积」/「毛重」字段,只做去单位与乘加,不认长宽高、不从品名猜货型。
|
||
|
||
副作用:无。纯函数,可在任意线程调用。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
from typing import Any, Optional
|
||
|
||
# 空运体积重系数(KG / CBM)。产品口径固定值,不从 TMS「比例」字段反推:
|
||
# 比例(如 1:300)是货型/泡重说明,不等于本单计价系数。
|
||
VOLUME_WEIGHT_DIVISOR = 166.7
|
||
|
||
# 允许出现在数字后面的单位后缀。去掉后只留数字,不做其它规范化。
|
||
_UNIT_SUFFIX = re.compile(
|
||
r"(?i)\s*(?:CBM|M3|立方米|立方|方|KGS?|KGM|公斤|千克|KG|吨)\s*$"
|
||
)
|
||
|
||
# 「KM」之类不在上面,避免把别的东西吃掉。
|
||
_TON_SUFFIX = re.compile(r"(?i)\s*(?:吨|TON|TONS)\s*$")
|
||
|
||
# 金额行常把币种写在数字前面(USD11.00);币种不是数量,读数字前先剥掉。
|
||
_CCY_PREFIX = re.compile(r"(?i)^\s*(?:CNY|RMB|USD|EUR|HKD|JPY|GBP|人民币|美元|港币|欧元|日元)\s*")
|
||
|
||
# 计费重行的计价单位(大小写、斜杠、口语「每公斤」都认)。
|
||
_KG_UNITS = frozenset({"KG", "KGS", "KGM", "公斤", "千克"})
|
||
|
||
|
||
def parse_quantity(raw: Any) -> Optional[float]:
|
||
"""
|
||
把「1,200」「500KG」「3CBM」「1.5吨」读成数字。
|
||
|
||
只去单位、去千分位;读不出正数返回 None(0 也当没填,避免算出 0 计费重)。
|
||
「吨」按 1000KG 换算,这是确定性的单位投影,不是猜测。
|
||
"""
|
||
if raw in (None, ""):
|
||
return None
|
||
text = str(raw).strip().replace(",", "").replace(",", "")
|
||
if not text or text in {"-", "—", "-", "null", "None"}:
|
||
return None
|
||
# 「大概4吨」「4吨左右」:先去掉口语模糊词,否则吨数会漏换算或读成 4。
|
||
try:
|
||
from agent.schema.field_validate import strip_quantity_filler
|
||
|
||
text = strip_quantity_filler(text)
|
||
except Exception:
|
||
pass
|
||
text = _CCY_PREFIX.sub("", text)
|
||
ton = False
|
||
if _TON_SUFFIX.search(text):
|
||
ton = True
|
||
text = _UNIT_SUFFIX.sub("", text)
|
||
text = _TON_SUFFIX.sub("", text).strip()
|
||
# 允许数字后面还留着零星说明(如「500 左右」),只取开头的数字段。
|
||
hit = re.match(r"(\d+(?:\.\d+)?)", text)
|
||
if not hit:
|
||
return None
|
||
try:
|
||
value = float(hit.group(1))
|
||
except ValueError:
|
||
return None
|
||
if ton:
|
||
value *= 1000.0
|
||
return value if value > 0 else None
|
||
|
||
|
||
def volume_weight_kg(volume_cbm: Optional[float]) -> Optional[float]:
|
||
"""体积重(KG)= 体积(CBM)× 166.7;没有体积返回 None。"""
|
||
if volume_cbm is None or volume_cbm <= 0:
|
||
return None
|
||
return volume_cbm * VOLUME_WEIGHT_DIVISOR
|
||
|
||
|
||
def format_kg(value: Optional[float]) -> str:
|
||
"""
|
||
计费重的写法:最多两位小数,去掉无意义的尾零。
|
||
|
||
例:848.87 → "848.87";500.10 → "500.1";500.00 → "500"。
|
||
报价单与群摘要共用这一种写法,避免同一个数在两个地方长得不一样。
|
||
"""
|
||
if value is None:
|
||
return ""
|
||
text = f"{float(value):.2f}".rstrip("0").rstrip(".")
|
||
return text or "0"
|
||
|
||
|
||
def with_kg_unit(raw: Any) -> str:
|
||
"""计费重展示补 KG;原文已经带单位就原样,不重复写。"""
|
||
text = str(raw or "").strip()
|
||
if not text or text in {"-", "—", "-"}:
|
||
return ""
|
||
upper = text.upper()
|
||
if any(upper.endswith(unit) for unit in ("KG", "KGS", "KGM", "公斤", "千克")):
|
||
return text
|
||
return f"{text}KG"
|
||
|
||
|
||
# 航线在群里明说「计费重800KG/计费重量 800」:以他说的为准,本机不重算。
|
||
_DECLARED_CHARGEABLE = re.compile(
|
||
r"计费重(?:量)?\s*[::]?\s*(\d[\d,]*(?:\.\d+)?)\s*(?:KG|KGS|KGM|公斤|千克)?",
|
||
re.I,
|
||
)
|
||
|
||
|
||
def harvest_declared_chargeable(text: str | None) -> Optional[float]:
|
||
"""
|
||
从人工报价原话里读航线点明的计费重。
|
||
|
||
只认紧跟「计费重/计费重量」的数字;「计费重按实重」这种没数字的返回 None,
|
||
交给体积/毛重公式。副作用:无。
|
||
"""
|
||
hit = _DECLARED_CHARGEABLE.search(text or "")
|
||
if not hit:
|
||
return None
|
||
try:
|
||
value = float(hit.group(1).replace(",", ""))
|
||
except ValueError:
|
||
return None
|
||
return value if value > 0 else None
|
||
|
||
|
||
def compute_chargeable(facts: dict[str, Any] | None) -> Optional[dict[str, Any]]:
|
||
"""
|
||
按工单事实算一票的计费重。
|
||
|
||
取值顺序:
|
||
1. 事实里已经写明「计费重/计费重量」→ 直接用(航线/模型给了就不覆盖);
|
||
2. 否则按体积重与毛重取大;只有一边有值就用那一边。
|
||
|
||
返回 None 表示体积和毛重都没读到数字——这时不能编一个数出来。
|
||
返回字段:
|
||
gross_kg 毛重(KG),可能 None
|
||
volume_cbm 体积(CBM),可能 None
|
||
volume_weight_kg 体积重(KG),可能 None
|
||
chargeable_kg 计费重(KG,正数)
|
||
basis 内部依据:explicit=事实已写明;volume=体积重大;gross=毛重大。
|
||
只用于排查与落库(chargeable_weight_basis),
|
||
产品 2026-11-22 晚确定:对外文字不再展示依据括注。
|
||
"""
|
||
src = dict(facts or {})
|
||
explicit = parse_quantity(src.get("计费重") or src.get("计费重量"))
|
||
gross = parse_quantity(
|
||
src.get("毛重")
|
||
or src.get("重量")
|
||
or src.get("重量(KG)")
|
||
or src.get("weight_kg")
|
||
or src.get("weightKg")
|
||
)
|
||
volume = parse_quantity(
|
||
src.get("体积")
|
||
or src.get("体积(CBM)")
|
||
or src.get("volume_cbm")
|
||
or src.get("volume")
|
||
)
|
||
vol_weight = volume_weight_kg(volume)
|
||
if explicit is not None:
|
||
return {
|
||
"gross_kg": gross,
|
||
"volume_cbm": volume,
|
||
"volume_weight_kg": vol_weight,
|
||
"chargeable_kg": explicit,
|
||
"basis": "explicit",
|
||
}
|
||
candidates = [x for x in (gross, vol_weight) if x is not None]
|
||
if not candidates:
|
||
return None
|
||
chargeable = max(candidates)
|
||
# 两边相等时记「体积重」,只是内部依据(排查/落库用),不写进对外文字。
|
||
basis = "volume" if vol_weight is not None and vol_weight >= (gross or 0) else "gross"
|
||
return {
|
||
"gross_kg": gross,
|
||
"volume_cbm": volume,
|
||
"volume_weight_kg": vol_weight,
|
||
"chargeable_kg": chargeable,
|
||
"basis": basis,
|
||
}
|
||
|
||
|
||
def _has_chargeable(quote: dict[str, Any]) -> bool:
|
||
"""报价对象上是否已经有计费重(TMS 或航线明说的),有就不覆盖。"""
|
||
for key in ("chargeableWeightKg", "chargeable_weight_kg", "chargeableWeight"):
|
||
text = str(quote.get(key) or "").strip()
|
||
if text and text not in {"-", "—", "-"}:
|
||
return True
|
||
return False
|
||
|
||
|
||
def _parse_rows(raw: Any) -> tuple[list[dict[str, Any]], bool]:
|
||
"""
|
||
费用行统一成 list[dict]。
|
||
|
||
返回 (行, 原来是不是 JSON 字符串)。主账回读时 fee_rows 可能是文本,
|
||
写回时要保持同一种形态,否则模板和卡片读法不一致。
|
||
"""
|
||
was_str = False
|
||
if isinstance(raw, str) and raw.strip():
|
||
try:
|
||
raw = json.loads(raw)
|
||
was_str = True
|
||
except json.JSONDecodeError:
|
||
return [], False
|
||
if not isinstance(raw, list):
|
||
return [], False
|
||
return [dict(x) for x in raw if isinstance(x, dict)], was_str
|
||
|
||
|
||
def _unit_token(raw: Any) -> str:
|
||
"""计价单位归一:/KG、每公斤、KGS 都认,其它原样返回。"""
|
||
text = str(raw or "").strip().upper()
|
||
for sep in ("/", "每", " "):
|
||
text = text.replace(sep, "")
|
||
return text
|
||
|
||
|
||
def _fill_kg_rows(
|
||
rows: list[dict[str, Any]], chargeable_kg: float
|
||
) -> int:
|
||
"""
|
||
把按 KG 报价、但没写数量的费用行补成「单价 × 计费重」。
|
||
|
||
为什么只补没写数量的:航线自己写了「800KG」就说明这票按 800 计,
|
||
本机不能再按体积重改掉他的意思。
|
||
副作用:原地改 rows;返回补了几行。
|
||
"""
|
||
filled = 0
|
||
cw_text = format_kg(chargeable_kg)
|
||
for row in rows:
|
||
if _unit_token(row.get("unit") or row.get("unitName")) not in _KG_UNITS:
|
||
continue
|
||
qty = str(row.get("quantity") or row.get("chargeQuantity") or "").strip()
|
||
if qty and qty not in {"-", "—", "-"}:
|
||
continue
|
||
unit_raw = row.get("unit_price") or row.get("unitPrice") or row.get("price")
|
||
unit_price = parse_quantity(unit_raw)
|
||
if unit_price is None:
|
||
continue
|
||
# 行金额已经是另一笔整票金额(航线自己算过),不能拿体积重改掉;
|
||
# 只有「金额=单价」或没有金额时,才说明这只是单价。
|
||
current_amount = parse_quantity(
|
||
row.get("amount") or row.get("value") or row.get("salePrice")
|
||
)
|
||
if current_amount is not None and abs(current_amount - unit_price) > 1e-6:
|
||
continue
|
||
row["quantity"] = cw_text
|
||
row["amount"] = format_kg(unit_price * chargeable_kg)
|
||
filled += 1
|
||
return filled
|
||
|
||
|
||
def _sum_primary_currency(rows: list[dict[str, Any]], fallback_ccy: str = "") -> str:
|
||
"""
|
||
按合同重算合计:只加第一行币种,异币种留明细、不折算。
|
||
|
||
读不出金额的行(百分比费率等)跳过,不让「1%」把合计算成 0。
|
||
"""
|
||
primary = ""
|
||
for row in rows:
|
||
ccy = str(row.get("currency") or row.get("currencyCode") or "").strip().upper()
|
||
if ccy:
|
||
primary = "CNY" if ccy == "RMB" else ccy
|
||
break
|
||
if not primary:
|
||
primary = str(fallback_ccy or "").strip().upper()
|
||
total = 0.0
|
||
has = False
|
||
for row in rows:
|
||
raw_amount = str(row.get("amount") or row.get("value") or row.get("salePrice") or "").strip()
|
||
# 费率/税率是百分比,不是整票金额,不计入合计(合同:合计只加绝对金额)。
|
||
if "%" in raw_amount or "%" in raw_amount:
|
||
continue
|
||
amount = parse_quantity(raw_amount)
|
||
if amount is None:
|
||
continue
|
||
ccy = str(row.get("currency") or row.get("currencyCode") or primary).strip().upper()
|
||
if ccy == "RMB":
|
||
ccy = "CNY"
|
||
if primary and ccy and ccy != primary:
|
||
continue
|
||
total += amount
|
||
has = True
|
||
if not has:
|
||
return ""
|
||
return format_kg(total)
|
||
|
||
|
||
def apply_to_quote(
|
||
quote: dict[str, Any] | None,
|
||
facts: dict[str, Any] | None,
|
||
*,
|
||
business_line: str = "AIR",
|
||
) -> dict[str, Any]:
|
||
"""
|
||
人工报价落库前补计费重:报价对象 + KG 费用行 + 合计一起补齐。
|
||
|
||
只对空运生效:
|
||
- 海运拼柜按 CBM/重量计费、整柜按箱型,不套 166.7;
|
||
- 陆运按车型/票,也不套空运体积重。
|
||
|
||
不覆盖已有计费重(TMS 带回的、航线明说的都优先);
|
||
事实里体积和毛重都读不到时原样返回,绝不编数字。
|
||
返回新 dict,入参不被修改。
|
||
"""
|
||
src = dict(quote or {})
|
||
if business_line and business_line.strip().upper() != "AIR":
|
||
return src
|
||
if _has_chargeable(src):
|
||
return src
|
||
computed = compute_chargeable(facts)
|
||
if computed is None:
|
||
return src
|
||
chargeable = float(computed["chargeable_kg"])
|
||
out = dict(src)
|
||
out["chargeableWeightKg"] = format_kg(chargeable)
|
||
out["chargeable_weight_kg"] = format_kg(chargeable)
|
||
if computed.get("volume_weight_kg") is not None:
|
||
out["volumeWeightKg"] = format_kg(computed["volume_weight_kg"])
|
||
if computed.get("gross_kg") is not None:
|
||
out["grossWeightKg"] = format_kg(computed["gross_kg"])
|
||
out["chargeable_weight_basis"] = str(computed.get("basis") or "")
|
||
|
||
raw = out.get("fee_rows") if out.get("fee_rows") not in (None, "") else out.get("fee_lines")
|
||
rows, was_str = _parse_rows(raw)
|
||
if rows:
|
||
filled = _fill_kg_rows(rows, chargeable)
|
||
if filled:
|
||
if was_str:
|
||
text = json.dumps(rows, ensure_ascii=False)
|
||
out["fee_rows"] = text
|
||
out["fee_lines"] = text
|
||
else:
|
||
out["fee_rows"] = rows
|
||
out["fee_lines"] = list(rows)
|
||
# 行金额刚被改成「单价×计费重」,合计必须跟着;否则群里看单价、
|
||
# 后台却把单价当整票总价(旧缺陷:USD11 当成整票金额)。
|
||
total = _sum_primary_currency(rows, str(out.get("currency") or ""))
|
||
if total:
|
||
out["total"] = total
|
||
return out
|