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

68 lines
2.5 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/po_number.py
用途:提取、标准化并回填发货通知中的采购单号。
依赖:正则表达式与标准 `typing` 工具。
逻辑:由 extract.py 在发货通知解析收尾阶段调用本文件,把文档级 PO Number 写回解析结果。
"""
from __future__ import annotations
import re
from typing import Any
_PO_NUMBER_PATTERNS = (
r"(?i)(?:PO|P\.O\.)\s*(?:Number|No\.?|#)?\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
r"(?i)Purchase\s+Order\s*(?:Number|No\.?|#)?\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
r"(?:采购订单号|采购单号|订单号|PO号)\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
)
_ATOMIC_PO_NUMBER_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9\-_/]*")
def normalize_po_number(value: Any) -> str:
"""
标准化采购单号;Wistron 等客户原文常带 ZNB 前缀(如 ZNB16754796 / ZNB-16754796),输出为纯数字段。
纯数字 PO 前导零视为格式差异(0060208010 与 60208010 是同一张 PO),统一剥除,避免跨来源误判冲突。
"""
text = str(value or "").strip()
if not text:
return ""
if text.lower() in {"number", "no", "n/a", "na", "none"}:
return ""
upper = text.upper()
if upper.startswith("ZNB") and len(text) > 3:
tail = text[3:].strip().lstrip("-_/ ")
if tail.isdigit():
return tail.lstrip("0") or "0"
return text.lstrip("0") or "0"
def normalize_atomic_po_number(value: Any) -> str:
"""标准化单一 PO;含多个 PO 或自由文本的值不能作为合并、建单身份。"""
normalized = normalize_po_number(value)
return normalized if _ATOMIC_PO_NUMBER_PATTERN.fullmatch(normalized) else ""
def find_po_number_in_document(text: str) -> str:
"""从发货通知全文中按正则模式提取 PO Number。"""
raw = str(text or "")
if not raw.strip():
return ""
for pattern in _PO_NUMBER_PATTERNS:
match = re.search(pattern, raw)
if match:
return normalize_po_number(match.group(1))
return ""
def enrich_notice_with_po_number(parsed: dict[str, Any], *, raw_text: str = "") -> dict[str, Any]:
"""将结构化/文档级 PO Number 回填到 parsed 结果(含 ZNB 前缀标准化)。"""
po_number = normalize_po_number(
parsed.get("po_number") or parsed.get("PO Number") or parsed.get("purchase_order_number")
)
if not po_number:
po_number = find_po_number_in_document(raw_text)
if po_number:
parsed["po_number"] = po_number
return parsed