feat(shipping-notice): 无表头文档抽取增强与复核深链身份修复

- 新增表头 OCR 救援:模板匹配落 layout_drift/no_match 时按表头带证据补洞重评候选身份,主抽取流程接入并落 identity_rescue 事实字段
- 预约号裸数字兜底:正文无表头且常规证据缺失时扫描 5/10 位纯数字候选,持久化预置、合并末段唯一/多候选裁决
- 修复复核深链仅带 run_no 时队列项显示未命名:Case 身份优先按当前工作面 displayCase 匹配队列项
- 同步抽取 Job/运行服务/候选持久化配套与 OCR 救援、预约号启发式、表头身份测试
This commit is contained in:
hugo committed 2026-10-14 20:44:31 +08:00
1 parent 5187b6105b
commit 3b53a2219c
15 files changed
+1660 -6

No files matched your search

@@ -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]