Files
syops/backend/tests/test_shipping_reservation_heuristic.py
T
hugo d7d4819a42 feat(shipping-notice): 无表头文档抽取增强与复核深链身份修复
- 新增表头 OCR 救援:模板匹配落 layout_drift/no_match 时按表头带证据补洞重评候选身份,主抽取流程接入并落 identity_rescue 事实字段
- 预约号裸数字兜底:正文无表头且常规证据缺失时扫描 5/10 位纯数字候选,持久化预置、合并末段唯一/多候选裁决
- 修复复核深链仅带 run_no 时队列项显示未命名:Case 身份优先按当前工作面 displayCase 匹配队列项
- 同步抽取 Job/运行服务/候选持久化配套与 OCR 救援、预约号启发式、表头身份测试
2026-10-14 19:55:37 +08:00

331 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""验证 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]