为什么改:应用建的协同群只能代答,销售在群里发文件、@人、问报价都对不上人; 本次把群对话交给智价通BOT,应用只负责拉群和解散群,并把几处销售已反馈的口径补齐。 群与身份: - 新增 group_bot 短协调(Redis 带环境前缀):记录 BOT 已接管群、当前关联工单、 @BOT 指令窗口与窗口外先到的附件,只做协调不当六态,六态仍在主账。 - 群里没有 @BOT 的文字不回;非 @ 文字断开当前单关联,之后必须重新 @BOT 带工单号。 - 先发文件再 @BOT 也认:窗口外附件先缓冲,等 @BOT 认领后补办。 - 会话存档只补附件、不重复办理 BOT 已办的同一句文字,避免同一条消息回两遍。 - 入站 from.userid 是加密 open_userid 时按官方接口换明文(带 Redis 缓存), 否则与主账 sales_wecom_id 永远比不上,航线本人会被判成「不是本人」。 - 桥侧只认本群 req_id,不再借用别的群 req_id,避免测服把话发进别的群。 报价单: - 建群后只发字段摘要和成交卡,Excel/PDF 等群里 @BOT 说「生成报价单」再出; 多段逐段出,没价出空白表;出表后补推成交跟进不涨 deal_version、不重置等待计时。 - 陆运转人工先选业务类型和报价场景再建群,按选定模板名直取,不再靠关键词猜。 - 空运舱位只回一条时直接出该条报价,不再发选择卡。 字段与金额: - 客户名称改为海/空/陆询价非必填,有值写回工单列,后台列表、报价单与 factsJson 一致。 - 空运新增计费重投影:体积重=CBM×166.7,计费重=max(毛重,体积重); TMS 无价、航线手工按 KG 报价时按计费重×单价算整票金额,群摘要与报价单同公式。 - 陆运报价附加条件统一到 land_quote_condition:未含税/含0税/未含燃油/含燃油费, 燃油只乘主运费,不乘提货送货报关等杂费;跨境整车无备注列时追加到底部备注事项。 - 海运拼柜不适用箱型箱量:不进必填、不进补问、不出站,改回整柜可再用。 - 海运提货地址/派送地址改为非必填,写了才出站(placeOfReceipt/deliveryAddress), 禁止从港口或贸易条款反推地址;TMS 查不到价时把 TMS 原话透给销售。 - 中港集拼与跨境集拼同口径:按体积+毛重,不采车型数量;修正被国内拼车别名抢单。 - 报关费区只收报关类费目;口岸海关监管费+接驳费按车型列回填固定行。 主账与后台: - 看板处理量按协同群处理人统计;下线「平均报价销售额」;处理人搜索先把姓名换回企微 id。 - 「转人工」筛选同时兼容旧六态与新 collab_mode=handoff,新版单不再漏。 - 报价单客户名称、提货/派送地址、空运计费重、拼柜空箱型按新口径填表。 - 新增协同成员查询支持与 AIR_NEED_WO v2 迁移脚本。 文档:04 补海运/空运/陆运必填与地址口径,10 补地址出站规则,12 补测服独立应用 1000015 的部署与切换记录。 Co-authored-by: Cursor <cursoragent@cursor.com>
447 lines
17 KiB
Python
447 lines
17 KiB
Python
"""
|
||
陆运报价附加条件:未含税 / 含0税 / 未含燃油 / 含燃油费。
|
||
|
||
本文件职责(产品 2026-11-22 口径):
|
||
1. 未含税N% —— 税率写 N%,运输费不动,备注「未含税N%」;
|
||
2. 未含税 —— 税率留空,运输费不动,不加备注;
|
||
3. 含0税 —— 税率写 0,运输费不动,备注「含0税」;
|
||
4. 未含燃油N% —— 燃油费率写 N%,主运费 ×(1+N%),备注「未含燃油N%」;
|
||
5. 含燃油费N% —— 燃油费率写 N%,主运费不乘,备注「含燃油费N%」。
|
||
|
||
为什么单独成模块:
|
||
- 这五句是陆运产品报价的口语条件,解析、金额换算、备注口径必须一处定义;
|
||
智能体抽字段(extract_text)和挂段(sea_group_ops)都只调这里,禁止各写一份。
|
||
- 「未含燃油」的乘法只作用于**主运费**(车型价 / 分档单价 / 运输费、陆运费、运费),
|
||
提货、送货、报关、过境等杂费不乘;否则客户会被多收一段杂费的燃油。
|
||
- 模板本轮不改,条件备注走现有 remark 字段;跨境整车没有备注列,
|
||
由主账出单时追加到模板底部「备注事项」。
|
||
|
||
线程:纯函数,无共享可变状态,可在 Worker 槽并发调用。
|
||
副作用:`apply_to_quote` 会原地修改传入的报价 dict(只改本次入参,不落库)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
import unicodedata
|
||
from dataclasses import dataclass
|
||
from decimal import Decimal, InvalidOperation
|
||
from typing import Any
|
||
|
||
# 条件代码:解析结果和日志都用这几个常量,禁止在调用方再写字符串字面量。
|
||
UNTAXED_RATE = "UNTAXED_RATE" # 未含税N%
|
||
UNTAXED_BLANK = "UNTAXED_BLANK" # 未含税(无点数)
|
||
ZERO_TAX = "ZERO_TAX" # 含0税
|
||
FUEL_EXCLUDED = "FUEL_EXCLUDED" # 未含燃油N%(运费要乘)
|
||
FUEL_INCLUDED = "FUEL_INCLUDED" # 含燃油费N%(运费不乘)
|
||
|
||
# 全角数字/百分号先在入口归一,正则只写半角;否则「未含税13%」会漏。
|
||
_RE_FUEL_EXCLUDED = re.compile(
|
||
r"未\s*含\s*燃油(?:附加)?费?\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?"
|
||
)
|
||
# 「含燃油费13%」与「未含燃油13%」只差一个字:先匹配未含,命中即返回,
|
||
# 这里再要求前面不是「未」,避免同句被两种条件同时吃掉。
|
||
_RE_FUEL_INCLUDED = re.compile(
|
||
r"(?<!未)含\s*燃油(?:附加)?费?\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?"
|
||
)
|
||
_RE_UNTAXED_RATE = re.compile(
|
||
r"未\s*含\s*税\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?"
|
||
)
|
||
# 只写「未含税」不带点数:税率必须留空,禁止退化成 0。
|
||
_RE_UNTAXED = re.compile(r"未\s*含\s*税(?!\s*[::=]?\s*\d)")
|
||
_RE_ZERO_TAX = re.compile(r"含\s*0\s*(?:点)?\s*税")
|
||
|
||
# 剥条件句用:比识别正则更宽松,连同后面的点数一起拿掉,
|
||
# 防止「含燃油费13%」被费用行正则当成费目「含燃油费:13」。
|
||
_RE_STRIP_FUEL = re.compile(
|
||
r"(?:未\s*含\s*燃油|(?<!未)含\s*燃油)(?:附加)?费?\s*[::=]?\s*\d+(?:\.\d+)?\s*%?"
|
||
)
|
||
_RE_STRIP_TAX = re.compile(
|
||
r"未\s*含\s*税(?:\s*[::=]?\s*\d+(?:\.\d+)?\s*%?)?"
|
||
)
|
||
_RE_STRIP_ZERO_TAX = re.compile(r"含\s*0\s*(?:点)?\s*税")
|
||
|
||
# 主运费费目:只有这些才乘燃油;含提货/送货/报关等杂费词的一律排除。
|
||
_MAIN_FREIGHT_WORDS = ("运输费", "陆运费", "运费", "干线费", "拖车费", "车费")
|
||
_EXTRA_FEE_WORDS = (
|
||
"提货",
|
||
"送货",
|
||
"派送",
|
||
"报关",
|
||
"过境",
|
||
"保险",
|
||
"仓储",
|
||
"装卸",
|
||
"搬运",
|
||
"燃油",
|
||
"附加",
|
||
"税",
|
||
)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class LandQuoteCondition:
|
||
"""
|
||
一条陆运报价条件(税与燃油可同时存在)。
|
||
|
||
code:主条件代码(有燃油取燃油,否则取税),供日志/测试识别;
|
||
tax_rate/fuel_rate 是展示串(如 "13%"、"0");
|
||
remark:写进报价单备注的内容(未含税无点数时为空串;两项都有时用「;」拼接);
|
||
multiply_fuel:只有「未含燃油N%」为 True;
|
||
clear_tax:写了「未含税」但没点数,必须把税率留空。
|
||
"""
|
||
|
||
code: str
|
||
tax_rate: str = ""
|
||
fuel_rate: str = ""
|
||
remark: str = ""
|
||
multiply_fuel: bool = False
|
||
clear_tax: bool = False
|
||
|
||
|
||
def _normalize(text: str) -> str:
|
||
"""全角转半角、去多余空白;不做金额/城市归一。"""
|
||
return unicodedata.normalize("NFKC", text or "")
|
||
|
||
|
||
def _rate_text(raw: str) -> str:
|
||
"""
|
||
点数展示:去掉无意义的小数零,统一带 %。
|
||
|
||
例:13 → 13%;13.0 → 13%;13.50 → 13.5%。
|
||
"""
|
||
try:
|
||
val = Decimal(str(raw).strip())
|
||
except (InvalidOperation, AttributeError):
|
||
return ""
|
||
text = format(val.normalize(), "f")
|
||
return f"{text}%"
|
||
|
||
|
||
def _parse_fuel_condition(src: str) -> LandQuoteCondition | None:
|
||
"""只解析燃油条件:未含燃油N%(要乘)/ 含燃油费N%(不乘)。"""
|
||
fuel_excluded = _RE_FUEL_EXCLUDED.search(src)
|
||
if fuel_excluded:
|
||
rate = _rate_text(fuel_excluded.group("rate"))
|
||
if rate:
|
||
return LandQuoteCondition(
|
||
code=FUEL_EXCLUDED,
|
||
fuel_rate=rate,
|
||
remark=f"未含燃油{rate}",
|
||
multiply_fuel=True,
|
||
)
|
||
fuel_included = _RE_FUEL_INCLUDED.search(src)
|
||
if fuel_included:
|
||
rate = _rate_text(fuel_included.group("rate"))
|
||
if rate:
|
||
return LandQuoteCondition(
|
||
code=FUEL_INCLUDED,
|
||
fuel_rate=rate,
|
||
remark=f"含燃油费{rate}",
|
||
)
|
||
return None
|
||
|
||
|
||
def _parse_tax_condition(src: str) -> LandQuoteCondition | None:
|
||
"""只解析税条件:未含税N% / 含0税 / 未含税(无点数)。"""
|
||
untaxed_rate = _RE_UNTAXED_RATE.search(src)
|
||
if untaxed_rate:
|
||
rate = _rate_text(untaxed_rate.group("rate"))
|
||
if rate:
|
||
return LandQuoteCondition(
|
||
code=UNTAXED_RATE,
|
||
tax_rate=rate,
|
||
remark=f"未含税{rate}",
|
||
)
|
||
zero_tax = _RE_ZERO_TAX.search(src)
|
||
if zero_tax:
|
||
# 产品写「含0点税」就保留原话(历史摘要/模板备注一直这么显示);
|
||
# 写「含0税」时按本轮口径统一成「含0税」。两种都表示税率 0。
|
||
raw = re.sub(r"\s+", "", zero_tax.group(0))
|
||
remark = "含0点税" if "点" in raw else "含0税"
|
||
return LandQuoteCondition(code=ZERO_TAX, tax_rate="0", remark=remark)
|
||
if _RE_UNTAXED.search(src):
|
||
# 产品口径:未含税但不给点数 → 税率留空、备注也留空。
|
||
return LandQuoteCondition(code=UNTAXED_BLANK, clear_tax=True)
|
||
return None
|
||
|
||
|
||
def parse_land_quote_condition(text: str) -> LandQuoteCondition | None:
|
||
"""
|
||
从产品报价原话里识别陆运附加条件(税与燃油可同时出现)。
|
||
|
||
为什么两项分开解析再合并:
|
||
- 产品可能写「运输费3200,未含税13%,未含燃油5%」,税率和燃油都要出单;
|
||
只取一句会丢掉另一项,模板侧栏就会空一格。
|
||
- 备注按「税在前、燃油在后」用「;」拼接,销售在群里一眼能读完。
|
||
|
||
参数 text:产品报价原话(可含 @机器人、工单号)。
|
||
返回:条件对象;五项都没出现时返回 None。
|
||
副作用:无。线程:纯函数。
|
||
"""
|
||
src = _normalize(text)
|
||
if not src:
|
||
return None
|
||
fuel = _parse_fuel_condition(src)
|
||
tax = _parse_tax_condition(src)
|
||
if fuel is None and tax is None:
|
||
return None
|
||
primary = fuel or tax
|
||
remarks = [item.remark for item in (tax, fuel) if item and item.remark]
|
||
return LandQuoteCondition(
|
||
code=primary.code if primary else "",
|
||
tax_rate=tax.tax_rate if tax else "",
|
||
fuel_rate=fuel.fuel_rate if fuel else "",
|
||
remark=";".join(remarks),
|
||
multiply_fuel=bool(fuel and fuel.multiply_fuel),
|
||
clear_tax=bool(tax and tax.code == UNTAXED_BLANK),
|
||
)
|
||
|
||
|
||
def strip_land_quote_condition(text: str) -> str:
|
||
"""
|
||
去掉条件短语后再抽金额/费用行。
|
||
|
||
为什么必须剥:
|
||
- 「含燃油费13%」会被费用行正则认成费目「含燃油费」+ 金额 13;
|
||
- 「未含税」里的「含税」会被旧备注正则当成含税备注;
|
||
- 「13%」若留在正文,可能被金额回退抓成运费。
|
||
副作用:无。线程:纯函数。
|
||
"""
|
||
cleaned = _normalize(text)
|
||
cleaned = _RE_STRIP_FUEL.sub(" ", cleaned)
|
||
cleaned = _RE_STRIP_TAX.sub(" ", cleaned)
|
||
cleaned = _RE_STRIP_ZERO_TAX.sub(" ", cleaned)
|
||
return cleaned
|
||
|
||
|
||
def is_main_transport_fee(name: str) -> bool:
|
||
"""
|
||
这条费目是不是「主运费」(燃油乘法的对象)。
|
||
|
||
主运费:运输费/陆运费/运费/干线费/拖车费/车费;
|
||
杂费:提货、送货、报关、过境、保险、仓储、装卸、搬运、燃油附加、税费 —— 不乘。
|
||
副作用:无。线程:纯函数。
|
||
"""
|
||
label = _normalize(name).strip()
|
||
if not label:
|
||
return False
|
||
if any(word in label for word in _EXTRA_FEE_WORDS):
|
||
return False
|
||
return any(word in label for word in _MAIN_FREIGHT_WORDS)
|
||
|
||
|
||
def _scale_amount(raw: Any, factor: Decimal) -> str:
|
||
"""
|
||
金额乘系数,保留两位小数并去掉无意义的零。
|
||
|
||
认不出数字(「面议」「-」「含税」)就原样返回,禁止把非金额写成 0。
|
||
副作用:无。线程:纯函数。
|
||
"""
|
||
text = str(raw or "").strip().replace(",", "")
|
||
if not text:
|
||
return str(raw or "")
|
||
try:
|
||
val = Decimal(text) * factor
|
||
except (InvalidOperation, ValueError):
|
||
return text
|
||
val = val.quantize(Decimal("0.01"))
|
||
out = format(val, "f")
|
||
if "." in out:
|
||
out = out.rstrip("0").rstrip(".")
|
||
return out or "0"
|
||
|
||
|
||
def _as_decimal(raw: Any) -> Decimal | None:
|
||
"""把金额串转 Decimal;失败返回 None(不猜)。"""
|
||
text = str(raw or "").strip().replace(",", "")
|
||
if not text:
|
||
return None
|
||
try:
|
||
return Decimal(text)
|
||
except (InvalidOperation, ValueError):
|
||
return None
|
||
|
||
|
||
def _scale_rows(
|
||
rows: Any,
|
||
factor: Decimal,
|
||
*,
|
||
only_main: bool,
|
||
delta_currency: str = "",
|
||
) -> Decimal:
|
||
"""
|
||
就地缩放费用行,返回主运费相对原值的增量(用于修正合计)。
|
||
|
||
only_main=True:只乘运输费;False:所有非费率行都乘(车型价明细用)。
|
||
带 % 的费率行永远不乘。
|
||
delta_currency:合计只统计该币种的行(空行币种视为同币);多币种报价
|
||
的合计本来就是主币种小计,不能把异币种增量加进去。
|
||
"""
|
||
delta = Decimal("0")
|
||
target_ccy = str(delta_currency or "").strip().upper()
|
||
if not isinstance(rows, list):
|
||
return delta
|
||
for row in rows:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
amount = str(row.get("amount") or "")
|
||
if "%" in amount or "%" in str(row.get("unit") or ""):
|
||
continue
|
||
if only_main and not is_main_transport_fee(str(row.get("name") or "")):
|
||
continue
|
||
row_ccy = str(row.get("currency") or "").strip().upper()
|
||
count_delta = not target_ccy or not row_ccy or row_ccy == target_ccy
|
||
before = _as_decimal(amount)
|
||
if before is None:
|
||
continue
|
||
after_text = _scale_amount(amount, factor)
|
||
after = _as_decimal(after_text)
|
||
if after is None:
|
||
continue
|
||
row["amount"] = after_text
|
||
if str(row.get("unit_price") or "").strip():
|
||
row["unit_price"] = _scale_amount(row.get("unit_price"), factor)
|
||
if count_delta:
|
||
delta += after - before
|
||
return delta
|
||
|
||
|
||
def apply_to_quote(quote: dict[str, Any], condition: LandQuoteCondition | None) -> dict[str, Any]:
|
||
"""
|
||
把条件写进报价对象:税率/燃油费率/备注,并按需乘主运费。
|
||
|
||
写入键同时给 snake_case 和 camelCase,主账与群摘要都能读到。
|
||
「未含燃油」的乘法范围:
|
||
* 车型价 vehicleRates / vehicle_rates(全是主运费);
|
||
* 分档单价 weightPrices[].price 与 price_per_kg;
|
||
* 费用行里 is_main_transport_fee 命中的行(运输费/陆运费/运费…)。
|
||
合计修正:
|
||
* 有车型价/分档价:合计取调整后的第一档(与产品「展示取第一档」一致);
|
||
* 只有费用行:在原合计上加上主运费增量,提货/报关等杂费不参与乘法。
|
||
参数 quote:本次入参报价 dict,会被原地修改。
|
||
返回:同一个 dict,便于调用方链式返回。
|
||
副作用:改 quote 及其 fee_rows/vehicleRates/weightPrices。线程:调用方各自持有报价副本。
|
||
"""
|
||
if not isinstance(quote, dict) or condition is None:
|
||
return quote
|
||
|
||
rate = str(condition.tax_rate or "").strip()
|
||
if rate:
|
||
quote["tax_rate"] = rate
|
||
quote["taxRate"] = rate
|
||
elif condition.clear_tax:
|
||
# 未含税无点数:税率必须空着,清掉同句其它规则误抽的税率。
|
||
quote.pop("tax_rate", None)
|
||
quote.pop("taxRate", None)
|
||
|
||
fuel = str(condition.fuel_rate or "").strip()
|
||
if fuel:
|
||
quote["fuel_surcharge_rate"] = fuel
|
||
quote["fuelSurchargeRate"] = fuel
|
||
|
||
# 未含税无点数的备注就是空:不新增,也不抹掉同句里真正单独的「备注:…」。
|
||
if condition.remark:
|
||
quote["remark"] = condition.remark
|
||
_stamp_remark_on_fee_rows(quote.get("fee_rows"), condition.remark)
|
||
|
||
if condition.multiply_fuel and fuel:
|
||
try:
|
||
factor = Decimal("1") + Decimal(fuel.rstrip("%")) / Decimal("100")
|
||
except (InvalidOperation, ValueError):
|
||
factor = Decimal("1")
|
||
if factor != Decimal("1"):
|
||
_multiply_main_freight(quote, factor)
|
||
return quote
|
||
|
||
|
||
def _stamp_remark_on_fee_rows(rows: Any, remark: str) -> None:
|
||
"""
|
||
条件备注优先挂到主运费行,其次才挂第一条非费率行。
|
||
|
||
为什么优先主运费:跨境整车无 landSegments 时,主账用「运输费」行拼路线行,
|
||
路线行的 remark 直接读这一行;挂到提货费/报关费上,底部备注会读不到。
|
||
副作用:改 rows 里的 dict。
|
||
"""
|
||
if not isinstance(rows, list):
|
||
return
|
||
fallback = None
|
||
for row in rows:
|
||
if not isinstance(row, dict):
|
||
continue
|
||
if "%" in str(row.get("amount") or ""):
|
||
continue
|
||
if fallback is None:
|
||
fallback = row
|
||
if is_main_transport_fee(str(row.get("name") or "")):
|
||
row["remark"] = remark
|
||
return
|
||
if fallback is not None:
|
||
fallback["remark"] = remark
|
||
|
||
|
||
def _multiply_main_freight(quote: dict[str, Any], factor: Decimal) -> None:
|
||
"""
|
||
未含燃油:乘主运费并修正展示合计。
|
||
|
||
先算费用行增量,再处理车型/分档价;顺序不影响结果,因为两条路径互斥:
|
||
多车型价时 fee_rows 只有一行「陆运费」摘要,分档价时 fee_rows 是档位明细。
|
||
"""
|
||
total_before = _as_decimal(quote.get("total"))
|
||
# 分档价的 fee_rows 是「2-500KG / 500KG以上」档位明细,费目名不含「运费」,
|
||
# 按主运费规则会漏乘;这里先按 weightPrices 判断,档位价与顶层价必须同乘。
|
||
tiers = quote.get("weightPrices")
|
||
if isinstance(tiers, list) and tiers:
|
||
_scale_rows(quote.get("fee_rows"), factor, only_main=False)
|
||
fee_lines = quote.get("fee_lines")
|
||
if isinstance(fee_lines, list) and fee_lines is not quote.get("fee_rows"):
|
||
same_objects = bool(fee_lines) and fee_lines[0] is (quote.get("fee_rows") or [None])[0]
|
||
if not same_objects:
|
||
_scale_rows(fee_lines, factor, only_main=False)
|
||
for tier in tiers:
|
||
if isinstance(tier, dict) and str(tier.get("price") or "").strip():
|
||
tier["price"] = _scale_amount(tier.get("price"), factor)
|
||
first_tier = tiers[0] if isinstance(tiers[0], dict) else {}
|
||
first = str(first_tier.get("price") or "").strip()
|
||
if first:
|
||
quote["total"] = first
|
||
quote["price_per_kg"] = first
|
||
return
|
||
|
||
delta = _scale_rows(
|
||
quote.get("fee_rows"),
|
||
factor,
|
||
only_main=True,
|
||
delta_currency=str(quote.get("currency") or ""),
|
||
)
|
||
# fee_lines 常与 fee_rows 是同一批 dict;若被复制成两份,再乘一次会翻倍。
|
||
fee_lines = quote.get("fee_lines")
|
||
if isinstance(fee_lines, list) and fee_lines is not quote.get("fee_rows"):
|
||
same_objects = bool(fee_lines) and fee_lines[0] is (quote.get("fee_rows") or [None])[0]
|
||
if not same_objects:
|
||
delta += _scale_rows(
|
||
fee_lines,
|
||
factor,
|
||
only_main=True,
|
||
delta_currency=str(quote.get("currency") or ""),
|
||
)
|
||
|
||
rates = quote.get("vehicleRates") or quote.get("vehicle_rates")
|
||
if isinstance(rates, dict) and rates:
|
||
scaled = {
|
||
str(key): _scale_amount(val, factor)
|
||
for key, val in rates.items()
|
||
if str(key).strip()
|
||
}
|
||
quote["vehicleRates"] = dict(scaled)
|
||
quote["vehicle_rates"] = dict(scaled)
|
||
# 车型价明细也一起乘,群摘要「车型价」才和合计一致。
|
||
_scale_rows(quote.get("vehicle_fee_rows"), factor, only_main=False)
|
||
first = next(iter(scaled.values()), "")
|
||
if first:
|
||
quote["total"] = first
|
||
return
|
||
|
||
if total_before is not None:
|
||
quote["total"] = _scale_amount(total_before + delta, Decimal("1"))
|