feat(shipping-notice): 完善订单模板解析与库存 RPA 调度流程
- 新增行字段补充合并与订单模板匹配能力 - 优化运行时解析策略、签名校验及资料验证 - 完善库存 RPA 归档、收尾与 Worker 启动流程 - 补充前后端测试、多语言文案及功能文档
This commit is contained in:
1 parent
8f2f568f92
commit
dabf140e41
45 files changed
+2007
-151
No files matched your search
@@ -323,6 +323,57 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
assert not (failed_dir / trigger_path.name).exists()
|
||||
|
||||
|
||||
def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tmp_path):
|
||||
"""配置测试无订单 Attempt/Gate 身份:不得 trigger_identity_invalid,须回调专用 ready。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
drop_dir = tmp_path / "drop"
|
||||
processed_dir = trigger_dir / "processed"
|
||||
failed_dir = trigger_dir / "failed"
|
||||
trigger_dir.mkdir()
|
||||
drop_dir.mkdir()
|
||||
run_no = "CONFIG-DSV360_AWSBI_BYAWSPRD01-20260909020428918536"
|
||||
trigger_path = trigger_dir / f"inventory_export_batch_{run_no}.json"
|
||||
# 与 inventory_configuration_test.start_test_export 写入形状一致:
|
||||
# trigger_type=configuration_test,无 task_no / gate_id / execution_id 等生产身份。
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no,
|
||||
"trigger_type": "configuration_test",
|
||||
"configuration_test_run_id": 42,
|
||||
"requested_at": "2026-09-09T02:04:28.918536",
|
||||
"inventory_sources": [{
|
||||
"source_code": "DSV360_AWSBI_BYAWSPRD01",
|
||||
"connector_type": "dbs",
|
||||
"worker_connector_type": "dsv360",
|
||||
"warehouse_id": "BYAWSPRD01",
|
||||
"login_url": "https://s360.dbschenker.com/",
|
||||
"entry_url": "https://s360.dbschenker.com/",
|
||||
"navigation": {},
|
||||
"parameters": [],
|
||||
"query": {},
|
||||
"credential_envelope": {},
|
||||
}],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert not any(body.get("error_code") == "trigger_identity_invalid" for _, body in callbacks)
|
||||
ready = next(body for path, body in callbacks if path.endswith("/inventory-configuration-test-ready"))
|
||||
assert ready["run_no"] == run_no
|
||||
assert ready["status"] == "success"
|
||||
assert ready.get("file_path")
|
||||
assert not any(path.endswith("/inventory-batch-ready") for path, _ in callbacks)
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
assert not (failed_dir / trigger_path.name).exists()
|
||||
|
||||
|
||||
def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup(monkeypatch, tmp_path):
|
||||
"""Ctrl+C 中断导出时不回调或移动 trigger,且清理异常不能阻止停止 Playwright。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
"""
|
||||
tests/test_line_field_supplement_merge.py
|
||||
|
||||
用途:覆盖同文档 COO/明细字段补充表按 LN 合并的契约。
|
||||
依赖:line_field_supplement_merge、order_profile.TableRegionProfile、
|
||||
order_extraction_workflow._pick_overlapping_layout_table。
|
||||
逻辑:断言空补、前缀补全、冲突不覆盖、LN 歧义/缺失与禁止改 qty;
|
||||
成功补齐仅表级 reasons、不写入 issues;以及补充区与 MinerU 表重叠时的物理表选取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile import TableRegionProfile
|
||||
from app.services.shipping_notice.line_field_supplement_merge import (
|
||||
REASON_APPLIED,
|
||||
REASON_CONFLICT,
|
||||
REASON_LN_AMBIGUOUS,
|
||||
merge_line_field_supplement,
|
||||
normalize_line_start_key,
|
||||
normalize_part_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_pick_overlapping_layout_table,
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_line_start_and_part_values():
|
||||
"""关键断言:行号去前导零对齐;料号仅去空白。"""
|
||||
assert normalize_line_start_key(' 02 ') == '2'
|
||||
assert normalize_line_start_key('00010') == '10'
|
||||
assert normalize_part_value('WTP-B3- A08') == 'WTP-B3-A08'
|
||||
|
||||
|
||||
def test_merge_fills_empty_and_prefix_without_touching_qty():
|
||||
"""空值直补、截断前缀补全,数量保持主表原值。"""
|
||||
main = [
|
||||
{'customer_po_line_no': '1', 'customer_part_number': '', 'part_number': 'B3-', 'qty': '30'},
|
||||
{
|
||||
'customer_po_line_no': '2',
|
||||
'customer_part_number': 'WTP-B3-',
|
||||
'part_number': '',
|
||||
'qty': '3',
|
||||
},
|
||||
]
|
||||
supplement = [
|
||||
{
|
||||
'customer_po_line_no': '1',
|
||||
'customer_part_number': 'WTP-B3-A08AR11000001',
|
||||
'part_number': 'B3-A08AR11000001',
|
||||
},
|
||||
{
|
||||
'customer_po_line_no': '2',
|
||||
'customer_part_number': 'WTP-B3-A08AR10000017-A6',
|
||||
'part_number': 'B3-A08AR10000017-A6',
|
||||
},
|
||||
]
|
||||
|
||||
merged, reasons = merge_line_field_supplement(main, supplement)
|
||||
|
||||
assert merged[0]['customer_part_number'] == 'WTP-B3-A08AR11000001'
|
||||
assert merged[0]['part_number'] == 'B3-A08AR11000001'
|
||||
assert merged[0]['qty'] == '30'
|
||||
assert merged[1]['customer_part_number'] == 'WTP-B3-A08AR10000017-A6'
|
||||
assert merged[1]['part_number'] == 'B3-A08AR10000017-A6'
|
||||
assert merged[1]['qty'] == '3'
|
||||
assert REASON_APPLIED in reasons
|
||||
assert REASON_CONFLICT not in reasons
|
||||
# 关键断言:成功补齐不得进入行 issues,否则正式建单会被误判为 row_needs_review。
|
||||
assert REASON_APPLIED not in (merged[0].get('issues') or [])
|
||||
assert REASON_APPLIED not in (merged[1].get('issues') or [])
|
||||
|
||||
|
||||
def test_merge_conflict_does_not_overwrite():
|
||||
"""两边完整且不同时保留主表并记冲突。"""
|
||||
main = [{'customer_po_line_no': '1', 'part_number': 'MAIN-ONLY', 'qty': '1'}]
|
||||
supplement = [{'customer_po_line_no': '1', 'part_number': 'COO-OTHER'}]
|
||||
|
||||
merged, reasons = merge_line_field_supplement(main, supplement)
|
||||
|
||||
assert merged[0]['part_number'] == 'MAIN-ONLY'
|
||||
assert merged[0]['qty'] == '1'
|
||||
assert REASON_CONFLICT in reasons
|
||||
assert REASON_CONFLICT in merged[0]['issues']
|
||||
|
||||
|
||||
def test_merge_skips_ambiguous_line_numbers():
|
||||
"""主表或补充表 LN 重复时不补该键。"""
|
||||
main = [
|
||||
{'customer_po_line_no': '1', 'part_number': ''},
|
||||
{'customer_po_line_no': '1', 'part_number': ''},
|
||||
]
|
||||
supplement = [{'customer_po_line_no': '1', 'part_number': 'B3-A08'}]
|
||||
|
||||
merged, reasons = merge_line_field_supplement(main, supplement)
|
||||
|
||||
assert merged[0]['part_number'] == ''
|
||||
assert merged[1]['part_number'] == ''
|
||||
assert REASON_LN_AMBIGUOUS in reasons
|
||||
|
||||
|
||||
def test_merge_workflow_shaped_rows():
|
||||
"""workflow fields 列表形态同样可补齐。"""
|
||||
main = [{
|
||||
'status': 'needs_review',
|
||||
'fields': [
|
||||
{'field_code': 'customer_po_line_no', 'value': '2'},
|
||||
{'field_code': 'customer_part_number', 'value': 'WTP-B3-'},
|
||||
{'field_code': 'qty', 'value': '3'},
|
||||
],
|
||||
'issues': [],
|
||||
}]
|
||||
supplement = [{
|
||||
'fields': [
|
||||
{'field_code': 'customer_po_line_no', 'value': '2'},
|
||||
{'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'},
|
||||
{'field_code': 'part_number', 'value': 'B3-A08AR10000017-A6'},
|
||||
],
|
||||
}]
|
||||
|
||||
merged, reasons = merge_line_field_supplement(main, supplement)
|
||||
values = {item['field_code']: item['value'] for item in merged[0]['fields']}
|
||||
|
||||
assert values['customer_part_number'] == 'WTP-B3-A08AR10000017-A6'
|
||||
assert values['part_number'] == 'B3-A08AR10000017-A6'
|
||||
assert values['qty'] == '3'
|
||||
assert REASON_APPLIED in reasons
|
||||
assert REASON_APPLIED not in (merged[0].get('issues') or [])
|
||||
|
||||
|
||||
def test_apply_line_field_supplement_uses_reconstructed_coo_rows(monkeypatch):
|
||||
"""关键断言:正式路径在主表截断后用补充表重建行补全料号。"""
|
||||
from app.services.shipping_notice import order_extraction_workflow as workflow
|
||||
|
||||
def _fake_reconstruct(**_kwargs):
|
||||
return (
|
||||
[{
|
||||
'fields': [
|
||||
{'field_code': 'customer_po_line_no', 'value': '2'},
|
||||
{'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'},
|
||||
{'field_code': 'part_number', 'value': 'B3-A08AR10000017-A6'},
|
||||
],
|
||||
'issues': [],
|
||||
}],
|
||||
'customer_po_line_no',
|
||||
)
|
||||
|
||||
monkeypatch.setattr(workflow, '_reconstruct_line_field_supplement_rows', _fake_reconstruct)
|
||||
parsed = [{
|
||||
'status': 'parsed',
|
||||
'fields': [
|
||||
{'field_code': 'customer_po_line_no', 'value': '2'},
|
||||
{'field_code': 'customer_part_number', 'value': 'WTP-B3-'},
|
||||
{'field_code': 'part_number', 'value': ''},
|
||||
{'field_code': 'qty', 'value': '3'},
|
||||
],
|
||||
'issues': [],
|
||||
}]
|
||||
merged, reasons = workflow._apply_line_field_supplement(
|
||||
raw_profile={'definition': {}},
|
||||
layout={},
|
||||
parsed_rows=parsed,
|
||||
schema_fields={},
|
||||
)
|
||||
values = {item['field_code']: item['value'] for item in merged[0]['fields']}
|
||||
assert values['customer_part_number'] == 'WTP-B3-A08AR10000017-A6'
|
||||
assert values['part_number'] == 'B3-A08AR10000017-A6'
|
||||
assert values['qty'] == '3'
|
||||
assert REASON_APPLIED in reasons
|
||||
|
||||
|
||||
def test_project_supplement_onto_validation_evidence():
|
||||
"""关键断言:验证证据 lines 可被 COO 补齐且保留其它列。"""
|
||||
from app.services.shipping_notice.line_field_supplement_merge import (
|
||||
project_line_field_supplement_onto_validation_evidence,
|
||||
)
|
||||
|
||||
evidence = {
|
||||
'header_fields': [],
|
||||
'lines': [{
|
||||
'row_index': 0,
|
||||
'fields': [
|
||||
{'field_code': 'customer_po_line_no', 'raw_value': '2', 'normalized_value': '2', 'status': 'passed', 'issues': []},
|
||||
{'field_code': 'customer_part_number', 'raw_value': 'WTP-B3-', 'normalized_value': 'WTP-B3-', 'status': 'passed', 'issues': []},
|
||||
{'field_code': 'qty', 'raw_value': '3', 'normalized_value': '3', 'status': 'passed', 'issues': []},
|
||||
],
|
||||
}],
|
||||
'cross_checks': {},
|
||||
}
|
||||
updated, reasons = project_line_field_supplement_onto_validation_evidence(
|
||||
evidence,
|
||||
supplement_rows=[{
|
||||
'fields': [
|
||||
{'field_code': 'customer_po_line_no', 'value': '2'},
|
||||
{'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR10000017-A6'},
|
||||
],
|
||||
}],
|
||||
)
|
||||
part = next(item for item in updated['lines'][0]['fields'] if item['field_code'] == 'customer_part_number')
|
||||
qty = next(item for item in updated['lines'][0]['fields'] if item['field_code'] == 'qty')
|
||||
assert part['raw_value'] == 'WTP-B3-A08AR10000017-A6'
|
||||
assert qty['raw_value'] == '3'
|
||||
assert REASON_APPLIED in reasons
|
||||
|
||||
|
||||
def test_line_field_supplement_region_rejects_non_part_bindings():
|
||||
"""补充表绑定数量等业务字段必须失败。"""
|
||||
payload = {
|
||||
'region_id': 'coo_lines',
|
||||
'page_scope': 'exact_page',
|
||||
'page_no': 1,
|
||||
'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9},
|
||||
'region_role': 'line_field_supplement',
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{
|
||||
'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line',
|
||||
'region': {'x0': .2, 'y0': 0, 'x1': .4, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
],
|
||||
}],
|
||||
}
|
||||
with pytest.raises(ValidationError, match='line_field_supplement may only bind'):
|
||||
TableRegionProfile.model_validate(payload)
|
||||
|
||||
|
||||
def test_line_field_supplement_region_accepts_part_bindings():
|
||||
"""补充表仅绑 LN + 料号字段可通过。"""
|
||||
region = TableRegionProfile.model_validate({
|
||||
'region_id': 'coo_lines',
|
||||
'page_scope': 'exact_page',
|
||||
'page_no': 1,
|
||||
'region': {'x0': 0, 'y0': 0.6, 'x1': 1, 'y1': 0.9},
|
||||
'region_role': 'line_field_supplement',
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{
|
||||
'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'cpn', 'field_code': 'customer_part_number', 'scope': 'line',
|
||||
'region': {'x0': .2, 'y0': 0, 'x1': .6, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'pn', 'field_code': 'part_number', 'scope': 'line',
|
||||
'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
],
|
||||
}],
|
||||
})
|
||||
assert region.region_role == 'line_field_supplement'
|
||||
|
||||
|
||||
def test_pick_overlapping_layout_table_prefers_max_vertical_overlap():
|
||||
"""关键断言:同页重叠表取纵向重叠面积最大者;无重叠返回空。"""
|
||||
page_size = {'width': 100.0, 'height': 100.0}
|
||||
region = {'x0': 0.05, 'y0': 0.67, 'x1': 0.9, 'y1': 0.70}
|
||||
tables = [
|
||||
{
|
||||
'table_id': 'header-ish',
|
||||
'page_no': 1,
|
||||
'bbox': {'x0': 5.0, 'y0': 10.0, 'x1': 90.0, 'y1': 40.0},
|
||||
},
|
||||
{
|
||||
'table_id': 'coo-table',
|
||||
'page_no': 1,
|
||||
'bbox': {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0},
|
||||
},
|
||||
{
|
||||
'table_id': 'other-page',
|
||||
'page_no': 2,
|
||||
'bbox': {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0},
|
||||
},
|
||||
]
|
||||
|
||||
table_id, bbox = _pick_overlapping_layout_table(
|
||||
layout_tables=tables,
|
||||
page_no=1,
|
||||
region_relative=region,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
assert table_id == 'coo-table'
|
||||
assert bbox == {'x0': 5.0, 'y0': 66.0, 'x1': 90.0, 'y1': 78.0}
|
||||
|
||||
empty_id, empty_bbox = _pick_overlapping_layout_table(
|
||||
layout_tables=tables,
|
||||
page_no=1,
|
||||
region_relative={'x0': 0.05, 'y0': 0.90, 'x1': 0.9, 'y1': 0.95},
|
||||
page_size=page_size,
|
||||
)
|
||||
assert empty_id is None
|
||||
assert empty_bbox is None
|
||||
@@ -64,6 +64,18 @@ def _two_page_layout() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def test_approved_pdf_ignores_line_field_supplement_applied_issue():
|
||||
"""关键断言:COO 成功补齐的审计码不得触发 row_needs_review。"""
|
||||
row = _row('PO-1', 'P-1')
|
||||
row['issues'] = ['line_field_supplement_applied']
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=DEFINITION, table={'rows': [row]},
|
||||
)
|
||||
assert reason is None
|
||||
assert len(orders or []) == 1
|
||||
|
||||
|
||||
def test_approved_pdf_rejects_multiple_pos_in_one_pdf():
|
||||
"""同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
|
||||
@@ -12,6 +12,7 @@ import json
|
||||
import zipfile
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -27,8 +28,10 @@ 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_result_excel_name,
|
||||
persist_inventory_rpa_raw_zip_archive,
|
||||
resolve_inventory_raw_zip_download,
|
||||
_build_zip_entry_name,
|
||||
)
|
||||
from tests.conftest import parse_api_error
|
||||
from tests.test_shipping_notice_inventory_schedule import _make_inventory_schedule_task
|
||||
@@ -160,10 +163,12 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p
|
||||
with zipfile.ZipFile(zip_path) as archive:
|
||||
names = archive.namelist()
|
||||
assert "manifest.json" in names
|
||||
assert any(name.endswith(".xlsx") for name in names)
|
||||
xlsx_names = [name for name in names if name.endswith(".xlsx")]
|
||||
assert xlsx_names == ["001_DSV360_AWSBI_BYAWSCMH01.xlsx"]
|
||||
manifest = json.loads(archive.read("manifest.json").decode("utf-8"))
|
||||
assert manifest["run_no"] == run.run_no
|
||||
assert manifest["files"][0]["inventory_file_no"] == "SIF-20260710-ARCH01"
|
||||
assert manifest["files"][0]["file_name"] == "001_DSV360_AWSBI_BYAWSCMH01.xlsx"
|
||||
|
||||
|
||||
def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
|
||||
@@ -230,7 +235,9 @@ def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path)
|
||||
|
||||
zip_path, file_name = resolve_inventory_raw_zip_download(run)
|
||||
assert zip_path.is_file()
|
||||
assert file_name == inventory_raw_zip_download_name(run.run_no)
|
||||
assert file_name == inventory_raw_zip_download_name(run)
|
||||
assert file_name.endswith("-库存.zip")
|
||||
assert file_name.startswith("库存RPA-")
|
||||
|
||||
|
||||
def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app):
|
||||
@@ -431,7 +438,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
|
||||
task.notify_enabled = True
|
||||
task.notify_user_ids_json = [user.id]
|
||||
run.excel_file_data = b"schedule excel"
|
||||
run.excel_file_name = "schedule.xlsx"
|
||||
run.excel_file_name = inventory_rpa_result_excel_name(run)
|
||||
db.session.commit()
|
||||
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
@@ -442,8 +449,8 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
|
||||
assert "run_id=" in captured[0]
|
||||
assert "raw_zip=1" in captured[0]
|
||||
assert "download=inventory_raw_zip" in captured[0]
|
||||
assert "schedule.xlsx" in media_uploads
|
||||
assert inventory_raw_zip_download_name("RUN-ARCH-NOTIFY-1") in media_uploads
|
||||
assert any(name.endswith("-结果.xlsx") for name in media_uploads)
|
||||
assert any(name.endswith("-库存.zip") for name in media_uploads)
|
||||
assert file_sends == ["media-1", "media-2"]
|
||||
|
||||
|
||||
@@ -471,7 +478,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
|
||||
admin_jwt_headers,
|
||||
tmp_path,
|
||||
):
|
||||
"""admin 鉴权通过时应返回 application/zip 且文件名与 run_no 一致。"""
|
||||
"""admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
@@ -497,7 +504,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
|
||||
run.response_summary_json = persist_inventory_rpa_raw_zip_archive(run)
|
||||
db.session.commit()
|
||||
run_id = run.id
|
||||
expected_name = inventory_raw_zip_download_name(run.run_no)
|
||||
expected_name = inventory_raw_zip_download_name(run)
|
||||
|
||||
res = client.get(
|
||||
f'/api/admin/schedule-runs/{run_id}/inventory-raw-zip',
|
||||
@@ -505,12 +512,36 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.mimetype == 'application/zip'
|
||||
assert expected_name in res.headers.get('Content-Disposition', '')
|
||||
# Werkzeug ASCII filename 会剥掉中文;真实下载名在 filename*=UTF-8'' 段。
|
||||
disposition = res.headers.get('Content-Disposition', '')
|
||||
assert quote(expected_name) in disposition
|
||||
|
||||
with zipfile.ZipFile(BytesIO(res.data)) as archive:
|
||||
names = archive.namelist()
|
||||
assert 'manifest.json' in names
|
||||
assert any(name.endswith('.xlsx') for name in names)
|
||||
assert '001_DSV360_AWSBI_BYAWSCMH01.xlsx' in names
|
||||
|
||||
|
||||
def test_build_zip_entry_name_prefers_source_code():
|
||||
"""包内条目优先 source_code;无 source 时才回退仓码。"""
|
||||
assert _build_zip_entry_name(
|
||||
index=2,
|
||||
source_code="DSV360_AWSBI_BYAWSCMH01",
|
||||
warehouse_id="BYAWSCMH01",
|
||||
original_suffix=".xlsx",
|
||||
) == "002_DSV360_AWSBI_BYAWSCMH01.xlsx"
|
||||
assert _build_zip_entry_name(
|
||||
index=1,
|
||||
source_code="CRANE_FOOTPRINT",
|
||||
warehouse_id="unknown",
|
||||
original_suffix=".xlsx",
|
||||
) == "001_CRANE_FOOTPRINT.xlsx"
|
||||
assert _build_zip_entry_name(
|
||||
index=3,
|
||||
source_code="",
|
||||
warehouse_id="AWSSG",
|
||||
original_suffix=".xlsx",
|
||||
) == "003_AWSSG.xlsx"
|
||||
|
||||
|
||||
def test_get_inventory_raw_zip_returns_404_when_archive_unavailable(
|
||||
|
||||
@@ -84,6 +84,18 @@ def test_reservation_region_maps_line_when_reservation_label_and_line_number_are
|
||||
}]
|
||||
|
||||
|
||||
def test_reservation_region_maps_hyve_l_hash_abbreviation_to_line():
|
||||
"""关键断言:Hyve ``Reservation L#1: 1000153133`` 必须归明细行,不得写入单头。"""
|
||||
assert extract_reservation_from_region_text("Reservation L#1: 1000153133") == [{
|
||||
'value': '1000153133', 'line_no': 1, 'scope': 'line',
|
||||
'raw_text': 'Reservation L#1: 1000153133', 'status': 'mapped',
|
||||
}]
|
||||
assert extract_reservation_from_region_text("Reservation LN#2: 1000153134") == [{
|
||||
'value': '1000153134', 'line_no': 2, 'scope': 'line',
|
||||
'raw_text': 'Reservation LN#2: 1000153134', 'status': 'mapped',
|
||||
}]
|
||||
|
||||
|
||||
def test_reservation_region_assigns_reservation_without_line_to_header():
|
||||
"""无行号 Reservation 是整单事实,写 Header 后由既有回退规则应用给全部明细。"""
|
||||
assert extract_reservation_from_region_text("MDW hub order.Reservation#33008") == [{
|
||||
|
||||
@@ -836,6 +836,89 @@ def test_near_twin_header_discriminator_makes_unique_match():
|
||||
assert 'profile_header_discriminator_conflict' in mx_on_tw.reason_codes
|
||||
|
||||
|
||||
def test_single_logical_header_wrap_pollution_sanitized_for_identity():
|
||||
"""单逻辑表头旧签名含折行副标签时,须并入所属列后再比身份(文案保留)。"""
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
merge_header_identity_wrap_tokens,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_header_discriminator_atoms_conflict,
|
||||
_signature_identity_header_tokens,
|
||||
)
|
||||
|
||||
# Hyve 旧签名:主行 + 折行副标签 Vendor Item# / Date(centers 回退)。
|
||||
signature = {
|
||||
'table_patterns': [{
|
||||
'header_row_count': 1,
|
||||
'header_tokens': [
|
||||
'LN', 'Quantity', 'Part', 'Number', 'Description',
|
||||
'Requested Arrival', 'Unit', 'Price', 'Extension', 'Vendor Item#', 'Date',
|
||||
],
|
||||
'column_centers': [
|
||||
0.0727, 0.1372, 0.2144, 0.2542, 0.3671, 0.561, 0.6532, 0.6841, 0.801,
|
||||
0.2418, 0.5217,
|
||||
],
|
||||
}],
|
||||
}
|
||||
identity = _signature_identity_header_tokens(signature)
|
||||
joined = ' '.join(identity)
|
||||
# 关键断言:副标签文案仍在;不再作为独立尾列。
|
||||
assert 'Vendor Item#' in joined
|
||||
assert 'Date' in joined
|
||||
assert identity[-1] != 'Date'
|
||||
assert identity[-1] != 'Vendor Item#'
|
||||
assert len(identity) == 9
|
||||
|
||||
observed_tokens, observed_centers, _ = merge_header_identity_wrap_tokens(
|
||||
[
|
||||
'ln', 'quantity', 'part', 'number', 'description',
|
||||
'requested arrival', 'unit', 'price', 'extension', 'vendor item#', 'date',
|
||||
],
|
||||
[
|
||||
0.0727, 0.1372, 0.2144, 0.2542, 0.3671, 0.561, 0.6532, 0.6841, 0.801,
|
||||
0.2418, 0.5217,
|
||||
],
|
||||
)
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=signature,
|
||||
observed={'header_tokens': observed_tokens},
|
||||
) is False
|
||||
|
||||
# 近亲缺 ECCN 仍须硬杀。
|
||||
twin_signature = {
|
||||
'table_patterns': [{
|
||||
'header_row_count': 1,
|
||||
'header_tokens': [
|
||||
'Item', 'Parts', 'No', 'ECCN', 'Description', 'REV', 'UNIT', 'QTY',
|
||||
],
|
||||
'column_centers': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8],
|
||||
}],
|
||||
}
|
||||
twin_observed = {
|
||||
'header_tokens': ['Item', 'Parts', 'No', 'Description', 'REV', 'UNIT', 'QTY'],
|
||||
}
|
||||
assert _header_discriminator_atoms_conflict(signature=twin_signature, observed=twin_observed) is True
|
||||
|
||||
|
||||
def test_multi_row_header_signature_keeps_secondary_row_identity():
|
||||
"""真多行表头(header_row_count>1)不得做折行合并。"""
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_signature_identity_header_tokens,
|
||||
)
|
||||
|
||||
signature = {
|
||||
'table_patterns': [{
|
||||
'header_row_count': 3,
|
||||
'header_tokens': ['Item', 'Qty', 'Price', 'Amount', 'PR_Number'],
|
||||
# 故意造 x 回退:多行正式表头不得合并掉 PR_Number。
|
||||
'column_centers': [0.1, 0.3, 0.5, 0.7, 0.2],
|
||||
}],
|
||||
}
|
||||
assert _signature_identity_header_tokens(signature) == [
|
||||
'Item', 'Qty', 'Price', 'Amount', 'PR_Number',
|
||||
]
|
||||
|
||||
|
||||
def test_required_anchors_skip_header_atom_hard_mutex():
|
||||
"""已配置必选锚点时,表头原子差异不得再硬杀;身份交给锚点门禁。"""
|
||||
mx_header = 'Item Parts No Description REV UNIT QTY Delivery Date Unit Total Price'
|
||||
|
||||
@@ -166,6 +166,39 @@ def test_parse_validation_accepts_month_day_year_date_format():
|
||||
assert result['metrics']['type_issue_count'] == 0
|
||||
|
||||
|
||||
def test_parse_validation_accepts_two_digit_year_dates():
|
||||
"""关键断言:MM/DD/YY 通过类型 sanity,不得误杀 Hyve 等 PO 日期。"""
|
||||
profile = _minimal_profile_snapshot(line_regions=[
|
||||
{
|
||||
'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'region': {'x0': 0.05, 'y0': 0.4, 'x1': 0.09, 'y1': 0.5},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
'target_fields': [{
|
||||
'scope': 'line', 'field_code': 'customer_po_line_no', 'field_id': 'line-id',
|
||||
}],
|
||||
},
|
||||
{
|
||||
'field_id': 'date-id', 'field_code': 'requested_receipt_date', 'scope': 'line',
|
||||
'region': {'x0': 0.10, 'y0': 0.4, 'x1': 0.6, 'y1': 0.5},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
'target_fields': [{
|
||||
'scope': 'line', 'field_code': 'requested_receipt_date', 'field_id': 'date-id',
|
||||
}],
|
||||
},
|
||||
])
|
||||
|
||||
result = validate_profile_parse_candidate(
|
||||
profile_snapshot=profile,
|
||||
layout=_layout_with_line_text('06/16/26'),
|
||||
definition={'fields': [{
|
||||
'field_code': 'requested_receipt_date', 'enabled': True, 'value_type': 'date',
|
||||
}]},
|
||||
)
|
||||
|
||||
assert 'profile_parse_type_sanity_failed' not in result['reason_codes']
|
||||
assert result['metrics'].get('type_issue_count', 0) == 0
|
||||
|
||||
|
||||
def _layout_with_shifted_line_text(*, text: str = '001 PART-A 10') -> dict:
|
||||
"""构造明细区文字被纵向位移到冻结字段带之下的 layout。
|
||||
|
||||
|
||||
@@ -182,3 +182,98 @@ def test_signature_relation_graph_uses_anchor_text_contract():
|
||||
snapshot = build_layout_signature(definition=definition, sample_layouts=[_sample_layout()])
|
||||
|
||||
assert isinstance(snapshot['signature']['field_relation_graph'], list)
|
||||
|
||||
|
||||
def test_single_logical_header_wrap_excludes_secondary_visual_line_from_identity():
|
||||
"""逻辑一行表头框住折行时,副标签并入所属列,不得拆成新身份列。"""
|
||||
definition = _minimal_definition()
|
||||
# 表头框盖住主行 + 折行副标签(与 Hyve 标注同构)。
|
||||
definition['table_regions'][0]['header_layouts'][0]['region'] = {
|
||||
'x0': 0, 'y0': 0.20, 'x1': 1, 'y1': 0.32,
|
||||
}
|
||||
page_h = 280.0
|
||||
main_y0, main_y1 = 60.0, 72.0
|
||||
wrap_y0, wrap_y1 = 76.0, 88.0
|
||||
glyphs = []
|
||||
# 主行:LN Quantity Part
|
||||
x = 10.0
|
||||
for word in ('LN', 'Quantity', 'Part'):
|
||||
for char in word:
|
||||
glyphs.append({
|
||||
'text': char,
|
||||
'bbox': {'x0': x, 'y0': main_y0, 'x1': x + 3, 'y1': main_y1},
|
||||
'boundary_before': 'none',
|
||||
})
|
||||
x += 3.5
|
||||
x += 8
|
||||
# 折行副标签:Vendor(落在 Part 列下方)
|
||||
x = 40.0
|
||||
for char in 'Vendor':
|
||||
glyphs.append({
|
||||
'text': char,
|
||||
'bbox': {'x0': x, 'y0': wrap_y0, 'x1': x + 3, 'y1': wrap_y1},
|
||||
'boundary_before': 'none',
|
||||
})
|
||||
x += 3.5
|
||||
layout = {
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 200, 'y1': 200}}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': page_h}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'tables': {'table-1': glyphs},
|
||||
},
|
||||
}
|
||||
pattern = build_layout_signature(definition=definition, sample_layouts=[layout])['signature']['table_patterns'][0]
|
||||
tokens = [str(item) for item in pattern['header_tokens']]
|
||||
assert pattern['header_row_count'] == 1
|
||||
joined = ' '.join(tokens).casefold()
|
||||
# 关键断言:Vendor 文案保留并入所属列,不得作为独立尾列。
|
||||
assert 'ln' in joined
|
||||
assert 'quantity' in joined
|
||||
assert 'part' in joined
|
||||
assert 'vendor' in joined
|
||||
assert tokens[-1].casefold() != 'vendor'
|
||||
assert len(tokens) == len(pattern['column_centers'])
|
||||
assert len(tokens) <= 3
|
||||
|
||||
|
||||
def test_multi_header_layouts_keep_both_visual_rows_in_identity():
|
||||
"""多个 header_layout(真多行表头)须保留各行身份 token,不做折行合并。"""
|
||||
definition = _minimal_definition()
|
||||
definition['table_regions'][0]['header_layouts'] = [
|
||||
{
|
||||
'layout_id': 'header_r1', 'region': {'x0': 0, 'y0': 0.20, 'x1': 1, 'y1': 0.26},
|
||||
'field_regions': [{
|
||||
'field_id': 'hdr-item', 'field_code': 'item_no', 'scope': 'header',
|
||||
'region': {'x0': 0.05, 'y0': 0.21, 'x1': 0.2, 'y1': 0.25},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
},
|
||||
{
|
||||
'layout_id': 'header_r2', 'region': {'x0': 0, 'y0': 0.27, 'x1': 1, 'y1': 0.33},
|
||||
'field_regions': [{
|
||||
'field_id': 'hdr-pr', 'field_code': 'pr_number', 'scope': 'header',
|
||||
'region': {'x0': 0.05, 'y0': 0.28, 'x1': 0.3, 'y1': 0.32},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
},
|
||||
]
|
||||
glyphs = []
|
||||
for index, char in enumerate('ITEM'):
|
||||
glyphs.append({'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 60, 'x1': 13 + index * 4, 'y1': 72}})
|
||||
for index, char in enumerate('PRNO'):
|
||||
glyphs.append({'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 80, 'x1': 13 + index * 4, 'y1': 92}})
|
||||
layout = {
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 50, 'x1': 200, 'y1': 200}}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 280}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'tables': {'table-1': glyphs},
|
||||
},
|
||||
}
|
||||
pattern = build_layout_signature(definition=definition, sample_layouts=[layout])['signature']['table_patterns'][0]
|
||||
joined = ' '.join(str(item) for item in pattern['header_tokens']).upper()
|
||||
assert pattern['header_row_count'] == 2
|
||||
# 关键断言:两行正式表头都进入身份,不被折行合并误伤。
|
||||
assert 'ITEM' in joined
|
||||
assert 'PRNO' in joined
|
||||
@@ -97,6 +97,74 @@ def test_runtime_strategy_requires_review_when_two_valid_modes_disagree_on_busin
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_uses_dynamic_to_confirm_fixed_when_adaptive_conflicts():
|
||||
"""关键断言:固定/自适应料号冲突时,动态列单侧覆盖固定则可落选;加长字段时升级动态列。"""
|
||||
fixed = _row(line_no='1', part_no='B3-A08AR11000001')
|
||||
fixed['fields'].append({'field_code': 'customer_part_number', 'value': 'WTP-B3-'})
|
||||
adaptive = _row(line_no='1', part_no='WTP-B3-')
|
||||
adaptive['fields'].append({'field_code': 'customer_part_number', 'value': 'WTP-B3-'})
|
||||
dynamic = _row(line_no='1', part_no='B3-A08AR11000001')
|
||||
dynamic['fields'].append({
|
||||
'field_code': 'customer_part_number', 'value': 'WTP-B3-A08AR11000001',
|
||||
})
|
||||
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]},
|
||||
fixed_rows=[fixed],
|
||||
adaptive_rows=[adaptive],
|
||||
dynamic_rows=[dynamic],
|
||||
)
|
||||
|
||||
assert result.status == 'selected'
|
||||
assert result.row_mode == 'dynamic_x_columns'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_uses_dynamic_to_confirm_adaptive_when_fixed_conflicts():
|
||||
"""动态只与自适应一致时,应落选自适应而非继续 Review。"""
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]},
|
||||
fixed_rows=[_row(line_no='1', part_no='PART-WRONG')],
|
||||
adaptive_rows=[_row(line_no='1', part_no='PART-RIGHT')],
|
||||
dynamic_rows=[_row(line_no='1', part_no='PART-RIGHT')],
|
||||
)
|
||||
|
||||
assert result.status == 'selected'
|
||||
assert result.row_mode == 'adaptive_record_columns'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',)
|
||||
|
||||
|
||||
def test_runtime_strategy_prefers_dynamic_when_it_extends_baseline_field_values():
|
||||
"""动态无额外行但字段值严格加长时,也应升级动态列,避免截断料号。"""
|
||||
fixed = _row(line_no='1', part_no='B3-A08')
|
||||
dynamic = _row(line_no='1', part_no='B3-A08AR11000001')
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]},
|
||||
fixed_rows=[fixed], adaptive_rows=[], dynamic_rows=[dynamic],
|
||||
)
|
||||
|
||||
assert result.status == 'selected'
|
||||
assert result.row_mode == 'dynamic_x_columns'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_prefers_dynamic_when_it_confirms_fixed_and_recovers_extra_row():
|
||||
"""动态确认固定侧且额外恢复记录时,应升级为动态列。"""
|
||||
result = resolve_runtime_parse_strategy(
|
||||
page_glyphs={'1': [{}]},
|
||||
fixed_rows=[_row(line_no='20', part_no='PART-B')],
|
||||
adaptive_rows=[_row(line_no='20', part_no='PART-X')],
|
||||
dynamic_rows=[
|
||||
_row(line_no='10', part_no='PART-A'),
|
||||
_row(line_no='20', part_no='PART-B'),
|
||||
],
|
||||
)
|
||||
|
||||
assert result.status == 'selected'
|
||||
assert result.row_mode == 'dynamic_x_columns'
|
||||
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
|
||||
|
||||
|
||||
def test_runtime_strategy_requires_review_when_two_modes_disagree_on_non_key_business_value():
|
||||
"""同项次料号但数量不同仍是业务冲突,不能因主键一致而静默采用固定子行。"""
|
||||
fixed = _row(line_no='10', part_no='PART-A')
|
||||
|
||||
Reference in new issue
Block a user