Merge branch 'dev' into invoice-check

This commit is contained in:
sophie committed 2026-09-10 13:39:31 +08:00
commit b15dd6808f
112 files changed
+6300 -586

No files matched your search

@@ -0,0 +1,117 @@
"""
backend/tests/test_contract_payment_ledger_focus.py
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、待补充、本月应付合同后核对计数与 focus 筛选。
"""
from __future__ import annotations
from datetime import date
from app import db
from app.models import ContractPaymentContract, ContractPaymentNode, User
from app.services.contract_payment.ledger_focus import ledger_focus_counts
def _create_user(*, username: str) -> User:
"""创建具备合同付款预警访问权的落库用户。"""
user = User(
username=username,
email=f'{username}@example.com',
role='user',
status='active',
real_name=f'{username}-实名',
employee_id=f'{username.upper()}-EMP',
department='采购部',
)
user.set_feature_permissions({'contract_payment.access': True})
user.set_password('password123')
db.session.add(user)
db.session.commit()
db.session.refresh(user)
db.session.expunge(user)
return user
def _auth_headers(user: User) -> dict[str, str]:
"""生成测试鉴权头。"""
return {
'X-User-Id': str(user.id),
'X-Username': user.username,
'Content-Type': 'application/json',
}
def _add_contract(*, contract_no: str, status: str = 'active') -> ContractPaymentContract:
"""写入一份已进入台账的合同。"""
contract = ContractPaymentContract(
contract_no=contract_no,
parse_status='parsed',
status=status,
)
db.session.add(contract)
db.session.flush()
return contract
def _add_node(contract: ContractPaymentContract, *, due: date | None, node_status: str = 'active') -> None:
"""写入一个付款节点,供汇总卡按到期日分类。"""
db.session.add(ContractPaymentNode(
contract_id=contract.id,
node_code=f'prepayment-{contract.id}',
node_type='prepayment',
status=node_status,
due_date=due,
offset_days=0,
reminder_days=14,
))
def _seed_focus_contracts() -> None:
"""构造四张汇总卡各自至少命中一份的台账合同。"""
today = date(2026, 9, 10)
due = _add_contract(contract_no='HT-FOCUS-DUE')
_add_node(due, due=today.replace(day=14))
overdue = _add_contract(contract_no='HT-FOCUS-OVERDUE')
_add_node(overdue, due=date(2026, 8, 20))
_add_contract(contract_no='HT-FOCUS-NEEDS')
month = _add_contract(contract_no='HT-FOCUS-MONTH')
_add_node(month, due=date(2026, 9, 28))
db.session.commit()
def test_ledger_focus_counts_by_contract(app):
"""四张汇总卡均按合同计数;本月应付只含本自然月未付合同。"""
with app.app_context():
_seed_focus_contracts()
counts = ledger_focus_counts(session=db.session, today=date(2026, 9, 10))
# 关键断言:即将到期 1、逾期 1、待补充 1、本月应付为 9/14 与 9/28 两份。
assert counts['due'] == 1
assert counts['overdue'] == 1
assert counts['needs_completion'] == 1
assert counts['due_this_month'] == 2
def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
"""点汇总卡后列表只返回对应合同;汇总接口不跟 keyword。"""
monkeypatch.setattr(
'app.services.contract_payment.ledger_focus.business_today',
lambda today=None: today or date(2026, 9, 10),
)
with app.app_context():
user = _create_user(username='cp_focus_list')
_seed_focus_contracts()
headers = _auth_headers(user)
overdue = client.get('/api/contract-payment/contracts?focus=overdue', headers=headers)
summary = client.get('/api/contract-payment/contracts/summary', headers=headers)
empty = client.get('/api/contract-payment/contracts?focus=overdue&keyword=NO-SUCH', headers=headers)
# 关键断言:逾期卡只筛出逾期合同;汇总仍看全量台账。
assert overdue.status_code == 200
data = overdue.get_json()['data']
assert data['total'] == 1
assert data['items'][0]['contract_no'] == 'HT-FOCUS-OVERDUE'
assert summary.get_json()['data']['overdue'] == 1
assert empty.get_json()['data']['total'] == 0
@@ -0,0 +1,98 @@
"""
backend/tests/test_contract_payment_list.py
用途:验收合同付款台账列表的 keyword 筛选,尤其是按供应商名称模糊匹配。
依赖:Flask test client、ContractPaymentContract、用户功能权限。
逻辑:构造两份已解析合同,确认供应商片段只命中对应行,且合同号/采购单号检索仍可用。
"""
from __future__ import annotations
from app import db
from app.models import ContractPaymentContract, User
def _create_user(*, username: str) -> User:
"""创建具备合同付款预警访问权的落库用户,供列表接口走 legacy header 认证。"""
user = User(
username=username,
email=f'{username}@example.com',
role='user',
status='active',
real_name=f'{username}-实名',
employee_id=f'{username.upper()}-EMP',
department='采购部',
)
user.set_feature_permissions({'contract_payment.access': True})
user.set_password('password123')
db.session.add(user)
db.session.commit()
db.session.refresh(user)
db.session.expunge(user)
return user
def _auth_headers(user: User) -> dict[str, str]:
"""生成测试鉴权头。"""
return {
'X-User-Id': str(user.id),
'X-Username': user.username,
'Content-Type': 'application/json',
}
def _seed_parsed_contracts() -> None:
"""写入两份已进入台账的合同,供应商名称可区分。"""
db.session.add_all(
[
ContractPaymentContract(
contract_no='HT-20260903-30622-0',
workflow_no='5203-2609020001',
purchase_order_no='5203-2609020001',
supplier_name='诺亘(上海)工业自动化有限公司',
parse_status='parsed',
status='active',
),
ContractPaymentContract(
contract_no='HT-20260903-30612-0',
workflow_no='5203-2608270005',
purchase_order_no='5203-2608270005',
supplier_name='无锡市质谨机电科技有限公司',
parse_status='parsed',
status='active',
),
]
)
db.session.commit()
def test_list_contracts_filters_by_supplier_name(client, app):
"""关键词命中供应商名称时只返回对应合同,不误伤其他供应商。"""
with app.app_context():
user = _create_user(username='cp_list_supplier')
_seed_parsed_contracts()
headers = _auth_headers(user)
res = client.get('/api/contract-payment/contracts?keyword=诺亘', headers=headers)
assert res.status_code == 200
data = res.get_json()['data']
# 关键断言:供应商模糊匹配生效,且仍走 parsed 台账口径。
assert data['total'] == 1
assert data['items'][0]['supplier_name'] == '诺亘(上海)工业自动化有限公司'
assert data['items'][0]['contract_no'] == 'HT-20260903-30622-0'
def test_list_contracts_keyword_still_matches_contract_and_po(client, app):
"""合同号、采购单号原有检索不能被供应商筛选挤掉。"""
with app.app_context():
user = _create_user(username='cp_list_keyword')
_seed_parsed_contracts()
headers = _auth_headers(user)
by_po = client.get('/api/contract-payment/contracts?keyword=5203-2608270005', headers=headers)
by_contract = client.get('/api/contract-payment/contracts?keyword=HT-20260903-30622-0', headers=headers)
# 关键断言:原合同号/采购单号路径仍精确命中。
assert by_po.get_json()['data']['total'] == 1
assert by_po.get_json()['data']['items'][0]['purchase_order_no'] == '5203-2608270005'
assert by_contract.get_json()['data']['total'] == 1
assert by_contract.get_json()['data']['items'][0]['contract_no'] == 'HT-20260903-30622-0'
+85 -3
View File
@@ -1,9 +1,9 @@
"""
backend/tests/test_contract_payment_parse.py
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配及周汇总摘要。
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)。
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信。
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名。
"""
from datetime import date, datetime
@@ -17,10 +17,17 @@ from app.models import (
ContractPaymentNode,
User,
)
from io import BytesIO
from openpyxl import load_workbook
from app.services.contract_payment.alert_service import (
bind_contract_owner_from_applicant,
build_weekly_alert_summary,
generate_alerts,
_alert_status_label,
_build_excel,
_recipient_display_name,
)
from app.services.contract_payment import parse_service
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text
@@ -549,6 +556,81 @@ def test_weekly_alert_summary_counts_pending_and_next_friday(app):
assert at_send_time["next_send_at"] == "2026-09-11T10:00:00Z"
def test_weekly_excel_writes_recipient_real_name_not_role(app):
"""关键断言:企微 Excel 列名为「收件人」,单元格写系统用户真实姓名,不再写岗位名称。"""
with app.app_context():
owner = User(
username="excel-owner",
email="excel-owner@example.com",
status="active",
real_name="张三",
)
db.session.add(owner)
db.session.flush()
contract = ContractPaymentContract(
contract_no="HT-EXCEL-1",
purchase_order_no="PO-1",
supplier_name="苏州供应商",
owner_user_id=owner.id,
status="active",
)
db.session.add(contract)
db.session.flush()
node = ContractPaymentNode(
contract_id=contract.id,
node_code="shipment",
node_type="shipment",
status="active",
due_date=date(2026, 9, 1),
)
db.session.add(node)
db.session.flush()
alert = ContractPaymentAlert(
contract_id=contract.id,
node_id=node.id,
trigger_key="round:1:date:2026-09-01",
recipient_user_id=owner.id,
alert_round=1,
status="pending",
)
db.session.add(alert)
db.session.commit()
data, summary = _build_excel([(alert, contract, node, owner)])
wb = load_workbook(BytesIO(data))
headers = [cell.value for cell in wb.active[1]]
row = [cell.value for cell in wb.active[2]]
assert "收件岗位" not in headers
assert headers[10] == "收件人"
assert row[10] == "张三"
assert row[11] == "待发送"
assert "pending" not in row
assert "采购负责人" not in row
assert summary["total"] == 1
def test_recipient_display_name_falls_back_to_username(app):
"""关键断言:真实姓名为空时 Excel 收件人回退用户名,而不是岗位标签。"""
with app.app_context():
named = User(username="buyer", email="named@example.com", status="active", real_name="李采购")
unnamed = User(username="buyer02", email="unnamed@example.com", status="active", real_name=" ")
assert _recipient_display_name(named) == "李采购"
assert _recipient_display_name(unnamed) == "buyer02"
assert _recipient_display_name(None) == "—"
def test_alert_status_label_uses_chinese():
"""关键断言:Excel 状态列把 pending/sent/failed 写成中文,未知码保留原文。"""
assert _alert_status_label("pending") == "待发送"
assert _alert_status_label("sent") == "已发送"
assert _alert_status_label("failed") == "发送失败"
assert _alert_status_label("resolved") == "已关闭"
assert _alert_status_label("unknown-code") == "unknown-code"
assert _alert_status_label(None) == "—"
def test_erp_payment_amount_matches_the_corresponding_stage():
"""关键断言:不同金额的 ERP 付款必须分别匹配同金额付款阶段。"""
paid_node_ids = resolve_paid_node_ids(
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_permissions.py
用途:验收合同付款预警专项权限 `contract_payment.access` 的角色默认值、显式覆盖与 API 拦截。
依赖:User 功能权限、Flask test client、contract_payment 蓝图。
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账;关闭 admin 覆盖后同样 403。
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账,但不能触发同步/扫描/发送;关闭 admin 覆盖后同样 403。
"""
from __future__ import annotations
@@ -128,3 +128,23 @@ def test_contract_payment_api_allows_granted_user(client, app):
body = list_res.get_json()
assert body.get('success') is True
assert 'items' in (body.get('data') or {})
def test_contract_payment_jobs_require_admin(client, app):
"""已授权的普通用户可查台账,但不能触发同步、扫描或周汇总发送。"""
with app.app_context():
granted = _create_user(
username='cp_api_jobs_denied',
feature_permissions={'contract_payment.access': True},
)
headers = _auth_headers(granted)
# 关键断言:访问权不等于操作权,手动任务仅管理员。
for path in (
'/api/contract-payment/sync',
'/api/contract-payment/alerts/run',
'/api/contract-payment/alerts/weekly-run',
):
res = client.post(path, headers=headers, json={})
assert res.status_code == 403, path
assert _json_error(res)['code'] == 'CONTRACT_PAYMENT.ADMIN_REQUIRED'
+77 -1
View File
@@ -1,7 +1,8 @@
"""验证 EML 正文补充表的确定性解析、关联和数量保护。
依赖:正文补充解析器与合并服务。
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威,歧义稳定进入复核。
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威;关联优先 PO+料号,
其次 PO+预约号,歧义稳定进入复核。
"""
from __future__ import annotations
@@ -345,6 +346,81 @@ def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
def test_email_supplement_po_reservation_injects_hint_when_parts_do_not_match():
"""同 PO 下 PDF 已有预约号、邮件仅 APN 不对料号时,按 reservation 对齐灌入库存源线索。
回归:AWS allocation 表 Component APN 对不上 Wistron MPN 时,不得因缺 po_mpn
把多行 VMI-* 线索整单丢掉。
"""
order = {
'_hxops_intake_id': 1,
'header_fields': [{'field_id': 'po', 'observations': [{'value': '16776707'}]}],
'lines': [
{'fields': [
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000002'}]},
{'field_id': 'reservation', 'observations': [{'value': '2000484577'}]},
{'field_id': 'qty', 'observations': [{'value': 30}]},
]},
{'fields': [
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]},
{'field_id': 'reservation', 'observations': [{'value': '2000484578'}]},
{'field_id': 'qty', 'observations': [{'value': 24}]},
]},
],
'conflicts': [],
}
supplement = {
'document_id': 44,
'rows': [
{
'customer_po_number': '16776707',
'part_number': '504-006055-001',
'reservation_id': '2000484577',
'inventory_source_hint': 'VMI-RTM01',
'evidence': {'inventory_source_hint': {'raw_value': 'VMI-RTM01'}},
},
{
'customer_po_number': '16776707',
'part_number': '504-006056-001',
'reservation_id': '2000484578',
'inventory_source_hint': 'VMI-DUB',
'evidence': {'inventory_source_hint': {'raw_value': 'VMI-DUB'}},
},
],
}
merged = merge_email_supplements(
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
)[0]
# 关键断言:关联码为 po_reservation;两行分别灌入对应线索,数量不被覆盖。
assert merged['_hxops_email_supplement_relation'] == 'po_reservation'
assert _value(merged['lines'][0]['fields'], 'source') == 'VMI-RTM01'
assert _value(merged['lines'][1]['fields'], 'source') == 'VMI-DUB'
assert _value(merged['lines'][0]['fields'], 'qty') == 30
assert _value(merged['lines'][1]['fields'], 'qty') == 24
assert not any(item.get('reason') == 'supplement_relation_ambiguous' for item in merged['conflicts'])
def test_email_supplement_po_mpn_still_preferred_over_po_reservation():
"""料号能精确命中时仍走 po_mpn,不得因两边都有预约号改走 reservation 档。"""
order = _order()
order['lines'][0]['fields'].append({
'field_id': 'reservation', 'observations': [{'value': '2000484577'}],
})
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: {'document_id': 44, 'rows': [{
'customer_po_number': '4518738152',
'part_number': 'D4-A08AR12000002',
'reservation_id': '2000484577',
'inventory_source_hint': 'DSB CMH',
'evidence': {},
}]}},
schema_definition=SCHEMA,
)[0]
assert merged['_hxops_email_supplement_relation'] == 'po_mpn'
assert _value(merged['lines'][0]['fields'], 'source') == 'DSB CMH'
def test_email_supplement_po_fallback_writes_unique_reservation_without_part_match():
"""唯一 PO 兜底不得在写入阶段重新要求邮件料号匹配。"""
result = merge_email_supplements(
+51
View File
@@ -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()
@@ -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')
@@ -0,0 +1,117 @@
"""
inventory RPA:Playwright Download.save_as 因浏览器关闭失败时,应按 downloads_path 目录兜底落盘。
"""
from __future__ import annotations
import importlib.util
import sys
import tempfile
from pathlib import Path
def _load_worker():
module_path = (
Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
)
scripts_dir = str(module_path.parent)
if scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir)
# common/ 需可 import download_artifact_fallback
common_dir = str(module_path.parent.parent / "common")
if common_dir not in sys.path:
sys.path.insert(0, common_dir)
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_save_fallback_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class _ClosedBrowserDownload:
"""模拟 Playwright Download:save_as 时浏览器已关闭。"""
suggested_filename = "OnHandInventory.xlsx"
def save_as(self, dest: str) -> None:
raise RuntimeError("Download.save_as: Target page, context or browser has been closed")
def test_save_batch_download_falls_back_when_browser_closed(monkeypatch):
"""save_as 因浏览器关闭失败、目录已有稳定 xlsx 时,应改名落盘并返回规范路径。"""
worker = _load_worker()
with tempfile.TemporaryDirectory() as tmp:
drop_dir = Path(tmp) / "drop"
drop_dir.mkdir()
(drop_dir / "noise.txt").write_text("old", encoding="utf-8")
landed = drop_dir / "chromium_download.xlsx"
landed.write_bytes(b"PK" + b"0" * 600)
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
out = worker._save_batch_download(
_ClosedBrowserDownload(),
drop_dir,
"BATCH-RUN-1",
{"source_code": "DSV360_AWSSG", "warehouse_id": "AWSSG"},
baseline_names={"noise.txt"},
)
assert out.exists()
assert out.parent == drop_dir
assert "DSV360_AWSSG" in out.name
assert "AWSSG" in out.name
assert out.suffix == ".xlsx"
assert not landed.exists()
def test_save_batch_download_reraises_when_fallback_missing(monkeypatch):
"""浏览器关闭且目录无新文件时,应继续抛出原 save_as 错误。"""
worker = _load_worker()
with tempfile.TemporaryDirectory() as tmp:
drop_dir = Path(tmp) / "drop"
drop_dir.mkdir()
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
monkeypatch.setattr(
worker,
"_wait_for_new_download_file",
lambda **_kwargs: None,
)
try:
worker._save_batch_download(
_ClosedBrowserDownload(),
drop_dir,
"BATCH-RUN-2",
{"source_code": "DSV360_AWSSG", "warehouse_id": "AWSSG"},
baseline_names=set(),
fallback_timeout_seconds=0.1,
)
raise AssertionError("expected RuntimeError")
except RuntimeError as exc:
# 断言:错误信息仍指向浏览器关闭,避免被吞成模糊失败
assert "has been closed" in str(exc).lower()
def test_save_download_falls_back_when_browser_closed(monkeypatch):
"""单票路径同样在 save_as 浏览器关闭后走目录兜底。"""
worker = _load_worker()
with tempfile.TemporaryDirectory() as tmp:
drop_dir = Path(tmp) / "drop"
drop_dir.mkdir()
landed = drop_dir / "raw.xlsx"
landed.write_bytes(b"PK" + b"0" * 600)
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
out = worker._save_download(
_ClosedBrowserDownload(),
drop_dir,
"OT-1",
"DSV360_AWSSG",
baseline_names=set(),
)
assert out.exists()
assert "DSV360_AWSSG" in out.name
assert not landed.exists()
@@ -0,0 +1,80 @@
"""
tests/test_kb_source_file_download.py
用途:知识库源文件下载的 Content-Disposition 与中文文件名。
依赖:kb.common.build_content_disposition、documents 路由、kb 模型。
逻辑:纯函数校验 RFC 5987 头;API 用例确认 ?download=1 返回原名且正文为原件。
"""
from pathlib import Path
from urllib.parse import quote
from app import db
from app.api.kb.common import build_content_disposition
from app.core.auth.jwt import issue_local_access_token
from app.models import KbDocument, KbDocumentVersion, KbGroup, User
def test_build_content_disposition_quotes_ascii_and_keeps_utf8_filename():
"""
ASCII 回退名必须加引号,真实中文名在 filename* 段。
关键断言:不得出现无引号的 `filename=docx; filename*=...`,否则浏览器会把两段拼成怪名。
"""
filename = '企业文化.docx'
header = build_content_disposition(filename, as_attachment=True)
assert header.startswith('attachment; filename="download.docx"; filename*=UTF-8\'\'')
assert quote(filename, safe='') in header
assert 'filename=docx;' not in header
def test_source_file_download_uses_original_filename(app, client, tmp_path):
"""
工作台源文件下载应以下载附件返回,且 Content-Disposition 含原始中文文件名。
关键断言:响应体是原件字节;filename* 为 企业文化.docx;ASCII 回退名带引号。
"""
storage_root = tmp_path / 'kb-storage'
storage_root.mkdir()
source_name = '企业文化.docx'
source_path = storage_root / 'corp-culture.docx'
source_bytes = b'PK\x03\x04fake-docx'
source_path.write_bytes(source_bytes)
app.config['KB_STORAGE_ROOT'] = str(storage_root)
with app.app_context():
user = User(
username='kb-download-admin',
email='kb-download-admin@example.com',
role='admin',
status='active',
)
user.set_password('password123')
group = KbGroup(name='源文件下载分组')
document = KbDocument(group=group, title='企业文化', status='uploaded')
version = KbDocumentVersion(
document=document,
version_no=1,
status='uploaded',
is_current=True,
source_file_name=source_name,
source_file_path=str(source_path),
source_file_ext='docx',
source_file_size=len(source_bytes),
)
db.session.add_all([user, group, document, version])
db.session.commit()
version_id = version.id
token = issue_local_access_token(user)
res = client.get(
f'/api/kb/document-versions/{version_id}/source-file?download=1',
headers={'Authorization': f'Bearer {token}'},
)
assert res.status_code == 200
assert res.data == source_bytes
disposition = res.headers.get('Content-Disposition', '')
assert 'attachment' in disposition
assert f'filename*=UTF-8\'\'{quote(source_name, safe="")}' in disposition
assert 'filename="download.docx"' in disposition
assert 'filename=docx;' not in disposition
@@ -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
@@ -14,6 +14,7 @@ from app.extensions import db
from app.models import (
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingOrderDocumentProfileDraftRevision,
ShippingOrderDocumentProfileValidationRun,
User,
)
@@ -196,12 +197,19 @@ def test_report_ignores_submitted_pre_hydration_signature(app, monkeypatch):
def test_report_blocks_when_overlap_failed(app, monkeypatch):
"""关键断言:重叠验证 failed 时报告写入 overlap 阻断项与 conflict 引用。"""
"""关键断言:当前草稿上的 overlap failed 展开真实门禁,不得误报 overlap_validation_stale。"""
with app.app_context():
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-overlap-create')
lease = _lease(draft['id']); run = _passing_run(draft); _signature_run(draft)
failed_overlap = _overlap_run(draft, status='failed')
failed_overlap.summary_json = {
**dict(failed_overlap.summary_json or {}),
'self_unique_hit_rate_training': 0.0,
'training_sample_count': 2,
'blind_sample_count': 0,
}
db.session.commit()
monkeypatch.setattr(
validation_service, 'run_cross_template_overlap',
lambda *args, **kwargs: {'id': failed_overlap.id, 'status': 'failed', 'stored_status': 'failed'},
@@ -211,10 +219,37 @@ def test_report_blocks_when_overlap_failed(app, monkeypatch):
actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-overlap-report',
)
keys = {str(item.get('key')) for item in report['blocking_items']}
assert 'overlap_validation_stale' in keys or 'overlap_validation_required' in keys or 'self_match_not_unique' in keys
assert 'self_match_not_unique' in keys
assert 'overlap_validation_stale' not in keys
assert report['overlap_validation_run_id'] == failed_overlap.id
def test_blocking_from_overlap_marks_stale_only_on_checksum_drift(app):
"""关键断言:仅 definition_checksum 漂移才标 stale;同 checksum 的 failed 展开指标。"""
with app.app_context():
schema = _schema_version()
draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-stale-vs-failed')
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
profile_id=draft['id'], revision_no=draft['draft_revision']['revision_no'],
).one()
stale_run = _overlap_run(draft, status='passed')
stale_run.definition_checksum = 'not-current-checksum'
db.session.commit()
stale_keys = {item['key'] for item in checks._blocking_from_overlap(None, stale_run, revision)}
assert stale_keys == {'overlap_validation_stale'}
failed_run = _overlap_run(draft, status='failed')
failed_run.summary_json = {
**dict(failed_run.summary_json or {}),
'self_unique_hit_rate_training': 0.0,
'training_sample_count': 1,
}
db.session.commit()
failed_keys = {item['key'] for item in checks._blocking_from_overlap(dict(failed_run.summary_json), failed_run, revision)}
assert 'self_match_not_unique' in failed_keys
assert 'overlap_validation_stale' not in failed_keys
def test_report_invalidates_when_signature_cleared(app, monkeypatch):
"""关键断言:草稿签名引用清空后既有报告查询即 invalidated。"""
with app.app_context():
@@ -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(
@@ -160,13 +172,22 @@ def test_profile_without_reservation_region_does_not_scan_vendor_comments():
def test_enabled_reservation_region_requires_review_when_terms_heading_is_missing():
"""专区缺少结束锚点时,不得把未封闭文本区的值当成可自动建单证据。"""
"""专区缺少结束锚点时,窗内候选可展示/归属,但订单必须标 needs_review。"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]},
reservation_region_candidates=[{
'value': '1000143920', 'scope': 'line', 'line_no': 1,
'raw_text': 'DBS Reservation Line 1: 1000143920', 'status': 'mapped',
}],
reservation_region_reason='terms_and_conditions_anchor_missing',
)
assert reason is None
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
assert (orders or [])[0]['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing']
order = (orders or [])[0]
assert order['reservation_region_status'] == 'needs_review'
assert order['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing']
assert any(
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == '1000143920'
for item in order['lines'][0]['fields']
)
@@ -1717,3 +1717,37 @@ def test_table_region_profile_freezes_confirmed_visual_geometry_source_only():
}).visual_evidence_source == 'acroform_widget_geometry'
with pytest.raises(ValueError, match='visual_evidence_source'):
TableRegionProfile.model_validate({**payload, 'visual_evidence_source': 'xfa_dataset'})
def test_strategy_needs_review_still_returns_best_effort_rows_for_display(monkeypatch):
"""策略需复核时仍返回最佳努力明细,盲测/验证才能展示,不能整表吞掉。"""
from app.services.shipping_notice.document_layout import runtime_parse_strategy as strategy_module
from app.services.shipping_notice.document_layout.runtime_parse_strategy import RuntimeParseStrategy
def _force_review(**_kwargs):
return RuntimeParseStrategy('needs_review', (1,), None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',))
monkeypatch.setattr(strategy_module, 'resolve_runtime_parse_strategy', _force_review)
rows, strategy = reconstruct_coordinate_profile_rows_with_strategy(
characters=_glyphs(
[('1', 10), ('PART-A', 80)],
[('2', 10), ('PART-B', 80)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
line_layouts=[{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}},
],
}],
line_start_field_code='customer_po_line_no',
)
assert strategy.status == 'needs_review'
assert [row.fields for row in rows] == [
{'customer_po_line_no': '1', 'part_number': 'PART-A'},
{'customer_po_line_no': '2', 'part_number': 'PART-B'},
]
@@ -710,6 +710,59 @@ def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app):
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
def test_coordinate_blind_candidate_keeps_rows_when_strategy_needs_review(app, monkeypatch):
"""关键断言:策略需复核时盲测预览仍展示最佳努力明细,不能整表吞掉。"""
from app.services.shipping_notice.document_layout.runtime_parse_strategy import RuntimeParseStrategy
with app.app_context():
profile, user, documents = _published_profile_with_samples()
profile.definition_json = {
'document_match': {'required_anchors': []},
'table_regions': [{
'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
],
}],
}], 'order_field_layouts': [],
}
glyphs = [
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}}
for index, char in enumerate('20')
] + [
{'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}}
for index, char in enumerate('PART-A')
]
record_inline_layout_snapshot(documents[1], {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'table-1', 'page_no': 1}],
'coordinate_evidence': {
'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
db.session.commit()
def _force_review(**_kwargs):
return RuntimeParseStrategy('needs_review', (1,), None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',))
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.runtime_parse_strategy.resolve_runtime_parse_strategy',
_force_review,
)
candidate = quality._candidate_for_sample(
profile=profile, document_id=documents[1].id, table_id='table-1',
)
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
with app.app_context():
@@ -10,8 +10,10 @@ 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
import pytest
@@ -27,8 +29,11 @@ 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,
_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 +165,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 +237,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 +440,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 +451,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 +480,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 +506,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 +514,53 @@ 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_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(
@@ -2409,7 +2409,7 @@ def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch,
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
)
def _fake_link(actual_task, inv_file, *, reason, role='member', audit_payload=None):
def _fake_link(actual_task, inv_file, *, reason, audit_payload=None):
call_order.append(f'link:{reason}')
assert actual_task is task
assert inv_file is snapshot
@@ -2424,7 +2424,7 @@ def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch,
return {'status': 'ok', 'message': 'linked-and-loaded'}
monkeypatch.setattr(
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation',
_fake_link,
)
monkeypatch.setattr(
@@ -2495,7 +2495,7 @@ def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app):
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation',
lambda *_a, **_k: None,
)
@@ -2516,3 +2516,85 @@ def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app):
assert result['status'] == 'needs_human'
assert result['data']['blocking_reason']['code'] == 'inventory_file_missing'
def test_stp_candidate_ready_uses_preparation_link_when_warehouse_pending(monkeypatch, app):
"""[断言] 动态仓未决时 preparation 软绑定仍推进,不得投影 inventory_file_missing。"""
from app.services.shipping_notice import inventory_workflow
task = SimpleNamespace(
task_no='OT-STP-SOFT-LINK',
id=703,
inventory_lines_json=None,
inventory_source_status='candidates_frozen',
active_inventory_candidate_set_id=11,
)
snapshot = SimpleNamespace(inventory_file_no='INV-WH-PENDING', source_code='CRANE', warehouse_id=None)
call_order: list[str] = []
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {})
monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs)
monkeypatch.setattr(inventory_workflow.db.session, 'flush', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['CRANE'],
)
monkeypatch.setattr(
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
lambda _task: {
'status': 'ready',
'candidate_set_id': 11,
'lines': [{'part_number': 'P1', '__source_code': 'CRANE', '__inventory_file_no': 'INV-WH-PENDING'}],
'missing_source_codes': [],
'loaded_source_codes': ['CRANE'],
'evidence': [{
'source_code': 'CRANE',
'status': 'loaded',
'inventory_file_no': 'INV-WH-PENDING',
'line_count': 1,
'required': True,
}],
'required_source_codes': ['CRANE'],
},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
lambda _task: None,
)
monkeypatch.setattr(
ShippingInventoryFile,
'query',
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
)
def _fake_prep_link(actual_task, inv_file, *, reason, audit_payload=None):
call_order.append(f'prep:{reason}')
assert reason == 'stp_candidate_prep'
assert inv_file is snapshot
return SimpleNamespace(id=99, identity_check_status='pending_matching')
def _fake_loaded(actual_task, lines, **kwargs):
call_order.append('loaded')
assert kwargs.get('persist_lines') is False
return {'status': 'ok', 'message': 'soft-linked'}
monkeypatch.setattr(
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation',
_fake_prep_link,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response',
_fake_loaded,
)
monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _fake_loaded)
result = inventory_workflow.ensure_inventory({
'task_id': task.task_no,
'mode': 'auto',
'_orchestrator_internal_dispatch': True,
})
assert result['status'] == 'ok'
assert call_order == ['prep:stp_candidate_prep', 'loaded']
@@ -8,6 +8,8 @@ from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
extract_reservation_from_region_text,
extract_reservation_from_vendor_comments_pages,
project_reservation_onto_validation_evidence,
reservation_region_candidates_from_layout,
)
@@ -82,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") == [{
@@ -106,8 +120,23 @@ def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading()
assert [item['value'] for item in candidates] == ['33008', '3000098851']
def test_terms_heading_matches_when_phrase_is_only_part_of_title():
"""结束锚点只需标题含 Terms and Conditions,不要求整行仅有该短语。"""
candidates, reason = extract_reservation_from_vendor_comments_pages([
(1, _glyph_lines(
'Vendor Comments',
'DBS Reservation Line 1: 1000143920',
'7. Terms and Conditions of Sale',
'Reservation#99999',
)),
])
assert reason is None
assert [item['value'] for item in candidates] == ['1000143920']
def test_vendor_comments_window_requires_start_and_end_headings():
"""缺少任一边界时不能把全文中的 Reservation 当作专区证据。"""
"""缺少起始锚点时不得扫描全文;缺少结束锚点时仍返回窗内候选但必须带复核原因。"""
candidates, reason = extract_reservation_from_vendor_comments_pages([
(1, _glyph_lines('Reservation#33008')),
])
@@ -115,6 +144,18 @@ def test_vendor_comments_window_requires_start_and_end_headings():
assert candidates == []
assert reason == 'vendor_comments_anchor_missing'
open_candidates, open_reason = extract_reservation_from_vendor_comments_pages([
(1, _glyph_lines(
'Vendor Comments:',
'DBS Reservation Line 1: 1000143920',
'End Customer: D1',
)),
])
assert open_reason == 'terms_and_conditions_anchor_missing'
assert [item['value'] for item in open_candidates] == ['1000143920']
assert open_candidates[0]['scope'] == 'line'
assert open_candidates[0]['line_no'] == 1
def test_reservation_region_applies_header_and_line_override_together():
"""整单值是默认值,指定行的 Reservation 仅覆盖对应明细。"""
@@ -165,3 +206,71 @@ def test_reservation_gate_blocks_empty_and_malformed_order_lines():
assert reservation_gate_issues([])[0]["reason"] == "missing_order_lines"
assert reservation_gate_issues(["invalid-line"])[0]["reason"] == "invalid_order_line"
def test_reservation_region_candidates_from_layout_requires_configured_region():
"""未标注专区时不得扫描 Vendor Comments;标注后必须走锚点窗而非 page_no/region。"""
layout = {
'coordinate_evidence': {
'pages': {'1': {'width': 800, 'height': 600}},
'page_glyphs': {
'1': _glyph_lines(
'Vendor Comments:',
'DBS Reservation Line 1: 1000143920',
'Terms and Conditions:',
),
},
},
}
assert reservation_region_candidates_from_layout(definition={}, layout=layout) == {
'candidates': [], 'reason': None,
}
result = reservation_region_candidates_from_layout(
definition={'reservation_id_region': {'page_no': 9, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}}},
layout=layout,
)
assert result['reason'] is None
assert [item['value'] for item in result['candidates']] == ['1000143920']
assert result['candidates'][0]['scope'] == 'line'
assert result['candidates'][0]['line_no'] == 1
def test_project_reservation_onto_validation_evidence_writes_line_and_review_reason():
"""验证证据必须落入与正式解析相同的 header/line 字段,并保留锚点缺失原因。"""
evidence = {
'header_fields': [{
'field_id': 'f-po', 'field_code': 'customer_po_number', 'raw_value': 'PO-1',
'normalized_value': 'PO-1', 'status': 'passed', 'issues': [],
}],
'lines': [{'row_index': 0, 'fields': [{
'field_id': 'f-part', 'field_code': 'part_number', 'raw_value': 'P-1',
'normalized_value': 'P-1', 'status': 'passed', 'issues': [],
}]}],
'cross_checks': {},
}
projected = project_reservation_onto_validation_evidence(
evidence,
candidates=[{
'value': '1000143920', 'line_no': 1, 'scope': 'line',
'raw_text': 'DBS Reservation Line 1: 1000143920', 'status': 'mapped',
}],
reason=None,
schema_fields={
'header-reservation': {
'field_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header',
},
'line-reservation': {
'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line',
},
},
)
assert projected['lines'][0]['fields'][-1] == {
'field_id': 'line-reservation', 'field_code': 'reservation_id',
'raw_value': '1000143920', 'normalized_value': '1000143920',
'status': 'passed', 'issues': [],
}
missing = project_reservation_onto_validation_evidence(
evidence, candidates=[], reason='vendor_comments_anchor_missing', schema_fields={},
)
assert missing['reservation_region_status'] == 'needs_review'
assert missing['reservation_region_review_reasons'] == ['vendor_comments_anchor_missing']
@@ -676,7 +676,7 @@ def test_create_run_scopes_to_selected_intakes_only(app):
@pytest.mark.parametrize('layout_status', ['queued', 'running'])
def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction(app, layout_status):
"""发送后必须先完成版面解析;订单 Job 不得与布局 Job 并行抢跑。"""
"""发送后若 PDF 版式仍在进行,Run 进入 waiting_layout;不得对未 ready 的 PDF 抽取。"""
with app.app_context():
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
user, agent, session, intake, document = _seed_run_input(suffix=f'LAYOUT-{layout_status.upper()}')
@@ -750,14 +750,14 @@ def test_create_run_accepts_a_reused_layout_from_an_identical_document(app):
assert run.status == 'queued'
def test_last_layout_completion_enqueues_waiting_run_once(app):
"""最后一份附件布局完成才唤醒 Run,提前完成其中一份不能启动订单提取。"""
def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app):
"""任一份附件布局完成即可唤醒 Run;无需等齐全部版式。"""
with app.app_context():
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
user, agent, session, intake, first = _seed_run_input(suffix='WAIT-ALL')
user, agent, session, intake, first = _seed_run_input(suffix='WAIT-PARTIAL')
second = ShippingOrderDocument(
intake_id=intake.id, asset_id=first.asset_id, document_type='attachment',
attachment_key='orders-WAIT-ALL-2.pdf', filename='orders-WAIT-ALL-2.pdf',
attachment_key='orders-WAIT-PARTIAL-2.pdf', filename='orders-WAIT-PARTIAL-2.pdf',
content_hash='b' * 64, classification='order_notice', parse_status='parsed', extracted_text='PO 2',
)
db.session.add(second)
@@ -770,12 +770,31 @@ def test_last_layout_completion_enqueues_waiting_run_once(app):
ShippingDocumentLayoutVersion.document_id.in_([first.id, second.id]),
).all()
assert len(layouts) == 2
ready_payload = {
'status': 'ready',
'layout_candidate': {},
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}},
'page_glyphs': {'1': []},
},
}
layouts[0].status = 'ready'
layouts[0].payload_json = dict(ready_payload)
first.current_layout_version_id = layouts[0].id
db.session.commit()
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 0
assert db.session.get(Job, run.current_job_id) is not None
# 关键断言:第一份 ready 即可 resume(活跃 Job 去重仍只保留一条 extraction)。
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 1
db.session.refresh(run)
first_job_id = run.current_job_id
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'
layouts[1].payload_json = dict(ready_payload)
second.current_layout_version_id = layouts[1].id
db.session.commit()
assert resume_runs_waiting_for_layout(document_id=layouts[1].document_id) == 1
db.session.refresh(run)
@@ -783,6 +802,7 @@ def test_last_layout_completion_enqueues_waiting_run_once(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):
@@ -67,6 +67,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
monkeypatch.setattr(handler, 'materialize_order_extraction_run_inputs', fake_materialize)
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda _run, *, created_by_id: events.append('schedule') or False)
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {1})
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: events.append('units') or [])
monkeypatch.setattr(handler, '_next_existing_batch', lambda _plan, *, after_batch: None)
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda _run, _plan: [])
@@ -113,6 +114,7 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
lambda _run, *, created_by_id: events.append('schedule') or True,
)
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {357: 'layout_pending'})
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: set())
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('waiting'))
def fake_finish_job(*_args, **kwargs):
events.append('finished')
@@ -134,6 +136,116 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
assert finished['message'] == '已转交附件版面解析,完成后自动创建后继订单识别任务'
def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(monkeypatch):
"""部分 PDF 版式就绪时只抽 ready Unit,Job 以 partial_units_done 收口且不终态 Run。"""
import app.jobs.handlers.shipping_order_extraction as handler
events: list[str] = []
finished: dict = {}
run = SimpleNamespace(
id=4, user_id=9, run_no='SNER-WORKER-PARTIAL', status='queued', phase='queued',
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
execution_result_json=None, extraction_completed_at=None,
)
job = SimpleNamespace(id=4, attempts=1, business_ref=run.run_no, max_attempts=3)
ready_unit = SimpleNamespace(
id=41, document_id=101, intake_id=1, status='pending', result_json=None, position=1,
cancellation_requested_at=None,
)
pending_unit = SimpleNamespace(
id=42, document_id=102, intake_id=1, status='pending', result_json=None, position=2,
cancellation_requested_at=None,
)
plan = SimpleNamespace(id=4, unit_count=2, units=[ready_unit, pending_unit])
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else ready_unit)
monkeypatch.setattr(
handler, 'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
))),
)
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
position=SimpleNamespace(asc=lambda: None),
status=SimpleNamespace(in_=lambda *_a, **_k: True),
query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
order_by=lambda *_args: SimpleNamespace(all=lambda: [ready_unit, pending_unit]),
),
),
))
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: events.append('freeze_begin'))
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: events.append('freeze_complete'))
monkeypatch.setattr(
handler, 'materialize_order_extraction_run_inputs',
lambda _run, *, finalize_plan=True: events.append('finalize' if finalize_plan else 'materialize') or (plan if finalize_plan else None),
)
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: events.append('schedule') or False)
monkeypatch.setattr(
handler, 'order_extraction_layout_prerequisite_issues',
lambda _run: {102: 'layout_pending'},
)
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {101})
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True)
monkeypatch.setattr(
handler, 'transition_order_extraction_run',
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
)
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [ready_unit, pending_unit])
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
def _fake_transition(unit, *, target_status, **_kwargs):
unit.status = target_status
events.append(f'transition:{target_status}')
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
_fake_transition,
)
def _process(**_kwargs):
events.append('processed')
ready_unit.status = 'merging_supplement'
return [{'po_number': 'PO-1', '_hxops_intake_id': 1}]
monkeypatch.setattr(handler, '_process_unit_with_retries', _process)
monkeypatch.setattr(
handler, 'merge_unit_orders',
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
)
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {})
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
def fake_finish(*_args, **kwargs):
events.append('finished')
finished.update(kwargs)
monkeypatch.setattr(handler, 'finish_job', fake_finish)
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 4})
assert 'processed' in events
assert 'progressed' in events
assert 'terminalized' not in events
assert 'persist_started' not in events
assert run.phase == 'waiting_layout'
assert run.status == 'processing'
assert finished['result']['handoff_status'] == 'partial_units_done'
assert finished['result']['waiting_layout'] is True
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
"""版面 Job 创建失败(如 MinerU 关闭)时必须同步收口 Run,禁止仅失败 Job 而留下 queued。"""
import app.jobs.handlers.shipping_order_extraction as handler
@@ -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'
@@ -836,6 +1155,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'
@@ -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
@@ -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。
@@ -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()
@@ -182,3 +243,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')