feat(shipping-notice): 增强发货通知候选管理功能,支持候选选择、重复检测与业务摘要修订

This commit is contained in:
hugo committed 2026-07-15 11:57:04 +08:00
1 parent 70f684b94a
commit b595e157e9
83 files changed
+5857 -200

No files matched your search

@@ -8,6 +8,7 @@ services/shipping_notice/notice_lines.py
from __future__ import annotations
import re
from typing import Any
from app.services.shipping_notice.notice_line_constants import (
@@ -33,6 +34,8 @@ from app.services.shipping_notice.reservation_id import (
extract_reservation_id,
find_reservation_id_in_document,
looks_like_reservation_id,
is_valid_reservation_id,
validated_reservation_id,
)
# 向后兼容:旧代码/tests 仍可从 notice_lines 引用私有别名
@@ -43,6 +46,13 @@ _map_notice_header = map_notice_header
_parse_number = parse_number
def derive_hub_code(source_type: Any) -> str:
"""从已知库存来源提示中派生 Hub Code,如 VMI-FRA01→FRA01、DBS DUB→DUB。"""
text = re.sub(r"\s+", " ", str(source_type or "").strip().upper())
match = re.fullmatch(r"(?:VMI|DBS)[\s_-]+([A-Z0-9]+)", text)
return match.group(1) if match else ""
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
"""
标准化单条发货通知订单行。
@@ -94,6 +104,9 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
)
if reservation_id:
line["reservation_id"] = reservation_id
evidence = raw.get("reservation_id_evidence")
if isinstance(evidence, dict):
line["reservation_id_evidence"] = dict(evidence)
unit_price = parse_number(raw.get("unit_price") if raw.get("unit_price") is not None else raw.get("price"))
if unit_price is not None:
@@ -137,6 +150,23 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
if vendor_part_number:
line["vendor_part_number"] = vendor_part_number
optional_aliases = {
"po_number": ("po_number", "poNumber", "PO", "PO Number"),
"allocation_id": ("allocation_id", "allocationId", "Allocation ID"),
"source_type": ("source_type", "sourceType", "Source Type"),
"customer_sku": ("customer_sku", "customerSku", "allocated_hhpn", "Allocated HHPN"),
"hub_code": ("hub_code", "hubCode", "Hub Code", "Hub", "HUB"),
}
for field, aliases in optional_aliases.items():
value = next((str(raw.get(alias) or "").strip() for alias in aliases if raw.get(alias)), "")
if value:
line[field] = value
if not line.get("hub_code"):
hub_code = derive_hub_code(line.get("source_type"))
if hub_code:
line["hub_code"] = hub_code
remark = str(raw.get("remark") or raw.get("note") or "").strip()
if remark:
line["remark"] = remark
@@ -160,6 +190,110 @@ def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
return normalized
def adjudicate_notice_lines(
lines: list[dict[str, Any]],
*,
raw_text: str = "",
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], str]:
"""
对 LLM 候选订单行执行后端真值裁决,并输出可审计问题清单。
核心逻辑:先从保留列边界的原文解析结构证据;非法候选仅在同 SKU 唯一命中合法表格值时纠正,
否则清空并阻断。合法候选与明确表格证据冲突时保留候选但标记阻断,禁止静默覆盖。
Args:
lines: 已完成基础标准化的 LLM/启发式候选行。
raw_text: 原始通知正文;仅 TSV/HTML 保留下来的明确列关系可作为自动纠错证据。
Returns:
tuple: (裁决后的业务行、parse_issues、validation_status)。
"""
evidence_lines = parse_notice_table_text(raw_text) if "\t" in str(raw_text or "") else []
evidence_by_sku: dict[str, list[dict[str, Any]]] = {}
for evidence_line in evidence_lines:
sku = str(evidence_line.get("sku") or "").strip()
evidence = evidence_line.get("reservation_id_evidence")
source_column = norm_header(evidence.get("source_column")) if isinstance(evidence, dict) else ""
if sku and source_column and validated_reservation_id(evidence_line.get("reservation_id")):
evidence_by_sku.setdefault(sku, []).append(evidence_line)
adjudicated: list[dict[str, Any]] = []
issues: list[dict[str, Any]] = []
for index, source_line in enumerate(lines):
line = dict(source_line)
raw_candidate = str(line.get("reservation_id") or "").strip()
candidate = validated_reservation_id(raw_candidate)
line_sku = str(line.get("sku") or "").strip()
line_vendor_part = str(line.get("vendor_part_number") or "").strip()
matches = list(evidence_by_sku.get(line_sku, []))
if not matches:
matches = [
item
for candidates in evidence_by_sku.values()
for item in candidates
if (
str(item.get("vendor_part_number") or "").strip()
and (
str(item.get("vendor_part_number") or "").strip() == line_vendor_part
or str(item.get("vendor_part_number") or "").strip() in line_sku
)
)
]
evidence_values = {
validated_reservation_id(item.get("reservation_id"))
for item in matches
if validated_reservation_id(item.get("reservation_id"))
}
evidence_values.discard("")
if candidate and evidence_values and candidate not in evidence_values:
issues.append(
{
"line_index": index,
"sku": line.get("sku"),
"field": "reservation_id",
"reason": "source_conflict",
"severity": "blocking",
"raw_value": raw_candidate,
"evidence_values": sorted(evidence_values),
}
)
elif not candidate and len(evidence_values) == 1:
resolved = next(iter(evidence_values))
line["reservation_id"] = resolved
evidence_line = matches[0]
evidence = evidence_line.get("reservation_id_evidence") or {}
issues.append(
{
"line_index": index,
"sku": line.get("sku"),
"field": "reservation_id",
"reason": "value_corrected",
"severity": "info",
"raw_value": raw_candidate,
"resolved_value": resolved,
"resolution_basis": f"email_table.{evidence.get('source_column') or 'Reservation ID'}",
}
)
elif not candidate:
line.pop("reservation_id", None)
issues.append(
{
"line_index": index,
"sku": line.get("sku"),
"field": "reservation_id",
"reason": "missing" if not raw_candidate else "invalid_format",
"severity": "blocking",
"raw_value": raw_candidate,
}
)
else:
line["reservation_id"] = candidate
adjudicated.append(line)
status = "needs_review" if any(item.get("severity") == "blocking" for item in issues) else "ready"
return adjudicated, issues, status
def enrich_notice_with_document_reservation(
parsed: dict[str, Any],
*,
@@ -179,8 +313,8 @@ def enrich_notice_with_document_reservation(
"prNumber",
"PR Number",
):
extracted = extract_reservation_id(parsed.get(key))
if extracted and looks_like_reservation_id(extracted):
extracted = validated_reservation_id(parsed.get(key))
if extracted:
doc_rid = extracted
break
@@ -288,12 +422,11 @@ def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
line["sku"]
for line in lines
if str(line.get("reservation_id") or "").strip()
and not looks_like_reservation_id(line.get("reservation_id"))
and not is_valid_reservation_id(line.get("reservation_id"))
]
if invalid_reservation:
warnings.append(
f"{len(invalid_reservation)} 行 Reservation ID 非典型纯数字格式(常见为 8~12 位,如 1000140351),"
"请核对是否解析正确。"
f"{len(invalid_reservation)} 行 Reservation ID 不满足业务格式契约,请核对来源列与原始值。"
)
missing_price = sum(1 for line in lines if line.get("unit_price") is None and line.get("amount") is None)
@@ -318,7 +451,7 @@ def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
item += 0.35
if line.get("qty"):
item += 0.35
if line.get("reservation_id"):
if is_valid_reservation_id(line.get("reservation_id")):
item += 0.15
if line.get("unit_price") is not None or line.get("amount") is not None:
item += 0.15
@@ -333,6 +466,8 @@ __all__ = [
"enrich_notice_with_document_currency",
"enrich_notice_with_document_required_date",
"enrich_notice_with_document_reservation",
"derive_hub_code",
"adjudicate_notice_lines",
"normalize_notice_line",
"normalize_notice_lines",
"notice_parse_completeness",