""" 陆运 TMS 线路报价:按 segmentSequence 收成一条条完整线路。 本文件职责:一段里的多段是中转,不是多条线路;抽出每段成本;选定后只留这一条的段。 禁止:把 costPrice 标成销售价;编没有回的站名;改六态。 """ from __future__ import annotations import json import logging import re from typing import Any logger = logging.getLogger(__name__) def _as_list(raw: Any) -> list[Any]: """list 或 JSON 串。""" if isinstance(raw, str) and raw.strip(): try: raw = json.loads(raw) except json.JSONDecodeError: logger.warning("land.routes landSegments 不是 JSON") return [] return list(raw) if isinstance(raw, list) else [] def parse_land_legs(quote: dict[str, Any] | None) -> list[dict[str, Any]]: """摊平 quote.landSegments。""" src = dict(quote or {}) out: list[dict[str, Any]] = [] for item in _as_list(src.get("landSegments") or src.get("land_segments")): if isinstance(item, dict): out.append(dict(item)) return out def _seq(item: dict[str, Any]) -> int: try: return int(item.get("segmentSequence") or item.get("segment_sequence") or 1) except (TypeError, ValueError): return 1 def _leg_no(item: dict[str, Any]) -> int: try: return int(item.get("routeLegSequence") or item.get("route_leg_sequence") or 0) except (TypeError, ValueError): return 0 def group_land_routes(quote: dict[str, Any] | None) -> list[dict[str, Any]]: """ 同一 segmentSequence 收成一条线路,段按 routeLegSequence 排。 """ buckets: dict[int, list[dict[str, Any]]] = {} order: list[int] = [] for leg in parse_land_legs(quote): key = _seq(leg) if key not in buckets: buckets[key] = [] order.append(key) buckets[key].append(leg) routes: list[dict[str, Any]] = [] for key in order: legs = sorted(buckets[key], key=_leg_no) routes.append({"segmentSequence": key, "legs": legs}) return routes def needs_route_pick(quote: dict[str, Any] | None) -> bool: """多于一条完整线路才进 H5。""" return len(group_land_routes(quote)) > 1 def route_line(route: dict[str, Any] | None) -> str: """上海-谅山-胡志明:第一段起运 + 各段目的。""" legs = list((route or {}).get("legs") or []) if not legs: return "" names = [str(legs[0].get("origin") or "").strip()] for leg in legs: dest = str(leg.get("destination") or "").strip() if dest: names.append(dest) return "-".join(x for x in names if x) def _money(raw: Any, currency: str = "") -> str: text = str(raw if raw is not None else "").strip() if not text or text in {"None", "null"}: return "" ccy = (currency or "").strip() if ccy and ccy not in text: return f"{ccy} {text}" return text def option_fee_lines(route: dict[str, Any] | None) -> list[tuple[str, str]]: """选线路页用:始发 → 目的 + 该段成本,方便区分备选。报价明细不走这里。""" rows: list[tuple[str, str]] = [] for leg in list((route or {}).get("legs") or []): origin = str(leg.get("origin") or "").strip() or "-" dest = str(leg.get("destination") or "").strip() or "-" ccy = str(leg.get("currency") or "").strip() amount = _money(leg.get("costPrice") if leg.get("costPrice") is not None else leg.get("cost_price"), ccy) if not amount: continue rows.append((f"{origin} → {dest}", amount)) return rows def _num(raw: Any) -> float | None: """金额比大小:去掉币种和逗号。""" if raw is None: return None text = str(raw).strip() if not text or text in {"-", "None", "null"}: return None for bit in text.replace(",", " ").split(): try: return float(bit) except ValueError: continue return None def _same_amount(left: Any, right: Any) -> bool: a, b = _num(left), _num(right) if a is None or b is None: return False return abs(a - b) < 0.0001 def _leg_cost(leg: dict[str, Any] | None) -> Any: src = dict(leg or {}) if src.get("costPrice") is not None: return src.get("costPrice") return src.get("cost_price") def _has_seq(item: dict[str, Any] | None) -> bool: src = dict(item or {}) raw = src.get("segmentSequence") if raw is None: raw = src.get("segment_sequence") return raw not in (None, "", "null") def _fee_name(item: dict[str, Any] | None) -> str: """费用名只认 TMS 原文,禁止用路段名冒充。""" src = dict(item or {}) return str( src.get("feeName") or src.get("name") or src.get("chargeName") or src.get("itemName") or src.get("feeType") or "" ).strip() def is_port_handling_fee(item: dict[str, Any] | None) -> bool: """ 是否「口岸海关监管费 + 接驳费」这一项(东南亚整车境外段的固定费目)。 为什么按名字认:TMS 陆运费目没有单独字段区分这类费,模板行名是 「口岸海关监管费+接驳费」,主账 fee_lines 也原样保留 feeName。 只认「接驳」或「口岸 + 监管」,避免把运输费、提货费、报关费算进来。 副作用:无。线程:纯函数。 """ compact = str(_fee_name(item) or "").replace(" ", "") if not compact: return False if "接驳" in compact: return True return "口岸" in compact and "监管" in compact def _all_named_fee_rows(quote: dict[str, Any] | None) -> list[dict[str, Any]]: """ 合并 fee_lines 与 feeItems 两处 TMS 费目,按「费名 + 金额」去重。 为什么两处都看:主账有时只把运输费投影进 fee_lines,口岸监管/接驳费 仍留在原始 feeItems;只看 fee_lines 会漏掉这一项。 金额数字才收(沿用 _named_from_rows 口径),不编造。 副作用:无。线程:纯函数。 """ src = dict(quote or {}) rows: list[dict[str, Any]] = [] seen: set[tuple[str, str]] = set() for key in ("fee_lines", "fee_rows", "feeItems", "fee_items"): for row in _named_from_rows(src.get(key)): name = str(row.get("name") or "").strip() amount = str(row.get("amount") or "").strip() mark = (name, amount) if mark in seen: continue seen.add(mark) rows.append(row) return rows def land_port_handling_fees( quote: dict[str, Any] | None, *, shown_fees: list[dict[str, Any]] | None = None, ) -> list[dict[str, Any]]: """ 文字价格明细要单独展示的口岸监管/接驳费(TMS 有才有,非必填)。 参数: quote TMS 投影后的报价对象(fee_lines / feeItems 任一有即可); shown_fees 已经写在各段下面、无需重复展示的费用行。 返回:TMS 原名的费用行列表;名称、金额、币种都照抄 TMS,本地不改写。 为什么不放进 land_leg_fee_blocks:那里每段只取一条主运费,且销售调价会写回 路段 costPrice;这类附加费不是路段成本,混进去会把整段运价改错。 副作用:无。线程:纯函数。 """ shown: set[tuple[str, str]] = set() for fee in list(shown_fees or []): name = str(fee.get("name") or _fee_name(fee) or "").strip() amount = str(fee.get("amount") or "").strip() if name and amount: shown.add((name, amount)) src = dict(quote or {}) # 已选定线路时,原始 feeItems 仍含其它备选的费目;带段号的只认当前这一条, # 否则会把没选中的线路接驳费也展示出来(费用合计却不含它)。 selected = _selected_route_obj(src) want_seq: int | None = None if selected: raw_seq = selected.get("segmentSequence") if raw_seq is None: raw_seq = selected.get("segment_sequence") try: want_seq = int(raw_seq) if raw_seq not in (None, "", "null") else None except (TypeError, ValueError): want_seq = None out: list[dict[str, Any]] = [] for fee in _all_named_fee_rows(src): if not is_port_handling_fee(fee): continue name = str(fee.get("name") or "").strip() amount = str(fee.get("amount") or "").strip() if not name or _num(amount) is None: continue if (name, amount) in shown: continue if want_seq is not None and _has_seq(fee) and _seq(fee) != want_seq: continue out.append(fee) return out def parse_tms_fee_rows(quote: dict[str, Any] | None) -> list[dict[str, Any]]: """摊平 TMS feeItems / 已投影的 fee_lines。""" src = dict(quote or {}) raw = src.get("feeItems") or src.get("fee_items") or src.get("fee_lines") or src.get("fee_rows") return [dict(x) for x in _as_list(raw) if isinstance(x, dict)] # TMS 陆运把「口岸海关监管+接驳费」塞在费用备注里,不是独立费目。 # 原文形如:4、口岸海关监管+接驳费:1.25T/821元、2.5T/821元,…、8T/1093元、40HQ/1380元… # 识别用这句做锚点;对外展示统一用 PORT_HANDLING_FEE_LABEL(报价单模板行名)。 PORT_HANDLING_FEE_LABEL = "口岸海关监管费+接驳费" _PORT_FEE_HEAD = re.compile(r"口岸[^\r\n::]{0,16}?监管[^\r\n::]{0,16}?接驳[^\r\n::]{0,4}?[::]") # 一项费率:车型/金额元。车型带字母(T/HQ/M),可能再跟「冷柜」「平板」这类中文尾缀。 _PORT_FEE_PAIR = re.compile( r"([0-9]+(?:\.[0-9]+)?\s*[A-Za-z]{1,4}[^\s//、,,;;::]{0,4}?)\s*[//]\s*([0-9]+(?:\.[0-9]+)?)\s*元" ) def _remark_texts(quote: dict[str, Any] | None) -> list[str]: """ 收集报价里所有可能带口岸监管费说明的原文。 来源:各段 landSegments / route_rows 的 remark,以及 fee_lines / feeItems 的 remark。 为什么都收:TMS 只把这段说明挂在其中一段的备注上,主账投影后两处都可能出现, 只读一处会漏;同文去重后返回。 副作用:无。线程:纯函数。 """ src = dict(quote or {}) texts: list[str] = [] seen: set[str] = set() def _add(raw: Any) -> None: for item in _as_list(raw): if not isinstance(item, dict): continue for key in ("remark", "note", "description", "feeRemark"): text = str(item.get(key) or "").strip() if not text or text in seen: continue seen.add(text) texts.append(text) for key in ("landSegments", "land_segments", "route_rows"): _add(src.get(key)) for key in ("fee_lines", "fee_rows", "feeItems", "fee_items"): _add(src.get(key)) # 整单备注:TMS 有时只把说明挂在报价根节点上。 for key in ("remark", "note"): text = str(src.get(key) or "").strip() if text and text not in seen: seen.add(text) texts.append(text) selected = src.get("selected_land_route") if isinstance(selected, dict): _add(selected.get("legs")) return texts def _port_fee_head(text: str) -> tuple[str, str] | None: """ 切出「口岸…监管…接驳…」这句的费名与冒号后的价表。 返回 (TMS 这句的开头, 价表)。费名仅供内部认句,对外展示统一用模板行名 「口岸海关监管费+接驳费」,与报价单模板一致。没有这句返回 None。 副作用:无。线程:纯函数。 """ head = _PORT_FEE_HEAD.search(text or "") if not head: return None title = str(head.group(0) or "").rstrip("::").strip() return title, text[head.end():] def parse_port_handling_rates(quote: dict[str, Any] | None) -> list[tuple[str, str]]: """ 从 TMS 备注里抽「口岸海关监管+接驳费」的车型价表。 返回 [(车型, 金额)],如 [("1.25T", "821"), ("8T", "1093"), ("40HQ", "1380")]。 为什么解析备注:TMS 报价回包里这一项没有 feeName/amount,只有这句说明; 不解析就永远显示不出来(WO202611220035 实测)。 相同车型+金额只留一条;抽不到返回空列表,绝不编数字。 副作用:无。线程:纯函数。 """ pairs: list[tuple[str, str]] = [] seen: set[tuple[str, str]] = set() for text in _remark_texts(quote): split = _port_fee_head(text) if not split: continue clause = split[1] for hit in _PORT_FEE_PAIR.finditer(clause): token = re.sub(r"\s+", "", hit.group(1)) amount = hit.group(2) mark = (token, amount) if not token or mark in seen: continue seen.add(mark) pairs.append(mark) return pairs def _vehicle_token_key(raw: str) -> str: """车型比较键:去空格、转大写。8t/8T 视为同一车型。""" return re.sub(r"\s+", "", raw or "").upper() def land_vehicle_type(quote: dict[str, Any] | None, facts: dict[str, Any] | None = None) -> str: """ 当前这单的车型,用于对上口岸监管费价表。 先取已选线路各段的 vehicleType(TMS 原样,如 8T / 40HQ), 再退回工单「车型/数量」里斜杠前那段(8T/1 → 8T)。 只用于匹配费率,不改写工单字段。 副作用:无。线程:纯函数。 """ for leg in _selected_legs(quote): token = str(leg.get("vehicleType") or leg.get("vehicle_type") or "").strip() if token: return token src = dict(facts or {}) combo = str(src.get("车型/数量") or src.get("车型") or "").strip() if not combo: return "" return re.split(r"[//xX×**\s]", combo, maxsplit=1)[0].strip() def land_port_handling_rate( quote: dict[str, Any] | None, facts: dict[str, Any] | None = None, ) -> tuple[str, str] | None: """ 按当前车型在价表里取「口岸海关监管+接驳费」,取不到返回 None。 匹配规则:车型规范化后完全相同优先;否则允许一方是另一方前缀 (模板写 48RH,TMS 写 48RH冷柜,要能对上)。仍然对不上就返回 None, 由调用方把 TMS 原表整段展示,禁止自己挑一个数。 副作用:无。线程:纯函数。 """ pairs = parse_port_handling_rates(quote) if not pairs: return None vehicle = _vehicle_token_key(land_vehicle_type(quote, facts)) if not vehicle: return None for token, amount in pairs: if _vehicle_token_key(token) == vehicle: return token, amount for token, amount in pairs: key = _vehicle_token_key(token) if key.startswith(vehicle) or vehicle.startswith(key): return token, amount return None def land_port_handling_clause(quote: dict[str, Any] | None) -> str: """ TMS 备注里「口岸海关监管+接驳费:…」这一句的原文(含冒号后的价表)。 车型对不上价表时整句展示,销售能自己按车型看费率;抽不到返回空串。 副作用:无。线程:纯函数。 """ for text in _remark_texts(quote): split = _port_fee_head(text) if not split: continue # 取到行尾为止,避免把整段备注条款都搬进价格明细。 clause = re.split(r"[\r\n]", split[1], maxsplit=1)[0].strip() if clause: return clause return "" def land_port_handling_title(quote: dict[str, Any] | None) -> str: """ 展示用的费目名(报价单模板行名,产品确认口径)。 固定写「口岸海关监管费+接驳费」,与模板固定行一致;TMS 备注里那句 「口岸海关监管+接驳费」只是识别用的锚点,不拿来当展示名。 备注里没有这句时返回空串,调用方据此判断这单有没有这一项。 副作用:无。线程:纯函数。 """ for text in _remark_texts(quote): if _port_fee_head(text): return PORT_HANDLING_FEE_LABEL return "" def _named_from_rows(raw: Any) -> list[dict[str, Any]]: """只要 TMS 费目名。路段名冒充的费用行丢掉。""" rows: list[dict[str, Any]] = [] for item in _as_list(raw): if not isinstance(item, dict): continue name = _fee_name(item) if not name or "→" in name or "->" in name: continue amount = item.get("amount") if amount is None: amount = item.get("costPrice") if item.get("costPrice") is not None else item.get("salePrice") if _num(amount) is None: continue line = dict(item) line["name"] = name line["amount"] = amount rows.append(line) return rows def _named_tms_fees(quote: dict[str, Any] | None) -> list[dict[str, Any]]: """ 先看已投影的 fee_lines,没有真费目再看 feeItems。 主账有时把路段名写进 fee_lines;这时必须回到 TMS feeItems 取运输费。 """ src = dict(quote or {}) named = _named_from_rows(src.get("fee_lines") or src.get("fee_rows")) if named: return named named = _named_from_rows(src.get("feeItems") or src.get("fee_items")) if named: return named return _named_from_rows(parse_tms_fee_rows(src)) def _pick_fee_for_leg( fees: list[dict[str, Any]], used: set[int], leg: dict[str, Any], prefer_seq: int = 0, ) -> dict[str, Any] | None: """按段号 / 腿号 / 金额认回这一段的 TMS 费用。""" want_leg = _leg_no(leg) want_amt = _leg_cost(leg) checks = ( lambda f: prefer_seq and _has_seq(f) and _seq(f) == prefer_seq and _leg_no(f) == want_leg, lambda f: prefer_seq and _has_seq(f) and _seq(f) == prefer_seq and _same_amount(f.get("amount"), want_amt), lambda f: _leg_no(f) == want_leg and _same_amount(f.get("amount"), want_amt), lambda f: _same_amount(f.get("amount"), want_amt), ) # 口岸监管/接驳费也带段号时,不能抢在各段主运费前面被认成「运输费」。 # 先试普通费目,再试这类附加费;顺序稳定,命中即止。 ordered = sorted( enumerate(fees), key=lambda pair: (1 if is_port_handling_fee(pair[1]) else 0, pair[0]), ) for check in checks: for i, fee in ordered: if i in used: continue try: ok = check(fee) except (TypeError, ValueError): ok = False if ok: used.add(i) return fee return None def selected_tms_fee_lines( quote: dict[str, Any] | None, route: dict[str, Any] | None, ) -> list[dict[str, Any]]: """ 选定一条陆运线路后:只留该条 TMS 费用行,名称原样。 主账常把 fee_lines 收成 JSON 串,也不一定带段号;这时按各段成本和腿号认回去。 """ src = dict(route or {}) try: seq = int(src.get("segmentSequence") or src.get("segment_sequence") or 0) except (TypeError, ValueError): seq = 0 fees = _named_tms_fees(quote) matched = [f for f in fees if _has_seq(f) and _seq(f) == seq] if matched: return matched used: set[int] = set() out: list[dict[str, Any]] = [] for leg in list(src.get("legs") or []): if not isinstance(leg, dict): continue picked = _pick_fee_for_leg(fees, used, leg, prefer_seq=seq) if picked: out.append(picked) if out: return out if fees and not needs_route_pick(quote): return fees return [] def _od_title(leg: dict[str, Any] | None) -> str: """上海 → 谅山:站名用 TMS 原文。""" src = dict(leg or {}) origin = str(src.get("origin") or "").strip() dest = str(src.get("destination") or "").strip() if not origin and not dest: return "" return f"{origin or '-'} → {dest or '-'}" def _quote_fee_dicts(quote: dict[str, Any] | None) -> list[dict[str, Any]]: """优先已选定的 fee_lines,避免再摊开整单 feeItems。""" src = dict(quote or {}) rows = [dict(x) for x in _as_list(src.get("fee_lines") or src.get("fee_rows")) if isinstance(x, dict)] if rows: return rows return parse_tms_fee_rows(src) def _selected_route_obj(quote: dict[str, Any] | None) -> dict[str, Any]: """ 已选线路对象。主账回读时常把它落成 JSON 串,这里统一还原成 dict。 为什么必须认串:从 inq_quote.payload_json 读出来的 selected_land_route 是字符串, 只判断 dict 会让「已选哪条线路」失效,进而把别的备选附加费也算进来。 副作用:无。线程:纯函数。 """ raw = dict(quote or {}).get("selected_land_route") if isinstance(raw, str) and raw.strip(): try: raw = json.loads(raw) except json.JSONDecodeError: return {} return dict(raw) if isinstance(raw, dict) else {} def _selected_legs(quote: dict[str, Any] | None) -> list[dict[str, Any]]: """当前这条线路的各段。多条未选时不编。""" src = dict(quote or {}) selected = _selected_route_obj(src) if selected: legs = [dict(x) for x in list(selected.get("legs") or []) if isinstance(x, dict)] if legs: return legs routes = group_land_routes(src) if len(routes) == 1: return [dict(x) for x in list(routes[0].get("legs") or []) if isinstance(x, dict)] legs = parse_land_legs(src) seqs = {_seq(x) for x in legs} if len(seqs) == 1: return sorted(legs, key=_leg_no) return [] def land_leg_fee_blocks( quote: dict[str, Any] | None, ) -> list[tuple[str, list[dict[str, Any]], str]]: """ 价格明细按段:路段标题、该段 TMS 费目、该段时效原文。 例:上海 → 谅山 / 运输费 7500 / N+2。时效没有就不写,禁止编。 """ legs = _selected_legs(quote) if not legs: return [] fees = _named_tms_fees(quote) # 附加费(口岸监管/接驳)不能当各段运费的兜底名字,否则整段成本会被标成接驳费。 fallback_name = next( ( str(f.get("name") or "").strip() for f in fees if f.get("name") and not is_port_handling_fee(f) ), "", ) # 路段名把 TMS 费目冲掉时,各段成本仍按运输费展示,禁止再用始发→目的冒充费名。 if not fallback_name: fallback_name = "运输费" used: set[int] = set() blocks: list[tuple[str, list[dict[str, Any]], str]] = [] for leg in legs: title = _od_title(leg) if not title: continue eta = str(leg.get("transitDays") or leg.get("transit_days") or "").strip() picked: list[dict[str, Any]] = [] one = _pick_fee_for_leg(fees, used, leg, prefer_seq=_seq(leg)) if one: picked.append(one) elif fallback_name and _num(_leg_cost(leg)) is not None: picked.append( { "name": fallback_name, "amount": _leg_cost(leg), "currency": str(leg.get("currency") or "").strip(), } ) blocks.append((title, picked, eta)) return blocks def land_leg_fee_blocks_for_route( quote: dict[str, Any] | None, route: dict[str, Any] | None, ) -> list[tuple[str, list[dict[str, Any]], str]]: """H5 某一条备选:只收该条各段,费用名仍是 TMS 原文。""" src = dict(route or {}) mini = dict(quote or {}) mini["selected_land_route"] = src mini["landSegments"] = [dict(x) for x in list(src.get("legs") or []) if isinstance(x, dict)] picked = selected_tms_fee_lines(quote, src) if picked: mini["fee_lines"] = picked return land_leg_fee_blocks(mini) def option_total(route: dict[str, Any] | None) -> str: """各段成本相加。加不上就空。""" total = 0.0 ccy = "" any_num = False for leg in list((route or {}).get("legs") or []): raw = leg.get("costPrice") if raw is None: raw = leg.get("cost_price") if raw is None or str(raw).strip() in {"", "None", "null"}: continue try: total += float(raw) any_num = True except (TypeError, ValueError): continue if not ccy: ccy = str(leg.get("currency") or "").strip() if not any_num: return "-" text = str(int(total)) if total == int(total) else str(total) return _money(text, ccy) or "-" def option_eta_bits(route: dict[str, Any] | None) -> list[tuple[str, str]]: """每段时效,有 transitDays 才写。""" bits: list[tuple[str, str]] = [] for i, leg in enumerate(list((route or {}).get("legs") or []), 1): days = str(leg.get("transitDays") or leg.get("transit_days") or "").strip() if days: bits.append((f"第{i}段时效", days)) return bits def project_selected_route(quote: dict[str, Any] | None, route: dict[str, Any] | None) -> dict[str, Any]: """ 选定一条后:只留该条 landSegments,费用名按 TMS 原文,合计用成本加总。 """ base = dict(quote or {}) src = dict(route or {}) legs = [dict(x) for x in list(src.get("legs") or [])] base["landSegments"] = legs lines = selected_tms_fee_lines(base, src) if not lines: mini = dict(base) mini["selected_land_route"] = src for _, fees, _eta in land_leg_fee_blocks(mini): lines.extend(fees) base["fee_lines"] = lines base["total"] = option_total(src) base["freight"] = "-" base["other_fee"] = "-" base["route_line"] = route_line(src) base["selected_land_route"] = src etas = option_eta_bits(src) if etas: # 时效按段原文拼接(N+2 / N+3),禁止当成小时数相加。 base["eta"] = " / ".join(d for _, d in etas) if src: base["cost"] = option_total(src) return base