""" services/shipping_notice/reservation_id.py 用途:提取、标准化并识别发货通知与库存中的 Reservation ID。 依赖:正则表达式与标准 `typing` 工具。 逻辑:由 notice_lines、inventory_snapshot、match、extract 等多个解析/匹配模块复用本文件完成 Reservation ID 归一化。 """ from __future__ import annotations import re from typing import Any # 常见 Reservation ID:纯数字,如 1000140351(通常 8~12 位) RESERVATION_ID_NUMERIC_RE = re.compile(r"^\d{8,12}$") # Wistron 等 PO:PR Number = ADU_S-ENCWIW260528126265@1000140351 RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{8,12})\b") PR_NUMBER_LINE_RE = re.compile( r"PR\s*Number\s*[::]?\s*([^\n\r]+)", re.IGNORECASE, ) def normalize_reservation_id(value: Any) -> str: """标准化 Reservation ID;处理 Excel 浮点、千分位与 x.0 尾缀。""" if value is None: return "" if isinstance(value, bool): return "" if isinstance(value, float): if value != value: # NaN return "" if value.is_integer(): return str(int(value)) text = str(value).strip() elif isinstance(value, int): text = str(value) else: text = str(value).strip() if not text: return "" text = text.replace(",", "").replace(",", "").strip() if re.fullmatch(r"\d+\.0+", text): text = text.split(".", 1)[0] return text def extract_reservation_id(value: Any) -> str: """从纯数字、Excel 浮点或 PR Number(xxx@1000140351)中提取 Reservation ID。""" text = str(value or "").strip() if not text: return "" direct = normalize_reservation_id(text) if looks_like_reservation_id(direct): return direct match = RESERVATION_AT_SUFFIX_RE.search(text) if match: return match.group(1) if "@" in text: tail = normalize_reservation_id(text.rsplit("@", 1)[-1]) if looks_like_reservation_id(tail): return tail return direct def find_reservation_id_in_document(text: str) -> str: """扫描全文 PR Number 行或 @1000140351 后缀,提取文档级 Reservation ID。""" body = str(text or "") if not body.strip(): return "" pr_match = PR_NUMBER_LINE_RE.search(body) if pr_match: extracted = extract_reservation_id(pr_match.group(1)) if extracted and looks_like_reservation_id(extracted): return extracted for match in RESERVATION_AT_SUFFIX_RE.finditer(body): candidate = match.group(1) if looks_like_reservation_id(candidate): return candidate return "" def looks_like_reservation_id(value: Any) -> bool: """判断标准化后的值是否符合 8~12 位纯数字 Reservation ID 格式。""" text = normalize_reservation_id(value) return bool(text and RESERVATION_ID_NUMERIC_RE.fullmatch(text))