""" services/shipping_notice/reservation_id.py 用途:提取、标准化并校验发货通知与库存中的 Reservation ID。 依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。 逻辑:由 notice_lines、onhand_snapshot、match、extract、EML 补充解析等多个模块复用; 归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。 另提供「裸数字兜底」:正文数据表无表头且常规证据缺失时,扫描「整格恰好为 5/10 位纯数字」的 HTML 表格单元格候选(供 order_supplement_merge 在合并 末段做唯一/多候选裁决;自由文本不扫描)。 """ from __future__ import annotations import re from typing import Any # Reservation ID 业务契约固定为 5 位或 10 位纯数字。 RESERVATION_ID_NUMERIC_RE = re.compile(r"^(?:\d{5}|\d{10})$") # 数据库主键、哈希或 UUID 不属于业务 Reservation ID。 INTERNAL_HEX_ID_RE = re.compile(r"^[0-9a-f]{32}$", re.IGNORECASE) INTERNAL_UUID_RE = re.compile( r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$", re.IGNORECASE, ) # Reservation 本体后可带一段半角或全角括号备注;普通尾随文本不属于合法值。 RESERVATION_VALUE_RE = re.compile(r"^(\d{10}|\d{5})(?!\d)\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$") # ``@`` 是预约号与前缀说明的显式分隔,后缀复用 Reservation 值的括号备注契约。 RESERVATION_AT_SUFFIX_RE = re.compile(r"@\s*(\d{10}|\d{5})(?!\d)(?=\s*(?:\([^()\r\n]*\)|([^()\r\n]*))?\s*$)") # QUANTA IR# 等:合法 5/10 位本体 + 一段短数字行序后缀(- / - / _);多段后缀拒绝。 RESERVATION_SHORT_NUMERIC_SUFFIX_RE = re.compile(r"^(\d{10}|\d{5})[--_](\d+)$") PR_NUMBER_LINE_RE = re.compile( r"PR\s*Number\s*[::]?\s*([^\n\r]+)", re.IGNORECASE, ) # [裸数字兜底] 紧跟业务标签的数字串(PO/订单/发票/数量)不是预约单号;捕获组为数字本体。 # 保留前导词边界防止命中复合词内部;尾部不加边界、由「必须跟数字」门控, # 使 PO12345 / PO# 12345 / Purchase Order: 12345 等写法都被覆盖,而 podium 等词不受影响。 # 仅用于邮件主题等上下文的标签排除;正文候选已收紧为「整格纯数字」,不再做自由文本扫描。 LABELED_NON_RESERVATION_RE = re.compile( r"(?i)(?:\bp\.?\s*o\.?|\bpurchase\s+orders?|\borders?|\binvoices?|\binv\.?|\bqty\.?|\bquantity)" r"(?:\s*(?:number|no\.?|#))?\s*[:#]?\s*(\d{3,})" ) # 候选数量上限:转发/引用链可能携带大量历史数字,防止 supplement 快照被刷爆。 MAX_HEURISTIC_RESERVATION_CANDIDATES = 20 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: """标准化 Reservation ID,并识别括号备注、``@`` 分隔与短数字行序后缀。 核心逻辑:先匹配纯 5/10 位(可带括号备注);再搜 ``@`` 后本体;最后剥离 一段 ``-``/``-``/``_`` + 数字后缀(如 ``35354-1`` → ``35354``)。多段后缀不采纳。 Args: value: Reservation ID 字段原始值。 Returns: str: 已确认的五位或十位纯数字 Reservation ID;无法安全抽取时返回空字符串。 """ text = str(value or "").strip() if not text: return "" # [STEP 1] 整体纯数字(可选括号备注) direct = normalize_reservation_id(text) direct_match = RESERVATION_VALUE_RE.fullmatch(direct) if direct_match: return direct_match.group(1) # [STEP 2] 显式 @ 分隔(可带括号备注) match = RESERVATION_AT_SUFFIX_RE.search(text) if match: return match.group(1) # [STEP 3] 短数字行序后缀(IR# 35354-1);仅一段后缀 suffix_match = RESERVATION_SHORT_NUMERIC_SUFFIX_RE.fullmatch(direct) if suffix_match: return suffix_match.group(1) return "" def find_reservation_id_in_document(text: str) -> str: """扫描全文 PR Number 行或 ``@`` 分隔、可带括号备注的 Reservation ID。 Args: text: 文档原始文本;仅接受 ``@`` 后可带括号备注的完整五位或十位纯数字。 Returns: str: 已验证的五位或十位纯数字 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: """判断标准化后的值是否符合 5 位或 10 位纯数字 Reservation ID 格式。""" text = normalize_reservation_id(value) return bool(text and RESERVATION_ID_NUMERIC_RE.fullmatch(text)) def is_valid_reservation_id(value: Any, *, numeric_only: bool = False) -> bool: """ 判断候选值是否可作为业务 Reservation ID。 核心逻辑:只接受 5 位或 10 位纯数字;字母型编号、其他长度数字、hex 和 UUID 均拒绝。 Args: value: 待校验的原始值。 numeric_only: 兼容既有调用签名;当前统一契约始终只接受 5 位或 10 位纯数字。 Returns: bool: 值是否满足当前 Reservation ID 契约。 """ text = extract_reservation_id(value) if not text or INTERNAL_HEX_ID_RE.fullmatch(text) or INTERNAL_UUID_RE.fullmatch(text): return False return bool(RESERVATION_ID_NUMERIC_RE.fullmatch(text)) def validated_reservation_id(value: Any, *, numeric_only: bool = False) -> str: """提取并返回合法 Reservation ID;候选不满足契约时返回空字符串。""" candidate = extract_reservation_id(value) return candidate if is_valid_reservation_id(candidate, numeric_only=numeric_only) else "" def reservation_ids_in_labeled_context(text: str) -> set[str]: """返回文本中紧跟业务标签(PO/订单/发票/数量)的数字串,供裸数字候选排除。 AI 触发时机:合并末段判断裸数字候选前,先排除邮件主题等上下文里 「PO xxx」「Invoice xxx」这类带标签的数字,即使它们未被提取为字段。 Args: text: 任意原文(邮件主题、正文段落等)。 Returns: set[str]: 标签后紧跟的数字串原文(未归一);无命中返回空集合。 """ return { match.group(1) for match in LABELED_NON_RESERVATION_RE.finditer(str(text or "")) } def _iter_heuristic_cell_texts(html_tables: list[str] | None, content_hash: str): """惰性产出 HTML 表格单元格文本及其证据定位;解析失败的表安全跳过。 逻辑:版面网格的 cell_id 是 DOM 级可追溯证据,优先于行号猜测; 惰性导入 html_table 避免给本工具模块增加常驻依赖。 """ if not html_tables: return from app.services.shipping_notice.document_layout.html_table import parse_html_grid for table_index, html in enumerate(html_tables): try: grid = parse_html_grid( str(html or ''), table_id=f'reservation-heuristic:{content_hash}:{table_index}', ) except Exception: continue for row_index, row in enumerate(grid.rows): for column, slot in enumerate(row): if slot is None or not str(slot.text or '').strip(): continue yield str(slot.text), { 'table_index': table_index, 'row_index': row_index, 'column_index': column, 'cell_id': slot.cell_id, } def _heuristic_cell_is_bare_number(cell_text: str) -> bool: """判断表格单元格是否「整格恰好为 5/10 位纯数字」(2026-10-15 收紧规则)。 前后带任何字符都不取:地址邮编(``Secaucus, NJ 07094``)、带字母前后的 编号(``T00410``)、带备注的值(``39739 (A)``)一律排除,只留独立数值格。 """ return bool(RESERVATION_ID_NUMERIC_RE.fullmatch(str(cell_text or '').strip())) def find_bare_numeric_reservation_candidates( *, html_tables: list[str] | None = None, content_hash: str = "", ) -> list[dict[str, Any]]: """扫描正文 HTML 表格中「整格恰好为 5/10 位纯数字」的预约单号候选。 AI 触发时机:EML 正文数据表没有表头、常规表头契约解析不出预约单号时, 在补充事实里预置候选列表;真正「是否采纳」由 order_supplement_merge 在 合并末段结合已提取字段值裁决,本函数绝不直接写入订单。 核心逻辑:只认表格(2026-10-15 收紧)——自由文本(签名、地址、引用链) 一律不扫描,杜绝邮编等噪声;单元格整格纯数字才算候选(PO 号同为 10 位 纯数字会入选,由合并端按已提取字段值/主题标签排除);同值只保留首个证据; 总数截断到 MAX_HEURISTIC_RESERVATION_CANDIDATES。 Args: html_tables: 正文顶层 HTML 表格片段列表;为空时返回空列表(无表格不兜底)。 content_hash: 正文 Document 内容哈希,用于稳定 cell_id。 Returns: list[dict]: ``[{value, evidence}]``;evidence 含 table_index/row_index/ column_index/cell_id/raw_value(DOM 级可追溯)。 """ candidates: list[dict[str, Any]] = [] seen: set[str] = set() for cell_text, base_evidence in _iter_heuristic_cell_texts(html_tables, content_hash): if not _heuristic_cell_is_bare_number(cell_text): continue value = str(cell_text).strip() if value in seen or len(candidates) >= MAX_HEURISTIC_RESERVATION_CANDIDATES: continue seen.add(value) candidates.append({'value': value, 'evidence': {**base_evidence, 'raw_value': value}}) return candidates def filter_reservation_heuristic_candidates( candidates: list[dict[str, Any]], *, excluded_values: set[str], ) -> tuple[list[dict[str, Any]], str]: """按「已识别字段值/跨单已占用」排除后裁决候选状态。 Args: candidates: ``find_bare_numeric_reservation_candidates`` 的产物。 excluded_values: 需排除的值集合(比较前统一 strip+大写)。 Returns: ``(surviving, status)``:status 为 ``unique``(恰好一个,可自动采纳)、 ``ambiguous``(多个,转人工裁决)或 ``none``(无候选)。 """ excluded = {str(value).strip().upper() for value in excluded_values if str(value).strip()} surviving = [ item for item in (candidates or []) if str(item.get('value') or '').strip().upper() not in excluded ] if not surviving: return [], 'none' if len(surviving) == 1: return surviving, 'unique' return surviving, 'ambiguous'