Files
syops/backend/tests/test_shipping_reservation_heuristic.py
T
hugo e78f750db0 fix(shipping-notice): 重识别 Run 终态激活 Case 并收紧裸数字兜底口径
- 修复重解析延迟激活钩子未接线:Run 终态原子激活可复核 Case 为文件 Stream 当前版本,工作台队列不再空白
- 新增 run_is_reparse_successor_of_case 判定 Case 与重解析 Run 的后继关系
- 裸数字兜底口径收紧:仅扫「整格恰好 5/10 位纯数字」的正文 HTML 表格单元格,自由文本与带前后字符的值一律不取,防误绑签名与邮编
- 新增客户 PO 匹配变体集合(原值/归一/去前导零)纳入排除集,补充合并末段裁决更准
- 同步预约号启发式测试,business/technical 文档记录收紧决策
2026-10-15 01:26:23 +08:00

323 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_table_row():
"""截图场景:无表头数据表只识别整格纯数字的 39739;PO 整格入选由合并端排除。"""
html = (
'<table><tr><td>DBS PHX01</td><td>39739</td><td>6233</td>'
'<td>504-006055-001</td><td>D4-A08AR12000002</td><td>WEL</td>'
'<td>10/12/2026</td><td>120</td><td>1000053286</td></tr></table>'
)
candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h')
# 断言:仅两个整格纯数字入选——预约号 39739 与 PO 1000053286(10 位同样合规,
# 由合并端用已提取 PO 字段值/主题标签排除);仓库/料号/日期/数量格一概不取。
assert [item['value'] for item in candidates] == ['39739', '1000053286']
evidence = candidates[0]['evidence']
# 断言:DOM 级证据齐全,可回溯到具体表格/行/列。
assert evidence['table_index'] == 0
assert evidence['row_index'] == 0 and evidence['column_index'] == 1
assert evidence['cell_id'].startswith('reservation-heuristic:h:0')
def test_scan_ignores_cells_with_any_surrounding_content():
"""收紧规则:邮编地址、带字母/备注前后的值一律不取(07094/00410 误报修复)。"""
html = (
'<table><tr>'
'<td>Secaucus, NJ 07094</td>'
'<td>T00410</td>'
'<td>00410-CN</td>'
'<td>39739 (A)</td>'
'<td> 39739 </td>'
'<td>35354-1</td>'
'</tr></table>'
)
candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h')
# 断言:只有去除首尾空白后恰好为纯数字的整格幸存(39739);
# 07094 藏在地址文本里、00410 带字母前后、39739 带备注、35354-1 带后缀,全部排除。
assert [item['value'] for item in candidates] == ['39739']
def test_scan_returns_nothing_without_html_tables():
"""收紧规则:正文无 HTML 表格时不做兜底,纯文本中的数字不再是候选来源。"""
assert find_bare_numeric_reservation_candidates(html_tables=[], content_hash='h') == []
assert find_bare_numeric_reservation_candidates(html_tables=None, content_hash='h') == []
def test_scan_dedupes_and_caps_candidates():
"""同值只留首个证据;候选总数截断到上限,防止大表刷爆快照。"""
cells = '<td>4000122230</td><td>4000122230</td>' + ''.join(
f'<td>{30000 + index}</td>' for index in range(25)
)
html = f'<table><tr>{cells}</tr></table>'
candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h')
values = [item['value'] for item in candidates]
# 断言:重复格只保留首个证据;总数截断到 20(1 个 10 位 + 前 19 个 5 位)。
assert len(values) == 20
assert values[0] == '4000122230'
assert values.count('4000122230') == 1
def test_labeled_context_helper_extracts_subject_po():
"""主题「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]