From 6502f73cb5cf95e1487a964bf42eee05bdcd94e3 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 15 Oct 2026 01:22:14 +0800 Subject: [PATCH] =?UTF-8?q?fix(shipping-notice):=20=E9=87=8D=E8=AF=86?= =?UTF-8?q?=E5=88=AB=20Run=20=E7=BB=88=E6=80=81=E6=BF=80=E6=B4=BB=20Case?= =?UTF-8?q?=20=E5=B9=B6=E6=94=B6=E7=B4=A7=E8=A3=B8=E6=95=B0=E5=AD=97?= =?UTF-8?q?=E5=85=9C=E5=BA=95=E5=8F=A3=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 修复重解析延迟激活钩子未接线:Run 终态原子激活可复核 Case 为文件 Stream 当前版本,工作台队列不再空白 - 新增 run_is_reparse_successor_of_case 判定 Case 与重解析 Run 的后继关系 - 裸数字兜底口径收紧:仅扫「整格恰好 5/10 位纯数字」的正文 HTML 表格单元格,自由文本与带前后字符的值一律不取,防误绑签名与邮编 - 新增客户 PO 匹配变体集合(原值/归一/去前导零)纳入排除集,补充合并末段裁决更准 - 同步预约号启发式测试,business/technical 文档记录收紧决策 --- .../document_candidate_persist.py | 3 +- .../shipping_notice/order_extraction.py | 47 +++++++++ .../order_extraction_run_service.py | 3 +- .../shipping_notice/order_supplement_merge.py | 44 +++++++++ .../shipping_notice/reservation_id.py | 68 ++++++------- .../shipping_notice/review_stream_service.py | 38 +++++++ .../test_shipping_reservation_heuristic.py | 98 +++++++++---------- docs/features/shipping-notice/business.md | 1 + docs/features/shipping-notice/technical.md | 4 +- 9 files changed, 208 insertions(+), 98 deletions(-) diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index 8a1141be..2fb923ec 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -666,10 +666,9 @@ def persist_documents_and_candidates( schema_definition=definition, ) supplement['document_id'] = int(body_doc.id) - # [裸数字兜底] 无表头数据行解析不出补充行时,预置正文裸 5/10 位数字候选; + # [裸数字兜底] 无表头数据表解析不出补充行时,预置「整格纯数字」表格候选; # 是否采纳由 merge_email_supplements 在合并末段结合已提取字段值裁决。 supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates( - body_text=body_text, html_tables=canonical_html_tables, content_hash=str(body_doc.content_hash or ''), ) diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 50f56a64..43857a44 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -865,6 +865,53 @@ def persist_order_extraction_result( 'non_shipping_order_indexes': document_non_shipping_indexes[int(document.id)], } + # [STEP 2.5] 重识别 Run 终态收口:本 Run 已落库的可复核 Case 必须在此原子激活为 + # 文件 Stream 当前版本——Case 创建时按 reparse 延迟激活、约定等 Run 终态切换,但 + # 该钩子此前从未接线,导致工作台队列(按 Stream.current_case_id 平铺)看不到任何 + # Case,单据永远不可见(回归 SNER-20261014-35E35017 → BB05A18B:9 Case 全部 + # stream_id=NULL,工作台空白且停接收解析)。 + if run.reparse_of_run_id is not None: + from app.models import ShippingOrderReviewCase + from app.services.shipping_notice.candidate_service import ( + is_current_reviewable_candidate, + ) + from app.services.shipping_notice.review_stream_service import ( + activate_review_case, + ensure_review_stream_for_case, + run_is_reparse_successor_of_case, + ) + + reparse_cases = ShippingOrderReviewCase.query.filter( + ShippingOrderReviewCase.run_id == int(run.id), + ShippingOrderReviewCase.status != 'superseded', + ShippingOrderReviewCase.candidate_id.isnot(None), + ).all() + for review_case in reparse_cases: + try: + candidate = db.session.get( + ShippingOrderCandidate, int(review_case.candidate_id), + ) + if not is_current_reviewable_candidate(candidate): + continue + stream = ensure_review_stream_for_case(case=review_case) + declared_source = None + if stream.current_case_id is not None: + current_case = db.session.get( + ShippingOrderReviewCase, int(stream.current_case_id), + ) + if ( + current_case is not None + and run_is_reparse_successor_of_case(run=run, current_case=current_case) + ): + declared_source = int(current_case.id) + activate_review_case( + case=review_case, trigger='batch_reparse_succeeded', + declared_source_case_id=declared_source, + ) + except ConflictError: + # 已确认/履约中的当前版本不得被草稿覆盖:保留现状态供人工处理。 + continue + # [STEP 3] 只对本次 documents 作用域内消失的 Candidate 做版本失效。 # Unit 增量提交仅带当前 PDF,禁止把同 Intake/Run 的兄弟 PDF Candidate # 误判为 stale;历史 Candidate 可能已被 Case/OT 引用,不得物理删除。 diff --git a/backend/app/services/shipping_notice/order_extraction_run_service.py b/backend/app/services/shipping_notice/order_extraction_run_service.py index 767ffc4d..5fc38c51 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -933,10 +933,9 @@ def _build_snapshot( ) if isinstance(email_supplement, dict): email_supplement['document_id'] = int(document.id) - # [裸数字兜底] 快照冻结前按当前正文重扫裸 5/10 位数字候选; + # [裸数字兜底] 快照冻结前按当前正文重扫「整格纯数字」表格候选; # 合并末段结合订单已提取字段值裁决,快照重建保证与 Schema 同源。 email_supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates( - body_text=str(document.extracted_text or ''), html_tables=html_tables, content_hash=str(document.content_hash or ''), ) diff --git a/backend/app/services/shipping_notice/order_supplement_merge.py b/backend/app/services/shipping_notice/order_supplement_merge.py index 54fff4d1..744d48f3 100644 --- a/backend/app/services/shipping_notice/order_supplement_merge.py +++ b/backend/app/services/shipping_notice/order_supplement_merge.py @@ -377,6 +377,26 @@ def _order_has_reservation_value(order: dict[str, Any], ids: dict[str, str]) -> return False +def _order_po_variants(order: dict[str, Any], ids: dict[str, str]) -> set[str]: + """本单已提取客户 PO 号的匹配变体集合(原值/归一/去前导零)。""" + reverse_ids = {v: k for k, v in ids.items()} + values = list(_values(order.get('header_fields'), 'customer_po_number', reverse_ids)) + for line in order.get('lines') or []: + if isinstance(line, dict): + values.extend(_values(line.get('fields'), 'customer_po_number', reverse_ids)) + variants: set[str] = set() + for value in values: + text = str(value).strip() + if not text: + continue + variants.add(text) + po = normalize_atomic_po_number(text) + if po: + variants.update({po, po.lstrip('0')}) + variants.add(text.lstrip('0')) + return {variant for variant in variants if variant} + + def _apply_reservation_heuristic( order: dict[str, Any], supplement: dict[str, Any], @@ -407,6 +427,30 @@ def _apply_reservation_heuristic( surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=excluded) if status == 'none': return + # [PO 行定位收敛] 分配邮件整批表格一行一个 PO+预约号:本单 PO 所在行的预约号 + # 即本单预约号。裸数字候选携带原始表坐标(table_index/row_index),与补充解析行 + # 同源对齐——对齐行内含本单 PO 即认定该候选为本单预约号。命中唯一 → 按唯一路径 + # 写入;命中多个或未命中时维持既有冲突裁决(绝不自动猜值)。 + order_po_values = _order_po_variants(order, ids) + supplement_rows = supplement.get('rows') if isinstance(supplement.get('rows'), list) else [] + parsed_rows_by_pos = { + (str(row.get('table_index') or 0), str(row.get('row_index') or 0)): row + for row in supplement_rows if isinstance(row, dict) + } + scoped: list[dict[str, Any]] = [] + if order_po_values and parsed_rows_by_pos: + for item in surviving: + evidence = item.get('evidence') if isinstance(item.get('evidence'), dict) else {} + pos = (str(evidence.get('table_index') or 0), str(evidence.get('row_index') or 0)) + row = parsed_rows_by_pos.get(pos) + if row is None: + continue + row_values = {str(value).strip() for value in row.values() if str(value or '').strip()} + if order_po_values & row_values: + scoped.append(item) + if scoped: + surviving = scoped + status = 'unique' if len(surviving) == 1 else 'multiple' document_id = int(supplement.get('document_id') or 0) values = [str(item.get('value') or '') for item in surviving] marker = {'status': status, 'values': values, 'document_id': document_id or None} diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py index 8fdc7d3b..00aa364a 100644 --- a/backend/app/services/shipping_notice/reservation_id.py +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -5,8 +5,9 @@ services/shipping_notice/reservation_id.py 依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。 逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用; 归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。 - 另提供「裸数字兜底」:正文无表头且常规证据缺失时,扫描排除后的 5/10 位 - 纯数字候选(供 order_supplement_merge 在合并末段做唯一/多候选裁决)。 + 另提供「裸数字兜底」:正文数据表无表头且常规证据缺失时,扫描「整格恰好为 + 5/10 位纯数字」的 HTML 表格单元格候选(供 order_supplement_merge 在合并 + 末段做唯一/多候选裁决;自由文本不扫描)。 """ from __future__ import annotations @@ -32,11 +33,10 @@ PR_NUMBER_LINE_RE = re.compile( r"PR\s*Number\s*[::]?\s*([^\n\r]+)", re.IGNORECASE, ) -# [裸数字兜底] 独立的 5/10 位纯数字 token;前后不能紧贴数字,防止从更长数字串截取。 -BARE_NUMERIC_RESERVATION_RE = re.compile(r"(? set[str]: } -def _heuristic_context_snippet(text: str, match: re.Match[str]) -> str: - """截取 token 所在行命中国的前后片段,供复核面板展示证据上下文。""" - start = max(match.start() - 40, 0) - end = min(match.end() + 40, len(text)) - return text[start:end].strip() - - def _iter_heuristic_cell_texts(html_tables: list[str] | None, content_hash: str): """惰性产出 HTML 表格单元格文本及其证据定位;解析失败的表安全跳过。 @@ -220,54 +213,49 @@ def _iter_heuristic_cell_texts(html_tables: list[str] | None, content_hash: str) } +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( *, - body_text: str = "", html_tables: list[str] | None = None, content_hash: str = "", ) -> list[dict[str, Any]]: - """扫描正文中的裸 5/10 位纯数字预约单号候选(排除带业务标签的数字)。 + """扫描正文 HTML 表格中「整格恰好为 5/10 位纯数字」的预约单号候选。 - AI 触发时机:EML 正文数据行没有表头、常规表头契约解析不出预约单号时, + AI 触发时机:EML 正文数据表没有表头、常规表头契约解析不出预约单号时, 在补充事实里预置候选列表;真正「是否采纳」由 order_supplement_merge 在 合并末段结合已提取字段值裁决,本函数绝不直接写入订单。 - 核心逻辑:先扫 HTML 表格单元格(保留 DOM cell_id 证据),再扫纯文本行 - (保留行号与上下文片段);紧跟 PO/订单/发票/数量标签的数字串不作为候选; - 同值只保留首个证据;总数截断到 MAX_HEURISTIC_RESERVATION_CANDIDATES。 + 核心逻辑:只认表格(2026-10-15 收紧)——自由文本(签名、地址、引用链) + 一律不扫描,杜绝邮编等噪声;单元格整格纯数字才算候选(PO 号同为 10 位 + 纯数字会入选,由合并端按已提取字段值/主题标签排除);同值只保留首个证据; + 总数截断到 MAX_HEURISTIC_RESERVATION_CANDIDATES。 Args: - body_text: EML 正文纯文本(含展平的数据行)。 - html_tables: 正文顶层 HTML 表格片段列表;可为空。 + html_tables: 正文顶层 HTML 表格片段列表;为空时返回空列表(无表格不兜底)。 content_hash: 正文 Document 内容哈希,用于稳定 cell_id。 Returns: list[dict]: ``[{value, evidence}]``;evidence 含 table_index/row_index/ - column_index/cell_id/raw_value,纯文本候选另含 context。扫描不到返回空列表。 + column_index/cell_id/raw_value(DOM 级可追溯)。 """ candidates: list[dict[str, Any]] = [] seen: set[str] = set() - - def _collect(text: str, base_evidence: dict[str, Any]) -> None: - excluded_spans = [item.span() for item in LABELED_NON_RESERVATION_RE.finditer(text)] - for match in BARE_NUMERIC_RESERVATION_RE.finditer(text): - if any(start <= match.start() and match.end() <= end for start, end in excluded_spans): - continue - value = match.group() - if value in seen or len(candidates) >= MAX_HEURISTIC_RESERVATION_CANDIDATES: - continue - seen.add(value) - evidence = {**base_evidence, 'raw_value': value} - if 'cell_id' not in evidence: - evidence['cell_id'] = f"reservation-heuristic:{content_hash}:line{evidence.get('row_index')}" - evidence['context'] = _heuristic_context_snippet(text, match) - candidates.append({'value': value, 'evidence': evidence}) - for cell_text, base_evidence in _iter_heuristic_cell_texts(html_tables, content_hash): - _collect(cell_text, dict(base_evidence)) - for line_index, line in enumerate(str(body_text or '').splitlines()): - if line.strip(): - _collect(line, {'table_index': None, 'row_index': line_index + 1, 'column_index': None}) + 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 diff --git a/backend/app/services/shipping_notice/review_stream_service.py b/backend/app/services/shipping_notice/review_stream_service.py index 6e0f606a..4f3897dc 100644 --- a/backend/app/services/shipping_notice/review_stream_service.py +++ b/backend/app/services/shipping_notice/review_stream_service.py @@ -17,6 +17,7 @@ from app import db from app.core.errors import ConflictError from app.models import ( ShippingOrderDocument, + ShippingOrderProcessingRun, ShippingOrderReviewCase, ShippingOrderReviewCaseEvent, ShippingOrderReviewStream, @@ -30,6 +31,33 @@ ReviewStreamTrigger = Literal[ ] +def run_is_reparse_successor_of_case( + *, + run: ShippingOrderProcessingRun, + current_case: ShippingOrderReviewCase, + max_hops: int = 10, +) -> bool: + """ + 判定 Run 是否为某文件当前 Case 所属 Run 的重解析后继(沿 reparse_of_run_id 有界上溯)。 + + 核心逻辑:批次重解析(reparse_order_extraction_run)不写 review_reparse 快照 + marker,activate_review_case 的替代来源证明需要调用方提供;本函数即该证明—— + 上溯有界跳数内命中 current_case.run_id 即认定同文件版本替代关系成立。 + """ + current_run_id = int(current_case.run_id) + cursor = run + for _ in range(max(1, int(max_hops))): + ancestor_id = getattr(cursor, 'reparse_of_run_id', None) + if ancestor_id is None: + return False + if int(ancestor_id) == current_run_id: + return True + cursor = db.session.get(ShippingOrderProcessingRun, int(ancestor_id)) + if cursor is None: + return False + return False + + def _document_content_identity(document_id: int) -> str: """计算 Stream 的稳定文件身份;当前业务按 Document 严格隔离,哈希仅供审计说明。""" document = db.session.get(ShippingOrderDocument, int(document_id)) @@ -91,12 +119,19 @@ def activate_review_case( *, case: ShippingOrderReviewCase, trigger: ReviewStreamTrigger, + declared_source_case_id: int | None = None, ) -> ShippingOrderReviewStream: """ 将一个成功可复核的 Case 原子切换为其文件 Stream 的当前版本。 AI 触发时机:初次 PDF 完成时或重解析成功且新 Case 已完整落库时调用;失败、等待布局和 仅创建后继 Run 时禁止调用。确认/履约中的当前版本不可被草稿覆盖,冲突必须显式暴露。 + + Args: + declared_source_case_id: 调用方已证明的版本替代来源 Case id(如按 Run 谱系 + 验证过的前代 Case)。快照 marker 缺失时(批次重解析不写 + review_reparse.source_case_no)以它补全替代关系证明;快照 marker + 优先,两者皆缺时维持保守冲突语义。 """ stream = ensure_review_stream_for_case(case=case) stream = ShippingOrderReviewStream.query.filter_by(id=int(stream.id)).with_for_update().one() @@ -111,6 +146,9 @@ def activate_review_case( return stream if trigger != 'initial_extraction' and current is not None: declared_source_id = _declared_reparse_source_case_id(incoming) + if declared_source_id is None and declared_source_case_id is not None: + # 调用方已按 Run 谱系证明替代来源(批次重解析不写快照 marker 的口径)。 + declared_source_id = int(declared_source_case_id) if declared_source_id is None or declared_source_id != int(current.id): # [CONCURRENCY] 晚到分支只能进入冲突,绝不能覆盖已切换的另一文件版本。 stream.state = 'conflict' diff --git a/backend/tests/test_shipping_reservation_heuristic.py b/backend/tests/test_shipping_reservation_heuristic.py index 277de2dc..dcfe4ecb 100644 --- a/backend/tests/test_shipping_reservation_heuristic.py +++ b/backend/tests/test_shipping_reservation_heuristic.py @@ -77,68 +77,60 @@ def _reservation_observation(order: dict): # ---------------------------------------------------------------- 候选扫描 -def test_scan_finds_bare_reservation_in_headerless_row(): - """截图 1:无表头数据行只识别 4000122230;仓库/料号/日期/供应商号不误报。""" - row = 'DBS SLC 4000122230 6233 504-006075-001 D4-AR1200163A1 Welltrust 10/13/2026' - candidates = find_bare_numeric_reservation_candidates(body_text=row, content_hash='h') - # 断言:仅 10 位纯数字 4000122230 入选;4 位站点号、带连字符料号、日期均被长度/边界挡住。 - assert [item['value'] for item in candidates] == ['4000122230'] - assert candidates[0]['evidence']['row_index'] == 1 - assert candidates[0]['evidence']['cell_id'].startswith('reservation-heuristic:h:line') +def test_scan_finds_bare_reservation_in_headerless_table_row(): + """截图场景:无表头数据表只识别整格纯数字的 39739;PO 整格入选由合并端排除。""" + html = ( + '' + '' + '
DBS PHX01397396233504-006055-001D4-A08AR12000002WEL10/12/20261201000053286
' + ) + candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h') + # 断言:仅两个整格纯数字入选——预约号 39739 与 PO 1000053286(10 位同样合规, + # 由合并端用已提取 PO 字段值/主题标签排除);仓库/料号/日期/数量格一概不取。 + assert [item['value'] for item in candidates] == ['39739', '1000053286'] + evidence = candidates[0]['evidence'] + # 断言:DOM 级证据齐全,可回溯到具体表格/行/列。 + assert evidence['table_index'] == 0 + assert evidence['row_index'] == 0 and evidence['column_index'] == 1 + assert evidence['cell_id'].startswith('reservation-heuristic:h:0') -def test_scan_finds_five_digit_reservation(): - """截图 3:5 位候选 39739 同样可识别。""" - row = 'DBS PHX01 39739 6233 504-006055-001 D4-A08AR12000002 WEL 10/12/2026' - candidates = find_bare_numeric_reservation_candidates(body_text=row, content_hash='h') +def test_scan_ignores_cells_with_any_surrounding_content(): + """收紧规则:邮编地址、带字母/备注前后的值一律不取(07094/00410 误报修复)。""" + html = ( + '' + '' + '' + '' + '' + '' + '' + '
Secaucus, NJ 07094T0041000410-CN39739 (A) 39739 35354-1
' + ) + candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h') + # 断言:只有去除首尾空白后恰好为纯数字的整格幸存(39739); + # 07094 藏在地址文本里、00410 带字母前后、39739 带备注、35354-1 带后缀,全部排除。 assert [item['value'] for item in candidates] == ['39739'] -def test_scan_rejects_labeled_context_and_wrong_lengths(): - """标签上下文(PO/Invoice/Qty/紧凑 PO12345)排除;4/6/11/13 位数字不入选。""" - text = ( - 'PO# 1000053337\n' - 'Purchase Order : 1000053286\n' - 'Invoice 1234567890\n' - 'Qty 10000\n' - 'PO39739\n' - 'ref 1234 123456 12345678901 1234567890123\n' - 'valid 4000122230' - ) - candidates = find_bare_numeric_reservation_candidates(body_text=text, content_hash='h') - # 断言:只有裸露的 10 位 4000122230 幸存;带标签数字与错误长度全部排除。 - assert [item['value'] for item in candidates] == ['4000122230'] - - -def test_scan_accepts_short_numeric_suffix_form(): - """35354-1 短行序后缀形态:本体 35354 作为候选(归一由合并端处理)。""" - candidates = find_bare_numeric_reservation_candidates(body_text='IR# 35354-1', content_hash='h') - # 断言:35354 后跟 "-"(非数字)满足边界;IR# 标签不在排除标签清单内。 - assert [item['value'] for item in candidates] == ['35354'] +def test_scan_returns_nothing_without_html_tables(): + """收紧规则:正文无 HTML 表格时不做兜底,纯文本中的数字不再是候选来源。""" + assert find_bare_numeric_reservation_candidates(html_tables=[], content_hash='h') == [] + assert find_bare_numeric_reservation_candidates(html_tables=None, content_hash='h') == [] def test_scan_dedupes_and_caps_candidates(): - """同值只留首个证据;候选总数截断到上限,防止引用链刷爆快照。""" - text = '\n'.join(['4000122230'] + [f'{30000 + index}' for index in range(30)]) - candidates = find_bare_numeric_reservation_candidates(body_text=text, content_hash='h') - values = [item['value'] for item in candidates] - # 断言:30 个不同 5 位数字 + 1 个 10 位数字共 31 个 token,但只保留前 20 个。 - assert len(values) == 20 - assert values.count('4000122230') == 1 - - -def test_scan_uses_dom_cell_evidence_for_html_tables(): - """HTML 表格单元格候选携带 DOM 级 cell_id,供复核证据回溯。""" - html = '
10000533374000122230
' - candidates = find_bare_numeric_reservation_candidates( - body_text='', html_tables=[html], content_hash='dom123', + """同值只留首个证据;候选总数截断到上限,防止大表刷爆快照。""" + cells = '40001222304000122230' + ''.join( + f'{30000 + index}' for index in range(25) ) - assert [item['value'] for item in candidates] == ['1000053337', '4000122230'] - # 断言:表格路径证据含 table_index/column_index/cell_id(DOM 定位),无 context 片段。 - evidence = candidates[1]['evidence'] - assert evidence['table_index'] == 0 - assert evidence['column_index'] == 1 - assert evidence['cell_id'].startswith('reservation-heuristic:dom123:0') + html = f'{cells}
' + candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h') + values = [item['value'] for item in candidates] + # 断言:重复格只保留首个证据;总数截断到 20(1 个 10 位 + 前 19 个 5 位)。 + assert len(values) == 20 + assert values[0] == '4000122230' + assert values.count('4000122230') == 1 def test_labeled_context_helper_extracts_subject_po(): diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index 5325475c..05dd7fae 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -466,6 +466,7 @@ WYC26071501 - 必须为 **5 位或 10 位纯数字**,例如 `12345` 或 `1000140351`。 - Excel 中的数字型编号可能被存成浮点格式,系统会自动规范为同一字符串再比对,避免「1000140351」与「1000140351.0」对不上。 - 32 位十六进制内部主键和 UUID 会被拒绝,不参与订单关联、指纹或库存匹配。 +- **邮件正文表格裸数字兜底(2026-10-14,2026-10-15 收紧)**:邮件正文的数据表没有表头、无法按列名识别预约单号时,系统只扫描**正文表格**中「整格恰好为 5 位或 10 位纯数字」的单元格:若排除其他字段内容(客户 PO 号、数量、日期、供应商编号等)后恰好剩一个候选,作为预约单号的低置信度默认值并在工作台提示「待人工确认」;存在多个候选则不自动填入,转人工在字段冲突面板选择。自由文本(签名、地址邮编如 `Secaucus, NJ 07094`)与前后带任何字符的值(如 `T00410`)一律不取;客户 PO 号本身常为 10 位纯数字,无论它在表格还是主题(如「PO 1000053337」),都会被优先排除。 **不参与匹配的字段:** diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index f0ef8f83..9151a045 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -454,6 +454,8 @@ L1 字段级:目标单元格 + 表头 + 相邻单元格 **邮件补充重建规则(2026-07-31)**:邮件表头只能按当前 Run 冻结 Schema 的显式别名映射;行级 `reservation_id` 包含真实业务表头 `External reservation ID`。只要 Intake 保留原始 `body_html_tables`,Run 冻结时必须按自己的 Schema 重新解析完整补充表,不能复用上传阶段缺字段但已有部分行的旧结果;没有 HTML 时才复用已有完整结果或安全回退纵向纯文本解析。**关联收紧(2026-09-15)**:`mpn_fallback` 仅适用于补充行 PO 缺失且料号唯一命中;有 PO 且与 PDF 不一致不得补充。预约号允许短数字行序后缀归一(如 `35354-1` → `35354`)。**无 PO 表头(2026-09-16)**:分配表缺 PO 列但已映射料号或预约号时仍解析补充行(`po_header_missing` 仅作可观测标记);无身份列时仍整表跳过。 +**预约单号裸数字兜底(2026-10-14,2026-10-15 收紧)**:EML 正文数据行无表头(如 `DBS SLC 4000122230 6233 504-006075-001 …`)时,表头契约解析不出补充行,`reservation_id` 缺失会阻断库存匹配/Excel/货代上传。补充合并末段(`merge_email_supplements`)因此增加有条件兜底:仅当订单头与全部行均无预约单号取值时触发(已有值含非法格式原值、人工填写一律不覆盖)。候选扫描(`reservation_id.find_bare_numeric_reservation_candidates`,摄取落库与 Run 冻结重建两处执行)**只扫正文 HTML 表格**,且单元格整格去除首尾空白后必须恰好为 5/10 位纯数字(与 Reservation ID 值契约同源)——**2026-10-15 收紧**:不再扫描自由文本(签名、地址邮编 `Secaucus, NJ 07094`、引用链均排除),带任何前后字符的值(如 `T00410`、`39739 (A)`、`35354-1`)一律不取;无 HTML 表格的正文不做兜底。候选数上限 20,DOM cell_id 证据可回溯。排除集 = 订单已提取字段值(全部 Observation 及 PO/预约号归一变体)∪ 邮件补充行值 ∪ 主题「PO/Invoice/Qty」等标签后数字 ∪ 同趟跨单已占用值(PO 号同为 10 位整格纯数字会入选候选,靠本排除集剔除)。排除后**唯一候选** → 以 confidence 0.5、`email_supplement_evidence.basis='bare_numeric_heuristic'` 低置信度写入(Schema 声明 header 作用域写订单头默认值,否则写缺失行),relation 标记 `reservation_heuristic`(前端四语言展示「待人工确认」)并发审计事件 `reservation_heuristic_applied`;**多候选** → 复用 `supplement_field_conflict` 冲突结构转现有字段冲突裁决面板,绝不自动挑值,发审计事件 `reservation_heuristic_ambiguous`;**零候选** → 维持现状(缺失阻断提示不变)。本兜底是「不扫描任意单元格猜 Reservation ID」红线唯一放开的例外,仅限 EML 正文表格;PDF/附件文档仍严格走模板/Schema 契约。一期全局启用、不做按客户配置,误判率经上述审计事件观察后再收敛。 + **`llm_extraction` 回退语义(2026-08-01)**:订单字段标记为 `llm_extraction` 表示“确定性解析无法取值时允许 LLM 补充”,不表示必须使用 LLM。通用解析门禁应依据字段是否已有完整、无冲突的确定性证据裁决;已取得必填 Header/Line 值时可直通,缺失时由 `required_field_missing` 转入 LLM/人工复核。 验收标准:四语言文案完整;前端 `npm run build` 通过;业务按钮只消费后端允许动作;对象版本冲突可见;普通用户无法进入模板治理或全局审计;页面不展示虚假百分比或内部 Workflow/Job/Provider 细节。 @@ -768,7 +770,7 @@ export / exportable_snapshot_line_ids)无论库存状态一律剔除结案行 > **历史归档说明(2026-07-28,2026-07-31 纠偏)**:下列阶段 1–5 及 L5-L7 的 Manifest/`orders` 描述记录了 2026-07-21 的旧订单抽取 Workflow 设计,已经失效。订单抽取 Run 不调用该 Workflow;当前 Dify 只在同一 `shipping_notice` Chatflow 的人工字段复核分支接收 `order-review-llm.v1` 最小证据请求。历史段落仅用于审计设计演进,禁止作为画布配置依据。 -**阶段 1 历史结论(2026-07-21)**:Run 锁定版本的完整 `definition_json` 已成为确定性订单表格解析的唯一业务配置来源。解析器只使用已启用字段的 `field_code + display_name + aliases` 编译冻结表头契约,不再维护业务别名常量,不读取当前 published 版本,也不在缺少契约时猜测表头。保存草稿和发布版本都会拒绝标准化后跨字段别名碰撞,并拒绝把 Allocation ID、Parent Allocation ID、Commodity Group ID、Supplier Code、UUID、Internal ID 配置为 Reservation ID 表头。同一字段命中多列时不静默选首列,而是记录 `deterministic_table_issues` 并进入复核。后端不再扫描任意单元格猜 Reservation ID,不把文档级 Reservation 广播到所有明细行,也不会为 Schema 未启用的 UOM、币种、金额等字段注入默认值或派生值。冻结的 retired 版本继续按自身别名解析,上传预处理若在任务边界选择当前 published Schema,也只生成提示,不替代正式 Run 的冻结真值。 +**阶段 1 历史结论(2026-07-21)**:Run 锁定版本的完整 `definition_json` 已成为确定性订单表格解析的唯一业务配置来源。解析器只使用已启用字段的 `field_code + display_name + aliases` 编译冻结表头契约,不再维护业务别名常量,不读取当前 published 版本,也不在缺少契约时猜测表头。保存草稿和发布版本都会拒绝标准化后跨字段别名碰撞,并拒绝把 Allocation ID、Parent Allocation ID、Commodity Group ID、Supplier Code、UUID、Internal ID 配置为 Reservation ID 表头。同一字段命中多列时不静默选首列,而是记录 `deterministic_table_issues` 并进入复核。后端不再扫描任意单元格猜 Reservation ID(**2026-10-14 修订**:唯一放开的例外是 EML 正文无表头时的「预约单号裸数字兜底」,见下方专段;模板专区之外的 PDF/附件单元格仍禁止猜测),不把文档级 Reservation 广播到所有明细行,也不会为 Schema 未启用的 UOM、币种、金额等字段注入默认值或派生值。冻结的 retired 版本继续按自身别名解析,上传预处理若在任务边界选择当前 published Schema,也只生成提示,不替代正式 Run 的冻结真值。 **Reservation ID 专用证据区域(2026-08-25)**:管理员在同一模板画布圈选唯一的 `reservation_id_region`(区域坐标与页码),不配置 JSON、来源映射、拆分规则或 Header/Line 归属。后端只从该区域内带 `Reservation` 语义的 5/10 位数字提取候选:无行号的值写入 `header.reservation_id`,并由既有有效值规则作为所有未覆盖明细的默认 Reservation;`Line N` / `for line N` / `L#N` 的值按 Customer PO 行号(`customer_po_line_no`,LN 列)定位对应逻辑明细并覆盖默认值(**2026-09-16 修订**:此前按"第 N 个逻辑明细"位置写入,LN 非连续——如部分行已拆到其他 PO——时会错配行归属并把存在的行号误报越界;解析行缺少 LN 取值时才回退位置序以兼容无 LN 字段的旧 Schema)。多个不同整单值、同一行不同值、被引用行号不存在或 Schema 未启用行字段时转 Review;普通数量、客户号等无 Reservation 标签数字一律忽略。区域页可不同于明细页,正式解析、画布预览和盲测共用同一解析/归属契约;XFA 拆分规则仍仅负责 datasets 结构取值,不能代替本能力。**带复核原因的确定性订单必须保留(2026-09-16)**:Reservation 专区/行校验触发 `needs_review` 时以 `deterministic` 携带原因码交 STP 裁决,已解析订单继续落 provisional Candidate 供复核台编辑;不得以 `review_required` 丢弃取值导致复核草稿空白。