Merge branch 'dev' of https://gitee.com/justop/hxops into dev
This commit is contained in:
commit
62430bc1d0
23 files changed
+1356
-129
No files matched your search
@@ -165,6 +165,45 @@ def test_dsv_report_inventory_rows_returns_false_when_no_data_within_deadline(mo
|
||||
assert worker._wait_dsv_report_inventory_rows(page=object(), timeout_ms=2_500) is False
|
||||
|
||||
|
||||
def test_ensure_dsv_inventory_rows_retries_view_report_then_allows_export_fallback(monkeypatch):
|
||||
"""DOM 无行时重试 View Report;仍无行不得抛空,应继续导出由 Excel 判空。"""
|
||||
worker = _load_dsv_report_export()
|
||||
clicks: list[str] = []
|
||||
waits: list[int] = []
|
||||
row_outcomes = iter([False, False])
|
||||
|
||||
monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_wait_dsv_report_inventory_rows",
|
||||
lambda page_arg, timeout_ms: (waits.append(timeout_ms) or next(row_outcomes, False)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_click_dsv_view_report",
|
||||
lambda page_arg: clicks.append("view"),
|
||||
)
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms: None)
|
||||
|
||||
worker._ensure_dsv_inventory_rows_or_export_fallback(page=object(), report_name="On Hand Inventory by Location")
|
||||
|
||||
assert clicks == ["view"]
|
||||
assert waits == [5_000, 5_000]
|
||||
|
||||
|
||||
def test_ensure_dsv_inventory_rows_skips_retry_when_rows_already_visible(monkeypatch):
|
||||
"""首次轮询已有明细行时不得再点 View Report。"""
|
||||
worker = _load_dsv_report_export()
|
||||
clicks: list[str] = []
|
||||
monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000)
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_inventory_rows", lambda page_arg, timeout_ms: True)
|
||||
monkeypatch.setattr(worker, "_click_dsv_view_report", lambda page_arg: clicks.append("view"))
|
||||
|
||||
worker._ensure_dsv_inventory_rows_or_export_fallback(page=object(), report_name="On Hand Inventory by Location")
|
||||
|
||||
assert clicks == []
|
||||
|
||||
|
||||
def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
|
||||
"""单票 DSV 导出应走与批量相同的 session + export 函数。"""
|
||||
worker = _load_worker()
|
||||
|
||||
@@ -145,6 +145,29 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp
|
||||
assert ShippingInventoryConfigurationTestRun.query.count() == 1
|
||||
|
||||
|
||||
def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app, tmp_path):
|
||||
"""Worker 回传 Windows drop 路径时,必须映射到 Linux 共享目录再分析,不能报「文件不存在」。"""
|
||||
drop_dir = tmp_path / 'inventory_drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
result_file = drop_dir / f"inventory_{started['run_no']}_DSV360_BYAWSPRD01.xlsx"
|
||||
_workbook(result_file)
|
||||
windows_path = rf'C:\HxopsRpaTest\data\inventory_drop\{result_file.name}'
|
||||
completed = inventory_configuration_test.report_test_export({
|
||||
'run_no': started['run_no'], 'status': 'success', 'file_path': windows_path,
|
||||
})
|
||||
assert completed['status'] == 'completed'
|
||||
assert completed.get('error_message') in (None, '')
|
||||
assert not ShippingInventoryFile.query.count()
|
||||
|
||||
|
||||
def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
|
||||
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
@@ -28,6 +29,7 @@ from app.services.schedule.scheduler_service import (
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import (
|
||||
inventory_raw_zip_available_from_summary,
|
||||
inventory_raw_zip_download_name,
|
||||
inventory_rpa_attachment_stem,
|
||||
inventory_rpa_result_excel_name,
|
||||
persist_inventory_rpa_raw_zip_archive,
|
||||
resolve_inventory_raw_zip_download,
|
||||
@@ -544,6 +546,23 @@ def test_build_zip_entry_name_prefers_source_code():
|
||||
) == "003_AWSSG.xlsx"
|
||||
|
||||
|
||||
def test_inventory_rpa_attachment_stem_converts_utc_to_schedule_timezone(app):
|
||||
"""展示名 HHmm 必须用业务时区,不能直接用库内 UTC naive / run_no 内嵌时刻。"""
|
||||
with app.app_context():
|
||||
run = _make_inventory_run_with_created(
|
||||
schedule_no="ARCH-TZ-STEM",
|
||||
username="arch_tz_stem",
|
||||
created=[],
|
||||
)
|
||||
# UTC 06:27 → Asia/Shanghai 14:27
|
||||
run.started_at = datetime(2026, 9, 9, 6, 27, 17)
|
||||
run.task.schedule_timezone = "Asia/Shanghai"
|
||||
db.session.commit()
|
||||
assert inventory_rpa_attachment_stem(run) == "库存RPA-20260909-1427"
|
||||
assert inventory_rpa_result_excel_name(run) == "库存RPA-20260909-1427-结果.xlsx"
|
||||
assert inventory_raw_zip_download_name(run) == "库存RPA-20260909-1427-库存.zip"
|
||||
|
||||
|
||||
def test_get_inventory_raw_zip_returns_404_when_archive_unavailable(
|
||||
client,
|
||||
app,
|
||||
|
||||
@@ -786,7 +786,10 @@ def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app):
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 1
|
||||
db.session.refresh(run)
|
||||
first_job_id = run.current_job_id
|
||||
assert db.session.get(Job, first_job_id) is not None
|
||||
first_job = db.session.get(Job, first_job_id)
|
||||
assert first_job is not None
|
||||
# 关键断言:抬高 priority,避免被同队列剩余 layout FIFO 堵住。
|
||||
assert int(first_job.priority or 0) >= 10
|
||||
assert run.phase == 'waiting_layout'
|
||||
|
||||
layouts[1].status = 'ready'
|
||||
@@ -799,6 +802,7 @@ def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app):
|
||||
assert run.phase == 'queued'
|
||||
assert job is not None
|
||||
assert job.job_type == 'shipping_order_extraction'
|
||||
assert int(job.priority or 0) >= 10
|
||||
|
||||
|
||||
def test_pdf_without_ready_coordinate_layout_is_a_prerequisite_failure(app):
|
||||
|
||||
@@ -690,6 +690,124 @@ def test_profile_matcher_selects_signature_main_table_when_metadata_table_preced
|
||||
assert result.candidates[0].dimension_scores.column_topology >= 0.75
|
||||
|
||||
|
||||
def _header_glyphs_at(*, text: str, y0: float, y1: float, x0: float = 10.0, step: float = 4.0) -> list[dict]:
|
||||
"""在指定纵坐标生成带空格边界的表头字符证据。"""
|
||||
return [
|
||||
{
|
||||
'text': char,
|
||||
'bbox': {'x0': x0 + index * step, 'y0': y0, 'x1': x0 + index * step + 3, 'y1': y1},
|
||||
'boundary_before': 'space' if index and text[index - 1] == ' ' else 'none',
|
||||
}
|
||||
for index, char in enumerate(text)
|
||||
if char != ' '
|
||||
]
|
||||
|
||||
|
||||
def _foxconn_dual_table_layout() -> dict:
|
||||
"""模拟 4210012210:右上角 ORDER DATE KV 小表 + 下方明细表,全页均有 glyphs。"""
|
||||
layout = _layout('PLANT NAME: FACTORY A', header_text='ITEM NO QTY')
|
||||
meta_header = 'ORDER DATE ORDER NO BU CODE CURRENCY'
|
||||
main_header = 'ITEM NO MATERIAL DESCRIPTION UNIT QTY DELIVERY DATE UNIT PRICE TOTAL PRICE'
|
||||
meta_glyphs = _header_glyphs_at(text=meta_header, y0=70, y1=82, x0=120.0)
|
||||
main_glyphs = _header_glyphs_at(text=main_header, y0=150, y1=162, x0=10.0)
|
||||
layout['tables'] = [
|
||||
{
|
||||
'table_id': 'order-meta',
|
||||
'page_no': 1,
|
||||
# 绝对点坐标:与 pages width/height=200/280 一致,贴近真实 MinerU 右上角 KV 表。
|
||||
'bbox': {'x0': 120.0, 'y0': 55.0, 'x1': 195.0, 'y1': 100.0},
|
||||
},
|
||||
{
|
||||
'table_id': 'line-items',
|
||||
'page_no': 1,
|
||||
'bbox': {'x0': 10.0, 'y0': 140.0, 'x1': 190.0, 'y1': 250.0},
|
||||
},
|
||||
]
|
||||
layout['coordinate_evidence']['tables'] = {
|
||||
'order-meta': meta_glyphs,
|
||||
'line-items': main_glyphs,
|
||||
}
|
||||
# 锚点 glyphs + 两表表头均写入页级证据,再现「全页 glyphs 非空」场景。
|
||||
layout['coordinate_evidence']['page_glyphs']['1'] = [
|
||||
*layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')],
|
||||
*meta_glyphs,
|
||||
*main_glyphs,
|
||||
]
|
||||
return layout
|
||||
|
||||
|
||||
def test_profile_matcher_prefers_line_table_when_order_meta_table_precedes_it():
|
||||
"""全页 glyphs 下须按签名表头亲和度选明细表,不能被前置 ORDER DATE KV 小表抢走。"""
|
||||
layout = _foxconn_dual_table_layout()
|
||||
profile = _profile('FOX_MX')
|
||||
profile['definition']['document_match']['required_anchors'] = []
|
||||
main_region = {'x0': 0.05, 'y0': 0.50, 'x1': 0.95, 'y1': 0.90}
|
||||
profile['definition']['table_regions'][0]['region'] = main_region
|
||||
profile['definition']['table_regions'][0]['line_layouts'][0]['region'] = main_region
|
||||
# 签名只在明细表布局上冻结,模拟已发布 FOX MX。
|
||||
sign_layout = _layout('PLANT NAME: FACTORY A', header_text='ITEM NO MATERIAL DESCRIPTION UNIT QTY DELIVERY DATE UNIT PRICE TOTAL PRICE')
|
||||
sign_layout['tables'] = [layout['tables'][1]]
|
||||
sign_layout['coordinate_evidence']['tables'] = {'line-items': layout['coordinate_evidence']['tables']['line-items']}
|
||||
sign_layout['coordinate_evidence']['page_glyphs']['1'] = [
|
||||
*sign_layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')],
|
||||
*layout['coordinate_evidence']['tables']['line-items'],
|
||||
]
|
||||
profile = _with_signature(profile, sign_layout)
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
|
||||
|
||||
# 关键断言:双表全页 glyphs 仍唯一命中明细模板,不得因 KV 小表落到 evidence_insufficient。
|
||||
assert result.status == 'unique_match'
|
||||
assert result.profile_code == 'FOX_MX'
|
||||
assert result.candidates[0].hard_match is True
|
||||
assert 'profile_header_discriminator_conflict' not in result.candidates[0].reason_codes
|
||||
assert 'profile_coordinate_evidence_unavailable' not in result.candidates[0].reason_codes
|
||||
|
||||
|
||||
def test_profile_matcher_does_not_escalate_unrelated_coordinate_unavailable(monkeypatch):
|
||||
"""近亲 header 冲突时,远亲候选的坐标不可用不得把整单抬成 evidence_insufficient。"""
|
||||
from app.services.shipping_notice.document_layout import order_profile_matcher as matcher
|
||||
|
||||
line_layout = _layout(
|
||||
'PLANT NAME: FACTORY A',
|
||||
header_text='ITEM NO MATERIAL DESCRIPTION UNIT QTY',
|
||||
)
|
||||
near = _profile_without_required_anchors('NEAR_TWIN', _layout(
|
||||
header_text='PART NUMBER AMOUNT CURRENCY INVOICE CODE',
|
||||
))
|
||||
far = _profile_without_required_anchors('FAR_EMPTY', _layout(
|
||||
header_text='VENDOR INVOICE TOTAL AMOUNT',
|
||||
))
|
||||
|
||||
real_observe = matcher._observe_layout_features
|
||||
|
||||
def fake_observe(*, signature, **kwargs):
|
||||
"""远亲强制空表头观测,稳定触发 profile_coordinate_evidence_unavailable。"""
|
||||
observed = real_observe(signature=signature, **kwargs)
|
||||
tokens = matcher._signature_identity_header_tokens(signature)
|
||||
atoms = matcher._header_token_atoms([str(item) for item in tokens])
|
||||
if 'vendor' in atoms:
|
||||
return {
|
||||
**observed,
|
||||
'header_tokens': [],
|
||||
'column_centers': [],
|
||||
'column_width_ratios': [],
|
||||
'column_count': 0,
|
||||
}
|
||||
return observed
|
||||
|
||||
monkeypatch.setattr(matcher, '_observe_layout_features', fake_observe)
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[near, far], layout=line_layout)
|
||||
|
||||
# 关键断言:不得因远亲坐标码把整单抬成 evidence_insufficient。
|
||||
assert result.status != 'evidence_insufficient'
|
||||
near_cand = next(item for item in result.candidates if item.profile_code == 'NEAR_TWIN')
|
||||
far_cand = next(item for item in result.candidates if item.profile_code == 'FAR_EMPTY')
|
||||
assert 'profile_header_discriminator_conflict' in near_cand.reason_codes
|
||||
assert 'profile_coordinate_evidence_unavailable' in far_cand.reason_codes
|
||||
|
||||
|
||||
def test_profile_matcher_excludes_below_threshold_hard_candidate_from_uniqueness():
|
||||
"""硬门禁通过但得分或证据覆盖不合格的候选,不得阻塞唯一合格模板。"""
|
||||
layout = _layout('PLANT NAME: FACTORY A')
|
||||
@@ -812,6 +930,207 @@ def _profile_without_required_anchors(code: str, layout: dict) -> dict:
|
||||
return profile
|
||||
|
||||
|
||||
def test_header_token_atoms_ignore_parenthetical_gloss():
|
||||
"""括号印刷注记经统一归一化后不得改变表头原子(不依赖 vat 特判停用词)。"""
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_header_discriminator_atoms_conflict,
|
||||
_header_token_atoms,
|
||||
)
|
||||
|
||||
expected = [
|
||||
'Item', 'Parts No.& Description', 'REV.', 'UNIT', "Q'TY",
|
||||
'Delivery Date', 'Unit', 'Total', 'Price',
|
||||
]
|
||||
observed = [
|
||||
'item 项次', 'parts no.& description 料号', 'rev.', 'unit', "q'ty",
|
||||
'delivery date', 'unit', 'price (vat excluded)', 'total', 'price',
|
||||
]
|
||||
assert _header_token_atoms(expected) == _header_token_atoms(observed)
|
||||
assert 'vat' not in _header_token_atoms(observed)
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature={'table_patterns': [{'header_tokens': expected}]},
|
||||
observed={'header_tokens': observed},
|
||||
) is False
|
||||
# 近亲多出的 ECCN 仍须硬杀。
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature={'table_patterns': [{'header_tokens': expected + ['ECCN']}]},
|
||||
observed={'header_tokens': observed},
|
||||
) is True
|
||||
|
||||
|
||||
def _profile_with_header_band(
|
||||
code: str,
|
||||
layout: dict,
|
||||
*,
|
||||
header_region: dict,
|
||||
required_anchors: bool = True,
|
||||
) -> dict:
|
||||
"""构造带 header_layouts 的 Profile,使签名冻结合法 header_bbox。"""
|
||||
profile = _profile(code)
|
||||
if not required_anchors:
|
||||
profile['definition']['document_match']['required_anchors'] = []
|
||||
bbox = layout['tables'][0]['bbox']
|
||||
table = profile['definition']['table_regions'][0]
|
||||
table['region'] = {
|
||||
'x0': float(bbox['x0']), 'y0': float(bbox['y0']),
|
||||
'x1': float(bbox['x1']), 'y1': float(bbox['y1']),
|
||||
}
|
||||
table['header_layouts'] = [{
|
||||
'layout_id': 'hdr',
|
||||
'region': header_region,
|
||||
'field_regions': [_field_region(region=header_region)],
|
||||
}]
|
||||
# 明细行区必须与表头带不重叠,否则 OrderCoordinateProfile 校验失败。
|
||||
line_region = {
|
||||
'x0': float(bbox['x0']),
|
||||
'y0': float(header_region['y1']),
|
||||
'x1': float(bbox['x1']),
|
||||
'y1': float(bbox['y1']),
|
||||
}
|
||||
table['line_layouts'][0]['region'] = line_region
|
||||
table['line_layouts'][0]['field_regions'] = [_field_region(region=line_region)]
|
||||
return _with_signature(profile, layout)
|
||||
|
||||
|
||||
def test_observe_header_ignores_vat_row_outside_aligned_header_band():
|
||||
"""身份观测不得用表顶宽带读入签名表头框外的 Unit Price (VAT Excluded) 行。"""
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_extract_matching_signature,
|
||||
_header_token_atoms,
|
||||
_observe_layout_features,
|
||||
)
|
||||
|
||||
header_text = 'ITEM NO QTY'
|
||||
layout = _layout(header_text=header_text, bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95})
|
||||
# 表顶 18% 内、但低于紧表头带:放入 VAT 注记行。
|
||||
vat_text = 'Unit Price (VAT Excluded)'
|
||||
vat_glyphs = [
|
||||
{
|
||||
'text': char,
|
||||
'bbox': {'x0': 10 + index * 5, 'y0': 100, 'x1': 14 + index * 5, 'y1': 112},
|
||||
'boundary_before': 'space' if index and vat_text[index - 1] == ' ' else 'none',
|
||||
}
|
||||
for index, char in enumerate(vat_text)
|
||||
if char != ' '
|
||||
]
|
||||
layout['coordinate_evidence']['page_glyphs']['1'].extend(vat_glyphs)
|
||||
header_region = {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.32}
|
||||
profile = _profile_with_header_band('PO_BAND', layout, header_region=header_region)
|
||||
signature_body, _ = _extract_matching_signature(profile)
|
||||
evidence = layout['coordinate_evidence']
|
||||
observed = _observe_layout_features(
|
||||
layout=layout,
|
||||
tables=layout['tables'],
|
||||
pages=evidence['pages'],
|
||||
glyph_tables=evidence['tables'],
|
||||
page_glyphs=evidence['page_glyphs'],
|
||||
signature=signature_body,
|
||||
)
|
||||
atoms = _header_token_atoms([str(item) for item in (observed.get('header_tokens') or [])])
|
||||
# 关键断言:框外 VAT 行不得进入身份原子。
|
||||
assert 'vat' not in atoms
|
||||
assert 'excluded' not in atoms
|
||||
assert 'item' in atoms or 'qty' in atoms
|
||||
|
||||
|
||||
def test_aligned_header_band_unique_match_after_table_delta_y():
|
||||
"""主表相对签名整体下移时,表头框 deltaY 对齐后仍应 unique_match。"""
|
||||
baseline = _layout(
|
||||
header_text='ITEM NO MATERIAL QTY',
|
||||
bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95},
|
||||
)
|
||||
header_region = {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.32}
|
||||
profile = _profile_with_header_band(
|
||||
'PO_SHIFT', baseline, header_region=header_region, required_anchors=False,
|
||||
)
|
||||
|
||||
shifted = _layout(
|
||||
header_text='ITEM NO MATERIAL QTY',
|
||||
bbox={'x0': 0.05, 'y0': 0.40, 'x1': 0.95, 'y1': 0.95},
|
||||
)
|
||||
# 默认表头 glyphs 按 y≈0.27 生成;整体下移与主表顶边一致。
|
||||
# table-1 与 page_glyphs 共享同一 glyph 对象,只平移一次。
|
||||
delta = (0.40 - 0.25) * 280
|
||||
for glyph in shifted['coordinate_evidence']['page_glyphs']['1']:
|
||||
if glyph['bbox']['y0'] >= 50:
|
||||
glyph['bbox']['y0'] += delta
|
||||
glyph['bbox']['y1'] += delta
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=shifted)
|
||||
assert result.status == 'unique_match'
|
||||
assert result.profile_code == 'PO_SHIFT'
|
||||
|
||||
|
||||
def test_in_band_parenthetical_vat_aligns_without_stopwords():
|
||||
"""框内印刷括号注记时仅靠括号归一化与无括号签名对齐(无 vat 停用词)。"""
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_extract_matching_signature,
|
||||
_header_discriminator_atoms_conflict,
|
||||
_header_token_atoms,
|
||||
_observe_layout_features,
|
||||
_signature_identity_header_tokens,
|
||||
)
|
||||
|
||||
clean = _layout(
|
||||
header_text='ITEM Unit Price Total',
|
||||
bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95},
|
||||
)
|
||||
header_region = {'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.34}
|
||||
profile = _profile_with_header_band(
|
||||
'PO_PAREN', clean, header_region=header_region, required_anchors=False,
|
||||
)
|
||||
# 紧凑字形间距,避免长括号注记超出表头带 x 范围被截断。
|
||||
with_gloss = _layout(
|
||||
header_text='ITEM Unit Price (VAT Excluded) Total',
|
||||
bbox={'x0': 0.05, 'y0': 0.25, 'x1': 0.95, 'y1': 0.95},
|
||||
)
|
||||
gloss_text = 'ITEM Unit Price (VAT Excluded) Total'
|
||||
header_glyphs = [
|
||||
{
|
||||
'text': char,
|
||||
'bbox': {'x0': 10 + index * 5, 'y0': 76, 'x1': 13 + index * 5, 'y1': 88},
|
||||
'boundary_before': 'space' if index and gloss_text[index - 1] == ' ' else 'none',
|
||||
}
|
||||
for index, char in enumerate(gloss_text)
|
||||
if char != ' '
|
||||
]
|
||||
with_gloss['coordinate_evidence']['tables']['table-1'] = header_glyphs
|
||||
anchor_glyphs = [
|
||||
glyph for glyph in clean['coordinate_evidence']['page_glyphs']['1']
|
||||
if float(glyph['bbox']['y0']) < 50
|
||||
]
|
||||
with_gloss['coordinate_evidence']['page_glyphs']['1'] = [*anchor_glyphs, *header_glyphs]
|
||||
|
||||
signature_body, _ = _extract_matching_signature(profile)
|
||||
evidence = with_gloss['coordinate_evidence']
|
||||
observed = _observe_layout_features(
|
||||
layout=with_gloss,
|
||||
tables=with_gloss['tables'],
|
||||
pages=evidence['pages'],
|
||||
glyph_tables=evidence['tables'],
|
||||
page_glyphs=evidence['page_glyphs'],
|
||||
signature=signature_body,
|
||||
)
|
||||
expected_tokens = _signature_identity_header_tokens(signature_body)
|
||||
observed_tokens = [str(item) for item in (observed.get('header_tokens') or [])]
|
||||
assert _header_token_atoms(expected_tokens) == _header_token_atoms(observed_tokens)
|
||||
assert 'vat' not in _header_token_atoms(observed_tokens)
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=signature_body, observed=observed,
|
||||
) is False
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_score_header_semantic_position,
|
||||
)
|
||||
header_score = _score_header_semantic_position(
|
||||
signature=signature_body,
|
||||
observed=observed,
|
||||
required_hits=[],
|
||||
enforce_atom_discriminator=True,
|
||||
)
|
||||
assert header_score.state == 'matched'
|
||||
|
||||
|
||||
def test_near_twin_header_discriminator_makes_unique_match():
|
||||
"""无必选锚点的近亲模板仅差表头原子时,须硬互斥成 unique_match。"""
|
||||
mx_header = 'Item Parts No Description REV UNIT QTY Delivery Date Unit Total Price'
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
"""
|
||||
tests/test_shipping_order_profile_matcher_replay.py
|
||||
|
||||
用途:回放本地库历史 unique_match 冻结快照,验证收紧表头身份读取不回归已发布模板。
|
||||
依赖:SQLAlchemy、match_frozen_coordinate_profiles、shipping_order_route_decisions 表。
|
||||
逻辑:只读查询 Run 冻结 input_snapshot_json;无 DB/快照时 skip;失败样本按 profile 汇总。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.engine import Engine
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
match_frozen_coordinate_profiles,
|
||||
)
|
||||
|
||||
_REPLAY_DB_URL = os.environ.get(
|
||||
'HXOPS_PROFILE_REPLAY_DATABASE_URL',
|
||||
os.environ.get('DATABASE_URL', 'postgresql://postgres:postgres@127.0.0.1:5432/hxops_db'),
|
||||
)
|
||||
_MAX_PER_PROFILE = int(os.environ.get('HXOPS_PROFILE_REPLAY_MAX_PER_PROFILE', '20'))
|
||||
_EXTRA_DOC_IDS = {
|
||||
int(item.strip())
|
||||
for item in os.environ.get('HXOPS_PROFILE_REPLAY_DOC_IDS', '194').split(',')
|
||||
if item.strip().isdigit()
|
||||
}
|
||||
|
||||
|
||||
def _can_connect(url: str) -> bool:
|
||||
"""探测回放库是否可连;连不上则整条集成测试 skip。"""
|
||||
try:
|
||||
engine = create_engine(url)
|
||||
with engine.connect() as conn:
|
||||
conn.execute(text('SELECT 1'))
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def replay_engine() -> Engine:
|
||||
"""模块级只读引擎;本地无 hxops_db 时跳过。"""
|
||||
if not _can_connect(_REPLAY_DB_URL):
|
||||
pytest.skip(f'Replay database unavailable: {_REPLAY_DB_URL}')
|
||||
return create_engine(_REPLAY_DB_URL)
|
||||
|
||||
|
||||
def _document_from_snapshot(
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
document_id: int,
|
||||
intake_id: int,
|
||||
) -> dict[str, Any] | None:
|
||||
"""在冻结 intake 列表中定位 document 及其 layout_snapshot。"""
|
||||
for intake in snapshot.get('intakes') or []:
|
||||
if not isinstance(intake, dict) or int(intake.get('intake_id') or 0) != int(intake_id):
|
||||
continue
|
||||
for document in intake.get('documents') or []:
|
||||
if not isinstance(document, dict):
|
||||
continue
|
||||
if int(document.get('document_id') or 0) == int(document_id):
|
||||
return document
|
||||
return None
|
||||
|
||||
|
||||
def _layout_ready(layout: dict[str, Any] | None) -> bool:
|
||||
"""layout 须 ready 且具备 matcher 所需坐标证据。"""
|
||||
if not isinstance(layout, dict) or layout.get('status') != 'ready':
|
||||
return False
|
||||
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 {}
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
return bool(pages and (page_glyphs or glyph_tables or tables))
|
||||
|
||||
|
||||
def _frozen_profiles(snapshot: dict[str, Any], *, schema_version_id: int) -> list[dict[str, Any]]:
|
||||
"""与 Worker 一致:仅取与 Run schema_version_id 对齐的冻结模板。"""
|
||||
profiles = snapshot.get('order_document_profiles')
|
||||
if not isinstance(profiles, list):
|
||||
profiles = snapshot.get('profiles') if isinstance(snapshot.get('profiles'), list) else []
|
||||
return [
|
||||
item for item in profiles
|
||||
if isinstance(item, dict)
|
||||
and int(item.get('schema_version_id') or 0) == int(schema_version_id)
|
||||
]
|
||||
|
||||
|
||||
def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取 unique_match 路由样本;每个 profile_code 最多保留最近 N 条。
|
||||
|
||||
Returns:
|
||||
含 route/run/unit/document/profile 期望字段的字典列表。
|
||||
"""
|
||||
query = text("""
|
||||
SELECT
|
||||
r.id AS route_id,
|
||||
r.run_id,
|
||||
r.unit_id,
|
||||
r.selected_profile_code,
|
||||
r.selected_profile_version,
|
||||
r.selected_profile_checksum,
|
||||
run.input_snapshot_json,
|
||||
run.schema_version_id,
|
||||
u.document_id,
|
||||
u.intake_id
|
||||
FROM shipping_order_route_decisions r
|
||||
JOIN shipping_order_processing_runs run ON run.id = r.run_id
|
||||
JOIN shipping_order_processing_units u ON u.id = r.unit_id
|
||||
WHERE r.match_status = 'unique_match'
|
||||
AND r.selected_profile_code IS NOT NULL
|
||||
AND run.input_snapshot_json IS NOT NULL
|
||||
ORDER BY r.selected_profile_code ASC, r.id DESC
|
||||
""")
|
||||
rows: list[dict[str, Any]] = []
|
||||
per_profile: dict[str, int] = defaultdict(int)
|
||||
with engine.connect() as conn:
|
||||
for row in conn.execute(query).mappings():
|
||||
code = str(row['selected_profile_code'] or '')
|
||||
if per_profile[code] >= _MAX_PER_PROFILE:
|
||||
continue
|
||||
snapshot = row['input_snapshot_json']
|
||||
if isinstance(snapshot, str):
|
||||
snapshot = json.loads(snapshot)
|
||||
if not isinstance(snapshot, dict):
|
||||
continue
|
||||
document = _document_from_snapshot(
|
||||
snapshot,
|
||||
document_id=int(row['document_id'] or 0),
|
||||
intake_id=int(row['intake_id'] or 0),
|
||||
)
|
||||
layout = document.get('layout_snapshot') if isinstance(document, dict) else None
|
||||
if not _layout_ready(layout if isinstance(layout, dict) else None):
|
||||
continue
|
||||
profiles = _frozen_profiles(snapshot, schema_version_id=int(row['schema_version_id'] or 0))
|
||||
if not profiles:
|
||||
continue
|
||||
per_profile[code] += 1
|
||||
rows.append({
|
||||
'route_id': int(row['route_id']),
|
||||
'run_id': int(row['run_id']),
|
||||
'unit_id': int(row['unit_id']),
|
||||
'document_id': int(row['document_id']),
|
||||
'expected_profile_code': code,
|
||||
'expected_profile_version': int(row['selected_profile_version'] or 0),
|
||||
'expected_profile_checksum': str(row['selected_profile_checksum'] or ''),
|
||||
'profiles': profiles,
|
||||
'layout': layout,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def test_replay_published_unique_match_snapshots(replay_engine: Engine) -> None:
|
||||
"""历史 unique_match 样本回放后仍应命中同一 profile(收紧表头带回归门禁)。"""
|
||||
samples = _load_replay_samples(replay_engine)
|
||||
if not samples:
|
||||
pytest.skip('No replayable unique_match snapshots in database')
|
||||
|
||||
failures: list[str] = []
|
||||
summary: dict[str, dict[str, int]] = defaultdict(lambda: {'pass': 0, 'fail': 0})
|
||||
|
||||
for sample in samples:
|
||||
code = sample['expected_profile_code']
|
||||
result = match_frozen_coordinate_profiles(
|
||||
profiles=sample['profiles'],
|
||||
layout=sample['layout'],
|
||||
)
|
||||
ok = (
|
||||
result.status == 'unique_match'
|
||||
and result.profile_code == sample['expected_profile_code']
|
||||
and (
|
||||
not sample['expected_profile_version']
|
||||
or int(result.version or 0) == int(sample['expected_profile_version'])
|
||||
)
|
||||
)
|
||||
if ok:
|
||||
summary[code]['pass'] += 1
|
||||
else:
|
||||
summary[code]['fail'] += 1
|
||||
failures.append(
|
||||
f"{code} route={sample['route_id']} run={sample['run_id']} "
|
||||
f"doc={sample['document_id']}: expected {sample['expected_profile_code']}"
|
||||
f"/v{sample['expected_profile_version']}, got {result.status}"
|
||||
f"/{result.profile_code}/v{result.version}"
|
||||
)
|
||||
|
||||
if failures:
|
||||
lines = [
|
||||
'Published unique_match replay failures:',
|
||||
*[f' - {item}' for item in failures[:50]],
|
||||
'Per-profile summary:',
|
||||
]
|
||||
for profile_code, counts in sorted(summary.items()):
|
||||
lines.append(f' {profile_code}: pass={counts["pass"]} fail={counts["fail"]}')
|
||||
pytest.fail('\n'.join(lines))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('document_id', sorted(_EXTRA_DOC_IDS))
|
||||
def test_replay_specific_document_rematch_after_header_band(replay_engine: Engine, document_id: int) -> None:
|
||||
"""
|
||||
对指定 document(默认 194 / 4210012210)用最新 Run 冻结快照重匹配。
|
||||
|
||||
历史路由可能失败;本断言验证收紧表头带后应 FOX MX unique_match。
|
||||
"""
|
||||
query = text("""
|
||||
SELECT
|
||||
run.id AS run_id,
|
||||
run.input_snapshot_json,
|
||||
run.schema_version_id,
|
||||
u.document_id,
|
||||
u.intake_id
|
||||
FROM shipping_order_processing_units u
|
||||
JOIN shipping_order_processing_plans p ON p.id = u.plan_id
|
||||
JOIN shipping_order_processing_runs run ON run.id = p.run_id
|
||||
WHERE u.document_id = :document_id
|
||||
ORDER BY run.id DESC
|
||||
LIMIT 1
|
||||
""")
|
||||
with replay_engine.connect() as conn:
|
||||
row = conn.execute(query, {'document_id': document_id}).mappings().first()
|
||||
if row is None:
|
||||
pytest.skip(f'No processing run for document_id={document_id}')
|
||||
|
||||
snapshot = row['input_snapshot_json']
|
||||
if isinstance(snapshot, str):
|
||||
snapshot = json.loads(snapshot)
|
||||
document = _document_from_snapshot(
|
||||
snapshot,
|
||||
document_id=int(row['document_id']),
|
||||
intake_id=int(row['intake_id']),
|
||||
)
|
||||
layout = document.get('layout_snapshot') if isinstance(document, dict) else None
|
||||
if not _layout_ready(layout if isinstance(layout, dict) else None):
|
||||
pytest.skip(f'Layout not replayable for document_id={document_id}')
|
||||
|
||||
profiles = _frozen_profiles(snapshot, schema_version_id=int(row['schema_version_id'] or 0))
|
||||
result = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
|
||||
assert result.status == 'unique_match'
|
||||
if document_id == 194:
|
||||
assert result.profile_code == 'ODP-20260824-2C542346805B'
|
||||
else:
|
||||
assert result.profile_code
|
||||
@@ -74,6 +74,67 @@ def test_same_input_produces_same_checksum():
|
||||
assert signature_checksum(first['signature']) == first['signature_checksum']
|
||||
|
||||
|
||||
def test_layout_signature_excludes_line_field_supplement_table_patterns():
|
||||
"""
|
||||
补充表不得进入匹配签名 table_patterns。
|
||||
|
||||
关键断言:即便补充区样本含料号行文案,签名 identity 也只保留 business_lines,
|
||||
避免 line_field_supplement 污染表头原子硬互斥。
|
||||
"""
|
||||
definition = _minimal_definition()
|
||||
definition['table_regions'][0]['region_role'] = 'business_lines'
|
||||
definition['table_regions'][0]['region'] = {'x0': 0, 'y0': 0.2, 'x1': 1, 'y1': 0.55}
|
||||
definition['table_regions'][0]['line_layouts'][0]['region'] = {
|
||||
'x0': 0, 'y0': 0.35, 'x1': 1, 'y1': 0.55,
|
||||
}
|
||||
definition['table_regions'].append({
|
||||
'region_id': 'line_supplement',
|
||||
'region_role': 'line_field_supplement',
|
||||
'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9},
|
||||
'line_layouts': [{
|
||||
'layout_id': 'supp_main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{
|
||||
'field_id': 'supp-ln',
|
||||
'field_code': 'customer_po_line_no',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0.05, 'y0': 0.1, 'x1': 0.2, 'y1': 0.4},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'supp-pn',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0.25, 'y0': 0.1, 'x1': 0.8, 'y1': 0.4},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
],
|
||||
}],
|
||||
})
|
||||
layout = _sample_layout(header_text='ITEM NO QTY')
|
||||
# 补充表区高度内放入料号正文,模拟 HYVE 脏表头污染场景。
|
||||
dirty = 'WTP-B3-A08AR11000001 CN,TH,JP'
|
||||
for index, char in enumerate(dirty):
|
||||
layout['coordinate_evidence']['page_glyphs']['1'].append({
|
||||
'text': char,
|
||||
'bbox': {'x0': 10 + index * 3, 'y0': 190, 'x1': 12 + index * 3, 'y1': 202},
|
||||
})
|
||||
|
||||
snapshot = build_layout_signature(definition=definition, sample_layouts=[layout])
|
||||
patterns = snapshot['signature']['table_patterns']
|
||||
region_ids = [item.get('region_id') for item in patterns]
|
||||
assert region_ids == ['lines']
|
||||
joined = ' '.join(
|
||||
str(token)
|
||||
for pattern in patterns
|
||||
for token in (pattern.get('header_tokens') or [])
|
||||
).upper()
|
||||
assert 'WTP-B3-A08AR11000001' not in joined
|
||||
assert 'CN,TH,JP' not in joined
|
||||
|
||||
|
||||
|
||||
def test_different_samples_produce_different_checksum():
|
||||
"""不同表头样本应产生不同 checksum。"""
|
||||
definition = _minimal_definition()
|
||||
|
||||
Reference in new issue
Block a user