Compare commits

...
Author SHA1 Message Date
linmianxunandCursor 97f0219dfd 产品调价继承工单币种(港币不再默成美元);陆运集拼空分档只填询价重量那一档,跨境整车按已选线路写起讫。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 19:22:44 +08:00
linmianxun 3a4c440354 Merge remote-tracking branch 'origin/feat/list-footer-multi-hint-20261012' into lmx202610121455 2026-10-12 16:37:56 +08:00
jillion886andCursor 4f8c373121 后台列表总数改到每页左边,报价模板页同样靠右。陆运选线补每段车型。多段群每次带出询价字段时,底部补上另报提示。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 14:59:07 +08:00
linmianxunandCursor 428548c390 陆运产品价无费名时默认陆运费;看板指标与工单列表共用起止日,趋势按日铺点。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 14:57:27 +08:00
linmianxunandCursor 739ba401aa 空运报价有费才出行并补齐单位数量;模板按 sha 防 MinIO 坏文件,锁舱运输费必带重量单位。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 09:56:31 +08:00
jillion886andCursor 185abbf45e 空运「货交」只记提货地址,不再当成起运地。舱位旧说法「释放」先问航线是否取消,陆运通关口岸示例改为友谊关。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 20:45:53 +08:00
linmianxunandCursor b070a9b7a7 后台按查看权限收紧菜单与「只看自己」数据范围;跨境整车报价填表更稳,协商中顺延不再误报销售超时。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 13:04:09 +08:00
linmianxunandCursor ae818f26b1 合并 feat/continue-deal-card-20261009:报价发出后继续工单重发成交卡;空运锁舱补参与看板滚动一并收下。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-09 09:06:43 +08:00
linmianxunandCursor ab6923d8cc 运营后台中间主区可滚动:看板不再被裁切无条,列表页仍表格区内滚。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 11:39:45 +08:00
linmianxunandCursor e197ecea10 空运人工价锁舱现拉补全舱位并拦清缺参;成交/报价填表与工单陆运费率展示同步收紧。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-07 23:35:24 +08:00
64 changed files with 5318 additions and 849 deletions
@@ -1,7 +1,7 @@
"""
陆运选线路 H5 页。
本文件职责:按完整线路列出各段成本与合计,提交所选下标。
本文件职责:按完整线路列出各段车型、成本与合计,提交所选下标。
样式对齐空运选线路页。禁止 URL userid;禁止本页查 TMS。
"""
@@ -64,19 +64,40 @@ def render_land_route_ok() -> str:
)
def _segment_vehicle(leg: dict[str, Any] | None) -> str:
"""每段车型用 TMS 的 vehicleType 原文。没有台数,空值显示 -。"""
src = dict(leg or {})
raw = str(
src.get("vehicleType") or src.get("vehicle_type") or src.get("truckType") or ""
).strip()
if raw.lower() in {"none", "null"}:
raw = ""
return raw or "-"
def _route_card(index: int, route: dict[str, Any], quote: dict[str, Any] | None = None) -> str:
"""一张线路:航线、各段路段+TMS 费目、合计。"""
"""一张线路:航线、各段路段、车型、TMS 费目、合计。"""
line = html.escape(route_line(route))
blocks = land_leg_fee_blocks_for_route(quote, route)
shown_legs = [
leg
for leg in list(route.get("legs") or [])
if str(leg.get("origin") or "").strip() or str(leg.get("destination") or "").strip()
]
etas = {i: d for i, (_, d) in enumerate(option_eta_bits(route), 1)}
fee_bits: list[str] = []
items = ""
if blocks:
for i, (title, fees, eta) in enumerate(blocks, 1):
vehicle = _segment_vehicle(shown_legs[i - 1] if i - 1 < len(shown_legs) else None)
items += (
f"<li class='leg'><span class='n'>{html.escape(title)}</span>"
"<span></span></li>"
)
items += (
f"<li><span class='n'>车型 {html.escape(vehicle)}</span>"
"<span></span></li>"
)
for fee in fees:
amount = _money(fee.get("amount"), str(fee.get("currency") or "").strip())
name = str(fee.get("name") or "").strip()
@@ -53,6 +53,8 @@ from agent.routing.air_group_intent import (
INTENT_PICK_OPTION,
INTENT_QUOTE,
INTENT_RELEASE,
INTENT_RELEASE_ASK,
cabin_confirm_answer,
classify_air_group_text,
)
@@ -167,6 +169,9 @@ def handle_air_group(
return "duplicate_inbound"
mark_air_text(chat_id=chat_id, sender_id=message.sender_id, text=text)
wo = copy.extract_work_order_no(text)
answered = _answer_pending_cabin_cancel(engine, message, text)
if answered:
return answered
# 句中有多段工单号,或本群已经激活过多段单:跟这张单,不必每句再带工单号。
followed = _follow_activated_multi(
engine,
@@ -200,7 +205,7 @@ def handle_air_group(
intent,
wo or "-",
)
if intent in {INTENT_LOCK, INTENT_RELEASE}:
if intent in {INTENT_LOCK, INTENT_RELEASE, INTENT_RELEASE_ASK}:
return _handle_cabin(
engine,
message,
@@ -309,6 +314,92 @@ def _should_speak_activate(intent: str) -> bool:
return intent in {INTENT_ACTIVATE, INTENT_OTHER}
def _answer_pending_cabin_cancel(engine, message: InboundMessage, text: str) -> str:
"""
上一句已经问过是否取消舱位。
航线回是/需要/确认/取消舱位才执行。回否/不用/不需要就停。
销售回这些词不算。说了别的业务就清掉询问,按那句话继续办。
没有待确认时返回空串。
"""
from agent.policy.air_group_ops import is_airline
from agent.redis_coord.pending_cabin_cancel import (
clear_pending_cabin_cancel,
load_pending_cabin_cancel,
)
chat_id = (message.chat_id or "").strip()
pending_wo = load_pending_cabin_cancel(chat_id)
if not pending_wo:
return ""
kind = cabin_confirm_answer(text)
if not kind:
clear_pending_cabin_cancel(chat_id)
logger.info("cabin.ask dropped chat=%s wo=%s", chat_id, pending_wo)
return ""
if not is_airline(engine, message.sender_id):
send_group_text(group_client_of(engine), chat_id, copy.air_airline_only_cabin())
return "not_airline"
clear_pending_cabin_cancel(chat_id)
if kind == "no":
send_group_text(group_client_of(engine), chat_id, copy.air_release_ask_dropped())
return "release_ask_dropped"
ticket, phase = resolve_cabin_ticket(
flow=engine,
chat_id=chat_id,
work_order_no=pending_wo,
allow_terminal=True,
)
if ticket is None:
return phase
return apply_air_release(
flow=engine,
ticket=ticket,
sender_id=message.sender_id,
chat_id=chat_id,
instruction=text,
)
def _ask_cabin_cancel(
engine,
message: InboundMessage,
*,
work_order_no: str,
) -> str:
"""航线说了释放舱位:只提问,不打 TMS。"""
from agent.policy.air_group_ops import is_airline
from agent.redis_coord.pending_cabin_cancel import save_pending_cabin_cancel
chat_id = message.chat_id
if not is_airline(engine, message.sender_id):
send_group_text(group_client_of(engine), chat_id, copy.air_airline_only_cabin())
return "not_airline"
no = (work_order_no or "").strip()
if not no:
bound = current_ticket(engine, chat_id)
if bound is not None and is_air_ticket(bound):
from agent.policy.sea_group_ops import ticket_no
no = ticket_no(bound)
if not no:
send_group_text(group_client_of(engine), chat_id, copy.air_lock_need_work_order())
return "cabin_need_work_order"
ticket, phase = resolve_cabin_ticket(
flow=engine,
chat_id=chat_id,
work_order_no=no,
allow_terminal=True,
)
if ticket is None:
return phase
from agent.policy.sea_group_ops import ticket_no
save_pending_cabin_cancel(chat_id, ticket_no(ticket))
send_group_text(group_client_of(engine), chat_id, copy.air_release_ask())
return "release_ask"
def _handle_cabin(
engine,
message: InboundMessage,
@@ -319,6 +410,12 @@ def _handle_cabin(
) -> str:
_ = injected_quote
chat_id = message.chat_id
if intent == INTENT_RELEASE_ASK:
return _ask_cabin_cancel(
engine,
message,
work_order_no=work_order_no,
)
if not work_order_no:
# 本群已经在锁这张单时,补舱位不用再报工单号。
bound = current_ticket(engine, chat_id)
@@ -123,6 +123,35 @@ def notify_app_flag(override: Optional[bool]) -> bool:
return notify_app_ready()
def _skip_sales_timeout(
*,
status: str,
wait_kind: str,
next_followup_at: str,
lost_reason: str,
now: datetime,
) -> str:
"""
成交跟进相关等待在终态/顺延窗内不应再告警。
返回跳过原因;空串表示继续按小时判定。
协商中:只要还排着再问时刻(next_followup_at > now),就不发销售超时;
再问认领后会清空该时刻并重新 start deal,那时才重新计时。
"""
st = (status or "").strip()
_ = wait_kind
if st == "未成交" and (lost_reason or "").strip():
return "lost_reason_recorded"
if st == "协商中":
raw = (next_followup_at or "").strip()
if not raw:
return ""
due = _parse_started(raw)
if due is None or due > now:
return "negotiate_followup_pending"
return ""
def _handle_one(
row: dict[str, Any],
*,
@@ -139,6 +168,14 @@ def _handle_one(
kind = str(row.get("event_wait_kind") or row.get("eventWaitKind") or "").strip()
if not no or not kind:
return False
status = str(row.get("status") or "").strip()
followup = str(row.get("next_followup_at") or row.get("nextFollowupAt") or "").strip()
lost_reason = str(row.get("lost_reason") or row.get("lostReason") or "").strip()
# 产品口径:协商中顺延再问期间不算「销售无响应」;未成交已写原因不再催。
# 即使 clear_wait 失败留下陈旧 deal 等待,这里也要挡住(WO202610060024 / WO202610070034)。
skip_reason = _skip_sales_timeout(
status=status, wait_kind=kind, next_followup_at=followup, lost_reason=lost_reason, now=now
)
line = str(row.get("business_line") or row.get("businessLine") or "").strip()
facts = dict(row.get("facts") or {})
klass = str(facts.get("运输分类") or facts.get("transportType") or "").strip()
@@ -154,6 +191,9 @@ def _handle_one(
started = _parse_started(row.get("event_wait_started_at") or row.get("eventWaitStartedAt"))
if started is None:
return False
if skip_reason:
logger.info("事件异常跳过 wo=%s kind=%s reason=%s", no, kind, skip_reason)
return False
if workday_elapsed_hours(started, now) < hours:
return False
watchers = [dict(x) for x in (row.get("watchers") or []) if isinstance(x, dict)]
+18 -4
View File
@@ -40,8 +40,18 @@ class HttpLedger:
def _post(self, path: str, body: dict[str, Any], *, idem: str = "") -> dict[str, Any]:
resp = self._client.request_json("POST", path, json_body=body, idempotency_key=idem)
if not resp.ok:
logger.warning("http_ledger fail path=%s status=%s err=%s", path, resp.status_code, resp.error)
return {"ok": False, "error": resp.error or f"http_{resp.status_code}"}
# 500 时 Jeecg 仍可能带回 message(如六态非法);勿只留 http_500,
# 否则成交补「已报价」重试认不出「询价中」(WO023)。
data = resp.data if isinstance(resp.data, dict) else {}
msg = ""
if isinstance(data, dict):
msg = str(data.get("message") or "").strip()
unwrapped = _unwrap(data)
if unwrapped.get("error"):
msg = str(unwrapped.get("error") or msg)
err = msg or resp.error or f"http_{resp.status_code}"
logger.warning("http_ledger fail path=%s status=%s err=%s", path, resp.status_code, err)
return {"ok": False, "error": err}
return _unwrap(resp.data)
def find_similar_open(
@@ -166,8 +176,12 @@ class HttpLedger:
"""
no = (work_order_no or "").strip()
src = dict(quote or {})
if not no or not src:
return {"ok": True, "quote_version": 1, "status": to_status or "已报价"}
if not no:
return {"ok": False, "error": "work_order_blank"}
# 空报价不打主账(避免抹掉已有查价),但禁止伪装成「已写入已报价」——
# 否则会话以为已报价、主账仍停询价中,成交三态会失败(WO022)。
if not src:
return {"ok": False, "error": "quote_blank", "skipped": True}
out = self._post(
"/inquiry/agent/ticket/replaceTmsQuote",
{"workOrderNo": no, "quote": src, "toStatus": to_status},
+49 -1
View File
@@ -344,12 +344,23 @@ class MemoryLedger:
ticket.next_followup_at = ""
if lost_reason:
ticket.lost_reason = lost_reason
# 成交等待结束;若仍缺原因由智能体再 start lost_reason
ticket.event_wait_kind = ""
ticket.event_wait_started_at = ""
ticket.event_wait_alerted = 0
elif to_status == "已成交":
ticket.next_followup_at = ""
if deal_notify_summary:
ticket.deal_notify_summary = deal_notify_summary
ticket.event_wait_kind = ""
ticket.event_wait_started_at = ""
ticket.event_wait_alerted = 0
elif to_status == "协商中":
ticket.next_followup_at = next_followup_at
# 顺延再问期间不盯成交超时;到期再问会重新 start deal
ticket.event_wait_kind = ""
ticket.event_wait_started_at = ""
ticket.event_wait_alerted = 0
return {"ok": True, "status": ticket.status}
def patch_lost_reason(self, *, work_order_no: str, lost_reason: str) -> dict[str, Any]:
@@ -363,6 +374,9 @@ class MemoryLedger:
if not reason:
return {"ok": False, "error": "reason_blank"}
ticket.lost_reason = reason
ticket.event_wait_kind = ""
ticket.event_wait_started_at = ""
ticket.event_wait_alerted = 0
return {"ok": True, "work_order_no": work_order_no, "lost_reason": reason}
def claim_due_negotiate(self) -> list[dict[str, Any]]:
@@ -829,7 +843,11 @@ class MemoryLedger:
airline: str = "",
flight_no: str = "",
) -> dict[str, Any]:
"""单测可注入 _cabin_lock_result;默认成功。"""
"""单测可注入 _cabin_lock_result;默认成功。
纯人工且视图无 TMS 舱位时,缺 option/航司/航班 → lock_incomplete,
对齐主账「现拉仍缺才回」的口径(内存账不会真查 TMS)。
"""
_ = sender_id, operator_name, instruction_text, airline, flight_no
forced = getattr(self, "_cabin_lock_result", None)
if isinstance(forced, dict):
@@ -846,6 +864,27 @@ class MemoryLedger:
quote_id = str(quote.get("quoteId") or "").strip()
if quote_id.upper().startswith("QT-WO"):
quote_id = ""
air_opts = quote.get("airOptions") or quote.get("air_options") or []
has_tms_cabin = bool(quote_id) or bool(air_opts)
opt = (option_no or "").strip()
air = (airline or "").strip()
fn = (flight_no or "").strip()
if not has_tms_cabin:
missing: list[str] = []
if not opt:
missing.append("舱位编号optionNo")
if not air:
missing.append("航司airline")
if not fn:
missing.append("航班号flightNo")
if missing:
return {
"ok": False,
"error": "lock_incomplete",
"failReason": "锁舱参数不完整,缺少:"
+ "、".join(missing)
+ "。请按「AIR-OPT01 CZ 航班CZ327」补舱位、航司和航班号后再锁。",
}
return {
"ok": True,
"status": "LOCKED",
@@ -915,6 +954,11 @@ class MemoryLedger:
continue
if ticket.status in {"已成交", "已关闭", "转人工"}:
continue
# 未成交已写原因、协商中仍排着再问:不进巡检列表
if ticket.status == "未成交" and (ticket.lost_reason or "").strip():
continue
if ticket.status == "协商中" and (ticket.next_followup_at or "").strip():
continue
watchers: list[dict[str, Any]] = []
seen: set[str] = set()
sales_id = (ticket.sales_wecom_id or "").strip()
@@ -964,6 +1008,10 @@ class MemoryLedger:
"collab_member_ids": list(ticket.collab_member_ids),
"facts": dict(ticket.facts),
"eventException": ticket.event_exception,
"lost_reason": ticket.lost_reason,
"lostReason": ticket.lost_reason,
"next_followup_at": ticket.next_followup_at,
"nextFollowupAt": ticket.next_followup_at,
"watchers": watchers,
}
)
+303 -30
View File
@@ -11,14 +11,17 @@ import logging
import re
from typing import Any, Optional
from agent.schema.field_validate import QUOTE_DATE_SYNONYMS
try:
from agent.schema.field_validate import QUOTE_DATE_SYNONYMS
except ImportError: # 测服旧 release 未导出同义词时仍可抽产品价
QUOTE_DATE_SYNONYMS = ()
logger = logging.getLogger(__name__)
# 报价日期同义词。长的在前,避免短词截断。货好时间、提货地址不在这里。
_QUOTE_DATE_LABEL_RE = "|".join(
re.escape(name)
for name in sorted(("报价日期",) + QUOTE_DATE_SYNONYMS, key=len, reverse=True)
for name in sorted(("报价日期",) + tuple(QUOTE_DATE_SYNONYMS or ()), key=len, reverse=True)
)
_MODE_WORDS = (
@@ -371,6 +374,68 @@ def _tighten_sheet_labels(text: str) -> str:
return body
# 「货交上海」是提货地址,不是起运地。地址/地、到/于只是口语粘连,不进地址正文。
_RE_CARGO_HANDOVER = re.compile(
r"货交\s*(?:地址|地)?\s*[::]?\s*(?:到|于|至|往)?\s*([^\n,,。;;]{1,60})"
)
# 同一行跟在地址后面的询价口头禅或下一栏字段,不是地址的一部分。
_RE_HANDOVER_TAIL = re.compile(
r"(?:\s+|,|,)?(?:看看价格|看一下价格|看价格|询价|报价|多少钱|多少|"
r"目的地|目的港|起运地|起运港|品名|件数|毛重|体积|包装|空运|海运|陆运).*$"
)
# 另有起运说法时保留起运地。先抠掉「货交…」,避免「货交到上海」被当成「到上海」。
_RE_EXPLICIT_ORIGIN = re.compile(
r"起运地|起运港|"
r"[A-Za-z]{3}\s*[-–—//]\s*[A-Za-z]{3}|"
r"[A-Za-z]{3}\s*(?:到|至)\s*[A-Za-z]{3}|"
r"从\s*\S{1,16}\s*(?:飞|到|至)|"
r"[\u4e00-\u9fff]{2,12}\s*飞|"
r"[\u4e00-\u9fff]{2,12}\s*到\s*[\u4e00-\u9fffA-Za-z]{2,12}"
)
def _handover_place(raw: str) -> str:
"""货交后面的地名。去掉口头禅和首尾标点,空的不当地址。"""
place = _RE_HANDOVER_TAIL.sub("", (raw or "").strip())
return place.strip(" ::,,。;;")
def _has_explicit_origin(text: str) -> bool:
"""原话里另写了起运地、三字码航线或「从哪飞/到」。货交那一段先拿掉。"""
stripped = _RE_CARGO_HANDOVER.sub(" ", text or "")
return _RE_EXPLICIT_ORIGIN.search(stripped) is not None
def apply_cargo_handover_synonym(
text: str,
facts: dict[str, str] | None,
*,
business_line: str = "",
) -> dict[str, str]:
"""
货交 = 提货地址。例:货交上海 → 提货地址上海。
只认原话里的「货交」,不把裸城市猜成港口。
空运且没有另写起运地时,清掉被误收成起运地的同一处地名,否则 TMS 会按错误起运查价。
海运/陆运只补提货地址,不动起运港。副作用:无。
"""
merged = dict(facts or {})
places: list[str] = []
for hit in _RE_CARGO_HANDOVER.finditer(text or ""):
place = _handover_place(hit.group(1))
if place and place not in places:
places.append(place)
if not places:
return merged
merged["提货地址"] = "、".join(places)
is_air = (business_line or "").strip().upper() == "AIR" or "空运" in (text or "")
if is_air and not _has_explicit_origin(text):
merged.pop("起运港", None)
merged.pop("起运地", None)
merged.pop("originCode", None)
return merged
def _drop_fee_place_values(facts: dict[str, str]) -> dict[str, str]:
"""起运地/目的地收成「操作费、文件费」时丢掉。那是费用栏,不是港口。"""
out = dict(facts or {})
@@ -407,6 +472,7 @@ def extract_inquiry_snapshot(
facts = harvest_oral_measures(text, normalize_facts(dict(injected_facts)))
facts = _merge_spoken_collab(text, facts)
facts = _merge_optional_inquiry_labels(text, facts)
facts = apply_cargo_handover_synonym(text, facts, business_line=mode)
for key in ("货好时间", "提货地址", "收货地址", "货源地", "贸易条款"):
if str(facts.get(key) or "").strip():
facts[key] = clip_inquiry_value(str(facts[key]))
@@ -453,6 +519,7 @@ def extract_inquiry_snapshot(
facts = harvest_oral_measures(text, normalize_facts(facts))
facts = _merge_spoken_collab(text, facts)
facts = _merge_optional_inquiry_labels(text, facts)
facts = apply_cargo_handover_synonym(text, facts, business_line=mode)
for key in ("货好时间", "提货地址", "收货地址", "货源地", "贸易条款"):
if str(facts.get(key) or "").strip():
facts[key] = clip_inquiry_value(str(facts[key]))
@@ -765,18 +832,44 @@ def extract_air_collab_fields(
return {k: got[k] for k in keys if str(got.get(k) or "").strip()}
# 金额旁币种词:含港币;禁止只认 USD/CNY 把港币单漏成美元。
_CCY_TOKEN = r"USD|CNY|RMB|HKD|EUR|JPY|GBP|美金|美元|人民币|港币|港元|欧元|日元|英镑"
_RE_MONEY = re.compile(
r"(?:USD|CNY|RMB|美金|美元|人民币)?\s*(\d+(?:\.\d+)?)\s*(?:USD|CNY|RMB|美金|美元|人民币|元)?"
r"|(?:USD|CNY|RMB|美金|美元)\s*(\d+(?:\.\d+)?)",
rf"(?:{_CCY_TOKEN}|元)?\s*(\d+(?:\.\d+)?)\s*(?:{_CCY_TOKEN}|元)?"
rf"|(?:{_CCY_TOKEN})\s*(\d+(?:\.\d+)?)",
re.I,
)
# 陆运集拼:「2-500KG 单价CNY990」是分档单价,不是「燃油附加费=2」。
_RE_WEIGHT_BAND_PRICE = re.compile(
r"(?P<min>\d+)\s*[-~~—–到至]\s*(?P<max>\d+)\s*K\s*G"
r"(?:\s*以上)?"
r"\s*(?:单价)?"
rf"\s*(?:(?P<ccy>{_CCY_TOKEN})\s*)?"
r"(?P<price>\d+(?:\.\d+)?)",
re.I,
)
_RE_WEIGHT_BAND_OPEN = re.compile(
r"(?P<min>\d+)\s*K\s*G\s*以上"
r"\s*(?:单价)?"
rf"\s*(?:(?P<ccy>{_CCY_TOKEN})\s*)?"
r"(?P<price>\d+(?:\.\d+)?)",
re.I,
)
_RE_FUEL_SURCHARGE_RATE = re.compile(
r"燃油附加费率\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?",
re.I,
)
_RE_TAX_RATE = re.compile(
r"(?<![A-Za-z\u4e00-\u9fff])税率\s*[::=]?\s*(?P<rate>\d+(?:\.\d+)?)\s*%?",
re.I,
)
_RE_FEE_LINE = re.compile(
r"(?P<name>[\u4e00-\u9fffA-Za-z][\u4e00-\u9fffA-Za-z0-9/()()++\--]{0,24}费|[A-Za-z]{2,10})"
r"\s*(?:改为|改成|调整为|调整成)?"
r"\s*[::=]?"
r"\s*(?:(?P<ccy1>USD|CNY|RMB|美金|美元|人民币)\s+)?"
rf"\s*(?:(?P<ccy1>{_CCY_TOKEN})\s+)?"
r"(?P<amount>\d+(?:\.\d+)?)"
r"\s*(?P<ccy2>USD|CNY|RMB|美金|美元|人民币|元)?",
rf"\s*(?P<ccy2>{_CCY_TOKEN}|元)?",
re.I,
)
# 「文件发改为:500」漏了「费」、中间还有冒号,不能丢掉。
@@ -785,19 +878,21 @@ _RE_FEE_CHANGE = re.compile(
r"\s*(?:改为|改成|调整为|调整成)"
r"\s*[::=]?"
r"\s*(?P<amount>\d+(?:\.\d+)?)"
r"\s*(?P<ccy>USD|CNY|RMB|美金|美元|人民币|元)?",
rf"\s*(?P<ccy>{_CCY_TOKEN}|元)?",
re.I,
)
_SKIP_FEE_NAMES = frozenset({"usd", "cny", "rmb", "美金", "美元", "人民币", "元"})
_SKIP_FEE_NAMES = frozenset(
{"usd", "cny", "rmb", "hkd", "eur", "jpy", "gbp", "美金", "美元", "人民币", "港币", "港元", "元"}
)
# 航线常写「空运费 单价CNY99,数量100,金额CNY199」。单价和金额不是同一个数,必须认金额。
_RE_FEE_PRICED = re.compile(
r"(?P<name>[\u4e00-\u9fffA-Za-z][\u4e00-\u9fffA-Za-z0-9/()()++\--]{0,24}费)"
r"\s*单价\s*"
r"(?:(?P<unit_ccy>USD|CNY|RMB|美金|美元|人民币)\s*)?"
rf"(?:(?P<unit_ccy>{_CCY_TOKEN})\s*)?"
r"(?P<unit>\d+(?:\.\d+)?)"
r"(?:\s*[,,、]\s*数量\s*(?P<qty>\d+(?:\.\d+)?))?"
r"(?:\s*[,,、]\s*金额\s*"
r"(?:(?P<amt_ccy>USD|CNY|RMB|美金|美元|人民币)\s*)?"
rf"(?:(?P<amt_ccy>{_CCY_TOKEN})\s*)?"
r"(?P<amount>\d+(?:\.\d+)?))?",
re.I,
)
@@ -810,21 +905,40 @@ def _ascii_amount(raw: str) -> str:
def _currency_of(text: str, hint: str = "") -> str:
"""
从正文/提示抽三字码。正文没写币种时只回传 hint,禁止默认编造 USD。
港币必须先于「元」判断,避免「港元」被误判成 CNY。
WO202610090107:TMS 是 HKD,产品只写「运输费调整为1100」时必须继承 HKD。
"""
blob = f"{hint} {text}".upper()
if any(x in blob for x in ("CNY", "RMB", "人民币", "元")):
raw = f"{hint} {text}"
if any(x in blob for x in ("HKD", "港币", "港元", "HK$")) or "港币" in raw or "港元" in raw:
return "HKD"
if any(x in blob for x in ("CNY", "RMB", "人民币")) or (
"元" in raw and "港元" not in raw and "港币" not in raw
):
return "CNY"
if any(x in blob for x in ("USD", "美金", "美元")):
return "USD"
return hint or "USD"
if any(x in blob for x in ("EUR", "欧元")):
return "EUR"
if any(x in blob for x in ("JPY", "日元")):
return "JPY"
if any(x in blob for x in ("GBP", "英镑")):
return "GBP"
return str(hint or "").strip().upper()
def _parse_fee_rows(text: str) -> list[dict[str, str]]:
def _parse_fee_rows(text: str, baseline_currency: str = "") -> list[dict[str, str]]:
"""
按行抽费用:码头操作费100CNY、报关费改为300CNY。
只认带「费」的中文名或短英文费用码,避免把工单号当金额。
句里无币种时继承 baseline_currency(通常是当前 TMS/主账币种),禁止默认 USD。
"""
raw = _ascii_amount(text or "")
base_ccy = str(baseline_currency or "").strip().upper()
rows: list[dict[str, str]] = []
seen: set[str] = set()
@@ -837,10 +951,11 @@ def _parse_fee_rows(text: str) -> list[dict[str, str]]:
if name in seen:
return
seen.add(name)
line_ccy = _currency_of(raw, ccy or base_ccy) or base_ccy
row = {
"name": name,
"amount": amount,
"currency": _currency_of(raw, ccy),
"currency": line_ccy,
}
for key, val in extra.items():
if val:
@@ -873,14 +988,45 @@ def _parse_fee_rows(text: str) -> list[dict[str, str]]:
return rows
def extract_product_quote(text: str, *, injected: Optional[dict[str, Any]] = None) -> dict[str, Any]:
def _default_product_fee_name(business_line: str = "", transport_mode: str = "") -> str:
"""
产品文字未点费用名时的默认费目。
必须跟本单运输方式走:陆运→陆运费、空运→空运费、其余→海运费。
禁止陆运单无费名时硬编码「海运费」(WO202610090118「价格为1RMB/KG」)。
"""
line = (business_line or "").strip().upper()
mode = (transport_mode or "").strip()
if line == "LAND" or mode in {"陆运", "LAND", "land"}:
return "陆运费"
if line == "AIR" or mode in {"空运", "AIR", "air"}:
return "空运费"
if line == "SEA" or mode in {"海运", "SEA", "sea"}:
return "海运费"
# 未传业务线时保持旧默认,避免海运调用方漏参后费名变空。
return "海运费"
def extract_product_quote(
text: str,
*,
injected: Optional[dict[str, Any]] = None,
business_line: str = "",
transport_mode: str = "",
baseline_currency: str = "",
) -> dict[str, Any]:
"""
产品文字报价:先按费用行抽,再退回合计/币别。注入优先。
认不出价格返回空 dict,调用方回「没有识别到报价」。
群里常见「码头操作费100CNY / 报关费改为300CNY」,不能只把第一笔数当成海运费。
「空运费 单价…金额…」必须保留空运费,金额用「金额」后面的数,不用单价。
陆运集拼:「2-500KG 单价CNY990,燃油附加费率1%,税率6%」走分档单价+费率,
禁止把公斤档下限「2」当成燃油附加费金额(WO021)。
无费用名时按 business_line/transport_mode 默认陆运费/空运费/海运费,禁止陆运硬套海运费。
正文未写币种时继承 baseline_currency(当前 TMS/主账币种),禁止默认 USD(WO107)。
"""
base_ccy = str(baseline_currency or "").strip().upper()
if isinstance(injected, dict) and (injected.get("total") or injected.get("fee_rows")):
out = dict(injected)
out.setdefault("source_label", "产品报价")
@@ -892,16 +1038,22 @@ def extract_product_quote(text: str, *, injected: Optional[dict[str, Any]] = Non
compact = stripped.replace(" ", "").replace(" ", "")
if re.fullmatch(r"WO\d{12}", compact, re.I):
return {}
rows = _parse_fee_rows(raw)
band = _parse_weight_band_quote(raw, baseline_currency=base_ccy)
if band:
return band
# 费率句若仍落到普通费用行,会把「燃油附加费」配上句首公斤数。先剥掉再抽。
scrubbed = _strip_rate_and_band_noise(raw)
rows = _parse_fee_rows(scrubbed, baseline_currency=base_ccy) if scrubbed.strip() else []
if rows:
ccy = rows[0].get("currency") or _currency_of(raw)
total = rows[0]["amount"]
if len({x.get("currency") for x in rows}) == 1:
ccy = rows[0].get("currency") or _currency_of(raw, base_ccy) or base_ccy
money_rows = [x for x in rows if "%" not in str(x.get("amount") or "")]
total = (money_rows[0] if money_rows else rows[0])["amount"]
if money_rows and len({x.get("currency") for x in money_rows}) == 1:
try:
total = str(sum(float(x["amount"]) for x in rows))
total = str(sum(float(x["amount"]) for x in money_rows))
except ValueError:
total = rows[0]["amount"]
return {
total = money_rows[0]["amount"]
out = {
"total": total,
"currency": ccy,
"source_label": "产品报价",
@@ -909,22 +1061,30 @@ def extract_product_quote(text: str, *, injected: Optional[dict[str, Any]] = Non
"fee_rows": rows,
"fee_lines": list(rows),
}
hit = _RE_MONEY.search(_ascii_amount(raw))
out.update(_extract_rate_fields(raw))
return out
hit = _RE_MONEY.search(_ascii_amount(scrubbed or raw))
if not hit:
return {}
rates = _extract_rate_fields(raw)
return rates if rates else {}
amount = _ascii_amount(hit.group(1) or hit.group(2) or "")
if not amount:
return {}
ccy = _currency_of(raw)
ccy = _currency_of(raw, base_ccy) or base_ccy
default_fee = _default_product_fee_name(business_line, transport_mode)
# 句里已经点了费用名(空运费)时,不能退回默认海运费。
named = re.search(
r"([\u4e00-\u9fffA-Za-z][\u4e00-\u9fffA-Za-z0-9/()()++\--]{0,24}费)",
raw,
scrubbed or raw,
)
fee_name = (named.group(1) if named else "") or "海运费"
if fee_name in {"费用"}:
fee_name = "海运费"
return {
fee_name = (named.group(1) if named else "") or default_fee
if fee_name == "费用":
# 句里只有「费用」没有运输方式前缀时,跟本单默认运费。
fee_name = default_fee
elif fee_name == "燃油附加费":
# 「燃油附加费率」误抽成费名时:陆运/空运用本单默认;海运旧行为落陆运费,避免当海运费金额。
fee_name = default_fee if default_fee != "海运费" else "陆运费"
out = {
"total": amount,
"currency": ccy,
"source_label": "产品报价",
@@ -932,3 +1092,116 @@ def extract_product_quote(text: str, *, injected: Optional[dict[str, Any]] = Non
"fee_rows": [{"name": fee_name, "amount": amount, "currency": ccy}],
"fee_lines": [{"name": fee_name, "amount": amount, "currency": ccy}],
}
out.update(_extract_rate_fields(raw))
return out
def _format_percent_rate(raw: str) -> str:
"""费率展示统一带 %;已有 % 保留。"""
text = (raw or "").strip()
if not text:
return ""
if text.endswith("%"):
return text
return f"{text}%"
def _extract_rate_fields(text: str) -> dict[str, str]:
"""抽出燃油附加费率 / 税率;只返回出现过的键。"""
out: dict[str, str] = {}
fuel = _RE_FUEL_SURCHARGE_RATE.search(text or "")
if fuel:
out["fuel_surcharge_rate"] = _format_percent_rate(fuel.group("rate") or "")
out["fuelSurchargeRate"] = out["fuel_surcharge_rate"]
tax = _RE_TAX_RATE.search(text or "")
if tax:
out["tax_rate"] = _format_percent_rate(tax.group("rate") or "")
out["taxRate"] = out["tax_rate"]
return out
def _strip_rate_and_band_noise(text: str) -> str:
"""去掉分档价与费率短语,避免后续费用行/金额回退误伤。"""
cleaned = _ascii_amount(text or "")
cleaned = _RE_WEIGHT_BAND_PRICE.sub(" ", cleaned)
cleaned = _RE_WEIGHT_BAND_OPEN.sub(" ", cleaned)
cleaned = _RE_FUEL_SURCHARGE_RATE.sub(" ", cleaned)
cleaned = _RE_TAX_RATE.sub(" ", cleaned)
return cleaned
def _parse_weight_band_quote(text: str, baseline_currency: str = "") -> dict[str, Any]:
"""
陆运集拼分档单价:2-500KG 单价CNY990 + 可选燃油附加费率/税率。
产出 weightPrices,供主账出单按「2-500KG」表头对档;费率进顶层字段填 Excel。
无币种时优先继承 baseline,再退回 CNY(集拼常见人民币报价)。
"""
raw = _ascii_amount(text or "")
base_ccy = str(baseline_currency or "").strip().upper()
tiers: list[dict[str, Any]] = []
rows: list[dict[str, str]] = []
ccy = ""
for hit in _RE_WEIGHT_BAND_PRICE.finditer(raw):
lo = int(hit.group("min") or 0)
hi = int(hit.group("max") or 0)
price = _ascii_amount(hit.group("price") or "")
if not price:
continue
line_ccy = _currency_of(raw, hit.group("ccy") or base_ccy) or base_ccy
ccy = ccy or line_ccy
label = f"{lo}-{hi}KG"
tiers.append({"min": lo, "max": hi, "price": price})
rows.append(
{
"name": label,
"amount": price,
"currency": line_ccy,
"unit_price": price,
}
)
for hit in _RE_WEIGHT_BAND_OPEN.finditer(raw):
lo = int(hit.group("min") or 0)
price = _ascii_amount(hit.group("price") or "")
if not price:
continue
line_ccy = _currency_of(raw, hit.group("ccy") or base_ccy) or base_ccy
ccy = ccy or line_ccy
label = f"{lo}KG以上"
tiers.append({"min": lo, "max": None, "price": price})
rows.append(
{
"name": label,
"amount": price,
"currency": line_ccy,
"unit_price": price,
}
)
if not tiers:
return {}
rates = _extract_rate_fields(raw)
# 费率行进明细方便群摘要展示;金额带 %,合计时只加数字价。
if rates.get("fuel_surcharge_rate"):
rows.append(
{
"name": "燃油附加费率",
"amount": rates["fuel_surcharge_rate"],
"currency": "",
}
)
if rates.get("tax_rate"):
rows.append({"name": "税率", "amount": rates["tax_rate"], "currency": ""})
# 分档是单价,不能把多档相加冒充费用合计。
out: dict[str, Any] = {
"total": tiers[0]["price"],
"currency": ccy or base_ccy or "CNY",
"source_label": "产品报价",
"raw_text": (text or "").strip(),
"fee_rows": rows,
"fee_lines": list(rows),
"weightPrices": tiers,
"price_per_kg": tiers[0]["price"],
}
out.update(rates)
return out
@@ -35,6 +35,7 @@ _FIELD_KEYS = (
"车型数量",
"通关口岸",
"贸易条款",
"提货地址",
)
@@ -134,6 +135,8 @@ def build_extract_messages(text: str) -> list[dict[str, str]]:
"陆运「通关口岸:皇岗」「通关口岸皇岗」「过皇岗」有说就写入通关口岸,没说留空,禁止编造口岸。"
"原话单独出现 DAP、DDP、CIF、CIP、FOB、EXW 时写入贸易条款;没出现留空,禁止编造。"
"「从南京飞吉隆坡」起运港=南京、目的港=吉隆坡;「北京飞吉隆坡」起运港=北京。"
"「货交上海」「货交:上海」「货交到上海」是提货地址=上海,不是起运港。"
"没有另写起运地、三字码航线或「从哪飞/到」时,起运港必须空串。"
"原话是机场三字码或航线就原样记,禁止翻译成城市名:"
"SZX-CGK / SZX/CGK / SZX到CGK → 起运港=SZX、目的港=CGK,不要写成深圳、雅加达。"
"换城市必须覆盖旧值,不要沿用上一句的港口。"
+177 -23
View File
@@ -3,7 +3,8 @@
本文件职责:群里副作用(主账 + BOT 回话)。海运应用群仍走 sea_group_ops。
禁止:自动建群/拉人/解散;拿当前工单去猜锁舱工单号。
锁舱按 TMS /air/cabin/lock 拼字段出站;没有 TMS 报价编号也要锁,用工单字段补 quoteId/optionNo。
锁舱按 TMS /air/cabin/lock 拼字段出站;没有 TMS 报价编号也可走 MANUAL。
禁止编造 optionNo;缺舱位编号/航司/计费重时先群里补问,禁止空壳打 TMS。
"""
from __future__ import annotations
@@ -628,12 +629,19 @@ def apply_air_quote(
fields = extract_air_collab_fields(text)
if fields:
flow.ledger.patch_collab_facts(work_order_no=no, facts=fields, sender_id=sender_id)
quote = injected_quote or extract_product_quote(text) or {}
view = ticket_view(ticket)
current = dict(view.get("quote") or {})
from agent.policy.sea_group_ops import _quote_currency_hint
quote = injected_quote or extract_product_quote(
text,
business_line="AIR",
transport_mode="空运",
baseline_currency=_quote_currency_hint(current),
) or {}
if not quote:
send_group_text(client, chat_id, copy.air_quote_not_recognized())
return "quote_empty"
view = ticket_view(ticket)
current = dict(view.get("quote") or {})
if _has_tms_quote(current) and not _is_product_quote(current):
_park_air_pending(flow, no, quote, sender_id)
send_group_text(client, chat_id, copy.group_ask_tms_or_product())
@@ -802,22 +810,46 @@ def apply_air_deal(
if stopped:
return stopped
from agent.policy.deal_outcome import finish_deal_outcome, harvest_inline_lost_reason
from agent.policy.sea_group_ops import facts_of_group
from agent.policy.sea_group_ops import _quote_fee_rows, facts_of_group
view = ticket_view(ticket)
no = ticket_no(ticket)
quote = dict(view.get("quote") or {})
status_now = ticket_status(ticket)
usable_total = str(quote.get("total") or "").strip()
if usable_total in {"", "-"}:
usable_total = ""
# 与海运一致:询价中且无报价时先说清原因,禁止笼统「主账状态更新失败」。
if not (usable_total or _quote_fee_rows(quote) or status_now in {"已报价", "协商中"}):
send_group_text(
group_client_of(flow), chat_id, copy.deal_fail_no_quote(work_order_no=no)
)
return "deal_need_quote"
inline = harvest_inline_lost_reason(text) if outcome == "未成交" else ""
result = finish_deal_outcome(
ledger=flow.ledger,
work_order_no=ticket_no(ticket),
work_order_no=no,
outcome=outcome,
facts=facts_of_group(view),
quote=dict(view.get("quote") or {}),
quote=quote,
business_line="AIR",
sales_name=str(view.get("sales_name") or ""),
lost_reason=inline,
)
if not result.get("ok"):
send_group_text(group_client_of(flow), chat_id, "主账状态更新失败,成交结果未入账。")
# 迁态失败且仍无报价时,同样用「没有报价」说明,避免旧笼统句。
err = str(result.get("error") or "")
still_no_quote = not (
usable_total or _quote_fee_rows(quote) or status_now in {"已报价", "协商中"}
)
if still_no_quote or "询价中" in err:
send_group_text(
group_client_of(flow), chat_id, copy.deal_fail_no_quote(work_order_no=no)
)
else:
send_group_text(
group_client_of(flow), chat_id, "主账状态更新失败,成交结果未入账。"
)
return "ledger_fail"
phase = str(result.get("phase") or "done")
ack_reason = inline if phase == "done" and outcome == "未成交" else ""
@@ -826,7 +858,7 @@ def apply_air_deal(
chat_id,
copy.deal_ack(
outcome,
ticket_no(ticket),
no,
str(result.get("next_followup_at") or ""),
lost_reason=ack_reason,
),
@@ -1006,7 +1038,6 @@ def apply_air_lock(
emit_group_deal(flow=flow, ticket=view, quote=dict(view.get("quote") or {}))
return "lock_ok"
def _release_should_push_deal(ticket: object) -> bool:
"""
放舱成功后要不要再推成交跟进。
@@ -1044,7 +1075,7 @@ def apply_air_release(
send_group_text(
group_client_of(flow),
chat_id,
copy.air_release_fail(work_order_no=no, operator=name, reason="主账未开放释放"),
copy.air_release_fail(work_order_no=no, operator=name, reason="主账未开放取消舱位"),
)
return "release_unavailable"
from agent.policy.system_exception import (
@@ -1080,7 +1111,7 @@ def apply_air_release(
event=SystemExceptionEvent(
exception_type=TYPE_TMS,
step=STEP_TMS_RELEASE,
reason="空运释放舱位接口调用失败",
reason="空运取消舱位接口调用失败",
service="空运舱位",
error_code=why or "RELEASE_FAIL",
work_order_no=no,
@@ -1537,17 +1568,6 @@ def _labels_from_incomplete_reason(reason: str) -> list[str]:
return found or ["舱位编号", "航司", "航班号"]
def _quote_ready_for_lock(quote: dict[str, Any]) -> bool:
"""有总价、费用或报价编号才值得让航线补舱位。完全没报价仍走「还没有报价」。"""
if str(quote.get("total") or "").strip() not in {"", "-"}:
return True
if quote.get("fee_lines") or quote.get("feeItems") or quote.get("departureCharges"):
return True
if _air_options(quote):
return True
return bool(str(quote.get("quoteId") or quote.get("quote_id") or "").strip())
def _remember_partial_lock(
flow: Any,
*,
@@ -1577,6 +1597,140 @@ def _quote_id(quote: dict[str, Any]) -> str:
return str(quote.get("quoteId") or quote.get("quote_id") or "").strip()
def _quote_ready_for_lock(quote: dict[str, Any]) -> bool:
"""
有没有可锁的报价:真实 TMS 编号,或人工总价/费用明细。
与内存账本口径一致,禁止把空报价当成「缺舱位」去补问。
"""
src = dict(quote or {})
label = str(src.get("source_label") or src.get("sourceLabel") or "")
if "确认" in label and "TMS" in label.upper():
qid = str(src.get("quoteId") or "").strip()
return bool(qid) and not qid.upper().startswith("QT-")
if str(src.get("total") or "").strip() not in {"", "-"}:
return True
if src.get("fee_rows") or src.get("fee_lines") or src.get("feeItems") or src.get("departureCharges"):
return True
if _air_options(src):
return True
qid = str(src.get("quoteId") or src.get("quote_id") or "").strip()
return bool(qid) and not qid.upper().startswith("QT-WO")
def _picked_option(
options: list[dict[str, Any]], option_no: str
) -> dict[str, Any]:
"""按 optionNo 取舱位;对不上返回空 dict。"""
want = (option_no or "").strip().upper()
if not want:
return {}
for row in options:
no = str(row.get("optionNo") or row.get("option_no") or "").strip().upper()
if no == want:
return row
return {}
def _airline_from_quote_or_option(
quote: dict[str, Any],
options: list[dict[str, Any]],
option_no: str,
) -> str:
"""
锁舱航司:舱位 airlineCode > 报价顶层 > 航班号前两位。
只回两位大写字母;猜不到就空,交给群里补问。
"""
opt = _picked_option(options, option_no)
raw = str(
opt.get("airlineCode")
or opt.get("airline")
or quote.get("airlineCode")
or quote.get("airline")
or ""
).strip().upper()
if len(raw) >= 2 and raw[:2].isalpha():
return raw[:2]
flight = str(
opt.get("flightNo") or opt.get("flight_no") or quote.get("flightNo") or ""
).strip().upper()
if len(flight) >= 2 and flight[0].isalpha() and flight[1].isalpha():
return flight[:2]
name = str(opt.get("airlineName") or quote.get("airlineName") or "").strip()
# 名称里不硬猜二字码,避免「南航」编成乱码。
_ = name
return ""
def _flight_no_from_quote_or_option(
quote: dict[str, Any],
options: list[dict[str, Any]],
option_no: str,
instruction: str = "",
) -> str:
"""航班号:舱位/报价字段,或句中「航班CZ327」「CZ327」形态。"""
import re
opt = _picked_option(options, option_no)
raw = str(opt.get("flightNo") or opt.get("flight_no") or quote.get("flightNo") or "").strip()
if raw:
return raw.upper()
blob = (instruction or "").upper()
m = re.search(r"(?:航班|FLIGHT)\s*([A-Z0-9]{2,8})", blob)
if m:
return m.group(1)
m = re.search(r"\b([A-Z]{2}\d{2,4})\b", blob)
if m:
return m.group(1)
return ""
def _chargeable_weight_kg(
quote: dict[str, Any],
options: list[dict[str, Any]],
option_no: str,
ticket: object,
) -> str:
"""
计费重:舱位 > 报价 > 工单事实「计费重」> 毛重。
有正数才返回;否则空串,门禁会补问。
"""
opt = _picked_option(options, option_no)
candidates = [
opt.get("chargeableWeightKg") or opt.get("chargeable_weight_kg"),
quote.get("chargeableWeightKg") or quote.get("chargeable_weight_kg"),
]
view = ticket_view(ticket)
facts = dict(view.get("facts") or {})
candidates.extend(
[
facts.get("计费重"),
facts.get("计费重量"),
view.get("chargeableWeightKg"),
facts.get("毛重"),
view.get("weightKg") or view.get("weight_kg"),
]
)
for raw in candidates:
text = str(raw or "").strip().replace(",", "")
if not text or text in {"-", "null", "None"}:
continue
# 去掉「公斤」「KGS」等后缀,只留数字。
num = ""
for ch in text:
if ch.isdigit() or ch == ".":
num += ch
elif num:
break
if not num:
continue
try:
if float(num) > 0:
return num
except ValueError:
continue
return ""
def _air_options(quote: dict[str, Any]) -> list[dict[str, Any]]:
raw = quote.get("airOptions") or quote.get("air_options")
if isinstance(raw, str) and raw.strip().startswith("["):
+25 -2
View File
@@ -1809,8 +1809,12 @@ class AirTextInquiryFlow:
extra,
)
from agent.redis_coord.quote_file import mark_quote_file_ready
from agent.policy.deal_outcome import ensure_ticket_quoted
mark_quote_file_ready(sess.work_order_no)
# 文件已出就必须让主账离开「询价中」,否则成交三态会被六态拒绝。
ensure_ticket_quoted(self._ledger, work_order_no=sess.work_order_no)
sess.status = sess.status or "已报价"
sess.phase = "wait_deal"
sess.allowed = (copy.BTN_DEAL, copy.BTN_LOST, copy.BTN_NEGOTIATE)
sess.wait_version += 1
@@ -1955,20 +1959,37 @@ class AirTextInquiryFlow:
"""点成交/未成交/协商中:先整卡置灰,再入主账。未成交同一句带原因则一次记完。"""
self._grey_clicked_card(reply, card_meta, replace_name=status)
from agent.policy.deal_outcome import finish_deal_outcome, harvest_inline_lost_reason
from agent.policy.sea_group_ops import _quote_fee_rows
quote = dict(sess.quote or {})
status_now = str(sess.status or "").strip()
usable_total = str(quote.get("total") or "").strip()
if usable_total in {"", "-"}:
usable_total = ""
if not (
usable_total
or _quote_fee_rows(quote)
or status_now in {"已报价", "协商中"}
):
reply(copy.deal_fail_no_quote(work_order_no=sess.work_order_no))
return "deal_need_quote"
inline = harvest_inline_lost_reason(source_text) if status == "未成交" else ""
result = finish_deal_outcome(
ledger=self._ledger,
work_order_no=sess.work_order_no,
outcome=status,
facts=sess.facts,
quote=sess.quote,
quote=quote,
business_line=sess.business_line,
sales_name=sess.invited_sales_name,
lost_reason=inline,
)
if not result.get("ok"):
reply("主账状态更新失败,成交结果未入账。")
err = str(result.get("error") or "")
if (not usable_total and not _quote_fee_rows(quote)) or "询价中" in err:
reply(copy.deal_fail_no_quote(work_order_no=sess.work_order_no))
else:
reply("主账状态更新失败,成交结果未入账。")
return "ledger_fail"
phase = str(result.get("phase") or "done")
sess.status = status
@@ -2024,8 +2045,10 @@ class AirTextInquiryFlow:
if not no:
return
from agent.redis_coord.quote_file import mark_quote_file_ready
from agent.policy.deal_outcome import ensure_ticket_quoted
mark_quote_file_ready(no)
ensure_ticket_quoted(self._ledger, work_order_no=no)
if not sender_id:
return
with self._lock:
+78 -1
View File
@@ -210,7 +210,11 @@ def finish_deal_outcome(
writer = getattr(ledger, "transition", None)
if not callable(writer):
return {"ok": False, "error": "no_transition", "phase": "ledger_fail"}
result = writer(work_order_no=no, to_status=status, **extra) or {}
# 报价文件已出、会话已进入成交跟进,但主账仍停在「询价中」时,
# 直接迁「未成交/已成交/协商中」会被六态拒绝。先补「已报价」再迁目标态。
result = _transition_deal_status(
writer, work_order_no=no, to_status=status, extra=extra, ledger=ledger
)
if not result.get("ok"):
return {"ok": False, "error": result.get("error") or "transition_failed", "phase": "ledger_fail"}
from agent.policy.event_exception import WAIT_LOST_REASON, clear_wait, start_wait
@@ -241,6 +245,79 @@ def finish_deal_outcome(
}
def _transition_deal_status(
writer: Callable[..., dict[str, Any]],
*,
work_order_no: str,
to_status: str,
extra: dict[str, Any],
ledger: Any = None,
) -> dict[str, Any]:
"""
写入成交三态。若主账仍停在询价中,先迁已报价再迁目标态。
运行证据:
- WO022/WO023:文件已发仍停询价中,直迁未成交被六态拒绝;
- HTTP 500 时 http_ledger 常只回 http_500(正文里的「询价中」丢失),
不能只靠错误文案判断,要以工单当前状态为准。
"""
no = (work_order_no or "").strip()
status = (to_status or "").strip()
result = writer(work_order_no=no, to_status=status, **extra) or {}
if result.get("ok"):
return result
if status not in {"已成交", "未成交", "协商中"}:
return result
err = str(result.get("error") or result.get("message") or "")
cur = ""
getter = getattr(ledger, "get_for_agent", None) if ledger is not None else None
if callable(getter):
try:
snap = getter(work_order_no=no, sender_id="") or {}
cur = str(snap.get("status") or "").strip()
except Exception:
cur = ""
# 状态确认询价中,或错误文案带询价中,或仅有 http_5xx 时仍尝试补已报价。
should_promote = (
cur == "询价中"
or "询价中" in err
or err.startswith("http_5")
or err in {"transition_failed", "ledger_error"}
)
if not should_promote:
return result
promoted = writer(
work_order_no=no,
to_status="已报价",
remark="成交跟进前补已报价",
) or {}
if not promoted.get("ok"):
return result
return writer(work_order_no=no, to_status=status, **extra) or {}
def ensure_ticket_quoted(ledger: Any, *, work_order_no: str) -> dict[str, Any]:
"""
报价文件发出 / 进入成交跟进时,保证主账至少是「已报价」。
幂等:已离开「询价中」则不再迁态(已报价→已报价会被六态拒绝)。
"""
no = (work_order_no or "").strip()
writer = getattr(ledger, "transition", None)
if not no or not callable(writer):
return {"ok": False, "error": "no_transition"}
getter = getattr(ledger, "get_for_agent", None)
if callable(getter):
try:
snap = getter(work_order_no=no, sender_id="") or {}
except Exception:
snap = {}
st = str(snap.get("status") or "").strip()
if st and st != "询价中":
return {"ok": True, "status": st, "skipped": True}
return writer(work_order_no=no, to_status="已报价", remark="报价文件已出") or {}
def capture_lost_reason(*, ledger: Any, work_order_no: str, reason: str) -> dict[str, Any]:
"""把销售下一句写进未成交原因。@询价小助手 不是原因。"""
text = strip_bot_mentions(reason or "")
+164 -24
View File
@@ -39,6 +39,24 @@ def _r(code: str, default: str, **kwargs: Any) -> str:
return render(code, default, **kwargs)
def _cabin_copy(code: str, default: str, **kwargs: Any) -> str:
"""
舱位话术。库里旧句仍写「释放」时,新发出的改用当前默认句。
先把填进去的原因、工单号抠掉再看骨架,避免 TMS 原文里的「释放」把新句子打回去。
已经发出的历史消息不在这里改。
"""
text = _r(code, default, **kwargs)
skeleton = text
for value in kwargs.values():
token = str(value or "")
if token:
skeleton = skeleton.replace(token, "")
if "释放" in skeleton:
return default
return text
# 空运补问:必填 7 项 + 非必填。报价日期默认当天,不进待补充。
_AIR_EXAMPLES = {
"起运港": "南京",
@@ -314,7 +332,7 @@ _LAND_EXAMPLES = {
"体积": "100CBM",
"毛重": "50kg",
"车型/数量": "9米6/1",
"通关口岸": "皇岗",
"通关口岸": "友谊关",
"运输类型": "国内运输拼车",
"线路类别": "国内长途/零担",
"运输分类": "急件",
@@ -1023,7 +1041,12 @@ def quote_fee_lines(quote: dict[str, Any] | None) -> list[tuple[str, str]]:
amount = str(item.get("amount") or item.get("value") or "").strip()
line_ccy = str(item.get("currency") or item.get("currencyCode") or header_ccy).strip()
if name and amount and amount != "-":
lines.append((name, money_text(amount, line_ccy)))
# 燃油附加费率 / 税率是百分比,禁止套成「CNY 1%」。
if "%" in amount or name.endswith("费率") or name in {"税率", "燃油附加费率"}:
shown = amount if "%" in amount else f"{amount}%"
lines.append((name, shown))
else:
lines.append((name, money_text(amount, line_ccy)))
if lines:
return lines
freight = str(src.get("freight") or "").strip()
@@ -1219,10 +1242,21 @@ def sea_quote_detail_text(
def collab_hint(work_order_no: str) -> str:
"""空运价格卡协同说明:请把相关方拉进原有协同群,并 @ 询价小助手。紧挨生成报价单按钮上方。"""
return (
f"请手动将相关方拉到空运原有协同群,并在空运协同群中发送"
f"“ {work_order_no}@询价小助手”,谢谢。"
"""
空运价格卡协同说明:紧挨「不需要协同,直接生成报价单」上方。
后台 inquiring.air_collab_hint;库内模板可用 {{ticket_no}}。
无后台模板时用本默认句(已带工单号)。销售侧示例:
…发送“ WO202610060030@询价小助手”,谢谢。
"""
no = (work_order_no or "").strip()
return _r(
"inquiring.air_collab_hint",
(
f"若需要咨询内部航线人员,请手动将相关方拉到空运原有协同群,"
f"并在空运协同群中发送“ {no}@询价小助手”,谢谢。"
),
ticket_no=no,
)
@@ -2590,6 +2624,20 @@ def group_tms_confirm_hint(*, business_line: str = "") -> str:
return f"请{who}回复“确认报价”确定采用TMS报价。\n{_GROUP_QUOTE_TAIL}"
def multi_group_field_hint(*, includes_air: bool) -> str:
"""
多段群里每次带出各段询价字段时,贴在最后一行字段下面。
任一段是空运,喊航线或产品;没有空运只喊产品。成交跟进不走这里。
注里说的是附件报价单只存档,不改报价写入规则。
"""
who = "航线或产品人员" if includes_air else "产品人员"
return (
f"{who}可通过“纯文字”告知新报价,或直接将新报价excel表发给智能体。\n"
"(注:附件报价单仅作为文件存储于后台,智能体不读取且不将报价内容写进系统)"
)
def group_no_tms_quote_hint(*, business_line: str = "") -> str:
"""
TMS 无价时写在「暂无匹配」下方:谁可以用文字或 Excel 另报。
@@ -2667,8 +2715,24 @@ def group_deal_stale(*, work_order_no: str) -> str:
return f"这张成交确认已过期。工单{no}已有更新的报价,请点击群里最新一条成交跟进。"
def group_deal_need_quote() -> str:
return "还没有可确认的报价,请先完成报价再确认成交状态。"
def group_deal_need_quote(*, work_order_no: str = "") -> str:
"""
群里确认成交/未成交时,主账还没有可确认报价。
空运 WO027:询价中且无 inq_quote,旧句「主账状态更新失败」不说明原因。
"""
no = (work_order_no or "").strip()
if no:
return (
f"工单{no}状态更新失败,原因:没有报价。\n"
f"请先报价,然后再更新工单状态。"
)
return "工单状态更新失败,原因:没有报价。\n请先报价,然后再更新工单状态。"
def deal_fail_no_quote(*, work_order_no: str = "") -> str:
"""成交三态写入失败且判定为没有报价时的销售可见说明。与群门禁同句。"""
return group_deal_need_quote(work_order_no=work_order_no)
def group_deal_sales_only() -> str:
@@ -2847,9 +2911,9 @@ def air_need_work_order() -> str:
def air_lock_need_work_order() -> str:
"""锁舱/释放必须自带工单号。后台 inquiring.air_lock_need_wo。"""
return _r(
return _cabin_copy(
"inquiring.air_lock_need_wo",
"锁舱或释放舱位请带上工单号,例如 WO202609160001锁舱。",
"锁舱或取消舱位请带上工单号,例如 WO202609160001取消舱位。",
)
@@ -3009,9 +3073,9 @@ def air_airline_only_quote() -> str:
def air_airline_only_cabin() -> str:
"""只有航线能锁舱或释放。后台 inquiring.air_airline_only_cabin。"""
return _r(
return _cabin_copy(
"inquiring.air_airline_only_cabin",
"只有岗位为「航线·空运」的人能锁舱或释放舱位。",
"只有岗位为「航线·空运」的人能锁舱或取消舱位。",
)
@@ -3074,6 +3138,53 @@ def air_ask_lock_option(options: list) -> str:
return "\n".join(lines)
def air_ask_manual_lock_fields(
*,
need_option: bool = False,
need_airline: bool = False,
need_chargeable: bool = False,
need_flight: bool = False,
options: list | None = None,
) -> str:
"""
手动报价锁舱缺 TMS MANUAL 必填项时,群里补问,禁止空壳出站。
例:请回复「AIR-OPT01 CZ 航班CZ327」。
"""
bits: list[str] = []
if need_option:
bits.append("舱位编号(如 AIR-OPT01)")
if need_airline:
bits.append("航司两位码(如 CZ)")
if need_flight:
bits.append("航班号(如 CZ327)")
if need_chargeable:
bits.append("计费重(公斤)")
need = "、".join(bits) if bits else "舱位编号、航司和航班号"
lines = [
f"锁舱还缺:{need}。",
"请按「AIR-OPT01 CZ 航班CZ327」回复;",
]
if need_chargeable:
lines.append("若还缺计费重,请再写「计费重xx公斤」。")
else:
lines.append("例如:AIR-OPT01 CZ 航班CZ327")
opts = options or []
shown = False
for item in opts:
if not isinstance(item, dict):
continue
no = str(item.get("optionNo") or item.get("option_no") or "").strip()
airline = str(item.get("airlineCode") or item.get("airlineName") or "").strip()
if not no:
continue
if not shown:
lines.append("可选舱位:")
shown = True
lines.append(f"{no} {airline}".strip() if airline else no)
return "\n".join(lines)
def air_lock_ok(
*,
work_order_no: str,
@@ -3128,7 +3239,7 @@ def multi_air_lock_unsupported(*, work_order_no: str, operator: str) -> str:
def air_lock_fail(*, work_order_no: str, operator: str, reason: str) -> str:
"""空运锁舱失败。后台 inquiring.air_lock_fail。"""
"""空运锁舱失败(接口/系统类)。后台 inquiring.air_lock_fail。"""
why = (reason or "").strip() or "TMS未返回原因"
default = (
f"工单{work_order_no} 空运锁舱失败。\n"
@@ -3145,6 +3256,25 @@ def air_lock_fail(*, work_order_no: str, operator: str, reason: str) -> str:
)
def air_lock_incomplete(*, work_order_no: str, operator: str, reason: str = "") -> str:
"""
锁舱参数不齐(纯手工价、运价库无舱位等):业务补问,不算系统异常,不惊动 IT。
航线按示例回舱位+航司+航班后即可再锁。
"""
why = (reason or "").strip()
lines = [
f"工单{work_order_no} 还不能锁舱。",
f"操作人:{operator}",
]
if why:
lines.append(f"原因:{why}")
else:
lines.append("原因:本单没有可引用的 TMS 舱位(手工价或运价库无匹配)。")
lines.append("请直接回复「AIR-OPT01 CZ 航班CZ327」(换成实际舱位、航司、航班号)后再锁。")
return "\n".join(lines)
def air_cabin_fail_reason(*, tms_reason: str = "", flight_date: str = "", today: str = "") -> str:
"""
锁舱/释放失败原因:原样回 TMS 的 failReason。
@@ -3166,13 +3296,13 @@ def air_release_ok(
) -> str:
"""空运释放成功。后台 inquiring.air_release_ok。"""
default = (
f"工单{work_order_no} 已通知TMS执行空运释放舱位成功\n"
f"工单{work_order_no} 已通知TMS执行空运取消舱位成功\n"
f"操作人:{operator}\n"
f"舱位选项:{option_no}\n"
f"执行编号:{exec_no}\n"
f"报价编号:{quote_no}"
)
return _r(
return _cabin_copy(
"inquiring.air_release_ok",
default,
ticket_no=work_order_no,
@@ -3187,12 +3317,12 @@ def air_release_fail(*, work_order_no: str, operator: str, reason: str) -> str:
"""空运释放失败。后台 inquiring.air_release_fail。"""
why = (reason or "").strip() or "TMS未返回原因"
default = (
f"工单{work_order_no} 空运释放舱位失败。\n"
f"工单{work_order_no} 空运取消舱位失败。\n"
f"操作人:{operator}\n"
f"释放舱位失败的原因:{why}\n"
f"取消舱位失败的原因:{why}\n"
"已通知IT运维排查,请稍等。"
)
return _r(
return _cabin_copy(
"inquiring.air_release_fail",
default,
ticket_no=work_order_no,
@@ -3204,9 +3334,9 @@ def air_release_fail(*, work_order_no: str, operator: str, reason: str) -> str:
def air_release_deal_blocked(work_order_no: str) -> str:
"""已成交不能释放舱位。后台 inquiring.air_release_deal_blocked。"""
no = (work_order_no or "").strip()
return _r(
return _cabin_copy(
"inquiring.air_release_deal_blocked",
f"释放舱位失败,工单{no}已成交。",
f"取消舱位失败,工单{no}已成交。",
ticket_no=no,
)
@@ -3214,9 +3344,9 @@ def air_release_deal_blocked(work_order_no: str) -> str:
def air_release_need_lock(work_order_no: str) -> str:
"""没有有效锁舱不能释放。后台 inquiring.air_release_need_lock。"""
no = (work_order_no or "").strip()
return _r(
return _cabin_copy(
"inquiring.air_release_need_lock",
f"工单{no}还没有有效锁舱,不能释放。",
f"工单{no}还没有有效锁舱,不能取消舱位。",
ticket_no=no,
)
@@ -3244,9 +3374,19 @@ SYS_EXC_RECOVERY_GROUP = "建群已恢复正常,感谢您的耐心等待。"
IMPACT_LLM_NO_TICKET = "尚未建单,不落后台工单"
IMPACT_LLM = "当前识别暂停,已有字段与工单状态保持不变"
IMPACT_TMS_QUOTE = "当前询价流程暂停,识别字段与原业务节点保持不变"
IMPACT_TMS_CABIN = "当前锁舱/释放暂停,工单状态保持不变"
IMPACT_TMS_CABIN = "当前锁舱/取消舱位暂停,工单状态保持不变"
IMPACT_TMS_LOCK = "锁舱失败,工单状态保持不变"
IMPACT_TMS_RELEASE = "释放舱位失败,工单状态保持不变"
IMPACT_TMS_RELEASE = "取消舱位失败,工单状态保持不变"
def air_release_ask() -> str:
"""航线说了和舱位有关的「释放」时先问,不直接取消。"""
return "是否需要取消舱位?"
def air_release_ask_dropped() -> str:
"""航线否认这次取消。不打 TMS。"""
return "已取消这次操作"
IMPACT_GROUP = "当前建群/加人暂停,已建群不新建第二个群"
+34 -4
View File
@@ -18,6 +18,7 @@ from agent.llm.extract_text import extract_collab_fields, extract_product_quote
from agent.policy import inquiry_copy as copy
from agent.policy.multi_segments import Segment, group_brief, includes_air, segments_from_payload
from agent.policy.sea_group_ops import (
_quote_currency_hint,
apply_group_deal,
group_client_of,
is_sales,
@@ -152,7 +153,22 @@ def handle_multi_inbound(
ticket = _reload(flow, no) or ticket
segments = load_segments(ticket)
target = next((seg for seg in segments if seg.mode == mode), target)
quote = extract_product_quote(text or "", injected=injected_quote)
# 段报价币种优先;否则用工单顶层 quote(产品未写币种时继承 TMS)
baseline = ""
if target is not None:
baseline = _quote_currency_hint((segment_quotes(ticket) or {}).get(target.mode) or {})
if not baseline:
baseline = _quote_currency_hint(dict(ticket_view(ticket).get("quote") or {}))
quote = extract_product_quote(
text or "",
injected=injected_quote,
business_line=str(mode or "").upper(),
transport_mode=(
"陆运" if str(mode or "").upper() == "LAND"
else ("空运" if str(mode or "").upper() == "AIR" else "海运")
),
baseline_currency=baseline,
)
if not quote:
if fields:
return "multi_collab_saved"
@@ -289,6 +305,15 @@ def _cabin(flow: Any, ticket: object, chat_id: str, sender_id: str, text: str, i
operator_name,
)
if intent == "ask":
if not is_airline(flow, sender_id):
send_group_text(group_client_of(flow), chat_id, copy.air_airline_only_cabin())
return "not_airline"
from agent.redis_coord.pending_cabin_cancel import save_pending_cabin_cancel
save_pending_cabin_cancel(chat_id, ticket_no(ticket))
send_group_text(group_client_of(flow), chat_id, copy.air_release_ask())
return "release_ask"
if intent == "release":
return apply_air_release(
flow=flow,
@@ -314,10 +339,15 @@ def _cabin(flow: Any, ticket: object, chat_id: str, sender_id: str, text: str, i
def _cabin_intent(text: str) -> str:
raw = text or ""
if "释放" in raw and "舱" in raw:
"""取消舱位马上办;和舱位有关的「释放」只提问。"""
from agent.routing.air_group_intent import cabin_release_kind
kind = cabin_release_kind(text or "")
if kind == "direct":
return "release"
if "锁舱" in raw:
if kind == "ask":
return "ask"
if "锁舱" in (text or ""):
return "lock"
return ""
@@ -385,6 +385,7 @@ def group_brief(
结构对齐私聊核对:@销售和各段产品,下一行直接接段1询价字段。
不写 TMS,不写协同段。工单号已在私聊提示过,群里不再重复一行。
每次拼这段字段都在底部加另报提示;成交跟进是另一条消息,不加。
"""
_ = work_order_no
names: list[str] = []
@@ -406,6 +407,8 @@ def group_brief(
body = _segment_inquiry_block(seg).strip()
if body:
lines.extend(body.splitlines())
# 紧挨最后一行字段,中间不空行。含空运与不含空运用不同开头。
lines.append(copy.multi_group_field_hint(includes_air=includes_air(segments)))
return "\n".join(lines)
+152 -5
View File
@@ -929,17 +929,28 @@ def apply_product_quote(
merged = dict(sess.collab_facts)
merged.update(fields)
sess.collab_facts = merged
quote = extract_product_quote(text, injected=injected_quote)
line = str(view.get("business_line") or view.get("businessLine") or "").strip().upper()
base = _current_quote(view, sess)
quote = extract_product_quote(
text,
injected=injected_quote,
business_line=line,
transport_mode="陆运" if line == "LAND" else ("海运" if line == "SEA" else ""),
baseline_currency=_quote_currency_hint(base),
)
if not quote:
logger.info("产品报价未识别 wo=%s text=%s", no, (text or "")[:200])
send_group_text(client, chat_id, copy.group_quote_not_recognized())
return "quote_not_recognized"
base = _current_quote(view, sess)
quote = _attach_land_weight_band_segment(quote, view)
if _has_tms_quote(base):
_park_pending_quote(no, quote, sess, flow)
send_group_text(client, chat_id, copy.group_ask_tms_or_product())
return "wait_tms_choice"
if _quote_fee_rows(base):
# 分档单价是完整人工价(含费率),禁止和旧错误行(如燃油附加费=2)相加。
# 旧错默认「海运费」的陆运产品价:重报时按本单默认运费对齐后再盖,避免海运费+陆运费并排。
if _quote_fee_rows(base) and not (quote.get("weightPrices") or []):
base = _align_wrong_default_freight(base, quote, business_line=line)
quote = merge_quote_fees(base, quote)
_save_product_quote(flow, no, quote, sess)
ticket2 = _reload(flow, chat_id, no) or ticket
@@ -1259,8 +1270,11 @@ def apply_group_deal(
return "not_sales"
quote = _current_quote(view, sess)
status_now = ticket_status(ticket) or (sess.status if sess else "")
if not (quote.get("total") or _quote_fee_rows(quote) or status_now in {"已报价", "协商中"}):
send_group_text(client, chat_id, copy.group_deal_need_quote())
usable_total = str(quote.get("total") or "").strip()
if usable_total in {"", "-"}:
usable_total = ""
if not (usable_total or _quote_fee_rows(quote) or status_now in {"已报价", "协商中"}):
send_group_text(client, chat_id, copy.group_deal_need_quote(work_order_no=no))
return "deal_need_quote"
from agent.policy.deal_outcome import finish_deal_outcome, harvest_inline_lost_reason
@@ -1392,6 +1406,53 @@ def _current_quote(view: dict[str, Any], sess: Any) -> dict[str, Any]:
return base
def _quote_currency_hint(quote: dict[str, Any] | None) -> str:
"""
当前报价币种提示:顶层 currency → 金额前缀 → 费用行/线路段。
产品改价未写币种时继承此值,禁止默认 USD(WO202610090107 中港 HKD)。
"""
src = dict(quote or {})
for key in ("currency", "currencyCode"):
code = str(src.get(key) or "").strip().upper()
if code:
return code
for key in ("cost", "total", "freight", "land_freight"):
raw = str(src.get(key) or "").strip().upper()
for prefix in ("HKD", "CNY", "USD", "EUR", "JPY", "GBP", "RMB"):
if raw.startswith(prefix):
return "CNY" if prefix == "RMB" else prefix
for row in _quote_fee_rows(src):
code = str(row.get("currency") or row.get("currencyCode") or "").strip().upper()
if code:
return code
for key in ("landSegments", "route_rows", "selected_land_route"):
raw = src.get(key)
if isinstance(raw, str) and raw.strip():
try:
import json
raw = json.loads(raw)
except Exception:
continue
if isinstance(raw, dict):
legs = raw.get("legs") if isinstance(raw.get("legs"), list) else [raw]
for leg in legs:
if not isinstance(leg, dict):
continue
code = str(leg.get("currency") or "").strip().upper()
if code:
return code
elif isinstance(raw, list):
for leg in raw:
if not isinstance(leg, dict):
continue
code = str(leg.get("currency") or "").strip().upper()
if code:
return code
return ""
def _has_tms_quote(quote: dict[str, Any] | None) -> bool:
"""当前价来自 TMS 才要问;产品价、销售调价不再替用户选。"""
src = dict(quote or {})
@@ -1622,6 +1683,45 @@ def _merged_total(
return str(src.get("total") or ""), header_ccy
def _align_wrong_default_freight(
base: dict[str, Any] | None,
overlay: dict[str, Any] | None,
*,
business_line: str = "",
) -> dict[str, Any]:
"""
陆运/空运旧产品价若误落成别的运输方式默认费名,重报前改成与新报价同名,便于按行盖价。
只动「海运费/陆运费/空运费/运输费」这类主运费默认名,不碰操作费等真实分项。
"""
src = dict(base or {})
line = (business_line or "").strip().upper()
want = {"LAND": "陆运费", "AIR": "空运费", "SEA": "海运费"}.get(line, "")
if not want:
return src
new_names = {
str(x.get("name") or "").strip()
for x in (overlay or {}).get("fee_rows") or (overlay or {}).get("fee_lines") or []
if isinstance(x, dict)
}
if want not in new_names:
return src
mains = {"海运费", "陆运费", "空运费", "运输费"}
rows = _quote_fee_rows(src)
changed = False
for row in rows:
name = str(row.get("name") or "").strip()
if name in mains and name != want:
row["name"] = want
changed = True
if not changed:
return src
out = dict(src)
out["fee_rows"] = rows
out["fee_lines"] = rows
return out
def merge_quote_fees(base: dict[str, Any] | None, overlay: dict[str, Any] | None) -> dict[str, Any]:
"""
产品按行改价盖到原 TMS 明细上。没点名的费用原样保留。
@@ -1666,6 +1766,53 @@ def merge_quote_fees(base: dict[str, Any] | None, overlay: dict[str, Any] | None
return stamp_prices_for_sheet(out)
def _attach_land_weight_band_segment(
quote: dict[str, Any], view: dict[str, Any]
) -> dict[str, Any]:
"""
陆运产品分档价:把 weightPrices / 燃油税率挂到 landSegments,出单才能填「2-500KG」列。
无分档价时原样返回。OD 取工单询价事实,不另猜城市。
"""
src = dict(quote or {})
tiers = src.get("weightPrices")
if not isinstance(tiers, list) or not tiers:
return src
facts = dict(view.get("facts") or {})
origin = str(
facts.get("始发地")
or facts.get("起运地")
or facts.get("origin")
or view.get("origin")
or ""
).strip()
dest = str(
facts.get("目的地")
or facts.get("destination")
or view.get("destination")
or ""
).strip()
seg: dict[str, Any] = {
"origin": origin,
"destination": dest,
"weightPrices": list(tiers),
"currency": str(src.get("currency") or "CNY"),
"salePrice": str(src.get("total") or tiers[0].get("price") or ""),
"price_per_kg": str(src.get("price_per_kg") or tiers[0].get("price") or ""),
}
fuel = str(src.get("fuel_surcharge_rate") or src.get("fuelSurchargeRate") or "").strip()
tax = str(src.get("tax_rate") or src.get("taxRate") or "").strip()
if fuel:
seg["fuel_surcharge_rate"] = fuel
seg["fuelSurchargeRate"] = fuel
if tax:
seg["tax_rate"] = tax
seg["taxRate"] = tax
src["landSegments"] = [seg]
src["route_rows"] = [seg]
return src
def _save_product_quote(
flow: Any,
no: str,
@@ -879,6 +879,7 @@ def _resume_cabin_step(
work_order_no=no,
lock_id=lock_id,
sender_id=sender,
operator_name=str(extra.get("operator_name") or "").strip(),
instruction_text=instruction,
)
or {}
@@ -887,17 +888,22 @@ def _resume_cabin_step(
is_ok=lambda x: bool((x or {}).get("ok")),
)
service = "空运舱位"
reason = "空运释放舱位接口调用失败"
reason = "空运取消舱位接口调用失败"
else:
# 与首次群锁舱对齐:重试必须带 operatorName / airline,否则 MANUAL 出站缺姓名。
locker = getattr(ledger, "lock_cabin", None)
op_name = str(extra.get("operator_name") or "").strip()
airline = str(extra.get("airline") or "").strip()
flight_no = str(extra.get("flight_no") or "").strip()
out = call_with_retries(
lambda: locker(
work_order_no=no,
option_no=option_no,
sender_id=sender,
operator_name=op_name,
instruction_text=instruction,
airline=str(extra.get("airline") or ""),
flight_no=str(extra.get("flight_no") or ""),
airline=airline,
flight_no=flight_no,
)
or {}
if callable(locker)
+2
View File
@@ -57,6 +57,8 @@ QUOTE_FILE_READY = "quote_file_ready"
PENDING_PRODUCT_QUOTE = "pending_product_quote"
# 陆运核对卡已出、等确定查价:短协调,不当六态、不当工单号
PENDING_LAND_CONFIRM = "pending_land_confirm"
# 空运群问过「是否需要取消舱位」:短协调,不当六态
PENDING_CABIN_CANCEL = "pending_cabin_cancel"
# 空运/海运/陆运当前书签:HTTP 与 Worker 共用,不当六态
FLOW_BOOKMARK = "flow_bookmark"
# 私聊图片波次:HTTP 与 Worker 必须共用,不当六态
@@ -0,0 +1,72 @@
"""
空运群取消舱位待确认。
航线说出和舱位有关的「释放」后先问一句,确认前不打 TMS。
短协调,不当六态、不当 checkpoint。按群记下工单号,双进程仍能读到。
两小时没人接话就过期,避免过后回一个「是」误取消。
"""
from __future__ import annotations
import json
import logging
from agent.redis_coord.keys import PENDING_CABIN_CANCEL
from agent.redis_coord.runtime import get_redis_runtime
logger = logging.getLogger(__name__)
# 问句只在这一阵有效。过期后「是」不再取消舱位。
_TTL_SECONDS = 2 * 60 * 60
def save_pending_cabin_cancel(chat_id: str, work_order_no: str) -> None:
"""记下本群正在等航线确认取消哪张单。"""
room = (chat_id or "").strip()
no = (work_order_no or "").strip()
if not room or not no:
return
payload = {"work_order_no": no}
try:
client = get_redis_runtime().client
client.raw.set(
client.key(PENDING_CABIN_CANCEL, room),
json.dumps(payload, ensure_ascii=False),
ex=_TTL_SECONDS,
)
logger.info("cabin.ask saved chat=%s wo=%s", room, no)
except Exception:
logger.exception("写取消舱位待确认失败 chat=%s", room)
def load_pending_cabin_cancel(chat_id: str) -> str:
"""本群正在等确认的工单号。没有则空串。"""
room = (chat_id or "").strip()
if not room:
return ""
try:
client = get_redis_runtime().client
raw = client.raw.get(client.key(PENDING_CABIN_CANCEL, room))
if not raw:
return ""
if isinstance(raw, bytes):
raw = raw.decode("utf-8")
data = json.loads(raw)
if not isinstance(data, dict):
return ""
return str(data.get("work_order_no") or "").strip()
except Exception:
logger.exception("读取消舱位待确认失败 chat=%s", room)
return ""
def clear_pending_cabin_cancel(chat_id: str) -> None:
"""确认、否认或改口办别的事时清掉。"""
room = (chat_id or "").strip()
if not room:
return
try:
client = get_redis_runtime().client
client.raw.delete(client.key(PENDING_CABIN_CANCEL, room))
except Exception:
logger.exception("清取消舱位待确认失败 chat=%s", room)
@@ -35,12 +35,15 @@ logger = logging.getLogger(__name__)
INTENT_ACTIVATE = "air_activate"
INTENT_LOCK = "air_lock"
INTENT_RELEASE = "air_release"
# 说出和舱位有关的「释放」:先问是否取消,不直接执行。
INTENT_RELEASE_ASK = "air_release_ask"
INTENT_PICK_OPTION = "air_pick_option"
_VALID = {
INTENT_ACTIVATE,
INTENT_LOCK,
INTENT_RELEASE,
INTENT_RELEASE_ASK,
INTENT_PICK_OPTION,
INTENT_FIELDS,
INTENT_QUOTE,
@@ -56,7 +59,10 @@ _VALID = {
# 相近说法回退,不是唯一口令。
_LOCK_HINTS = ("锁舱", "锁仓", "锁定舱位", "锁住舱位", "帮我锁舱")
_RELEASE_HINTS = ("释放舱位", "放舱", "解锁舱", "取消锁舱", "释放舱")
# 这四句马上取消舱位。「释放舱位」不在这里。
_RELEASE_DIRECT = ("取消舱位", "放舱", "解锁舱", "取消锁舱")
_CONFIRM_YES = ("是", "需要", "确认")
_CONFIRM_NO = ("不需要", "不用", "否")
def is_missed_air_bot_at(text: str, *, room_already_air: bool = False) -> bool:
@@ -154,20 +160,70 @@ def classify_air_group_text(
return INTENT_OTHER
def _compact_cabin_text(text: str) -> str:
"""去掉空白,方便认「取消舱位」「释放舱位」。"""
return (text or "").replace(" ", "").replace(" ", "")
def cabin_release_kind(text: str) -> str:
"""
舱位取消怎么认。
direct:马上执行。ask:先问「是否需要取消舱位」。
跟舱位有关的「释放」只问不办。没说舱位的「释放」不当取消。
"""
blob = _compact_cabin_text(text)
# 「释放舱位」里含着「放舱」,必须先认释放,避免被放舱直接取消。
if "释放" in blob and "舱" in blob:
return "ask"
if any(hint in blob for hint in _RELEASE_DIRECT):
return "direct"
return ""
def cabin_confirm_answer(text: str) -> str:
"""
问过之后这一句是确认、否认,还是别的业务。
只认整句(可带工单号和 @)。「不需要」不能被看成「需要」。
返回 yes / no / 空串。空串表示询问作废,调用方按原句继续办。
"""
raw = text or ""
no = copy.extract_work_order_no(raw)
rest = raw.replace(no, "").replace(no.lower(), "")
rest = rest.replace("@询价小助手", "").replace("询价小助手", "")
rest = "".join(ch for ch in rest if ch.isalnum() or "\u4e00" <= ch <= "\u9fff")
if rest in _CONFIRM_NO:
return "no"
if rest in _CONFIRM_YES or rest == "取消舱位":
return "yes"
return ""
def _hint_lock_or_release(text: str) -> str:
blob = (text or "").replace(" ", "").replace(" ", "")
if any(x in blob for x in _RELEASE_HINTS):
kind = cabin_release_kind(text)
if kind == "direct":
return INTENT_RELEASE
if kind == "ask":
return INTENT_RELEASE_ASK
blob = _compact_cabin_text(text)
if any(x in blob for x in _LOCK_HINTS):
return INTENT_LOCK
return ""
def _only_work_order(text: str) -> bool:
"""去掉工单号和 @询价小助手 后几乎没字,当作激活/切单。"""
"""
去掉工单号和 @询价小助手 后几乎没字,当作激活/切单。
销售常按话术复制「工单编号WO…@询价小助手」;残留「工单编号」不算业务意图。
运行证据:only_wo=false 后走 extract_product_quote→product_quote→航线岗拒绝。
"""
no = copy.extract_work_order_no(text)
rest = (text or "").replace(no, "").replace(no.lower(), "")
rest = rest.replace("@询价小助手", "").replace("询价小助手", "")
for noise in ("工单编号", "工单号", "编号"):
rest = rest.replace(noise, "")
rest = "".join(ch for ch in rest if ch.isalnum() or "\u4e00" <= ch <= "\u9fff")
return not rest.strip()
@@ -184,7 +240,8 @@ def _classify_with_model(text: str, settings) -> str:
client = LlmHttpClient.from_settings(settings)
system = (
"你是空运协同群意图分类。只回复一个英文词,不要解释。"
"air_lock=航线要锁舱;air_release=航线要释放舱位;"
"air_lock=航线要锁舱;air_release=航线要取消舱位(取消舱位、放舱、解锁舱、取消锁舱);"
"说出释放舱位、释放舱、把舱位释放了时不要回 air_release;"
"air_activate=只是指定/切换工单号;"
"air_pick_option=在补充或选择舱位编号、航司、航班号,写法不限;"
"collab_fields=在补是否含电/是否含磁;"
+110 -6
View File
@@ -20,6 +20,7 @@ from agent.policy import inquiry_copy as copy
from agent.routing.air_group_intent import (
INTENT_LOCK,
INTENT_RELEASE,
INTENT_RELEASE_ASK,
classify_air_group_text,
)
from agent.routing.dispatch import dispatch_inbound
@@ -201,7 +202,12 @@ class AirGroupCollabTests(unittest.TestCase):
def test_intent_lock_is_not_hardcoded(self) -> None:
self.assertEqual(classify_air_group_text("帮我锁舱 WO202609160001", allow_network=False), INTENT_LOCK)
self.assertEqual(classify_air_group_text("WO202609160001释放舱位", allow_network=False), INTENT_RELEASE)
self.assertEqual(classify_air_group_text("WO202609160001取消舱位", allow_network=False), INTENT_RELEASE)
self.assertEqual(classify_air_group_text("放舱", allow_network=False), INTENT_RELEASE)
self.assertEqual(classify_air_group_text("解锁舱", allow_network=False), INTENT_RELEASE)
self.assertEqual(classify_air_group_text("取消锁舱", allow_network=False), INTENT_RELEASE)
self.assertEqual(classify_air_group_text("WO202609160001释放舱位", allow_network=False), INTENT_RELEASE_ASK)
self.assertEqual(classify_air_group_text("把舱位释放了", allow_network=False), INTENT_RELEASE_ASK)
def test_airline_fee_wording_is_quote_not_adjust(self) -> None:
"""航线写「空运费改为900」是手工报价,不能先判成调价。比例和改总价仍是调价。"""
@@ -527,6 +533,21 @@ class AirGroupCollabTests(unittest.TestCase):
classify_air_group_text("@询价小助手 WO202609160002", allow_network=False),
INTENT_ACTIVATE,
)
# 话术前缀「工单编号」不能当成报价(WO026 复现:误走 product_quote)。
self.assertEqual(
classify_air_group_text(
"工单编号WO202610070026@询价小助手",
allow_network=False,
),
INTENT_ACTIVATE,
)
self.assertEqual(
classify_air_group_text(
"工单编号 WO202610060026@询价小助手",
allow_network=False,
),
INTENT_ACTIVATE,
)
from unittest.mock import patch
with patch(
@@ -540,6 +561,13 @@ class AirGroupCollabTests(unittest.TestCase):
),
INTENT_ACTIVATE,
)
self.assertEqual(
classify_air_group_text(
"工单编号WO202610070026@询价小助手",
allow_network=True,
),
INTENT_ACTIVATE,
)
def test_dispatch_aibot_goes_air(self) -> None:
from agent.routing.dispatch import dispatch_inbound as _disp
@@ -1051,7 +1079,8 @@ class AirGroupCollabTests(unittest.TestCase):
self.assertFalse(any("AIR-OPT-01" in t for t in self._texts()))
self.assertFalse(any("执行成功" in t for t in self._texts()))
def test_manual_quote_without_quote_id_can_lock(self) -> None:
def test_manual_quote_without_option_asks_fields(self) -> None:
"""纯人工价且口令无 AIR-OPT:交主账后仍缺 → lock_incomplete(不空壳成功)。"""
wo = self._create_air(
quote={
"total": "100",
@@ -1255,9 +1284,84 @@ class AirGroupCollabTests(unittest.TestCase):
)
self.assertEqual(phase, "release_ok")
added = "\n".join(self._texts()[before:])
self.assertIn("释放", added)
self.assertIn("取消舱位", added)
self.assertNotIn("请确认成交状态", added)
def test_release_wording_asks_before_cancel(self) -> None:
"""说出释放舱位只提问。销售回「是」不算,航线确认后才取消。"""
wo = self._create_air()
handle_air_group(
self._msg(sender="air1", text=f"{wo}锁舱", chat="wr_air_ask", mid="ask0"),
flow=self.flow,
ledger=self.ledger,
injected_intent="air_lock",
)
self.groups.sent.clear()
phase = handle_air_group(
self._msg(sender="air1", text=f"{wo}释放舱位", chat="wr_air_ask", mid="ask1"),
flow=self.flow,
ledger=self.ledger,
)
self.assertEqual(phase, "release_ask")
self.assertIn("是否需要取消舱位?", "\n".join(self._texts()))
self.assertNotIn("已通知TMS执行空运取消舱位成功", "\n".join(self._texts()))
phase = handle_air_group(
self._msg(sender="sales1", text="是", chat="wr_air_ask", mid="ask2"),
flow=self.flow,
ledger=self.ledger,
)
self.assertEqual(phase, "not_airline")
self.assertNotIn("已通知TMS执行空运取消舱位成功", "\n".join(self._texts()))
phase = handle_air_group(
self._msg(sender="air1", text="是", chat="wr_air_ask", mid="ask3"),
flow=self.flow,
ledger=self.ledger,
)
self.assertEqual(phase, "release_ok")
self.assertIn("已通知TMS执行空运取消舱位成功", "\n".join(self._texts()))
def test_release_wording_can_be_declined(self) -> None:
wo = self._create_air()
handle_air_group(
self._msg(sender="air1", text=f"{wo}锁舱", chat="wr_air_ask_no", mid="no0"),
flow=self.flow,
ledger=self.ledger,
injected_intent="air_lock",
)
self.groups.sent.clear()
handle_air_group(
self._msg(sender="air1", text=f"{wo}把舱位释放了", chat="wr_air_ask_no", mid="no1"),
flow=self.flow,
ledger=self.ledger,
)
phase = handle_air_group(
self._msg(sender="air1", text="不用", chat="wr_air_ask_no", mid="no2"),
flow=self.flow,
ledger=self.ledger,
)
self.assertEqual(phase, "release_ask_dropped")
self.assertIn("已取消这次操作", "\n".join(self._texts()))
self.assertNotIn("已通知TMS执行空运取消舱位成功", "\n".join(self._texts()))
def test_cancel_cabin_words_release_immediately(self) -> None:
wo = self._create_air()
handle_air_group(
self._msg(sender="air1", text=f"{wo}锁舱", chat="wr_air_now", mid="now0"),
flow=self.flow,
ledger=self.ledger,
injected_intent="air_lock",
)
self.groups.sent.clear()
phase = handle_air_group(
self._msg(sender="air1", text=f"{wo}取消舱位", chat="wr_air_now", mid="now1"),
flow=self.flow,
ledger=self.ledger,
)
self.assertEqual(phase, "release_ok")
joined = "\n".join(self._texts())
self.assertIn("已通知TMS执行空运取消舱位成功", joined)
self.assertNotIn("是否需要取消舱位?", joined)
def test_sales_cannot_lock(self) -> None:
wo = self._create_air()
phase = handle_air_group(
@@ -1688,7 +1792,7 @@ class AirGroupCollabTests(unittest.TestCase):
def test_lock_without_quote_still_shows_tms_reason(self) -> None:
"""TMS 拒绝锁舱时原样回失败原因,不要改写成选项不匹配。"""
wo = self._create_air(quote={}, status="询价中")
wo = self._create_air()
self.ledger._cabin_lock_result = {
"ok": False,
"error": "lock_fail",
@@ -1802,9 +1906,9 @@ class AirGroupCollabTests(unittest.TestCase):
)
self.assertEqual(phase, "system_exception")
joined = "\n".join(self._texts())
self.assertIn(f"工单{wo} 空运释放舱位失败。", joined)
self.assertIn(f"工单{wo} 空运取消舱位失败。", joined)
self.assertIn("操作人:HangXian", joined)
self.assertIn("释放舱位失败的原因:舱位不存在", joined)
self.assertIn("取消舱位失败的原因:舱位不存在", joined)
self.assertIn("已通知IT运维排查,请稍等。", joined)
self.assertNotIn("TMS接口异常,IT运维排查中", joined)
+45
View File
@@ -144,6 +144,51 @@ class TestDealOutcome(unittest.TestCase):
view = self.ledger.get_for_agent(work_order_no=self.wo, sender_id="sales1")
self.assertEqual(view.get("wait_phase"), "done")
def test_lost_from_inquiring_promotes_quoted_first(self) -> None:
"""主账仍询价中时点未成交:先补已报价再入未成交,禁止直接失败。"""
class _StrictSix:
def __init__(self) -> None:
self.status = "询价中"
self.lost_reason = ""
self.event_wait_kind = ""
def transition(self, *, work_order_no, to_status, **kwargs):
_ = work_order_no
allowed = {
"询价中": {"已报价", "协商中", "已关闭"},
"已报价": {"协商中", "已成交", "未成交", "已关闭"},
}
if to_status not in allowed.get(self.status, set()):
# 模拟 http_ledger 在 500 时只回 http_500(丢失正文)
return {"ok": False, "error": "http_500"}
self.status = to_status
if to_status == "未成交" and kwargs.get("lost_reason"):
self.lost_reason = str(kwargs.get("lost_reason") or "")
return {"ok": True, "status": self.status}
def patch_lost_reason(self, *, work_order_no, lost_reason):
_ = work_order_no
self.lost_reason = lost_reason
return {"ok": True}
def get_for_agent(self, *, work_order_no, sender_id):
_ = (work_order_no, sender_id)
return {"status": self.status, "lost_reason": self.lost_reason}
ledger = _StrictSix()
out = finish_deal_outcome(
ledger=ledger,
work_order_no="WO202610070023",
outcome="未成交",
facts={},
quote={},
business_line="AIR",
)
self.assertTrue(out.get("ok"), out)
self.assertEqual(ledger.status, "未成交")
self.assertEqual(out.get("phase"), "wait_lost_reason")
def test_lost_reason_ack_repeats_user_text(self) -> None:
self.assertEqual(copy.lost_reason_ack("客户不要了"), "已记下未成交原因:客户不要了。")
self.assertEqual(copy.lost_reason_ack("价格高。"), "已记下未成交原因:价格高。")
+199 -13
View File
@@ -222,6 +222,9 @@ class TestPoll(unittest.TestCase):
from agent.ledger.memory_ledger import MemoryLedger
from agent.policy.deal_followup import SHANGHAI
# 钉在周五,避免周日跑单测时工作日折算为 0
now = datetime(2026, 10, 9, 18, 0, 0, tzinfo=SHANGHAI)
path = os.path.join(ROOT, "agent", "jobs", "event_exception_poll.py")
spec = importlib.util.spec_from_file_location("ee_poll", path)
self.assertIsNotNone(spec)
@@ -248,9 +251,7 @@ class TestPoll(unittest.TestCase):
t = book.get_ticket(work_order_no=wo)
t.collab_chat_id = "wr1"
t.collab_member_ids = ["p1"]
t.event_wait_started_at = (datetime.now(SHANGHAI) - timedelta(hours=3)).strftime(
"%Y-%m-%d %H:%M:%S"
)
t.event_wait_started_at = (now - timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S")
book._timeouts["sea_product_other"] = 0.25
groups: list[dict] = []
@@ -258,7 +259,6 @@ class TestPoll(unittest.TestCase):
groups.append({"chat_id": chat_id, "content": content, "line": business_line})
return True
now = datetime.now(SHANGHAI)
n = poll_event_exceptions(
ledger=book, now=now, send_group=send_group, notify_ready=False
)
@@ -305,13 +305,12 @@ class TestPoll(unittest.TestCase):
)
created = book.create_ticket(sender_id="sales1", business_line="AIR", facts={"起运港": "南京"})
wo = created["work_order_no"]
now = datetime(2026, 10, 9, 18, 0, 0, tzinfo=SHANGHAI)
book.start_event_wait(work_order_no=wo, wait_kind="air_quote")
ticket = book.get_ticket(work_order_no=wo)
ticket.collab_chat_id = "wr-air"
ticket.collab_member_ids = []
ticket.event_wait_started_at = (datetime.now(SHANGHAI) - timedelta(hours=3)).strftime(
"%Y-%m-%d %H:%M:%S"
)
ticket.event_wait_started_at = (now - timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S")
book._timeouts["air_route"] = 0.25
groups: list[dict] = []
@@ -321,7 +320,7 @@ class TestPoll(unittest.TestCase):
n = mod.poll_event_exceptions(
ledger=book,
now=datetime.now(SHANGHAI),
now=now,
send_group=send_group,
notify_ready=False,
)
@@ -355,13 +354,12 @@ class TestPoll(unittest.TestCase):
{"wecomId": "air1", "name": "吴季林", "roleCode": "air", "status": "active"},
]
)
now = datetime(2026, 10, 9, 18, 0, 0, tzinfo=SHANGHAI)
created = book.create_ticket(sender_id="sales1", business_line="AIR", facts={})
wo = created["work_order_no"]
book.start_event_wait(work_order_no=wo, wait_kind="adopt")
ticket = book.get_ticket(work_order_no=wo)
ticket.event_wait_started_at = (datetime.now(SHANGHAI) - timedelta(hours=3)).strftime(
"%Y-%m-%d %H:%M:%S"
)
ticket.event_wait_started_at = (now - timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S")
book._timeouts["air_sales"] = 0.25
private: list[dict] = []
@@ -374,7 +372,7 @@ class TestPoll(unittest.TestCase):
n = mod.poll_event_exceptions(
ledger=book,
now=datetime.now(SHANGHAI),
now=now,
enqueue=enqueue,
send_group=send_group,
notify_ready=False,
@@ -402,7 +400,7 @@ class TestPoll(unittest.TestCase):
n_deal = mod.poll_event_exceptions(
ledger=book,
now=datetime.now(SHANGHAI),
now=now,
enqueue=enqueue,
send_group=send_deal_group,
notify_ready=False,
@@ -429,5 +427,193 @@ class TestMentionsForRole(unittest.TestCase):
self.assertEqual([row["name"] for row in rows], ["吴季林"])
class TestDealOutcomeStopsTimeout(unittest.TestCase):
"""对应现网截图:协商中顺延 / 未成交已写原因后不应再发销售响应超时。"""
def _poll_mod(self):
import importlib.util
path = os.path.join(ROOT, "agent", "jobs", "event_exception_poll.py")
spec = importlib.util.spec_from_file_location("ee_poll_deal_stop", path)
self.assertIsNotNone(spec)
self.assertIsNotNone(spec.loader)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def _book_with_deal_wait(self):
from datetime import datetime, timedelta
from agent.ledger.memory_ledger import MemoryLedger
from agent.policy.deal_followup import SHANGHAI
book = MemoryLedger()
book.set_sea_staff(
[
{
"wecomId": "sales1",
"name": "罗小华",
"roleCode": "sales",
"status": "active",
}
]
)
created = book.create_ticket(sender_id="sales1", business_line="AIR", facts={})
wo = created["work_order_no"]
book.transition(work_order_no=wo, to_status="已报价")
book.start_event_wait(work_order_no=wo, wait_kind="deal")
ticket = book.get_ticket(work_order_no=wo)
ticket.collab_chat_id = "wr-deal"
ticket.event_wait_started_at = (datetime.now(SHANGHAI) - timedelta(hours=72)).strftime(
"%Y-%m-%d %H:%M:%S"
)
book._timeouts["air_sales"] = 48
return book, wo
def test_negotiate_clears_wait_no_timeout(self) -> None:
from datetime import datetime
from agent.policy.deal_followup import SHANGHAI
from agent.policy.deal_outcome import finish_deal_outcome
book, wo = self._book_with_deal_wait()
result = finish_deal_outcome(
ledger=book,
work_order_no=wo,
outcome="协商中",
facts={},
quote={"total": "100"},
business_line="AIR",
sales_name="罗小华",
notify_ready=False,
)
self.assertTrue(result.get("ok"))
ticket = book.get_ticket(work_order_no=wo)
self.assertEqual(ticket.status, "协商中")
self.assertEqual(ticket.event_wait_kind, "")
groups: list[dict] = []
n = self._poll_mod().poll_event_exceptions(
ledger=book,
now=datetime.now(SHANGHAI),
send_group=lambda **kwargs: groups.append(kwargs) or True,
notify_ready=False,
)
self.assertEqual(n, 0)
self.assertEqual(groups, [])
def test_lost_with_reason_clears_wait_no_timeout(self) -> None:
from datetime import datetime
from agent.policy.deal_followup import SHANGHAI
from agent.policy.deal_outcome import finish_deal_outcome
book, wo = self._book_with_deal_wait()
result = finish_deal_outcome(
ledger=book,
work_order_no=wo,
outcome="未成交",
facts={},
quote={"total": "100"},
business_line="AIR",
sales_name="罗小华",
lost_reason="客户不要了",
notify_ready=False,
)
self.assertTrue(result.get("ok"))
self.assertEqual(result.get("phase"), "done")
ticket = book.get_ticket(work_order_no=wo)
self.assertEqual(ticket.status, "未成交")
self.assertEqual(ticket.lost_reason, "客户不要了")
self.assertEqual(ticket.event_wait_kind, "")
groups: list[dict] = []
n = self._poll_mod().poll_event_exceptions(
ledger=book,
now=datetime.now(SHANGHAI),
send_group=lambda **kwargs: groups.append(kwargs) or True,
notify_ready=False,
)
self.assertEqual(n, 0)
self.assertEqual(groups, [])
def test_stale_deal_wait_during_negotiate_is_skipped(self) -> None:
"""截图回归:协商中已顺延,即使库里仍留着陈旧 deal 等待,也不再发超时。"""
from datetime import datetime
from agent.policy.deal_followup import SHANGHAI
from agent.policy.deal_outcome import finish_deal_outcome
book, wo = self._book_with_deal_wait()
ticket = book.get_ticket(work_order_no=wo)
started = ticket.event_wait_started_at
result = finish_deal_outcome(
ledger=book,
work_order_no=wo,
outcome="协商中",
facts={},
quote={"total": "100"},
business_line="AIR",
sales_name="罗小华",
notify_ready=False,
)
self.assertTrue(result.get("ok"))
ticket = book.get_ticket(work_order_no=wo)
self.assertEqual(ticket.status, "协商中")
self.assertTrue((ticket.next_followup_at or "").strip())
# 人为留下陈旧等待(模拟 clear/迁态未清干净),巡检必须跳过
ticket.event_wait_kind = "deal"
ticket.event_wait_started_at = started
ticket.event_wait_alerted = 0
groups: list[dict] = []
n = self._poll_mod().poll_event_exceptions(
ledger=book,
now=datetime.now(SHANGHAI),
send_group=lambda **kwargs: groups.append(kwargs) or True,
notify_ready=False,
)
self.assertEqual(n, 0)
self.assertEqual(groups, [])
def test_stale_deal_wait_after_lost_reason_is_skipped(self) -> None:
"""截图回归:未成交原因已记,陈旧 deal 等待不再触发销售超时。"""
from datetime import datetime
from agent.policy.deal_followup import SHANGHAI
from agent.policy.deal_outcome import finish_deal_outcome
book, wo = self._book_with_deal_wait()
ticket = book.get_ticket(work_order_no=wo)
started = ticket.event_wait_started_at
result = finish_deal_outcome(
ledger=book,
work_order_no=wo,
outcome="未成交",
facts={},
quote={"total": "100"},
business_line="AIR",
sales_name="罗小华",
lost_reason="客户不要了",
notify_ready=False,
)
self.assertTrue(result.get("ok"))
ticket = book.get_ticket(work_order_no=wo)
self.assertEqual(ticket.lost_reason, "客户不要了")
ticket.event_wait_kind = "deal"
ticket.event_wait_started_at = started
ticket.event_wait_alerted = 0
groups: list[dict] = []
n = self._poll_mod().poll_event_exceptions(
ledger=book,
now=datetime.now(SHANGHAI),
send_group=lambda **kwargs: groups.append(kwargs) or True,
notify_ready=False,
)
self.assertEqual(n, 0)
self.assertEqual(groups, [])
if __name__ == "__main__":
unittest.main()
+73
View File
@@ -624,6 +624,79 @@ AIR_QUOTE_SHEET = """
"""
class CargoHandoverSynonymTests(unittest.TestCase):
"""货交是提货地址,不能当成起运地。"""
def test_huojiao_shanghai_is_pickup_not_origin(self) -> None:
text = (
"KUL 空运 普货 散货\n"
"8686KG//9PLT//11.6CBM\n"
"110*110*118CM*7\n"
"110*110*80CM*1\n"
"110*110*53CM*1\n"
"货交上海\n"
"看看价格 几号"
)
guessed = parse_extract_payload(
{
"transport_mode": "AIR",
"fields": {
"起运港": "上海",
"目的港": "KUL",
"品名": "普货",
"件数": "9",
"毛重": "8686KG",
"体积": "11.6CBM",
"包装方式": "散货",
},
}
)
facts = extract_inquiry_snapshot(text, b_result=guessed)["facts"]
self.assertEqual(facts.get("提货地址"), "上海")
self.assertNotIn("起运港", facts)
self.assertEqual(facts.get("目的港"), "KUL")
def test_huojiao_colon_and_dao_same_as_pickup(self) -> None:
for spoken in ("货交:上海", "货交到上海", "货交地:上海"):
guessed = parse_extract_payload(
{
"transport_mode": "AIR",
"fields": {"起运港": "上海", "目的港": "KUL", "品名": "普货"},
}
)
facts = extract_inquiry_snapshot(
f"空运 {spoken} 目的地KUL", b_result=guessed
)["facts"]
self.assertEqual(facts.get("提货地址"), "上海", spoken)
self.assertNotIn("起运港", facts, spoken)
def test_explicit_route_keeps_origin(self) -> None:
text = "SZX-CGK 空运 货交深圳"
guessed = parse_extract_payload(
{
"transport_mode": "AIR",
"fields": {"起运港": "SZX", "目的港": "CGK", "品名": "普货"},
}
)
facts = extract_inquiry_snapshot(text, b_result=guessed)["facts"]
self.assertEqual(facts.get("提货地址"), "深圳")
self.assertEqual(facts.get("起运港"), "SZX")
self.assertEqual(facts.get("目的港"), "CGK")
def test_fly_from_city_keeps_origin(self) -> None:
text = "从南京飞吉隆坡 空运 货交上海"
guessed = parse_extract_payload(
{
"transport_mode": "AIR",
"fields": {"起运港": "南京", "目的港": "吉隆坡", "品名": "普货"},
}
)
facts = extract_inquiry_snapshot(text, b_result=guessed)["facts"]
self.assertEqual(facts.get("提货地址"), "上海")
self.assertEqual(facts.get("起运港"), "南京")
self.assertEqual(facts.get("目的港"), "吉隆坡")
class AirQuoteSheetInquiryOnlyTests(unittest.TestCase):
def test_quote_sheet_keeps_inquiry_fields_only(self) -> None:
"""费用明细、报价条件、落款不能进补问。起运地不能收成操作费。"""
+1 -1
View File
@@ -123,7 +123,7 @@ class LandCopyTest(unittest.TestCase):
self.assertIn("始发站(必填):广州", text)
self.assertIn(copy.CLARIFY_PASTE_HINT, text)
self.assertIn("1.体积(CBM)(必填):\n(如:100CBM)", text)
self.assertIn("2.通关口岸(非必填):\n(如:皇岗)", text)
self.assertIn("2.通关口岸(非必填):\n(如:友谊关)", text)
self.assertNotIn("体积(必填):(如:", text)
self.assertNotIn(copy.LAND_CONFIRM_TAIL, text)
@@ -360,6 +360,84 @@ class LandGroupCollabTests(unittest.TestCase):
"只有这张单的销售能调价。航线请继续报价,价格未改。",
)
def test_land_bare_price_defaults_to_land_fee(self) -> None:
"""陆运「价格为1RMB/KG」无费用名时默认陆运费,禁止落成海运费(WO118)。"""
from agent.llm.extract_text import extract_product_quote
land = extract_product_quote("价格为1RMB/KG", business_line="LAND")
rows = list(land.get("fee_rows") or [])
self.assertTrue(rows)
self.assertEqual(str(rows[0].get("name") or ""), "陆运费")
self.assertEqual(str(land.get("total") or ""), "1")
sea = extract_product_quote("价格为1RMB/KG", business_line="SEA")
self.assertEqual(str((sea.get("fee_rows") or [{}])[0].get("name") or ""), "海运费")
air = extract_product_quote("价格为1RMB/KG", business_line="AIR")
self.assertEqual(str((air.get("fee_rows") or [{}])[0].get("name") or ""), "空运费")
def test_land_adjust_without_currency_inherits_tms_hkd(self) -> None:
"""WO202610090107:TMS 港币,产品只写「运输费调整为1100」时继承 HKD,禁止默认 USD。"""
from agent.llm.extract_text import extract_product_quote
from agent.policy.sea_group_ops import _quote_currency_hint, merge_quote_fees
tms = {
"currency": "HKD",
"cost": "HKD 1000",
"total": "1000",
"source": "TMS",
"fee_lines": [
{
"name": "运输费",
"amount": "1000",
"currency": "HKD",
}
],
"landSegments": [
{
"origin": "广东省-深圳市-福田区",
"destination": "香港特别行政区",
"currency": "HKD",
"costPrice": "1000",
}
],
}
self.assertEqual(_quote_currency_hint(tms), "HKD")
# 旧行为:无 baseline 会落到 USD
legacy = extract_product_quote("运输费调整为1100", business_line="LAND")
self.assertNotEqual(str(legacy.get("currency") or ""), "USD")
quote = extract_product_quote(
"运输费调整为1100",
business_line="LAND",
baseline_currency=_quote_currency_hint(tms),
)
self.assertEqual(str(quote.get("currency") or ""), "HKD")
self.assertEqual(str((quote.get("fee_lines") or [{}])[0].get("currency") or ""), "HKD")
self.assertEqual(str((quote.get("fee_lines") or [{}])[0].get("amount") or ""), "1100")
merged = merge_quote_fees(tms, quote)
self.assertEqual(str((merged.get("fee_lines") or [{}])[0].get("currency") or ""), "HKD")
self.assertEqual(str(merged.get("currency") or ""), "HKD")
def test_land_requote_replaces_wrong_sea_fee_name(self) -> None:
"""旧陆运产品价误落海运费时,重报陆运费应盖掉而不是并排两行。"""
from agent.policy.sea_group_ops import _align_wrong_default_freight, merge_quote_fees
base = {
"fee_rows": [{"name": "海运费", "amount": "1", "currency": "CNY"}],
"fee_lines": [{"name": "海运费", "amount": "1", "currency": "CNY"}],
"total": "1",
"source_label": "产品报价",
}
overlay = {
"fee_rows": [{"name": "陆运费", "amount": "2", "currency": "CNY"}],
"fee_lines": [{"name": "陆运费", "amount": "2", "currency": "CNY"}],
"total": "2",
"source_label": "产品报价",
}
aligned = _align_wrong_default_freight(base, overlay, business_line="LAND")
merged = merge_quote_fees(aligned, overlay)
names = [str(x.get("name") or "") for x in (merged.get("fee_rows") or [])]
self.assertEqual(names, ["陆运费"])
self.assertEqual(str((merged.get("fee_rows") or [{}])[0].get("amount") or ""), "2")
if __name__ == "__main__":
unittest.main()
@@ -433,6 +433,41 @@ class LandRouteOptionsTests(unittest.TestCase):
self.assertIn("CNY 7500", page)
self.assertIn("成本价合计", page)
def test_h5_shows_vehicle_type_on_each_leg(self) -> None:
"""多条线路的 H5 卡片按段展示 TMS 车型,没有就写 -。"""
from agent.channel.h5.land_route_page import render_land_route_page
quote = _three_routes()
for leg in quote["landSegments"]:
dest = str(leg.get("destination") or "")
origin = str(leg.get("origin") or "")
if dest == "深圳":
leg["vehicleType"] = "9米6"
elif origin == "深圳":
leg["vehicleType"] = "13米"
elif dest == "广西":
leg["vehicleType"] = None
quote["fee_lines"] = _tms_land_fees(
(1, 1, "运输费", 7500),
(1, 2, "运输费", 9600),
(2, 1, "运输费", 7500),
(2, 2, "运输费", 9600),
(3, 1, "运输费", 7500),
(3, 2, "运输费", 9600),
)
page = render_land_route_page(
{"work_order_no": "WO202609220010", "quote": quote}
)
od = page.find("上海 → 深圳")
vehicle = page.find("车型 9米6", od)
fee = page.find("运输费", vehicle)
self.assertGreaterEqual(od, 0)
self.assertGreater(vehicle, od)
self.assertGreater(fee, vehicle)
self.assertIn("车型 13米", page)
self.assertIn("车型 -", page)
self.assertNotIn("9米6/1", page)
def test_h5_and_detail_use_tms_fees_when_java_sends_json_strings(self) -> None:
"""主账 quote 常是 JSON 串,且 fee_lines 可能没带段号。"""
from agent.channel.h5.land_route_page import render_land_route_page
+5
View File
@@ -177,6 +177,7 @@ class QuoteTests(unittest.TestCase):
)
self.assertEqual(phase, "multi_deal_sent")
self.assertIn("120", self.client.texts[-1])
self.assertNotIn("纯文字", self.client.texts[-1])
self.assertNotIn("100", deal_text(
work_order_no=self.ticket.work_order_no,
segments=[Segment(index=1, mode="SEA"), Segment(index=2, mode="LAND")],
@@ -198,6 +199,8 @@ class QuoteTests(unittest.TestCase):
brief = self.client.texts[-1]
self.assertIn("段1:海运", brief)
self.assertIn("段2:陆运", brief)
self.assertIn("产品人员可通过“纯文字”告知新报价", brief)
self.assertNotIn("航线或产品人员", brief)
self.assertNotIn("TMS报价", brief)
self.assertNotIn("其他段报完", brief)
self.assertEqual(self.ledger.get_ticket(work_order_no=no).collab_chat_id, "room-9")
@@ -265,6 +268,8 @@ class QuoteTests(unittest.TestCase):
self.assertIn("段2:空运", brief)
self.assertIn("目的地(必填):CRK", brief)
self.assertIn("贸易条款(非必填):DAP", brief)
self.assertTrue(brief.endswith("(注:附件报价单仅作为文件存储于后台,智能体不读取且不将报价内容写进系统)"))
self.assertIn("航线或产品人员可通过“纯文字”告知新报价", brief)
self.assertNotIn("其他段报完", "\n".join(self.client.texts))
self.assertNotIn("询价字段:", brief)
@@ -167,6 +167,10 @@ class SplitTests(unittest.TestCase):
)
self.assertIn("@吴季林@林绵助\n段1:", text)
self.assertNotIn("@林绵助\n\n段1", text)
self.assertTrue(
text.endswith(copy.multi_group_field_hint(includes_air=True)),
text,
)
def test_missing_fields_use_single_chat_examples(self) -> None:
outcome = split_segments("段1:海运\n起运港:广州港\n段2:空运\n目的地:CRK")
@@ -694,6 +698,11 @@ class PullTests(unittest.TestCase):
segments=flow._segments(flow.session_of("sales")),
)
self.assertNotIn("TMS", brief_text)
self.assertTrue(
brief_text.endswith(copy.multi_group_field_hint(includes_air=False)),
brief_text,
)
self.assertNotIn("航线或产品人员", brief_text)
class CardPullTests(unittest.TestCase):
@@ -1341,6 +1341,28 @@ class SeaGroupCollabFieldTests(unittest.TestCase):
self.assertEqual(str(rows["海运费"].get("amount") or ""), "100.00")
self.assertEqual(str(rows["燃油附加费"].get("amount") or ""), "15.00")
def test_land_weight_band_unit_price_and_rates(self) -> None:
"""陆运集拼:2-500KG 单价 + 燃油附加费率/税率,不能把档下限 2 当成燃油附加费。"""
from agent.llm.extract_text import extract_product_quote
quote = extract_product_quote(
"2-500KG 单价CNY990,燃油附加费率1%,税率6%"
)
self.assertEqual(str(quote.get("total") or ""), "990")
self.assertEqual(str(quote.get("fuel_surcharge_rate") or ""), "1%")
self.assertEqual(str(quote.get("tax_rate") or ""), "6%")
tiers = list(quote.get("weightPrices") or [])
self.assertEqual(len(tiers), 1)
self.assertEqual(int(tiers[0].get("min") or 0), 2)
self.assertEqual(int(tiers[0].get("max") or 0), 500)
self.assertEqual(str(tiers[0].get("price") or ""), "990")
rows = {str(x.get("name") or ""): x for x in (quote.get("fee_rows") or [])}
self.assertIn("2-500KG", rows)
self.assertEqual(str(rows["2-500KG"].get("amount") or ""), "990")
self.assertNotEqual(str(rows.get("燃油附加费", {}).get("amount") or ""), "2")
self.assertEqual(str(rows.get("燃油附加费率", {}).get("amount") or ""), "1%")
self.assertEqual(str(rows.get("税率", {}).get("amount") or ""), "6%")
def test_air_unit_qty_amount_keeps_air_freight_name(self) -> None:
"""空运费 单价/数量/金额:费用名是空运费,金额用「金额」不是单价。"""
from agent.llm.extract_text import extract_product_quote
+31 -11
View File
@@ -65,7 +65,7 @@ class TestSystemExceptionCopy(unittest.TestCase):
)
self.assertEqual(
copy.system_exception_impact(copy.STEP_TMS_RELEASE),
"释放舱位失败,工单状态保持不变",
"取消舱位失败,工单状态保持不变",
)
def test_alert_title_never_has_test_prefix(self) -> None:
@@ -118,9 +118,9 @@ class TestSystemExceptionCopy(unittest.TestCase):
)
self.assertEqual(
text,
"工单WO202609210001 空运释放舱位失败。\n"
"工单WO202609210001 空运取消舱位失败。\n"
"操作人:吴季林\n"
"释放舱位失败的原因:舱位不存在\n"
"取消舱位失败的原因:舱位不存在\n"
"已通知IT运维排查,请稍等。",
)
@@ -409,7 +409,7 @@ class TestConfirmSystemException(unittest.TestCase):
)
card = queued[0]["payload"]["template_card"]
values = {row["keyname"]: row["value"] for row in card["horizontal_content_list"]}
self.assertEqual(values["影响范围"], "释放舱位失败,工单状态保持不变")
self.assertEqual(values["影响范围"], "取消舱位失败,工单状态保持不变")
def test_closed_ticket_not_marked(self) -> None:
self.ledger.transition(work_order_no=self.wo, to_status="已关闭")
@@ -480,27 +480,45 @@ class TestConfirmSystemException(unittest.TestCase):
self.assertTrue("USD" in joined or "拉产品" in joined or "已报价" in joined)
def test_admin_retry_cabin_lock_runs_lock(self) -> None:
# 空运单 + 可锁报价;重试必须带上 operator_name / airline。
air = self.ledger.create_ticket(
sender_id="sales1",
business_line="AIR",
facts={"起运地": "上海", "目的地": "洛杉矶", "毛重": "100"},
)
air_wo = str(air.get("work_order_no") or "")
self.ledger.upsert_quote(
work_order_no=self.wo,
quote={"total": "100", "quoteId": "QT-AIR-1"},
work_order_no=air_wo,
quote={
"total": "800",
"source": "TMS",
"quoteId": "QT-AIR-1",
"airOptions": [{"optionNo": "AIR-OPT-01", "airlineCode": "CZ"}],
},
to_status="已报价",
)
self.ledger.mark_system_exception(
work_order_no=self.wo,
work_order_no=air_wo,
system_exception=TYPE_TMS,
system_exception_reason="空运锁舱接口调用失败",
step=STEP_TMS_CABIN,
payload={
"conversation_kind": "group",
"conversation_target": "chat-air",
"extra": {"option_no": "AIR-OPT-01", "instruction": "锁舱"},
"extra": {
"option_no": "AIR-OPT-01",
"instruction": "锁舱",
"operator_name": "HangXian",
"airline": "CZ",
},
},
)
hits = {"n": 0}
hits = {"n": 0, "kwargs": {}}
orig_lock = self.ledger.lock_cabin
def counted(**kwargs):
hits["n"] += 1
hits["kwargs"] = dict(kwargs)
return orig_lock(**kwargs)
self.ledger.lock_cabin = counted # type: ignore[method-assign]
@@ -512,12 +530,14 @@ class TestConfirmSystemException(unittest.TestCase):
orig = se._send_to_conversation
se._send_to_conversation = lambda **kwargs: talks.append(str(kwargs.get("text") or ""))
try:
out = run_admin_retry(self.wo, ledger=self.ledger)
out = run_admin_retry(air_wo, ledger=self.ledger)
finally:
se._send_to_conversation = orig
self.assertTrue(out.get("ok"))
self.assertGreaterEqual(hits["n"], 1)
ticket = self.ledger.get_ticket(work_order_no=self.wo)
self.assertEqual(hits["kwargs"].get("operator_name"), "HangXian")
self.assertEqual(hits["kwargs"].get("airline"), "CZ")
ticket = self.ledger.get_ticket(work_order_no=air_wo)
self.assertFalse(ticket_is_paused(ticket))
self.assertTrue(any("空运舱位接口已恢复" in x for x in talks))
@@ -27,7 +27,10 @@ public class InquiryDashboardController {
@ApiOperation("看板指标")
@GetMapping("/metrics")
public Result<Map<String, Object>> metrics(@RequestParam(name = "range", defaultValue = "today") String range) {
return Result.OK(dashboardService.metrics(range));
public Result<Map<String, Object>> metrics(
@RequestParam(name = "range", defaultValue = "today") String range,
@RequestParam(name = "dateFrom", required = false) String dateFrom,
@RequestParam(name = "dateTo", required = false) String dateTo) {
return Result.OK(dashboardService.metrics(range, dateFrom, dateTo));
}
}
@@ -9,9 +9,13 @@ public interface IInquiryDashboardService {
/**
* 返回看板指标:metrics + trend + rankings + costDates/costRoutes。
* rankings 与工单列表同套发起人解析;costRoutes 为近 7 日线路均价(主账工单投影)。
* rankings 与工单列表同套发起人解析;costRoutes 为选定周期内线路均价(主账工单投影)。
* <p>
* 有 dateFrom/dateTo 时以显式日期为准(与工单列表筛选同源);否则回退 range=today|7d|30d。
*
* @param range today|7d|30d,默认 today
* @param range today|7d|30d,默认 today(无显式日期时)
* @param dateFrom 起日 yyyy-MM-dd,可空
* @param dateTo 止日 yyyy-MM-dd,可空
*/
Map<String, Object> metrics(String range);
Map<String, Object> metrics(String range, String dateFrom, String dateTo);
}
@@ -2,8 +2,6 @@ package org.jeecg.modules.inquiry.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.inquiry.domain.TicketStatuses;
import org.jeecg.modules.inquiry.entity.InquiryQuote;
import org.jeecg.modules.inquiry.entity.InquiryStaffRole;
@@ -14,6 +12,7 @@ import org.jeecg.modules.inquiry.mapper.InquiryStaffRoleMapper;
import org.jeecg.modules.inquiry.mapper.InquiryTicketMapper;
import org.jeecg.modules.inquiry.mapper.InquiryTicketStatusLogMapper;
import org.jeecg.modules.inquiry.service.IInquiryDashboardService;
import org.jeecg.modules.inquiry.support.InquiryDataScopeSupport;
import org.jeecg.modules.inquiry.support.InquiryTicketDisplaySupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -79,23 +78,18 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
private InquiryQuoteMapper quoteMapper;
@Override
public Map<String, Object> metrics(String range) {
LocalDate today = LocalDate.now(ZONE);
LocalDate fromDate;
if ("7d".equalsIgnoreCase(range)) {
fromDate = today.minusDays(6);
} else if ("30d".equalsIgnoreCase(range)) {
fromDate = today.minusDays(29);
} else {
fromDate = today;
}
public Map<String, Object> metrics(String range, String dateFromStr, String dateToStr) {
LocalDate[] bounds = resolveMetricBounds(range, dateFromStr, dateToStr);
LocalDate fromDate = bounds[0];
LocalDate toDate = bounds[1];
Date from = Date.from(fromDate.atStartOfDay(ZONE).toInstant());
Date to = Date.from(LocalDateTime.of(today, LocalTime.MAX).atZone(ZONE).toInstant());
Date to = Date.from(LocalDateTime.of(toDate, LocalTime.MAX).atZone(ZONE).toInstant());
// 指标 / 排名 / 趋势 / 成本:同一批工单、同一日期窗,与工单列表 dateFrom~dateTo 对齐
LambdaQueryWrapper<InquiryTicket> qw = new LambdaQueryWrapper<InquiryTicket>()
.ge(InquiryTicket::getCreateTime, from)
.le(InquiryTicket::getCreateTime, to);
applyDashboardSelfOnly(qw);
InquiryDataScopeSupport.applySelfOnly(qw);
List<InquiryTicket> tickets = ticketMapper.selectList(qw);
long total = tickets.size();
@@ -128,28 +122,24 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
metricCards.add(card("avgResp", "内部报价平均响应",
"AVG(首次有效回复时间 − 分发时间)", avgResp, true));
// 近 7 日趋势 + 成本:一次拉周内工单,避免 7 次 count
Date weekFrom = Date.from(today.minusDays(6).atStartOfDay(ZONE).toInstant());
LambdaQueryWrapper<InquiryTicket> weekQw = new LambdaQueryWrapper<InquiryTicket>()
.ge(InquiryTicket::getCreateTime, weekFrom)
.le(InquiryTicket::getCreateTime, to);
applyDashboardSelfOnly(weekQw);
List<InquiryTicket> weekTickets = ticketMapper.selectList(weekQw);
List<String> trendDates = new ArrayList<>(7);
List<Map<String, Object>> trend = new ArrayList<>(7);
// 趋势 / 成本:按选定起止日逐日铺点(单日则一点;长周期最多 62 天防图爆炸)
List<String> trendDates = new ArrayList<>();
List<Map<String, Object>> trend = new ArrayList<>();
Map<LocalDate, Integer> dayIndex = new HashMap<>();
for (int i = 6; i >= 0; i--) {
LocalDate d = today.minusDays(i);
dayIndex.put(d, trendDates.size());
String label = d.format(DAY_FMT);
LocalDate cursor = fromDate;
int dayGuard = 0;
while (!cursor.isAfter(toDate) && dayGuard < 62) {
dayIndex.put(cursor, trendDates.size());
String label = cursor.format(DAY_FMT);
trendDates.add(label);
Map<String, Object> p = new HashMap<>();
p.put("date", label);
p.put("value", 0L);
trend.add(p);
cursor = cursor.plusDays(1);
dayGuard++;
}
for (InquiryTicket t : weekTickets) {
for (InquiryTicket t : tickets) {
LocalDate d = toLocalDate(t.getCreateTime());
Integer idx = d == null ? null : dayIndex.get(d);
if (idx == null) {
@@ -175,10 +165,12 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
}
List<Map<String, Object>> rankings = buildRankings(tickets, staffByWecom, staffByName);
List<Map<String, Object>> costRoutes = buildCostRoutes(weekTickets, dayIndex, trendDates);
List<Map<String, Object>> costRoutes = buildCostRoutes(tickets, dayIndex, trendDates);
Map<String, Object> result = new LinkedHashMap<>();
result.put("range", range == null ? "today" : range);
result.put("dateFrom", fromDate.toString());
result.put("dateTo", toDate.toString());
result.put("metrics", metricCards);
result.put("trend", trend);
result.put("rankings", rankings);
@@ -187,6 +179,33 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
return result;
}
/**
* 解析看板统计起止日。
* 优先用显式 dateFrom/dateTo(与工单列表同源);否则按 range=today|7d|30d 相对「今天」。
*/
private static LocalDate[] resolveMetricBounds(String range, String dateFromStr, String dateToStr) {
if (StringUtils.isNotBlank(dateFromStr) && StringUtils.isNotBlank(dateToStr)) {
LocalDate fromDate = LocalDate.parse(dateFromStr.trim());
LocalDate toDate = LocalDate.parse(dateToStr.trim());
if (toDate.isBefore(fromDate)) {
LocalDate tmp = fromDate;
fromDate = toDate;
toDate = tmp;
}
return new LocalDate[]{fromDate, toDate};
}
LocalDate today = LocalDate.now(ZONE);
LocalDate fromDate;
if ("7d".equalsIgnoreCase(range)) {
fromDate = today.minusDays(6);
} else if ("30d".equalsIgnoreCase(range)) {
fromDate = today.minusDays(29);
} else {
fromDate = today;
}
return new LocalDate[]{fromDate, today};
}
/**
* 人员排名:与工单列表 enrichDisplayFields 同口径。
* 聚合键优先 salesWecomId(同人合并),展示名走 resolveSalesDisplayName。
@@ -667,87 +686,4 @@ public class InquiryDashboardServiceImpl implements IInquiryDashboardService {
return "sales";
}
/**
* 账号勾选「只看自己数据」时收紧看板工单范围。
* <p>
* 口径对齐原项目:非超管且 dashboardSelfOnly=true →
* 工单 salesWecomId = 当前账号工号(企微 id)或 createBy = 登录名。
* 超管(username=admin 或角色 admin)忽略开关。
*/
private void applyDashboardSelfOnly(LambdaQueryWrapper<InquiryTicket> qw) {
LoginUser login = currentLoginUser();
if (login == null) {
return;
}
if (isAdministrator(login)) {
return;
}
if (!Boolean.TRUE.equals(login.getDashboardSelfOnly())) {
return;
}
String username = StringUtils.trimToEmpty(login.getUsername());
String wecom = dashboardWecomId(login);
qw.and(w -> {
boolean any = false;
if (StringUtils.isNotBlank(wecom)) {
w.eq(InquiryTicket::getSalesWecomId, wecom);
any = true;
}
if (StringUtils.isNotBlank(username)) {
if (any) {
w.or();
}
w.eq(InquiryTicket::getCreateBy, username);
any = true;
}
if (!any) {
// 未绑企微且无用户名:宁可不看数据,也不漏看全站
w.apply("1 = 0");
}
});
}
private static LoginUser currentLoginUser() {
try {
Object p = SecurityUtils.getSubject().getPrincipal();
if (p instanceof LoginUser) {
return (LoginUser) p;
}
} catch (Exception ignored) {
// 无登录上下文时不做过滤
}
return null;
}
/** 超管:登录名 admin,或 Shiro 角色 admin/管理员。 */
private static boolean isAdministrator(LoginUser login) {
if (login == null) {
return false;
}
if ("admin".equalsIgnoreCase(StringUtils.trimToEmpty(login.getUsername()))) {
return true;
}
try {
return SecurityUtils.getSubject().hasRole("admin")
|| SecurityUtils.getSubject().hasRole("管理员");
} catch (Exception e) {
return false;
}
}
/**
* 看板「只看自己」用的企微工号。
* 不用直接调 getWorkNo:测服打包时基座 LoginUser 可能还没有这个方法。
*/
private static String dashboardWecomId(LoginUser login) {
if (login == null) {
return "";
}
try {
Object v = login.getClass().getMethod("getWorkNo").invoke(login);
return v == null ? "" : StringUtils.trimToEmpty(String.valueOf(v));
} catch (ReflectiveOperationException ignored) {
return "";
}
}
}
@@ -235,6 +235,8 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
int nextVer = nextVersionNo(template.getId());
String sha = DigestUtils.sha256Hex(fileBytes);
// 本地 by-sha 镜像:MinIO 对象损坏时仍能按版本 sha 回退出完好模板
objectStore.writeByShaMirror(fileBytes, sha);
InquiryQuoteTemplateVersion version = new InquiryQuoteTemplateVersion();
version.setTemplateId(template.getId());
@@ -564,7 +566,7 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
if (!"excel".equals(ver.getFormat())) {
throw new IllegalStateException("仅 Excel 支持样例回填预览");
}
Path source = resolveObjectPath(ver.getObjectKey());
Path source = resolveObjectPath(ver.getObjectKey(), ver.getSha256());
JSONObject contract = QuoteTemplateExcelSupport.loadContract(resolveContractPath());
JSONObject mapping;
try {
@@ -599,7 +601,7 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
if (!"excel".equals(ver.getFormat())) {
throw new IllegalStateException("仅 Excel 支持表格预览");
}
Path source = resolveObjectPath(ver.getObjectKey());
Path source = resolveObjectPath(ver.getObjectKey(), ver.getSha256());
JSONObject mapping;
try {
mapping = StringUtils.isNotBlank(ver.getMappingJson())
@@ -681,7 +683,7 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
Files.createDirectories(previewDir);
Path cachedPng = previewDir.resolve(ver.getId() + "-snapshot-v5.png");
Path cachedPdf = previewDir.resolve(ver.getId() + "-snapshot-v5.pdf");
Path source = resolveObjectPath(ver.getObjectKey());
Path source = resolveObjectPath(ver.getObjectKey(), ver.getSha256());
QuoteTemplateSnapshotRenderer.PreviewBytes rendered = snapshotRenderer.render(source, ver.getId());
Path target = rendered.isImage() ? cachedPng : cachedPdf;
Files.write(target, rendered.getBytes());
@@ -696,6 +698,13 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
return objectStore.resolve(objectKey);
}
/**
* 带版本 sha256 的解析:远程缓存/对象与指纹不一致时删缓存并回退 by-sha 镜像。
*/
public Path resolveObjectPath(String objectKey, String expectedSha256) {
return objectStore.resolve(objectKey, expectedSha256);
}
@Override
public List<Map<String, Object>> listEnabledForAgent(boolean enabledOnly) {
QueryWrapper<InquiryQuoteTemplate> qw = new QueryWrapper<>();
@@ -750,13 +759,16 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
}
String objectKey = String.valueOf(picked.getOrDefault("objectKey", ""));
String mappingJson = String.valueOf(picked.getOrDefault("mappingJson", ""));
String expectedSha = String.valueOf(picked.getOrDefault("sha256", ""));
if (StringUtils.isBlank(objectKey) || "null".equalsIgnoreCase(objectKey)) {
log.warn("报价出单模板无文件 wo={} template={}", workOrderNo, picked.get("templateId"));
return fail;
}
Path source;
try {
source = resolveObjectPath(objectKey);
// 传入版本 sha:防止 MinIO/缓存被掏空后仍出「费目名全空」的坏表
source = resolveObjectPath(objectKey,
("null".equalsIgnoreCase(expectedSha) ? null : expectedSha));
} catch (Exception e) {
log.warn("报价出单找不到模板文件 wo={} err={}", workOrderNo, e.getMessage());
return fail;
@@ -1043,6 +1055,18 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
out.put("chargeable_weight_kg", chargeable);
out.put("chargeableWeightKg", chargeable);
}
// 重量单位:仅供「已有费用行」时写入报价明细「单位」;无报价不出费用行,也不填单位。
String weightUnitEarly = first(src, "重量单位", "weight_unit", "weightUnit", "毛重单位");
if (StringUtils.isBlank(weightUnitEarly)) {
String rawW = first(src, "毛重", "重量", "重量(KG)", "weight_kg");
if (StringUtils.isNotBlank(rawW) && rawW.matches("(?i).*\\b(KG|KGS|公斤)\\b.*")) {
weightUnitEarly = "KG";
}
}
if (looksAirInquiry(src, q, businessLine)) {
out.put("weight_unit", QuoteTemplateExcelSupport.normalizeWeightUnit(weightUnitEarly));
out.put("重量单位", out.getString("weight_unit"));
}
for (Map.Entry<String, String> e : QuoteTemplateExcelSupport.LAND_TMS_KEY_TO_CODE.entrySet()) {
String val = first(q, e.getKey(), e.getValue());
if (StringUtils.isNotBlank(val) && !"-".equals(val) && StringUtils.isBlank(out.getString(e.getValue()))) {
@@ -1080,8 +1104,8 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
}
}
}
// 空运:已落库的旧明细若只有费率,出单时按计费重补 单位/单价/数量/行金额
if (!rows.isEmpty() && StringUtils.isNotBlank(chargeable)) {
// 空运:补单位/数量/单价(手工常只有金额,WO020 空运费与增点费)
if (!rows.isEmpty()) {
List<Map<String, String>> lineMaps = new ArrayList<>();
for (int i = 0; i < rows.size(); i++) {
JSONObject one = rows.getJSONObject(i);
@@ -1097,8 +1121,15 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
}
lineMaps.add(m);
}
// 出单路径自带重算(单位/单价/数量/金额)
QuoteTemplateExcelSupport.enrichAirWeightFeeRows(lineMaps, chargeable);
String weightUnit = first(src, "重量单位", "weight_unit", "weightUnit", "毛重单位");
if (StringUtils.isBlank(weightUnit)) {
// 从「262 KG」「重量:262KG」里剥单位
String rawW = first(src, "毛重", "重量", "重量(KG)", "weight_kg");
if (StringUtils.isNotBlank(rawW) && rawW.matches("(?i).*\\b(KG|KGS|公斤)\\b.*")) {
weightUnit = "KG";
}
}
QuoteTemplateExcelSupport.enrichAirWeightFeeRows(lineMaps, chargeable, weightUnit);
JSONArray enriched = new JSONArray();
for (Map<String, String> m : lineMaps) {
// Fastjson 只要 Map<String,Object>,不能直接塞 Map<String,String>。
@@ -1145,19 +1176,50 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
if (!routeRows.isEmpty()) {
QuoteTemplateExcelSupport.copyMissingWeightPrices(landSegs, rawLand);
}
// 销售已选线路透传:跨境整车国内/境外段按 legs 写完整起讫(多备选混在 route_rows 时不能靠同序列过滤)
Object selectedLand = q.get("selected_land_route");
if (selectedLand == null) {
selectedLand = q.get("selectedLandRoute");
}
if (selectedLand != null) {
out.put("selected_land_route", selectedLand);
}
if (!landSegs.isEmpty()) {
out.put("landSegments", landSegs);
out.put("route_rows", landSegs);
// 首段时效若 facts 尚无,用腿上 transit
if (StringUtils.isBlank(out.getString("transit_time")) || "-".equals(out.getString("transit_time"))) {
JSONObject firstSeg = landSegs.getJSONObject(0);
if (firstSeg != null) {
String t = firstNonBlankLocal(firstSeg.getString("transit_time"), firstSeg.getString("transitDays"));
// 首段时效/燃油/税率抬到顶层,供侧栏与标签回填(WO006 燃油列不能空着有数却写不上)
for (int i = 0; i < landSegs.size(); i++) {
JSONObject seg = landSegs.getJSONObject(i);
if (seg == null) {
continue;
}
if (StringUtils.isBlank(out.getString("transit_time")) || "-".equals(out.getString("transit_time"))) {
String t = firstNonBlankLocal(seg.getString("transit_time"), seg.getString("transitDays"));
if (StringUtils.isNotBlank(t)) {
out.put("transit_time", t);
out.put("transit_days", t);
}
}
if (StringUtils.isBlank(out.getString("fuel_surcharge_rate"))) {
String fuel = firstNonBlankLocal(seg.getString("fuel_surcharge_rate"),
seg.getString("fuelSurchargeRate"));
if (StringUtils.isNotBlank(fuel)) {
out.put("fuel_surcharge_rate", fuel);
}
}
if (StringUtils.isBlank(out.getString("tax_rate"))) {
String tax = firstNonBlankLocal(seg.getString("tax_rate"), seg.getString("taxRate"),
seg.getString("rate"));
if (StringUtils.isNotBlank(tax)) {
out.put("tax_rate", tax);
}
}
if (StringUtils.isBlank(out.getString("currency"))) {
String ccy = StringUtils.trimToEmpty(seg.getString("currency"));
if (StringUtils.isNotBlank(ccy)) {
out.put("currency", ccy);
}
}
}
} else if (looksLandInquiry(src)) {
// 无 landSegments 时:用询价 OD + fee_lines 分项拼一行,尽量填「提货费/运输费/送货费」列
@@ -1171,6 +1233,27 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
one.put("delivery_fee", out.getString("delivery_fee"));
one.put("price_per_cbm", out.getString("price_per_cbm"));
one.put("price_per_kg", out.getString("price_per_kg"));
// 产品文字报「2-500KG 单价…」时 weightPrices / 费率在 quote 顶层,无 TMS landSegments。
Object wp = q.get("weightPrices");
if (wp != null) {
one.put("weightPrices", wp);
}
String fuelRate = firstNonBlankLocal(
out.getString("fuel_surcharge_rate"),
first(q, "fuel_surcharge_rate"),
first(q, "fuelSurchargeRate"));
if (StringUtils.isNotBlank(fuelRate)) {
one.put("fuel_surcharge_rate", fuelRate);
one.put("fuelSurchargeRate", fuelRate);
}
String taxRate = firstNonBlankLocal(
out.getString("tax_rate"),
first(q, "tax_rate"),
first(q, "taxRate"));
if (StringUtils.isNotBlank(taxRate)) {
one.put("tax_rate", taxRate);
one.put("taxRate", taxRate);
}
String landAmt = firstNonBlankLocal(out.getString("land_freight"), out.getString("price_per_cbm"));
for (int i = 0; i < rows.size(); i++) {
JSONObject fee = rows.getJSONObject(i);
@@ -1529,7 +1612,7 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
throw new IllegalArgumentException("模板不存在");
}
try {
Path local = resolveObjectPath(ver.getObjectKey());
Path local = resolveObjectPath(ver.getObjectKey(), ver.getSha256());
byte[] fileBytes = Files.readAllBytes(local);
ver.setParseStatus("pending");
ver.setParseMessage("解析中,请稍候");
@@ -1598,7 +1681,7 @@ public class InquiryQuoteTemplateServiceImpl extends ServiceImpl<InquiryQuoteTem
org.apache.poi.ss.usermodel.Workbook wb = null;
try {
if (StringUtils.isNotBlank(ver.getObjectKey())) {
Path local = resolveObjectPath(ver.getObjectKey());
Path local = resolveObjectPath(ver.getObjectKey(), ver.getSha256());
try (InputStream in = Files.newInputStream(local)) {
wb = org.apache.poi.ss.usermodel.WorkbookFactory.create(in);
}
@@ -26,6 +26,7 @@ import org.jeecg.modules.inquiry.mapper.InquiryTicketMapper;
import org.jeecg.modules.inquiry.mapper.InquiryTicketStatusLogMapper;
import org.jeecg.modules.inquiry.support.AgentSystemExceptionRetryClient;
import org.jeecg.modules.inquiry.service.IInquiryWorkOrderService;
import org.jeecg.modules.inquiry.support.InquiryDataScopeSupport;
import org.jeecg.modules.inquiry.support.InquiryQuoteDisplaySupport;
import org.jeecg.modules.inquiry.support.InquiryQuoteFileSupport;
import org.jeecg.modules.inquiry.support.InquiryTicketDisplaySupport;
@@ -122,6 +123,8 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
if (StringUtils.isNotBlank(dateTo)) {
qw.le(InquiryTicket::getCreateTime, dateTo + " 23:59:59");
}
// 与看板同源:账号勾「只看自己」时收紧列表(非超管)
InquiryDataScopeSupport.applySelfOnly(qw);
qw.orderByDesc(InquiryTicket::getCreateTime);
IPage<InquiryTicket> result = page(page, qw);
enrichDisplayFields(result.getRecords());
@@ -283,24 +286,36 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
if (TicketStatuses.CLOSED.equals(to) && StringUtils.isNotBlank(req.getRemark())) {
ticket.setCloseReason(req.getRemark());
}
boolean clearEventWait = false;
if (TicketStatuses.LOST.equals(to)) {
ticket.setNextFollowupAt(null);
if (StringUtils.isNotBlank(req.getLostReason())) {
ticket.setLostReason(StringUtils.left(req.getLostReason().trim(), 500));
}
// 成交等待结束;缺原因时由智能体再 start lost_reason,避免陈旧 deal 继续催
clearEventWait = true;
} else if (TicketStatuses.DEAL.equals(to)) {
ticket.setNextFollowupAt(null);
if (StringUtils.isNotBlank(req.getDealNotifySummary())) {
ticket.setDealNotifySummary(StringUtils.left(req.getDealNotifySummary().trim(), 500));
}
clearEventWait = true;
} else if (TicketStatuses.NEGOTIATING.equals(to)) {
Date follow = parseDateTime(req.getNextFollowupAt());
ticket.setNextFollowupAt(follow);
// 顺延再问期间不盯销售超时;到期再问会重新 start deal
clearEventWait = true;
} else if (TicketStatuses.CLOSED.equals(to)) {
clearEventWait = true;
}
ticket.setVersion(ticket.getVersion() == null ? 2 : ticket.getVersion() + 1);
ticket.setUpdateBy(operator);
ticket.setUpdateTime(new Date());
updateById(ticket);
// updateById 默认不写 null:等待三列必须在落库后再强制清空
if (clearEventWait) {
clearEventWaitColumns(ticket);
}
String remark = StringUtils.defaultIfBlank(req.getRemark(),
StringUtils.defaultIfBlank(req.getDealNotifySummary(), req.getLostReason()));
appendLog(ticket, from, to, "transition", operator, remark);
@@ -1494,6 +1509,8 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
ticket.setUpdateBy(StringUtils.defaultIfBlank(operator, "agent"));
ticket.setUpdateTime(new Date());
updateById(ticket);
// 原因已入账:强制清空等待三列(updateById 写不进 null)
clearEventWaitColumns(ticket);
appendLog(ticket, ticket.getStatus(), ticket.getStatus(), "lost_reason", operator, reason);
out.put("ok", true);
out.put("work_order_no", no);
@@ -1637,11 +1654,7 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
out.put("error", "not_found");
return out;
}
ticket.setEventWaitKind(null);
ticket.setEventWaitStartedAt(null);
ticket.setEventWaitAlerted(0);
ticket.setUpdateTime(new Date());
updateById(ticket);
clearEventWaitColumns(ticket);
out.put("ok", true);
out.put("work_order_no", ticket.getWorkOrderNo());
return out;
@@ -1661,10 +1674,21 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
return out;
}
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
for (InquiryTicket ticket : rows) {
if (ticket == null || !EventExceptionRule.isWatchable(ticket.getStatus())) {
continue;
}
// 未成交已写原因、协商中仍排着再问:不进巡检(挡住陈旧等待)
if (TicketStatuses.LOST.equals(ticket.getStatus())
&& StringUtils.isNotBlank(ticket.getLostReason())) {
continue;
}
if (TicketStatuses.NEGOTIATING.equals(ticket.getStatus())
&& ticket.getNextFollowupAt() != null
&& ticket.getNextFollowupAt().after(now)) {
continue;
}
Map<String, Object> one = new LinkedHashMap<>();
one.put("workOrderNo", ticket.getWorkOrderNo());
one.put("work_order_no", ticket.getWorkOrderNo());
@@ -1688,6 +1712,8 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
one.put("collabMemberIds", members);
one.put("collab_member_ids", members);
one.put("eventException", StringUtils.defaultString(ticket.getEventException()));
one.put("lostReason", StringUtils.defaultString(ticket.getLostReason()));
one.put("lost_reason", StringUtils.defaultString(ticket.getLostReason()));
Map<String, String> facts = new LinkedHashMap<>();
if (StringUtils.isNotBlank(ticket.getFactsJson())) {
JSONObject parsed = JSON.parseObject(ticket.getFactsJson());
@@ -1710,6 +1736,30 @@ public class InquiryWorkOrderServiceImpl extends ServiceImpl<InquiryTicketMapper
return out;
}
/**
* 清空事件异常当前等待三列。不改六态、不改事件异常摘要。
* <p>
* 必须用 UpdateWrapper 强制写 null:MyBatis-Plus updateById 默认跳过 null 字段,
* 否则协商中/未成交后库里仍残留 deal 等待,巡检会继续催(WO202610060024 / WO202610070034)。
*/
private void clearEventWaitColumns(InquiryTicket ticket) {
if (ticket == null || StringUtils.isBlank(ticket.getId())) {
return;
}
Date now = new Date();
lambdaUpdate()
.eq(InquiryTicket::getId, ticket.getId())
.set(InquiryTicket::getEventWaitKind, null)
.set(InquiryTicket::getEventWaitStartedAt, null)
.set(InquiryTicket::getEventWaitAlerted, 0)
.set(InquiryTicket::getUpdateTime, now)
.update();
ticket.setEventWaitKind(null);
ticket.setEventWaitStartedAt(null);
ticket.setEventWaitAlerted(0);
ticket.setUpdateTime(now);
}
@Override
@Transactional(rollbackFor = Exception.class)
public Map<String, Object> recordEventException(String workOrderNo, String eventException) {
@@ -0,0 +1,105 @@
package org.jeecg.modules.inquiry.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.inquiry.entity.InquiryTicket;
/**
* 后台数据范围:账号「只看自己数据」时收紧工单查询。
* <p>
* 口径:非超管且 {@code dashboardSelfOnly=true} →
* {@code salesWecomId = 工号} 或 {@code createBy = 登录名}。
* 看板与工单列表共用,避免只看板生效、列表漏看全站。
* 线程:只读登录态,无全局锁。
*/
public final class InquiryDataScopeSupport {
private InquiryDataScopeSupport() {
}
/**
* 按当前登录账号把「只看自己」条件叠到工单查询上。
*
* @param qw 工单查询包装器;null 时直接返回
*/
public static void applySelfOnly(LambdaQueryWrapper<InquiryTicket> qw) {
if (qw == null) {
return;
}
LoginUser login = currentLoginUser();
if (login == null) {
return;
}
if (isAdministrator(login)) {
return;
}
if (!Boolean.TRUE.equals(login.getDashboardSelfOnly())) {
return;
}
String username = StringUtils.trimToEmpty(login.getUsername());
String wecom = wecomId(login);
qw.and(w -> {
boolean any = false;
if (StringUtils.isNotBlank(wecom)) {
w.eq(InquiryTicket::getSalesWecomId, wecom);
any = true;
}
if (StringUtils.isNotBlank(username)) {
if (any) {
w.or();
}
w.eq(InquiryTicket::getCreateBy, username);
any = true;
}
if (!any) {
// 未绑企微且无用户名:宁可不看数据,也不漏看全站
w.apply("1 = 0");
}
});
}
private static LoginUser currentLoginUser() {
try {
Object p = SecurityUtils.getSubject().getPrincipal();
if (p instanceof LoginUser) {
return (LoginUser) p;
}
} catch (Exception ignored) {
// 无登录上下文
}
return null;
}
/** 超管:登录名 admin,或 Shiro 角色 admin/管理员。 */
private static boolean isAdministrator(LoginUser login) {
if (login == null) {
return false;
}
if ("admin".equalsIgnoreCase(StringUtils.trimToEmpty(login.getUsername()))) {
return true;
}
try {
return SecurityUtils.getSubject().hasRole("admin")
|| SecurityUtils.getSubject().hasRole("管理员");
} catch (Exception e) {
return false;
}
}
/**
* 企微工号。反射读 getWorkNo,兼容测服旧 LoginUser 无该方法的包。
*/
public static String wecomId(LoginUser login) {
if (login == null) {
return "";
}
try {
Object v = login.getClass().getMethod("getWorkNo").invoke(login);
return v == null ? "" : StringUtils.trimToEmpty(String.valueOf(v));
} catch (ReflectiveOperationException ignored) {
return "";
}
}
}
@@ -22,7 +22,8 @@ import java.util.Locale;
* <p>
* Jeecg MinIO/OSS 上传返回完整 http(s) URL,Windows 上 {@code Paths.get("http://...")}
* 会在冒号处抛 Illegal char &lt;:&gt;。本类先认远程 URL,拉到本地缓存再给 POI / 下载。
* 副作用:写 {@code upload/inquiry/quote-templates/_remote-cache/}。
* 副作用:写 {@code upload/inquiry/quote-templates/_remote-cache/},以及
* {@code upload/inquiry/quote-templates/by-sha/{sha256}.xlsx} 本地镜像(上传时写入,远程损坏时可回退)。
* 线程:跟随调用方 HTTP 线程;不持有全局锁。
*/
@Slf4j
@@ -70,18 +71,75 @@ public class QuoteTemplateObjectStore {
* @return 已存在的本地文件,或从对象存储落地后的缓存文件
*/
public Path resolve(String objectKey) {
return resolve(objectKey, null);
}
/**
* 解析模板文件,并在提供 expectedSha256 时校验内容指纹。
* <p>
* 为何:MinIO 对象偶发被掏空/覆盖后,旧逻辑只要缓存「非空」就直接用,导致空运报价费目名全空。
* 有 sha 时:缓存/远程不匹配则删缓存重拉;仍不匹配则回退 {@code by-sha/{sha}.xlsx}。
*
* @param objectKey 主账 version.object_key(本地相对路径或 http(s) URL)
* @param expectedSha256 版本表记录的 sha256(可空;空则只做路径解析,与历史行为一致)
* @return 可读本地文件
*/
public Path resolve(String objectKey, String expectedSha256) {
if (StringUtils.isBlank(objectKey)) {
throw new IllegalArgumentException("objectKey 空");
}
String key = objectKey.trim();
String want = normalizeSha(expectedSha256);
if (want != null) {
Path bySha = tryByShaMirror(want);
if (bySha != null) {
return bySha;
}
}
Path resolved;
if (isRemoteUrl(key)) {
return fetchRemoteToCache(key);
resolved = fetchRemoteToCache(key, want);
} else {
resolved = tryLocalFile(key);
if (resolved == null) {
throw new IllegalStateException("找不到模板文件: " + key);
}
if (want != null && !shaMatches(resolved, want)) {
Path fallback = tryByShaMirror(want);
if (fallback != null) {
log.warn("本地模板 sha 不匹配,改用 by-sha 镜像 key={}", key);
return fallback;
}
throw new IllegalStateException("模板文件 sha256 不匹配: " + key);
}
}
Path local = tryLocalFile(key);
if (local != null) {
return local;
return resolved;
}
/**
* 上传成功后写一份按内容指纹命名的本地镜像,供远程损坏时回退。
* <p>
* 副作用:写 {@code upload/inquiry/quote-templates/by-sha/{sha256}.xlsx}。
* 失败只记日志,不阻断上传主流程。
*/
public void writeByShaMirror(byte[] fileBytes, String sha256Hex) {
String sha = normalizeSha(sha256Hex);
if (fileBytes == null || fileBytes.length == 0 || sha == null) {
return;
}
try {
Path dir = Paths.get(StringUtils.defaultIfBlank(uploadPath, System.getProperty("java.io.tmpdir")),
BIZ_PATH, "by-sha");
Files.createDirectories(dir);
Path target = dir.resolve(sha + ".xlsx");
Files.write(target, fileBytes);
log.info("模板 by-sha 镜像已写入 sha={} bytes={}", sha.substring(0, 12), fileBytes.length);
} catch (Exception e) {
log.warn("模板 by-sha 镜像写入失败 sha={} err={}", sha, e.getMessage());
}
throw new IllegalStateException("找不到模板文件: " + key);
}
/**
@@ -138,9 +196,11 @@ public class QuoteTemplateObjectStore {
}
/**
* 从 MinIO/OSS 拉到本地缓存。同一 URL 只落一次(文件名带时间戳,一般不会覆盖)。
* 从 MinIO/OSS 拉到本地缓存。同一 URL 缓存文件名 = sha256(url)。
* <p>
* 有 expectedSha 时:已有缓存若指纹不对则删除重拉;重拉后仍不对则回退 by-sha 镜像。
*/
private Path fetchRemoteToCache(String url) {
private Path fetchRemoteToCache(String url, String expectedSha) {
Path cacheDir = Paths.get(StringUtils.defaultIfBlank(uploadPath, System.getProperty("java.io.tmpdir")),
BIZ_PATH, "_remote-cache");
try {
@@ -152,7 +212,11 @@ public class QuoteTemplateObjectStore {
Path cacheFile = cacheDir.resolve(DigestUtils.sha256Hex(url) + ext);
try {
if (Files.isRegularFile(cacheFile) && Files.size(cacheFile) > 0) {
return cacheFile;
if (expectedSha == null || shaMatches(cacheFile, expectedSha)) {
return cacheFile;
}
log.warn("模板远程缓存 sha 不匹配,删除后重拉 file={}", cacheFile.getFileName());
Files.deleteIfExists(cacheFile);
}
} catch (Exception ignored) {
// 读缓存失败则重新拉取
@@ -161,11 +225,66 @@ public class QuoteTemplateObjectStore {
Files.copy(in, cacheFile, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
log.error("对象存储落地失败 url={}", url, e);
if (expectedSha != null) {
Path fallback = tryByShaMirror(expectedSha);
if (fallback != null) {
log.warn("对象存储读取失败,改用 by-sha 镜像 url={}", url);
return fallback;
}
}
throw new IllegalStateException("对象存储读取失败: " + e.getMessage(), e);
}
if (expectedSha != null && !shaMatches(cacheFile, expectedSha)) {
log.error("对象存储模板 sha256 与版本表不一致 urlHash={}",
DigestUtils.sha256Hex(url).substring(0, 12));
try {
Files.deleteIfExists(cacheFile);
} catch (Exception ignored) {
// ignore
}
Path fallback = tryByShaMirror(expectedSha);
if (fallback != null) {
log.warn("远程模板损坏,改用 by-sha 镜像");
return fallback;
}
throw new IllegalStateException("对象存储模板内容与版本 sha256 不一致");
}
return cacheFile;
}
private Path tryByShaMirror(String sha) {
if (StringUtils.isBlank(sha)) {
return null;
}
Path p = Paths.get(StringUtils.defaultIfBlank(uploadPath, System.getProperty("java.io.tmpdir")),
BIZ_PATH, "by-sha", sha + ".xlsx");
try {
if (Files.isRegularFile(p) && Files.size(p) > 0 && shaMatches(p, sha)) {
return p;
}
} catch (Exception ignored) {
return null;
}
return null;
}
private static String normalizeSha(String sha) {
if (StringUtils.isBlank(sha)) {
return null;
}
String s = sha.trim().toLowerCase(Locale.ROOT);
return s.matches("[0-9a-f]{64}") ? s : null;
}
private static boolean shaMatches(Path file, String expectedSha) {
try {
String actual = DigestUtils.sha256Hex(Files.readAllBytes(file)).toLowerCase(Locale.ROOT);
return expectedSha.equals(actual);
} catch (Exception e) {
return false;
}
}
private InputStream openRemoteStream(String url) {
String[] parts = splitStorageUrl(url, MinioUtil.getMinioUrl());
if (parts != null) {
@@ -11,6 +11,7 @@ import org.jeecg.modules.inquiry.entity.InquiryQuote;
import org.jeecg.modules.inquiry.entity.InquiryTicket;
import org.jeecg.modules.inquiry.mapper.InquiryQuoteMapper;
import org.jeecg.modules.inquiry.service.IInquiryWorkOrderService;
import org.jeecg.modules.inquiry.template.QuoteTemplateExcelSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@@ -96,11 +97,16 @@ public class InquiryTmsCabinService {
Map<String, Object> quote = payloadOf(rows.get(0));
// 「AIR-OPT01 TH」被误落成航线报价不算真正人工价 → 仍走仅 TMS(SYSTEM)。
boolean latestManual = isManualQuote(quote) && !isFakeManualLockQuote(quote);
if (!latestManual && StringUtils.isBlank(resolveQuoteId(quote, no))) {
// 库里只有人工价、没有舱位时也要现拉 TMS:补 quoteId/airOptions,
// 避免 MANUAL 空壳 1001,也避免逼航线手打航班号。
boolean cabinSparse = StringUtils.isBlank(resolveQuoteId(quote, no))
|| airOptions(quote).isEmpty();
if (cabinSparse) {
quote = refreshLockQuote(ticket, quote);
}
String tmsQuoteId = realTmsQuoteId(rows, no);
if (!latestManual && StringUtils.isBlank(tmsQuoteId)) {
// 现拉到的 TMS 编号也算:库里无历史行时仍可 MANUAL+quoteId。
if (StringUtils.isBlank(tmsQuoteId)) {
tmsQuoteId = resolveQuoteId(quote, no);
}
boolean hasTms = StringUtils.isNotBlank(tmsQuoteId);
@@ -161,26 +167,68 @@ public class InquiryTmsCabinService {
text(option, "destination"), ticket.getDestination(),
fact(ticket, "目的地", "目的港")));
// 航司:句中两位码(如「AIR-OPT01 TH」)> 舱位/报价字段 > 航班号前两位。
req.put("airline", firstNonBlank(
// airlineName 中文名不能当航司码出站,只取两位码或航班前缀。
String airlineCode = firstNonBlank(
text(body, "airline", "airlineCode"),
airlineFromInstruction(text(body, "instructionText", "instruction_text")),
text(option, "airlineCode", "airline"),
text(option, "airlineName"),
text(quote, "airlineCode", "airline", "airlineName"),
fact(ticket, "航司", "航司代码"),
airlineFromFlight(firstNonBlank(text(option, "flightNo"), text(quote, "flightNo")))));
text(quote, "airlineCode", "airline"),
fact(ticket, "航司代码"),
airlineFromFlight(firstNonBlank(text(option, "flightNo"), text(quote, "flightNo"))),
airlineCodeOrBlank(text(option, "airlineName")),
airlineCodeOrBlank(text(quote, "airlineName")),
airlineCodeOrBlank(fact(ticket, "航司")));
req.put("airline", airlineCode);
req.put("weightKg", ticket.getWeightKg());
req.put("volumeCbm", ticket.getVolumeCbm());
req.put("pieceQty", ticket.getPieces());
// 计费重:舱位 > 报价 > 工单计费重事实 > 毛重(避免 MANUAL 空壳 1001)。
req.put("chargeableWeightKg", firstNonBlank(
text(option, "chargeableWeightKg", "chargeable_weight_kg"),
text(quote, "chargeableWeightKg", "chargeable_weight_kg")));
text(quote, "chargeableWeightKg", "chargeable_weight_kg"),
fact(ticket, "计费重", "计费重量"),
ticket.getWeightKg() == null ? "" : String.valueOf(ticket.getWeightKg()),
fact(ticket, "毛重")));
req.put("operatorUserId", text(body, "operatorUserId", "sender_id"));
req.put("operatorName", text(body, "operatorName", "operator_name"));
// 重试漏传姓名时用 userid 兜底,仍要有 operatorName 键。
req.put("operatorName", firstNonBlank(
text(body, "operatorName", "operator_name"),
text(body, "operatorUserId", "sender_id")));
req.put("instructionText", text(body, "instructionText", "instruction_text"));
if ("MANUAL".equals(lockSource)) {
// 有 TMS 时保留 quoteId;纯人工才去掉。
fillManualLock(req, quote, option, body, StringUtils.isNotBlank(quoteId));
// 人工价常不写有效期:用航班日当天 23:59:59+08:00 兜底,避免空壳 1001。
if (StringUtils.isBlank(text(req, "validUntil"))) {
String isoUntil = normalizeValidUntilIso(text(req, "flightDate"));
if (StringUtils.isNotBlank(isoUntil)) {
req.put("validUntil", isoUntil);
if (StringUtils.isBlank(text(req, "requestedUntil"))) {
req.put("requestedUntil", isoUntil);
}
}
}
// 缺必填仍出站会被 TMS 1001;在此拦住并回清原因。
String incomplete = validateManualLockOutbound(req);
// 现拉仍无舱位时,改成业务补问口径(禁止堆「缺少 optionNo」技术字段名)。
if (StringUtils.isNotBlank(incomplete)) {
String refreshClass = text(quote, "_lockRefreshClass");
String refreshMsg = text(quote, "_lockRefreshMsg");
boolean noMatch = "TMS_NO_QUOTE_1002".equals(refreshClass)
|| (StringUtils.isNotBlank(refreshMsg) && refreshMsg.contains("无匹配"));
if (noMatch) {
incomplete = "本单是手工报价,且运价库无匹配舱位,无法自动带出航班。"
+ "请按「AIR-OPT01 CZ 航班CZ327」补舱位、航司和航班号后再锁。"
+ "(现拉TMS:" + firstNonBlank(refreshMsg, "标准运价库无匹配报价") + ")";
} else if (StringUtils.isNotBlank(refreshMsg)) {
incomplete = incomplete + "(现拉TMS:" + refreshMsg + ")";
}
}
if (StringUtils.isNotBlank(incomplete)) {
log.info("tms.lock incomplete wo={} optionNo={} missing={}",
no, resolvedOption, incomplete);
return fail("lock_incomplete", incomplete);
}
} else {
// 仅 TMS:source=SYSTEM + quoteId。禁止再塞 validUntil/feeItems(会 1001)。
req.put("source", "SYSTEM");
@@ -247,7 +295,7 @@ public class InquiryTmsCabinService {
return fail("release_need_lock", "本单还没有成功锁舱记录");
}
if (!properties.lockConfigured()) {
return fail("lock_disabled", "主账未开放释放");
return fail("lock_disabled", "主账未开放取消舱位");
}
Map<String, Object> req = new LinkedHashMap<>();
req.put("lockId", lockId);
@@ -316,7 +364,7 @@ public class InquiryTmsCabinService {
return out;
} catch (RuntimeException ex) {
log.warn("tms.release fail wo={} err={}", ticket.getWorkOrderNo(), ex.getMessage());
return fail("release_fail", firstNonBlank(ex.getMessage(), "释放失败"));
return fail("release_fail", firstNonBlank(ex.getMessage(), "取消舱位失败"));
}
}
@@ -356,14 +404,26 @@ public class InquiryTmsCabinService {
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("workOrderNo", ticket.getWorkOrderNo());
// 锁舱现拉必须用「今天」报价日:历史询价日常已无运价(1002),
// 不能把销售初询那天的日期带出去导致永远补不到舱位。
JSONObject facts = new JSONObject();
if (StringUtils.isNotBlank(ticket.getFactsJson())) {
JSONObject facts = JSON.parseObject(ticket.getFactsJson());
if (facts != null) {
body.put("facts", facts);
JSONObject stored = JSON.parseObject(ticket.getFactsJson());
if (stored != null) {
facts.putAll(stored);
}
}
SimpleDateFormat dayFmt = new SimpleDateFormat("yyyy-MM-dd");
dayFmt.setTimeZone(java.util.TimeZone.getTimeZone("Asia/Shanghai"));
String today = dayFmt.format(new java.util.Date());
facts.put("报价日期", today);
body.put("facts", facts);
try {
Map<String, Object> live = queryService.queryFromAgent(body);
if (live != null && live.get("classification") != null) {
current.put("_lockRefreshClass", String.valueOf(live.get("classification")));
current.put("_lockRefreshMsg", String.valueOf(live.get("message") == null ? "" : live.get("message")));
}
Object raw = live == null ? null : live.get("quote");
if (!(raw instanceof Map)) {
return current;
@@ -376,14 +436,19 @@ public class InquiryTmsCabinService {
if (airOptions(current).isEmpty() && fetched.get("airOptions") != null) {
current.put("airOptions", fetched.get("airOptions"));
}
if (airOptions(current).isEmpty() && fetched.get("air_options") != null) {
current.put("airOptions", fetched.get("air_options"));
}
if (StringUtils.isBlank(text(current, "chargeableWeightKg", "chargeable_weight_kg"))
&& StringUtils.isNotBlank(text(fetched, "chargeableWeightKg", "chargeable_weight_kg"))) {
current.put("chargeableWeightKg", text(fetched, "chargeableWeightKg", "chargeable_weight_kg"));
}
log.info("tms.lock refresh wo={} hasQuoteId={} airOpt={}",
log.info("tms.lock refresh wo={} hasQuoteId={} airOpt={} class={} quoteDate={}",
ticket.getWorkOrderNo(),
StringUtils.isNotBlank(text(current, "quoteId", "quote_id")),
airOptions(current).size());
airOptions(current).size(),
live == null ? "" : live.get("classification"),
today);
} catch (RuntimeException ex) {
log.warn("tms.lock refresh fail wo={} err={}", ticket.getWorkOrderNo(), ex.getMessage());
}
@@ -465,7 +530,11 @@ public class InquiryTmsCabinService {
if (StringUtils.isNotBlank(transfer)) {
req.put("transferAirport", transfer);
}
String flightNo = firstNonBlank(text(option, "flightNo"), text(quote, "flightNo"));
// 句中/请求体点名的航班号优先,其次舱位与报价。
String flightNo = firstNonBlank(
text(body, "flightNo", "flight_no"),
text(option, "flightNo", "flight_no"),
text(quote, "flightNo", "flight_no"));
if (StringUtils.isNotBlank(flightNo)) {
req.put("flightNo", flightNo);
}
@@ -512,11 +581,41 @@ public class InquiryTmsCabinService {
List<Map<String, Object>> departure = feeRows(quote, option, "departureCharges", "departure_charges");
List<Map<String, Object>> fees = feeRows(quote, option, "feeItems", "fee_items");
splitFeeRows(quote, departure, fees);
if (!departure.isEmpty()) {
req.put("departureCharges", toLockFees(departure, true));
}
// 运行证据(2026-10-07):只要出站带 departureCharges,TMS 一律 1001「参数格式错误」;
// 去掉后变为业务码 2008。feeItems 可保留。故 MANUAL 锁舱不再出站 departureCharges。
if (!fees.isEmpty()) {
req.put("feeItems", toLockFees(fees, false));
} else if (!departure.isEmpty()) {
// 仅有起运港费、无 feeItems 时,折进 feeItems,避免再走 departureCharges。
List<Map<String, Object>> asFees = new ArrayList<>();
for (Map<String, Object> row : toLockFees(departure, true)) {
Map<String, Object> fee = new LinkedHashMap<>();
String name = text(row, "chargeName", "feeName");
if (StringUtils.isNotBlank(name)) {
fee.put("feeName", name);
}
if (row.get("unitPrice") != null) {
fee.put("unitPrice", row.get("unitPrice"));
}
if (row.get("quantity") != null) {
fee.put("quantity", row.get("quantity"));
}
if (row.get("amount") != null) {
fee.put("amount", row.get("amount"));
}
if (row.get("currency") != null) {
fee.put("currency", row.get("currency"));
}
if (row.get("unit") != null) {
fee.put("unit", row.get("unit"));
}
if (!fee.isEmpty()) {
asFees.add(fee);
}
}
if (!asFees.isEmpty()) {
req.put("feeItems", asFees);
}
}
}
@@ -740,10 +839,24 @@ public class InquiryTmsCabinService {
return true;
}
/**
* 本单真实 TMS quoteId:优先非人工报价行;人工覆盖后再锁仍要带原编号。
* 跳过 QT-WO 假编号。
*/
static String realTmsQuoteId(List<InquiryQuote> rows, String workOrderNo) {
if (rows == null) {
return "";
}
for (InquiryQuote row : rows) {
Map<String, Object> payload = payloadOf(row);
if (isManualQuote(payload) && !isFakeManualLockQuote(payload)) {
continue;
}
String id = resolveQuoteId(payload, workOrderNo);
if (StringUtils.isNotBlank(id)) {
return id;
}
}
for (InquiryQuote row : rows) {
String id = resolveQuoteId(payloadOf(row), workOrderNo);
if (StringUtils.isNotBlank(id)) {
@@ -753,6 +866,51 @@ public class InquiryTmsCabinService {
return "";
}
/**
* MANUAL 出站必填校验。缺字段直接失败,禁止 HMAC 空壳打 TMS(会 1001)。
* 返回中文原因;齐了返回空串。
*/
static String validateManualLockOutbound(Map<String, Object> req) {
if (req == null) {
return "锁舱参数为空";
}
java.util.List<String> missing = new ArrayList<>();
if (StringUtils.isBlank(text(req, "optionNo", "option_no"))) {
missing.add("舱位编号optionNo");
}
if (StringUtils.isBlank(text(req, "airline", "airlineCode"))) {
missing.add("航司airline");
}
if (StringUtils.isBlank(text(req, "chargeableWeightKg", "chargeable_weight_kg"))) {
missing.add("计费重chargeableWeightKg");
}
if (StringUtils.isBlank(text(req, "flightNo", "flight_no"))) {
missing.add("航班号flightNo");
}
if (StringUtils.isBlank(text(req, "operatorName", "operator_name"))) {
missing.add("操作人operatorName");
}
if (StringUtils.isBlank(text(req, "validUntil", "valid_until"))) {
missing.add("有效期validUntil");
}
if (missing.isEmpty()) {
return "";
}
return "锁舱参数不完整,缺少:" + String.join("、", missing)
+ "。请按「AIR-OPT01 CZ 航班CZ327」补舱位、航司和航班号后再锁。";
}
/**
* 航司名只有恰好两位字母时才当代码;「南航」等中文名不当 airline 出站。
*/
static String airlineCodeOrBlank(String raw) {
String text = StringUtils.trimToEmpty(raw).toUpperCase();
if (text.length() == 2 && Character.isLetter(text.charAt(0)) && Character.isLetter(text.charAt(1))) {
return text;
}
return "";
}
private List<InquiryQuote> quoteRows(String workOrderNo) {
if (StringUtils.isBlank(workOrderNo)) {
return new ArrayList<>();
@@ -893,6 +1051,10 @@ public class InquiryTmsCabinService {
item.put("currency", currency);
}
String unit = text(row, "unit", "单位");
// 手工报价常只有金额无单位;空运运输费锁舱必须带 unit(WO007:单位未传 TMS)
if (QuoteTemplateExcelSupport.isAirWeightFeeName(name)) {
unit = QuoteTemplateExcelSupport.normalizeWeightUnit(unit);
}
if (StringUtils.isNotBlank(unit)) {
item.put("unit", unit);
}
@@ -20,9 +20,12 @@ import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
/**
@@ -380,8 +383,13 @@ public class InquiryTmsQueryService {
quote.put("landSegments", json);
// 同步一份 route_rows,字段名对齐填表(transit_time / salePrice 等)
List<Map<String, String>> rows = normalizeLandSegmentRows(raw);
// 腿上缺燃油时,从同段 feeItems 补(TMS 有时只把 fuelSurchargeRate 挂在费用行上)
enrichLandFuelTaxFromFeeItems(rows, data == null ? null : data.get("feeItems"),
data == null ? null : data.get("fee_items"));
if (!rows.isEmpty()) {
quote.put("route_rows", JSON.toJSONString(rows));
// 回写补全后的腿,避免后续只读 landSegments 时又丢燃油
quote.put("landSegments", JSON.toJSONString(rows));
}
// feeItems 为空时,用各腿成本补运输费。顶层总价会被误收成「空运费」,陆运要换掉。
String feeLines = quote.get("fee_lines");
@@ -484,6 +492,21 @@ public class InquiryTmsQueryService {
putExtra(row, pair[1], firstText(seg.get(pair[0]), seg.get(pair[1])));
putExtra(row, pair[0], firstText(seg.get(pair[0])));
}
// 陆运 TMS:fuelSurchargeRate=燃油附加费率;rate=税率;rateFlag=是否含税(1是0否)。
// 只投影 landSegments,禁止拿 fxRates.rate(汇率)冒充税率。
String fuelRate = formatLandPercentRate(firstText(
seg.get("fuelSurchargeRate"), seg.get("fuel_surcharge_rate")));
putExtra(row, "fuel_surcharge_rate", fuelRate);
putExtra(row, "fuelSurchargeRate", fuelRate);
String taxRate = formatLandTaxRate(firstText(
seg.get("rate"), seg.get("tax_rate"), seg.get("taxRate")));
putExtra(row, "tax_rate", taxRate);
putExtra(row, "taxRate", taxRate);
putExtra(row, "rate", firstText(seg.get("rate")));
String rateFlagRaw = firstText(seg.get("rateFlag"), seg.get("rate_flag"));
putExtra(row, "rateFlag", rateFlagRaw);
putExtra(row, "rate_flag", rateFlagRaw);
putExtra(row, "tax_included", formatLandTaxIncluded(rateFlagRaw));
if (StringUtils.isNotBlank(row.get("origin")) || StringUtils.isNotBlank(row.get("destination"))
|| StringUtils.isNotBlank(row.get("amount"))) {
out.add(row);
@@ -783,17 +806,13 @@ public class InquiryTmsQueryService {
continue;
}
Map<?, ?> opt = (Map<?, ?>) optObj;
Object charges = first(opt.get("departureCharges"), opt.get("departure_charges"),
opt.get("charges"), opt.get("feeItems"));
if (!(charges instanceof List)) {
continue;
}
// 合并 departureCharges + feeItems,避免只取附加费丢掉空运费
List<Map<?, ?>> charges = mergeAirOptionChargeMaps(opt);
String optCcy = firstText(opt.get("currency"), headerCurrency);
for (Object one : (List<?>) charges) {
if (!(one instanceof Map)) {
for (Map<?, ?> ch : charges) {
if (ch == null) {
continue;
}
Map<?, ?> ch = (Map<?, ?>) one;
String name = firstText(ch.get("chargeName"), ch.get("feeName"), ch.get("name"));
String unitPrice = firstText(ch.get("unitPrice"), ch.get("unit_price"), ch.get("salePrice"), ch.get("amount"));
if (StringUtils.isBlank(name) || StringUtils.isBlank(unitPrice)) {
@@ -810,6 +829,8 @@ public class InquiryTmsQueryService {
// 先把单价写入 amount;运输费会在 enrich 里改成 单价×计费重
addFeeLine(out, name, unitPrice, lineCcy, extras);
}
// departureCharges 只有附加费时,用舱位 salePrice 补空运费(与出单 parse 对齐)
injectAirFreightFeeLineIfMissing(out, opt, headerCurrency);
// 通常只用首个舱位选项的费用明细
if (!out.isEmpty()) {
break;
@@ -818,6 +839,93 @@ public class InquiryTmsQueryService {
return out;
}
/** 合并舱位 departureCharges / feeItems,同名去重。 */
@SuppressWarnings("unchecked")
static List<Map<?, ?>> mergeAirOptionChargeMaps(Map<?, ?> opt) {
List<Map<?, ?>> out = new ArrayList<>();
if (opt == null) {
return out;
}
Set<String> seen = new HashSet<>();
for (Object key : new Object[]{"departureCharges", "departure_charges", "charges", "feeItems", "fee_items"}) {
Object raw = opt.get(key);
if (!(raw instanceof List)) {
continue;
}
for (Object one : (List<?>) raw) {
if (!(one instanceof Map)) {
continue;
}
Map<?, ?> ch = (Map<?, ?>) one;
String name = firstText(ch.get("chargeName"), ch.get("feeName"), ch.get("name"));
if (StringUtils.isBlank(name)) {
continue;
}
String dedupe = name.trim().toLowerCase(Locale.ROOT);
if (!seen.add(dedupe)) {
continue;
}
out.add(ch);
}
}
return out;
}
/**
* 查价投影 fee_lines:明细无运输/空运费时,用舱位 salePrice/unitPrice 注入。
* 与 QuoteTemplateExcelSupport.injectAirFreightLineIfMissing 口径一致。
*/
static void injectAirFreightFeeLineIfMissing(List<Map<String, String>> lines, Map<?, ?> opt, String headerCurrency) {
if (lines == null || opt == null) {
return;
}
for (Map<String, String> line : lines) {
if (line != null && isAirWeightFeeName(line.get("name"))) {
return;
}
}
String unitPrice = firstText(opt.get("unitPrice"), opt.get("unit_price"), opt.get("pricePerKg"), opt.get("freightRate"));
String salePrice = firstText(opt.get("salePrice"), opt.get("sale_price"), opt.get("totalSalePrice"),
opt.get("airFreight"), opt.get("freight"));
String cw = firstText(opt.get("chargeableWeightKg"), opt.get("chargeable_weight_kg"));
String amount = "";
String price = unitPrice;
if (StringUtils.isNotBlank(unitPrice) && StringUtils.isNotBlank(cw)) {
amount = multiplyDecimal(unitPrice, cw);
} else if (StringUtils.isNotBlank(salePrice) && !"-".equals(salePrice)) {
amount = salePrice;
if (StringUtils.isBlank(price) && StringUtils.isNotBlank(cw)) {
try {
java.math.BigDecimal a = new java.math.BigDecimal(salePrice.trim().replace(",", ""));
java.math.BigDecimal b = new java.math.BigDecimal(cw.trim().replace(",", ""));
if (b.compareTo(java.math.BigDecimal.ZERO) != 0) {
price = a.divide(b, 4, java.math.RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
}
} catch (Exception ignored) {
price = "";
}
}
}
if (StringUtils.isBlank(amount) || "-".equals(amount)) {
return;
}
String ccy = firstText(opt.get("currency"), headerCurrency);
Map<String, String> extras = new LinkedHashMap<>();
putExtra(extras, "project", "空运段");
putExtra(extras, "unit_price", StringUtils.isNotBlank(price) ? price : amount);
if (StringUtils.isNotBlank(cw)) {
putExtra(extras, "quantity", cw);
putExtra(extras, "unit", "KG");
}
// 先 append 再挪到最前:空运段在附加费之前
int before = lines.size();
addFeeLine(lines, "空运费", amount, ccy, extras);
if (lines.size() > before) {
Map<String, String> injected = lines.remove(lines.size() - 1);
lines.add(0, injected);
}
}
/**
* 空运运输费:单价 × 计费重 = 行金额。
* <p>
@@ -1004,6 +1112,154 @@ public class InquiryTmsQueryService {
}
}
/**
* 陆运腿缺燃油附加费率/税率时,按同段 feeItems 补。
* <p>
* 为何:TMS 偶发只在费用行带 fuelSurchargeRate,腿上为 null;出单侧栏就会空着。
* 不编造;feeItems 也没有则保持空。
*/
@SuppressWarnings("unchecked")
static void enrichLandFuelTaxFromFeeItems(List<Map<String, String>> rows, Object... feeSources) {
if (rows == null || rows.isEmpty() || feeSources == null) {
return;
}
List<Map<?, ?>> fees = new ArrayList<>();
for (Object src : feeSources) {
if (src == null) {
continue;
}
Object parsed = src;
if (src instanceof String) {
try {
parsed = JSON.parse(String.valueOf(src));
} catch (Exception ex) {
continue;
}
}
if (parsed instanceof List) {
for (Object one : (List<?>) parsed) {
if (one instanceof Map) {
fees.add((Map<?, ?>) one);
}
}
}
}
if (fees.isEmpty()) {
return;
}
for (Map<String, String> row : rows) {
if (row == null) {
continue;
}
boolean needFuel = StringUtils.isBlank(row.get("fuel_surcharge_rate"))
&& StringUtils.isBlank(row.get("fuelSurchargeRate"));
boolean needTax = StringUtils.isBlank(row.get("tax_rate"))
&& StringUtils.isBlank(row.get("taxRate"));
if (!needFuel && !needTax) {
continue;
}
String seg = firstText(row.get("segmentSequence"), "1");
String leg = firstText(row.get("routeLegSequence"), "");
for (Map<?, ?> fee : fees) {
String feeSeg = firstText(fee.get("segmentSequence"), fee.get("segment_sequence"), "1");
String feeLeg = firstText(fee.get("routeLegSequence"), fee.get("route_leg_sequence"), "");
if (!seg.equals(feeSeg)) {
continue;
}
if (StringUtils.isNotBlank(leg) && StringUtils.isNotBlank(feeLeg) && !leg.equals(feeLeg)) {
continue;
}
if (needFuel) {
String fuel = formatLandPercentRate(firstText(
fee.get("fuelSurchargeRate"), fee.get("fuel_surcharge_rate")));
if (StringUtils.isNotBlank(fuel)) {
row.put("fuel_surcharge_rate", fuel);
row.put("fuelSurchargeRate", fuel);
needFuel = false;
}
}
if (needTax) {
// 费用行 rate 是税率;禁止拿无关字段冒充
String tax = formatLandTaxRate(firstText(fee.get("rate"), fee.get("tax_rate"), fee.get("taxRate")));
if (StringUtils.isNotBlank(tax)) {
row.put("tax_rate", tax);
row.put("taxRate", tax);
needTax = false;
}
}
if (!needFuel && !needTax) {
break;
}
}
}
}
/**
* 燃油附加费率展示:数字带 %;已带 % 保留。空值不编造。
*/
static String formatLandPercentRate(String raw) {
if (StringUtils.isBlank(raw) || "-".equals(raw) || "null".equalsIgnoreCase(raw.trim())) {
return "";
}
String text = raw.trim();
if (text.contains("%")) {
return text;
}
if (text.matches("-?\\d+(\\.\\d+)?")) {
if (text.contains(".")) {
text = text.replaceAll("0+$", "").replaceAll("\\.$", "");
}
return text + "%";
}
return text;
}
/**
* 税率 rate 展示:TMS 常回小数(0.09=9%);大于 1 的按百分点(10=10%)。
*/
static String formatLandTaxRate(String raw) {
if (StringUtils.isBlank(raw) || "-".equals(raw) || "null".equalsIgnoreCase(raw.trim())) {
return "";
}
String text = raw.trim();
if (text.contains("%")) {
return text;
}
if (!text.matches("-?\\d+(\\.\\d+)?")) {
return text;
}
try {
java.math.BigDecimal n = new java.math.BigDecimal(text);
java.math.BigDecimal abs = n.abs();
if (abs.compareTo(java.math.BigDecimal.ZERO) > 0
&& abs.compareTo(java.math.BigDecimal.ONE) <= 0) {
n = n.multiply(java.math.BigDecimal.TEN).multiply(java.math.BigDecimal.TEN)
.stripTrailingZeros();
}
String out = n.stripTrailingZeros().toPlainString();
return out + "%";
} catch (RuntimeException ex) {
return text;
}
}
/**
* rateFlag:是否含税。字典 1=是、0=否。
*/
static String formatLandTaxIncluded(String raw) {
if (StringUtils.isBlank(raw) || "-".equals(raw) || "null".equalsIgnoreCase(raw.trim())) {
return "";
}
String text = raw.trim();
if ("1".equals(text) || "true".equalsIgnoreCase(text) || "是".equals(text) || "含税".equals(text)) {
return "含税";
}
if ("0".equals(text) || "false".equalsIgnoreCase(text) || "否".equals(text) || "不含税".equals(text)) {
return "不含税";
}
return text;
}
private static void addFeeLine(List<Map<String, String>> lines, String name, String amount,
String currency, Map<String, String> extras) {
TmsQuoteCurrency.Money money = TmsQuoteCurrency.split(amount, currency);
@@ -69,7 +69,7 @@ VALUES
('brv10000000000000000000000000038','deal','已成交','deal.recorded_won','销售选择「成交」','已记录为「已成交」。工单 {{ticket_no}} 已关闭智能体跟进。',1,1,'admin',NOW()),
('brv10000000000000000000000000039','negotiating','协商中','negotiating.recorded','成交跟进中选择「协商中」','已记录为「协商中」。已顺延三个工作日,{{followup_when}}的9:00再次发起成交状态询问。',1,1,'admin',NOW()),
('brv10000000000000000000000000040','lost','未成交','lost.ask_reason','成交跟进中选择「未成交」且未写原因','已记录为「未成交」。请补充未成交原因。',1,1,'admin',NOW()),
('brv10000000000000000000000000041','lost','未成交','lost.reason_ack','销售回复未成交原因','已记下未成交原因:{{lost_reason}}。',1,2,'admin',NOW()),
('brv10000000000000000000000000041','lost','未成交','lost.reason_ack','销售回复未成交原因','已将未成交原因“{{lost_reason}}”记录在后台,工单 {{ticket_no}}已关闭,智能体不再跟进该工单,请悉知。',1,2,'admin',NOW()),
('brv10000000000000000000000000042','closed','已关闭','closed.air_cannot_activate','空运工单已是终态仍要激活','工单{{ticket_no}}已是「{{status}}」,不能再激活。',1,1,'admin',NOW()),
('brv10000000000000000000000000043','sys-ex','系统异常','sys.llm_fail','大模型调用失败(销售侧)','大模型服务异常,IT排查中...',1,1,'admin',NOW()),
('brv10000000000000000000000000044','sys-ex','系统异常','sys.tms_fail','TMS 接口失败(销售侧)','TMS接口异常,IT运维排查中...',1,2,'admin',NOW()),
@@ -2,10 +2,14 @@ package org.jeecg.modules.inquiry.template;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
@@ -35,6 +39,31 @@ public class QuoteTemplateFillTest {
assertEquals("14669.60", rows.getJSONObject(0).getString("amount"));
}
@Test
public void manualAirFeesOnlyAmountFillsUnitPriceQtyAndUnit() {
// WO020:手工只有金额 → 空运费补 KG/1/单价;增点费补 票/1/单价
java.util.List<Map<String, String>> lines = new java.util.ArrayList<>();
Map<String, String> air = new HashMap<>();
air.put("name", "空运费");
air.put("amount", "150");
air.put("currency", "CNY");
lines.add(air);
Map<String, String> add = new HashMap<>();
add.put("name", "增点费");
add.put("amount", "200");
add.put("currency", "CNY");
add.put("project", "空运段"); // 误归空运段也要纠正
lines.add(add);
QuoteTemplateExcelSupport.enrichAirWeightFeeRows(lines, "", "KG");
assertEquals("KG", lines.get(0).get("unit"));
assertEquals("1", lines.get(0).get("quantity"));
assertEquals("150", lines.get(0).get("unit_price"));
assertEquals("票", lines.get(1).get("unit"));
assertEquals("1", lines.get(1).get("quantity"));
assertEquals("200", lines.get(1).get("unit_price"));
assertEquals("起运港", lines.get(1).get("project"));
}
@Test
public void parseFeeLinesDoubleEncoded() {
JSONArray rows = QuoteTemplateExcelSupport.parseFeeRows("[{\"name\":\"空运费\",\"amount\":\"14669.60\"}]");
@@ -239,8 +268,8 @@ public class QuoteTemplateFillTest {
}
/**
* 回归:无 TMS 费用行时,费用表「项目=起运港」不得把 pol 写进右侧「费用名称」。
* 对应 WO202609230026 空运协同出单:空运段旁费用名称被写成「广州」。
* 回归:无 TMS 费用行时,不得把 pol 写进费用名称;
* 并保留模板项目骨架「空运段/起运港」(图2),禁止掏空项目列。
*/
@Test
public void airNoTmsMustNotWritePolIntoFeeNameColumn() throws Exception {
@@ -264,13 +293,17 @@ public class QuoteTemplateFillTest {
head.createCell(7).setCellValue("备注");
org.apache.poi.ss.usermodel.Row airSeg = sheet.createRow(16);
airSeg.createCell(0).setCellValue("空运段");
airSeg.createCell(1).setCellValue("");
airSeg.createCell(1).setCellValue("空运费");
org.apache.poi.ss.usermodel.Row polSeg = sheet.createRow(17);
polSeg.createCell(0).setCellValue("起运港");
polSeg.createCell(1).setCellValue("");
org.apache.poi.ss.usermodel.Row otherSeg = sheet.createRow(18);
polSeg.createCell(1).setCellValue("操作费");
org.apache.poi.ss.usermodel.Row destSeg = sheet.createRow(18);
destSeg.createCell(0).setCellValue("目的港");
destSeg.createCell(1).setCellValue("目的港派送费");
org.apache.poi.ss.usermodel.Row otherSeg = sheet.createRow(19);
otherSeg.createCell(0).setCellValue("其他");
otherSeg.createCell(1).setCellValue("");
otherSeg.createCell(1).setCellValue("*其他杂费");
otherSeg.createCell(7).setCellValue("发生时收取");
try (java.io.OutputStream os = Files.newOutputStream(src)) {
wb.write(os);
}
@@ -297,13 +330,22 @@ public class QuoteTemplateFillTest {
b16 = fmt.formatCellValue(sheet.getRow(16).getCell(1));
b17 = fmt.formatCellValue(sheet.getRow(17).getCell(1));
b18 = fmt.formatCellValue(sheet.getRow(18).getCell(1));
String b19 = fmt.formatCellValue(sheet.getRow(19).getCell(1));
String h19 = fmt.formatCellValue(sheet.getRow(19).getCell(7));
String cargoPol = fmt.formatCellValue(sheet.getRow(5).getCell(1));
assertTrue(cargoPol.contains("广州"), "货物区起运港应写入广州,实际=" + cargoPol);
assertFalse(b16.contains("广州"), "空运段旁费用名称不应是起运港,实际=" + b16);
assertFalse(b17.contains("广州"), "起运港项目旁费用名称不应是起运港,实际=" + b17);
assertFalse(b18.contains("广州"), "其他旁费用名称不应是起运港,实际=" + b18);
assertEquals("起运港", fmt.formatCellValue(sheet.getRow(17).getCell(0)));
assertFalse(b16.contains("广州"), "费用名称不应是起运港,实际=" + b16);
assertFalse(b17.contains("广州"), "费用名称不应是起运港,实际=" + b17);
assertFalse(b18.contains("广州"), "费用名称不应是起运港,实际=" + b18);
// 无 fee_rows:项目骨架保留;样例费目名/备注清掉(有费用的才显示行)
assertEquals("空运段", fmt.formatCellValue(sheet.getRow(16).getCell(0)));
assertEquals("起运港", fmt.formatCellValue(sheet.getRow(17).getCell(0)));
assertEquals("目的港", fmt.formatCellValue(sheet.getRow(18).getCell(0)));
assertEquals("", b16.trim(), "无费用时空运费样例名应清空,实际=" + b16);
assertEquals("", b17.trim(), "无费用时操作费样例名应清空,实际=" + b17);
assertEquals("", b18.trim(), "无费用时目的港派送费样例名应清空,实际=" + b18);
assertEquals("", b19.trim(), "无费用时其他杂费样例名应清空,实际=" + b19);
assertEquals("", h19.trim(), "无费用时样例备注应清空,实际=" + h19);
} finally {
Files.deleteIfExists(src);
Files.deleteIfExists(out);
@@ -854,6 +896,104 @@ public class QuoteTemplateFillTest {
assertEquals("16670", QuoteTemplateExcelSupport.feeQuantityOrDefault("16670", "运输费"));
}
/**
* WO014:departureCharges 只有增点/拆板时,必须注入空运费,且项目列归类正确。
*/
@Test
public void parseAirDepartureChargesInjectsFreightAndProjects() {
String airOptions = "["
+ "{\"optionNo\":\"AIR-OPT01\",\"salePrice\":4750.95,\"currency\":\"CNY\","
+ "\"chargeableWeightKg\":500.1,"
+ "\"departureCharges\":["
+ "{\"chargeName\":\"增点费\",\"unitPrice\":100.0,\"unit\":\"点\",\"currency\":\"CNY\"},"
+ "{\"chargeName\":\"拆板费\",\"unitPrice\":100.0,\"unit\":\"板数\",\"currency\":\"USD\"}"
+ "]}]";
JSONArray rows = QuoteTemplateExcelSupport.parseAirDepartureChargeRows(
airOptions, null, "500.1", "CNY");
assertEquals(3, rows.size());
assertEquals("空运费", rows.getJSONObject(0).getString("name"));
assertEquals("空运段", rows.getJSONObject(0).getString("project"));
assertEquals("4750.95", rows.getJSONObject(0).getString("amount"));
assertEquals("增点费", rows.getJSONObject(1).getString("name"));
assertEquals("起运港", rows.getJSONObject(1).getString("project"));
assertEquals("拆板费", rows.getJSONObject(2).getString("name"));
assertEquals("起运港", rows.getJSONObject(2).getString("project"));
}
/**
* 映射未标 project 列时,表头「项目」仍要写入,增点费不能留在模板样例「空运段」。
*/
@Test
public void airFeeProjectColumnFilledFromHeaderWhenMappingOmitsIt() throws Exception {
Path src = Files.createTempFile("quote-air-proj-src", ".xlsx");
Path out = Files.createTempFile("quote-air-proj-out", ".xlsx");
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("Sheet2");
org.apache.poi.ss.usermodel.Row head = sheet.createRow(15);
head.createCell(0).setCellValue("项目");
head.createCell(1).setCellValue("费用名称");
head.createCell(2).setCellValue("单位");
head.createCell(3).setCellValue("币别");
head.createCell(4).setCellValue("单价");
head.createCell(5).setCellValue("数量");
head.createCell(6).setCellValue("金额");
org.apache.poi.ss.usermodel.Row r1 = sheet.createRow(16);
r1.createCell(0).setCellValue("空运段");
r1.createCell(1).setCellValue("样例费");
r1.createCell(6).setCellValue(1.0);
org.apache.poi.ss.usermodel.Row r2 = sheet.createRow(17);
r2.createCell(0).setCellValue("起运港");
r2.createCell(1).setCellValue("样例2");
r2.createCell(6).setCellValue(1.0);
org.apache.poi.ss.usermodel.Row total = sheet.createRow(22);
total.createCell(0).setCellValue("预估费用");
total.createCell(6).setCellFormula("SUM(G17:G22)");
try (java.io.OutputStream os = Files.newOutputStream(src)) {
wb.write(os);
}
}
JSONObject mapping = new JSONObject();
mapping.put("fields", new JSONObject());
JSONObject region = new JSONObject(true);
region.put("id", "air_fee_detail");
region.put("anchor", "Sheet2!A17");
region.put("stopAtText", java.util.Collections.singletonList("预估费用"));
JSONObject cols = new JSONObject(true);
cols.put("name", "B");
cols.put("unit", "C");
cols.put("currency", "D");
cols.put("unit_price", "E");
cols.put("quantity", "F");
cols.put("amount", "G");
// 故意不写 project,验证 mergeFeeColumnsFromHeader 补 A 列
region.put("columns", cols);
mapping.put("feeRegions", new JSONArray(java.util.Collections.singletonList(region)));
JSONObject facts = new JSONObject(true);
facts.put("total_amount", "5001");
facts.put("currency", "CNY");
facts.put("fee_rows", QuoteTemplateExcelSupport.parseAirDepartureChargeRows(
"[{\"salePrice\":4750.95,\"currency\":\"CNY\",\"chargeableWeightKg\":500.1,"
+ "\"departureCharges\":["
+ "{\"chargeName\":\"增点费\",\"unitPrice\":100.0,\"unit\":\"点\",\"currency\":\"CNY\"},"
+ "{\"chargeName\":\"拆板费\",\"unitPrice\":100.0,\"unit\":\"板数\",\"currency\":\"USD\"}"
+ "]}]",
null, "500.1", "CNY"));
QuoteTemplateExcelSupport.fillWorkbook(src, out, mapping, facts);
try (Workbook got = new XSSFWorkbook(Files.newInputStream(out))) {
Sheet sheet = got.getSheet("Sheet2");
DataFormatter fmt = new DataFormatter();
assertEquals("空运段", fmt.formatCellValue(sheet.getRow(16).getCell(0)));
assertEquals("空运费", fmt.formatCellValue(sheet.getRow(16).getCell(1)));
assertEquals("起运港", fmt.formatCellValue(sheet.getRow(17).getCell(0)));
assertEquals("增点费", fmt.formatCellValue(sheet.getRow(17).getCell(1)));
assertEquals("起运港", fmt.formatCellValue(sheet.getRow(18).getCell(0)));
assertEquals("拆板费", fmt.formatCellValue(sheet.getRow(18).getCell(1)));
} finally {
Files.deleteIfExists(src);
Files.deleteIfExists(out);
}
}
/**
* 出单后必须 A4 水平居中,抬头行高够放下中英文公司名。
* 否则转 PDF 会顶部裁字、整页偏左。
@@ -1340,6 +1480,81 @@ public class QuoteTemplateFillTest {
}
}
/**
* WO202610080043:TMS weightPrices 只有 min/max、整票 costPrice=18200(计价单位:次)。
* 询价毛重 2KG 落入 2-500KG 档时写入 18200;其它公斤列保持空;有真实档内单价时不走此回退。
*/
@Test
public void landGroupageEmptyWeightBandsWritesFlatFeeIntoCargoBandOnly() throws Exception {
Path src = Files.createTempFile("quote-land-groupage-flat", ".xlsx");
Path out = Files.createTempFile("quote-land-groupage-flat-out", ".xlsx");
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("跨境集拼");
org.apache.poi.ss.usermodel.Row matrix = row(sheet, 7);
matrix.createCell(1).setCellValue("始发地");
matrix.createCell(2).setCellValue("目的地");
matrix.createCell(3).setCellValue("最低收费");
matrix.createCell(4).setCellValue("2-500KG");
matrix.createCell(5).setCellValue("501-1000KG");
matrix.createCell(6).setCellValue("1001-3000KG");
matrix.createCell(7).setCellValue("3001-5000KG");
matrix.createCell(8).setCellValue("5001KG以上");
row(sheet, 9);
try (java.io.OutputStream os = Files.newOutputStream(src)) {
wb.write(os);
}
}
JSONObject route = new JSONObject(true);
route.put("origin", "凉山-春疆货场");
route.put("destination", "湖北省-武汉市");
route.put("currency", "CNY");
route.put("costPrice", "18200.00");
route.put("amount", "18200.00");
route.put("weightPrices", JSONArray.parseArray(
"[{\"min\":2,\"max\":500},{\"min\":501,\"max\":1000},{\"min\":1001,\"max\":3000},"
+ "{\"min\":3001,\"max\":5000},{\"min\":5001}]"));
JSONArray routeRows = new JSONArray();
routeRows.add(route);
JSONObject mapping = new JSONObject(true);
mapping.put("sheet", "跨境集拼");
JSONArray regions = new JSONArray();
JSONObject region = new JSONObject(true);
region.put("headerRow", 8);
region.put("dataStartRow", 10);
JSONObject columns = new JSONObject(true);
columns.put("origin", "B");
columns.put("destination", "C");
JSONObject vehicleRates = new JSONObject(true);
vehicleRates.put("最低收费", "D");
vehicleRates.put("2-500KG", "E");
vehicleRates.put("501-1000KG", "F");
vehicleRates.put("1001-3000KG", "G");
vehicleRates.put("3001-5000KG", "H");
vehicleRates.put("5001KG以上", "I");
columns.put("vehicleRates", vehicleRates);
region.put("columns", columns);
regions.add(region);
mapping.put("routeRegions", regions);
JSONObject facts = new JSONObject(true);
facts.put("毛重", "2");
facts.put("route_rows", routeRows);
QuoteTemplateExcelSupport.fillWorkbook(src, out, mapping, facts);
try (Workbook filled = new XSSFWorkbook(Files.newInputStream(out))) {
Sheet sheet = filled.getSheetAt(0);
assertEquals("凉山-春疆货场", read(sheet, 9, 1));
assertEquals("湖北省-武汉市", read(sheet, 9, 2));
assertEquals("18200", normalizeMoney(read(sheet, 9, 3)));
assertEquals("18200", normalizeMoney(read(sheet, 9, 4)));
assertEquals("", read(sheet, 9, 5));
assertEquals("", read(sheet, 9, 6));
assertEquals("", read(sheet, 9, 7));
assertEquals("", read(sheet, 9, 8));
} finally {
Files.deleteIfExists(src);
Files.deleteIfExists(out);
}
}
/**
* 销售没填客户名称时,客户名称格保持空白,不能写成业务员。
* 询价条带的时效写在表头下一行;公斤分档价按 weightPrices 落入各列。
@@ -1736,6 +1951,133 @@ public class QuoteTemplateFillTest {
}
}
/**
* 跨境整车分段切片后仍须带上车型与运价;尺寸副表头行不能被 4000 盖掉,运价写在下一行。
* WO006:单腿 vehicleType=3T 时,国内写 3T 列,国外段换算成 3.5T 再写,不能留空。
*/
@Test
public void landCrossBorderFtlKeepsVehiclePriceAfterOdSlice() throws Exception {
Path src = Files.createTempFile("quote-land-cb-price-src", ".xlsx");
Path out = Files.createTempFile("quote-land-cb-price-out", ".xlsx");
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("跨境整车");
row(sheet, 5).createCell(0).setCellValue("一、国内段报价");
org.apache.poi.ss.usermodel.Row head1 = row(sheet, 7);
head1.createCell(1).setCellValue("起始地");
head1.createCell(2).setCellValue("目的地");
head1.createCell(3).setCellValue("3T");
head1.createCell(4).setCellValue("5T");
org.apache.poi.ss.usermodel.Row dim1 = row(sheet, 8);
dim1.createCell(3).setCellValue("4.1*2.1*2.3M");
dim1.createCell(4).setCellValue("6.5*2.4*2.5M");
row(sheet, 24).createCell(0).setCellValue("二、境外报价");
org.apache.poi.ss.usermodel.Row head2 = row(sheet, 26);
head2.createCell(1).setCellValue("起始地");
head2.createCell(2).setCellValue("目的地");
head2.createCell(3).setCellValue("1.25T");
head2.createCell(4).setCellValue("2.5T");
head2.createCell(5).setCellValue("3.5T");
org.apache.poi.ss.usermodel.Row dim2 = row(sheet, 27);
dim2.createCell(3).setCellValue("2.8x1.5x1.6M");
dim2.createCell(4).setCellValue("3.50x1.6x1.6M");
dim2.createCell(5).setCellValue("4.2x1.8x1.8M");
try (java.io.OutputStream os = Files.newOutputStream(src)) {
wb.write(os);
}
}
JSONObject mapping = new JSONObject(true);
mapping.put("sheet", "跨境整车");
JSONArray regions = new JSONArray();
JSONObject inland = new JSONObject(true);
inland.put("title", "国内段报价");
inland.put("headerRow", 8);
inland.put("dataStartRow", 8);
JSONObject cols1 = new JSONObject(true);
cols1.put("origin", "B");
cols1.put("destination", "C");
JSONObject rates1 = new JSONObject(true);
rates1.put("3T", "D");
rates1.put("5T", "E");
cols1.put("vehicleRates", rates1);
inland.put("columns", cols1);
regions.add(inland);
JSONObject overseas = new JSONObject(true);
overseas.put("title", "境外报价");
overseas.put("headerRow", 27);
overseas.put("dataStartRow", 27);
JSONObject cols2 = new JSONObject(true);
cols2.put("origin", "B");
cols2.put("destination", "C");
JSONObject rates2 = new JSONObject(true);
rates2.put("1.25T", "D");
rates2.put("2.5T", "E");
rates2.put("3.5T", "F");
cols2.put("vehicleRates", rates2);
overseas.put("columns", cols2);
regions.add(overseas);
mapping.put("routeRegions", regions);
JSONObject facts = new JSONObject(true);
facts.put("origin", "深圳");
facts.put("destination", "春疆货场");
facts.put("currency", "CNY");
facts.put("route_rows",
"[{\"origin\":\"广东省-深圳市\",\"destination\":\"谅山-春疆货场\","
+ "\"vehicleType\":\"3T\",\"amount\":\"4000.00\",\"currency\":\"CNY\"}]");
QuoteTemplateExcelSupport.fillWorkbook(src, out, mapping, facts);
try (Workbook filled = new XSSFWorkbook(Files.newInputStream(out))) {
Sheet sheet = filled.getSheetAt(0);
assertEquals("4.1*2.1*2.3M", read(sheet, 8, 3));
assertEquals("广东省-深圳市", read(sheet, 9, 1));
assertEquals("", read(sheet, 9, 2));
assertEquals("4000", normalizeMoney(read(sheet, 9, 3)));
assertEquals("", read(sheet, 9, 4));
assertEquals("2.8x1.5x1.6M", read(sheet, 27, 3));
assertEquals("", read(sheet, 28, 1));
assertEquals("谅山-春疆货场", read(sheet, 28, 2));
assertEquals("", read(sheet, 28, 3));
assertEquals("", read(sheet, 28, 4));
assertEquals("4000", normalizeMoney(read(sheet, 28, 5)));
} finally {
Files.deleteIfExists(src);
Files.deleteIfExists(out);
}
}
/**
* 境外段「起始地」若是白底,对齐表头时不能拿它去刷「币种」灰底。
*/
@Test
public void landCrossBorderFtlAlignHeaderSkipsWhiteOriginFill() throws Exception {
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("跨境整车");
Row head = sheet.createRow(26);
head.createCell(1).setCellValue("起始地");
head.createCell(2).setCellValue("目的地");
head.createCell(3).setCellValue("1.25T");
head.createCell(4).setCellValue("2.5T");
head.createCell(14).setCellValue("币种");
XSSFCellStyle white = (XSSFCellStyle) wb.createCellStyle();
white.setFillForegroundColor(new XSSFColor(new byte[]{(byte) 0xFF, (byte) 0xFF, (byte) 0xFF}, null));
white.setFillPattern(FillPatternType.SOLID_FOREGROUND);
XSSFCellStyle grey = (XSSFCellStyle) wb.createCellStyle();
grey.setFillForegroundColor(new XSSFColor(new byte[]{(byte) 0xCF, (byte) 0xCF, (byte) 0xCF}, null));
grey.setFillPattern(FillPatternType.SOLID_FOREGROUND);
head.getCell(1).setCellStyle(white);
head.getCell(2).setCellStyle(white);
head.getCell(3).setCellStyle(grey);
head.getCell(4).setCellStyle(grey);
head.getCell(14).setCellStyle(grey);
byte[] sample = QuoteTemplateExcelSupport.sampleLandMatrixHeaderFill(sheet, 26);
assertFalse(QuoteTemplateExcelSupport.looksLikeWhiteOrEmptyFill(sample));
assertEquals("CFCFCF", String.format("%02X%02X%02X",
sample[0] & 0xff, sample[1] & 0xff, sample[2] & 0xff));
QuoteTemplateExcelSupport.alignLandNestedHeaderFill(wb);
byte[] currencyFill = QuoteTemplateExcelSupport.readFillRgb(head.getCell(14));
assertEquals("CFCFCF", String.format("%02X%02X%02X",
currencyFill[0] & 0xff, currencyFill[1] & 0xff, currencyFill[2] & 0xff));
}
}
/**
* 跨境整车国内段只写境内起点,境外段只写境外终点,不能两段都写成郑州→吉隆坡。
*/
@@ -1819,6 +2161,234 @@ public class QuoteTemplateFillTest {
}
}
/**
* WO202610120001:route_rows 混有多条备选(不同 segmentSequence),国内/境外段应写完整两段 OD,
* 不能因「整表必须同序列」退回切片导致口岸列空。
*/
@Test
public void landCrossBorderFtlFillsFullOdFromMultiAltRouteRows() throws Exception {
Path src = Files.createTempFile("quote-land-cb-wo001-src", ".xlsx");
Path out = Files.createTempFile("quote-land-cb-wo001-out", ".xlsx");
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("跨境整车");
row(sheet, 5).createCell(0).setCellValue("一、国内段报价");
org.apache.poi.ss.usermodel.Row head1 = row(sheet, 7);
head1.createCell(1).setCellValue("起始地");
head1.createCell(2).setCellValue("目的地");
head1.createCell(3).setCellValue("3T");
row(sheet, 24).createCell(0).setCellValue("二、境外段报价");
org.apache.poi.ss.usermodel.Row head2 = row(sheet, 26);
head2.createCell(1).setCellValue("起始地");
head2.createCell(2).setCellValue("目的地");
head2.createCell(3).setCellValue("3.5T");
try (java.io.OutputStream os = Files.newOutputStream(src)) {
wb.write(os);
}
}
JSONObject mapping = new JSONObject(true);
mapping.put("sheet", "跨境整车");
JSONArray regions = new JSONArray();
JSONObject inland = new JSONObject(true);
inland.put("title", "国内段报价");
inland.put("headerRow", 8);
inland.put("dataStartRow", 8);
JSONObject cols1 = new JSONObject(true);
cols1.put("origin", "B");
cols1.put("destination", "C");
cols1.put("3T", "D");
inland.put("columns", cols1);
regions.add(inland);
JSONObject overseas = new JSONObject(true);
overseas.put("title", "境外段报价");
overseas.put("headerRow", 27);
overseas.put("dataStartRow", 27);
JSONObject cols2 = new JSONObject(true);
cols2.put("origin", "B");
cols2.put("destination", "C");
cols2.put("3.5T", "D");
overseas.put("columns", cols2);
regions.add(overseas);
mapping.put("routeRegions", regions);
JSONObject facts = new JSONObject(true);
facts.put("origin", "上海");
facts.put("destination", "胡志明");
JSONArray rows = new JSONArray();
JSONObject a1 = new JSONObject(true);
a1.put("segmentSequence", "1");
a1.put("routeLegSequence", "1");
a1.put("origin", "上海");
a1.put("destination", "谅山-春疆货场");
a1.put("vehicleType", "3T");
a1.put("costPrice", "7500");
a1.put("currency", "CNY");
rows.add(a1);
JSONObject a2 = new JSONObject(true);
a2.put("segmentSequence", "1");
a2.put("routeLegSequence", "2");
a2.put("origin", "谅山-春疆货场");
a2.put("destination", "胡志明");
a2.put("vehicleType", "3.5T");
a2.put("costPrice", "9600");
a2.put("currency", "CNY");
rows.add(a2);
JSONObject b1 = new JSONObject(true);
b1.put("segmentSequence", "2");
b1.put("routeLegSequence", "1");
b1.put("origin", "上海");
b1.put("destination", "凭祥友谊关口岸");
b1.put("vehicleType", "3T");
b1.put("costPrice", "7000");
rows.add(b1);
JSONObject b2 = new JSONObject(true);
b2.put("segmentSequence", "2");
b2.put("routeLegSequence", "2");
b2.put("origin", "凭祥友谊关口岸");
b2.put("destination", "胡志明");
b2.put("vehicleType", "3T");
b2.put("costPrice", "9000");
rows.add(b2);
facts.put("route_rows", rows);
facts.put("landSegments", rows);
QuoteTemplateExcelSupport.fillWorkbook(src, out, mapping, facts);
try (Workbook filled = new XSSFWorkbook(Files.newInputStream(out))) {
Sheet sheet = filled.getSheetAt(0);
assertEquals("上海", read(sheet, 8, 1));
assertEquals("谅山-春疆货场", read(sheet, 8, 2));
assertEquals("谅山-春疆货场", read(sheet, 27, 1));
assertEquals("胡志明", read(sheet, 27, 2));
} finally {
Files.deleteIfExists(src);
Files.deleteIfExists(out);
}
}
/**
* WO202610080006:跨境整车上传版表头是「时效 | 币种(错行) | 燃油 | 税率 | 含税合计」。
* 起始地不能被费用名「运输费」盖掉;CNY 只能进币种列;燃油附加费率要写到燃油列。
*/
@Test
public void landCrossBorderFtlKeepsOriginCurrencyFuelOnStaggeredHeaders() throws Exception {
Path src = Files.createTempFile("quote-land-cb-wo006-src", ".xlsx");
Path out = Files.createTempFile("quote-land-cb-wo006-out", ".xlsx");
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("跨境整车报价模板");
row(sheet, 4).createCell(0).setCellValue("一、国内段报价");
org.apache.poi.ss.usermodel.Row band1 = row(sheet, 5);
band1.createCell(0).setCellValue("国内段报价");
band1.createCell(1).setCellValue("路线");
band1.createCell(3).setCellValue("车型");
band1.createCell(13).setCellValue("时效");
band1.createCell(15).setCellValue("燃油附加费率");
band1.createCell(16).setCellValue("税率");
band1.createCell(17).setCellValue("含税合计");
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(5, 7, 13, 13));
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(5, 7, 15, 15));
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(5, 7, 16, 16));
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(5, 7, 17, 17));
org.apache.poi.ss.usermodel.Row head1 = row(sheet, 6);
head1.createCell(1).setCellValue("起始地");
head1.createCell(2).setCellValue("目的地");
head1.createCell(3).setCellValue("3T");
head1.createCell(4).setCellValue("5T");
// 币种只印在第 7 行 O 列,和时效/燃油不在同一行(上传版真实布局)
head1.createCell(14).setCellValue("币种");
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(6, 7, 1, 1));
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(6, 7, 2, 2));
row(sheet, 7).createCell(3).setCellValue("4.1*2.1*2.3M");
row(sheet, 23).createCell(0).setCellValue("二、境外报价");
org.apache.poi.ss.usermodel.Row band2 = row(sheet, 24);
band2.createCell(0).setCellValue("境外报价");
band2.createCell(13).setCellValue("时效");
band2.createCell(15).setCellValue("燃油附加费率");
band2.createCell(16).setCellValue("税率");
band2.createCell(17).setCellValue("含税合计");
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(24, 26, 13, 13));
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(24, 26, 15, 15));
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(24, 26, 16, 16));
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(24, 26, 17, 17));
org.apache.poi.ss.usermodel.Row head2 = row(sheet, 25);
head2.createCell(1).setCellValue("起始地");
head2.createCell(2).setCellValue("目的地");
head2.createCell(3).setCellValue("1.25T");
head2.createCell(14).setCellValue("币种");
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(25, 26, 1, 1));
sheet.addMergedRegion(new org.apache.poi.ss.util.CellRangeAddress(25, 26, 2, 2));
try (java.io.OutputStream os = Files.newOutputStream(src)) {
wb.write(os);
}
}
JSONObject mapping = new JSONObject(true);
mapping.put("sheet", "跨境整车报价模板");
// 映射误把 currency 指到燃油列 P9:writeCell 路径也必须拒绝
JSONObject fields = new JSONObject(true);
fields.put("currency", "跨境整车报价模板!P9");
mapping.put("fields", fields);
JSONArray regions = new JSONArray();
JSONObject inland = new JSONObject(true);
inland.put("title", "国内段报价");
// headerRow 只指到带「时效/燃油」的第 6 行;币种在下一行,侧栏扫描必须仍能找到
inland.put("headerRow", 6);
inland.put("dataStartRow", 9);
JSONObject cols1 = new JSONObject(true);
cols1.put("origin", "B");
cols1.put("destination", "C");
inland.put("columns", cols1);
regions.add(inland);
JSONObject overseas = new JSONObject(true);
overseas.put("title", "境外报价");
overseas.put("headerRow", 25);
overseas.put("dataStartRow", 28);
JSONObject cols2 = new JSONObject(true);
cols2.put("origin", "B");
cols2.put("destination", "C");
overseas.put("columns", cols2);
regions.add(overseas);
mapping.put("routeRegions", regions);
// fee_rows 在 routeRegions 之后写:误指运价行时不能把「运输费」盖掉起始地
JSONObject feeRows = new JSONObject(true);
feeRows.put("anchor", "跨境整车报价模板!B9");
JSONObject feeCols = new JSONObject(true);
feeCols.put("name", "B");
feeCols.put("amount", "D");
feeRows.put("columns", feeCols);
mapping.put("fee_rows", feeRows);
JSONObject facts = new JSONObject(true);
facts.put("origin", "深圳");
facts.put("destination", "春疆货场");
facts.put("currency", "CNY");
facts.put("transit_days", "N+1");
facts.put("fuel_surcharge_rate", "8%");
facts.put("tax_rate", "0%");
facts.put("route_rows", QuoteTemplateExcelSupport.parseFeeRows(
"[{\"origin\":\"深圳\",\"destination\":\"春疆货场\",\"currency\":\"CNY\","
+ "\"transit_time\":\"N+1\",\"fuel_surcharge_rate\":\"8%\",\"tax_rate\":\"0%\","
+ "\"amount\":\"1200\"}]"));
facts.put("fee_rows", QuoteTemplateExcelSupport.parseFeeRows(
"[{\"name\":\"运输费\",\"amount\":\"1200\",\"currency\":\"CNY\"}]"));
QuoteTemplateExcelSupport.fillWorkbook(src, out, mapping, facts);
try (Workbook filled = new XSSFWorkbook(Files.newInputStream(out))) {
Sheet sheet = filled.getSheetAt(0);
assertEquals("起始地", read(sheet, 6, 1));
// 国内段只写境内起点;春疆货场是境外终点,不能被「运输费」盖掉起点
assertEquals("深圳", read(sheet, 8, 1));
assertEquals("", read(sheet, 8, 2));
assertEquals("N+1", read(sheet, 8, 13));
assertEquals("CNY", read(sheet, 8, 14));
assertEquals("8%", read(sheet, 8, 15));
assertEquals("0%", read(sheet, 8, 16));
assertFalse("CNY".equalsIgnoreCase(read(sheet, 8, 15)));
assertFalse("运输费".equals(read(sheet, 8, 1)));
assertEquals("币种", read(sheet, 6, 14));
assertEquals("燃油附加费率", read(sheet, 5, 15));
// 境外段只写境外终点
assertEquals("", read(sheet, 27, 1));
assertEquals("春疆货场", read(sheet, 27, 2));
} finally {
Files.deleteIfExists(src);
Files.deleteIfExists(out);
}
}
/**
* 国内整车:4.2米/3T 这类车型费用也是标签右侧,不是海运费目表。
*/
@@ -2231,4 +2801,70 @@ public class QuoteTemplateFillTest {
}
return cell.getStringCellValue();
}
/** 金额格可能是数字 18200.0 或文本 18200.00,统一成去尾零纯数字再比。 */
private static String normalizeMoney(String raw) {
if (raw == null || raw.isBlank() || "-".equals(raw.trim())) {
return "";
}
try {
return new java.math.BigDecimal(raw.trim()).stripTrailingZeros().toPlainString();
} catch (RuntimeException ex) {
return raw.trim();
}
}
/**
* 陆运运价表:燃油附加费率、税率必须写到表头同列的数据行。
* rate=0.09→9%;rateFlag 是是否含税,不写进税率格。
*/
@Test
public void landGroupageFillsFuelSurchargeAndTaxRateOnMatrix() throws Exception {
Path src = Files.createTempFile("quote-land-fuel-tax-src", ".xlsx");
Path out = Files.createTempFile("quote-land-fuel-tax-out", ".xlsx");
try (Workbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("中越集拼报价");
org.apache.poi.ss.usermodel.Row matrix = row(sheet, 7);
matrix.createCell(1).setCellValue("始发地");
matrix.createCell(2).setCellValue("目的地");
matrix.createCell(9).setCellValue("币种");
matrix.createCell(10).setCellValue("燃油附加费率");
matrix.createCell(11).setCellValue("税率");
row(sheet, 9);
try (java.io.OutputStream os = Files.newOutputStream(src)) {
wb.write(os);
}
}
JSONObject mapping = new JSONObject(true);
mapping.put("sheet", "中越集拼报价");
JSONArray regions = new JSONArray();
JSONObject region = new JSONObject(true);
region.put("headerRow", 8);
region.put("dataStartRow", 10);
JSONObject columns = new JSONObject(true);
columns.put("origin", "B");
columns.put("destination", "C");
region.put("columns", columns);
regions.add(region);
mapping.put("routeRegions", regions);
JSONObject facts = new JSONObject(true);
facts.put("route_rows", QuoteTemplateExcelSupport.parseFeeRows(
"[{\"origin\":\"广州\",\"destination\":\"河内\",\"fuelSurchargeRate\":\"8\",\"rate\":\"0.09\",\"rateFlag\":\"1\"}]"));
QuoteTemplateExcelSupport.fillWorkbook(src, out, mapping, facts);
try (Workbook filled = new XSSFWorkbook(Files.newInputStream(out))) {
Sheet sheet = filled.getSheetAt(0);
assertEquals("广州", read(sheet, 9, 1));
assertEquals("河内", read(sheet, 9, 2));
assertEquals("8%", read(sheet, 9, 10));
assertEquals("9%", read(sheet, 9, 11));
assertEquals("燃油附加费率", read(sheet, 7, 10));
assertEquals("税率", read(sheet, 7, 11));
} finally {
Files.deleteIfExists(src);
Files.deleteIfExists(out);
}
assertEquals("9%", QuoteTemplateExcelSupport.formatLandTaxRateDisplay("0.09"));
assertEquals("8%", QuoteTemplateExcelSupport.formatLandPercentDisplay("8.0"));
assertEquals("含税", QuoteTemplateExcelSupport.formatLandTaxIncludedDisplay("1"));
}
}
@@ -42,4 +42,11 @@ public class QuoteTemplateObjectStoreTest {
public void splitRejectsBlank() {
assertNull(QuoteTemplateObjectStore.splitStorageUrl(" ", "http://127.0.0.1:9000/"));
}
@Test
public void remoteUrlStillDetectedAfterShaOverload() {
// 回归:增加 resolve(objectKey, sha) 后,URL 识别不能回退成 Paths.get
assertTrue(QuoteTemplateObjectStore.isRemoteUrl(
"http://127.0.0.1:9000/inquiry-robot/inquiry/quote-templates/空运到门报价单模板_1790069791709.xlsx"));
}
}
@@ -187,14 +187,36 @@ public class InquiryTmsCabinServiceTest {
InquiryTmsCabinService.fillLockQuoteExtras(req, quote, option);
assertEquals("2026-09-30T23:59:59+08:00", req.get("validUntil"));
@SuppressWarnings("unchecked")
java.util.List<Map<String, Object>> dep =
(java.util.List<Map<String, Object>>) req.get("departureCharges");
assertEquals("运输费", dep.get(0).get("chargeName"));
// departureCharges 出站会 TMS 1001,只保留 feeItems。
org.junit.jupiter.api.Assertions.assertNull(req.get("departureCharges"));
@SuppressWarnings("unchecked")
java.util.List<Map<String, Object>> fees =
(java.util.List<Map<String, Object>>) req.get("feeItems");
assertEquals("空运费", fees.get(0).get("feeName"));
// 空运费缺单位时锁舱补 KG(WO007)
assertEquals("KG", fees.get(0).get("unit"));
}
@Test
public void manualFeeLinesWithoutUnitGetsKgOnLock() {
Map<String, Object> quote = new HashMap<>();
quote.put("source", "PRODUCT");
Map<String, Object> line = new HashMap<>();
line.put("name", "空运费");
line.put("unit_price", "10.00");
line.put("quantity", "5063");
line.put("amount", "50630");
line.put("currency", "CNY");
quote.put("fee_lines", java.util.Arrays.asList(line));
Map<String, Object> req = new HashMap<>();
InquiryTmsCabinService.fillLockQuoteExtras(req, quote, new HashMap<>());
@SuppressWarnings("unchecked")
java.util.List<Map<String, Object>> fees =
(java.util.List<Map<String, Object>>) req.get("feeItems");
assertNotNull(fees);
assertEquals(1, fees.size());
assertEquals("空运费", fees.get(0).get("feeName"));
assertEquals("KG", fees.get(0).get("unit"));
}
@Test
@@ -298,4 +320,40 @@ public class InquiryTmsCabinServiceTest {
InquiryTmsCabinService.fillManualLock(req, quote, new HashMap<>(), new HashMap<>(), false);
org.junit.jupiter.api.Assertions.assertNull(req.get("quoteId"));
}
@Test
public void validateManualLockOutboundReportsMissingFields() {
Map<String, Object> empty = new HashMap<>();
String why = InquiryTmsCabinService.validateManualLockOutbound(empty);
org.junit.jupiter.api.Assertions.assertTrue(why.contains("optionNo"));
org.junit.jupiter.api.Assertions.assertTrue(why.contains("airline"));
org.junit.jupiter.api.Assertions.assertTrue(why.contains("chargeableWeightKg"));
Map<String, Object> ok = new HashMap<>();
ok.put("optionNo", "AIR-OPT01");
ok.put("airline", "CZ");
ok.put("chargeableWeightKg", "100");
ok.put("flightNo", "CZ327");
ok.put("operatorName", "航线");
ok.put("validUntil", "2026-10-01T23:59:59+08:00");
assertEquals("", InquiryTmsCabinService.validateManualLockOutbound(ok));
}
@Test
public void airlineCodeOrBlankRejectsChineseName() {
assertEquals("CZ", InquiryTmsCabinService.airlineCodeOrBlank("CZ"));
assertEquals("", InquiryTmsCabinService.airlineCodeOrBlank("南航"));
assertEquals("", InquiryTmsCabinService.airlineCodeOrBlank(""));
}
@Test
public void realTmsQuoteIdSkipsManualAndKeepsOlderTms() {
org.jeecg.modules.inquiry.entity.InquiryQuote manual = new org.jeecg.modules.inquiry.entity.InquiryQuote();
manual.setPayloadJson("{\"source\":\"PRODUCT\",\"source_label\":\"航线报价\",\"total\":\"200\"}");
org.jeecg.modules.inquiry.entity.InquiryQuote tms = new org.jeecg.modules.inquiry.entity.InquiryQuote();
tms.setPayloadJson("{\"source\":\"TMS\",\"quoteId\":\"AIR-REAL-1\",\"airOptions\":[{\"optionNo\":\"AIR-OPT01\"}]}");
String id = InquiryTmsCabinService.realTmsQuoteId(
java.util.Arrays.asList(manual, tms), "WO202610030009");
assertEquals("AIR-REAL-1", id);
}
}
@@ -184,6 +184,75 @@ public class TmsQuoteCurrencyTest {
assertTrue(quote.get("fee_lines").contains("2800"));
}
/**
* 陆运 TMS:fuelSurchargeRate=燃油附加费率;rate=税率;rateFlag=是否含税。
* 禁止用 fxRates.rate(汇率)冒充税率。
*/
@Test
public void toAgentQuoteProjectsLandFuelAndTaxRate() {
Map<String, Object> seg = new HashMap<>();
seg.put("segmentSequence", 1);
seg.put("origin", "广州市");
seg.put("destination", "深圳市");
seg.put("costPrice", "110");
seg.put("currency", "CNY");
seg.put("fuelSurchargeRate", 8);
seg.put("rate", 0.09);
seg.put("rateFlag", 1);
Map<String, Object> data = new HashMap<>();
data.put("quoteFound", true);
data.put("currency", "CNY");
data.put("landSegments", Collections.singletonList(seg));
Map<String, Object> tms = new HashMap<>();
tms.put("code", 1);
tms.put("tmsData", data);
Map<String, String> quote = InquiryTmsQueryService.toAgentQuote(tms);
assertTrue(quote.get("route_rows").contains("\"fuel_surcharge_rate\":\"8%\""));
assertTrue(quote.get("route_rows").contains("\"tax_rate\":\"9%\""));
assertTrue(quote.get("route_rows").contains("\"tax_included\":\"含税\""));
assertTrue(quote.get("route_rows").contains("\"rateFlag\":\"1\""));
assertFalse(quote.get("route_rows").contains("fxRates"));
assertEquals("8%", InquiryTmsQueryService.formatLandPercentRate("8"));
assertEquals("9%", InquiryTmsQueryService.formatLandTaxRate("0.09"));
assertEquals("10%", InquiryTmsQueryService.formatLandTaxRate("10"));
assertEquals("含税", InquiryTmsQueryService.formatLandTaxIncluded("1"));
assertEquals("不含税", InquiryTmsQueryService.formatLandTaxIncluded("0"));
assertEquals("", InquiryTmsQueryService.formatLandPercentRate(null));
}
/**
* 腿上燃油为空时,从同段 feeItems.fuelSurchargeRate 补到 route_rows,供出单侧栏写入。
*/
@Test
public void toAgentQuoteFillsLandFuelFromFeeItemsWhenSegmentMissing() {
Map<String, Object> seg = new HashMap<>();
seg.put("segmentSequence", 1);
seg.put("routeLegSequence", 1);
seg.put("origin", "深圳");
seg.put("destination", "春疆货场");
seg.put("costPrice", "1200");
seg.put("currency", "CNY");
Map<String, Object> fee = new HashMap<>();
fee.put("segmentSequence", 1);
fee.put("routeLegSequence", 1);
fee.put("feeName", "运输费");
fee.put("amount", 1200);
fee.put("currency", "CNY");
fee.put("fuelSurchargeRate", 8);
fee.put("rate", 0);
Map<String, Object> data = new HashMap<>();
data.put("quoteFound", true);
data.put("currency", "CNY");
data.put("landSegments", Collections.singletonList(seg));
data.put("feeItems", Collections.singletonList(fee));
Map<String, Object> tms = new HashMap<>();
tms.put("code", 1);
tms.put("tmsData", data);
Map<String, String> quote = InquiryTmsQueryService.toAgentQuote(tms);
assertTrue(quote.get("route_rows").contains("\"fuel_surcharge_rate\":\"8%\""));
assertTrue(quote.get("route_rows").contains("\"tax_rate\":\"0%\""));
}
@Test
public void toAgentQuoteKeepsSeaBucketTotals() {
Map<String, Object> pol = new HashMap<>();
@@ -568,13 +568,22 @@ public class LoginController {
}
/**
* 切换菜单表为vue3的表
* 切换菜单表为vue3的表。
* <p>
* 询价新库若已无 {@code sys_permission_v3},服务层会拒绝切换并返回错误,避免把现用菜单表 rename 掉。
* </p>
*/
@RequiresRoles({"admin"})
@GetMapping(value = "/switchVue3Menu")
public Result<String> switchVue3Menu(HttpServletResponse response) {
Result<String> res = new Result<String>();
sysPermissionService.switchVue3Menu();
try {
sysPermissionService.switchVue3Menu();
res.success("切换成功");
} catch (Exception e) {
log.error("switchVue3Menu rejected or failed: {}", e.getMessage(), e);
res.error500(e.getMessage());
}
return res;
}
@@ -49,6 +49,18 @@ public interface SysPermissionMapper extends BaseMapper<SysPermission> {
public void backupVue2Menu();
@Update("alter table sys_permission_v3 rename to sys_permission")
public void changeVue3Menu();
/**
* 是否存在 Jeecg 官方 Vue3 菜单备份表 {@code sys_permission_v3}。
* <p>
* 询价新库 {@code inquiry_robot} 的菜单种子本身已是 Vue3 形态,通常没有 v3 表;
* 若此时仍执行 rename 切换,会把正在使用的 {@code sys_permission} 改名后找不到替代表,侧栏全挂。
* </p>
*
* @return 存在则 &gt; 0
*/
@Select("SELECT COUNT(1) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'sys_permission_v3'")
Long countVue3MenuTable();
/**
* 获取模糊匹配规则的数据权限URL
@@ -55,10 +55,24 @@ public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, S
@Resource
private SysDepartRolePermissionMapper sysDepartRolePermissionMapper;
/**
* 将菜单表从 Vue2 备份切换为 Vue3 表(Jeecg 官方升级路径)。
* <p>
* 副作用:{@code sys_permission} rename 为 {@code sys_permission_v2},再把 {@code sys_permission_v3}
* rename 为 {@code sys_permission}。线程:请求线程,需 admin 角色。
* </p>
* <p>
* 为何加护栏:询价测服库菜单已是 Vue3,且没有 {@code sys_permission_v3};盲目切换会弄挂后台菜单。
* </p>
*/
/**
* 询价新库永久拒绝切表:即便存在 sys_permission_v3 也不自动 rename,
* 避免非管理员误点前端「Vue2 菜单」弹窗后弄挂 inquiry_robot 侧栏。
* 真要升级菜单表须走人工迁移脚本,禁止在线一键切换。
*/
@Override
public void switchVue3Menu() {
sysPermissionMapper.backupVue2Menu();
sysPermissionMapper.changeVue3Menu();
throw new JeecgBootException("已禁用在线切换 Vue3 菜单表;inquiry_robot 菜单按迁移脚本维护,禁止 rename sys_permission");
}
@Override
+6 -4
View File
@@ -24,10 +24,12 @@ export const getMenuList = () => {
};
/**
* 切换成vue3菜单
* 切换成 vue3 菜单 —— 询价库永久禁用。
* <p>
* Jeecg 原逻辑会把 sys_permission rename 成 v2 再切 v3 表;测服 inquiry_robot
* 菜单已是 Vue3 且常无 sys_permission_v3,执行会弄挂侧栏。前端不再发切表请求。
*/
export const switchVue3Menu = () => {
return new Promise((resolve) => {
defHttp.get({ url: Api.SwitchVue3Menu });
});
console.warn('[ytd] switchVue3Menu disabled: inquiry_robot menus are already Vue3');
return Promise.resolve({ success: false, message: 'switchVue3Menu disabled' });
};
+23 -3
View File
@@ -8,8 +8,10 @@
import { useRoute, useRouter, RouterView } from 'vue-router';
import { message, ConfigProvider } from 'ant-design-vue';
import { useUserStore } from '/@/store/modules/user';
import { usePermission } from '/@/hooks/web/usePermission';
import ProtoIcon from '/@/views/inquiry/components/ProtoIcon.vue';
import AdminModal from '/@/views/inquiry/components/AdminModal.vue';
import { canSeeInquiryPage } from '/@/views/inquiry/shared/inquiryPagePerms';
import '/@/views/inquiry/styles/admin-prototype.css';
import '/@/views/inquiry/styles/admin-fidelity.css';
import '/@/views/inquiry/styles/dashboard-prototype.css';
@@ -74,12 +76,26 @@
components: { RouterView, ProtoIcon, AdminModal, ConfigProvider },
setup() {
const userStore = useUserStore();
const { hasPermission } = usePermission();
const route = useRoute();
const router = useRouter();
const userMenuOpen = ref(false);
const profileOpen = ref(false);
const passwordOpen = ref(false);
/**
* 侧栏按查看权限码过滤;无权限的分组整组隐藏。
* 不再渲染写死全量 navGroups,避免「没权限仍看见菜单」。
*/
const visibleNavGroups = computed(() =>
navGroups
.map((g) => ({
...g,
items: g.items.filter((item) => canSeeInquiryPage(item.key, hasPermission)),
}))
.filter((g) => g.items.length > 0),
);
const pageTitle = computed(() => String(route.meta?.title || '友通达智能体运营后台'));
const crumb = computed(() => (route.meta?.crumb ? String(route.meta.crumb) : ''));
@@ -167,11 +183,15 @@
if (!t.closest('.admin-user-menu')) closeUserMenu();
}
onMounted(() => document.addEventListener('click', onDocClick));
onUnmounted(() => document.removeEventListener('click', onDocClick));
onMounted(() => {
document.addEventListener('click', onDocClick);
});
onUnmounted(() => {
document.removeEventListener('click', onDocClick);
});
return {
navGroups,
navGroups: visibleNavGroups,
themeToken,
route,
pageTitle,
+130 -55
View File
@@ -2,7 +2,6 @@ import type { AppRouteRecordRaw, Menu } from '/@/router/types';
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { useI18n } from '/@/hooks/web/useI18n';
import { useUserStore } from './user';
import { useAppStoreWithOut } from './app';
import { toRaw } from 'vue';
@@ -18,16 +17,16 @@ import { ERROR_LOG_ROUTE, PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { filter } from '/@/utils/helper/treeHelper';
import { getMenuList,switchVue3Menu } from '/@/api/sys/menu';
import { getMenuList } from '/@/api/sys/menu';
import { getPermCode } from '/@/api/sys/user';
import { useMessage } from '/@/hooks/web/useMessage';
import { PageEnum } from '/@/enums/pageEnum';
import { INQUIRY_PAGE_VIEW_PERMS } from '/@/views/inquiry/shared/inquiryPagePerms';
/**
* 询价原型侧栏路径是写死的;Jeecg BACK 模式只注册后台菜单里的路由。
* 菜单种子缺失/组件路径不对时,点侧栏会进 404(本机与线上相同)。
* 这里按侧栏清单补挂手写页,不依赖种子是否已导入。
* 询价手写页:纠正菜单种子里的组件路径/标题。
* 禁止把未授权页强行补进路由——否则 backMenuList 会膨胀成全量侧栏,无权限也看得见。
* 仅当「后台菜单已有该路径」或「用户已有对应查看权限码」时才补挂缺失叶子。
*/
type InquiryLeaf = {
path: string;
@@ -80,16 +79,65 @@ function findParent(list: AppRouteRecordRaw[] = [], parentPath: string): AppRout
return null;
}
function ensureInquiryHandwrittenRoutes(routeList: AppRouteRecordRaw[]) {
const groups: Record<string, { title: string; redirect: string; leaves: InquiryLeaf[] }> = {
/**
* 永久禁止 Jeecg「Vue2 菜单表」切表弹窗。
* <p>
* 检测条件:顶层既没有 component===layouts/default/index,图标也不含冒号。
* 非管理员若只分到缺标记的询价菜单,会被误判;点确认会 rename sys_permission,测服无 v3 表会弄挂侧栏。
* 本函数恒为 false,禁止再恢复弹窗逻辑。
*/
function shouldPromptVue2MenuSwitch(_routeList: AppRouteRecordRaw[]): boolean {
return false;
}
/**
* 给菜单补齐 Vue3 标记,避免未来误恢复 Jeecg 检测时再次弹窗。
* 副作用:就地改 component / meta.icon;不改业务权限。
*/
function normalizeVue3MenuMarkers(routeList: AppRouteRecordRaw[]): AppRouteRecordRaw[] {
for (const item of routeList || []) {
const comp = String((item as any).component || '');
// Jeecg 检测认 layouts/default/index;LAYOUT 也会被 transform 成询价壳
if (!comp || comp.toUpperCase() === 'LAYOUT') {
(item as any).component = 'layouts/default/index';
}
item.meta = item.meta || ({} as any);
const icon = String((item.meta as any).icon || '');
if (!icon) {
(item.meta as any).icon = 'ant-design:menu-outlined';
} else if (!icon.includes(':')) {
(item.meta as any).icon = `ant-design:${icon}`;
}
}
return routeList;
}
function ensureInquiryHandwrittenRoutes(routeList: AppRouteRecordRaw[], permCodes: Array<string | number> = []) {
const codeSet = new Set((permCodes || []).map(String));
const canAddLeaf = (leaf: InquiryLeaf) => {
// 后台菜单已下发该路径:只纠正组件,不算越权补挂
if (findRouteByPath(routeList, leaf.path)) {
return true;
}
const need = INQUIRY_PAGE_VIEW_PERMS[leaf.path];
// 无权限码表时不补挂(宁可少菜单,也不把未授权页塞进侧栏)
if (!need) {
return false;
}
return codeSet.has(need);
};
const groups: Record<string, { title: string; redirect: string; icon: string; leaves: InquiryLeaf[] }> = {
'/inquiry': {
title: '询价',
redirect: '/inquiry/dashboard',
icon: 'ant-design:robot-outlined',
leaves: INQUIRY_LEAVES.filter((l) => l.path.startsWith('/inquiry/') && !l.path.startsWith('/inquiry-sys')),
},
'/inquiry-sys': {
title: '询价系统配置',
redirect: '/inquiry-sys/system-setting',
icon: 'ant-design:setting-outlined',
leaves: INQUIRY_LEAVES.filter((l) => l.path.startsWith('/inquiry-sys/')),
},
};
@@ -107,6 +155,10 @@ function ensureInquiryHandwrittenRoutes(routeList: AppRouteRecordRaw[]) {
existing.meta = { ...(existing.meta || {}), title: leaf.title, ignoreKeepAlive: true };
continue;
}
// 角色未授权且无对应查看权限:禁止补挂(根因:曾把 8 个询价页全塞进 backMenuList)
if (!canAddLeaf(leaf)) {
continue;
}
const node: AppRouteRecordRaw = {
path: leaf.path,
name: leaf.name,
@@ -121,12 +173,23 @@ function ensureInquiryHandwrittenRoutes(routeList: AppRouteRecordRaw[]) {
parent = {
path: parentPath,
name: parentPath.replace(/\//g, '-').replace(/^-/, '') || 'inquiry-root',
component: 'LAYOUT' as any,
// 必须用 layouts/default/index + 带冒号图标,满足 Jeecg Vue3 菜单检测(实际仍映射到询价壳)
component: 'layouts/default/index' as any,
redirect: group.redirect,
meta: { title: group.title },
meta: { title: group.title, icon: group.icon },
children: [],
};
routeList.push(parent);
} else {
// 已有父级也补标记,防止非管理员菜单缺图标被误判 Vue2
const pComp = String((parent as any).component || '');
if (!pComp || pComp.toUpperCase() === 'LAYOUT') {
(parent as any).component = 'layouts/default/index';
}
parent.meta = {
...(parent.meta || {}),
icon: (parent.meta as any)?.icon || group.icon,
};
}
parent.children = parent.children || [];
if (leaf.path === group.redirect) {
@@ -139,6 +202,49 @@ function ensureInquiryHandwrittenRoutes(routeList: AppRouteRecordRaw[]) {
return routeList;
}
/**
* 去掉无查看权限的询价叶子(角色树勾了菜单但没勾按钮、或历史脏数据)。
* 父节点若子级删空则一并去掉,避免侧栏空分组。
*/
function pruneInquiryLeavesWithoutViewPerm(
routeList: AppRouteRecordRaw[],
permCodes: Array<string | number> = [],
): AppRouteRecordRaw[] {
const codeSet = new Set((permCodes || []).map(String));
// 权限码尚未就绪时禁止裁剪:否则会把 getMenuList 结果清空 → 重登 404
if (codeSet.size === 0) {
return routeList;
}
const norm = (p: string) => {
const s = String(p || '');
return s.startsWith('/') ? s : `/${s}`;
};
const walk = (list: AppRouteRecordRaw[] = []): AppRouteRecordRaw[] => {
const out: AppRouteRecordRaw[] = [];
for (const item of list) {
const path = norm(item.path || '');
const need = INQUIRY_PAGE_VIEW_PERMS[path];
if (need && !codeSet.has(need)) {
continue;
}
const next = { ...item };
if (next.children?.length) {
next.children = walk(next.children as AppRouteRecordRaw[]);
// 询价分组下无子页则不保留空壳
if (
(path === '/inquiry' || path === '/inquiry-sys') &&
(!next.children || next.children.length === 0)
) {
continue;
}
}
out.push(next);
}
return out;
};
return walk(routeList);
}
// 系统权限
interface AuthItem {
@@ -246,7 +352,6 @@ export const usePermissionStore = defineStore({
this.setAuthData(systemPermission);
},
async buildRoutesAction(): Promise<AppRouteRecordRaw[]> {
const { t } = useI18n();
const userStore = useUserStore();
const appStore = useAppStoreWithOut();
@@ -322,61 +427,31 @@ export const usePermissionStore = defineStore({
// 后台菜单构建
case PermissionModeEnum.BACK:
const { createMessage, createWarningModal } = useMessage();
// 菜单加载提示
// createMessage.loading({
// content: t('sys.app.menuLoading'),
// duration: 1,
// });
// 从后台获取权限码,
// 这个函数可能只需要执行一次,并且实际的项目可以在正确的时间被放置
let routeList: AppRouteRecordRaw[] = [];
try {
this.changePermissionCode();
// 必须 await:logout 会清空 permCodeList;若此处不候等,后面 prune 会在空权限码下
// 把询价叶子全删掉 → 侧栏仍能靠稍后到的权限码显示,点进去却是 404。
await this.changePermissionCode();
routeList = (await getMenuList()) as AppRouteRecordRaw[];
// update-begin----author:sunjianlei---date:20220315------for: 判断是否是 vue3 版本的菜单 ---
let hasIndex: boolean = false;
let hasIcon: boolean = false;
for (let menuItem of routeList) {
// 条件1:判断组件是否是 layouts/default/index
if (!hasIndex) {
hasIndex = menuItem.component === 'layouts/default/index';
}
// 条件2:判断图标是否带有 冒号
if (!hasIcon) {
hasIcon = !!menuItem.meta?.icon?.includes(':');
}
// 满足任何一个条件都直接跳出循环
if (hasIcon || hasIndex) {
break;
}
// 永久禁止 Vue2→Vue3 切表弹窗(shouldPromptVue2MenuSwitch 恒 false)
if (shouldPromptVue2MenuSwitch(routeList)) {
// 不可达;保留分支防止以后误合并 Jeecg 原弹窗代码
}
// 两个条件都不满足,就弹出提示框
if (!hasIcon && !hasIndex) {
// 延迟1.5秒之后再出现提示,否则提示框出不来
setTimeout(
() =>
createWarningModal({
title: '检测提示',
content:
'当前菜单表是 <b>Vue2版本</b>,导致菜单加载异常!<br>点击确认,切换到Vue3版菜单!',
onOk:function () {
switchVue3Menu();
location.reload();
}
}),
100
);
}
// update-end----author:sunjianlei---date:20220315------for: 判断是否是 vue3 版本的菜单 ---
// 非管理员菜单常缺 Vue3 标记 → 误弹「菜单表是 Vue2」;先规范化再往下走
routeList = normalizeVue3MenuMarkers(routeList || []);
} catch (error) {
console.error(error);
// 菜单接口失败时仍补挂询价手写页,避免侧栏点进去全是 404
routeList = Array.isArray(routeList) ? routeList : [];
}
// 无论菜单接口成功与否,都按侧栏清单补齐手写路由
routeList = ensureInquiryHandwrittenRoutes(routeList || []);
// 只纠正/补挂「已有菜单或已有查看权限」的手写页,禁止灌入未授权路由
const permCodes = this.getPermCodeList || [];
routeList = ensureInquiryHandwrittenRoutes(routeList || [], permCodes);
routeList = pruneInquiryLeavesWithoutViewPerm(routeList, permCodes);
// 补挂后再标一次(ensure 新建的父级也要带 Vue3 标记)
routeList = normalizeVue3MenuMarkers(routeList);
// 组件地址前加斜杠处理 author: lsq date:2021-09-08
routeList = addSlashToRouteComponent(routeList);
// 动态引入组件
@@ -19,6 +19,12 @@ import {
import ProtoIcon from "/@/views/inquiry/components/ProtoIcon.vue";
import AdminModal from "/@/views/inquiry/components/AdminModal.vue";
import AdminPagination from "/@/views/inquiry/components/AdminPagination.vue";
import { usePermission } from "/@/hooks/web/usePermission";
import { InquiryBtnPerm } from "/@/views/inquiry/shared/inquiryPagePerms";
const { hasPermission } = usePermission();
/** 账号新建/编辑/删除/重置密码均属 edit 权限 */
const canEditAccount = () => hasPermission(InquiryBtnPerm.accountEdit);
const rows = ref<AccountRow[]>([]);
const loading = ref(false);
@@ -299,7 +305,7 @@ function removeAccount(row: AccountRow) {
<button type="button" class="btn btn-secondary" disabled title="导出待后续开放">
<ProtoIcon name="download" :size="14" />导出
</button>
<button type="button" class="btn btn-primary" @click="openCreate">
<button v-if="canEditAccount()" type="button" class="btn btn-primary" @click="openCreate">
<ProtoIcon name="plus" :size="14" />新建账号
</button>
</div>
@@ -325,6 +331,7 @@ function removeAccount(row: AccountRow) {
<th>账号</th>
<th>姓名</th>
<th>绑定角色</th>
<th>数据范围</th>
<th>手机号</th>
<th>最后登录</th>
<th>状态</th>
@@ -333,10 +340,10 @@ function removeAccount(row: AccountRow) {
</thead>
<tbody>
<tr v-if="loading">
<td colspan="7" style="text-align: center; color: #94a3b8">加载中…</td>
<td colspan="8" style="text-align: center; color: #94a3b8">加载中…</td>
</tr>
<tr v-else-if="!rows.length">
<td colspan="7" style="text-align: center; color: #94a3b8">暂无账号</td>
<td colspan="8" style="text-align: center; color: #94a3b8">暂无账号</td>
</tr>
<tr v-for="row in rows" :key="row.id">
<td class="account-username">{{ row.username }}</td>
@@ -344,6 +351,20 @@ function removeAccount(row: AccountRow) {
<td>
<span class="tag" :class="row.roleTag">{{ row.roleLabel }}</span>
</td>
<td>
<!-- 与编辑弹窗「数据范围」同源:dashboardSelfOnly -->
<span
class="tag"
:class="row.dashboardSelfOnly ? 'tag-amber' : 'tag-teal'"
:title="
row.dashboardSelfOnly
? '分析看板仅统计本账号企微归属的工单'
: '分析看板可看权限内全部数据'
"
>
{{ row.dashboardSelfOnly ? "只看自己数据" : "全部数据" }}
</span>
</td>
<td>{{ row.phoneMasked }}</td>
<td>{{ row.lastLogin }}</td>
<td>
@@ -354,7 +375,7 @@ function removeAccount(row: AccountRow) {
<td>
<div class="account-row-actions">
<button
v-if="!row.isSuperAdmin"
v-if="canEditAccount() && !row.isSuperAdmin"
class="link-action"
type="button"
@click="openEdit(row)"
@@ -363,6 +384,7 @@ function removeAccount(row: AccountRow) {
</button>
<!-- 超管只隐藏编辑/删除;重置密码仍可用。不展示「不可编辑」占位文案 -->
<button
v-if="canEditAccount()"
class="link-action link-muted"
type="button"
@click="resetPassword(row)"
@@ -370,7 +392,7 @@ function removeAccount(row: AccountRow) {
重置密码
</button>
<button
v-if="!row.isSuperAdmin"
v-if="canEditAccount() && !row.isSuperAdmin"
class="link-action link-danger"
type="button"
@click="removeAccount(row)"
@@ -1,4 +1,4 @@
<script setup lang="ts">
<script setup lang="ts">
/**
* 机器人回复语:对接主账 /inquiry/botReply。
* 分类壳用本地元数据;条目内容全部来自库。
@@ -19,6 +19,13 @@ import {
} from "/@/views/inquiry/botReply/replyCategories";
import ProtoIcon from "/@/views/inquiry/components/ProtoIcon.vue";
import AdminModal from "/@/views/inquiry/components/AdminModal.vue";
import { usePermission } from "/@/hooks/web/usePermission";
import { InquiryBtnPerm } from "/@/views/inquiry/shared/inquiryPagePerms";
const { hasPermission } = usePermission();
const canAdd = () => hasPermission(InquiryBtnPerm.replyAdd);
const canEdit = () => hasPermission(InquiryBtnPerm.replyEdit);
const canDisable = () => hasPermission(InquiryBtnPerm.replyDisable);
const categories = ref<ReplyCategory[]>(emptyCategories());
const loading = ref(false);
@@ -152,7 +159,7 @@ async function save() {
<template>
<Teleport defer to="#page-topbar-actions">
<button type="button" class="btn btn-primary" @click="openCreate()">
<button v-if="canAdd()" type="button" class="btn btn-primary" @click="openCreate()">
<ProtoIcon name="plus" :size="16" />添加话术
</button>
</Teleport>
@@ -177,13 +184,21 @@ async function save() {
</div>
<div style="display: flex; align-items: center; gap: 8px; flex-shrink: 0">
<button
v-if="canDisable()"
type="button"
class="switch"
:class="{ 'is-on': item.enabled }"
:aria-label="item.enabled ? '停用' : '启用'"
@click="toggle(item)"
/>
<button type="button" class="link-action" @click="openEdit(cat.id, item)">编辑</button>
<button
v-if="canEdit()"
type="button"
class="link-action"
@click="openEdit(cat.id, item)"
>
编辑
</button>
</div>
</div>
</article>
@@ -1,6 +1,6 @@
<script setup lang="ts">
/**
* 询价后台列表分页条:总数 + 每页条数 + 页码。
* 询价后台列表分页条:整组靠右,总数紧挨在「每页」左边,页码在后。
* 样式对齐 admin-fidelity.css 的 .pagination;翻页只发事件,不请求接口。
*/
import { computed } from "vue";
@@ -87,13 +87,13 @@ function onSizeChange(e: Event) {
<template>
<div class="pagination admin-pagination">
<span class="admin-pagination__total">
共 <b>{{ total }}</b> {{ unit }}
<span v-if="total > 0" class="admin-pagination__range">
(第 {{ pageNo }} / {{ totalPages }} 页)
</span>
</span>
<div class="admin-pagination__right">
<span class="admin-pagination__total">
共 <b>{{ total }}</b> {{ unit }}
<span v-if="total > 0" class="admin-pagination__range">
(第 {{ pageNo }} / {{ totalPages }} 页)
</span>
</span>
<label class="admin-pagination__size">
每页
<select :value="pageSize" :disabled="disabled" @change="onSizeChange">
@@ -127,6 +127,11 @@ function onSizeChange(e: Event) {
gap: 10px;
flex-wrap: wrap;
justify-content: flex-end;
margin-left: auto;
}
.admin-pagination__total {
white-space: nowrap;
}
.admin-pagination__size {
@@ -1,5 +1,6 @@
/**
* 分析看板 API。
* 显式传 dateFrom/dateTo,与工单列表日期筛选同源;range 仅作无日期时的回退。
*/
import { defHttp } from '/@/utils/http/axios';
@@ -7,5 +8,20 @@ enum Api {
metrics = '/inquiry/dashboard/metrics',
}
export const getDashboardMetrics = (range = 'today') =>
defHttp.get({ url: Api.metrics, params: { range } });
export type DashboardMetricsParams = {
range?: string;
dateFrom?: string;
dateTo?: string;
};
export const getDashboardMetrics = (params: DashboardMetricsParams | string = 'today') => {
const query =
typeof params === 'string'
? { range: params }
: {
range: params.range || 'today',
dateFrom: params.dateFrom,
dateTo: params.dateTo,
};
return defHttp.get({ url: Api.metrics, params: query });
};
@@ -56,11 +56,15 @@ const activePoint = ref<string | null>(null);
const INQUIRY_PLOT_TOP = 36;
const INQUIRY_PLOT_BOTTOM = 188;
/**
* 粗粒度 range 仅作后端无 dateFrom/dateTo 时的回退;正式请求一律带显式日期。
* 注意:不可再把「单日」映射成 today——today 是日历今天,不是所选那一天。
*/
function resolveRange(): string {
const from = new Date(dateFrom.value);
const to = new Date(dateTo.value);
const days = Math.max(0, Math.round((to.getTime() - from.getTime()) / 86400000));
if (days <= 0) return "today";
if (days <= 0) return "1d";
if (days <= 6) return "7d";
return "30d";
}
@@ -88,7 +92,12 @@ function onDateRangeChange() {
async function loadMetrics() {
loading.value = true;
try {
const res: any = await getDashboardMetrics(resolveRange());
const req = {
range: resolveRange(),
dateFrom: dateFrom.value,
dateTo: dateTo.value,
};
const res: any = await getDashboardMetrics(req);
const data = res?.result || res || {};
todayMetrics.value = (data.metrics || []) as MetricCard[];
inquiryTrend.value = ((data.trend || []) as any[]).map((p) => ({
@@ -2,6 +2,9 @@
/**
* 询价后台登录页:视觉 1:1 对齐 admin/LoginView(居中白卡片 + 品牌区,无验证码)。
* 鉴权走 Jeecg loginApi;主账 inquiry 配置关闭图形验证码(jeecg.loginCaptchaEnabled=false)。
*
* 禁止写死 admin/123456:退出后再进登录页会误显示测试账号。
* 仅记住上次成功登录的账号(不存密码),方便换人登录时改账号。
*/
import { reactive, ref, toRaw } from 'vue';
import { ConfigProvider, message } from 'ant-design-vue';
@@ -10,11 +13,29 @@
import '/@/views/inquiry/styles/admin-prototype.css';
import '/@/views/inquiry/styles/admin-fidelity.css';
const LAST_USERNAME_KEY = 'inquiry_admin_last_username';
function readLastUsername(): string {
try {
return String(localStorage.getItem(LAST_USERNAME_KEY) || '').trim();
} catch {
return '';
}
}
function rememberUsername(username: string) {
try {
localStorage.setItem(LAST_USERNAME_KEY, username);
} catch {
/* 隐私模式等写失败时忽略 */
}
}
const userStore = useUserStore();
const loading = ref(false);
const form = reactive({
username: 'admin',
password: '123456',
username: readLastUsername(),
password: '',
});
const themeToken = {
@@ -36,9 +57,10 @@
}
loading.value = true;
try {
const username = form.username.trim();
const { userInfo } = await userStore.login(
toRaw({
username: form.username.trim(),
username,
password: form.password,
// 主账已关验证码;仍传空字段以兼容 LoginParams 类型
captcha: '',
@@ -48,6 +70,9 @@
})
);
if (userInfo) {
rememberUsername(username);
// 成功后清空密码,避免浏览器后退/再进登录页时残留明文
form.password = '';
message.success(`登录成功,欢迎 ${userInfo.realname || userInfo.username}`);
}
} catch (e: any) {
@@ -190,8 +190,8 @@ export const mockReplyCategories: ReplyCategory[] = [
{
id: "brv10000000000000000000000000024",
replyCode: "inquiring.air_lock_need_wo",
trigger: "空运锁舱/释放未带工单号",
text: "锁舱或释放舱位请带上工单号,例如 WO202609160001锁舱。",
trigger: "空运锁舱/取消舱位未带工单号",
text: "锁舱或取消舱位请带上工单号,例如 WO202609160001取消舱位。",
enabled: true,
},
{
@@ -205,7 +205,7 @@ export const mockReplyCategories: ReplyCategory[] = [
id: "brv10000000000000000000000000026",
replyCode: "inquiring.air_airline_only_cabin",
trigger: "只有航线能锁舱或释放",
text: "只有岗位为「航线·空运」的人能锁舱或释放舱位。",
text: "只有岗位为「航线·空运」的人能锁舱或取消舱位。",
enabled: true,
},
{
@@ -225,29 +225,29 @@ export const mockReplyCategories: ReplyCategory[] = [
{
id: "brv10000000000000000000000000029",
replyCode: "inquiring.air_release_ok",
trigger: "空运释放成功",
text: "工单{{ticket_no}} 已通知TMS执行空运释放舱位成功\n操作人:{{operator}}\n舱位选项:{{option_no}}\n执行编号:{{exec_no}}\n报价编号:{{quote_no}}",
trigger: "空运取消舱位成功",
text: "工单{{ticket_no}} 已通知TMS执行空运取消舱位成功\n操作人:{{operator}}\n舱位选项:{{option_no}}\n执行编号:{{exec_no}}\n报价编号:{{quote_no}}",
enabled: true,
},
{
id: "brv10000000000000000000000000030",
replyCode: "inquiring.air_release_fail",
trigger: "空运释放失败",
text: "工单{{ticket_no}} 空运释放舱位失败。\n操作人:{{operator}}\n释放舱位失败的原因:{{reason}}\n已通知IT运维排查,请稍等。",
trigger: "空运取消舱位失败",
text: "工单{{ticket_no}} 空运取消舱位失败。\n操作人:{{operator}}\n取消舱位失败的原因:{{reason}}\n已通知IT运维排查,请稍等。",
enabled: true,
},
{
id: "brv10000000000000000000000000031",
replyCode: "inquiring.air_release_deal_blocked",
trigger: "已成交不能释放舱位",
text: "释放舱位失败,工单{{ticket_no}}已成交。",
trigger: "已成交不能取消舱位",
text: "取消舱位失败,工单{{ticket_no}}已成交。",
enabled: true,
},
{
id: "brv10000000000000000000000000032",
replyCode: "inquiring.air_release_need_lock",
trigger: "没有有效锁舱不能释放",
text: "工单{{ticket_no}}还没有有效锁舱,不能释放。",
trigger: "没有有效锁舱不能取消舱位",
text: "工单{{ticket_no}}还没有有效锁舱,不能取消舱位。",
enabled: true,
}
],
@@ -342,7 +342,7 @@ export const mockReplyCategories: ReplyCategory[] = [
id: "brv10000000000000000000000000041",
replyCode: "lost.reason_ack",
trigger: "销售回复未成交原因",
text: "已记下未成交原因:{{lost_reason}}。",
text: "已将未成交原因“{{lost_reason}}”记录在后台,工单 {{ticket_no}}已关闭,智能体不再跟进该工单,请悉知。",
enabled: true,
}
],
@@ -26,6 +26,11 @@ import {
import ProtoIcon from "/@/views/inquiry/components/ProtoIcon.vue";
import AdminModal from "/@/views/inquiry/components/AdminModal.vue";
import { joinPermissionIds } from "/@/views/inquiry/role/rolePermission";
import { usePermission } from "/@/hooks/web/usePermission";
import { InquiryBtnPerm } from "/@/views/inquiry/shared/inquiryPagePerms";
const { hasPermission } = usePermission();
const canEditRole = () => hasPermission(InquiryBtnPerm.roleEdit);
const rows = ref<RoleRow[]>([]);
const loading = ref(false);
@@ -250,7 +255,7 @@ function onDataPermCheck(checked: string[] | { checked: string[] }) {
<template>
<Teleport defer to="#page-topbar-actions">
<button type="button" class="btn btn-primary" @click="openCreate">
<button v-if="canEditRole()" type="button" class="btn btn-primary" @click="openCreate">
<ProtoIcon name="plus" :size="14" />新增角色
</button>
</Teleport>
@@ -295,7 +300,7 @@ function onDataPermCheck(checked: string[] | { checked: string[] }) {
</span>
</td>
<td>
<template v-if="row.editable">
<template v-if="canEditRole() && row.editable">
<div class="role-row-actions">
<button class="link-action" type="button" @click="openEdit(row)">编辑</button>
<button class="link-action link-danger" type="button" @click="removeRole(row)">
@@ -0,0 +1,60 @@
/**
* 询价后台页面级权限码:侧栏显隐与「查看」按钮同源。
* <p>
* 为何:侧栏曾写死全量菜单,且 ensureInquiryHandwrittenRoutes 会把未授权页补进路由,
* 导致无 reply:list 等权限的人仍能看到「机器人回复语」。以 Jeecg 权限码为准过滤。
*/
/** 侧栏路径 → 进入该页至少需要的查看类权限码 */
export const INQUIRY_PAGE_VIEW_PERMS: Record<string, string> = {
'/inquiry/dashboard': 'inquiry:dashboard:view',
'/inquiry/work-order': 'inquiry:workorder:list',
'/inquiry/staff-role': 'inquiry:staff:list',
'/inquiry/template': 'inquiry:template:view',
'/inquiry/bot-reply': 'inquiry:reply:list',
'/inquiry-sys/system-setting': 'inquiry:timeout:list',
'/inquiry-sys/user': 'inquiry:account:view',
'/inquiry-sys/role': 'inquiry:role:view',
};
/** 按钮细粒度权限码(与 sys_permission / @RequiresPermissions 对齐) */
export const InquiryBtnPerm = {
workorderList: 'inquiry:workorder:list',
workorderDetail: 'inquiry:workorder:detail',
workorderTransition: 'inquiry:workorder:transition',
workorderExport: 'inquiry:workorder:export',
replyList: 'inquiry:reply:list',
replyAdd: 'inquiry:reply:add',
replyEdit: 'inquiry:reply:edit',
replyDisable: 'inquiry:reply:disable',
staffList: 'inquiry:staff:list',
staffAdd: 'inquiry:staff:add',
staffEdit: 'inquiry:staff:edit',
staffDisable: 'inquiry:staff:disable',
templateView: 'inquiry:template:view',
templateUpload: 'inquiry:template:upload',
templateEdit: 'inquiry:template:edit',
templateToggle: 'inquiry:template:toggle',
accountView: 'inquiry:account:view',
accountEdit: 'inquiry:account:edit',
roleView: 'inquiry:role:view',
roleEdit: 'inquiry:role:edit',
timeoutList: 'inquiry:timeout:list',
timeoutEdit: 'inquiry:timeout:edit',
} as const;
/**
* 当前权限码是否允许进入某侧栏路径。
* @param path 侧栏 key,如 /inquiry/bot-reply
* @param hasPerm hasPermission 回调
*/
export function canSeeInquiryPage(
path: string,
hasPerm: (code: string) => boolean,
): boolean {
const code = INQUIRY_PAGE_VIEW_PERMS[path];
if (!code) {
return true;
}
return hasPerm(code);
}
@@ -25,6 +25,13 @@ import {
dataPermTitle,
normalizeStaffRouteKeys,
} from "/@/views/inquiry/shared/dataPermCatalog";
import { usePermission } from "/@/hooks/web/usePermission";
import { InquiryBtnPerm } from "/@/views/inquiry/shared/inquiryPagePerms";
const { hasPermission } = usePermission();
const canAddStaff = () => hasPermission(InquiryBtnPerm.staffAdd);
const canEditStaff = () => hasPermission(InquiryBtnPerm.staffEdit);
const canDisableStaff = () => hasPermission(InquiryBtnPerm.staffDisable);
type StaffRole = "sales" | "air" | "sea" | "land";
@@ -485,10 +492,16 @@ function filterRouteOption(input: string, option: any) {
<template>
<Teleport defer to="#page-topbar-actions">
<div class="staff-topbar-actions">
<button type="button" class="btn btn-secondary" :disabled="syncing" @click="syncWecom">
<button
v-if="canEditStaff()"
type="button"
class="btn btn-secondary"
:disabled="syncing"
@click="syncWecom"
>
<ProtoIcon name="refresh" :size="16" />{{ syncing ? "同步中…" : "同步企业微信" }}
</button>
<button type="button" class="btn btn-primary" @click="openCreate">
<button v-if="canAddStaff()" type="button" class="btn btn-primary" @click="openCreate">
<ProtoIcon name="userPlus" :size="16" />新增员工
</button>
</div>
@@ -586,9 +599,16 @@ function filterRouteOption(input: string, option: any) {
</td>
<td>
<div style="display: flex; align-items: center; gap: 12px">
<button class="link-action" type="button" @click="openEdit(row)">编辑</button>
<button
v-if="row.status === 'active'"
v-if="canEditStaff()"
class="link-action"
type="button"
@click="openEdit(row)"
>
编辑
</button>
<button
v-if="canDisableStaff() && row.status === 'active'"
class="link-action link-danger"
type="button"
@click="removeStaff(row)"
@@ -23,36 +23,78 @@ body {
grid-template-columns: 220px minmax(0, 1fr) !important;
width: 100%;
max-width: 100%;
overflow-x: hidden;
/* 锁视口:避免 html overflow:hidden 裁切后整页既无文档滚、内容区又不内滚 */
height: 100vh !important;
max-height: 100vh !important;
min-height: 0 !important;
overflow: hidden !important;
}
.main-stage {
background: #f7f8fb !important;
min-width: 0 !important;
overflow-x: hidden;
/* 主区锁视口高度:列表页表格区内滚;看板等非列表页在 .admin-content 内滚 */
/*
* 中间主区 = 滚动容器(看板/非列表页)。
* 实测仅改 .admin-content 在生产壳层仍会被裁切且无条;改由本列横竖自滚最稳。
*/
height: 100vh !important;
max-height: 100vh !important;
min-height: 0 !important;
overflow: hidden !important;
overflow-x: auto !important;
overflow-y: scroll !important;
scrollbar-gutter: stable;
-webkit-overflow-scrolling: touch;
display: flex !important;
flex-direction: column !important;
}
.main-stage {
scrollbar-width: thin;
scrollbar-color: #cbd5e1 transparent;
}
.main-stage::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.main-stage::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 999px;
border: 1px solid transparent;
background-clip: padding-box;
}
.main-stage::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
background-clip: padding-box;
}
.main-stage::-webkit-scrollbar-track {
background: transparent;
}
.main-stage::-webkit-scrollbar-corner {
background: transparent;
}
.admin-content {
padding: 16px 16px 40px !important;
gap: 12px !important;
min-width: 0 !important;
/*
* 主区被锁成一屏。flex-basis 用 auto 时,格子会按内容把内容区撑高,
* 再被主区裁掉,页面上就没有滚动条,鼠标也滚不动。
* basis 取 0、高度先归零,再由 flex 撑满顶栏下方,多出来的内容在这里滚。
*/
flex: 1 1 0% !important;
/* 随内容增高/增宽;滚动条在 .main-stage */
flex: 0 0 auto !important;
height: auto !important;
max-height: none !important;
min-height: 0 !important;
overflow: visible !important;
}
/* 列表页:主区不滚,仍由表格区内滚(工单/账号等) */
.main-stage:has(.is-list-page) {
overflow: hidden !important;
}
.main-stage:has(.is-list-page) .admin-content {
flex: 1 1 0 !important;
height: 0 !important;
min-height: 0 !important;
overflow-x: hidden !important;
overflow-y: auto !important;
max-height: none !important;
overflow: hidden !important;
}
/*
@@ -68,6 +110,12 @@ body {
display: flex !important;
align-items: center !important;
border-bottom: 1px solid #e8edf4 !important;
/* 中间主区滚动时顶栏吸顶,不跟着内容滚走 */
position: sticky !important;
top: 0 !important;
z-index: 40 !important;
flex-shrink: 0 !important;
background: rgba(255, 255, 255, 0.96) !important;
}
.admin-brand {
@@ -870,6 +918,10 @@ body {
color: #155eef !important;
}
.pagination.admin-pagination {
justify-content: flex-end !important;
}
.pagination .pages {
display: inline-flex;
align-items: center;
@@ -1077,9 +1129,21 @@ h6 {
.admin-content:has(.ref-surface--metrics) {
padding: 14px 14px 36px !important;
gap: 10px !important;
/* 分析看板:内容区不裁切,滚动交给 .main-stage */
overflow: visible !important;
max-height: none !important;
align-content: start !important;
}
/* 看板缩窄时允许卡片/图表收缩,避免右侧被裁且无横滚 */
.admin-content .ref-surface,
.admin-content .ref-charts-section,
.admin-content .ref-metrics-grid,
.admin-content .ref-chart-panel {
min-width: 0 !important;
max-width: 100% !important;
}
/* ---- 话术 ---- */
.reply-category {
border: 1px solid #d9e2ef !important;
@@ -13,6 +13,11 @@ import {
getTimeoutListAll,
saveTimeoutHours,
} from '/@/views/inquiry/systemSetting/systemSetting.api';
import { usePermission } from '/@/hooks/web/usePermission';
import { InquiryBtnPerm } from '/@/views/inquiry/shared/inquiryPagePerms';
const { hasPermission } = usePermission();
const canEditTimeout = () => hasPermission(InquiryBtnPerm.timeoutEdit);
/** 分块顺序:海运 → 空运 → 陆运(产品确认同页分块) */
const MODE_BLOCKS = [
@@ -153,7 +158,7 @@ async function commitHours(row) {
min="0"
step="0.01"
:value="draftHours[row.id]"
:disabled="savingId === row.id"
:disabled="!canEditTimeout() || savingId === row.id"
@input="onHoursInput(row.id, $event.target.value)"
@blur="commitHours(row)"
@keydown.enter.prevent="commitHours(row)"
@@ -27,6 +27,13 @@ import {
summarizeMappingParse,
type MappingParseSummary,
} from "/@/views/inquiry/template/previewSample";
import { usePermission } from "/@/hooks/web/usePermission";
import { InquiryBtnPerm } from "/@/views/inquiry/shared/inquiryPagePerms";
const { hasPermission } = usePermission();
const canUploadTemplate = () => hasPermission(InquiryBtnPerm.templateUpload);
const canEditTemplate = () => hasPermission(InquiryBtnPerm.templateEdit);
const canToggleTemplate = () => hasPermission(InquiryBtnPerm.templateToggle);
// buildTemplateFileUrl 已由 downloadTemplateFile 替代(鉴权 blob 下载)
@@ -683,7 +690,12 @@ async function downloadPreviewOrOriginal() {
<template>
<!-- 唯一上传入口:顶栏 -->
<Teleport defer to="#page-topbar-actions">
<button type="button" class="btn btn-primary" @click.stop.prevent="openCreate">
<button
v-if="canUploadTemplate()"
type="button"
class="btn btn-primary"
@click.stop.prevent="openCreate"
>
<ProtoIcon name="upload" :size="16" />上传模板
</button>
</Teleport>
@@ -773,8 +785,16 @@ async function downloadPreviewOrOriginal() {
<button type="button" class="link-action link-muted" @click.stop="openPreview(row)">
预览
</button>
<button type="button" class="link-action" @click.stop="openEdit(row)">编辑</button>
<button
v-if="canEditTemplate()"
type="button"
class="link-action"
@click.stop="openEdit(row)"
>
编辑
</button>
<button
v-if="canEditTemplate()"
type="button"
class="link-action"
:disabled="row.parseStatus === '解析中'"
@@ -788,6 +808,7 @@ async function downloadPreviewOrOriginal() {
重新解析
</button>
<button
v-if="canToggleTemplate()"
type="button"
class="link-action"
:class="row.status === 'enabled' ? 'link-danger' : ''"
@@ -795,7 +816,12 @@ async function downloadPreviewOrOriginal() {
>
{{ row.status === "enabled" ? "禁用" : "启用" }}
</button>
<button type="button" class="link-action link-danger" @click.stop="removeTemplate(row)">
<button
v-if="canEditTemplate()"
type="button"
class="link-action link-danger"
@click.stop="removeTemplate(row)"
>
删除
</button>
</div>
@@ -804,7 +830,7 @@ async function downloadPreviewOrOriginal() {
</tbody>
</table>
</div>
<div class="pagination">
<div class="pagination admin-pagination">
<span>
共 <b style="color: #0f172a">{{ filtered.length }}</b> 个模板
</span>
@@ -22,6 +22,23 @@ import {
quantitySummary,
type DemandField,
} from "/@/views/inquiry/workOrder/demandFields";
import { usePermission } from "/@/hooks/web/usePermission";
import { InquiryBtnPerm } from "/@/views/inquiry/shared/inquiryPagePerms";
const { hasPermission } = usePermission();
const canCloseTicket = () => hasPermission(InquiryBtnPerm.workorderTransition);
const canRetryTicket = () => hasPermission(InquiryBtnPerm.workorderTransition);
const canViewDetail = () =>
hasPermission(InquiryBtnPerm.workorderDetail) || hasPermission(InquiryBtnPerm.workorderList);
/**
* 与主账 TicketStatuses 一致:仅询价中/已报价/协商中/转人工可关到「已关闭」。
* 已成交/未成交/已关闭为终态,禁止再显示「关闭工单」(否则点确认会报不允许流转)。
*/
const CLOSEABLE_STATUSES = new Set(["询价中", "已报价", "协商中", "转人工"]);
function canShowCloseForStatus(status: string) {
return canCloseTicket() && CLOSEABLE_STATUSES.has(String(status || "").trim());
}
/** 单条费用明细:名称 + 带币种金额,对齐企微价格明细。 */
type TicketQuoteFee = { name: string; amount: string };
@@ -253,9 +270,88 @@ function parseQuoteFees(q: any): TicketQuoteFee[] {
pushRows(asFeeArray(payload[key] || payload[bucket]));
}
}
// 陆运 TMS:燃油附加费率 / 税率挂在线路段上,不是金额费目行。
for (const extra of parseLandRateFees(payload)) {
if (!out.some((x) => x.name === extra.name && x.amount === extra.amount)) {
out.push(extra);
}
}
return out;
}
/**
* 陆运线路:fuelSurchargeRate=燃油附加费率;rate=税率;rateFlag=是否含税(1是0否)。
* 只读 payload,不写库。海运/空运没有这些键则不出行。
*/
function parseLandRateFees(payload: Record<string, any>): TicketQuoteFee[] {
const rows = asFeeArray(payload.route_rows || payload.landSegments || payload.land_segments);
const out: TicketQuoteFee[] = [];
const seen = new Set<string>();
for (const row of rows) {
if (!row || typeof row !== "object") continue;
const fuel = formatLandPercent(row.fuel_surcharge_rate ?? row.fuelSurchargeRate);
const tax = formatLandTaxRate(row.tax_rate ?? row.taxRate ?? row.rate);
const included = formatLandTaxIncluded(
row.tax_included ?? row.rateFlag ?? row.rate_flag
);
if (fuel) {
const key = `fuel:${fuel}`;
if (!seen.has(key)) {
seen.add(key);
out.push({ name: "燃油附加费率", amount: fuel });
}
}
if (tax) {
const key = `tax:${tax}`;
if (!seen.has(key)) {
seen.add(key);
out.push({ name: "税率", amount: tax });
}
}
if (included) {
const key = `inc:${included}`;
if (!seen.has(key)) {
seen.add(key);
out.push({ name: "是否含税", amount: included });
}
}
}
return out;
}
/** 燃油附加费率:数字带 %。 */
function formatLandPercent(raw: unknown): string {
const s = String(raw ?? "").trim();
if (!s || s === "-" || s.toLowerCase() === "null") return "";
if (s.includes("%")) return s;
if (/^-?\d+(\.\d+)?$/.test(s)) {
return `${s.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "")}%`;
}
return s;
}
/** 税率 rate:0.09→9%;大于 1 按百分点。 */
function formatLandTaxRate(raw: unknown): string {
const s = String(raw ?? "").trim();
if (!s || s === "-" || s.toLowerCase() === "null") return "";
if (s.includes("%")) return s;
if (!/^-?\d+(\.\d+)?$/.test(s)) return s;
const n = Number(s);
if (!Number.isFinite(n)) return s;
const abs = Math.abs(n);
const pct = abs > 0 && abs <= 1 ? n * 100 : n;
return `${String(pct).replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "")}%`;
}
/** rateFlag:1=含税,0=不含税。 */
function formatLandTaxIncluded(raw: unknown): string {
const s = String(raw ?? "").trim();
if (!s || s === "-" || s.toLowerCase() === "null") return "";
if (s === "1" || s.toLowerCase() === "true" || s === "是" || s === "含税") return "含税";
if (s === "0" || s.toLowerCase() === "false" || s === "否" || s === "不含税") return "不含税";
return s;
}
/**
* 主账 inq_ticket_status_log.action 是内部码,禁止当备注展示。
* transition 与「已报价」等 toStatus 重复,无用户备注时不再跟一段英文。
@@ -536,6 +632,10 @@ async function openDetail(row: TicketRow) {
}
function openClose(row: TicketRow) {
if (!canShowCloseForStatus(row.status)) {
message.warning(`「${row.status}」为终态,不能关闭工单`);
return;
}
current.value = row;
closeReason.value = "";
closeOpen.value = true;
@@ -824,7 +924,7 @@ function refresh() {
<td class="align-top col-actions col-sticky-right">
<div class="ticket-row-actions">
<button
v-if="row.systemException !== '-' && row.status !== '已关闭'"
v-if="canRetryTicket() && row.systemException !== '-' && row.status !== '已关闭'"
class="link-action"
type="button"
@click="retryTicket(row)"
@@ -832,14 +932,21 @@ function refresh() {
重试
</button>
<button
v-if="row.status !== '已关闭'"
v-if="canShowCloseForStatus(row.status)"
class="link-action"
type="button"
@click="openClose(row)"
>
关闭工单
</button>
<button class="link-action" type="button" @click="openDetail(row)">查看详情</button>
<button
v-if="canViewDetail()"
class="link-action"
type="button"
@click="openDetail(row)"
>
查看详情
</button>
</div>
</td>
</tr>
@@ -867,7 +974,12 @@ function refresh() {
<template #titleExtra>
<span v-if="current" class="ticket-detail-no">{{ current.id }}</span>
<button
v-if="current && current.systemException !== '-' && current.status !== '已关闭'"
v-if="
canRetryTicket() &&
current &&
current.systemException !== '-' &&
current.status !== '已关闭'
"
class="link-action"
type="button"
@click="retryTicket(current)"