Merge branch 'dev' of https://gitee.com/justop/hxops into dev

This commit is contained in:
sophie committed 2026-10-14 20:25:53 +08:00
commit a92df4c38d
15 files changed
+1660 -6

No files matched your search

@@ -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',
@@ -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)
@@ -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::<field_code> 原子(短语内单词不再残留);未命中的剩余单词沿用词级
原子的既有过滤(长度 >= _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::<field_code>` 列表项(短语内单词不残留);未命中词按 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] = []
@@ -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
@@ -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,
@@ -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(
@@ -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
@@ -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"(?<!\d)(\d{5}|\d{10})(?!\d)")
# [裸数字兜底] 紧跟业务标签的数字串(PO/订单/发票/数量)不是预约单号;捕获组为数字本体。
# 保留前导词边界防止命中复合词内部;尾部不加边界、由「必须跟数字」门控,
# 使 PO12345 / PO# 12345 / Purchase Order: 12345 等写法都被覆盖,而 podium 等词不受影响。
LABELED_NON_RESERVATION_RE = re.compile(
r"(?i)(?:\bp\.?\s*o\.?|\bpurchase\s+orders?|\borders?|\binvoices?|\binv\.?|\bqty\.?|\bquantity)"
r"(?:\s*(?:number|no\.?|#))?\s*[:#]?\s*(\d{3,})"
)
# 候选数量上限:转发/引用链可能携带大量历史数字,防止 supplement 快照被刷爆。
MAX_HEURISTIC_RESERVATION_CANDIDATES = 20
def normalize_reservation_id(value: Any) -> str:
@@ -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'
@@ -11,7 +11,8 @@ tests/test_order_profile_header_identity.py
逻辑:pure_unit;别名命中产出 field::<field_code> 标记原子(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']
@@ -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
@@ -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 = '<table><tr><td>1000053337</td><td>4000122230</td></tr></table>'
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]
@@ -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();
@@ -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(
@@ -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 {
@@ -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)