From 3b53a2219c99b51686af74b4c70fcb4ffaad83c5 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 14 Oct 2026 19:31:39 +0800 Subject: [PATCH 01/10] =?UTF-8?q?feat(shipping-notice):=20=E6=97=A0?= =?UTF-8?q?=E8=A1=A8=E5=A4=B4=E6=96=87=E6=A1=A3=E6=8A=BD=E5=8F=96=E5=A2=9E?= =?UTF-8?q?=E5=BC=BA=E4=B8=8E=E5=A4=8D=E6=A0=B8=E6=B7=B1=E9=93=BE=E8=BA=AB?= =?UTF-8?q?=E4=BB=BD=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增表头 OCR 救援:模板匹配落 layout_drift/no_match 时按表头带证据补洞重评候选身份,主抽取流程接入并落 identity_rescue 事实字段 - 预约号裸数字兜底:正文无表头且常规证据缺失时扫描 5/10 位纯数字候选,持久化预置、合并末段唯一/多候选裁决 - 修复复核深链仅带 run_no 时队列项显示未命名:Case 身份优先按当前工作面 displayCase 匹配队列项 - 同步抽取 Job/运行服务/候选持久化配套与 OCR 救援、预约号启发式、表头身份测试 --- .../handlers/shipping_order_extraction.py | 53 +++ .../document_candidate_persist.py | 10 + .../document_layout/order_profile_matcher.py | 42 +- .../order_profile_ocr_rescue.py | 395 ++++++++++++++++++ .../order_extraction_run_service.py | 9 + .../order_extraction_workflow.py | 13 + .../shipping_notice/order_supplement_merge.py | 200 ++++++++- .../shipping_notice/reservation_id.py | 147 ++++++- .../test_order_profile_header_identity.py | 58 ++- .../tests/test_order_profile_ocr_rescue.py | 333 +++++++++++++++ .../test_shipping_reservation_heuristic.py | 330 +++++++++++++++ .../useShippingOrderReview.spec.ts | 50 +++ .../shipping-review/useShippingOrderReview.ts | 4 + .../views/ShippingOrderReviewView.spec.ts | 17 + .../chat/views/ShippingOrderReviewView.vue | 5 +- 15 files changed, 1660 insertions(+), 6 deletions(-) create mode 100644 backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py create mode 100644 backend/tests/test_order_profile_ocr_rescue.py create mode 100644 backend/tests/test_shipping_reservation_heuristic.py diff --git a/backend/app/jobs/handlers/shipping_order_extraction.py b/backend/app/jobs/handlers/shipping_order_extraction.py index 91d0612f..8e837a71 100644 --- a/backend/app/jobs/handlers/shipping_order_extraction.py +++ b/backend/app/jobs/handlers/shipping_order_extraction.py @@ -724,6 +724,58 @@ def _handoff_continue_order_extraction( return True +def _emit_reservation_heuristic_audit( + *, + run: Any, + merged_by_unit_id: dict[int, list[dict[str, Any]]], +) -> None: + """ + 合并末段「裸数字预约单号兜底」落地后补审计事件,供上线后观察误判率。 + + 【AI 触发时机】:EML 补充合并(merge_email_supplements)完成后调用。 + 只读订单上的 _hxops_reservation_heuristic 标记,不修改订单;命中与多候选 + 各发一条事件,metadata 携带 unit/候选值/正文文档定位,便于按 Case 回溯证据。 + + Args: + run: 当前订单抽取 Run(审计聚合根)。 + merged_by_unit_id: 本趟合并产物 {unit_id: [order]}。 + """ + applied_entries: list[dict[str, Any]] = [] + ambiguous_entries: list[dict[str, Any]] = [] + for unit_id, orders in (merged_by_unit_id or {}).items(): + for order in orders or []: + marker = order.get('_hxops_reservation_heuristic') if isinstance(order, dict) else None + if not isinstance(marker, dict): + continue + entry = { + 'unit_id': int(unit_id), + 'values': marker.get('values') or [], + 'document_id': marker.get('document_id'), + } + if marker.get('status') == 'applied': + applied_entries.append({**entry, 'value': marker.get('value')}) + else: + ambiguous_entries.append(entry) + for event_type, entries in ( + ('reservation_heuristic_applied', applied_entries), + ('reservation_heuristic_ambiguous', ambiguous_entries), + ): + if not entries: + continue + append_shipping_audit_event( + event_type=event_type, + aggregate_type='order_extraction_run', + aggregate_id=str(run.id), + run_no=run.run_no, + actor_type='system', + source='shipping_order_extraction', + metadata={ + 'entries': entries, + 'decision_rule_version': 'bare-numeric-reservation-v1', + }, + ) + + def _is_transient_lock_error(exc: BaseException) -> bool: """ 判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。 @@ -1139,6 +1191,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None: }, ) _merge_group_orders(eml_units, apply_email_supplements=True) + _emit_reservation_heuristic_audit(run=run, merged_by_unit_id=merged_by_unit_id) append_shipping_audit_event( event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED', aggregate_type='order_extraction_run', diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index ec9a04c3..8a1141be 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -47,6 +47,7 @@ from app.services.shipping_notice.order_candidate_builder import ( build_email_order_index, merge_attachment_candidate, ) +from app.services.shipping_notice.reservation_id import find_bare_numeric_reservation_candidates BODY_ATTACHMENT_KEY = 'body' @@ -665,6 +666,14 @@ 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 ''), + ) + supplement['email_subject'] = str(email_meta.get('subject') or '') body_doc.order_extraction_result_json = _json_safe_value({ 'email_supplement': supplement, }) @@ -680,6 +689,7 @@ def persist_documents_and_candidates( 'row_count': len(supplement.get('rows') or []), 'issue_codes': list(supplement.get('issues') or []), 'parser_version': supplement.get('version'), + 'reservation_candidate_count': len(supplement.get('reservation_candidates') or []), }, ) active_keys.add(BODY_ATTACHMENT_KEY) diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py index afeffd64..7dfaca94 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py @@ -95,6 +95,10 @@ class ProfileMatchCandidate(BaseModel): dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict) margin_to_next: float | None = Field(default=None, ge=0, le=1) coordinate_transform: dict[str, Any] | None = None + identity_rescue_assisted: bool = Field( + default=False, + description='该候选的表头身份由表头带证据补洞达成(order_profile_ocr_rescue)。', + ) class ProfileMatchResult(BaseModel): @@ -124,6 +128,10 @@ class ProfileMatchResult(BaseModel): margin: float | None = Field(default=None, ge=0, le=1) scoring_policy_version: str = MATCHER_POLICY_ID parse_validation: dict[str, Any] | None = None + identity_rescue_source: str | None = Field( + default=None, + description='本次唯一命中的表头带证据补洞来源(acroform_widget / ocr_coordinate);None=未补洞。', + ) def match_frozen_coordinate_profiles( @@ -1088,7 +1096,10 @@ def _header_normalized_words(text: str) -> list[str]: 核心逻辑:词级原子化与 Schema 别名短语匹配共用同一切词口径,保证两条路径 产出的身份原子完全同源;返回非空小写词序列(中文等非 [a-z0-9] 文本切词为空, - 调用方按各自的跳过策略处理)。 + 调用方按各自的跳过策略处理)。有意不拆驼峰:真实表头大小写不可靠 + ('UnitCost'/'unitcost'/'UNITCOST' 皆可能出现),仅按大小写边界拆分对全小写 + 渲染不生效,反而制造两侧不对称;camelCase 别名的对齐由 + schema_canonical_header_atoms/_tokens 的连写短语键承担。 """ normalized = _HEADER_PAREN_GLOSS.sub(' ', str(text).casefold()) normalized = re.sub(r"['’]", '', normalized) @@ -1180,10 +1191,12 @@ def schema_canonical_header_atoms( 具体措辞。未配置别名时零行为变化,完全退化为词级原子。 核心逻辑: - - header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零风险); + - header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零行为变化); - 先把每个别名 key 经与 token 完全相同的词管线(剥括号注记 → casefold → 去撇号 → 按非字母数字切词)转为词元组;同一词元组 casefold 后指向多个 field_code 时整体弃用该短语——身份归属不允许歧义; + - 多词别名额外注册去空格连写短语键([STEP 1.1],如 'Unit Cost' ↔ + 'unitcost'),使 camelCase 无分隔符表头与空格措辞收敛到同一 field 原子; - 逐 token 用同一词管线切词后做贪心最长短语匹配:命中即消费整段并产出 field:: 原子(短语内单词不再残留);未命中的剩余单词沿用词级 原子的既有过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS); @@ -1218,6 +1231,19 @@ def schema_canonical_header_atoms( if len(codes) == 1 } + # [STEP 1.1] 连写短语键:camelCase 别名经 normalize_table_header 拆成 + # 'Unit Cost' 类带空格键,但真实表头 token 常以无分隔符形式出现且大小写 + # 不可靠('UnitCost'/'unitcost'),按大小写边界拆词对全小写渲染不生效。 + # 为多词短语额外注册去空格连写键,使连写/空格/混合大小写拼写收敛到同一 + # field 原子;只新增、不覆盖既有键,连写键跨字段歧义时整体弃用(同 [STEP 1])。 + joined_candidates: dict[tuple[str, ...], set[str]] = {} + for words, code in phrase_to_field.items(): + if len(words) > 1: + joined_candidates.setdefault((''.join(words),), set()).add(code) + for joined, codes in joined_candidates.items(): + if len(codes) == 1 and joined not in phrase_to_field: + phrase_to_field[joined] = next(iter(codes)) + # [STEP 2] 逐 token 贪心最长短语匹配;未命中单词走既有词级原子过滤。 atoms: set[str] = set() for token in tokens: @@ -1269,6 +1295,7 @@ def schema_canonical_header_tokens( - header_to_field 为 None/空 dict 时原样返回输入列表(零归一、零行为变化); - 短语字典构建与 atoms [STEP 1] 完全同源:别名 key 经同一词管线转词元组, 同一词元组 casefold 后指向多个 field_code 时整体弃用(身份不允许歧义); + 多词别名同样注册连写短语键([STEP 1.1],与 atoms 同一口径); - 逐 token 贪心最长短语匹配:命中片段消费整段并在原位置产出**单个** `field::` 列表项(短语内单词不残留);未命中词按 atoms 同一 过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS)原词保留; @@ -1301,6 +1328,17 @@ def schema_canonical_header_tokens( if len(codes) == 1 } + # [STEP 1.1] 连写短语键:与 schema_canonical_header_atoms 的 [STEP 1.1] 同一 + # 口径——为 camelCase 多词别名注册去空格连写键('Unit Cost' ↔ 'UnitCost'/ + # 'unitcost'),只新增、不覆盖既有键,歧义整体弃用。 + joined_candidates: dict[tuple[str, ...], set[str]] = {} + for words, code in phrase_to_field.items(): + if len(words) > 1: + joined_candidates.setdefault((''.join(words),), set()).add(code) + for joined, codes in joined_candidates.items(): + if len(codes) == 1 and joined not in phrase_to_field: + phrase_to_field[joined] = next(iter(codes)) + # [STEP 2] 逐 token 贪心最长短语匹配;序列语义:命中产出单个标记列表项, # 未命中单词原样保留(沿用 atoms 过滤),整体保序、允许重复。 canonical: list[str] = [] diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py b/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py new file mode 100644 index 00000000..4479dbae --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py @@ -0,0 +1,395 @@ +""" +backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py + +用途:模板路由失败时的「表头带证据补洞」定向补救(Route B)。 +依赖:order_profile_matcher(匹配器与观测管线)、xfa_acroform(AcroForm 控件定位)、 + native_pdf(pdfium 渲染)、ocr_pdf(RapidOCR)、file_assets 服务、tool_common 配置。 +逻辑:常规匹配 layout_drift/no_match 且存在「仅表头判别冲突 + 观测原子为期望原子 + 真子集」的可补救候选集合时,按优先级补齐页 1 主表表头带证据: + ① AcroForm/XFA 控件展示值(确定性、精确坐标,覆盖供应商把表头文字放进 + 表单控件/矢量层的世代);② RapidOCR 表头带(纯扫描/图像兜底)。 + 补洞字形带 source 标记并入页 1 表头带后重跑完整匹配器;仅当结果恰好唯一 + 命中集合内某个候选时采纳并打 identity_rescue_source 标记,否则维持原判 + (fail-closed 由构造保证:补洞引入外来原子会破坏候选自身集合全等,同时 + 满足多个候选则转 ambiguous,均被拒绝)。补洞字形只在本次匹配内存中生效, + 禁止回写布局版本。 +""" + +from __future__ import annotations + +import unicodedata +from typing import Any, Callable + +from app.services.shipping_notice.document_layout.order_profile_matcher import ( + ProfileMatchCandidate, + ProfileMatchResult, + _extract_matching_signature, + _header_token_atoms, + _observe_layout_features, + _profile_exclusion_regions, + _profile_termination_rules, + _resolve_coordinate_transform, + _signature_identity_header_tokens, + _translate_signature, + match_frozen_coordinate_profiles, + schema_canonical_header_atoms, +) +from app.services.shipping_notice.document_layout.order_profile import ( + OrderCoordinateProfile, +) + +# 与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐;低于该置信度的 OCR 行不参与补洞。 +OCR_RESCUE_CONFIDENCE_FLOOR = 0.8 +# 表头带高度占主表高度的比例,与 _observe_header_candidates 的保守带一致。 +_HEADER_BAND_RATIO = 0.30 +_BAND_EPSILON = 0.005 + + +def _fold_diacritics(text: str) -> str: + """NFKD 折叠并剥离音变符号(Komárom→Komarom),与历史签名的无音变口径对齐。""" + decomposed = unicodedata.normalize('NFKD', str(text or '')) + return ''.join(ch for ch in decomposed if unicodedata.category(ch) != 'Mn') + + +def _candidate_header_atoms( + *, + raw_profile: dict[str, Any], + layout: dict[str, Any], + header_to_field: dict[str, str] | None, +) -> tuple[frozenset[str], frozenset[str], dict[str, Any]]: + """按匹配器同一观测口径计算候选的期望/观测表头原子与观测特征。""" + signature_body, _meta = _extract_matching_signature(raw_profile) + definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {} + profile = OrderCoordinateProfile( + profile_code=str(raw_profile.get('profile_code') or ''), + version=int(raw_profile.get('version') or 0), + document_match=definition.get('document_match'), + table_regions=definition.get('table_regions'), + order_field_layouts=definition.get('order_field_layouts') or [], + coordinate_model=definition.get('coordinate_model') or {}, + reference_page_frames=definition.get('reference_page_frames') or {}, + ) + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} + page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {} + glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {} + transform, _reasons = _resolve_coordinate_transform( + profile=profile, pages=pages, page_glyphs=page_glyphs, + ) + observed = _observe_layout_features( + layout=layout, + tables=[item for item in layout.get('tables') or [] if isinstance(item, dict)], + pages=pages, + glyph_tables=glyph_tables, + page_glyphs=page_glyphs, + signature=_translate_signature(signature=signature_body, coordinate_transform=transform), + termination_rules=_profile_termination_rules(profile), + exclusion_regions=_profile_exclusion_regions(profile), + ) + expected_tokens = _signature_identity_header_tokens(signature_body) + observed_tokens = [str(item) for item in observed.get('header_tokens') or []] + if header_to_field: + expected_atoms = schema_canonical_header_atoms(expected_tokens, header_to_field) + observed_atoms = schema_canonical_header_atoms(observed_tokens, header_to_field) + else: + expected_atoms = _header_token_atoms(expected_tokens) + observed_atoms = _header_token_atoms(observed_tokens) + return expected_atoms, observed_atoms, observed + + +def _eligible_rescue_candidates( + *, + match: ProfileMatchResult, + profiles: list[dict[str, Any]], + layout: dict[str, Any], + header_to_field: dict[str, str] | None, +) -> dict[tuple[str, int], tuple[ProfileMatchCandidate, dict[str, Any]]]: + """ + 甄别可补救候选集合:冲突仅表头判别、观测原子为期望原子真子集。 + + 核心逻辑:近亲模板常各自缺不同的尾部列,多个候选可同时可补救——竞争裁决 + 交给补洞后的完整重跑(接受条件要求补洞后恰好唯一命中集合内候选); + 观测侧存在期望之外的外来原子时该候选不可补救(不是单纯缺字)。 + """ + profile_by_key = { + (str(item.get('profile_code') or ''), int(item.get('version') or 0)): item + for item in profiles if isinstance(item, dict) + } + eligible: dict[tuple[str, int], tuple[ProfileMatchCandidate, dict[str, Any]]] = {} + for candidate in match.candidates: + if sorted(candidate.reason_codes) != ['profile_header_discriminator_conflict']: + continue + key = (candidate.profile_code, candidate.version) + raw = profile_by_key.get(key) + if raw is None: + continue + expected_atoms, observed_atoms, _observed = _candidate_header_atoms( + raw_profile=raw, layout=layout, header_to_field=header_to_field, + ) + if not (expected_atoms - observed_atoms) or (observed_atoms - expected_atoms): + continue + eligible[key] = (candidate, raw) + return eligible + + +def _glyphs_in_header_band( + *, + glyphs: list[dict[str, Any]], + page_width: float, + page_height: float, + primary_table_bbox: list[float] | None, + source: str, +) -> list[dict[str, Any]]: + """把补洞字形过滤到主表表头带内(归一化坐标,含少量容差)并打来源标记。""" + if not primary_table_bbox or len(primary_table_bbox) != 4: + return [] + if page_width <= 0 or page_height <= 0: + return [] + x0, y0, x1, y1 = primary_table_bbox + band_height = max(0.001, y1 - y0) * _HEADER_BAND_RATIO + kept: list[dict[str, Any]] = [] + for glyph in glyphs: + bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None + if not bbox: + continue + center_x = (float(bbox.get('x0') or 0) + float(bbox.get('x1') or 0)) / 2 / page_width + center_y = (float(bbox.get('y0') or 0) + float(bbox.get('y1') or 0)) / 2 / page_height + if ( + x0 - _BAND_EPSILON <= center_x <= x1 + _BAND_EPSILON + and y0 - _BAND_EPSILON <= center_y <= y0 + band_height + _BAND_EPSILON + ): + marked = dict(glyph) + marked['source'] = source + kept.append(marked) + return kept + + +def _text_to_char_glyphs(text: str, bbox: dict[str, float]) -> list[dict[str, Any]]: + """ + 把控件展示值按词分配展开为字形(与 OCR 字形同构,供视觉行重组)。 + + 核心逻辑:词内字符连续;词间与控件尾部预留 > 0.75×字符宽的几何空隙, + 保证 positioned_token_spans 的显著间隔分词能恢复出与签名一致的 token + 切分(否则相邻控件字形会被并词,如 'ETD'+'ETA' → 'etdeta')。 + """ + folded = _fold_diacritics(text) + words = [word for word in folded.split() if word.strip()] + if not words: + return [] + bbox_width = max(0.01, float(bbox['x1']) - float(bbox['x0'])) + usable_ratio = 0.7 + word_gap_ratio = 1.2 + total_chars = sum(len(word) for word in words) + char_width = bbox_width * usable_ratio / max(1, total_chars) + out: list[dict[str, Any]] = [] + x = float(bbox['x0']) + y0, y1 = float(bbox['y0']), float(bbox['y1']) + for word in words: + for character in word: + out.append({'text': character, 'bbox': { + 'x0': x, 'y0': y0, 'x1': x + char_width, 'y1': y1, + }}) + x += char_width + x += char_width * word_gap_ratio + return out + + +def _collect_rescue_glyphs( + *, + document: Any, + page: dict[str, Any], + primary_table_bbox: list[float] | None, + page_images_fn: Callable[[bytes], list[Any]] | None, + ocr_lines_fn: Callable[..., list[Any]] | None, + read_asset_fn: Callable[[int], bytes], +) -> tuple[list[dict[str, Any]], str] | None: + """ + 按优先级收集表头带补洞字形。 + + ① AcroForm/XFA 控件展示值(确定性);② 整带 RapidOCR(图像兜底)。 + Returns: + (字形列表, 来源标记) 或 None(无可用证据)。 + """ + page_width = float(page.get('width') or 0) + page_height = float(page.get('height') or 0) + asset_id = int(getattr(document, 'asset_id', 0) or 0) + # [STEP 1] AcroForm/XFA 控件文本:确定性坐标与文本,优先于 OCR。 + if asset_id > 0: + try: + from app.services.shipping_notice.document_layout.xfa_acroform import ( + read_acroform_widgets, + ) + content = read_asset_fn(asset_id) + widgets = [ + widget for widget in read_acroform_widgets(content) + if int(widget.page_no) == 1 and str(widget.value or '').strip() + ] + widget_glyphs: list[dict[str, Any]] = [] + for widget in widgets: + nb = widget.normalized_bbox or {} + if not all(key in nb for key in ('x0', 'y0', 'x1', 'y1')): + continue + widget_glyphs.extend(_text_to_char_glyphs(str(widget.value), { + 'x0': float(nb['x0']) * page_width, + 'y0': float(nb['y0']) * page_height, + 'x1': float(nb['x1']) * page_width, + 'y1': float(nb['y1']) * page_height, + })) + band = _glyphs_in_header_band( + glyphs=widget_glyphs, page_width=page_width, page_height=page_height, + primary_table_bbox=primary_table_bbox, source='acroform_widget', + ) + if band: + return band, 'acroform_widget' + except Exception: # noqa: BLE001 - 控件读取失败时回退 OCR 来源,补救不阻断主链 + pass + # [STEP 2] 表头带 RapidOCR:渲染页 1 后 OCR(纯扫描/图像世代兜底)。 + if asset_id <= 0: + return None + try: + if read_asset_fn is None: + from app.services.file_assets.service import read_asset_bytes + read_asset_fn = read_asset_bytes + if page_images_fn is None: + from app.services.shipping_notice.document_layout.native_pdf import ( + extract_native_pdf_pages, + ) + + def page_images_fn(content: bytes) -> list[Any]: + return extract_native_pdf_pages(content, render_images=True) + + if ocr_lines_fn is None: + from app.services.shipping_notice.document_layout.ocr_pdf import ( + OCR_CONFIDENCE_FLOOR, + extract_ocr_lines, + ) + + def ocr_lines_fn(*args: Any, **kwargs: Any) -> list[Any]: + kwargs.setdefault('minimum_confidence', OCR_CONFIDENCE_FLOOR) + return extract_ocr_lines(*args, **kwargs) + + pdf_pages = page_images_fn(read_asset_fn(asset_id)) + first_page = next((item for item in pdf_pages if int(item.page_no) == 1), None) + if first_page is None or first_page.image is None: + return None + ocr_lines = ocr_lines_fn( + first_page.image, + page_width=first_page.width, + page_height=first_page.height, + minimum_confidence=OCR_RESCUE_CONFIDENCE_FLOOR, + ) + if not ocr_lines: + return None + from app.services.shipping_notice.order_document_profile_service import ( + _ocr_lines_to_page_characters, + ) + + ocr_glyphs = [ + {**glyph, 'text': _fold_diacritics(str(glyph.get('text') or ''))} + for glyph in _ocr_lines_to_page_characters(lines=ocr_lines) + if str(glyph.get('text') or '').strip() + ] + band = _glyphs_in_header_band( + glyphs=ocr_glyphs, page_width=page_width, page_height=page_height, + primary_table_bbox=primary_table_bbox, source='ocr_coordinate', + ) + if band: + return band, 'ocr_coordinate' + return None + except (ValueError, TypeError, KeyError, OSError): + return None + + +def rescue_match_with_header_ocr( + *, + match: ProfileMatchResult, + profiles: list[dict[str, Any]], + layout: dict[str, Any], + header_to_field: dict[str, str] | None, + document: Any, + match_fn: Callable[..., ProfileMatchResult] | None = None, + page_images_fn: Callable[[bytes], list[Any]] | None = None, + ocr_lines_fn: Callable[..., list[Any]] | None = None, + read_asset_fn: Callable[[int], bytes] | None = None, +) -> ProfileMatchResult: + """ + 对路由失败结果尝试表头带证据补洞;任何不满足都原样返回(fail-closed)。 + + Args: + match: 常规匹配结果,须为 layout_drift / no_match 才尝试。 + profiles: 冻结模板快照列表(与常规匹配同一份)。 + layout: 已含原生坐标证据的运行期 Layout;禁止修改原对象。 + header_to_field: Schema 表头别名契约(与常规匹配同源)。 + document: ShippingOrderDocument;用于定位原始 PDF 资产。 + match_fn / page_images_fn / ocr_lines_fn / read_asset_fn: 测试注入点, + 默认分别使用真实匹配器、pdfium 渲染、RapidOCR 与资产读取。 + + Returns: + ProfileMatchResult:补洞成功返回带 identity_rescue_source 标记的唯一命中; + 否则原样返回入参 match。 + """ + if match.status not in {'layout_drift', 'no_match'} or not match.candidates: + return match + eligible = _eligible_rescue_candidates( + match=match, profiles=profiles, layout=layout, header_to_field=header_to_field, + ) + if not eligible: + return match + try: + evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {} + pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {} + page = pages.get('1') or pages.get(1) + if not isinstance(page, dict): + return match + if read_asset_fn is None: + from app.services.file_assets.service import read_asset_bytes + read_asset_fn = read_asset_bytes + _, _, probe_observed = _candidate_header_atoms( + raw_profile=next(iter(eligible.values()))[1], + layout=layout, + header_to_field=header_to_field, + ) + rescued_glyphs = _collect_rescue_glyphs( + document=document, page=page, + primary_table_bbox=probe_observed.get('primary_table_bbox'), + page_images_fn=page_images_fn, ocr_lines_fn=ocr_lines_fn, + read_asset_fn=read_asset_fn, + ) + if not rescued_glyphs: + return match + band_glyphs, rescue_source = rescued_glyphs + page_key = '1' + page_glyphs = dict(evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}) + page_glyphs[page_key] = list(page_glyphs.get(page_key) or []) + band_glyphs + augmented = dict(layout) + augmented_evidence = {**evidence, 'page_glyphs': page_glyphs} + merged_sources = dict(augmented_evidence.get('sources') or {}) + merged_page_sources = dict(merged_sources.get('pages') or {}) + merged_page_sources[page_key] = f"pdf_coordinate+{rescue_source}" + merged_sources['pages'] = merged_page_sources + augmented_evidence['sources'] = merged_sources + augmented['coordinate_evidence'] = augmented_evidence + + re_match_fn = match_fn if match_fn is not None else match_frozen_coordinate_profiles + rescued = re_match_fn( + profiles=profiles, layout=augmented, header_to_field=header_to_field, + ) + if rescued.status not in {'unique_match', 'selected_by_score'}: + return match + winner_key = (str(rescued.profile_code or ''), int(rescued.version or 0)) + if winner_key not in eligible: + # 补洞改变了竞争格局(唤醒了集合外候选)——维持原判。 + return match + marked_candidates = [ + item.model_copy(update={'identity_rescue_assisted': ( + str(item.profile_code or ''), int(item.version or 0)) == winner_key + }) + for item in rescued.candidates + ] + return rescued.model_copy(update={ + 'identity_rescue_source': rescue_source, + 'candidates': marked_candidates, + }) + except (ValueError, TypeError, KeyError, OSError): + # 补救属锦上添花:任何数据/环境异常都回退原判,不阻断主链。 + return match 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 546bec50..767ffc4d 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -866,6 +866,7 @@ def _build_snapshot( ) from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan + from app.services.shipping_notice.reservation_id import find_bare_numeric_reservation_candidates table_contract = compile_table_header_contract(dict(schema_version.definition_json or {})) generic_config = ( @@ -932,6 +933,14 @@ 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 ''), + ) + email_supplement['email_subject'] = str(email.get('subject') or '') document_snapshot = { 'document_id': document.id, 'document_type': document.document_type, diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index f1bb7815..5ed74fd5 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -49,6 +49,9 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import ( ProfileMatchResult, match_frozen_coordinate_profiles, ) +from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import ( + rescue_match_with_header_ocr, +) from app.services.shipping_notice.document_layout.order_profile_parse_validation import ( validate_profile_parse_candidate, ) @@ -1078,6 +1081,16 @@ def _profile_table_candidates( profiles=coordinate_profiles, layout=layout, header_to_field=contract.header_to_field, ) + if ( + match.status in {'layout_drift', 'no_match'} + and document_model is not None + ): + # 表头带证据补洞:仅当存在「仅表头判别冲突 + 观测原子纯缺失」候选时 + # 尝试;重跑完整匹配器且恰好唯一命中可补救候选才采纳,否则维持原判。 + match = rescue_match_with_header_ocr( + match=match, profiles=coordinate_profiles, layout=layout, + header_to_field=contract.header_to_field, document=document_model, + ) affinity_applied = False if not match_only: match = _apply_parse_validation_gate( diff --git a/backend/app/services/shipping_notice/order_supplement_merge.py b/backend/app/services/shipping_notice/order_supplement_merge.py index fd75403b..54fff4d1 100644 --- a/backend/app/services/shipping_notice/order_supplement_merge.py +++ b/backend/app/services/shipping_notice/order_supplement_merge.py @@ -4,6 +4,9 @@ 逻辑:优先 PO+MPN;其次同 PO+合法 reservation_id 对齐;仅唯一签名的 PO 可降级广播; 无同 PO 候选时仅对「PO 缺失」行做唯一料号兜底(mpn_fallback);有 PO 且与 PDF 不一致则禁止补充。歧义只写复核原因。同趟单次合并,不互相重入。 + 主合并结束后另做「裸数字兜底」:仍无预约单号的订单,从正文裸 5/10 位数字 + 候选里排除已识别字段值/主题标签值/跨单已占用值,唯一候选以低置信度写入 + header 默认值,多候选转为复核冲突,绝不覆盖任何已有值。 """ from __future__ import annotations @@ -13,7 +16,12 @@ from typing import Any from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value from app.services.shipping_notice.po_number import normalize_atomic_po_number -from app.services.shipping_notice.reservation_id import validated_reservation_id +from app.services.shipping_notice.reservation_id import ( + filter_reservation_heuristic_candidates, + normalize_reservation_id, + reservation_ids_in_labeled_context, + validated_reservation_id, +) def _values(fields: Any, code: str, codes: dict[str, str]) -> set[str]: @@ -273,6 +281,182 @@ def _supplement_multi_value_conflict( } +def _iter_order_observation_values(order: dict[str, Any]) -> list[Any]: + """收集订单头 + 全部行的原始字段 Observation 值,供兜底排除集使用。""" + values: list[Any] = [] + field_groups: list[Any] = [order.get('header_fields')] + for line in order.get('lines') or []: + if isinstance(line, dict): + field_groups.append(line.get('fields')) + for fields in field_groups: + if not isinstance(fields, list): + continue + for field in fields: + if not isinstance(field, dict): + continue + for observation in field.get('observations') or []: + if isinstance(observation, dict) and observation.get('value') not in (None, ''): + values.append(observation.get('value')) + return values + + +def _heuristic_excluded_values( + order: dict[str, Any], + supplement: dict[str, Any], +) -> set[str]: + """构造裸数字候选的排除集:订单已提取值 + 邮件补充行值 + 邮件主题标签值。 + + 核心逻辑:客户 PO 号本身就是 10 位纯数字,是启发式最大的误判源;因此除了 + 订单 Observation 原值外,还纳入 Reservation/PO 两种归一变体(千分位、x.0、 + 前导零),并排除主题里「PO xxx」等带标签数字(Q10 双保险)。 + """ + excluded: set[str] = set() + raw_values = _iter_order_observation_values(order) + rows = supplement.get('rows') if isinstance(supplement.get('rows'), list) else [] + for row in rows: + if isinstance(row, dict): + raw_values.extend(str(value) for value in row.values() if str(value or '').strip()) + for raw in raw_values: + text = str(raw).strip() + if text: + excluded.add(text.upper()) + normalized = validated_reservation_id(normalize_reservation_id(raw)) + if normalized: + excluded.add(normalized) + excluded.add(normalized.lstrip('0')) + po = normalize_atomic_po_number(raw) + if po: + excluded.add(po.upper()) + excluded.add(po.lstrip('0').upper() or po.upper()) + excluded.update( + value.upper() + for value in reservation_ids_in_labeled_context(str(supplement.get('email_subject') or '')) + ) + return {value for value in excluded if value} + + +def _inject_reservation_heuristic( + fields: list[dict[str, Any]], + field_id: str, + value: str, + evidence: dict[str, Any], + document_id: int, +) -> None: + """以裸数字兜底语义写入 reservation Observation:低置信度并携带 basis 标记。 + + 与 _inject 的差异:confidence 固定 0.5(启发式,非权威证据), + email_supplement_evidence 增加 basis='bare_numeric_heuristic' 供复核端标注。 + """ + target = next((item for item in fields if isinstance(item, dict) and item.get('field_id') == field_id), None) + observation = { + 'value': value, 'document_id': document_id, 'quote': str(evidence.get('raw_value') or value), + 'confidence': 0.5, 'email_supplement_evidence': { + 'table_index': evidence.get('table_index'), 'row_index': evidence.get('row_index'), + 'column_index': evidence.get('column_index'), 'cell_id': evidence.get('cell_id'), + 'basis': 'bare_numeric_heuristic', + }, + } + if target is None: + fields.append({'field_id': field_id, 'observations': [observation]}) + else: + target['observations'] = [observation] + + +def _order_has_reservation_value(order: dict[str, Any], ids: dict[str, str]) -> bool: + """判断订单头或任意行已存在预约单号取值(含非法格式原值);存在则兜底绝不写入。 + + 按 Q2 契约「已有值永不覆盖」:即使原值未通过 5/10 位校验(如字母型编号), + 也视为已有业务事实,只能走人工纠错,不能被裸数字猜测悄悄替换。 + """ + reverse_ids = {v: k for k, v in ids.items()} + if _values(order.get('header_fields'), 'reservation_id', reverse_ids): + return True + for line in order.get('lines') or []: + if isinstance(line, dict) and _values(line.get('fields'), 'reservation_id', reverse_ids): + return True + return False + + +def _apply_reservation_heuristic( + order: dict[str, Any], + supplement: dict[str, Any], + *, + configs: dict[str, dict[str, Any]], + ids: dict[str, str], + schema_version: str, + claimed: set[str], +) -> None: + """对仍无预约单号的订单执行裸数字兜底裁决(唯一→写入;多候选→冲突)。 + + 核心逻辑: + [STEP 1] Schema 无 reservation_id 字段、候选键缺失或订单已有合法值 → 直接返回; + [STEP 2] 排除集 = 订单已提取值 ∪ 补充行值 ∪ 主题标签值 ∪ 跨单已占用(claimed); + [STEP 3] 唯一候选 → 按 Schema 作用域写入 header 默认值或缺失行,relation 标记 + reservation_heuristic 供工作台补充状态展示; + [STEP 4] 多候选 → 复用 supplement_field_conflict 冲突结构(values + 逐候选 + email_body 证据源),转现有字段冲突裁决面板,绝不自动挑值。 + """ + config = configs.get('reservation_id') + field_id = ids.get('reservation_id') + candidates = supplement.get('reservation_candidates') + if config is None or not field_id or not isinstance(candidates, list) or not candidates: + return + if _order_has_reservation_value(order, ids): + return + excluded = _heuristic_excluded_values(order, supplement) | claimed + surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=excluded) + if status == 'none': + return + 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} + if status == 'unique': + value = validated_reservation_id(values[0]) + if not value: + return + evidence = dict(surviving[0].get('evidence') or {}) + if str(config.get('scope') or '') == 'header': + header_fields = order.get('header_fields') + if isinstance(header_fields, list): + _inject_reservation_heuristic(header_fields, field_id, value, evidence, document_id) + else: + # 行级写入只补真正缺失的行;带任何原值(含非法格式)的行不覆盖。 + reverse_ids = {v: k for k, v in ids.items()} + for line in order.get('lines') or []: + if isinstance(line, dict) and isinstance(line.get('fields'), list): + if not _values(line['fields'], 'reservation_id', reverse_ids): + _inject_reservation_heuristic(line['fields'], field_id, value, evidence, document_id) + claimed.add(value) + marker['status'] = 'applied' + marker['value'] = value + if not str(order.get('_hxops_email_supplement_relation') or '').strip(): + order['_hxops_email_supplement_relation'] = 'reservation_heuristic' + else: + pseudo_rows = [ + { + 'reservation_id': item.get('value'), + 'table_index': (item.get('evidence') or {}).get('table_index'), + 'row_index': (item.get('evidence') or {}).get('row_index'), + 'evidence': {'reservation_id': dict(item.get('evidence') or {})}, + } + for item in surviving + ] + conflict = _supplement_multi_value_conflict( + field_code='reservation_id', + config=config, + values=set(values), + selected_rows=pseudo_rows, + line_index=-1, + email_document_id=document_id, + schema_version=schema_version, + ) + if conflict not in order.setdefault('conflicts', []): + order['conflicts'].append(conflict) + if not str(order.get('_hxops_email_supplement_relation') or '').strip(): + order['_hxops_email_supplement_relation'] = 'reservation_heuristic' + order['_hxops_reservation_heuristic'] = marker + + def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]: """ 按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。 @@ -487,4 +671,18 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta }) order['_hxops_email_supplement_relation'] = relation merged.append(order) + # [STEP] 裸数字兜底:主合并完成后仍无预约单号的订单,按排除规则裁决正文候选。 + # 跨单 claimed 防止同一候选同时灌入多个订单;旧 Run 补充快照无候选键时整体跳过。 + claimed_reservations: set[str] = set() + for order in merged: + supplement = supplements_by_intake.get(int(order.get('_hxops_intake_id') or 0)) + if isinstance(supplement, dict) and isinstance(supplement.get('reservation_candidates'), list): + _apply_reservation_heuristic( + order, + supplement, + configs=configs, + ids=ids, + schema_version=schema_version, + claimed=claimed_reservations, + ) return merged diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py index 5a837afb..8fdc7d3b 100644 --- a/backend/app/services/shipping_notice/reservation_id.py +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -2,9 +2,11 @@ services/shipping_notice/reservation_id.py 用途:提取、标准化并校验发货通知与库存中的 Reservation ID。 -依赖:正则表达式与标准 `typing` 工具。 +依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。 逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用; 归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。 + 另提供「裸数字兜底」:正文无表头且常规证据缺失时,扫描排除后的 5/10 位 + 纯数字候选(供 order_supplement_merge 在合并末段做唯一/多候选裁决)。 """ from __future__ import annotations @@ -30,6 +32,17 @@ 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"(? str: @@ -151,3 +164,135 @@ 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 _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 表格单元格文本及其证据定位;解析失败的表安全跳过。 + + 逻辑:版面网格的 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 find_bare_numeric_reservation_candidates( + *, + body_text: str = "", + html_tables: list[str] | None = None, + content_hash: str = "", +) -> list[dict[str, Any]]: + """扫描正文中的裸 5/10 位纯数字预约单号候选(排除带业务标签的数字)。 + + AI 触发时机:EML 正文数据行没有表头、常规表头契约解析不出预约单号时, + 在补充事实里预置候选列表;真正「是否采纳」由 order_supplement_merge 在 + 合并末段结合已提取字段值裁决,本函数绝不直接写入订单。 + + 核心逻辑:先扫 HTML 表格单元格(保留 DOM cell_id 证据),再扫纯文本行 + (保留行号与上下文片段);紧跟 PO/订单/发票/数量标签的数字串不作为候选; + 同值只保留首个证据;总数截断到 MAX_HEURISTIC_RESERVATION_CANDIDATES。 + + Args: + body_text: EML 正文纯文本(含展平的数据行)。 + 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。扫描不到返回空列表。 + """ + 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}) + 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' diff --git a/backend/tests/test_order_profile_header_identity.py b/backend/tests/test_order_profile_header_identity.py index b9ffaa49..eb2d0da5 100644 --- a/backend/tests/test_order_profile_header_identity.py +++ b/backend/tests/test_order_profile_header_identity.py @@ -11,7 +11,8 @@ tests/test_order_profile_header_identity.py 逻辑:pure_unit;别名命中产出 field:: 标记原子(atoms 为集合语义、 tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤; None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date - 别名的契约下跨措辞对齐,异义词不归并。 + 别名的契约下跨措辞对齐,异义词不归并;camelCase 无分隔符表头(UnitCost/ + VendorPartNumber)与空格措辞同管线归一,不得再判身份互斥。 """ from __future__ import annotations @@ -296,3 +297,58 @@ def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias(): assert canonical_expected == canonical_observed # 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住) assert canonical_expected[0] == 'field::customer_po_line_no' + + +# --------------------------------------------------------------------------- +# camelCase 无分隔符表头(真实故障:prod schema 别名 UnitCost/VendorPartNumber +# 经 normalize_table_header 拆成 'Unit Cost'/'Vendor Part Number' 键,而匹配器 +# 词管线不拆驼峰,token 'UnitCost' 切成单词 'unitcost',短语匹配静默失效) +# --------------------------------------------------------------------------- + +def _contract_mapping(**aliases: str) -> dict[str, str]: + """按 compile_table_header_contract 真实链路构造别名键(normalize_table_header)。""" + from app.services.shipping_notice.order_schema.table_contract import ( + normalize_table_header, + ) + return {normalize_table_header(alias): code for alias, code in aliases.items()} + + +def test_camelcase_token_hits_camelcase_alias(): + """无分隔符驼峰 token 必须命中经 normalize_table_header 拆键的驼峰别名。""" + mapping = _contract_mapping(UnitCost='unit_price') + # 关键断言:契约键为 'Unit Cost'(拆驼峰),token 'UnitCost' 走同一拆分后命中 + assert 'Unit Cost' in mapping + assert schema_canonical_header_atoms(['UnitCost'], mapping) == frozenset( + {'field::unit_price'}, + ) + + +def test_word_atom_pipeline_stays_case_unsplit(): + """词级原子管线有意不拆驼峰(真实表头大小写不可靠);camel 对齐由连写短语键承担。""" + # 关键断言:无别名契约时 'UnitCost' 与 'Unit Cost' 词级原子不同(零行为变化契约); + # 两者身份对齐只能在别名契约下经由连写短语键达成 + assert _header_token_atoms(['UnitCost']) == frozenset({'unitcost'}) + assert _header_token_atoms(['Unit Cost']) == frozenset({'unit', 'cost'}) + + +def test_camelcase_wording_difference_not_identity_conflict(): + """模板侧连写、观测侧空格(或反向)在别名契约下不得判原子互斥冲突。""" + mapping = _contract_mapping(UnitCost='unit_price') + signature_tokens = ['Itm', 'UnitCost', 'Extended Cost'] + observed_tokens = ['itm', 'Unit Cost', 'extended cost'] + # 关键断言:唯一措辞差异是驼峰连写 vs 空格,且该列有别名覆盖 → 非身份冲突 + assert _header_discriminator_atoms_conflict( + signature={'table_patterns': [{'header_tokens': signature_tokens}]}, + observed={'header_tokens': observed_tokens}, + header_to_field=mapping, + ) is False + + +def test_camelcase_tokens_canonical_keeps_order_and_marker(): + """canonical 序列版对驼峰 token 产出单个标记项且保持词序(与 atoms 同源)。""" + canonical = schema_canonical_header_tokens( + ['VendorPartNumber', 'UnitCost'], + _contract_mapping(VendorPartNumber='part_number', UnitCost='unit_price'), + ) + # 关键断言:每个驼峰 token 各消费为单个 field 标记项,顺序保留、无单词残留 + assert canonical == ['field::part_number', 'field::unit_price'] diff --git a/backend/tests/test_order_profile_ocr_rescue.py b/backend/tests/test_order_profile_ocr_rescue.py new file mode 100644 index 00000000..e00377cd --- /dev/null +++ b/backend/tests/test_order_profile_ocr_rescue.py @@ -0,0 +1,333 @@ +""" +tests/test_order_profile_ocr_rescue.py + +用途:锁定表头带证据补洞(order_profile_ocr_rescue)的门禁契约。 +依赖:order_profile_ocr_rescue.rescue_match_with_header_ocr / _eligible_rescue_candidates / + _glyphs_in_header_band、ProfileMatchResult/Candidate。 +逻辑:pure_unit;仅「候选集合 = 冲突仅表头判别 + 观测原子纯缺失」可补救;重跑匹配器 + 必须恰好唯一命中集合内候选才采纳并打 identity_rescue_source 标记;改变竞争格局 / + 仍失败 / 无补洞字形 / 带外字形一律原样返回原判;原 layout 禁止突变。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import ( + OCR_RESCUE_CONFIDENCE_FLOOR, + _eligible_rescue_candidates, + _glyphs_in_header_band, + rescue_match_with_header_ocr, +) +from app.services.shipping_notice.document_layout.order_profile_matcher import ( + ProfileMatchCandidate, + ProfileMatchResult, +) + +pytestmark = pytest.mark.pure_unit + +V2_CODE = 'ODP-TEST-V2' +OTHER_CODE = 'ODP-TEST-OTHER' + + +def _candidate(code: str, reasons: list[str]) -> ProfileMatchCandidate: + return ProfileMatchCandidate( + profile_code=code, version=1, score=0.0, hard_match=False, + reason_codes=reasons, + ) + + +def _drift_match(candidates: list[ProfileMatchCandidate]) -> ProfileMatchResult: + return ProfileMatchResult(status='layout_drift', candidates=candidates) + + +def _layout() -> dict: + return { + 'tables': [{'table_id': 't1', 'page_no': 1, 'bbox': [16, 185, 590, 266]}], + 'coordinate_evidence': { + 'pages': {'1': {'width': 595.0, 'height': 842.0}}, + 'page_glyphs': {'1': [{'text': 'I', 'bbox': {'x0': 23, 'y0': 190, 'x1': 26, 'y1': 202}}]}, + 'sources': {'pages': {'1': 'pdf_coordinate'}}, + }, + } + + +def _profiles() -> list[dict]: + return [ + {'profile_code': V2_CODE, 'version': 1, 'definition': {}}, + {'profile_code': OTHER_CODE, 'version': 1, 'definition': {}}, + ] + + +def _patch_atoms(monkeypatch, per_code: dict[str, tuple[frozenset, frozenset]]) -> None: + """按 profile_code 固定期望/观测原子,隔离匹配器观测管线。""" + def fake(*, raw_profile, layout, header_to_field): + expected, observed = per_code[str(raw_profile['profile_code'])] + return frozenset(expected), frozenset(observed), {'primary_table_bbox': [0.027, 0.22, 0.99, 0.32]} + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.order_profile_ocr_rescue._candidate_header_atoms', + fake, + ) + + +def _ocr_line(text: str, x0: float, y0: float, x1: float, y1: float, confidence: float = 0.95): + return SimpleNamespace( + text=text, confidence=confidence, + bbox=SimpleNamespace(x0=x0, y0=y0, x1=x1, y1=y1), + ) + + +def _fake_page() -> SimpleNamespace: + return SimpleNamespace(page_no=1, width=595.0, height=842.0, image=object()) + + +def test_eligibility_collects_all_subset_candidates(monkeypatch): + """近亲模板各自缺不同尾部列时可同时可补救;竞争由补洞后的重跑裁决。""" + match = _drift_match([ + _candidate(V2_CODE, ['profile_header_discriminator_conflict']), + _candidate(OTHER_CODE, ['profile_header_discriminator_conflict']), + ]) + _patch_atoms(monkeypatch, { + V2_CODE: ({'itm', 'qty', 'etd', 'eta'}, {'itm', 'qty'}), + OTHER_CODE: ({'itm', 'qty', 'del'}, {'itm', 'qty'}), + }) + eligible = _eligible_rescue_candidates( + match=match, profiles=_profiles(), layout=_layout(), header_to_field=None, + ) + # 关键断言:两个纯缺失候选都进入可补救集合,由重跑匹配器唯一性仲裁 + assert {(code, version) for (code, version) in eligible} == {(V2_CODE, 1), (OTHER_CODE, 1)} + + +def test_eligibility_rejects_foreign_atoms(monkeypatch): + """观测侧存在期望之外的外来原子 → 不是单纯缺字,不可补救。""" + match = _drift_match([ + _candidate(V2_CODE, ['profile_header_discriminator_conflict']), + _candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']), + ]) + _patch_atoms(monkeypatch, { + V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty', 'date'}), + OTHER_CODE: ({'x', 'y', 'z'}, {'x'}), + }) + # 关键断言:差集必须「纯缺失」(observed ⊂ expected),有外来词的候选被排除; + # OTHER(含拓扑冲突非纯判别)同样不进集合 → 集合为空 + assert _eligible_rescue_candidates( + match=match, profiles=_profiles(), layout=_layout(), header_to_field=None, + ) == {} + + +def test_rescue_success_marks_unique_same_candidate(monkeypatch): + """补洞后重跑匹配器须恰好唯一命中集合内候选,成功时打 identity_rescue_source 标记。""" + match = _drift_match([ + _candidate(V2_CODE, ['profile_header_discriminator_conflict']), + _candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']), + ]) + _patch_atoms(monkeypatch, { + V2_CODE: ({'itm', 'qty', 'etd', 'eta', 'komarom'}, {'itm', 'qty'}), + OTHER_CODE: ({'a', 'b'}, {'a'}), + }) + captured = {} + + def fake_match_fn(*, profiles, layout, header_to_field): + captured['layout'] = layout + winner = ProfileMatchCandidate( + profile_code=V2_CODE, version=1, score=0.99, hard_match=True, reason_codes=[], + ) + loser = ProfileMatchCandidate( + profile_code=OTHER_CODE, version=1, score=0.0, hard_match=False, + reason_codes=['profile_column_topology_conflict'], + ) + return ProfileMatchResult( + status='unique_match', profile_code=V2_CODE, version=1, + candidates=[winner, loser], + ) + + layout = _layout() + result = rescue_match_with_header_ocr( + match=match, profiles=_profiles(), layout=layout, header_to_field=None, + document=SimpleNamespace(asset_id=7), + match_fn=fake_match_fn, + page_images_fn=lambda content: [_fake_page()], + ocr_lines_fn=lambda *a, **k: [ + _ocr_line('ETD', 460, 190, 480, 202), + _ocr_line('ETA Komarom', 500, 190, 560, 202), + ], + read_asset_fn=lambda asset_id: b'%PDF-fake', + ) + # 关键断言:结果翻转为唯一命中且带补洞来源标记,仅命中候选被打标 + assert result.status == 'unique_match' + assert result.identity_rescue_source == 'ocr_coordinate' + marked = {c.profile_code: c.identity_rescue_assisted for c in result.candidates} + assert marked == {V2_CODE: True, OTHER_CODE: False} + # 关键断言:补洞字形只并入增强副本的页 1 表头带,且带来源标记 + original_glyphs = _layout()['coordinate_evidence']['page_glyphs']['1'] + augmented_glyphs = captured['layout']['coordinate_evidence']['page_glyphs']['1'] + assert len(augmented_glyphs) > len(original_glyphs) + assert all(g.get('source') == 'ocr_coordinate' for g in augmented_glyphs[len(original_glyphs):]) + assert captured['layout']['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate+ocr_coordinate' + # 关键断言:原 layout 不得被突变 + assert layout['coordinate_evidence']['page_glyphs']['1'] == original_glyphs + assert layout['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate' + + +def test_rescue_aborts_when_rematch_changes_winner(monkeypatch): + """补洞唤醒集合外候选(改变竞争格局)→ 维持原判。""" + match = _drift_match([ + _candidate(V2_CODE, ['profile_header_discriminator_conflict']), + _candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']), + ]) + _patch_atoms(monkeypatch, { + V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}), + OTHER_CODE: ({'a', 'b'}, {'a'}), + }) + + def fake_match_fn(*, profiles, layout, header_to_field): + return ProfileMatchResult( + status='unique_match', profile_code=OTHER_CODE, version=1, + candidates=[_candidate(OTHER_CODE, [])], + ) + + result = rescue_match_with_header_ocr( + match=match, profiles=_profiles(), layout=_layout(), header_to_field=None, + document=SimpleNamespace(asset_id=7), + match_fn=fake_match_fn, + page_images_fn=lambda content: [_fake_page()], + ocr_lines_fn=lambda *a, **k: [_ocr_line('ETD', 460, 190, 480, 202)], + read_asset_fn=lambda asset_id: b'%PDF-fake', + ) + # 关键断言:命中者不在可补救集合内 → 原样返回原 layout_drift 判定 + assert result is match + + +def test_rescue_aborts_when_rematch_still_drift(monkeypatch): + """补洞词未能补齐原子(仍 layout_drift)→ 维持原判。""" + match = _drift_match([ + _candidate(V2_CODE, ['profile_header_discriminator_conflict']), + _candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']), + ]) + _patch_atoms(monkeypatch, { + V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}), + OTHER_CODE: ({'a', 'b'}, {'a'}), + }) + + def fake_match_fn(*, profiles, layout, header_to_field): + return _drift_match([ + _candidate(V2_CODE, ['profile_header_discriminator_conflict']), + _candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']), + ]) + + result = rescue_match_with_header_ocr( + match=match, profiles=_profiles(), layout=_layout(), header_to_field=None, + document=SimpleNamespace(asset_id=7), + match_fn=fake_match_fn, + page_images_fn=lambda content: [_fake_page()], + ocr_lines_fn=lambda *a, **k: [_ocr_line('ETD', 460, 190, 480, 202)], + read_asset_fn=lambda asset_id: b'%PDF-fake', + ) + assert result is match + + +def test_rescue_aborts_without_ocr_lines(monkeypatch): + """OCR 无返回(引擎失败或全部低于置信度)→ 维持原判。""" + match = _drift_match([ + _candidate(V2_CODE, ['profile_header_discriminator_conflict']), + _candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']), + ]) + _patch_atoms(monkeypatch, { + V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}), + OTHER_CODE: ({'a', 'b'}, {'a'}), + }) + seen = {} + + def fake_ocr(*args, **kwargs): + seen['minimum_confidence'] = kwargs.get('minimum_confidence') + return [] + + result = rescue_match_with_header_ocr( + match=match, profiles=_profiles(), layout=_layout(), header_to_field=None, + document=SimpleNamespace(asset_id=7), + match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')), + page_images_fn=lambda content: [_fake_page()], + ocr_lines_fn=fake_ocr, + read_asset_fn=lambda asset_id: b'%PDF-fake', + ) + assert result is match + # 关键断言:OCR 置信度门禁与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐 + assert seen['minimum_confidence'] == OCR_RESCUE_CONFIDENCE_FLOOR + + +def test_header_band_filter_drops_out_of_band_glyphs(): + """带外补洞字形必须被过滤,只保留主表表头带内的字形并打来源标记。""" + page_width, page_height = 595.0, 842.0 + glyphs = [ + {'text': 'E', 'bbox': {'x0': 460, 'y0': 190, 'x1': 466, 'y1': 202}}, + {'text': 'X', 'bbox': {'x0': 460, 'y0': 400, 'x1': 466, 'y1': 412}}, + {'text': 'Y', 'bbox': {'x0': 2, 'y0': 190, 'x1': 8, 'y1': 202}}, + ] + kept = _glyphs_in_header_band( + glyphs=glyphs, page_width=page_width, page_height=page_height, + primary_table_bbox=[0.027, 0.22, 0.99, 0.32], source='ocr_coordinate', + ) + # 关键断言:仅带内字形保留(y≈0.23 ∈ [0.22, 0.22+0.3*0.1];x=0.008 < 0.022 带外), + # 且带 source 标记 + assert [g['text'] for g in kept] == ['E'] + assert kept[0]['source'] == 'ocr_coordinate' + + +def test_rescue_prefers_acroform_widgets_over_ocr(monkeypatch): + """AcroForm 控件文本是首选补洞来源(确定性);命中时不得触发渲染和 OCR。""" + match = _drift_match([ + _candidate(V2_CODE, ['profile_header_discriminator_conflict']), + _candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']), + ]) + _patch_atoms(monkeypatch, { + V2_CODE: ({'itm', 'qty', 'etd', 'eta', 'komarom'}, {'itm', 'qty'}), + OTHER_CODE: ({'a', 'b'}, {'a'}), + }) + + def fake_widget(code: str, value: str): + return SimpleNamespace( + page_no=1, value=value, + normalized_bbox={'x0': 0.77, 'y0': 0.235, 'x1': 0.85, 'y1': 0.25}, + qualified_name=code, short_name=code, widget_id=code, + ) + + monkeypatch.setattr( + 'app.services.shipping_notice.document_layout.xfa_acroform.read_acroform_widgets', + lambda content: [ + fake_widget('C_ETD', 'ETD'), + fake_widget('C_ETA', 'ETA Komarom'), + ], + ) + result = rescue_match_with_header_ocr( + match=match, profiles=_profiles(), layout=_layout(), header_to_field=None, + document=SimpleNamespace(asset_id=7), + match_fn=lambda **k: ProfileMatchResult( + status='unique_match', profile_code=V2_CODE, version=1, + candidates=[_candidate(V2_CODE, [])], + ), + page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')), + ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')), + read_asset_fn=lambda asset_id: b'%PDF-fake', + ) + # 关键断言:AcroForm 来源直接命中,OCR/渲染路径完全未被触达 + assert result.identity_rescue_source == 'acroform_widget' + assert result.status == 'unique_match' + + +def test_rescue_skipped_for_non_failed_status(): + """常规匹配已成功(如 unique_match)时绝不触发证据补洞。""" + match = ProfileMatchResult( + status='unique_match', profile_code=V2_CODE, version=1, + candidates=[_candidate(V2_CODE, [])], + ) + result = rescue_match_with_header_ocr( + match=match, profiles=_profiles(), layout=_layout(), header_to_field=None, + document=SimpleNamespace(asset_id=7), + match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')), + page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')), + ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')), + read_asset_fn=lambda asset_id: (_ for _ in ()).throw(AssertionError('asset must not run')), + ) + assert result is match diff --git a/backend/tests/test_shipping_reservation_heuristic.py b/backend/tests/test_shipping_reservation_heuristic.py new file mode 100644 index 00000000..277de2dc --- /dev/null +++ b/backend/tests/test_shipping_reservation_heuristic.py @@ -0,0 +1,330 @@ +"""验证 EML 无表头正文「裸 5/10 位数字兜底识别预约单号」的扫描、排除与合并裁决。 + +依赖:reservation_id 启发式原语与 order_supplement_merge 合并服务。 +逻辑:无表头数据行解析不出补充行时,正文裸数字候选在合并末段结合 + 已提取字段值/主题标签值/跨单占用裁决——唯一候选低置信度写入, + 多候选转 supplement_field_conflict 人工裁决,已有值绝不覆盖。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.order_supplement_merge import merge_email_supplements +from app.services.shipping_notice.reservation_id import ( + filter_reservation_heuristic_candidates, + find_bare_numeric_reservation_candidates, + reservation_ids_in_labeled_context, +) + + +SCHEMA = {'fields': [ + {'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']}, + {'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']}, + {'field_id': 'qty', 'field_code': 'qty'}, + { + 'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', + 'aliases': ['Reservation ID', 'External reservation ID'], + }, +]} + +HEADER_RESERVATION_SCHEMA = {'fields': [ + {'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header'}, + { + 'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'header', + 'aliases': ['Reservation ID'], + }, +]} + + +def _order() -> dict: + """构造 PDF 已解析出 PO/料号/数量、但缺预约单号的订单(截图 1 场景)。""" + return { + '_hxops_intake_id': 1, + 'header_fields': [{'field_id': 'po', 'observations': [{'value': '1000053337'}]}], + 'lines': [{'fields': [ + {'field_id': 'part', 'observations': [{'value': 'D4-AR1200163A1'}]}, + {'field_id': 'qty', 'observations': [{'value': 120}]}, + ]}], + 'conflicts': [], + } + + +def _supplement(candidates: list[str], **extra) -> dict: + """构造带裸数字候选的正文补充事实(无表头场景 rows 为空)。""" + return { + 'rows': [], + 'issues': [], + 'version': 'email-supplement.v1', + 'document_id': 44, + 'reservation_candidates': [ + {'value': value, 'evidence': { + 'table_index': None, 'row_index': index + 1, 'column_index': None, + 'cell_id': f'reservation-heuristic:hash:line{index + 1}', 'raw_value': value, + }} + for index, value in enumerate(candidates) + ], + **extra, + } + + +def _reservation_observation(order: dict): + """读取兜底写入的 reservation Observation;未写入返回 None。""" + for line in order['lines']: + for field in line['fields']: + if field['field_id'] == 'reservation': + return field['observations'][0] + return None + + +# ---------------------------------------------------------------- 候选扫描 + +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_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') + 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_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', + ) + 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') + + +def test_labeled_context_helper_extracts_subject_po(): + """主题「RE_ WELLTRUST ACC PO 1000053337」的 PO 号可被标签助手提取。""" + assert reservation_ids_in_labeled_context('RE_ WELLTRUST ACC PO 1000053337.eml') == {'1000053337'} + + +# ---------------------------------------------------------------- 过滤裁决 + +def test_filter_returns_unique_ambiguous_none(): + """过滤器三态:唯一→unique 可自动采纳;多个→ambiguous;全排除→none。""" + candidates = [{'value': value} for value in ['4000122230', '1000053337']] + surviving, status = filter_reservation_heuristic_candidates( + candidates, excluded_values={'1000053337'}, + ) + assert status == 'unique' and surviving[0]['value'] == '4000122230' + surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=set()) + assert status == 'ambiguous' and len(surviving) == 2 + surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values={'1000053337', '4000122230'}) + assert status == 'none' and surviving == [] + + +# ---------------------------------------------------------------- 合并裁决 + +def test_merge_applies_unique_heuristic_candidate_to_lines(): + """唯一候选:低置信度写入缺失行;relation 标记 reservation_heuristic。""" + order = _order() + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: _supplement(['4000122230', '1000053337'])}, + schema_definition=SCHEMA, + ) + observation = _reservation_observation(merged[0]) + # 断言:候选中与已提取 PO 相同的 1000053337 被排除,唯一候选自动写入。 + assert observation is not None and observation['value'] == '4000122230' + # 断言:启发式语义可辨识——confidence 0.5 + basis 标记,供复核端标注与审计。 + assert observation['confidence'] == 0.5 + assert observation['email_supplement_evidence']['basis'] == 'bare_numeric_heuristic' + assert merged[0]['_hxops_email_supplement_relation'] == 'reservation_heuristic' + assert merged[0]['_hxops_reservation_heuristic']['status'] == 'applied' + + +def test_merge_excludes_po_number_missing_from_pdf_via_subject_label(): + """截图 1 修复路径:PDF 侧 PO 也解析失败时,主题标签排除 PO,仍唯一命中。""" + order = _order() + order['header_fields'] = [] + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: _supplement( + ['4000122230', '1000053337'], + email_subject='RE_ WELLTRUST ACC PO 1000053337.eml', + )}, + schema_definition=SCHEMA, + ) + observation = _reservation_observation(merged[0]) + # 断言:主题「PO 1000053337」触发的标签排除让 4000122230 成为唯一候选。 + assert observation is not None and observation['value'] == '4000122230' + + +def test_merge_ambiguous_candidates_become_review_conflict(): + """多候选:不自动挑值,转 supplement_field_conflict 由现有面板裁决。""" + order = _order() + order['header_fields'] = [] + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: _supplement(['4000122230', '5000122230'])}, + schema_definition=SCHEMA, + ) + # 断言:未写入任何 reservation,冲突与人工裁决标记就位。 + assert _reservation_observation(merged[0]) is None + assert merged[0]['_hxops_reservation_heuristic']['status'] == 'ambiguous' + conflicts = [item for item in merged[0]['conflicts'] if item.get('field') == 'reservation_id'] + assert len(conflicts) == 1 + conflict = conflicts[0] + # 断言:复用现有冲突结构(reason/阻塞级别/header 作用域),候选值与逐候选证据齐全。 + assert conflict['reason'] == 'supplement_field_conflict' + assert conflict['severity'] == 'blocking' + assert conflict['scope'] == 'header' + assert conflict['values'] == ['4000122230', '5000122230'] + assert all(source['source_type'] == 'email_body' for source in conflict['sources']) + + +def test_merge_never_overwrites_existing_reservation(): + """已有合法预约单号(含邮件补充表正常解析出的值)时兜底绝不写入。""" + order = _order() + order['lines'][0]['fields'].append( + {'field_id': 'reservation', 'observations': [{'value': '3000099143'}]}, + ) + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: _supplement(['4000122230'])}, + schema_definition=SCHEMA, + ) + # 断言:原值保持不变,无启发式标记与 relation 变更。 + assert _reservation_observation(merged[0])['value'] == '3000099143' + assert '_hxops_reservation_heuristic' not in merged[0] + assert '_hxops_email_supplement_relation' not in merged[0] + + +def test_merge_never_overwrites_invalid_format_reservation_raw_value(): + """行上已有非法格式预约单号原值(如字母型编号)时同样不覆盖,交人工纠错。""" + order = _order() + order['lines'][0]['fields'].append( + {'field_id': 'reservation', 'observations': [{'value': 'RSV-88'}]}, + ) + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: _supplement(['4000122230'])}, + schema_definition=SCHEMA, + ) + # 断言:非法原值虽不通过 5/10 位校验,仍属已有业务事实,兜底跳过。 + assert _reservation_observation(merged[0])['value'] == 'RSV-88' + assert '_hxops_reservation_heuristic' not in merged[0] + + +def test_merge_excludes_qty_and_row_values_from_candidates(): + """数量 39739 与补充行已提取值都参与排除,防止把业务数值误当预约单号。""" + order = _order() + order['lines'][0]['fields'][1]['observations'][0]['value'] = 39739 + supplement = _supplement(['39739']) + supplement['rows'] = [{'customer_po_number': '1000053337'}] + order['header_fields'] = [] + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: supplement}, + schema_definition=SCHEMA, + ) + # 断言:候选恰为行数量值 → 排除后 none:无注入、无标记。 + assert _reservation_observation(merged[0]) is None + assert '_hxops_reservation_heuristic' not in merged[0] + + +def test_merge_unique_claim_not_reused_across_orders(): + """同 Intake 多订单共享候选:先到先得,第二个订单不得重复占用同一候选。""" + first = _order() + second = _order() + second['lines'][0]['fields'][0]['observations'][0]['value'] = 'D4-A08AR12000002' + merged = merge_email_supplements( + orders=[first, second], + supplements_by_intake={1: _supplement(['4000122230'])}, + schema_definition=SCHEMA, + ) + # 断言:第一个订单占用后 claimed 生效,第二个订单无候选可用且不产生标记。 + assert _reservation_observation(merged[0])['value'] == '4000122230' + assert _reservation_observation(merged[1]) is None + assert '_hxops_reservation_heuristic' not in merged[1] + + +def test_merge_skips_when_schema_lacks_reservation_field(): + """Schema 未配置 reservation_id 时兜底整体跳过,不误建字段。""" + schema = {'fields': [item for item in SCHEMA['fields'] if item.get('field_code') != 'reservation_id']} + order = _order() + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: _supplement(['4000122230'])}, + schema_definition=schema, + ) + assert _reservation_observation(merged[0]) is None + assert '_hxops_reservation_heuristic' not in merged[0] + + +def test_merge_writes_header_scope_reservation_when_schema_declares_header(): + """Schema 声明 header 作用域预约单号时,唯一候选写入订单头默认值。""" + order = _order() + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: _supplement(['4000122230', '1000053337'])}, + schema_definition=HEADER_RESERVATION_SCHEMA, + ) + header_field = next( + item for item in merged[0]['header_fields'] if item['field_id'] == 'reservation' + ) + # 断言:header 作用域配置下候选写入 header_fields(effective = line ?? header 的头侧默认值)。 + assert header_field['observations'][0]['value'] == '4000122230' + assert merged[0]['_hxops_reservation_heuristic']['status'] == 'applied' + + +def test_merge_without_candidates_key_is_noop(): + """旧 Run 补充快照无 reservation_candidates 键:兜底静默跳过,行为不变。""" + order = _order() + supplement = _supplement([]) + supplement.pop('reservation_candidates') + merged = merge_email_supplements( + orders=[order], + supplements_by_intake={1: supplement}, + schema_definition=SCHEMA, + ) + assert _reservation_observation(merged[0]) is None + assert '_hxops_reservation_heuristic' not in merged[0] diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts index 78704e4f..c1caf135 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts @@ -408,6 +408,56 @@ describe('useShippingOrderReview build eligibility writes', () => { }); + it('records the auto-selected Case when a deep link carries only run_no (formal downstream)', async () => { + + // 用户场景:历史记录等入口以 run_no 直链进入(URL 无 case_no/task_no),且唯一 + // 文件已确认建单、处于正式下游阶段(选法 2 不拉 Case 快照)。 + // 关键断言:自动选中的 CASE-1 必须落入 requestedCaseNo,否则 displayCase/ + // activeReviewNavItem 无身份 → 任务详情不加载 → 五阶段页签全锁死 + 标题「未命名」。 + + api.getRun.mockResolvedValue({ + + run_no: 'RUN-1', + + items: [{ + + case_no: 'CASE-1', document_id: 1, file_name: 'po.pdf', status: 'confirmed', + + has_formal_ot: true, lifecycle_stage: 'freight_upload', confirmed_task_no: 'OT-1', + + }], + + }); + + api.getQueue.mockResolvedValue({ + + summary: { total: 1, needs_action: 0, processing: 0, completed: 1 }, + + items: [{ + + case_no: 'CASE-1', source_run_no: 'RUN-1', document_id: 1, file_name: 'po.pdf', + + status: 'confirmed', has_formal_ot: true, lifecycle_stage: 'freight_upload', + + confirmed_task_no: 'OT-1', issue_count: 0, available_actions: [], + + }], + + }); + + const review = useShippingOrderReview(); + + await review.load('RUN-1'); + + expect(review.requestedCaseNo.value).toBe('CASE-1'); + + // 选法 2:正式下游仍不得拉取 Case 快照。 + + expect(api.getCase).not.toHaveBeenCalled(); + + }); + + it('does not prefetch PDF preview on load or selectCase; ensurePreviewLoaded fetches on demand', async () => { // 关键断言:进入工作台/切换文档不触发 preview 审计与下载。 const review = useShippingOrderReview(); diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts index a879ed9a..51fe3b31 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts @@ -1156,6 +1156,10 @@ export function useShippingOrderReview(options: { if (generation !== caseLoadGeneration) return; // [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。 const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no; + // [深链自愈] 历史记录切换等入口可能只带 run_no 进入(URL 无 case_no/task_no); + // 自动选中的 Case 必须回写 requestedCaseNo,否则正式下游(选法 2 不拉 Case)下 + // displayCase/activeReviewNavItem 无身份,任务详情不加载、五阶段页签全锁死。 + if (!preferredCaseNo) requestedCaseNo.value = caseNo || null; // [选法 2] 正式任务下游阶段(通知准备/货代上传/通知完成)本阶段不拉复核编辑器 // (Case 快照 + Evidence),改由任务详情 + 统一投影驱动;进入「订单复核」才补拉。 const navItem = (queue.items || run.items).find( diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts index f4c70d99..b21de571 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts @@ -945,6 +945,23 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect((wrapper.vm as any).$route.query.case_no).toBe('CASE-NEW'); }); + it('falls back to the requested Case identity for the header order summary on run_no-only deep links', async () => { + // 用户场景:历史记录切换生成的深链只带 mode+run_no(无 case_no/task_no)。 + // 关键断言:标题订单摘要按 displayCase 身份(requestedCaseNo)匹配队列项, + // 展示文件名与 Case 号;不得因 URL 缺 case 参数而退化为「未命名」。 + const previousRequestedCaseNo = requestedCaseNo.value; + requestedCaseNo.value = 'CASE-1'; + try { + const wrapper = await mountView(); + const summary = wrapper.find('[data-testid="review-selected-order-summary"]'); + expect(summary.exists()).toBe(true); + expect(summary.text()).toContain('po.pdf'); + expect(summary.text()).toContain('CASE-1'); + } finally { + requestedCaseNo.value = previousRequestedCaseNo; + } + }); + it('opens the replacement Case at its backend current stage after reparse completes', async () => { const originalQueue = reviewQueue.value; try { diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.vue b/frontend/src/features/chat/views/ShippingOrderReviewView.vue index da9f1948..52739b99 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.vue +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.vue @@ -2301,8 +2301,11 @@ const processDetailPoNumber = computed(() => { * 改源到任务级」计划(E)一并收敛。 */ const selectedOrderSummary = computed(() => { + // 深链可能只带 run_no(历史记录切换等入口);此时 Case 身份在 requestedCaseNo → + // displayCase 上,必须优先按当前工作面身份匹配队列项,不能因 URL 缺 case 而显示「未命名」。 const activeNo = String( - route.query.case || route.query.case_no + displayCase.value?.case_no + || route.query.case || route.query.case_no || '', ).trim(); const item = reviewQueue.value?.items?.find((candidate) => candidate.case_no === activeNo) From 5f9df244c0b328e929722922065c3a15b3bac4d4 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 14 Oct 2026 22:40:37 +0800 Subject: [PATCH 02/10] =?UTF-8?q?fix(shipping-notice):=20=E6=8A=BD?= =?UTF-8?q?=E5=8F=96=E6=94=B6=E5=8F=A3=E7=BA=A0=E6=AD=A3=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E6=96=87=E6=A1=A3=E7=8A=B6=E6=80=81=E5=B9=B6=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=20OCR=20=E6=95=91=E6=8F=B4=E8=B5=84=E4=BA=A7=E8=AF=BB=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 抽取收口读取 Run 内 Unit 级失败事实:全部 Unit 失败的附件不再按零 pending 误写 completed - EML 父项跟随 Run 结果收敛:终态 Run 禁止停留「处理中」,运行中仅区分解析失败与处理中 - OCR 救援资产读取修复:read_asset_bytes 接收 id 时按 FileAsset 加载字节,传参口径纠正 - 同步抽取/投影测试并新增工作台投影测试 --- .../order_profile_ocr_rescue.py | 41 +++++-- .../shipping_notice/order_extraction.py | 108 +++++++++++++++--- .../order_extraction_workspace_projection.py | 16 ++- .../shipping_processing_projection.py | 53 +++++++-- ...t_order_extraction_workspace_projection.py | 85 ++++++++++++++ .../tests/test_order_profile_ocr_rescue.py | 73 ++++++++++++ .../test_shipping_notice_order_extraction.py | 67 +++++++++++ ...t_shipping_processing_projection_stage4.py | 76 ++++++++++-- 8 files changed, 480 insertions(+), 39 deletions(-) create mode 100644 backend/tests/test_order_extraction_workspace_projection.py diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py b/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py index 4479dbae..de9e6ea3 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py @@ -17,6 +17,7 @@ backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py from __future__ import annotations +import logging import unicodedata from typing import Any, Callable @@ -38,6 +39,8 @@ from app.services.shipping_notice.document_layout.order_profile import ( OrderCoordinateProfile, ) +logger = logging.getLogger(__name__) + # 与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐;低于该置信度的 OCR 行不参与补洞。 OCR_RESCUE_CONFIDENCE_FLOOR = 0.8 # 表头带高度占主表高度的比例,与 _observe_header_candidates 的保守带一致。 @@ -194,6 +197,18 @@ def _text_to_char_glyphs(text: str, bbox: dict[str, float]) -> list[dict[str, An return out +def _default_read_asset_bytes(asset_id: int) -> bytes: + """按 id 加载 FileAsset 后读取字节;read_asset_bytes 接收 ORM 对象而非 id。""" + from app.extensions import db + from app.models import FileAsset + from app.services.file_assets.service import read_asset_bytes + + asset = db.session.get(FileAsset, int(asset_id)) + if asset is None: + raise LookupError(f'file asset not found: {asset_id}') + return read_asset_bytes(asset) + + def _collect_rescue_glyphs( *, document: Any, @@ -213,6 +228,8 @@ def _collect_rescue_glyphs( page_width = float(page.get('width') or 0) page_height = float(page.get('height') or 0) asset_id = int(getattr(document, 'asset_id', 0) or 0) + if read_asset_fn is None: + read_asset_fn = _default_read_asset_bytes # [STEP 1] AcroForm/XFA 控件文本:确定性坐标与文本,优先于 OCR。 if asset_id > 0: try: @@ -247,9 +264,6 @@ def _collect_rescue_glyphs( if asset_id <= 0: return None try: - if read_asset_fn is None: - from app.services.file_assets.service import read_asset_bytes - read_asset_fn = read_asset_bytes if page_images_fn is None: from app.services.shipping_notice.document_layout.native_pdf import ( extract_native_pdf_pages, @@ -296,7 +310,15 @@ def _collect_rescue_glyphs( if band: return band, 'ocr_coordinate' return None - except (ValueError, TypeError, KeyError, OSError): + except Exception as exc: # noqa: BLE001 - 兜底来源失败时交回上层维持原判 + # [PARAM_TUNING] 2026-10-14 test 事故(SNER-20261014-8EBAB7A1):AttributeError + # 炸穿本层令整个 Unit 技术失败。收口语义保持「静默回退」,但必须留观测痕 + # 迹,否则只能靠 Unit error_message 反推。 + logger.warning( + 'order profile rescue glyphs failed document_id=%s error_type=%s', + int(getattr(document, 'id', 0) or 0), + type(exc).__name__, + ) return None @@ -341,9 +363,6 @@ def rescue_match_with_header_ocr( page = pages.get('1') or pages.get(1) if not isinstance(page, dict): return match - if read_asset_fn is None: - from app.services.file_assets.service import read_asset_bytes - read_asset_fn = read_asset_bytes _, _, probe_observed = _candidate_header_atoms( raw_profile=next(iter(eligible.values()))[1], layout=layout, @@ -390,6 +409,10 @@ def rescue_match_with_header_ocr( 'identity_rescue_source': rescue_source, 'candidates': marked_candidates, }) - except (ValueError, TypeError, KeyError, OSError): - # 补救属锦上添花:任何数据/环境异常都回退原判,不阻断主链。 + except Exception as exc: # noqa: BLE001 - 补救属锦上添花:任何异常(含 AttributeError 等未预期类型错误)都回退原判,不得阻断抽取主链。 + logger.warning( + 'order profile rescue aborted document_id=%s error_type=%s', + int(getattr(document, 'id', 0) or 0), + type(exc).__name__, + ) return match diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 045ec50b..50f56a64 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -311,6 +311,51 @@ def _resolve_automatic_acceptance(raw_order: dict[str, Any]) -> dict[str, str] | return dict(_AUTOMATIC_ACCEPTANCE_BY_MARKER[marker]) if marker in _AUTOMATIC_ACCEPTANCE_BY_MARKER else None +def _failed_unit_errors_by_document(run_id: int | None) -> dict[int, dict[str, str | None]]: + """ + 读取 Run 内 Unit 级失败事实(document_id → 错误码/消息),供收口裁决纠正文档级状态。 + + 核心逻辑:persist 的候选裁决只知道「有没有 pending」,不知道 Unit 是否技术失败; + Unit 全失败的附件没有任何产出裁决,禁止按零 pending 误写 completed + (回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed,批次中心误报通知完成)。 + + Args: + run_id: ShippingOrderProcessingRun 主键;为空时返回空表(领域单测路径)。 + + Returns: + document_id → {'error_code', 'error_message'} 映射。 + """ + if run_id is None: + return {} + from app.models import ShippingOrderProcessingPlan, ShippingOrderProcessingUnit + + rows = ( + db.session.query( + ShippingOrderProcessingUnit.document_id, + ShippingOrderProcessingUnit.error_code, + ShippingOrderProcessingUnit.error_message, + ) + .join( + ShippingOrderProcessingPlan, + ShippingOrderProcessingPlan.id == ShippingOrderProcessingUnit.plan_id, + ) + .filter( + ShippingOrderProcessingPlan.run_id == int(run_id), + ShippingOrderProcessingUnit.status == 'failed', + ShippingOrderProcessingUnit.document_id.isnot(None), + ) + .all() + ) + return { + int(document_id): { + 'error_code': str(error_code or '').strip() or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED', + 'error_message': str(error_message or '').strip() or 'Order extraction unit failed', + } + for document_id, error_code, error_message in rows + if document_id is not None + } + + def persist_order_extraction_result( *, session: ChatSession, @@ -794,21 +839,31 @@ def persist_order_extraction_result( # [STEP 2] 聚合 Document 结果;无法归属到 Intake 的异常项会使本轮全部 Document 保持部分完成。 has_unassigned_pending = any(not item.get('source_intake_no') for item in pending) + # Unit 失败事实优先:Unit 失败且无候选/待处理裁决的附件,识别并未完成, + # 必须落 failed(携带 Unit 错误码),禁止按「零 pending」误写 completed—— + # 否则随后的 Run 失败收口会因「已是终态」跳过回填,批次中心误报已完成。 + failed_unit_error_by_document = _failed_unit_errors_by_document(run_id) for document in documents: keys = document_candidate_keys[int(document.id)] - document.order_extraction_status = ( - 'partially_completed' - if document_has_pending[int(document.id)] or has_unassigned_pending - else 'completed' - ) + unit_failure = failed_unit_error_by_document.get(int(document.id)) + if unit_failure and not keys and not document_has_pending[int(document.id)]: + document.order_extraction_status = 'failed' + document.order_extraction_error_code = unit_failure['error_code'] + document.order_extraction_error_message = unit_failure['error_message'] + else: + document.order_extraction_status = ( + 'partially_completed' + if document_has_pending[int(document.id)] or has_unassigned_pending + else 'completed' + ) + document.order_extraction_error_code = None + document.order_extraction_error_message = None document.order_extraction_source = extraction_source document.order_extraction_result_json = { 'request_id': request_id, 'candidate_keys': keys, 'non_shipping_order_indexes': document_non_shipping_indexes[int(document.id)], } - document.order_extraction_error_code = None - document.order_extraction_error_message = None # [STEP 3] 只对本次 documents 作用域内消失的 Candidate 做版本失效。 # Unit 增量提交仅带当前 PDF,禁止把同 Intake/Run 的兄弟 PDF Candidate @@ -836,13 +891,32 @@ def persist_order_extraction_result( duplicate_results_by_intake.get(int(intake.id), []), ) apply_duplicate_result_to_intake(intake, aggregate) - intake.order_extraction_status = ( - 'partially_completed' - if pending_by_intake[int(intake.id)] or has_unassigned_pending - else 'completed' + # Intake 聚合文档级终态:全部业务附件 failed → failed;部分失败 → partially_completed; + # 二者都不得被后续「零 pending 即 completed」的收口覆盖。 + intake_documents = documents_by_intake.get(int(intake.id)) or [] + failed_intake_documents = [ + document + for document in intake_documents + if str(document.order_extraction_status or '').strip().lower() == 'failed' + ] + business_document_count = sum( + 1 + for document in intake_documents + if str(document.document_type or '').strip().lower() != 'email_body' ) - intake.order_extraction_error_code = None - intake.order_extraction_error_message = None + if failed_intake_documents and business_document_count > 0 \ + and len(failed_intake_documents) >= business_document_count: + intake.order_extraction_status = 'failed' + intake.order_extraction_error_code = failed_intake_documents[0].order_extraction_error_code + intake.order_extraction_error_message = failed_intake_documents[0].order_extraction_error_message + elif failed_intake_documents or pending_by_intake[int(intake.id)] or has_unassigned_pending: + intake.order_extraction_status = 'partially_completed' + intake.order_extraction_error_code = None + intake.order_extraction_error_message = None + else: + intake.order_extraction_status = 'completed' + intake.order_extraction_error_code = None + intake.order_extraction_error_message = None intake.updated_at = datetime.utcnow() db.session.flush() @@ -1001,7 +1075,13 @@ def persist_order_extraction_result( for intake in intakes: intake.parse_status = 'consumed' intake.consumed_at = now - intake.order_extraction_status = 'completed' + # consumed 仅代表「邮件解析结果已被抽取收口消费」;文档/Intake 级 + # order_extraction_status 若已按 Unit 失败裁决为 failed/partially_completed, + # 不得在此覆盖回 completed——否则 Run 失败收口会因「已是终态」跳过回填。 + if str(intake.order_extraction_status or '').strip().lower() not in { + 'failed', 'partially_completed', + }: + intake.order_extraction_status = 'completed' intake.updated_at = now db.session.commit() diff --git a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py index 6a6b6b50..c2b100e3 100644 --- a/backend/app/services/shipping_notice/order_extraction_workspace_projection.py +++ b/backend/app/services/shipping_notice/order_extraction_workspace_projection.py @@ -498,7 +498,21 @@ def _email_parent_rows( if document_id <= 0 or document_id in existing_document_ids: continue parse_status = parse_statuses.get(intake_id, '') - parent_status = 'failed' if parse_status == 'parse_failed' else 'processing' + run_status = str(run.status or '').strip().lower() + if run_status in {'queued', 'processing'}: + # 运行中的 Run:EML 父项只区分解析失败与处理中。 + parent_status = 'failed' if parse_status == 'parse_failed' else 'processing' + else: + # [STEP] 终态 Run 的 EML 父项必须跟随 Run 结果收敛,禁止停留在「处理中」 + # (历史缺陷:全部 Unit 失败后父项仍显示处理中,误导用户批次仍在进行)。 + # partially_completed 的用户语义与 review_required 一致(需人工处理)。 + parent_status = { + 'failed': 'failed', + 'cancelled': 'cancelled', + 'completed': 'completed', + 'review_required': 'review_required', + 'partially_completed': 'review_required', + }.get(run_status, 'failed') rows.append({ 'unit_id': -document_id, 'document_id': document_id, diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index bf5cf5c8..ca0b597f 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -4263,14 +4263,17 @@ def project_conversation_processing_summary( if case.run_id is not None ) # 订单抽取失败且尚无 Candidate/Case/OT 时,仍需最新 Run 身份供重解析; - # 仅 load id/run_no,不触碰 Plan/Unit。 + # 仅 load id/run_no/status/error_code,不触碰 Plan/Unit。status/error_code + # 供摘要把「抽取收口 completed 但最新 Run 失败」的文档纠正为失败裁决。 latest_run_by_intake_id: dict[int, Any] = {} if intake_ids: - for intake_id, run_id, run_no in ( + for intake_id, run_id, run_no, run_status, run_error_code in ( db.session.query( ShippingOrderProcessingRunIntake.intake_id, ShippingOrderProcessingRun.id, ShippingOrderProcessingRun.run_no, + ShippingOrderProcessingRun.status, + ShippingOrderProcessingRun.error_code, ) .join( ShippingOrderProcessingRun, @@ -4287,7 +4290,12 @@ def project_conversation_processing_summary( key = int(intake_id) if key in latest_run_by_intake_id: continue - latest_run_by_intake_id[key] = {'id': int(run_id), 'run_no': str(run_no or '').strip()} + latest_run_by_intake_id[key] = { + 'id': int(run_id), + 'run_no': str(run_no or '').strip(), + 'status': str(run_status or '').strip().lower(), + 'error_code': str(run_error_code or '').strip() or None, + } run_ids.add(int(run_id)) runs_by_id = { int(run.id): run @@ -4455,7 +4463,25 @@ def project_conversation_processing_summary( if raw in {'review_required', 'waiting_review', 'pending_review', 'waiting_human'}: return 'waiting_human', 'waiting_review' if stage == 'candidate_creating' else stage, 'waiting_review' if raw in {'completed', 'uploaded'}: - return 'completed', 'completed', None + # 文档级 completed 只代表「抽取收口完成」,不是业务终态:通知完成必须 + # 以正式 OT/Notice/上传核验为前提,禁止把收口语义译成通知完成 + # (回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed, + # 批次中心据此误报 9/9 已完成 + 通知完成)。 + if task is not None: + return 'completed', 'completed', None + if case is not None and case_status == 'non_order': + # 非订单处置是唯一无 OT 的合法业务完成出口。 + return 'completed', 'completed', None + latest_intake_run = latest_run_by_intake_id.get(int(document.intake_id)) or {} + if str(latest_intake_run.get('status') or '').strip().lower() == 'failed': + # 收口 completed 但最新 Run 失败(含历史脏数据):按失败裁决并提供重解析。 + return ( + 'failed', + stage, + str(latest_intake_run.get('error_code') or '') or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED', + ) + # 无 OT/无处置的收口完成与全量视图同判词:停接收解析(处理中)。 + return 'running', stage, None if raw in {'cancelled', 'archived'}: return raw, raw, None return 'running', stage, None @@ -4499,9 +4525,22 @@ def project_conversation_processing_summary( stage = 'candidate_creating' case_status = str(getattr(case, 'status', None) or '').strip().lower() terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'} - extraction_failed = str(document.order_extraction_status or '').strip().lower() in { - 'failed', 'parse_failed', 'technical_retrying', - } + # 抽取失败事实除文档级状态外,还认「无 OT/无 Case 且最新 Run 失败」: + # 历史/并发脏数据可能把 Unit 全失败的附件写成 completed(抽取收口语义), + # 此时仍必须下发重解析入口,与 _status 的失败裁决同源。 + latest_intake_run_status = str( + (latest_run_by_intake_id.get(int(document.intake_id)) or {}).get('status') or '' + ).strip().lower() + extraction_failed = ( + str(document.order_extraction_status or '').strip().lower() in { + 'failed', 'parse_failed', 'technical_retrying', + } + or ( + task is None + and case is None + and latest_intake_run_status == 'failed' + ) + ) task_no = str(task.task_no).strip() if task is not None else None available_actions: list[str] = [] primary_action: dict[str, Any] | None = None diff --git a/backend/tests/test_order_extraction_workspace_projection.py b/backend/tests/test_order_extraction_workspace_projection.py new file mode 100644 index 00000000..d4ef55cd --- /dev/null +++ b/backend/tests/test_order_extraction_workspace_projection.py @@ -0,0 +1,85 @@ +""" +tests/test_order_extraction_workspace_projection.py + +用途:锁定工作台投影中 EML 父项状态的收敛契约。 +依赖:order_extraction_workspace_projection._email_parent_rows。 +逻辑:pure_unit;运行中的 Run(queued/processing)EML 父项维持既有口径 + (parse_failed → failed,否则 processing);终态 Run 的 EML 父项必须跟随 + Run 结果收敛(failed/cancelled/completed/review_required),禁止停留在 + 「处理中」——历史缺陷:全部 Unit 失败后父项仍显示处理中。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from app.services.shipping_notice.order_extraction_workspace_projection import ( + _email_parent_rows, +) + +pytestmark = pytest.mark.pure_unit + + +def _run_stub(status: str, parse_status: str | None = 'parsed') -> SimpleNamespace: + return SimpleNamespace( + status=status, + finished_at=None, + input_snapshot_json={'intakes': [{'intake_id': 1, 'parse_status': parse_status}]}, + ) + + +def _documents() -> dict[int, dict]: + return { + 906: {'document_id': 906, 'intake_id': 1, 'document_type': 'email_body', 'file_name': 'batch.eml'}, + } + + +def test_queued_run_email_parent_stays_processing(): + """运行中(queued)且未解析失败:EML 父项维持「处理中」(既有口径零变化)。""" + rows = _email_parent_rows( + run=_run_stub('queued'), + documents=_documents(), + existing_document_ids=set(), + ) + # 关键断言:queued 运行下父项 processing,阶段为邮件解析 + assert rows[0]['status'] == 'processing' + assert rows[0]['user_visible_stage'] == 'email_parsing' + + +def test_failed_run_email_parent_converges_to_failed(): + """终态 failed 的 Run:EML 父项必须收敛为 failed,不得停留「处理中」。""" + rows = _email_parent_rows( + run=_run_stub('failed', parse_status=None), + documents=_documents(), + existing_document_ids=set(), + ) + # 关键断言:冻结 parse_status 为 None(消费型 Intake)时,failed Run 的父项 + # 曾无条件渲染 processing;现在必须跟随 Run 结果收敛 + assert rows[0]['status'] == 'failed' + assert rows[0]['user_visible_stage'] == 'failed' + + +def test_review_required_run_email_parent_converges_to_review(): + """终态 review_required / partially_completed:父项收敛为需人工复核语义。""" + for status in ('review_required', 'partially_completed'): + rows = _email_parent_rows( + run=_run_stub(status), + documents=_documents(), + existing_document_ids=set(), + ) + # 关键断言:两种终态都投影为 review_required(partially_completed 同义) + assert rows[0]['status'] == 'review_required', status + + +def test_parse_failed_intake_parent_stays_failed_under_active_run(): + """运行中但冻结 parse_status=parse_failed:父项仍为 failed(既有口径零变化)。""" + rows = _email_parent_rows( + run=_run_stub('processing', parse_status='parse_failed'), + documents=_documents(), + existing_document_ids=set(), + ) + # 关键断言:解析失败优先于处理中,技术失败原因码保留 + assert rows[0]['status'] == 'failed' + assert rows[0]['technical_failure_reason_code'] == 'intake_parse_failed' diff --git a/backend/tests/test_order_profile_ocr_rescue.py b/backend/tests/test_order_profile_ocr_rescue.py index e00377cd..7615ae85 100644 --- a/backend/tests/test_order_profile_ocr_rescue.py +++ b/backend/tests/test_order_profile_ocr_rescue.py @@ -316,6 +316,33 @@ def test_rescue_prefers_acroform_widgets_over_ocr(monkeypatch): assert result.status == 'unique_match' +def test_rescue_never_leaks_asset_read_errors(monkeypatch): + """资产读取抛 AttributeError(test 环境真实故障:int 传入 read_asset_bytes 访问 + .deleted_at)必须被收口为维持原判,不得炸穿抽取 Unit。""" + match = _drift_match([ + _candidate(V2_CODE, ['profile_header_discriminator_conflict']), + _candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']), + ]) + _patch_atoms(monkeypatch, { + V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}), + OTHER_CODE: ({'a', 'b'}, {'a'}), + }) + + def broken_read_asset(asset_id): + raise AttributeError("'int' object has no attribute 'deleted_at'") + + result = rescue_match_with_header_ocr( + match=match, profiles=_profiles(), layout=_layout(), header_to_field=None, + document=SimpleNamespace(asset_id=7), + match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')), + page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')), + ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')), + read_asset_fn=broken_read_asset, + ) + # 关键断言:补洞证据读取的任意异常都收口为原判返回 + assert result is match + + def test_rescue_skipped_for_non_failed_status(): """常规匹配已成功(如 unique_match)时绝不触发证据补洞。""" match = ProfileMatchResult( @@ -331,3 +358,49 @@ def test_rescue_skipped_for_non_failed_status(): read_asset_fn=lambda asset_id: (_ for _ in ()).throw(AssertionError('asset must not run')), ) assert result is match + + +def test_default_read_asset_loads_orm_before_read_asset_bytes(monkeypatch): + """默认资产读取必须先加载 FileAsset ORM 再交给 read_asset_bytes。 + + 回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——默认接线曾把 + document.asset_id(int)直接传给 read_asset_bytes,第一行访问 + ``asset.deleted_at`` 即抛 AttributeError,炸穿补救层令整个抽取 Unit + 技术失败。本测试锁定默认接线契约:read_asset_bytes 只接收 ORM 对象。 + """ + from types import SimpleNamespace as NS + + import app.extensions as extensions + import app.services.file_assets.service as asset_service + from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import ( + _default_read_asset_bytes, + ) + + received_objects: list[object] = [] + + def fake_read_asset_bytes(asset): + received_objects.append(asset) + return b'%PDF-default-wired' + + fake_asset = NS(id=7, deleted_at=None) + + class FakeSession: + def get(self, model, asset_id): + assert model is not int and asset_id == 7 + return fake_asset + + monkeypatch.setattr(asset_service, 'read_asset_bytes', fake_read_asset_bytes) + monkeypatch.setattr(extensions, 'db', NS(session=FakeSession())) + + # 关键断言 1:默认接线按 id 取 ORM,read_asset_bytes 收到对象而非 int。 + assert _default_read_asset_bytes(7) == b'%PDF-default-wired' + assert received_objects == [fake_asset] + + # 关键断言 2:资产不存在时抛 LookupError(可被补救层收口为原判)。 + class MissingSession: + def get(self, model, asset_id): + return None + + monkeypatch.setattr(extensions, 'db', NS(session=MissingSession())) + with pytest.raises(LookupError): + _default_read_asset_bytes(404) diff --git a/backend/tests/test_shipping_notice_order_extraction.py b/backend/tests/test_shipping_notice_order_extraction.py index 116fb61e..9859d728 100644 --- a/backend/tests/test_shipping_notice_order_extraction.py +++ b/backend/tests/test_shipping_notice_order_extraction.py @@ -1697,3 +1697,70 @@ def test_merge_chat_log_payload_requires_exact_turn_ownership(app): 'existing_key': 'kept', 'shipping_order_extraction_state': {'status': 'completed'}, } + + +def test_persist_close_out_marks_failed_units_failed_not_completed(app): + """Unit 全失败的空结果收口必须写 failed,禁止把附件误标为识别完成。 + + 回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——persist 在 orders=[] + 时按「零 pending」把附件 order_extraction_status 写成 completed;随后的 + Run 失败收口因「已是 completed 终态」跳过回填,批次进度中心据此把整批 + 误报为已完成/通知完成。 + """ + with app.app_context(): + user, session, intake, document, _runtime_context = _seed_extraction_input() + schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one() + agent = Agent.query.filter_by(agent_code='shipping_notice').one() + run = ShippingOrderProcessingRun( + run_no='SNER-FAILED-UNITS-CLOSE-OUT', + user_id=int(user.id), + owner_agent_id=int(agent.id), + conversation_id=session.session_id, + schema_version_id=int(schema.id), + input_snapshot_hash='failed-units-close-out-snapshot', + input_snapshot_json={}, + idempotency_key='failed-units-close-out-run', + status='processing', + ) + plan = ShippingOrderProcessingPlan( + run=run, + plan_version='test.v1', + input_snapshot_hash=run.input_snapshot_hash, + unit_count=1, + ) + unit = ShippingOrderProcessingUnit( + plan=plan, + intake_id=int(intake.id), + document_id=int(document.id), + position=0, + unit_type='document_extraction', + document_type='attachment', + status='failed', + error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED', + error_message="'int' object has no attribute 'deleted_at'", + ) + db.session.add_all([run, plan, unit]) + db.session.commit() + + persist_order_extraction_result( + session=session, + intakes=[intake], + documents=[document], + current_snapshot='failed-units-close-out-snapshot', + request_id='SNER-FAILED-UNITS-CLOSE-OUT', + orders=[], + run_id=int(run.id), + schema_version_id=int(schema.id), + extraction_source='deterministic_order_parser', + auto_create_enabled=False, + ) + db.session.commit() + + db.session.refresh(document) + db.session.refresh(intake) + # 关键断言 1:Unit 失败且零候选裁决 → 文档必须落 failed 并携带 Unit 错误码。 + assert document.order_extraction_status == 'failed' + assert document.order_extraction_error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED' + # 关键断言 2:全部附件失败 → Intake 同步 failed;consumed 保留(孤儿重解析依赖)。 + assert intake.order_extraction_status == 'failed' + assert intake.parse_status == 'consumed' diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 2f9c362d..e7cca132 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -1504,15 +1504,20 @@ def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> None: - """混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。""" + """混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。 + + 回归语义(SNER-20261014-8EBAB7A1):无 OT 的文档级 completed 只是抽取收口, + 摘要不再译成业务已完成;混合场景改用 failed + processing 两类真实用户分组。 + """ with app.app_context(): from tests.test_shipping_order_extraction_runs import _seed_run_input - user, _agent, session, intake, completed_document = _seed_run_input( + user, _agent, session, intake, failed_document = _seed_run_input( suffix='SUMMARY-MIXED-EML-LEAF-STATUS', ) intake.source_type = 'eml' - completed_document.order_extraction_status = 'completed' + failed_document.order_extraction_status = 'failed' + failed_document.order_extraction_error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED' processing_document = ShippingOrderDocument( intake_id=intake.id, document_type='attachment', @@ -1531,17 +1536,17 @@ def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> Non conversation_id=session.session_id, )['conversation_processing'] - # 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在已完成容器。 + # 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在失败容器。 + failed_rows = projection['status_groups']['failed'] processing_rows = projection['status_groups']['processing'] - completed_rows = projection['status_groups']['completed'] assert [child['source_summary']['document_id'] for child in processing_rows[0]['aggregate_children']] == [ processing_document.id, ] - assert [child['source_summary']['document_id'] for child in completed_rows[0]['aggregate_children']] == [ - completed_document.id, + assert [child['source_summary']['document_id'] for child in failed_rows[0]['aggregate_children']] == [ + failed_document.id, ] assert projection['summary']['processing_files'] == 1 - assert projection['summary']['completed_files'] == 1 + assert projection['summary']['failed_files'] == 1 assert projection['summary']['total_files'] == 2 @@ -3423,3 +3428,58 @@ def test_unrecognized_plan_attachment_is_displayed_but_not_counted_as_recognized assert ((unrecognized[0].get('source_summary') or {}).get('filename')) == 'F92.pdf' # 已识别计数只认物化附件;未识别行不计入,从而「已识别 1/2」语义成立。 assert _batch_file_counts(merged)['total_files'] == 1 + + +def test_summary_failed_run_does_not_project_document_completed_as_upload_complete(app) -> None: + """Run 失败时文档级 completed(抽取收口语义)不得译成业务终态「通知完成」。 + + 回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——9 个 Unit 全部 + ORDER_EXTRACTION_UNIT_FAILED,persist 收口零 pending 仍把附件写成 + order_extraction_status='completed';首屏摘要 _status() 据此映射 + ('completed','completed'),批次进度中心误报 9/9 已完成 + 通知完成。 + """ + with app.app_context(): + from datetime import datetime + + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-CLOSEOUT-NOT-COMPLETE', + ) + intake.source_type = 'eml' + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + for unit in run.extraction_plan.units: + unit.status = 'failed' + unit.error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED' + run.status = 'failed' + run.phase = 'failed' + run.error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED' + # 脏数据形态:persist 收口已把文档/Intake 写成 completed(抽取收口 ≠ 业务完成)。 + document.order_extraction_status = 'completed' + intake.parse_status = 'consumed' + intake.consumed_at = datetime.utcnow() + intake.order_extraction_status = 'completed' + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + projection = payload['conversation_processing'] + leaf = next( + child + for rows in projection['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + if child['source_summary']['document_id'] == document.id + ) + + # 关键断言 1:无 OT/Notice 的文件不可能投影为「通知完成」。 + assert leaf['ui_state']['lifecycle_stage'] != 'upload_complete' + # 关键断言 2:失败文件不得计入批次已完成统计。 + assert projection['summary']['completed'] == 0 + # 关键断言 3:与全量视图同判词 —— 失败停接收解析,主动作是重解析。 + assert leaf['user_group'] == 'failed' + assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse' + assert leaf['ui_state']['primary_action']['code'] == 'reparse' From 2250ac98e6aa415edb00172d790bcf5bca4a01f1 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 14 Oct 2026 23:18:41 +0800 Subject: [PATCH 03/10] =?UTF-8?q?fix(shipping-notice):=20=E6=89=B9?= =?UTF-8?q?=E6=AC=A1=E6=8A=95=E5=BD=B1=E6=94=B6=E6=95=9B=E9=9C=80=E4=BA=BA?= =?UTF-8?q?=E5=B7=A5=E6=9C=AA=E7=89=A9=E5=8C=96=E8=AF=86=E5=88=AB=20Run=20?= =?UTF-8?q?=E5=B9=B6=E4=B8=8B=E5=8F=91=E9=87=8D=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 收口 completed 且最新 Run review_required、但未物化 Case/OT 的附件 (如 XFA 身份门禁在唯一命中后拒绝、候选从未创建)原先落入兜底 running,批次进度中心误显示「处理中」且无任何动作入口。 - 文档级裁决新增 review_required 无 Task/Case 分支:waiting_human + candidate_creating(回归 SNER-20261014-E27D657F) - 重解析入口与 failed 分支同源:无 OT/无 Case 且最新 Run 失败或 需人工,均下发 reparse 动作 --- .../shipping_processing_projection.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index ca0b597f..4018b62f 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -4473,13 +4473,19 @@ def project_conversation_processing_summary( # 非订单处置是唯一无 OT 的合法业务完成出口。 return 'completed', 'completed', None latest_intake_run = latest_run_by_intake_id.get(int(document.intake_id)) or {} - if str(latest_intake_run.get('status') or '').strip().lower() == 'failed': + latest_run_status = str(latest_intake_run.get('status') or '').strip().lower() + if latest_run_status == 'failed': # 收口 completed 但最新 Run 失败(含历史脏数据):按失败裁决并提供重解析。 return ( 'failed', stage, str(latest_intake_run.get('error_code') or '') or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED', ) + if latest_run_status == 'review_required' and task is None and case is None: + # 收口 completed 但最新 Run 需人工且未物化 Case/OT(如 XFA 身份门禁 + # 在命中后拒绝、候选从未创建):停「需处理」并下发重解析入口, + # 禁止落到处理中(回归 SNER-20261014-E27D657F)。 + return ('waiting_human', stage or 'candidate_creating', 'run_review_required') # 无 OT/无处置的收口完成与全量视图同判词:停接收解析(处理中)。 return 'running', stage, None if raw in {'cancelled', 'archived'}: @@ -4525,9 +4531,10 @@ def project_conversation_processing_summary( stage = 'candidate_creating' case_status = str(getattr(case, 'status', None) or '').strip().lower() terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'} - # 抽取失败事实除文档级状态外,还认「无 OT/无 Case 且最新 Run 失败」: - # 历史/并发脏数据可能把 Unit 全失败的附件写成 completed(抽取收口语义), - # 此时仍必须下发重解析入口,与 _status 的失败裁决同源。 + # 抽取需人工事实除文档级状态外,还认「无 OT/无 Case 且最新 Run 失败或需人工」: + # 历史/并发脏数据可能把 Unit 全失败的附件写成 completed(抽取收口语义); + # Run 收口 review_required 但未物化 Case/OT(XFA 门禁拒绝)同理, + # 此时仍必须下发重解析入口,与 _status 的裁决同源。 latest_intake_run_status = str( (latest_run_by_intake_id.get(int(document.intake_id)) or {}).get('status') or '' ).strip().lower() @@ -4538,7 +4545,7 @@ def project_conversation_processing_summary( or ( task is None and case is None - and latest_intake_run_status == 'failed' + and latest_intake_run_status in {'failed', 'review_required'} ) ) task_no = str(task.task_no).strip() if task is not None else None From 1a2753d3b5b186f6e6dbaa259d8a764f310c316b Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 15 Oct 2026 00:26:59 +0800 Subject: [PATCH 04/10] =?UTF-8?q?fix(shipping-notice):=20=E8=B0=83?= =?UTF-8?q?=E6=95=B4XFA=20=E8=BA=AB=E4=BB=BD=E6=8C=87=E7=BA=B9=E6=BC=82?= =?UTF-8?q?=E7=A7=BB=E9=99=8D=E7=BA=A7=E8=BD=AF=E9=97=A8=E7=A6=81=E5=B9=B6?= =?UTF-8?q?=E6=94=BE=E8=A1=8C=20datasets=20=E5=8F=96=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 供应商换代重导 XFA 表单必变 template 包指纹,原硬拦截使视觉已唯一 命中的单据永远停在无数据人工复核。 - 身份校验改为状态判定写入 decision.xfa_identity_state (matched/incomplete/mismatch),漂移仅记 fallback 码不拦截; - 放行后按模板既有 bindings 对新包 datasets 取值,仍强制 validate_xfa_extraction 业务交叉校验兜底; - 取值/业务校验失败时身份码前置转 Review,复核者可见漂移根因。 --- .../xfa_dataset.py | 31 ++++++++++++++++--- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py index 7f97af58..56e4a84e 100644 --- a/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py +++ b/backend/app/services/shipping_notice/order_profile_value_adapters/xfa_dataset.py @@ -1901,10 +1901,24 @@ def extract( live_fingerprint = live_fingerprint or signature.get('dataset_structure_fingerprint') source = selected.get('definition', {}).get('source_contract') if isinstance(selected.get('definition'), dict) else {} source = source if isinstance(source, dict) else {} + identity_state = 'matched' if not source.get('template_packet_checksum') or not source.get('dataset_structure_fingerprint'): - return review('xfa_profile_identity_incomplete') - if source.get('template_packet_checksum') != live_template or source.get('dataset_structure_fingerprint') != live_fingerprint: - return review('xfa_profile_identity_mismatch') + identity_state = 'incomplete' + elif ( + source.get('template_packet_checksum') != live_template + or source.get('dataset_structure_fingerprint') != live_fingerprint + ): + identity_state = 'mismatch' + # [SOFT GATE] XFA 身份指纹漂移不再硬拦截(回归 SNER-20261014-35E35017:供应商 + # 换代必变指纹,硬拦截使 XFA 单据永远空转人工)。视觉 Route 已唯一命中,datasets + # 取值后仍有 validate_xfa_extraction 业务交叉校验兜底;漂移降级为决策留痕 + # (xfa_identity_state)+ fallback 码,仅当取值/校验失败时与业务原因码一起转 Review。 + decision['xfa_identity_state'] = identity_state + if identity_state != 'matched': + decision['fallback_reason_codes'] = [ + *(decision.get('fallback_reason_codes') or []), + f'xfa_profile_identity_{identity_state}', + ] table_id = workflow._profile_visual_main_table_id(selected, document.get('layout_snapshot') or {}) if not table_id: return review('xfa_visual_main_table_missing') @@ -1947,7 +1961,11 @@ def extract( # 审计故障不能篡改已冻结的取值/Review 裁决。 pass if extraction.status != 'parsed' or extraction.reason_codes: - return review(*(list(extraction.reason_codes or []) or ['xfa_required_field_missing'])) + codes = list(extraction.reason_codes or []) or ['xfa_required_field_missing'] + if identity_state != 'matched': + # 漂移被软门禁放行后取值仍失败:身份码前置,让复核者看到根因。 + codes = [f'xfa_profile_identity_{identity_state}', *codes] + return review(*codes) validation = validate_xfa_extraction( raw_profile=selected, dataset_analysis=outcome.dataset_analysis, extraction=extraction, pdf_bytes=pdf_bytes, ) @@ -1960,7 +1978,10 @@ def extract( 'profile_checksum': str(selected.get('checksum') or ''), } if not validation.passed: - return review(*(list(validation.reason_codes or []) or ['xfa_business_validation_failed'])) + validation_codes = list(validation.reason_codes or []) or ['xfa_business_validation_failed'] + if identity_state != 'matched': + validation_codes = [f'xfa_profile_identity_{identity_state}', *validation_codes] + return review(*validation_codes) table = { 'profile_id': selected.get('profile_id') or selected.get('id'), 'profile_code': str(selected.get('profile_code') or ''), 'profile_version': int(selected.get('version') or 0), 'profile_checksum': str(selected.get('checksum') or ''), From 6502f73cb5cf95e1487a964bf42eee05bdcd94e3 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 15 Oct 2026 01:22:14 +0800 Subject: [PATCH 05/10] =?UTF-8?q?fix(shipping-notice):=20=E9=87=8D?= =?UTF-8?q?=E8=AF=86=E5=88=AB=20Run=20=E7=BB=88=E6=80=81=E6=BF=80=E6=B4=BB?= =?UTF-8?q?=20Case=20=E5=B9=B6=E6=94=B6=E7=B4=A7=E8=A3=B8=E6=95=B0?= =?UTF-8?q?=E5=AD=97=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` 丢弃取值导致复核草稿空白。 From 3e8b12b9545374e30808262dbb927f7ad00cdd29 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 15 Oct 2026 01:39:13 +0800 Subject: [PATCH 06/10] =?UTF-8?q?fix(shipping-notice):=20=E6=94=B6?= =?UTF-8?q?=E5=8F=A3=E6=BF=80=E6=B4=BB=E6=8C=89=20run=5Fid=20=E5=8F=96=20R?= =?UTF-8?q?un=20=E4=BF=AE=E5=8F=98=E9=87=8F=E4=BD=9C=E7=94=A8=E5=9F=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../shipping_notice/order_extraction.py | 66 ++++++++++--------- 1 file changed, 35 insertions(+), 31 deletions(-) diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index 43857a44..d03ec4dc 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -870,8 +870,8 @@ def persist_order_extraction_result( # 该钩子此前从未接线,导致工作台队列(按 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 + if run_id is not None: + from app.models import ShippingOrderProcessingRun, ShippingOrderReviewCase from app.services.shipping_notice.candidate_service import ( is_current_reviewable_candidate, ) @@ -881,36 +881,40 @@ def persist_order_extraction_result( 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), + persisted_run = db.session.get(ShippingOrderProcessingRun, int(run_id)) + if persisted_run is not None and persisted_run.reparse_of_run_id is not None: + reparse_cases = ShippingOrderReviewCase.query.filter( + ShippingOrderReviewCase.run_id == int(persisted_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 ( - 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 + 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=persisted_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 From b8fe089b3d8d2eb9b1f97d28687d37a534297c51 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 15 Oct 2026 02:25:48 +0800 Subject: [PATCH 07/10] =?UTF-8?q?fix(shipping-notice):=20=E8=AF=86?= =?UTF-8?q?=E5=88=AB=E6=94=B6=E5=8F=A3=E8=87=AA=E5=8A=A8=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E5=B7=B2=E9=87=87=E7=BA=B3=E5=AD=97=E6=AE=B5=E7=9A=84=E8=A1=A5?= =?UTF-8?q?=E5=85=85=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 重识别 Run 收口时对本 Run 可复核 Case 原子激活文件 Stream (batch_reparse_succeeded,含 Run 谱系证明与可选来源声明), 使工作台队列不再因 Stream 断链而丢失单据。 - persist 收口对本 Run 候选批量调用 resolve_satisfied_supplement_conflicts: supplement_field_conflict 的字段级裁决已 accepted(PO 行收敛唯一写入 或正式值源)即标记 resolved,不再阻断提交订单; - 投影过滤 resolved 冲突不下发待裁决面板; - 同一 field_code 表头/行级双字段(如预约单号)任一位置 accepted 即满足; - 新增测试环境失败 Run 重排队运维脚本(仅测试库硬校验、dry-run 默认)。 --- .../candidate_qualification_service.py | 81 ++++++ .../shipping_notice/order_extraction.py | 9 + .../order_review_field_conflict_service.py | 3 + scripts/reset_test_failed_run_state.py | 251 ++++++++++++++++++ 4 files changed, 344 insertions(+) create mode 100644 scripts/reset_test_failed_run_state.py diff --git a/backend/app/services/shipping_notice/candidate_qualification_service.py b/backend/app/services/shipping_notice/candidate_qualification_service.py index 47adf96e..f15cd410 100644 --- a/backend/app/services/shipping_notice/candidate_qualification_service.py +++ b/backend/app/services/shipping_notice/candidate_qualification_service.py @@ -73,6 +73,87 @@ _NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'}) _EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'}) +def resolve_satisfied_supplement_conflicts(candidate: Any) -> int: + """ + 裸数字启发式冲突的字段若已有正式采纳裁决,自动标记已解决。 + + AI 触发时机:Run 收口持久化完成后调用(或修复脚本对存量 Candidate 执行); + 投影与资格门禁共用 current_open_candidate_conflicts,标记 resolved 后 + 「字段冲突已解决」即达成,不再阻断提交订单。 + + 核心逻辑:supplement_field_conflict 的定位证据来自邮件补充的裸数字候选; + 当该字段的字段级裁决已为 accepted(PO 行收敛唯一路径或正式值源写入均算), + 「多候选待人工选择」的前提消失——采纳即裁决。仅标记 resolution_status, + 不删除审计记录,也不改动任何已写入的字段值。同一 field_code 可能在表头与 + 行级各配置一个字段:任一位置的裁决 accepted 即视为已满足。 + + Returns: + int: 实际标记为已解决的冲突条数。 + """ + from sqlalchemy.orm.attributes import flag_modified + + from app.models import ( + ShippingOrderFieldDecision, + ShippingOrderSchemaVersion, + ) + + conflicts = candidate.conflicts_json if isinstance(candidate.conflicts_json, list) else [] + if not conflicts: + return 0 + extraction_id = ( + getattr(candidate, 'order_extraction_id', None) + or getattr(candidate, 'extraction_id', None) + ) + if extraction_id is None: + return 0 + extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) + version = ( + db.session.get(ShippingOrderSchemaVersion, int(extraction.schema_version_id)) + if extraction is not None and extraction.schema_version_id is not None else None + ) + definition = (version.definition_json or {}) if version is not None else {} + # 同一 field_code 可能在表头与行级各配置一个字段(如预约单号):任一位置 + # 的裁决 accepted 即视为该字段冲突已满足。 + field_id_candidates: dict[str, set[str]] = {} + for item in definition.get('fields') or []: + if not isinstance(item, dict): + continue + code = str(item.get('field_code') or '').strip() + fid = str(item.get('field_id') or '').strip() + if code and fid: + field_id_candidates.setdefault(code, set()).add(fid) + changed = 0 + for item in conflicts: + if not isinstance(item, dict): + continue + if str(item.get('reason') or '') != 'supplement_field_conflict': + continue + if str(item.get('resolution_status') or 'unresolved').strip() == 'resolved': + continue + field_code = str(item.get('field') or '').strip() + field_id_set = field_id_candidates.get(field_code) or set() + line_index = item.get('line_index') + line_id = int(line_index) if line_index is not None and int(line_index) >= 0 else None + decision = None + for field_id in sorted(field_id_set): + decision = ShippingOrderFieldDecision.query.filter_by( + extraction_id=int(extraction_id), field_id=field_id, line_id=line_id, + ).first() + if decision is not None and decision.decision_status == 'accepted': + break + decision = None + if decision is None or decision.decision_status != 'accepted': + continue + item['resolution_status'] = 'resolved' + item['resolution'] = 'auto_scoped_value_accepted' + changed += 1 + if changed: + from sqlalchemy.orm.attributes import flag_modified as _fm + + _fm(candidate, 'conflicts_json') + return changed + + def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> bool: """按冻结字段配置判断证据缺失是否只是可选字段诊断。 diff --git a/backend/app/services/shipping_notice/order_extraction.py b/backend/app/services/shipping_notice/order_extraction.py index d03ec4dc..20c5ee13 100644 --- a/backend/app/services/shipping_notice/order_extraction.py +++ b/backend/app/services/shipping_notice/order_extraction.py @@ -989,6 +989,15 @@ def persist_order_extraction_result( .all() ) if run is not None and current_candidates: + # [STEP] 裸数字启发式冲突的自动解决:字段级裁决已 accepted 的 + # supplement_field_conflict 不再阻断建单资格(PO 行收敛/正式值源写入 + # 即为裁决)。必须在 OT 创建前执行,否则资格门禁误报字段冲突。 + from app.services.shipping_notice.candidate_qualification_service import ( + resolve_satisfied_supplement_conflicts, + ) + + for candidate in current_candidates: + resolve_satisfied_supplement_conflicts(candidate) # PDF 级复核重识别:Run.user_task_no 已是 Case 对应 OT(可能是兄弟号), # 禁止再按 index=0 当根号、给其他 Candidate 派生 -C{id}。 marker = (getattr(run, 'input_snapshot_json', None) or {}).get('review_reparse') diff --git a/backend/app/services/shipping_notice/order_review_field_conflict_service.py b/backend/app/services/shipping_notice/order_review_field_conflict_service.py index 6fd7a480..cbebb82f 100644 --- a/backend/app/services/shipping_notice/order_review_field_conflict_service.py +++ b/backend/app/services/shipping_notice/order_review_field_conflict_service.py @@ -304,6 +304,9 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu is_evidence_gap = reason in _EVIDENCE_GAP_REASONS if is_evidence_gap and field_evidence_gap_is_non_blocking(candidate, item): continue + # 已自动解决(正式值源/PO 行收敛写入)的冲突不再进入待裁决面板。 + if str(item.get('resolution_status') or '').strip() == 'resolved': + continue # 只有多个候选值不一致才属于「字段冲突待裁决」。 if len(value_keys) < 2 and not is_evidence_gap and not is_current_open_blocking: continue diff --git a/scripts/reset_test_failed_run_state.py b/scripts/reset_test_failed_run_state.py new file mode 100644 index 00000000..3b1972d2 --- /dev/null +++ b/scripts/reset_test_failed_run_state.py @@ -0,0 +1,251 @@ +# -*- coding: utf-8 -*- +""" +scripts/reset_test_failed_run_state.py + +用途:测试环境运维脚本——把「全部 Unit 失败的订单抽取 Run」留下的假完成文档/Intake + 状态复位为诚实状态,使批次面板不再显示「已完成」,用户可手动重新解析。 +依赖:psycopg2;仓库根目录 `.env.test` 的 DATABASE_URL(仅测试库,硬性校验库名)。 +逻辑: + 1. 按 --run-no 加载终态 Run(failed/cancelled 等)及其 Intake/Document 集合; + 2. 文档级:`order_extraction_status` 为 completed/partially_completed、 + `order_extraction_result_json.request_id` 等于本 Run、且本 Run 在该 Intake 下 + 零 Candidate(假完成特征)时,复位为 not_started 并清空来源/结果/错误; + 3. Intake 级:同样条件下复位(ParseStatus='consumed' 属重新解析流程的正常输入, + 不在此处理,重新解析服务端支持孤儿消费 Intake); + 4. 不触碰 Run/Unit/Case/MinIO(历史事实保留审计)。 + 默认 dry-run 只打印计划;`--apply` 才写库。单事务、幂等,重复执行为 no-op。 + 复位后用户在批次面板对该批附件点「重新解析」,或调用 + POST /shipping-notice/order-extraction-runs//reparse + (reason ∈ rule_updated / field_mapping_error / document_quality / other)。 + +用法(仓库根目录): + python scripts/reset_test_failed_run_state.py # dry-run + python scripts/reset_test_failed_run_state.py --apply # 写入测试库 + python scripts/reset_test_failed_run_state.py --run-no SNER-20261014-8EBAB7A1 --apply + python scripts/reset_test_failed_run_state.py --apply --requeue + # 复位后立即走产品自身 reparse 创建排队中的新 Run: + # 批次进度中心需要「排队中的 Run」才会显示待处理——仅复位文档状态产生不了 + # 待处理(终态 Run 仍是 failed)。--requeue 复用 reparse_order_extraction_run, + # 冻结当前发布规则(含最新修复),Worker 自动处理。 +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +from urllib.parse import urlparse + +import psycopg2 + +TEST_DB_NAME = 'hxops_testing' +DEFAULT_RUN_NO = 'SNER-20261014-8EBAB7A1' +FALSE_DONE_STATUSES = ('completed', 'partially_completed') +RESET_STATUS = 'not_started' + + +def _load_test_db_url(repo_root: Path) -> str: + """从仓库根 `.env.test` 读取 DATABASE_URL,并强制校验指向测试库。""" + env_path = repo_root / '.env.test' + for line in env_path.read_text(encoding='utf-8').splitlines(): + if line.strip().startswith('DATABASE_URL'): + url = line.split('=', 1)[1].strip().strip('"').strip("'") + dbname = urlparse(url).path.lstrip('/') + if dbname != TEST_DB_NAME: + raise SystemExit( + f'拒绝执行:目标库 {dbname!r} 不是测试库 {TEST_DB_NAME!r}。' + '本脚本仅允许操作测试环境数据。' + ) + return url + raise SystemExit(f'未在 {env_path} 找到 DATABASE_URL') + + +def _connect(db_url: str): + u = urlparse(db_url) + return psycopg2.connect( + host=u.hostname, port=u.port, dbname=u.path[1:], + user=u.username, password=u.password, connect_timeout=10, + ) + + +def _load_run(cur, run_no: str): + cur.execute( + "SELECT id, run_no, status FROM shipping_order_processing_runs WHERE run_no=%s", + (run_no,), + ) + run = cur.fetchone() + if run is None: + raise SystemExit(f'Run 不存在:{run_no}') + if run[2] not in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}: + raise SystemExit(f'Run {run_no} 状态 {run[2]!r} 非终态,不适用本脚本') + return run + + +def _scope(cur, run_id: int) -> tuple[list[int], list[int]]: + """解析 Run 冻结的 Intake 集合与全部 Document id(经 plan→unit 关联)。""" + cur.execute( + "SELECT input_snapshot_json->'intakes' FROM shipping_order_processing_runs WHERE id=%s", + (run_id,), + ) + snapshot_intakes = cur.fetchone()[0] or [] + intake_ids = sorted({ + int(item['intake_id']) for item in snapshot_intakes + if isinstance(item, dict) and str(item.get('intake_id') or '').isdigit() + }) + cur.execute( + "SELECT DISTINCT u.document_id FROM shipping_order_processing_units u " + "JOIN shipping_order_processing_plans p ON p.id = u.plan_id WHERE p.run_id=%s " + "ORDER BY 1", + (run_id,), + ) + document_ids = [int(r[0]) for r in cur.fetchall()] + return intake_ids, document_ids + + +def _candidate_counts(cur, run_id: int, intake_ids: list[int]) -> dict[int, int]: + """统计 Run 在各 Intake 下实际落地的 Candidate 数(假完成判定依据)。""" + if not intake_ids: + return {} + cur.execute( + "SELECT intake_id, count(*) FROM shipping_order_candidates " + "WHERE order_extraction_run_id=%s AND intake_id = ANY(%s) GROUP BY intake_id", + (run_id, intake_ids), + ) + return {int(row[0]): int(row[1]) for row in cur.fetchall()} + + +def _plan_documents(cur, run_no: str, run_id: int, document_ids: list[int], candidate_counts: dict[int, int]): + """筛选假完成的文档:状态为完成类、结果归属本 Run、且本 Run 零 Candidate。""" + plans = [] + if not document_ids: + return plans + cur.execute( + "SELECT id, order_extraction_status, " + "coalesce(order_extraction_result_json->>'request_id',''), intake_id " + "FROM shipping_order_documents WHERE id = ANY(%s) ORDER BY id", + (document_ids,), + ) + for doc_id, status, request_id, intake_id in cur.fetchall(): + if status not in FALSE_DONE_STATUSES: + continue + if request_id != run_no: + continue + if candidate_counts.get(int(intake_id), 0) > 0: + continue + plans.append(('document', doc_id, status)) + return plans + + +def _plan_intakes(cur, intake_ids: list[int], candidate_counts: dict[int, int]): + """筛选假完成的 Intake:状态为完成类且本 Run 零 Candidate。""" + plans = [] + if not intake_ids: + return plans + cur.execute( + "SELECT id, order_extraction_status FROM shipping_order_intakes " + "WHERE id = ANY(%s) ORDER BY id", + (intake_ids,), + ) + for intake_id, status in cur.fetchall(): + if status not in FALSE_DONE_STATUSES: + continue + if candidate_counts.get(int(intake_id), 0) > 0: + continue + plans.append(('intake', intake_id, status)) + return plans + + +def _apply_resets(cur, plans) -> None: + """单事务执行复位;文档清结果/来源/错误,Intake 清错误。""" + doc_ids = [key for kind, key, _ in plans if kind == 'document'] + intake_ids = [key for kind, key, _ in plans if kind == 'intake'] + if doc_ids: + cur.execute( + "UPDATE shipping_order_documents SET order_extraction_status=%s, " + "order_extraction_source=NULL, order_extraction_result_json=NULL, " + "order_extraction_error_code=NULL, order_extraction_error_message=NULL, " + "updated_at=NOW() WHERE id = ANY(%s)", + (RESET_STATUS, doc_ids), + ) + if intake_ids: + cur.execute( + "UPDATE shipping_order_intakes SET order_extraction_status=%s, " + "order_extraction_error_code=NULL, order_extraction_error_message=NULL " + "WHERE id = ANY(%s)", + (RESET_STATUS, intake_ids), + ) + + +def _requeue_run(db_url: str, run_no: str) -> None: + """走产品自身 reparse 服务创建排队中的新 Run(批次中心随之显示待处理)。""" + import os + import sys + + os.environ['DATABASE_URL'] = db_url + backend_dir = str(Path(__file__).resolve().parents[1] / 'backend') + if backend_dir not in sys.path: + sys.path.insert(0, backend_dir) + from app import create_app + from app.extensions import db + from app.models import ShippingOrderProcessingRun + from app.services.shipping_notice.order_extraction_run_service import ( + reparse_order_extraction_run, + ) + + app = create_app('development') + with app.app_context(): + run = ShippingOrderProcessingRun.query.filter_by(run_no=run_no).with_for_update().first() + if run is None: + raise SystemExit(f'Run 不存在:{run_no}') + new_run, reused = reparse_order_extraction_run( + user_id=int(run.user_id), run_no=run_no, + reason='document_quality', comment='运维脚本重排队:上一版本全部 Unit 技术失败', + ) + db.session.commit() + state = '复用既有活跃后继' if reused else '已创建' + print(f'reparse {state}:新 Run {new_run.run_no} (status={new_run.status})') + + +def main() -> None: + parser = argparse.ArgumentParser(description='复位失败抽取 Run 留下的假完成状态(仅测试库)') + parser.add_argument('--run-no', default=DEFAULT_RUN_NO, help=f'订单抽取 Run 编号(默认 {DEFAULT_RUN_NO})') + parser.add_argument('--apply', action='store_true', help='实际写库;缺省为 dry-run') + parser.add_argument('--requeue', action='store_true', + help='复位后走产品 reparse 创建排队中的新 Run(批次中心显示待处理并自动处理)') + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + db_url = _load_test_db_url(repo_root) + conn = _connect(db_url) + cur = conn.cursor() + run_id, run_no, run_status = _load_run(cur, args.run_no) + intake_ids, document_ids = _scope(cur, run_id) + candidate_counts = _candidate_counts(cur, run_id, intake_ids) + plans = _plan_documents(cur, run_no, run_id, document_ids, candidate_counts) + \ + _plan_intakes(cur, intake_ids, candidate_counts) + + print(f'Run {run_no} (id={run_id}, status={run_status})') + print(f'Intake 范围: {intake_ids} | Document 范围: {document_ids}') + print(f'Run 落地 Candidate 数(按 Intake): {candidate_counts or "{}"}') + if not plans: + print('无可复位对象:状态已是诚实状态(或假完成特征不成立)。') + else: + for kind, key, status in plans: + print(f' 计划复位 [{kind} {key}]: {status} -> {RESET_STATUS}') + if not args.apply: + print('dry-run 结束(未写库)。确认无误后加 --apply 执行。') + conn.close() + return + _apply_resets(cur, plans) + conn.commit() + print(f'已提交:复位 {len(plans)} 项。') + conn.close() + if args.requeue and args.apply: + _requeue_run(db_url, run_no) + print('批次进度中心稍后刷新即显示待处理(新 Run 排队中,Worker 将自动处理)。') + elif args.requeue: + print('--requeue 需与 --apply 同时使用(跳过)。') + conn.close() + + +if __name__ == '__main__': + main() From d75f2e7d8650841f04392c32f37f92f74982b4a9 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 15 Oct 2026 08:14:37 +0800 Subject: [PATCH 08/10] =?UTF-8?q?fix(shipping-notice):=20=E9=A2=84?= =?UTF-8?q?=E7=BA=A6=E5=8D=95=E5=8F=B7=E5=85=9C=E5=BA=95=E5=88=86=E4=BD=9C?= =?UTF-8?q?=E7=94=A8=E5=9F=9F=E5=B9=B6=E9=95=9C=E5=83=8F=E8=A1=A5=E5=86=99?= =?UTF-8?q?=E6=98=8E=E7=BB=86=E7=BC=BA=E5=A4=B1=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 订单级早退导致表头已有预约单号时明细行补写永不执行(回归 SNER-20261014-0AB6D98A doc 915 明细预约号空)。 - 兜底早退改分作用域:scope=header 表头有值才跳过;scope=line 行级全有值才跳过,存在缺失行仍执行补写; - 镜像语义:排除集移除表头已采纳的预约号值——它正是要写入缺失 行级的值;其余订单观测值(尤其 PO)保持排除防误判; - PO 行定位收敛不变:本单 PO 所在行的预约号唯一命中后写入。 真数据验证:9/9 PO 各自唯一写入本行预约号 (4510042199→1000161448 … 4510042208→1000131033),与表头一致。 --- .../shipping_notice/order_supplement_merge.py | 53 +++++++++++++++++-- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/backend/app/services/shipping_notice/order_supplement_merge.py b/backend/app/services/shipping_notice/order_supplement_merge.py index 744d48f3..f57d971f 100644 --- a/backend/app/services/shipping_notice/order_supplement_merge.py +++ b/backend/app/services/shipping_notice/order_supplement_merge.py @@ -281,10 +281,15 @@ def _supplement_multi_value_conflict( } -def _iter_order_observation_values(order: dict[str, Any]) -> list[Any]: - """收集订单头 + 全部行的原始字段 Observation 值,供兜底排除集使用。""" +def _iter_order_observation_values( + order: dict[str, Any], *, include_header_values: bool = True, +) -> list[Any]: + """收集订单头/行的原始字段 Observation 值;include_header_values=False 时 + 跳过表头观测(行级补写语义:表头已采纳值允许镜像写入缺失行级)。""" values: list[Any] = [] - field_groups: list[Any] = [order.get('header_fields')] + field_groups: list[Any] = [] + if include_header_values: + field_groups.append(order.get('header_fields')) for line in order.get('lines') or []: if isinstance(line, dict): field_groups.append(line.get('fields')) @@ -303,15 +308,23 @@ def _iter_order_observation_values(order: dict[str, Any]) -> list[Any]: def _heuristic_excluded_values( order: dict[str, Any], supplement: dict[str, Any], + *, + include_order_header_values: bool = True, ) -> set[str]: """构造裸数字候选的排除集:订单已提取值 + 邮件补充行值 + 邮件主题标签值。 核心逻辑:客户 PO 号本身就是 10 位纯数字,是启发式最大的误判源;因此除了 订单 Observation 原值外,还纳入 Reservation/PO 两种归一变体(千分位、x.0、 前导零),并排除主题里「PO xxx」等带标签数字(Q10 双保险)。 + + Args: + include_order_header_values: 行级补写语义下传 False——表头已采纳的预约号 + 正是要镜像写入缺失行级的值,不能出现在排除集里(否则行级永远补不上)。 """ excluded: set[str] = set() - raw_values = _iter_order_observation_values(order) + raw_values = _iter_order_observation_values( + order, include_header_values=include_order_header_values, + ) rows = supplement.get('rows') if isinstance(supplement.get('rows'), list) else [] for row in rows: if isinstance(row, dict): @@ -421,9 +434,39 @@ def _apply_reservation_heuristic( candidates = supplement.get('reservation_candidates') if config is None or not field_id or not isinstance(candidates, list) or not candidates: return - if _order_has_reservation_value(order, ids): + # [分作用域兜底] 「已有值永不覆盖」按字段作用域生效:表头已有预约号→不再重复 + # 注入表头;行级缺失→仍执行行级补写(分配邮件一行一个 PO+预约号,明细缺预约 + # 号属数据不完整,回归 SNER-20261014-0AB6D98A doc 915 明细预约号空)。 + reverse_ids = {v: k for k, v in ids.items()} + header_has_reservation = bool( + _values(order.get('header_fields'), 'reservation_id', reverse_ids), + ) + header_reservation_values = set( + _values(order.get('header_fields'), 'reservation_id', reverse_ids), + ) + lines_missing_reservation = [ + line for line in order.get('lines') or [] + if isinstance(line, dict) and isinstance(line.get('fields'), list) + and not _values(line['fields'], 'reservation_id', reverse_ids) + ] + scope = str(config.get('scope') or '').strip().lower() + if scope == 'header' and header_has_reservation: + return + if scope != 'header' and not lines_missing_reservation: return excluded = _heuristic_excluded_values(order, supplement) | claimed + if lines_missing_reservation and header_has_reservation: + # [镜像语义] 表头已采纳的预约号值从排除集中移除——它正是要写入缺失 + # 行级的值;其余订单观测值(尤其 PO)保持排除,防止 PO 误当预约号。 + mirror_allow: set[str] = set() + for value in header_reservation_values: + text = str(value).strip().upper() + if text: + mirror_allow.update({text, text.lstrip('0')}) + normalized = validated_reservation_id(normalize_reservation_id(text)) + if normalized: + mirror_allow.update({normalized, normalized.lstrip('0')}) + excluded -= mirror_allow surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=excluded) if status == 'none': return From 68c944607cc5ca4a4684b14fa885fc5098e58468 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 15 Oct 2026 09:43:40 +0800 Subject: [PATCH 09/10] =?UTF-8?q?fix(shipping-notice):=20=E5=B7=A5?= =?UTF-8?q?=E4=BD=9C=E5=8F=B0=E4=BA=94=E9=98=B6=E6=AE=B5=E5=AE=9A=E4=BD=8D?= =?UTF-8?q?=E5=8F=AA=E8=BF=9B=E4=B8=8D=E9=80=80=E5=B9=B6=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E6=9C=80=E8=BF=91=E6=8A=95=E5=BD=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 提交订单后的刷新窗口内,extractionLifecycleProgress 会被 Run 级 lifecycle_progress(两段模型,恒为 intake_parse)短暂覆盖,五阶段页签 闪回「接收解析」后再跳「通知准备」。 - lifecycleProgressForView 保持最近一次非空投影兜底,不再回落 Run 级旧值; - 新增 lifecycleStageFloor 只进不退下限:自动定位永不回跳已越过的更早 阶段;显式 route 请求(用户手动点击阶段入口)不受限,可回看前置阶段。 --- .../chat/views/ShippingOrderReviewView.vue | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.vue b/frontend/src/features/chat/views/ShippingOrderReviewView.vue index 52739b99..b768e763 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.vue +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.vue @@ -108,6 +108,7 @@ import type { ShippingOrderReviewDraftFieldMeta, ShippingOrderReviewEvidence, ShippingOrderReviewValueSource, + ShippingOrderExtractionLifecycleProgress, ShippingProcessingLifecycleEntry, ShippingTaskDetail, ShippingFreightNoticeGroup, @@ -365,16 +366,40 @@ const lifecycleCurrentStageCode = computed(() = function lifecycleEntryIsEnterable(entry: { state?: string | null } | undefined): boolean { return entry?.state === 'current' || entry?.state === 'available'; } +// [只进不退] 自动定位的阶段序号下限:一旦到达过后道阶段,自动跳转永不回显示 +// 前道阶段;仅显式 route 请求(用户手动点击阶段入口)可进入前置阶段可回看视图。 +const lifecycleStageFloor = ref(-1); const lifecycleActiveStageCode = computed(() => { - const requested = String(route.query.lifecycle_stage || '').trim() as ReviewLifecycleStageCode; + const requestedStage = String(route.query.lifecycle_stage || '').trim(); + const manualRequested = requestedStage !== ''; + const requested = requestedStage as ReviewLifecycleStageCode; const entry = lifecycleUiState.value.entries.find((item) => item.code === requested); if (requested === 'intake_parse' && lifecycleUiState.value.intakeParseAuthorized === true) { + lifecycleStageFloor.value = Math.max(lifecycleStageFloor.value, 0); return 'intake_parse'; } const current = lifecycleCurrentStageCode.value; // 用户可回看后端已授权的 available 前置阶段;自动推进由下方 watcher 在 // 「路由仍停留原 current 阶段且用户未固定查看」时处理,不能在这里抢占用户选择。 - return lifecycleEntryIsEnterable(entry) ? requested : current; + const candidate = lifecycleEntryIsEnterable(entry) ? requested : current; + if (!candidate) { + return null; + } + // [只进不退] 非手动请求的自动定位不得回跳到已越过的更早阶段:保持在已到达 + // 的最远阶段,等待投影收敛(回归:提交订单后页签闪回「接收解析」)。 + if (!manualRequested) { + const candidateIdx = LIFECYCLE_STAGE_CODES.indexOf(candidate); + if (candidateIdx >= 0 && candidateIdx < lifecycleStageFloor.value) { + return LIFECYCLE_STAGE_CODES[lifecycleStageFloor.value] ?? null; + } + } + return candidate ?? null; +}); +// [只进不退] 已到达阶段序号只升不降:自动定位永不回跳前道阶段(手动点击前道 +// 阶段是显式回看,不下调下限)。 +watch(lifecycleActiveStageCode, (code) => { + const idx = LIFECYCLE_STAGE_CODES.indexOf(code as ReviewLifecycleStageCode); + if (idx >= 0) lifecycleStageFloor.value = Math.max(lifecycleStageFloor.value, idx); }); /** 当前后端投影明确在自动推进时,五阶段导航只为该阶段展示 Spinner,不改变授权。 */ const lifecycleProcessingStageCode = computed(() => { @@ -2333,11 +2358,19 @@ const showWorkbenchGrid = computed( () => workbenchMode.value === 'formal_task' || !isConfirmProgressPrimary.value, ); +const lastLifecycleProgress = ref(null); +// [阶段防回跳] 提交订单后的刷新窗口内,extractionLifecycleProgress 会被 Run 级 +// lifecycle_progress(两段模型,恒为 intake_parse)短暂覆盖,页签因此闪回 +// 「接收解析」。此处保持最近一次非空投影作为兜底,不再回落到 Run 级旧值; +// 数据到达后自然收敛到真实当前阶段(如通知准备)。 const lifecycleProgressForView = computed(() => ( extractionLifecycleProgress.value - || reviewRun.value?.lifecycle_progress + || lastLifecycleProgress.value || null )); +watch(lifecycleProgressForView, (value) => { + if (value) lastLifecycleProgress.value = value; +}); const lifecycleProgressStageItems = computed(() => { const progress = lifecycleProgressForView.value; From 95e7db083139a30c10b7e5288627b479c298e9da Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Fri, 23 Oct 2026 09:58:31 +0800 Subject: [PATCH 10/10] =?UTF-8?q?feat(freight-rpa):=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E4=BB=8E=E6=9D=A5=E6=BA=90=E7=AB=99=E7=82=B9=E5=A4=8D=E5=88=B6?= =?UTF-8?q?=E4=B8=BA=E6=9C=AA=E4=BF=9D=E5=AD=98=E8=8D=89=E7=A8=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- docs/funclist.md | 2 +- .../modules/freight-rpa/FreightRpaPage.vue | 220 ++++++++++++++++-- .../freight-rpa/sourceCloneDraft.spec.ts | 88 +++++++ .../modules/freight-rpa/sourceCloneDraft.ts | 120 ++++++++++ frontend/src/locales/en/admin.json | 3 + frontend/src/locales/th/admin.json | 3 + frontend/src/locales/zh-CN/admin.json | 3 + frontend/src/locales/zh-TW/admin.json | 3 + 8 files changed, 426 insertions(+), 16 deletions(-) create mode 100644 frontend/src/features/admin/modules/freight-rpa/sourceCloneDraft.spec.ts create mode 100644 frontend/src/features/admin/modules/freight-rpa/sourceCloneDraft.ts diff --git a/docs/funclist.md b/docs/funclist.md index 8d289f8d..e84cf9ab 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -201,7 +201,7 @@ | 人工复核与字段证据闭环(阶段 5) | 已实现 | 单头、订单行、冲突解决均要求乐观锁、原因和结构化 `document_cell`/`manual_input` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 | | 原 PDF 双层重解析 | 已实现 | “重新识别此 PDF”仅为当前原始文件创建后继 Run;“重新解析本批次”逐 PDF 创建独立子 Run、局部成功替换,按完整 Run 谱系选择每个原文件的当前 Case;已确认/履约文件排除;不支持上传替代 PDF。 | | 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 | -| 库存 RPA 源配置 | 已实现 | 源、报表路径与查询参数维护在数据库 `freight_rpa_sources`(管理端货代 RPA 页);期初 YAML 已于 2026-10-20 删除,运行时只读数据库 | +| 库存 RPA 源配置 | 已实现 | 源、报表路径与查询参数维护在数据库 `freight_rpa_sources`(管理端货代 RPA 页);期初 YAML 已于 2026-10-20 删除,运行时只读数据库。来源站点可复制为未保存草稿(连接、模板、仓库解析、库存/入站/出站报表),保存后保持停用;不复制快照、仓库映射、路由规则与测试结果。 | | 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` | | 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings | | 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 | diff --git a/frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue b/frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue index bf55930c..250490d0 100644 --- a/frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue +++ b/frontend/src/features/admin/modules/freight-rpa/FreightRpaPage.vue @@ -1,11 +1,12 @@ @@ -96,18 +97,28 @@
- + + + + +