Files
syops/backend/app/services/shipping_notice/notice_lines.py
T

848 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
services/shipping_notice/notice_lines.py
用途:标准化发货通知订单行,并从文本/表格中抽取可用于后续库存匹配的行级结构化数据。
依赖:reservation_id、inventory_snapshot 的表格转行工具、正则与字段映射常量。
逻辑:由 extract/task_workflow 等上游模块调用本文件完成订单行归一化,再把结果交给匹配、人工更正与摘要生成链路。
"""
from __future__ import annotations
import re
from typing import Any
from app.services.shipping_notice.reservation_id import (
extract_reservation_id,
find_reservation_id_in_document,
looks_like_reservation_id,
normalize_reservation_id,
)
NOTICE_LINE_FIELDS = (
"line_no",
"sku",
"qty",
"unit_price",
"amount",
"currency",
"reservation_id",
"required_date",
"vendor_part_number",
"uom",
"remark",
)
# 订单行表头 → 系统字段(发货通知 PDF/Excel/邮件表格)
NOTICE_COLUMN_MAP: dict[str, str] = {
# SKU
"料号": "sku",
"SKU": "sku",
"sku": "sku",
"AWS Sku": "sku",
"AWS SKU": "sku",
"Part Number": "sku",
"Material": "sku",
"Material No": "sku",
"产品编号": "sku",
# 项次 / Item
"项次": "line_no",
"line_no": "line_no",
"Line No": "line_no",
"Line Number": "line_no",
"Line #": "line_no",
"Line": "line_no",
"Item": "line_no",
"Item No": "line_no",
"Item Number": "line_no",
# 需求数量
"数量": "qty",
"Qty": "qty",
"qty": "qty",
"Quantity": "qty",
"需求数量": "qty",
"订购数量": "qty",
"Order Qty": "qty",
"Ship Qty": "qty",
"发货数量": "qty",
# 单价
"单价": "unit_price",
"Unit Price": "unit_price",
"unit_price": "unit_price",
"Price": "unit_price",
"Unit Cost": "unit_price",
"价格": "unit_price",
# 金额
"金额": "amount",
"Amount": "amount",
"amount": "amount",
"Total": "amount",
"Line Amount": "amount",
"Line Total": "amount",
"小计": "amount",
"总价": "amount",
"Total Amount": "amount",
# 币种
"Currency": "currency",
"currency": "currency",
"Curr": "currency",
"CCY": "currency",
"币种": "currency",
"币别": "currency",
# Reservation ID
"Reservation ID": "reservation_id",
"Reservation Id": "reservation_id",
"reservation_id": "reservation_id",
"COM ID": "reservation_id",
"Reservation Order": "reservation_id",
"Reservation No": "reservation_id",
"Resv ID": "reservation_id",
"PR Number": "reservation_id",
"PR No": "reservation_id",
"PR#": "reservation_id",
# 交货日期
"Required Date": "required_date",
"Delivery Date": "required_date",
"required_date": "required_date",
"ETA": "required_date",
"交期": "required_date",
"交货日期": "required_date",
"要求交期": "required_date",
"Required Delivery Date": "required_date",
# 供应商料号
"Vendor Part Number": "vendor_part_number",
"Vendor Part No": "vendor_part_number",
"Vendor PN": "vendor_part_number",
"vendor_part_number": "vendor_part_number",
"Supplier Part No": "vendor_part_number",
"Supplier Part Number": "vendor_part_number",
"MPN": "vendor_part_number",
"供应商料号": "vendor_part_number",
# 单位
"单位": "uom",
"UOM": "uom",
"uom": "uom",
"Unit": "uom",
}
NOTICE_FIELD_LABELS = {
"line_no": "项次 / Item / Line No",
"sku": "SKU / 料号",
"qty": "需求数量",
"unit_price": "单价",
"amount": "金额",
"currency": "币种",
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
"required_date": "要求交期 / 交货日期",
"vendor_part_number": "供应商料号",
}
_HEADER_SKIP_TOKENS = {
"sku",
"料号",
"aws sku",
"qty",
"quantity",
"数量",
"reservation id",
"com id",
"单价",
"unit price",
"金额",
"amount",
"currency",
"币种",
"line no",
"item no",
"项次",
}
def _norm_header(value: Any) -> str:
return re.sub(r"\s+", " ", str(value or "").strip().lower())
def _map_notice_header(header: str, col_map: dict[str, str] | None = None) -> str | None:
text = str(header or "").strip()
if not text:
return None
mapping = col_map or NOTICE_COLUMN_MAP
if text in mapping:
return mapping[text]
norm = _norm_header(text)
for key, field in mapping.items():
if _norm_header(key) == norm:
return field
return None
def _resolve_notice_columns(headers: list[str]) -> dict[str, int | None]:
columns: dict[str, int | None] = {field: None for field in NOTICE_LINE_FIELDS if field not in {"uom", "remark"}}
for i, header in enumerate(headers):
mapped = _map_notice_header(header)
if mapped and columns.get(mapped) is None:
columns[mapped] = i
# Reservation 列名兜底
if columns.get("reservation_id") is None:
for i, header in enumerate(headers):
norm = _norm_header(header)
if norm in {"com id", "reservation order", "reservation id", "reservation no", "resv id"}:
columns["reservation_id"] = i
break
return columns
def _cell(row: list[Any] | tuple[Any, ...], index: int | None) -> Any:
if index is None or index >= len(row):
return None
return row[index]
def _normalize_line_no(value: Any) -> str:
if value is None:
return ""
if isinstance(value, float) and value.is_integer():
return str(int(value))
text = str(value).strip()
if not text:
return ""
if text.lower() in _HEADER_SKIP_TOKENS:
return ""
num = _parse_number(text)
if num is not None and num == int(num):
compact = text.replace(",", "").replace(",", "")
if re.fullmatch(r"\d+(?:\.0+)?", compact):
return str(int(num))
return text
def _normalize_required_date(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
m = re.match(r"^(\d{4})[/.-](\d{1,2})[/.-](\d{1,2})$", text)
if m:
return f"{m.group(1)}-{int(m.group(2)):02d}-{int(m.group(3)):02d}"
return text
_KNOWN_CURRENCY_CODES = frozenset(
{
"USD",
"EUR",
"GBP",
"JPY",
"CNY",
"RMB",
"HKD",
"TWD",
"SGD",
"AUD",
"CAD",
"KRW",
"INR",
"CHF",
"SEK",
"NOK",
"DKK",
"MYR",
"THB",
"VND",
"PHP",
"IDR",
"MXN",
"BRL",
"NZD",
}
)
_CURRENCY_ALIASES = {
"人民币": "CNY",
"美元": "USD",
"欧元": "EUR",
"英镑": "GBP",
"日元": "JPY",
"港币": "HKD",
"港元": "HKD",
"新台币": "TWD",
"新加坡元": "SGD",
"澳元": "AUD",
"加元": "CAD",
}
def _normalize_currency(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
upper = text.upper()
if upper in _KNOWN_CURRENCY_CODES:
return "CNY" if upper == "RMB" else upper
if text in _CURRENCY_ALIASES:
return _CURRENCY_ALIASES[text]
return ""
def _extract_currency(*values: Any) -> str:
for value in values:
text = str(value or "").strip()
if not text:
continue
normalized = _normalize_currency(text)
if normalized:
return normalized
if text.startswith("$"):
return "USD"
if text.startswith("¥") or text.startswith("¥"):
return "CNY"
match = re.search(r"\b([A-Z]{3})\b", text.upper())
if match and match.group(1) in _KNOWN_CURRENCY_CODES:
code = match.group(1)
return "CNY" if code == "RMB" else code
return ""
def _parse_number(value: Any) -> float | None:
if value is None:
return None
text = str(value).strip()
if not text:
return None
text = text.replace(",", "").replace(",", "")
if text.startswith("$") or text.startswith("¥") or text.startswith("¥"):
text = text[1:].strip()
match = re.search(r"[-+]?\d+(?:\.\d+)?", text)
if not match:
return None
try:
return float(match.group(0))
except (TypeError, ValueError):
return None
def _infer_reservation_id_from_row(
row: list[Any] | tuple[Any, ...],
*,
skip_indices: set[int],
) -> str:
for i, cell in enumerate(row):
if i in skip_indices:
continue
if looks_like_reservation_id(cell):
return extract_reservation_id(cell)
return ""
def _parse_notice_row(
row: list[Any] | tuple[Any, ...],
columns: dict[str, int | None],
*,
default_sku_index: int = 0,
default_qty_index: int = 1,
) -> dict[str, Any] | None:
idx_sku = columns.get("sku")
if idx_sku is None:
idx_sku = default_sku_index
sku = str(_cell(row, idx_sku) or "").strip()
if not sku:
return None
if sku.lower() in _HEADER_SKIP_TOKENS:
return None
idx_qty = columns.get("qty")
if idx_qty is not None:
qty = _parse_number(_cell(row, idx_qty))
else:
qty = _parse_number(_cell(row, default_qty_index))
if qty is None or qty <= 0:
return None
parsed: dict[str, Any] = {"sku": sku, "qty": qty, "uom": "EA"}
skip_indices: set[int] = {idx_sku}
if idx_qty is not None:
skip_indices.add(idx_qty)
idx_line_no = columns.get("line_no")
if idx_line_no is not None:
line_no = _normalize_line_no(_cell(row, idx_line_no))
skip_indices.add(idx_line_no)
if line_no:
parsed["line_no"] = line_no
idx_res = columns.get("reservation_id")
reservation_id = ""
if idx_res is not None:
reservation_id = extract_reservation_id(_cell(row, idx_res))
skip_indices.add(idx_res)
else:
reservation_id = _infer_reservation_id_from_row(row, skip_indices=skip_indices)
if reservation_id:
parsed["reservation_id"] = reservation_id
idx_price = columns.get("unit_price")
price_cell = None
if idx_price is not None:
price_cell = _cell(row, idx_price)
unit_price = _parse_number(price_cell)
if unit_price is not None:
parsed["unit_price"] = unit_price
idx_amount = columns.get("amount")
amount_cell = None
if idx_amount is not None:
amount_cell = _cell(row, idx_amount)
amount = _parse_number(amount_cell)
if amount is not None:
parsed["amount"] = amount
idx_currency = columns.get("currency")
currency = _extract_currency(
_cell(row, idx_currency) if idx_currency is not None else None,
price_cell,
amount_cell,
)
if currency:
parsed["currency"] = currency
idx_uom = columns.get("uom")
if idx_uom is not None:
uom = str(_cell(row, idx_uom) or "").strip()
if uom:
parsed["uom"] = uom
idx_required_date = columns.get("required_date")
if idx_required_date is not None:
required_date = _normalize_required_date(_cell(row, idx_required_date))
if required_date:
parsed["required_date"] = required_date
idx_vendor_part = columns.get("vendor_part_number")
if idx_vendor_part is not None:
vendor_part_number = str(_cell(row, idx_vendor_part) or "").strip()
if vendor_part_number:
parsed["vendor_part_number"] = vendor_part_number
# 若仅有 qty * unit_price,可推算 amount
if "amount" not in parsed and "unit_price" in parsed:
computed = round(parsed["unit_price"] * qty, 4)
if computed > 0:
parsed["amount"] = computed
return parsed
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 或缺数量的脏数据。
Args:
lines: 原始订单行列表。
Returns:
list[dict[str, Any]]: 标准化后的有效订单行集合。
"""
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,找不到再从原始文本中兜底提取。
Args:
parsed: 已解析出的发货通知结构。
raw_text: 原始发货通知文本,用于补充文档级 Reservation ID。
Returns:
dict[str, Any]: 已完成文档级 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 回填缺失的订单行交期。
核心逻辑:统一格式化文档级日期,并在订单行未给出独立交期时逐行补齐。
Args:
parsed: 已解析出的发货通知结构。
Returns:
dict[str, Any]: 已完成文档级交期回填的解析结果。
"""
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]:
"""
用文档级币种回填缺失的订单行币种。
核心逻辑:统一币种代码,并在订单行未给出币种时沿用文档级币种。
Args:
parsed: 已解析出的发货通知结构。
Returns:
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 parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]:
"""
从发货通知原始文本中的表格片段解析订单行。
核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。
Args:
raw_text: 原始发货通知文本,通常来自 PDF/OCR/邮件正文。
Returns:
list[dict[str, Any]]: 解析出的订单行列表。
"""
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
text = str(raw_text or "").strip()
if not text:
return []
rows = _rows_from_table_text(text)
if not rows:
return []
header_idx = _find_notice_header_row_index(rows)
header = [str(c or "").strip() for c in rows[header_idx]]
data_rows = rows[header_idx + 1 :]
lines = parse_notice_table_rows(header, data_rows)
doc_rid = find_reservation_id_in_document(text)
if doc_rid:
for line in lines:
if not line.get("reservation_id"):
line["reservation_id"] = doc_rid
return lines
def _score_notice_header_row(cells: list[Any]) -> int:
headers = [str(c or "").strip() for c in cells]
if len([h for h in headers if h]) < 2:
return 0
mapped: set[str] = set()
for h in headers:
field = _map_notice_header(h)
if field:
mapped.add(field)
score = len(mapped) * 10
if "sku" in mapped and "qty" in mapped:
score += 30
if "reservation_id" in mapped:
score += 10
if "unit_price" in mapped or "amount" in mapped:
score += 5
return score
def _find_notice_header_row_index(rows: list[list[Any]], *, max_scan: int = 40) -> int:
best_idx = 0
best_score = 0
for i, row in enumerate(rows[:max_scan]):
score = _score_notice_header_row(list(row))
if score > best_score:
best_score = score
best_idx = i
return best_idx if best_score > 0 else 0
def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> list[dict[str, Any]]:
"""
按表头定义解析发货通知表格数据行。
核心逻辑:根据 headers 推断列映射,仅在识别到有效表头时逐行提取 SKU、数量、金额等字段。
Args:
headers: 表头行。
data_rows: 表头之后的数据行集合。
Returns:
list[dict[str, Any]]: 解析后的订单行列表。
"""
columns = _resolve_notice_columns(headers)
has_header = columns.get("sku") is not None or columns.get("qty") is not None
if not has_header and headers:
has_header = any(_map_notice_header(h) for h in headers)
if not has_header:
return []
lines: list[dict[str, Any]] = []
for row in data_rows:
if not row:
continue
parsed = _parse_notice_row(list(row), columns)
if parsed:
lines.append(parsed)
return lines
def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
"""
生成订单行解析质量告警。
核心逻辑:检查 Reservation ID、价格字段等关键完整性,输出给前端/Agent 的提醒文本。
Args:
lines: 已标准化的订单行列表。
Returns:
list[str]: 告警文案列表,为空表示未发现明显问题。
"""
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;后续将仅按 SKU 汇总库存比对,"
"若订单含 COM ID / Reservation Order 请核对表头。"
)
elif missing_reservation:
warnings.append(
f"部分订单行缺少 Reservation ID({len(missing_reservation)}/{len(lines)} 行),"
"这些行将按 SKU 汇总库存比对。"
)
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 分数。
Args:
lines: 已标准化的订单行列表。
Returns:
float: 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)