343 lines
11 KiB
Python
343 lines
11 KiB
Python
"""
|
||
services/shipping_notice/notice_lines.py
|
||
|
||
用途:发货通知订单行的标准化、文档级回填、质量校验与完整度评估(对外统一入口)。
|
||
依赖:notice_line_constants、notice_line_values、notice_line_table、reservation_id。
|
||
逻辑:由 extract/task_workflow 等上游模块调用本文件;表格解析委托 notice_line_table,字段归一化委托 notice_line_values。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
|
||
from app.services.shipping_notice.notice_line_constants import (
|
||
HEADER_SKIP_TOKENS,
|
||
NOTICE_COLUMN_MAP,
|
||
NOTICE_FIELD_LABELS,
|
||
NOTICE_LINE_FIELDS,
|
||
)
|
||
from app.services.shipping_notice.notice_line_table import (
|
||
parse_notice_table_rows,
|
||
parse_notice_table_text,
|
||
)
|
||
from app.services.shipping_notice.notice_line_values import (
|
||
extract_currency,
|
||
map_notice_header,
|
||
norm_header,
|
||
normalize_currency,
|
||
normalize_line_no,
|
||
normalize_required_date,
|
||
parse_number,
|
||
)
|
||
from app.services.shipping_notice.reservation_id import (
|
||
extract_reservation_id,
|
||
find_reservation_id_in_document,
|
||
looks_like_reservation_id,
|
||
)
|
||
|
||
# 向后兼容:旧代码/tests 仍可从 notice_lines 引用私有别名
|
||
_HEADER_SKIP_TOKENS = HEADER_SKIP_TOKENS
|
||
_extract_currency = extract_currency
|
||
_norm_header = norm_header
|
||
_map_notice_header = map_notice_header
|
||
_parse_number = parse_number
|
||
|
||
|
||
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||
"""
|
||
标准化单条发货通知订单行。
|
||
|
||
核心逻辑:校验 SKU 与数量必填项,统一字段别名、币种、交期和 Reservation ID,并在缺少 amount 时按单价回填。
|
||
Args:
|
||
raw: 原始订单行字典,可包含多种字段别名。
|
||
|
||
Returns:
|
||
dict[str, Any] | None: 归一化后的订单行;若缺少关键字段则返回 None。
|
||
"""
|
||
if not isinstance(raw, dict):
|
||
return None
|
||
|
||
sku = str(raw.get("sku") or raw.get("part_number") or raw.get("material") or "").strip()
|
||
if not sku:
|
||
return None
|
||
|
||
qty = parse_number(raw.get("qty") if raw.get("qty") is not None else raw.get("quantity"))
|
||
if qty is None or qty <= 0:
|
||
return None
|
||
|
||
line: dict[str, Any] = {
|
||
"sku": sku,
|
||
"qty": qty,
|
||
"uom": str(raw.get("uom") or "EA").strip() or "EA",
|
||
}
|
||
|
||
line_no = normalize_line_no(
|
||
raw.get("line_no")
|
||
or raw.get("lineNo")
|
||
or raw.get("item")
|
||
or raw.get("item_no")
|
||
or raw.get("itemNo")
|
||
or raw.get("Item")
|
||
or raw.get("Item No")
|
||
)
|
||
if line_no:
|
||
line["line_no"] = line_no
|
||
|
||
reservation_id = extract_reservation_id(
|
||
raw.get("reservation_id")
|
||
or raw.get("reservationId")
|
||
or raw.get("com_id")
|
||
or raw.get("reservation_order")
|
||
or raw.get("pr_number")
|
||
or raw.get("prNumber")
|
||
or raw.get("PR Number")
|
||
)
|
||
if reservation_id:
|
||
line["reservation_id"] = reservation_id
|
||
|
||
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:
|
||
line["unit_price"] = unit_price
|
||
|
||
amount = parse_number(raw.get("amount") if raw.get("amount") is not None else raw.get("total"))
|
||
if amount is not None:
|
||
line["amount"] = amount
|
||
elif unit_price is not None:
|
||
line["amount"] = round(unit_price * qty, 4)
|
||
|
||
currency = normalize_currency(raw.get("currency") or raw.get("Currency"))
|
||
if not currency:
|
||
currency = extract_currency(
|
||
raw.get("unit_price"),
|
||
raw.get("price"),
|
||
raw.get("amount"),
|
||
raw.get("total"),
|
||
)
|
||
if currency:
|
||
line["currency"] = currency
|
||
|
||
required_date = normalize_required_date(
|
||
raw.get("required_date")
|
||
or raw.get("delivery_date")
|
||
or raw.get("deliveryDate")
|
||
or raw.get("eta")
|
||
or raw.get("ETA")
|
||
)
|
||
if required_date:
|
||
line["required_date"] = required_date
|
||
|
||
vendor_part_number = str(
|
||
raw.get("vendor_part_number")
|
||
or raw.get("vendorPartNumber")
|
||
or raw.get("vendor_pn")
|
||
or raw.get("supplier_part_number")
|
||
or raw.get("supplierPartNumber")
|
||
or ""
|
||
).strip()
|
||
if vendor_part_number:
|
||
line["vendor_part_number"] = vendor_part_number
|
||
|
||
remark = str(raw.get("remark") or raw.get("note") or "").strip()
|
||
if remark:
|
||
line["remark"] = remark
|
||
|
||
return line
|
||
|
||
|
||
def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
|
||
"""
|
||
批量标准化订单行列表。
|
||
|
||
核心逻辑:逐行调用 `normalize_notice_line`,自动过滤掉无效、缺 SKU 或缺数量的脏数据。
|
||
"""
|
||
if not isinstance(lines, list):
|
||
return []
|
||
normalized: list[dict[str, Any]] = []
|
||
for item in lines:
|
||
parsed = normalize_notice_line(item if isinstance(item, dict) else None)
|
||
if parsed:
|
||
normalized.append(parsed)
|
||
return normalized
|
||
|
||
|
||
def enrich_notice_with_document_reservation(
|
||
parsed: dict[str, Any],
|
||
*,
|
||
raw_text: str = "",
|
||
) -> dict[str, Any]:
|
||
"""
|
||
用文档级 Reservation ID 回填缺失的订单行。
|
||
|
||
核心逻辑:优先从 parsed 字段中找 document-level Reservation ID,找不到再从原始文本中兜底提取。
|
||
"""
|
||
doc_rid = ""
|
||
for key in (
|
||
"reservation_id",
|
||
"reservationId",
|
||
"document_reservation_id",
|
||
"pr_number",
|
||
"prNumber",
|
||
"PR Number",
|
||
):
|
||
extracted = extract_reservation_id(parsed.get(key))
|
||
if extracted and looks_like_reservation_id(extracted):
|
||
doc_rid = extracted
|
||
break
|
||
|
||
if not doc_rid:
|
||
doc_rid = find_reservation_id_in_document(raw_text)
|
||
|
||
if not doc_rid:
|
||
return parsed
|
||
|
||
lines = parsed.get("lines")
|
||
if not isinstance(lines, list):
|
||
return parsed
|
||
|
||
for line in lines:
|
||
if not isinstance(line, dict):
|
||
continue
|
||
if not str(line.get("reservation_id") or "").strip():
|
||
line["reservation_id"] = doc_rid
|
||
|
||
parsed["reservation_id"] = doc_rid
|
||
parsed.pop("document_reservation_id", None)
|
||
return parsed
|
||
|
||
|
||
def enrich_notice_with_document_required_date(parsed: dict[str, Any]) -> dict[str, Any]:
|
||
"""用文档级 required_date 回填缺失的订单行交期。"""
|
||
doc_date = normalize_required_date(
|
||
parsed.get("required_date") or parsed.get("document_required_date")
|
||
)
|
||
if not doc_date:
|
||
return parsed
|
||
|
||
lines = parsed.get("lines")
|
||
if not isinstance(lines, list):
|
||
return parsed
|
||
|
||
has_line_dates = any(
|
||
isinstance(line, dict) and str(line.get("required_date") or "").strip() for line in lines
|
||
)
|
||
if not has_line_dates:
|
||
parsed["required_date"] = doc_date
|
||
|
||
for line in lines:
|
||
if not isinstance(line, dict):
|
||
continue
|
||
if not str(line.get("required_date") or "").strip():
|
||
line["required_date"] = doc_date
|
||
|
||
parsed.pop("document_required_date", None)
|
||
return parsed
|
||
|
||
|
||
def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, Any]:
|
||
"""用文档级币种回填缺失的订单行币种。"""
|
||
doc_currency = normalize_currency(
|
||
parsed.get("currency") or parsed.get("document_currency")
|
||
)
|
||
if not doc_currency:
|
||
return parsed
|
||
|
||
lines = parsed.get("lines")
|
||
if not isinstance(lines, list):
|
||
return parsed
|
||
|
||
has_line_currency = any(
|
||
isinstance(line, dict) and str(line.get("currency") or "").strip() for line in lines
|
||
)
|
||
if not has_line_currency:
|
||
parsed["currency"] = doc_currency
|
||
|
||
for line in lines:
|
||
if not isinstance(line, dict):
|
||
continue
|
||
if not str(line.get("currency") or "").strip():
|
||
line["currency"] = doc_currency
|
||
|
||
parsed.pop("document_currency", None)
|
||
return parsed
|
||
|
||
|
||
def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
|
||
"""
|
||
生成订单行解析质量告警。
|
||
|
||
核心逻辑:检查 Reservation ID、价格字段等关键完整性,输出给前端/Agent 的提醒文本。
|
||
"""
|
||
warnings: list[str] = []
|
||
if not lines:
|
||
warnings.append("未解析到有效订单行(需至少包含 SKU 与需求数量)。")
|
||
return warnings
|
||
|
||
missing_reservation = [line["sku"] for line in lines if not str(line.get("reservation_id") or "").strip()]
|
||
if missing_reservation and len(missing_reservation) == len(lines):
|
||
warnings.append(
|
||
"订单行未解析到 Reservation ID;当前匹配规则会阻断后续库存匹配,"
|
||
"若订单含 COM ID / Reservation Order 请返回解析阶段核对表头。"
|
||
)
|
||
elif missing_reservation:
|
||
warnings.append(
|
||
f"部分订单行缺少 Reservation ID({len(missing_reservation)}/{len(lines)} 行),"
|
||
"当前匹配规则会阻断后续库存匹配,请先修正解析结果。"
|
||
)
|
||
|
||
invalid_reservation = [
|
||
line["sku"]
|
||
for line in lines
|
||
if str(line.get("reservation_id") or "").strip()
|
||
and not looks_like_reservation_id(line.get("reservation_id"))
|
||
]
|
||
if invalid_reservation:
|
||
warnings.append(
|
||
f"{len(invalid_reservation)} 行 Reservation ID 非典型纯数字格式(常见为 8~12 位,如 1000140351),"
|
||
"请核对是否解析正确。"
|
||
)
|
||
|
||
missing_price = sum(1 for line in lines if line.get("unit_price") is None and line.get("amount") is None)
|
||
if missing_price:
|
||
warnings.append(f"{missing_price} 行未解析到单价或金额(不影响库存匹配)。")
|
||
|
||
return warnings
|
||
|
||
|
||
def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
|
||
"""
|
||
评估订单行解析完整度。
|
||
|
||
核心逻辑:按 SKU、数量、Reservation ID、价格等字段覆盖率计算 0~1 分数。
|
||
"""
|
||
if not lines:
|
||
return 0.0
|
||
scores: list[float] = []
|
||
for line in lines:
|
||
item = 0.0
|
||
if line.get("sku"):
|
||
item += 0.35
|
||
if line.get("qty"):
|
||
item += 0.35
|
||
if 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
|
||
scores.append(item)
|
||
return round(sum(scores) / len(scores), 4)
|
||
|
||
|
||
__all__ = [
|
||
"NOTICE_COLUMN_MAP",
|
||
"NOTICE_FIELD_LABELS",
|
||
"NOTICE_LINE_FIELDS",
|
||
"enrich_notice_with_document_currency",
|
||
"enrich_notice_with_document_required_date",
|
||
"enrich_notice_with_document_reservation",
|
||
"normalize_notice_line",
|
||
"normalize_notice_lines",
|
||
"notice_parse_completeness",
|
||
"parse_notice_table_rows",
|
||
"parse_notice_table_text",
|
||
"validate_notice_lines",
|
||
]
|