feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
No files matched your search
@@ -1,11 +1,7 @@
|
||||
"""
|
||||
tests/services/shipping_notice/test_recovery_contract_phase1.py
|
||||
|
||||
用途:Phase 1 合同测试 — 锁定错误分类白名单与阻断→动作映射的纯函数矩阵。
|
||||
依赖:recovery_contract(is_tech_retryable_error、build_stp_job_blocked_manual_result、
|
||||
should_general_retry_be_removed、derive_blocking_next_actions)。
|
||||
逻辑:纯单元测,不依赖 DB/Worker,确保 T1 错误分类矩阵与 T3 动作注入判定
|
||||
与 Phase 1 冻结契约一致;一旦白名单/阻断规则被误修改将立即红。
|
||||
用途:恢复契约测试——失败必须停止,用户通过明确动作恢复。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,56 +13,11 @@ from app.services.shipping_notice.recovery_contract import (
|
||||
BLOCKING_REASON_TO_ACTION_CODES,
|
||||
REMOVE_ACTIONS_WHEN_BLOCKED,
|
||||
build_stp_job_blocked_manual_result,
|
||||
build_stp_job_failed_transient_result,
|
||||
derive_blocking_next_actions,
|
||||
is_tech_retryable_error,
|
||||
should_general_retry_be_removed,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# T1:is_tech_retryable_error 白名单矩阵(fail-closed)
|
||||
# ============================================================
|
||||
|
||||
T1_MATRIX = [
|
||||
# (error_code, category_hint, expected_retryable, case_label)
|
||||
('SHIPPING.TRANSIENT_NETWORK_TIMEOUT', None, True, 'TRANSIENT_ 前缀 → 技术临时网络'),
|
||||
('SHIPPING.TRANSIENT_STORAGE_CONNECTION', None, True, 'TRANSIENT_ 前缀 → 技术存储'),
|
||||
('SHIPPING.WORKER_TIMEOUT_LEASE_EXPIRED', None, True, 'WORKER_TIMEOUT_ 前缀'),
|
||||
('worker_timeout', 'worker_timeout', True, 'category_hint=worker_timeout'),
|
||||
('queue_unavailable', 'queue_unavailable', True, 'category_hint=queue_unavailable'),
|
||||
('temporary_network_error', 'temporary_network_error', True, 'category_hint 网络临时'),
|
||||
('temporary_storage_error', 'temporary_storage_error', True, 'category_hint 存储临时'),
|
||||
('external_service_5xx', 'external_service_5xx', True, 'category_hint 外部 5xx'),
|
||||
('lease_expired', 'lease_expired', True, 'category_hint 租约过期'),
|
||||
# 业务阻断码:默认不可重试(Q5 白名单制,不在即拒绝)
|
||||
('SHIPPING.NOTICE_EXACT_DUPLICATE', None, False, '精确重复 — 业务阻断,不可重试'),
|
||||
('SHIPPING.STP_NOT_ELIGIBLE', None, False, 'STP 资格不足 — 业务阻断'),
|
||||
('SHIPPING.REVIEW_DRAFT_MISSING', None, False, '草稿缺失 — 业务阻断'),
|
||||
('SHIPPING.REVIEW_RUN_MISSING', None, False, 'Run 缺失 — 业务阻断'),
|
||||
('SHIPPING.REVIEW_DOCUMENT_INVALID', None, False, '文档无效 — 业务阻断'),
|
||||
('SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT', None, False, '版本冲突 — 业务阻断,应 409 让前端刷新'),
|
||||
('profile_schema_mismatch', None, False, 'Profile 模板不匹配 — 业务阻断'),
|
||||
('final_required_field_missing', None, False, '关键字段缺失 — 业务阻断'),
|
||||
('duplicate_decision_required', None, False, '等待重复裁决 — 业务阻断'),
|
||||
# 空码/未知码:fail-closed(默认不可重试,不能因空码回退到 retryable=true)
|
||||
('', None, False, '空码 → fail-closed 不可重试'),
|
||||
('RANDOM.UNKNOWN_ERROR_XYZ', None, False, '未知码 → fail-closed 不可重试'),
|
||||
(None, None, False, 'None 码 → fail-closed 不可重试'),
|
||||
# category_hint 与前缀冲突:前缀优先(空码除外)
|
||||
('SHIPPING.TRANSIENT_NETWORK', 'worker_timeout', True, '前缀命中即使 hint 不同也可重试'),
|
||||
('trigger_not_claimed_missing', None, True, '库存 Trigger 缺失 → 技术重试'),
|
||||
('trigger_not_claimed_timeout', None, True, '库存 Trigger 超时 → 技术重试'),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('error_code, category_hint, expected, label', T1_MATRIX, ids=[m[3] for m in T1_MATRIX])
|
||||
def test_t1_is_tech_retryable_error_matrix(error_code, category_hint, expected, label):
|
||||
"""T1:错误码 → 是否允许技术自动重试(白名单制,fail-closed)。"""
|
||||
_ = label
|
||||
assert is_tech_retryable_error(error_code, category_hint=category_hint) is expected
|
||||
|
||||
|
||||
# ============================================================
|
||||
# T1-ext:build_stp_job_*_result 的结构契约(Q4 Job.result_json schema)
|
||||
# ============================================================
|
||||
@@ -92,20 +43,6 @@ def test_t1_blocked_manual_result_shape():
|
||||
assert 'decision_trace' in result
|
||||
|
||||
|
||||
def test_t1_transient_result_shape():
|
||||
"""技术临时错误 → retryable=true,blocking_reason/next_action 置空。"""
|
||||
result = build_stp_job_failed_transient_result(
|
||||
error_code='SHIPPING.TRANSIENT_NETWORK_TIMEOUT',
|
||||
message='Dify API 503',
|
||||
category_hint='external_service_5xx',
|
||||
)
|
||||
assert result['status'] == 'failed'
|
||||
assert result['retryable'] is True
|
||||
assert result['blocking_reason'] is None
|
||||
assert result['next_action'] is None
|
||||
assert result['contract_version'] == RECOVERY_CONTRACT_VERSION
|
||||
|
||||
|
||||
# ============================================================
|
||||
# T3:should_general_retry_be_removed + derive 动作矩阵(Q9 后端注入/删除动作)
|
||||
# ============================================================
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
收料报表配置管理接口测试。
|
||||
|
||||
用途:验证站点内独立收料配置的权限、DBS/Crane 规则及不可影响库存配置的边界。
|
||||
依赖:Flask 管理 API、库存站点测试种子、货代统一审计事件。
|
||||
逻辑:配置保存只更新 shipping_receipt_report_configs,并留存前后快照审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingAuditEvent, ShippingInventorySource, User
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
|
||||
def _headers(username: str, role: str) -> dict[str, str]:
|
||||
"""构造当前管理 API 使用的 Header 身份上下文。"""
|
||||
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def _create_users() -> None:
|
||||
"""创建管理员和普通接收人,验证收料配置不向业务用户开放。"""
|
||||
from app import db
|
||||
|
||||
db.session.add_all([
|
||||
User(username='receipt-admin', email='receipt-admin@example.com', role='admin', status='active'),
|
||||
User(username='receipt-user', email='receipt-user@example.com', role='user', status='active'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _dbs_payload() -> dict:
|
||||
"""构造 DBS 收料配置;日期未出现表示保持系统页面默认 NULL。"""
|
||||
return {
|
||||
'enabled': True,
|
||||
'report_path_json': {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
|
||||
},
|
||||
'warehouse_ids_json': ['AWSDU', 'AWSDU-02'],
|
||||
'query_parameters_json': [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}],
|
||||
}
|
||||
|
||||
|
||||
def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
"""DBS 收料配置按站点保存,不能变更既有库存路径、条件或版本。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
inventory_before = {
|
||||
'path': dict(source.report_path_json), 'parameters': list(source.query_parameters_json),
|
||||
'config_version': source.config_version,
|
||||
}
|
||||
|
||||
forbidden = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json=_dbs_payload(), headers=_headers('receipt-user', 'user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json=_dbs_payload(), headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
config = parse_api_data(response.get_json())
|
||||
assert config['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
assert config['report_path_json']['report_group'] == 'Inbound'
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.get(source_id)
|
||||
# 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义。
|
||||
assert source.report_path_json == inventory_before['path']
|
||||
assert source.query_parameters_json == inventory_before['parameters']
|
||||
assert source.config_version == inventory_before['config_version']
|
||||
audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
|
||||
).one()
|
||||
assert audit.before_snapshot_json is None
|
||||
assert audit.after_snapshot_json['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
|
||||
|
||||
def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, client):
|
||||
"""拒绝日期/selector 等 Driver 细节;DBS 与 Crane 的 Warehouse 规则必须分开。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
dbs_id = dbs.id
|
||||
from app import db
|
||||
crane_profile = dbs.rpa_profile.__class__(
|
||||
profile_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane',
|
||||
login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
source_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane',
|
||||
rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE',
|
||||
report_path_json={}, query_parameters_json=[], enabled=False,
|
||||
)
|
||||
db.session.add(crane_source)
|
||||
db.session.commit()
|
||||
crane_id = crane_source.id
|
||||
|
||||
invalid_date = _dbs_payload()
|
||||
invalid_date['query_parameters_json'] = [{'name': 'Report Date', 'mode': 'single', 'values': ['2026-08-19'], 'required': False, 'select_all': False}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=invalid_date, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
invalid_selector = _dbs_payload()
|
||||
invalid_selector['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': [], 'selector': '#owner'}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=invalid_selector, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
invalid_crane = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Other Report'},
|
||||
'warehouse_ids_json': ['NOT-ALLOWED'], 'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
json=invalid_crane, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
|
||||
def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
"""Crane 固定使用页面默认值直接 Run Report,管理员不能维护查询条件。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
from app import db
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = dbs.rpa_profile.__class__(
|
||||
profile_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane',
|
||||
login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
source_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane',
|
||||
rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE',
|
||||
report_path_json={}, query_parameters_json=[], enabled=False,
|
||||
)
|
||||
db.session.add(crane_source)
|
||||
db.session.commit()
|
||||
crane_id = crane_source.id
|
||||
|
||||
default_query = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Inbound Details'}, 'warehouse_ids_json': [],
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
json=default_query, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert parse_api_data(response.get_json())['query_parameters_json'] == []
|
||||
|
||||
configured = {**default_query, 'query_parameters_json': [
|
||||
{'name': 'material', 'mode': 'single', 'values': ['PN-01'], 'required': False, 'select_all': False},
|
||||
]}
|
||||
rejected = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
json=configured, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert rejected.status_code == 400
|
||||
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
@@ -1,147 +0,0 @@
|
||||
"""
|
||||
tests/test_conversation_retry_auto_progress.py
|
||||
|
||||
用途:锁定对话级重试自动推进的 eligible 判定、跳过原因与汇总结构。
|
||||
依赖:conversation_retry_auto_progress_service。
|
||||
逻辑:纯单元测跳过映射与 summary;不依赖完整 DB 工厂。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.conversation_retry_auto_progress_service import (
|
||||
ACTION_RETRY_AUTO_PROGRESS,
|
||||
_skip_reason_from_automation,
|
||||
_summarize_items,
|
||||
project_conversation_allowed_actions,
|
||||
)
|
||||
|
||||
|
||||
def test_formal_trigger_failure_overrides_stale_automation(monkeypatch):
|
||||
"""最新 Attempt 的 Trigger 缺失事实优先于历史 Job 的 needs_human 投影。"""
|
||||
from app.services.shipping_notice import conversation_retry_auto_progress_service as service
|
||||
|
||||
task = type('Task', (), {'task_no': 'OT-TRIGGER', 'id': 1})()
|
||||
class _Query:
|
||||
def filter_by(self, **_kwargs):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return task
|
||||
|
||||
monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts',
|
||||
lambda *_args, **_kwargs: {
|
||||
'latest_attempts': {
|
||||
'DSV360_AWSSL': {
|
||||
'status': 'failed',
|
||||
'error_code': 'trigger_not_claimed_missing',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert service._formal_task_has_retryable_inventory_trigger_failure('OT-TRIGGER') is True
|
||||
|
||||
|
||||
def test_failed_gate_job_does_not_count_as_active_attempt(monkeypatch):
|
||||
"""Attempt 残留 queued 但正式 Job 已失败时,不得继续投影 already_running。"""
|
||||
from app.services.shipping_notice import conversation_retry_auto_progress_service as service
|
||||
|
||||
task = type('Task', (), {'task_no': 'OT-STALE', 'id': 1})()
|
||||
|
||||
class _Query:
|
||||
def filter_by(self, **_kwargs):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return task
|
||||
|
||||
monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts',
|
||||
lambda *_args, **_kwargs: {'active_attempt_count': 0},
|
||||
)
|
||||
assert service._formal_task_has_active_attempt('OT-STALE') is False
|
||||
|
||||
|
||||
def test_skip_reason_maps_queued_and_not_retryable():
|
||||
"""queued → already_running;retryable=false → not_retryable。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'queued', 'retryable': False},
|
||||
task_missing=False,
|
||||
) == 'already_running'
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'waiting_to_start', 'retryable': False},
|
||||
task_missing=False,
|
||||
) == 'not_retryable'
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'failed', 'retryable': True},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_manual_fallback_human_owner_still_retryable():
|
||||
"""manual_fallback 虽 owner=human,但 retryable 时不得跳过。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'manual_fallback', 'retryable': True, 'owner_type': 'human'},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_inventory_needs_human_remains_retryable():
|
||||
"""库存快照/RPA 暂态 needs_human 必须继续进入库存重试决策器。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{
|
||||
'status': 'needs_human',
|
||||
'retryable': True,
|
||||
'reason_code': 'inventory_snapshot_prepare_failed',
|
||||
},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_missing_inventory_trigger_needs_human_remains_retryable():
|
||||
"""Trigger 未被领取的技术失败必须继续触发正式 OT 库存重试。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{
|
||||
'status': 'needs_human',
|
||||
'retryable': True,
|
||||
'error_code': 'trigger_not_claimed_missing',
|
||||
},
|
||||
task_missing=False,
|
||||
) is None
|
||||
|
||||
|
||||
def test_business_needs_human_stays_skipped():
|
||||
"""重复/短缺等业务裁决的 needs_human 不得触发库存 RPA。"""
|
||||
assert _skip_reason_from_automation(
|
||||
{
|
||||
'status': 'needs_human',
|
||||
'retryable': True,
|
||||
'reason_code': 'inventory_shortage',
|
||||
},
|
||||
task_missing=False,
|
||||
) == 'human_blocking'
|
||||
|
||||
|
||||
def test_task_missing_always_skipped():
|
||||
assert _skip_reason_from_automation(
|
||||
{'status': 'failed', 'retryable': True},
|
||||
task_missing=True,
|
||||
) == 'task_missing'
|
||||
|
||||
|
||||
def test_summarize_items_counts_outcomes():
|
||||
summary = _summarize_items([
|
||||
{'outcome': 'queued'},
|
||||
{'outcome': 'queued'},
|
||||
{'outcome': 'skipped', 'reason_code': 'already_running'},
|
||||
{'outcome': 'failed'},
|
||||
])
|
||||
assert summary == {'total': 4, 'retried': 2, 'skipped': 1, 'failed': 1, 'blocked': 0}
|
||||
|
||||
|
||||
def test_project_conversation_allowed_actions_empty_without_conversation():
|
||||
"""无 conversation_id 时不返回禁用空按钮。"""
|
||||
assert project_conversation_allowed_actions(user_id=1, conversation_id='') == []
|
||||
assert ACTION_RETRY_AUTO_PROGRESS == 'retry_auto_progress'
|
||||
@@ -16,13 +16,17 @@ from app.services.shipping_notice.order_supplement_merge import merge_email_supp
|
||||
SCHEMA = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']},
|
||||
{'field_id': 'customer-part', 'field_code': 'customer_part_number', 'scope': 'line', 'aliases': ['AMPN']},
|
||||
{'field_id': 'qty', 'field_code': 'qty'},
|
||||
{
|
||||
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'aliases': ['Reservation ID', 'External reservation ID'],
|
||||
'aliases': ['Reservation ID', 'External reservation ID', 'Reservation Number'],
|
||||
},
|
||||
{'field_id': 'allocation', 'field_code': 'allocation_id'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']},
|
||||
{'field_id': 'source-party', 'field_code': 'source_from_party', 'scope': 'line', 'aliases': ['source_from_party']},
|
||||
{'field_id': 'allocated-entity', 'field_code': 'allocated_entity', 'scope': 'line', 'aliases': ['allocated_entity']},
|
||||
{'field_id': 'allocated-qty', 'field_code': 'allocated_qty', 'scope': 'line', 'aliases': ['allocated_qty']},
|
||||
]}
|
||||
|
||||
|
||||
@@ -83,6 +87,125 @@ def test_email_supplement_external_reservation_id_alias_merges_real_mail_header(
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_ampn_alias_matches_customer_part_number():
|
||||
"""邮件 AMPN 应能与订单客户料号交叉关联并补入预约号。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'][0]['observations'][0]['value'] = 'D4-A08AR12000002'
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'customer-part', 'observations': [{'value': 'AMTEMP-S000218922'}],
|
||||
})
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='f' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>AMPN</th><th>Reservation Number</th></tr><tr><td>4518738152</td><td>AMTEMP-S000218922</td><td>33874</td></tr></table>'''],
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: {**supplement, 'document_id': 44}}, schema_definition=SCHEMA,
|
||||
)
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == '33874'
|
||||
|
||||
|
||||
def test_email_supplement_schema_field_fills_missing_part_number_from_pdf_customer_part_match():
|
||||
"""PDF 缺内部料号时,EML 的 Schema 内部料号应由 PO+客户料号唯一补齐。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'] = [
|
||||
{'field_id': 'customer-part', 'observations': [{'value': 'AMTEMP-S000218922'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 1}]},
|
||||
]
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='g' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>AMPN</th><th>Reservation Number</th></tr><tr><td>4518738152</td><td>D4-A08AR12000001</td><td>AMTEMP-S000218922</td><td>33874</td></tr></table>'''],
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: {**supplement, 'document_id': 44}}, schema_definition=SCHEMA,
|
||||
)
|
||||
fields = merged[0]['lines'][0]['fields']
|
||||
assert _value(fields, 'part') == 'D4-A08AR12000001'
|
||||
assert _value(fields, 'reservation') == '33874'
|
||||
|
||||
|
||||
def test_email_supplement_conflicting_schema_field_does_not_overwrite_pdf_or_pick_a_value():
|
||||
"""同一已关联行的 EML 字段多值必须逐字段转复核,禁止顺序覆盖。"""
|
||||
order = _order()
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'reservation_id': '33874', 'evidence': {}},
|
||||
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'reservation_id': '33875', 'evidence': {}},
|
||||
],
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert not any(item['field_id'] == 'reservation' for item in merged['lines'][0]['fields'])
|
||||
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
|
||||
|
||||
|
||||
def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review():
|
||||
"""PDF 与 EML 对同一 Schema 字段给出不同唯一值时不得静默接受任一方。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'reservation', 'observations': [{'value': 'PDF-33873'}],
|
||||
})
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [{
|
||||
'customer_po_number': '4518738152',
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': 'EML-33874',
|
||||
'evidence': {},
|
||||
}],
|
||||
}
|
||||
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == 'PDF-33873'
|
||||
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
|
||||
|
||||
|
||||
def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_numbers():
|
||||
"""邮件 PN/AMPN 均可与订单内部/客户料号交叉匹配,不依赖字段名称相同。"""
|
||||
scenarios = [
|
||||
('part_number', 'D4-A08AR12000002', 'part'),
|
||||
('part_number', 'AMTEMP-S000218922', 'customer-part'),
|
||||
('customer_part_number', 'D4-A08AR12000002', 'part'),
|
||||
('customer_part_number', 'AMTEMP-S000218922', 'customer-part'),
|
||||
]
|
||||
for index, (mail_field, value, order_field) in enumerate(scenarios, start=1):
|
||||
order = _order()
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'customer-part', 'observations': [{'value': 'AMTEMP-S000218922'}],
|
||||
})
|
||||
if order_field == 'part':
|
||||
order['lines'][0]['fields'][0]['observations'][0]['value'] = value
|
||||
supplement = {'document_id': 44, 'rows': [{
|
||||
'po_number': '4518738152', mail_field: value,
|
||||
'reservation_id': f'30000{index}', 'evidence': {},
|
||||
}]}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == f'30000{index}'
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_po_fallback_writes_unique_reservation_without_part_match():
|
||||
"""唯一 PO 兜底不得在写入阶段重新要求邮件料号匹配。"""
|
||||
result = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000001',
|
||||
'reservation_id': '33874', 'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '33874'
|
||||
assert result['_hxops_email_supplement_relation'] == 'po_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_po_fallback_requires_one_reservation():
|
||||
"""缺 MPN 时只有唯一 Reservation 的 PO 可广播;多 Reservation 必须复核。"""
|
||||
one = {'document_id': 44, 'rows': [{'po_number': '4518738152', 'reservation_id': '2000484577', 'evidence': {}}]}
|
||||
@@ -103,15 +226,15 @@ def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{
|
||||
'po_number': '4518738152', 'mpn': 'D4-A08AR12000002',
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'po_number': '4518738152', 'mpn': 'D4-A08AR12000002',
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'po_number': '4518838154', 'mpn': 'B3-AR1000270A1',
|
||||
'customer_po_number': '4518838154', 'part_number': 'B3-AR1000270A1',
|
||||
'reservation_id': '4000111701', 'evidence': {},
|
||||
},
|
||||
],
|
||||
@@ -133,9 +256,9 @@ def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_b
|
||||
)
|
||||
assert supplement['rows'] == [{
|
||||
'allocation_id': 'A-1', 'reservation_id': '2000484577',
|
||||
'source_from_party': 'Welltrust', 'source_type': 'DSB CMH',
|
||||
'allocated_entity': 'IEC-CJS', 'mpn': 'D4-A08AR12000002',
|
||||
'allocated_qty': '30', 'po_number': '4518838152',
|
||||
'source_from_party': 'Welltrust', 'inventory_source_hint': 'DSB CMH',
|
||||
'allocated_entity': 'IEC-CJS', 'part_number': 'D4-A08AR12000002',
|
||||
'allocated_qty': '30', 'customer_po_number': '4518838152',
|
||||
'evidence': supplement['rows'][0]['evidence'], 'table_index': None, 'row_index': 1,
|
||||
}]
|
||||
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
"""收料文件下载和人工补偿的权限/审计契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _headers(username: str, role: str) -> dict[str, str]:
|
||||
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client, monkeypatch):
|
||||
"""排程接收人可下载原样文件;非接收人不可通过猜测 ID 越权。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-download-user', email='receipt-download@example.com', role='user', status='active')
|
||||
other = User(username='receipt-other-user', email='receipt-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-DL', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-download', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/download.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='b' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
file_id = report_file.id
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_access.file_asset_storage.get_bytes', lambda _key: b'xlsx')
|
||||
|
||||
allowed = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-download-user', 'user'))
|
||||
denied = client.get(f'/api/workspace/receipt-report-files/{file_id}/download', headers=_headers('receipt-other-user', 'user'))
|
||||
assert allowed.status_code == 200
|
||||
assert allowed.data == b'xlsx'
|
||||
assert denied.status_code == 403
|
||||
|
||||
|
||||
def test_receipt_recipient_lists_only_own_archived_files(app, client):
|
||||
"""接收人文件列表仅返回本人排程归档,并且不得泄露对象存储定位。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-list-user', email='receipt-list@example.com', role='user', status='active')
|
||||
other = User(username='receipt-list-other', email='receipt-list-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
db.session.add_all([own_run, other_run]); db.session.flush()
|
||||
own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-list-own', status='success', config_snapshot_json={})
|
||||
other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-list-other', status='success', config_snapshot_json={})
|
||||
db.session.add_all([own_unit, other_unit]); db.session.flush()
|
||||
own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='d' * 64)
|
||||
db.session.add_all([own_file, ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/list-other.xlsx', original_filename='other.xlsx', file_size=4, sha256='e' * 64)])
|
||||
db.session.commit()
|
||||
own_file_id = own_file.id
|
||||
|
||||
response = client.get('/api/workspace/receipt-report-files', headers=_headers('receipt-list-user', 'user'))
|
||||
|
||||
assert response.status_code == 200
|
||||
items = response.get_json()['data']['items']
|
||||
# 关键断言:列表投影不能泄露非接收人的文件或对象存储定位。
|
||||
assert [item['id'] for item in items] == [own_file_id]
|
||||
assert 'storage_key' not in items[0]
|
||||
assert items[0]['download_url'].endswith(f'/receipt-report-files/{own_file_id}/download')
|
||||
|
||||
|
||||
def test_receipt_file_list_filters_before_applying_limit(app):
|
||||
"""其他人的新文件再多,也不能挤掉接收人较早的可见归档。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
from app.services.shipping_notice.receipt_report_access import list_receipt_report_files
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-limit-user', email='receipt-limit@example.com', role='user', status='active')
|
||||
other = User(username='receipt-limit-other', email='receipt-limit-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
db.session.add_all([own_run, other_run]); db.session.flush()
|
||||
own_unit = ShippingReceiptRpaUnitRun(schedule_run_id=own_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OWN', callback_id='receipt-limit-own', status='success', config_snapshot_json={})
|
||||
other_unit = ShippingReceiptRpaUnitRun(schedule_run_id=other_run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='OTHER', callback_id='receipt-limit-other', status='success', config_snapshot_json={})
|
||||
db.session.add_all([own_unit, other_unit]); db.session.flush()
|
||||
own_file = ShippingReceiptReportFile(unit_run_id=own_unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/limit-own.xlsx', original_filename='own.xlsx', file_size=4, sha256='f' * 64)
|
||||
db.session.add(own_file); db.session.flush()
|
||||
for index in range(3):
|
||||
db.session.add(ShippingReceiptReportFile(unit_run_id=other_unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'receipt/limit-other-{index}.xlsx', original_filename=f'other-{index}.xlsx', file_size=4, sha256=f'{index + 1}' * 64))
|
||||
db.session.commit()
|
||||
|
||||
items = list_receipt_report_files(recipient, limit=1)
|
||||
|
||||
# 关键断言:授权过滤发生在截断之前,避免被其他排程的归档饿死。
|
||||
assert [item['id'] for item in items] == [own_file.id]
|
||||
|
||||
|
||||
def test_admin_can_resend_without_reexporting(app, client, monkeypatch):
|
||||
"""管理员重发只调用文件投递,不创建 RPA 单元或 trigger。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
admin = User(username='receipt-resend-admin', email='receipt-resend-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RESEND', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-resend', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt/resend.xlsx', original_filename='receipt.xlsx', file_size=4, sha256='c' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
file_id = report_file.id
|
||||
calls = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.deliver_receipt_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0})
|
||||
|
||||
response = client.post(f'/api/admin/receipt-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
assert calls == [(file_id, True)]
|
||||
|
||||
|
||||
def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, client, monkeypatch):
|
||||
"""失败单元重试保留旧失败事实,创建新的 callback 单元和独立 trigger。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
admin = User(username='receipt-retry-admin', email='receipt-retry-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RETRY', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
failed = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-failed', status='failed', config_snapshot_json={'report_path_json': {}, 'query_parameters_json': []})
|
||||
db.session.add(failed); db.session.commit()
|
||||
failed_id = failed.id
|
||||
captured = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.write_receipt_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json')
|
||||
|
||||
response = client.post(f'/api/admin/receipt-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
with app.app_context():
|
||||
retry = ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=failed_id).one()
|
||||
assert retry.status == 'awaiting_rpa'
|
||||
assert retry.callback_id != 'receipt-failed'
|
||||
assert captured and captured[0][1][0]['callback_id'] == retry.callback_id
|
||||
|
||||
|
||||
def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client):
|
||||
"""管理员可见失败单元用于人工补偿;该接口会记录管理员查看审计。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun, User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
admin = User(username='receipt-units-admin', email='receipt-units-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-UNITS', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-admin-list', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
unit_id = unit.id
|
||||
|
||||
response = client.get('/api/admin/receipt-rpa-units?status=failed', headers=_headers('receipt-units-admin', 'admin'))
|
||||
|
||||
assert response.status_code == 200
|
||||
assert [item['id'] for item in response.get_json()['data']['items']] == [unit_id]
|
||||
with app.app_context():
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_units_listed').count() == 1
|
||||
@@ -0,0 +1,46 @@
|
||||
"""收料 RPA callback 的归档和幂等契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch):
|
||||
"""同一 callback 重放只归档一条收料文件,绝不创建库存快照。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
first = ingest_receipt_callback(payload)
|
||||
second = ingest_receipt_callback(payload)
|
||||
assert first['file_id'] == second['file_id']
|
||||
assert ShippingInventoryFile.query.count() == 0
|
||||
|
||||
|
||||
def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
|
||||
"""Callback cannot read arbitrary local xlsx files outside the receipt-only drop root."""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file
|
||||
|
||||
with app.app_context():
|
||||
allowed_root = tmp_path / 'receipt-drop'
|
||||
allowed_root.mkdir()
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
|
||||
outside = tmp_path / 'outside.xlsx'
|
||||
outside.write_bytes(b'not-a-real-xlsx')
|
||||
|
||||
with pytest.raises(ValidationError, match='receipt callback file'):
|
||||
_read_receipt_callback_file(str(outside))
|
||||
@@ -0,0 +1,65 @@
|
||||
"""收料文件企微投递和授权下载契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipients(app, monkeypatch):
|
||||
"""同一文件只向排程接收人发送一次,重放不会重复调用企微。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-recipient', email='recipient@example.com', role='user', status='active', wecom_userid='receipt-user')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-notify-callback', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.upload_wecom_temp_media', lambda *_args: 'media-1')
|
||||
calls: list[tuple] = []
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0})
|
||||
|
||||
assert deliver_receipt_file(report_file.id)['success_count'] == 1
|
||||
assert deliver_receipt_file(report_file.id)['success_count'] == 1
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_receipt_notification_failure_is_audited(app, monkeypatch):
|
||||
"""企微投递失败也必须保留接收人、时间、失败码和文件身份审计。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-unbound-recipient', email='receipt-unbound@example.com', role='user', status='active')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY-FAIL', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-notify-fail', status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
|
||||
outcome = deliver_receipt_file(report_file.id)
|
||||
|
||||
assert outcome['failed_count'] == 1
|
||||
audit = ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_file_notification_attempted', aggregate_id=str(report_file.id)).one()
|
||||
# 审计结果遵循统一枚举;业务投递状态仍保留为 failed。
|
||||
assert audit.result == 'failure'
|
||||
assert audit.after_snapshot_json['error_code'] == 'WECOM_USER_UNBOUND'
|
||||
@@ -0,0 +1,106 @@
|
||||
"""独立收料 RPA 排程的单元展开和 trigger 契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch):
|
||||
"""DBS 必须按 Warehouse 展开;Crane 固定为每站点一个单元。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingRpaProfile
|
||||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||||
|
||||
with app.app_context():
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
crane_profile = ShippingRpaProfile(profile_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', login_url='https://crane.invalid', login_config_json={'auth_mode': 'password'})
|
||||
crane = ShippingInventorySource(
|
||||
source_code='CRANE-RECEIPT', display_name='Crane', connector_type='crane', rpa_profile=crane_profile,
|
||||
parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, enabled=True, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, warehouse_ids_json=['A', 'B']),])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, enabled=True, report_path_json={'report_name': 'Inbound Details'}, warehouse_ids_json=[]))
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', job_params={'source_codes': [dbs.source_code, crane.source_code]})
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-1', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.commit()
|
||||
|
||||
captured = {}
|
||||
monkeypatch.setattr('app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger', lambda run_no, units, payload: captured.update(run_no=run_no, units=units, payload=payload) or 'receipt-trigger.json')
|
||||
total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run)
|
||||
|
||||
assert (total, success, failed, skipped, errors) == (3, 0, 0, 0, [])
|
||||
assert {(item['source_code'], item['warehouse_id']) for item in details} == {(dbs.source_code, 'A'), (dbs.source_code, 'B'), (crane.source_code, None)}
|
||||
assert captured['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert len(captured['units']) == 3
|
||||
dbs_unit = next(item for item in captured['units'] if item['source_code'] == dbs.source_code)
|
||||
# Worker only receives this frozen execution snapshot, not a later mutable site config.
|
||||
assert dbs_unit['rpa_profile_code'] == 'DBS_DUB_TEST'
|
||||
assert dbs_unit['login_url'] == 'https://test.invalid/dbs'
|
||||
assert dbs_unit['credential_envelope'] == {
|
||||
'username_ciphertext': None,
|
||||
'password_ciphertext': None,
|
||||
}
|
||||
assert dbs_unit['report_path_json']['report_name'] == 'Receipt Detail'
|
||||
assert dbs_unit['warehouse_id'] == 'A'
|
||||
|
||||
|
||||
def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
"""动态排程选项只暴露库存站点已启用且收料配置也启用的站点。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'},
|
||||
warehouse_ids_json=['A'],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
options = list_job_options('shipping_receipt_sources')
|
||||
|
||||
assert any(item['value'] == source.source_code for item in options)
|
||||
|
||||
|
||||
def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
"""无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='A', callback_id='receipt-timeout', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
|
||||
assert recover_stale_receipt_rpa_schedule_runs(task) == 1
|
||||
db.session.refresh(run); db.session.refresh(unit)
|
||||
|
||||
assert run.status == 'failed'
|
||||
assert unit.status == 'failed'
|
||||
assert unit.error_code == 'RPA.RECEIPT_CALLBACK_TIMEOUT'
|
||||
assert ShippingReceiptRpaUnitRun.query.filter_by(retry_of_id=unit.id).count() == 0
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_rpa_callback_timeout', aggregate_id=str(unit.id)).count() == 1
|
||||
|
||||
|
||||
def test_receipt_trigger_is_published_atomically(app, tmp_path):
|
||||
"""Worker 只能观察到完整 JSON;临时写入文件不会匹配其 *.json 扫描。"""
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
|
||||
written = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'receipt:atomic'}])
|
||||
|
||||
assert written is not None
|
||||
assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').is_file()
|
||||
assert not list(tmp_path.glob('*.tmp'))
|
||||
@@ -0,0 +1,43 @@
|
||||
"""独立收料 Worker 静态契约。"""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
|
||||
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'freight_receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text
|
||||
assert 'shipping_receipt_rpa.v1' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-batch-ready' in text
|
||||
assert 'freight_rpa_worker' not in text
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
|
||||
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
receipt_driver = (root / 'freight_receipt_crane_export.py').read_text(encoding='utf-8')
|
||||
crane_driver = (root / 'crane_report_export.py').read_text(encoding='utf-8')
|
||||
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver
|
||||
assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver
|
||||
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
module_path = root / 'freight_receipt_crane_export.py'
|
||||
sys.path.insert(0, str(root))
|
||||
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
assert module._inbound_details_entry_url('https://wms-portal.craneww.com/#/') == (
|
||||
'https://wms-portal.craneww.com/#/inbound-details-query'
|
||||
)
|
||||
assert module._inbound_details_entry_url('https://wms-portal.craneww.com/') == (
|
||||
'https://wms-portal.craneww.com/#/inbound-details-query'
|
||||
)
|
||||
@@ -26,6 +26,7 @@ def test_empty_rpa_snapshot_is_auditable_but_never_available_for_matching(app):
|
||||
)
|
||||
|
||||
# 关键断言:重放同一空结果不重复写审计;空快照不能污染匹配可用库存池。
|
||||
assert first.identity_status == 'unknown'
|
||||
assert repeated.id == first.id
|
||||
assert first.snapshot_status == 'empty'
|
||||
assert first.line_count == 0
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.models import (
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
|
||||
from tests.test_shipping_order_document_profile_service import _bind_ready_profile_sample, _schema_version
|
||||
|
||||
|
||||
@@ -86,8 +87,36 @@ def test_wizard_completion_invalid_main_table_rolls_back_without_profile(app):
|
||||
assert ShippingOrderDocumentProfileEditLease.query.count() == 0
|
||||
|
||||
|
||||
def test_wizard_xfa_mode_requires_authoritative_collection_not_table(app, monkeypatch):
|
||||
"""关键断言:XFA 样本向导拒绝缺失权威集合,且不要求 main_table_id。"""
|
||||
def test_public_identity_signature_owns_coordinate_run_lifecycle(app, monkeypatch):
|
||||
"""关键断言:坐标模板也不得回退到旧 layout runner 的独立生命周期。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
seed = ShippingOrderDocumentProfile(
|
||||
profile_code='SEED_SIGN', display_name='Seed', version=1, status='draft',
|
||||
schema_version_id=schema.id, structure_fingerprint='c' * 64,
|
||||
definition_json={}, template_mode='coordinate', lock_version=1,
|
||||
)
|
||||
db.session.add(seed)
|
||||
db.session.commit()
|
||||
sample = _bind_ready_profile_sample(seed.id)
|
||||
created = creation_service.complete_wizard(_wizard_payload(schema.id, sample.document_id), actor_id=None)
|
||||
lease = created['edit_lease']
|
||||
|
||||
def _legacy_runner_must_not_run(*_args, **_kwargs):
|
||||
raise AssertionError('public identity lifecycle must not dispatch to legacy coordinate runner')
|
||||
|
||||
monkeypatch.setattr(validation_service, 'run_layout_signature', _legacy_runner_must_not_run)
|
||||
signature = validation_service.run_profile_identity_signature(
|
||||
created['id'], data={}, actor_id=None, browser_session_id='wizard-tab-a',
|
||||
lease_token=lease['lease_token'], operation_id='coordinate-public-identity',
|
||||
)
|
||||
|
||||
assert signature['stored_status'] == 'passed'
|
||||
assert signature['run_type'] == 'layout_signature'
|
||||
|
||||
|
||||
def test_wizard_xfa_mode_creates_visual_main_table_draft_before_dataset_mapping(app, monkeypatch):
|
||||
"""关键断言:XFA 向导只冻结视觉主表;datasets 选择留给编辑映射,发布仍 fail-closed。"""
|
||||
from hashlib import sha256
|
||||
|
||||
from app.models import User
|
||||
@@ -130,28 +159,50 @@ def test_wizard_xfa_mode_requires_authoritative_collection_not_table(app, monkey
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
layout = dict(outcome.snapshot)
|
||||
layout['status'] = 'ready'
|
||||
layout['provider'] = 'xfa'
|
||||
layout['provider'] = 'mineru'
|
||||
layout['tables'] = [{'table_id': 'xfa-visual-main', 'page_no': 1}]
|
||||
layout['capability'] = {}
|
||||
layout['coordinate_evidence'] = {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
}
|
||||
layout.setdefault('xfa_capability', {})['structure_analysis_ready'] = True
|
||||
layout_version = record_inline_layout_snapshot(document, layout)
|
||||
persist_xfa_structure_analysis(
|
||||
document_id=document.id, layout_version_id=layout_version.id,
|
||||
source_content_hash=content_hash, outcome=outcome,
|
||||
)
|
||||
# 生产 Job 会在持久化 XFA analysis 后把 analysis_id 合并回同一视觉 Layout 快照。
|
||||
frozen_layout = dict(layout_version.payload_json)
|
||||
frozen_xfa_capability = dict(frozen_layout['xfa_capability'])
|
||||
frozen_xfa_capability['structure_analysis_id'] = outcome.analysis_record.id
|
||||
frozen_layout['xfa_capability'] = frozen_xfa_capability
|
||||
layout_version.payload_json = frozen_layout
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(Exception) as missing:
|
||||
with pytest.raises(Exception) as missing_table:
|
||||
creation_service.complete_wizard({
|
||||
'display_name': 'XFA', 'schema_version_id': schema.id, 'document_id': document.id,
|
||||
'browser_session_id': 'tab', 'operation_id': 'op-missing-auth',
|
||||
'authoritative_collection_path_id': _path_id_for('/data/ITEMS/DATA'),
|
||||
'browser_session_id': 'tab', 'operation_id': 'op-missing-table',
|
||||
}, actor_id=user.id)
|
||||
assert getattr(missing.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
assert getattr(missing_table.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'XFA', 'schema_version_id': schema.id, 'document_id': document.id,
|
||||
'authoritative_collection_path_id': _path_id_for('/data/ITEMS/DATA'),
|
||||
'browser_session_id': 'tab', 'operation_id': 'op-xfa-ok',
|
||||
'main_table_id': 'xfa-visual-main',
|
||||
'browser_session_id': 'tab', 'operation_id': 'op-xfa-draft-without-source',
|
||||
}, actor_id=user.id)
|
||||
assert created['template_mode'] == 'xfa_dataset'
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=created['id'], sample_role='annotation', table_id=None,
|
||||
profile_id=created['id'], sample_role='annotation', table_id='xfa-visual-main',
|
||||
).count() == 1
|
||||
assert created['definition']['main_table_id'] == 'xfa-visual-main'
|
||||
assert created['definition']['source_contract']['authoritative_line_collection_path'] is None
|
||||
assert created['definition']['line_mapping']['row_path'] is None
|
||||
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, created['id'])
|
||||
blocking = get_value_adapter(profile.definition_json).publish_checks(profile, validation=None)
|
||||
assert 'xfa_authoritative_collection_missing' in {item['key'] for item in blocking}
|
||||
@@ -35,7 +35,8 @@ def test_draft_save_creates_immutable_revision_and_same_operation_is_idempotent(
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='create-op')
|
||||
lease = _lease(draft['id'], session_id='tab-a', operation_id='lease-op')
|
||||
payload = _data(schema.id)
|
||||
payload['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.6
|
||||
# 保持两列不重叠:该测试验证 Revision/幂等而非覆盖坐标校验。
|
||||
payload['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.15
|
||||
payload.update({'expected_lock_version': draft['lock_version'], 'change_note': 'first edit'})
|
||||
first = profile_service.save_draft(
|
||||
payload,
|
||||
@@ -73,7 +74,8 @@ def test_edit_lease_conflict_takeover_and_restore_append_new_revision(app):
|
||||
|
||||
changed = _data(schema.id)
|
||||
changed['display_name'] = 'Changed profile name'
|
||||
changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.7
|
||||
# 保持两列不重叠:该测试验证租约接管与历史恢复。
|
||||
changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.15
|
||||
changed['expected_lock_version'] = draft['lock_version']
|
||||
saved = profile_service.save_draft(
|
||||
changed,
|
||||
|
||||
@@ -8,6 +8,11 @@ tests/test_order_document_profile_overlap_summary.py
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_document_profile_validation_service import build_cross_template_overlap_summary
|
||||
from app.services.shipping_notice.order_document_profile_validation_service import _evaluate_self_sample_match
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
ProfileMatchCandidate,
|
||||
ProfileMatchResult,
|
||||
)
|
||||
|
||||
|
||||
def test_overlap_summary_passes_when_all_self_unique():
|
||||
@@ -49,3 +54,24 @@ def test_overlap_summary_fails_on_false_hit_and_builds_conflicts():
|
||||
assert summary['false_hit_other_count'] == 1
|
||||
assert snapshot['conflict_profiles'][0]['profile_code'] == 'PO_B'
|
||||
assert 'false_hit' in snapshot['conflict_profiles'][0]['reason_codes']
|
||||
|
||||
|
||||
def test_overlap_ignores_ineligible_candidate_when_unique_match_has_no_eligible_rival():
|
||||
"""已判唯一命中时,未达自身资格的候选不得制造虚假 margin 失败。"""
|
||||
result = ProfileMatchResult(
|
||||
status='unique_match', profile_code='PO_A', version=1, margin=0.01,
|
||||
candidates=[ProfileMatchCandidate(
|
||||
profile_code='PO_A', version=1, score=1.0, evidence_coverage=0.8,
|
||||
hard_match=True, margin_to_next=0.01,
|
||||
)],
|
||||
)
|
||||
|
||||
outcome = _evaluate_self_sample_match(
|
||||
profile_code='PO_A', profile_version=1, match_result=result,
|
||||
parse_result={'passed': True},
|
||||
thresholds={'minimum_score': 0.9, 'minimum_margin': 0.12, 'evidence_coverage_minimum': 0.7},
|
||||
)
|
||||
|
||||
assert outcome['self_unique'] is True
|
||||
assert outcome['margin'] == 1.0
|
||||
assert outcome['margin_ok'] is True
|
||||
@@ -296,6 +296,59 @@ def test_frozen_sample_region_diagnostics_reads_only_configured_regions_in_visua
|
||||
}
|
||||
|
||||
|
||||
def test_frozen_region_diagnostics_retries_only_empty_hybrid_xfa_value_region_with_ocr(app, monkeypatch):
|
||||
"""Hybrid XFA 的原生标签不能掩盖同页视觉值框的 OCR 样本值。"""
|
||||
profile = SimpleNamespace(id=9, definition_json={
|
||||
'document_match': {'required_anchors': [{
|
||||
'anchor_id': 'po', 'label': 'ORDER NO', 'value': None, 'page_no': 1,
|
||||
'label_region': {'x0': .05, 'y0': .05, 'x1': .40, 'y1': .25},
|
||||
'value_region': {'x0': .45, 'y0': .05, 'x1': .95, 'y1': .25},
|
||||
}]},
|
||||
'table_regions': [], 'order_field_layouts': [], 'draft_unbound_order_field_layouts': [],
|
||||
})
|
||||
sample = SimpleNamespace(id=8)
|
||||
document = SimpleNamespace(id=7, filename='hybrid-xfa.pdf')
|
||||
asset = SimpleNamespace(id=6)
|
||||
native_label_glyphs = [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 8, 'y0': 10, 'x1': 16 + index * 8, 'y1': 20}}
|
||||
for index, char in enumerate('ORDER NO')
|
||||
]
|
||||
ocr_value_glyphs = [
|
||||
{'text': char, 'bbox': {'x0': 100 + index * 8, 'y0': 10, 'x1': 106 + index * 8, 'y1': 20}}
|
||||
for index, char in enumerate('4510039227')
|
||||
]
|
||||
layout = SimpleNamespace(payload_json={
|
||||
'tables': [],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': native_label_glyphs},
|
||||
},
|
||||
})
|
||||
calls: list[bool] = []
|
||||
|
||||
def recover(**kwargs):
|
||||
calls.append(bool(kwargs.get('force_ocr')))
|
||||
assert kwargs['force_ocr'] is True
|
||||
return {'width': 200, 'height': 100}, ocr_value_glyphs, 'ocr_coordinate'
|
||||
|
||||
monkeypatch.setattr(
|
||||
preview_service, '_frozen_sample_context',
|
||||
lambda **_kwargs: (profile, sample, document, layout, asset),
|
||||
)
|
||||
monkeypatch.setattr(preview_service, '_recover_frozen_page_coordinates', recover)
|
||||
monkeypatch.setattr(preview_service, '_audit', lambda **_kwargs: None)
|
||||
|
||||
with app.app_context():
|
||||
result = preview_service.frozen_sample_region_diagnostics(
|
||||
9, sample_binding_id=8, page_no=1, actor_id=1,
|
||||
)
|
||||
|
||||
by_id = {item['region_id']: item for item in result['items']}
|
||||
assert by_id['po_label']['recognized_value'] == 'ORDER NO'
|
||||
assert by_id['po_value']['recognized_value'] == '4510039227'
|
||||
assert calls == [True]
|
||||
|
||||
|
||||
def test_frozen_sample_region_diagnostics_without_coordinate_evidence_returns_empty(app, monkeypatch):
|
||||
"""缺少字符坐标证据时诊断为空,但不能把可预览 PDF 误报为页面不存在。"""
|
||||
profile = SimpleNamespace(id=9, definition_json={})
|
||||
|
||||
@@ -12,6 +12,26 @@ import pytest
|
||||
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileValidationRun
|
||||
from app.services.shipping_notice import order_document_profile_publish_check_service as checks
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
|
||||
|
||||
def test_adapter_publish_checks_keeps_xfa_rules_behind_a_common_hook():
|
||||
"""关键断言:公共发布编排只调用 adapter hook,不直接分叉 XFA 控制流。"""
|
||||
coordinate = ShippingOrderDocumentProfile(
|
||||
profile_code='COORDINATE_HOOK', display_name='Coordinate', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='a' * 64, definition_json={}, template_mode='coordinate',
|
||||
)
|
||||
xfa = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_HOOK', display_name='XFA', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='b' * 64,
|
||||
definition_json={'template_mode': 'xfa_dataset'}, template_mode='xfa_dataset',
|
||||
)
|
||||
xfa.schema_version = type('SV', (), {'definition_json': {'fields': []}})()
|
||||
|
||||
assert checks._adapter_publish_checks(coordinate, validation=None) == []
|
||||
assert 'xfa_structure_identity_missing' in {
|
||||
item['key'] for item in xfa_dataset.publish_checks(profile=xfa, validation=None)
|
||||
}
|
||||
|
||||
|
||||
def test_blocking_xfa_definition_flags_missing_paths_and_collection():
|
||||
@@ -47,13 +67,49 @@ def test_blocking_xfa_definition_flags_missing_paths_and_collection():
|
||||
profile.schema_version = type('SV', (), {'definition_json': {'fields': [
|
||||
{'field_id': 'f-po', 'field_code': 'customer_po_no', 'enabled': True, 'required': True},
|
||||
]}})()
|
||||
blocking = checks._blocking_xfa_definition(profile, None)
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
keys = {item['key'] for item in blocking}
|
||||
assert 'xfa_structure_identity_missing' in keys
|
||||
assert 'xfa_authoritative_collection_missing' in keys
|
||||
assert 'xfa_required_path_coverage_incomplete' in keys
|
||||
|
||||
|
||||
def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
"""关键断言:同名 header/line 字段缺路径时,发布诊断必须保留真实字段身份。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_SCOPE_DIAGNOSTIC', display_name='XFA Scope', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='c' * 64, template_mode='xfa_dataset',
|
||||
definition_json={
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:template', 'dataset_structure_fingerprint': 'sha256:structure',
|
||||
'dataset_root_path': '/data', 'authoritative_line_collection_path': '/data/ITEMS',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'bindings': [{
|
||||
'binding_id': 'header-reservation', 'field_id': 'reservation-header',
|
||||
'field_code': 'reservation_id', 'scope': 'header', 'field_layout_id': 'header-reservation',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'header-path', 'data_path': '/data/HEADER/RESERVATION'},
|
||||
}],
|
||||
'header_mappings': [], 'line_mapping': {'row_path': '/data/ITEMS', 'fields': []},
|
||||
'cross_checks': {},
|
||||
},
|
||||
)
|
||||
profile.schema_version = type('SV', (), {'definition_json': {'fields': [
|
||||
{'field_id': 'reservation-header', 'field_code': 'reservation_id', 'scope': 'header', 'enabled': True, 'required': False},
|
||||
{'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'required': True},
|
||||
]}})()
|
||||
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
coverage = next(item for item in blocking if item['key'] == 'xfa_required_path_coverage_incomplete')
|
||||
|
||||
# 同名显示码只是辅助信息;管理员必须能识别真正缺失的是 line 的 reservation_id。
|
||||
assert coverage['field_codes'] == ['reservation_id']
|
||||
assert coverage['missing_fields'] == [{
|
||||
'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
}]
|
||||
|
||||
|
||||
def test_blocking_xfa_definition_flags_stale_and_reconciliation():
|
||||
"""关键断言:stale 验证与对账失败码进入发布阻断。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
@@ -102,7 +158,7 @@ def test_blocking_xfa_definition_flags_stale_and_reconciliation():
|
||||
result_snapshot_json={},
|
||||
operation_id='recon',
|
||||
)
|
||||
blocking = checks._blocking_xfa_definition(profile, validation)
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=validation)
|
||||
keys = {item['key'] for item in blocking}
|
||||
assert 'current_validation_stale' in keys
|
||||
assert 'xfa_collection_ambiguity' in keys
|
||||
|
||||
@@ -8,13 +8,17 @@ backend/tests/test_order_document_profile_suggestion_service.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingOrderDocumentProfileSuggestionDecision
|
||||
from app.extensions import db
|
||||
from app.models import Job, ShippingOrderDocument, ShippingOrderDocumentProfileSuggestionDecision
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
from tests.test_shipping_order_document_profile_service import _data, _schema_version
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from tests.test_shipping_order_document_profile_service import _bind_ready_profile_sample, _data, _schema_version
|
||||
|
||||
|
||||
def _input() -> dict:
|
||||
@@ -48,3 +52,194 @@ def test_suggestion_decision_requires_active_lease(app):
|
||||
with pytest.raises(Exception) as missing:
|
||||
suggestion_service.decide(draft['id'], data=_input(), actor_id=None, browser_session_id='missing-tab', lease_token='invalid', operation_id='suggestion-missing')
|
||||
assert getattr(missing.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED'
|
||||
|
||||
|
||||
def test_suggestion_decision_audits_selected_visual_evidence_source(app):
|
||||
"""关键断言:多证据中确认的视觉来源进入审计,但不是正式值源绑定。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-evidence-create')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-evidence-tab', operation_id='suggestion-evidence-lease')
|
||||
payload = _input()
|
||||
summary = {**payload['suggestion_summary'], 'selected_evidence_source': 'opencv_geometry'}
|
||||
payload = {**payload, **suggestion_service.suggestion_identity(summary), 'suggestion_summary': summary}
|
||||
suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-evidence-tab', lease_token=lease['lease_token'], operation_id='suggestion-evidence-decision')
|
||||
decision = ShippingOrderDocumentProfileSuggestionDecision.query.filter_by(profile_id=draft['id']).one()
|
||||
assert decision.detail_json['selected_evidence_source'] == 'opencv_geometry'
|
||||
|
||||
|
||||
def test_suggestion_decision_accepts_xfa_widget_geometry_as_audited_visual_source(app):
|
||||
"""XFA Widget 几何仅作为已选视觉行来源,可审计但不改变 datasets 正式值源。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-widget-create')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-widget-tab', operation_id='suggestion-widget-lease')
|
||||
payload = _input()
|
||||
summary = {**payload['suggestion_summary'], 'selected_evidence_source': 'acroform_widget_geometry'}
|
||||
payload = {**payload, **suggestion_service.suggestion_identity(summary), 'suggestion_summary': summary}
|
||||
suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-widget-tab', lease_token=lease['lease_token'], operation_id='suggestion-widget-decision')
|
||||
decision = ShippingOrderDocumentProfileSuggestionDecision.query.filter_by(profile_id=draft['id']).one()
|
||||
assert decision.detail_json['selected_evidence_source'] == 'acroform_widget_geometry'
|
||||
|
||||
|
||||
def test_suggestion_decision_rejects_accept_without_required_visual_source(app):
|
||||
"""关键断言:后端不能被绕过前端,未选择多证据来源不得接受建议。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-required-create')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-required-tab', operation_id='suggestion-required-lease')
|
||||
payload = _input()
|
||||
summary = {**payload['suggestion_summary'], 'evidence_source_required': True, 'selected_evidence_source': None}
|
||||
payload = {**payload, **suggestion_service.suggestion_identity(summary), 'suggestion_summary': summary}
|
||||
with pytest.raises(Exception) as caught:
|
||||
suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-required-tab', lease_token=lease['lease_token'], operation_id='suggestion-required-decision')
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_suggestion_decision_recomputes_source_requirement_from_automark_job(app):
|
||||
"""关键断言:浏览器不能把 evidence_source_required 改为 false 绕过并行候选。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-job-create')
|
||||
sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-job-tab', operation_id='suggestion-job-lease')
|
||||
job = Job(
|
||||
domain='shipping_notice', job_type='shipping_pdf_automark', status='success',
|
||||
payload_json={
|
||||
'profile_id': draft['id'], 'document_id': sample.document_id, 'table_id': sample.table_id, 'page_no': 1,
|
||||
'layout_version_id': sample.layout_version_id, 'layout_payload_checksum': sample.layout_payload_checksum,
|
||||
},
|
||||
result_json={'candidates': [
|
||||
{'candidate_kind': 'table_reconstruction', 'evidence_sources': ['pdf_coordinate']},
|
||||
{'candidate_kind': 'table_reconstruction', 'evidence_sources': ['ocr_coordinate']},
|
||||
]},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
payload = _input()
|
||||
summary = {**payload['suggestion_summary'], 'automark_job_id': job.id, 'document_id': sample.document_id, 'table_id': sample.table_id, 'page_no': 1, 'evidence_source_required': False, 'selected_evidence_source': None}
|
||||
payload = {**payload, **suggestion_service.suggestion_identity(summary), 'suggestion_summary': summary}
|
||||
with pytest.raises(Exception) as caught:
|
||||
suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-decision')
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
selected = {**summary, 'selected_evidence_source': 'opencv_geometry'}
|
||||
invalid_payload = {**payload, **suggestion_service.suggestion_identity(selected), 'suggestion_summary': selected}
|
||||
with pytest.raises(Exception) as invalid:
|
||||
suggestion_service.decide(draft['id'], data=invalid_payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-invalid-source')
|
||||
assert getattr(invalid.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
sample.layout_payload_checksum = 'f' * 64
|
||||
db.session.commit()
|
||||
valid_source = {**summary, 'selected_evidence_source': 'pdf_coordinate'}
|
||||
stale_payload = {**payload, **suggestion_service.suggestion_identity(valid_source), 'suggestion_summary': valid_source}
|
||||
with pytest.raises(Exception) as stale:
|
||||
suggestion_service.decide(draft['id'], data=stale_payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-stale-layout')
|
||||
assert getattr(stale.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
# 恢复样本冻结身份后,模拟文档重解析完成而样本尚未重新冻结。
|
||||
sample.layout_payload_checksum = job.payload_json['layout_payload_checksum']
|
||||
document = db.session.get(ShippingOrderDocument, sample.document_id)
|
||||
document.current_layout_version.payload_checksum = 'e' * 64
|
||||
db.session.commit()
|
||||
with pytest.raises(Exception) as stale_current_checksum:
|
||||
suggestion_service.decide(draft['id'], data=stale_payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-stale-current-checksum')
|
||||
assert getattr(stale_current_checksum.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
# 恢复当前 Layout checksum 后,继续验证完整重解析导致的版本号失效。
|
||||
document.current_layout_version.payload_checksum = job.payload_json['layout_payload_checksum']
|
||||
db.session.commit()
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'status': 'ready',
|
||||
'pages': [{'page_no': 1}],
|
||||
'tables': [{
|
||||
'table_id': sample.table_id,
|
||||
'page_no': 1,
|
||||
'rows': [{'cells': [{'text': 'reparsed'}]}],
|
||||
'html': '<table><tr><td>reparsed</td></tr></table>',
|
||||
}],
|
||||
})
|
||||
db.session.commit()
|
||||
assert document.current_layout_version_id != sample.layout_version_id
|
||||
with pytest.raises(Exception) as stale_current_layout:
|
||||
suggestion_service.decide(draft['id'], data=stale_payload, actor_id=None, browser_session_id='suggestion-job-tab', lease_token=lease['lease_token'], operation_id='suggestion-job-stale-current-layout')
|
||||
assert getattr(stale_current_layout.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_suggestion_decision_requires_frozen_field_conflict_source_selection(app):
|
||||
"""关键断言:字段多证据冲突不能靠浏览器省略或伪造来源后直接接受。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-field-conflict-create')
|
||||
sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-field-conflict-tab', operation_id='suggestion-field-conflict-lease')
|
||||
job = Job(
|
||||
domain='shipping_notice', job_type='shipping_pdf_automark', status='success',
|
||||
payload_json={
|
||||
'profile_id': draft['id'], 'document_id': sample.document_id, 'table_id': sample.table_id, 'page_no': 1,
|
||||
'layout_version_id': sample.layout_version_id, 'layout_payload_checksum': sample.layout_payload_checksum,
|
||||
},
|
||||
result_json={
|
||||
'candidates': [
|
||||
{'candidate_kind': 'field_binding', 'evidence_sources': ['pdf_coordinate'], 'binding': {'field_id': 'f-po'}},
|
||||
{'candidate_kind': 'field_binding', 'evidence_sources': ['ocr_coordinate'], 'binding': {'field_id': 'f-po'}},
|
||||
],
|
||||
'diagnostics': {'field_conflicts': [{
|
||||
'code': 'field_binding_source_conflict', 'field_id': 'f-po',
|
||||
'sources': ['pdf_coordinate', 'ocr_coordinate'],
|
||||
}]},
|
||||
},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
base = {**_input()['suggestion_summary'], 'automark_job_id': job.id, 'document_id': sample.document_id, 'table_id': sample.table_id, 'page_no': 1}
|
||||
missing = {**_input(), **suggestion_service.suggestion_identity(base), 'suggestion_summary': base}
|
||||
with pytest.raises(Exception) as caught:
|
||||
suggestion_service.decide(draft['id'], data=missing, actor_id=None, browser_session_id='suggestion-field-conflict-tab', lease_token=lease['lease_token'], operation_id='suggestion-field-conflict-missing')
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
forged_summary = {**base, 'selected_field_evidence_sources': {'f-po': 'opencv_geometry'}}
|
||||
forged = {**_input(), **suggestion_service.suggestion_identity(forged_summary), 'suggestion_summary': forged_summary}
|
||||
with pytest.raises(Exception) as invalid:
|
||||
suggestion_service.decide(draft['id'], data=forged, actor_id=None, browser_session_id='suggestion-field-conflict-tab', lease_token=lease['lease_token'], operation_id='suggestion-field-conflict-invalid')
|
||||
assert getattr(invalid.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_verify_automark_evidence_rejects_job_when_current_layout_checksum_changed(monkeypatch):
|
||||
"""关键断言:当前 Layout 版本相同但内容已变化时,旧自动标记建议必须失效。"""
|
||||
job = SimpleNamespace(
|
||||
job_type='shipping_pdf_automark', status='success',
|
||||
payload_json={
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
|
||||
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
|
||||
},
|
||||
result_json={'candidates': []},
|
||||
)
|
||||
document = SimpleNamespace(
|
||||
current_layout_version_id=88,
|
||||
current_layout_version=SimpleNamespace(payload_checksum='b' * 64),
|
||||
)
|
||||
annotation = SimpleNamespace(layout_version_id=88, layout_payload_checksum='a' * 64)
|
||||
monkeypatch.setattr(
|
||||
suggestion_service.db.session,
|
||||
'get',
|
||||
lambda model, _ident: job if model is Job else document,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
suggestion_service, 'ShippingOrderDocumentProfileSample',
|
||||
SimpleNamespace(id=SimpleNamespace(asc=lambda: None), query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(first=lambda: annotation),
|
||||
),
|
||||
)),
|
||||
)
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
suggestion_service._verify_automark_evidence_source(
|
||||
profile_id=12,
|
||||
summary={'automark_job_id': 9001, 'document_id': 77, 'table_id': 'table-1'},
|
||||
selected_evidence_source=None,
|
||||
)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
@@ -8,6 +8,8 @@ tests/test_order_document_profile_validation_service.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
@@ -68,6 +70,21 @@ def test_current_sample_rejects_blind_test_binding(app):
|
||||
assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
|
||||
|
||||
def test_frozen_sample_layout_survives_source_document_retention_cleanup(monkeypatch):
|
||||
"""反向匹配只需冻结 Layout 时,原文档清理不能使发布模板失去可验证性。"""
|
||||
sample = SimpleNamespace(document_id=991, layout_version_id=771)
|
||||
frozen_layout = {'status': 'ready', 'tables': [], 'coordinate_evidence': {'pages': {}}}
|
||||
|
||||
def _get(model, identity):
|
||||
if model.__name__ == 'ShippingDocumentLayoutVersion' and identity == 771:
|
||||
return SimpleNamespace(payload_json=frozen_layout)
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(validation_service.db.session, 'get', _get)
|
||||
|
||||
assert validation_service._load_sample_layout(sample) == frozen_layout
|
||||
|
||||
|
||||
def test_failed_current_sample_run_remains_queryable(app):
|
||||
"""关键断言:运行时样本证据不可用也必须保存 failed 摘要,方便后续审计而非吞掉失败。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
tests/test_order_document_profile_validation_service_xfa_phase4.py
|
||||
|
||||
用途:阶段 4 XFA current_sample / xfa_structure_signature / stale 门禁 focused 验收。
|
||||
用途:阶段 4 XFA current_sample / 共同 layout_signature / stale 门禁 focused 验收。
|
||||
依赖:validation_service、creation_service、xfa helpers、pytest app fixture。
|
||||
逻辑:合成 XFA PDF → 向导草稿 → 保存映射 → 验证运行与结构签名;definition 变更后旧签名 stale。
|
||||
逻辑:合成 XFA PDF → 向导草稿 → 保存映射 → 共同验证运行与 layout signature;definition 变更后旧签名 stale。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,6 +15,7 @@ import pytest
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderDocumentProfileValidationRun,
|
||||
ShippingOrderSchema,
|
||||
@@ -68,10 +69,20 @@ def _schema_with_auto_create() -> ShippingOrderSchemaVersion:
|
||||
def _create_mapped_draft(*, user: User, schema: ShippingOrderSchemaVersion) -> tuple[dict, dict[str, str], str]:
|
||||
"""创建已映射 Header/Line 的 XFA 草稿并返回 lease token。"""
|
||||
document, paths, _ = _seed_xfa_sample(user=user)
|
||||
current_layout = dict(document.current_layout_version.payload_json)
|
||||
current_layout['tables'] = [{
|
||||
'table_id': 'visual-main-table',
|
||||
'page_no': 1,
|
||||
'html': '<table><tr><th>Material</th><th>Quantity</th></tr></table>',
|
||||
}]
|
||||
document.current_layout_version.payload_json = current_layout
|
||||
db.session.flush()
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'XFA Phase4 Draft',
|
||||
'schema_version_id': schema.id,
|
||||
'document_id': document.id,
|
||||
# 统一生命周期先冻结视觉主表;datasets 仅作为 bindings 的最终值源。
|
||||
'main_table_id': 'visual-main-table',
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'mirror_collection_path_ids': [paths['ITEMS1_DATA']],
|
||||
'browser_session_id': 'xfa-p4-tab',
|
||||
@@ -79,26 +90,47 @@ def _create_mapped_draft(*, user: User, schema: ShippingOrderSchemaVersion) -> t
|
||||
}, actor_id=user.id)
|
||||
lease = created['edit_lease']
|
||||
definition = dict(created['definition'])
|
||||
definition['header_mappings'] = [{
|
||||
'mapping_id': 'm-po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': paths['EBELN'],
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
}]
|
||||
definition['line_mapping'] = {
|
||||
'row_path': '/data/ITEMS/DATA',
|
||||
'fields': [
|
||||
{
|
||||
'mapping_id': 'm-mat', 'field_id': 'f-mat', 'field_code': 'material_no',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR', 'path_id': paths['MATNR'],
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
},
|
||||
{
|
||||
'mapping_id': 'm-qty', 'field_id': 'f-qty', 'field_code': 'quantity',
|
||||
'data_path': '/data/ITEMS/DATA/MENGE', 'path_id': _path_id_for('/data/ITEMS/DATA/MENGE'),
|
||||
'value_type': 'decimal', 'normalizer_key': 'trim',
|
||||
},
|
||||
definition['header_mappings'] = []
|
||||
definition['line_mapping'] = {'row_path': '/data/ITEMS/DATA', 'fields': []}
|
||||
definition['order_field_layouts'] = [
|
||||
{
|
||||
'layout_id': 'header_customer_po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'fallback_value_region': {'x0': 0.10, 'y0': 0.10, 'x1': 0.35, 'y1': 0.16},
|
||||
},
|
||||
]
|
||||
definition['table_regions'][0]['line_layouts'] = [{
|
||||
'layout_id': 'main_line', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0.05, 'y0': 0.35, 'x1': 0.60, 'y1': 0.50},
|
||||
'field_regions': [
|
||||
{'field_id': 'f-mat', 'field_code': 'material_no', 'scope': 'line',
|
||||
'region': {'x0': 0.10, 'y0': 0.35, 'x1': 0.35, 'y1': 0.42},
|
||||
'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'f-qty', 'field_code': 'quantity', 'scope': 'line',
|
||||
'region': {'x0': 0.40, 'y0': 0.35, 'x1': 0.55, 'y1': 0.42},
|
||||
'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
}
|
||||
'new_line_anchor': None, 'continuation_conditions': [],
|
||||
'required_fields': [], 'allowed_empty_fields': [],
|
||||
}]
|
||||
definition['table_regions'][0]['line_start_field_code'] = 'material_no'
|
||||
definition['bindings'] = [
|
||||
{
|
||||
'binding_id': 'bind-po-001', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'scope': 'header', 'field_layout_id': 'header_customer_po',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': paths['EBELN'], 'data_path': '/data/HEADER/EBELN'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-mat-001', 'field_id': 'f-mat', 'field_code': 'material_no',
|
||||
'scope': 'line', 'field_layout_id': 'main_line:material_no',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': paths['MATNR'], 'data_path': '/data/ITEMS/DATA/MATNR'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-qty-001', 'field_id': 'f-qty', 'field_code': 'quantity',
|
||||
'scope': 'line', 'field_layout_id': 'main_line:quantity',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': paths['MENGE'], 'data_path': '/data/ITEMS/DATA/MENGE'},
|
||||
},
|
||||
]
|
||||
definition['cross_checks'] = {
|
||||
'acroform_enabled': False,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
@@ -125,14 +157,65 @@ def test_current_sample_summary_still_supports_coordinate_schema_gate():
|
||||
status, summary, _ = validation_service._current_sample_summary(
|
||||
line_field_count=2, line_value_count=2, header_field_count=1, header_value_count=1,
|
||||
header_required_missing_count=0, auto_create_key_missing_count=1,
|
||||
sample_role='annotation', template_mode='xfa_dataset',
|
||||
sample_role='annotation', value_adapter='xfa_dataset',
|
||||
)
|
||||
assert status == 'failed'
|
||||
assert summary['failure_code'] == 'order_profile_current_sample_auto_create_key_missing'
|
||||
|
||||
|
||||
def test_xfa_current_sample_and_structure_signature_pass(app, _patch_xfa_io):
|
||||
"""关键断言:XFA current_sample 与 xfa_structure_signature 可通过并写入匹配引用。"""
|
||||
def test_instant_check_delegates_to_the_profile_value_adapter():
|
||||
"""关键断言:公共验证编排只调用 adapter 协议,不维护 datasets 分发表。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
|
||||
assert callable(get_value_adapter('coordinate').instant_summary)
|
||||
assert callable(get_value_adapter('xfa_dataset').instant_summary)
|
||||
|
||||
|
||||
def test_coordinate_validation_evidence_uses_the_same_field_and_line_shape_as_xfa():
|
||||
"""关键断言:坐标试读也输出 validation_evidence,页面无需按模板模式另取结果。"""
|
||||
evidence = validation_service._build_coordinate_validation_evidence(
|
||||
rows=[['MAT-1', '2']],
|
||||
field_codes=['material_no', 'quantity'],
|
||||
header_fields=[{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'value': 'PO-1', 'status': 'confirmed',
|
||||
}],
|
||||
)
|
||||
|
||||
assert evidence == {
|
||||
'header_fields': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'raw_value': 'PO-1',
|
||||
'normalized_value': 'PO-1', 'status': 'passed', 'issues': [],
|
||||
}],
|
||||
'lines': [{'row_index': 0, 'fields': [
|
||||
{'field_id': '', 'field_code': 'material_no', 'raw_value': 'MAT-1', 'normalized_value': 'MAT-1', 'status': 'passed', 'issues': []},
|
||||
{'field_id': '', 'field_code': 'quantity', 'raw_value': '2', 'normalized_value': '2', 'status': 'passed', 'issues': []},
|
||||
]}],
|
||||
'cross_checks': {},
|
||||
}
|
||||
|
||||
|
||||
def test_xfa_match_summary_keeps_the_shared_visual_match_contract(app, _patch_xfa_io):
|
||||
"""关键断言:XFA 摘要保留共同 matcher 字段,datasets 身份只能作为附加证据。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-summary', email='xfa-p4-summary@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = _schema_with_auto_create()
|
||||
draft, _paths, _lease_token = _create_mapped_draft(user=user, schema=schema)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
|
||||
summary = dict(profile.match_strategy_summary_json or {})
|
||||
|
||||
assert summary['template_mode'] == 'xfa_dataset'
|
||||
assert summary['main_table_id'] == 'visual-main-table'
|
||||
assert 'required_anchor_count' in summary
|
||||
assert 'table_region_count' in summary
|
||||
assert 'order_field_layout_count' in summary
|
||||
assert summary['value_adapter_evidence']['template_packet_checksum']
|
||||
assert summary['value_adapter_evidence']['dataset_structure_fingerprint']
|
||||
|
||||
|
||||
def test_xfa_current_sample_and_shared_layout_signature_pass(app, _patch_xfa_io):
|
||||
"""关键断言:XFA current_sample 与共同 layout_signature 可通过并写入匹配引用。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-val', email='xfa-p4-val@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
@@ -148,49 +231,99 @@ def test_xfa_current_sample_and_structure_signature_pass(app, _patch_xfa_io):
|
||||
lease_token=lease_token, operation_id='xfa-p4-instant',
|
||||
)
|
||||
assert instant['status'] == 'passed'
|
||||
assert instant['summary']['template_mode'] == 'xfa_dataset'
|
||||
assert instant['summary']['value_adapter'] == 'xfa_dataset'
|
||||
|
||||
current = validation_service.run_current_sample(
|
||||
draft['id'], data={'sample_binding_id': sample.id}, actor_id=user.id,
|
||||
browser_session_id='xfa-p4-tab', lease_token=lease_token, operation_id='xfa-p4-current',
|
||||
)
|
||||
assert current['status'] == 'passed'
|
||||
assert current['summary']['template_mode'] == 'xfa_dataset'
|
||||
assert current['summary']['value_adapter'] == 'xfa_dataset'
|
||||
assert current['summary']['validation_evidence']['header_fields']
|
||||
assert current['summary']['validation_evidence']['lines']
|
||||
assert int(current['summary'].get('header_required_missing_count') or 0) == 0
|
||||
assert int(current['summary'].get('auto_create_key_missing_count') or 0) == 0
|
||||
|
||||
signature = validation_service.run_xfa_structure_signature(
|
||||
signature = validation_service.run_profile_identity_signature(
|
||||
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease_token, operation_id='xfa-p4-sig',
|
||||
)
|
||||
assert signature['status'] == 'passed'
|
||||
assert signature['run_type'] == 'xfa_structure_signature'
|
||||
assert signature['run_type'] == 'layout_signature'
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
|
||||
assert profile.matching_signature_run_id == signature['id']
|
||||
assert profile.matching_signature_checksum
|
||||
assert profile.matching_signature_version.startswith('xfa-structure-signature')
|
||||
# Profile identity is the shared visual layout contract. The XFA
|
||||
# datasets fingerprint remains adapter evidence, never the matcher key.
|
||||
assert profile.matching_signature_version == 'order-profile-layout-signature'
|
||||
signature_run = db.session.get(
|
||||
ShippingOrderDocumentProfileValidationRun, signature['id'],
|
||||
)
|
||||
assert signature_run is not None
|
||||
signature_snapshot = signature_run.result_snapshot_json
|
||||
assert signature_snapshot['signature']['table_patterns']
|
||||
assert signature_snapshot['value_adapter_evidence']['adapter'] == 'xfa_dataset'
|
||||
|
||||
|
||||
def test_xfa_structure_signature_becomes_stale_after_definition_change(app, _patch_xfa_io):
|
||||
"""关键断言:definition checksum 变化后旧 xfa_structure_signature 查询态为 stale。"""
|
||||
def test_profile_identity_signature_resolves_xfa_adapter_run(app, _patch_xfa_io):
|
||||
"""关键断言:发布层只调用统一身份签名入口,XFA adapter 保留不可变审计 run_type。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-identity', email='xfa-p4-identity@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = _schema_with_auto_create()
|
||||
draft, _paths, lease_token = _create_mapped_draft(user=user, schema=schema)
|
||||
validation_service.run_profile_identity_signature(
|
||||
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease_token, operation_id='xfa-p4-identity-signature',
|
||||
)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile.id,
|
||||
).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first()
|
||||
assert revision is not None
|
||||
resolved = validation_service.resolve_profile_identity_signature(profile, revision)
|
||||
assert resolved.run_type == 'layout_signature'
|
||||
assert resolved.id == profile.matching_signature_run_id
|
||||
|
||||
|
||||
def test_public_identity_signature_entry_owns_xfa_run_lifecycle(app, _patch_xfa_io, monkeypatch):
|
||||
"""统一入口自己创建 Run;旧 XFA 入口不能再成为业务生命周期分支。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-public', email='xfa-p4-public@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = _schema_with_auto_create()
|
||||
draft, _paths, lease_token = _create_mapped_draft(user=user, schema=schema)
|
||||
|
||||
signature = validation_service.run_profile_identity_signature(
|
||||
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease_token, operation_id='xfa-p4-public-identity',
|
||||
)
|
||||
|
||||
assert signature['stored_status'] == 'passed'
|
||||
assert signature['run_type'] == 'layout_signature'
|
||||
|
||||
|
||||
def test_xfa_layout_signature_becomes_stale_after_definition_change(app, _patch_xfa_io):
|
||||
"""关键断言:definition checksum 变化后共同 layout_signature 查询态为 stale。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-stale', email='xfa-p4-stale@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = _schema_with_auto_create()
|
||||
draft, paths, lease_token = _create_mapped_draft(user=user, schema=schema)
|
||||
signature = validation_service.run_xfa_structure_signature(
|
||||
signature = validation_service.run_profile_identity_signature(
|
||||
draft['id'], data={}, actor_id=user.id, browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease_token, operation_id='xfa-p4-sig-stale',
|
||||
)
|
||||
stored = db.session.get(ShippingOrderDocumentProfileValidationRun, signature['id'])
|
||||
frozen = stored.definition_checksum
|
||||
definition = dict(draft['definition'])
|
||||
definition['header_mappings'] = [{
|
||||
'mapping_id': 'm-po2', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': paths['EBELN'],
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
}]
|
||||
definition['bindings'][0] = {
|
||||
**definition['bindings'][0],
|
||||
'binding_id': 'bind-po-002',
|
||||
}
|
||||
# 重新获取租约(保存后可能仍有效)
|
||||
lease = lease_service.acquire_lease(
|
||||
draft['id'], actor_id=user.id, browser_session_id='xfa-p4-tab', operation_id='xfa-p4-release',
|
||||
|
||||
@@ -8,12 +8,10 @@ tests/test_order_document_profile_version_service_xfa_phase4.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_document_profile_preview_service import (
|
||||
build_xfa_readonly_mapping_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.order_document_profile_version_service import (
|
||||
_definition_scale_summary,
|
||||
_xfa_structure_identity_summary,
|
||||
_value_source_identity_summary,
|
||||
)
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
|
||||
@@ -33,11 +31,11 @@ def test_xfa_definition_scale_and_identity_summary():
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': [{'mapping_id': 'm2'}]},
|
||||
}
|
||||
stats = _definition_scale_summary(definition)
|
||||
assert stats['template_mode'] == 'xfa_dataset'
|
||||
assert stats['value_adapter'] == 'xfa_dataset'
|
||||
assert stats['header_mapping_count'] == 1
|
||||
assert stats['line_mapping_count'] == 1
|
||||
assert stats['table_region_count'] == 0
|
||||
identity = _xfa_structure_identity_summary(definition)
|
||||
identity = _value_source_identity_summary(definition)
|
||||
assert identity['template_packet_checksum'] == 'sha256:tpl'
|
||||
assert identity['dataset_structure_fingerprint'] == 'sha256:fp'
|
||||
assert 'blind' not in str(identity).lower()
|
||||
@@ -79,9 +77,9 @@ def test_xfa_readonly_mapping_evidence_allows_pdf_preview():
|
||||
},
|
||||
},
|
||||
)
|
||||
evidence = build_xfa_readonly_mapping_evidence(profile)
|
||||
evidence = get_value_adapter('xfa_dataset').readonly_mapping_evidence(profile)
|
||||
assert evidence['pdf_preview_available'] is True
|
||||
assert evidence['template_mode'] == 'xfa_dataset'
|
||||
assert evidence['value_adapter'] == 'xfa_dataset'
|
||||
assert 'expected_rows' not in evidence
|
||||
assert 'expected_order_fields' not in evidence
|
||||
assert evidence['header_mappings'][0]['field_code'] == 'customer_po_no'
|
||||
@@ -99,6 +99,47 @@ def test_persist_prefers_formal_draft_line_key_over_matcher_temporary_key(app):
|
||||
assert added[0].shortage_qty == '16'
|
||||
|
||||
|
||||
def test_persist_derives_line_file_number_from_snapshot_when_matcher_omits_it(app):
|
||||
"""行级匹配结果漏带文件号时,持久化必须从已绑定快照补齐下载证据。"""
|
||||
from app.services.shipping_notice import line_inventory_match_persistence as svc
|
||||
|
||||
task = SimpleNamespace(id=1, inventory_snapshot_id=7)
|
||||
added = []
|
||||
snapshot = SimpleNamespace(inventory_file_no='SIF-SNAPSHOT-7')
|
||||
|
||||
with app.app_context():
|
||||
with (
|
||||
patch.object(svc, 'resolve_review_case_for_task', return_value=None),
|
||||
patch.object(svc, 'get_active_candidate_set', return_value=None),
|
||||
patch.object(svc, 'get_active_candidate_lines', return_value=[]),
|
||||
patch.object(svc, 'ShippingInventoryFile') as file_model,
|
||||
patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q,
|
||||
patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)),
|
||||
patch.object(svc.db.session, 'flush'),
|
||||
):
|
||||
file_model.query.get.return_value = snapshot
|
||||
match_q.filter_by.return_value.first.return_value = None
|
||||
match_q.filter_by.return_value.update.return_value = None
|
||||
svc.persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
inventory_snapshot_id=7,
|
||||
match_payload={
|
||||
'line_results': [{
|
||||
'line_index': 0,
|
||||
'disposition': 'shortage',
|
||||
'part_number': 'PN1',
|
||||
'reservation_id': 'R1',
|
||||
'required_qty': 2,
|
||||
'available_qty': 1,
|
||||
'shortage_qty': 1,
|
||||
}],
|
||||
'resolutions': [],
|
||||
},
|
||||
)
|
||||
|
||||
assert added[0].matched_file_no == 'SIF-SNAPSHOT-7'
|
||||
|
||||
|
||||
def test_unit_participates_in_match_key():
|
||||
"""BE-6:同料号预约单但单位不同不得命中。"""
|
||||
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
|
||||
|
||||
@@ -45,8 +45,8 @@ def _preview_intake(intake_no: str, attachments: list[dict], *, subject: str = '
|
||||
)
|
||||
|
||||
|
||||
def test_attachment_selection_snapshot_prefers_po_hints_and_skips_risky_duplicates():
|
||||
"""首轮仅选 2 个高相关附件;后续候选进入未来批次,风险附件和重复哈希必须稳定跳过。"""
|
||||
def test_attachment_selection_snapshot_materializes_all_budgeted_attachments_before_execution():
|
||||
"""预算内业务附件均在首轮物化;执行并发 2 不得把第三份附件推入扩批。"""
|
||||
snapshot = build_attachment_selection_snapshot(intakes=[
|
||||
_preview_intake(
|
||||
'SNI-A',
|
||||
@@ -121,19 +121,24 @@ def test_attachment_selection_snapshot_prefers_po_hints_and_skips_risky_duplicat
|
||||
# 内嵌签名资源不属于业务附件,不计入选择计划数量。
|
||||
assert snapshot['total_attachment_count'] == 5
|
||||
assert snapshot['eligible_attachment_count'] == 3
|
||||
assert snapshot['selected_attachment_count'] == 2
|
||||
assert snapshot['selected_attachment_count'] == 3
|
||||
assert snapshot['planned_attachment_count'] == 3
|
||||
assert snapshot['pending_expansion_attachment_count'] == 1
|
||||
assert snapshot['pending_expansion_batches'] == {'2': 1}
|
||||
assert snapshot['pending_expansion_attachment_count'] == 0
|
||||
assert snapshot['pending_expansion_batches'] == {}
|
||||
selected = [item for item in snapshot['items'] if item['selected']]
|
||||
assert [item['filename'] for item in selected] == ['PO_451883815A.pdf', 'booking_451883816.xlsx']
|
||||
assert [item['filename'] for item in selected] == [
|
||||
'PO_451883815A.pdf',
|
||||
'booking_451883816.xlsx',
|
||||
'order_notes.docx',
|
||||
]
|
||||
|
||||
by_name = {item['filename']: item for item in snapshot['items']}
|
||||
assert by_name['PO_451883815A_copy.pdf']['skip_reason_codes'] == ['duplicate_content_hash']
|
||||
assert 'customer-logo.png' not in by_name
|
||||
assert by_name['orders.zip']['skip_reason_codes'] == ['catalog_reason:archive']
|
||||
assert by_name['order_notes.docx']['skip_reason_codes'] == []
|
||||
assert by_name['order_notes.docx']['planned_selection_batch'] == 2
|
||||
assert by_name['order_notes.docx']['selection_batch'] == 1
|
||||
assert by_name['order_notes.docx']['planned_selection_batch'] is None
|
||||
assert by_name['PO_451883815A.pdf']['group_key'] == '451883815A'
|
||||
|
||||
|
||||
|
||||
@@ -29,6 +29,37 @@ TERMINAL_CASE_STATUSES = frozenset({
|
||||
})
|
||||
|
||||
|
||||
def test_stale_gate_job_stops_at_a_manual_failure_gate(app, monkeypatch):
|
||||
"""超时只记录失败并停在当前 Gate,不能伪装成“自动重试已耗尽”或自动续跑。"""
|
||||
from datetime import datetime, timedelta
|
||||
from app.services.shipping_notice import auto_progress_controller as controller
|
||||
|
||||
now = datetime.utcnow()
|
||||
job = SimpleNamespace(
|
||||
status='running',
|
||||
started_at=now - timedelta(seconds=600),
|
||||
gate_id=9,
|
||||
message=None,
|
||||
error_message=None,
|
||||
finished_at=None,
|
||||
locked_by='worker-1',
|
||||
locked_at=now,
|
||||
updated_at=None,
|
||||
)
|
||||
gate = SimpleNamespace(status='running', blocking_reason_code=None, updated_at=None)
|
||||
monkeypatch.setattr(controller, '_utc_now', lambda: now)
|
||||
monkeypatch.setitem(controller.current_app.config, 'SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 420)
|
||||
monkeypatch.setattr(controller.db.session, 'get', lambda *_args: gate)
|
||||
monkeypatch.setattr(controller.db.session, 'flush', lambda: None)
|
||||
|
||||
assert controller._recover_stale_active_job(job) is True
|
||||
assert job.status == 'failed'
|
||||
assert job.error_message == 'shipping_auto_progress_timeout'
|
||||
assert '允许重新入队' not in job.message
|
||||
assert gate.status == 'blocked_manual'
|
||||
assert gate.blocking_reason_code == 'technical_failure_present'
|
||||
|
||||
|
||||
# =========================================================================
|
||||
# 后端核心合同(9 项)
|
||||
# =========================================================================
|
||||
@@ -175,68 +206,40 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
|
||||
ensure_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(app):
|
||||
"""合同 4:Worker 启动 Sweeper → 扫描漏入队 Case → 协调器补偿建 STP Job。"""
|
||||
def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app):
|
||||
"""合同 4:恢复扫描只收敛超时事实,不能在失败后自动补建 STP Job。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
case = SimpleNamespace(
|
||||
id=4, case_no='SORC-P1-04', status='ready', confirmed_task_id=None,
|
||||
document_id=400, updated_at=None,
|
||||
)
|
||||
with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[4]), patch.object(
|
||||
sw, '_scan_stale_inventory_attempts', return_value=0,
|
||||
), patch.object(sw, '_recover_auto_progress_jobs', return_value=0), patch(
|
||||
with patch.object(sw, '_scan_stale_inventory_attempts', return_value=0), patch(
|
||||
'app.services.shipping_notice.shipping_recovery_sweeper_service.db',
|
||||
) as mock_db, patch.object(sw, 'ShippingOrderReviewCase') as ReviewCase, patch(
|
||||
) as mock_db, patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
|
||||
'reconcile_single_case_for_auto_progress',
|
||||
return_value={'case_no': 'SORC-P1-04', 'enqueue_status': 'queued',
|
||||
'job_id': 4404},
|
||||
) as coord_mock:
|
||||
mock_session = MagicMock()
|
||||
loaded = SimpleNamespace(id=4, status='ready', confirmed_task_id=None)
|
||||
mock_session.execute.return_value.scalar.return_value = None
|
||||
mock_session.begin_nested.return_value = MagicMock()
|
||||
type(mock_db).session = mock_session
|
||||
ReviewCase.query.filter_by.return_value.with_for_update.return_value.first.return_value = loaded
|
||||
count = sw.shipping_recovery_tick()
|
||||
|
||||
assert coord_mock.call_count == 1
|
||||
assert count >= 1
|
||||
assert coord_mock.call_count == 0
|
||||
assert count == 0
|
||||
|
||||
|
||||
def test_contract_04a_sweeper_skips_manual_draft_waiting_for_user_validation(app):
|
||||
"""人工草稿等待“保存并校验”时,恢复扫描不得再次改写 Draft 版本。"""
|
||||
def test_contract_04a_sweeper_only_commits_attempt_timeout_facts(app):
|
||||
"""恢复扫描没有 Case 自动推进入口,只提交库存 Attempt 的超时收敛结果。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
manual_case = SimpleNamespace(
|
||||
id=41,
|
||||
case_no='SORC-P1-04A',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
current_draft=SimpleNamespace(
|
||||
header_values_json={},
|
||||
lines_json=[{'values': {'part_number': {'source': 'manual', 'value': 'P-1'}}}],
|
||||
),
|
||||
)
|
||||
with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[41]), patch.object(
|
||||
sw, '_scan_stale_inventory_attempts', return_value=0,
|
||||
), patch.object(sw, '_recover_auto_progress_jobs', return_value=0), patch(
|
||||
'app.services.shipping_notice.shipping_recovery_sweeper_service.db',
|
||||
) as mock_db, patch.object(sw, 'ShippingOrderReviewCase') as review_case, patch(
|
||||
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
|
||||
'reconcile_single_case_for_auto_progress',
|
||||
) as coordinator:
|
||||
mock_session = MagicMock()
|
||||
mock_session.begin_nested.return_value = MagicMock()
|
||||
type(mock_db).session = mock_session
|
||||
review_case.query.filter_by.return_value.with_for_update.return_value.first.return_value = manual_case
|
||||
with patch.object(sw, '_scan_stale_inventory_attempts', return_value=0), patch.object(
|
||||
sw.db.session, 'commit',
|
||||
) as commit_mock:
|
||||
assert sw.shipping_recovery_tick() == 0
|
||||
|
||||
count = sw.shipping_recovery_tick()
|
||||
|
||||
# 这条 Case 必须留给用户显式保存;后台补偿不应启动校验或推进。
|
||||
assert count == 0
|
||||
coordinator.assert_not_called()
|
||||
commit_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
|
||||
@@ -287,29 +290,18 @@ def test_contract_05_recovery_tick_scans_stale_inventory_attempts(app):
|
||||
"""合同 5:shipping recovery tick 必须调用逐源库存超时扫描。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
with patch.object(sw, '_scan_stale_inventory_attempts', return_value=2) as scan_mock, \
|
||||
patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[]):
|
||||
with patch.object(sw, '_scan_stale_inventory_attempts', return_value=2) as scan_mock:
|
||||
count = sw.shipping_recovery_tick()
|
||||
|
||||
scan_mock.assert_called_once()
|
||||
assert count == 2
|
||||
|
||||
|
||||
def test_contract_05a_sweeper_respects_every_non_retryable_stp_failure(app):
|
||||
"""不可重试的 Schema 阻断不能被 Sweeper 通过新 Draft 版本绕过。"""
|
||||
from sqlalchemy.dialects import postgresql
|
||||
def test_contract_05a_sweeper_has_no_stp_candidate_query(app):
|
||||
"""失败链不再由 Sweeper 查询 Case 或补建 STP Job。"""
|
||||
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
|
||||
|
||||
captured = []
|
||||
with patch.object(sw.db.session, 'execute', side_effect=lambda stmt: captured.append(stmt) or MagicMock(fetchall=lambda: [])):
|
||||
assert sw._fetch_sweeper_case_candidates() == []
|
||||
|
||||
compiled = captured[0].compile(dialect=postgresql.dialect())
|
||||
sql = str(compiled)
|
||||
# 唯一裁决条件是 result_json.retryable=false,不能再按 blocking_reason 白名单漏拦。
|
||||
assert "result_json ->> %(result_json_1)s" in sql
|
||||
assert compiled.params['result_json_1'] == 'retryable'
|
||||
assert 'blocking_reason' not in compiled.params.values()
|
||||
assert not hasattr(sw, '_fetch_sweeper_case_candidates')
|
||||
|
||||
|
||||
def test_contract_05b_stp_schema_failure_stays_at_task_creation(app):
|
||||
@@ -340,7 +332,7 @@ def test_contract_05b_stp_schema_failure_stays_at_task_creation(app):
|
||||
assert bundle['user_stage'] == 'pre_ot_stp'
|
||||
assert bundle['user_current_gate_code'] == 'task_creation'
|
||||
assert bundle['current_gate']['gate_code'] == 'task_creation'
|
||||
assert bundle['current_gate']['next_action_code'] == 'edit_draft'
|
||||
assert bundle['current_gate']['next_action_code'] == 'retry_stp_auto_create'
|
||||
|
||||
|
||||
def test_contract_06_concurrent_sweep_produces_single_active_job_via_idempotency(app):
|
||||
@@ -367,8 +359,6 @@ def test_contract_06_concurrent_sweep_produces_single_active_job_via_idempotency
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.'
|
||||
'_persist_case_candidate_qualification', return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service._is_xfa_case', return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service._draft_has_manual_edits', return_value=False,
|
||||
), patch(
|
||||
@@ -563,7 +553,7 @@ def test_fe_01_stp_enqueue_missing_injects_blocking_reason(app):
|
||||
assert bundle is not None
|
||||
assert bundle['blocking_reason']['code'] == 'stp_enqueue_missing'
|
||||
assert bundle['user_status'] == 'retryable'
|
||||
assert bundle['primary_action']['code'] == 'retry_auto_progress'
|
||||
assert bundle['primary_action']['code'] == 'retry_stp_auto_create'
|
||||
assert bundle['user_stage'] == 'pre_ot_stp'
|
||||
|
||||
|
||||
@@ -592,7 +582,7 @@ def test_fe_02_retryable_shows_single_primary_action_only(app):
|
||||
assert bundle['user_status'] == 'retryable'
|
||||
primary = bundle.get('primary_action') or {}
|
||||
assert isinstance(primary, dict)
|
||||
assert primary.get('code') in {'retry_auto_progress', 'retry_stp_auto_create'}
|
||||
assert primary.get('code') == 'retry_stp_auto_create'
|
||||
# 短路由返回的 bundle 只包含 primary_action,不应出现 reconcile_and_progress
|
||||
assert primary.get('code') != 'reconcile_and_progress'
|
||||
|
||||
@@ -670,4 +660,4 @@ def test_fe_05_no_contradictory_waiting_manual_and_waiting_auto_together(app):
|
||||
# retryable 与 waiting_human 互斥:命中短路 stp_enqueue_missing 时,只能二选一
|
||||
assert status in {'retryable', 'waiting_human', 'running', 'failed', 'completed', 'cancelled'}
|
||||
assert not (status == 'retryable' and bundle.get('blocking_reason', {}).get('code') == 'order_review_required')
|
||||
assert not (status == 'waiting_human' and bundle.get('primary_action', {}).get('code') == 'retry_auto_progress')
|
||||
assert not (status == 'waiting_human' and bundle.get('primary_action', {}).get('code') == 'retry_stp_auto_create')
|
||||
@@ -6,267 +6,34 @@ backend/tests/test_shipping_chat_action_handlers.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.chat.action_schema import TurnInput
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.shipping_notice.chat_action_handlers import (
|
||||
ShippingCreateBatchFromIntakesAction,
|
||||
ShippingFreezeOrderAction,
|
||||
ShippingGenerateExcelAction,
|
||||
ShippingMarkManualUploadedAction,
|
||||
ShippingRetryUploadAction,
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_CODE,
|
||||
)
|
||||
from app.services.chat.action_registry import ensure_handlers_loaded, list_action_types
|
||||
|
||||
|
||||
def _create_task(user_id: int) -> str:
|
||||
from app.models import ShippingBatch, ShippingNotice
|
||||
def test_legacy_fulfillment_chat_actions_are_not_registered():
|
||||
"""正式 OT 的履约写只能经 Gate API,旧 Chat Turn 不得再有可解析处理器。"""
|
||||
ensure_handlers_loaded()
|
||||
|
||||
batch = ShippingBatch(batch_no="BATCH-HANDLER-001", user_id=user_id, file_count=1)
|
||||
task = ShippingNotice(
|
||||
task_no="SN-20260706-EFGH5678",
|
||||
batch=batch,
|
||||
user_id=user_id,
|
||||
source_type="manual",
|
||||
match_status="ok",
|
||||
)
|
||||
db.session.add_all([batch, task])
|
||||
db.session.commit()
|
||||
return task.task_no
|
||||
action_types = set(list_action_types())
|
||||
assert {
|
||||
"shipping.freeze_order",
|
||||
"shipping.generate_excel",
|
||||
"shipping.retry_upload",
|
||||
"shipping.match_inventory",
|
||||
"shipping.confirm_inventory_source",
|
||||
"shipping.submit_decision",
|
||||
"shipping.mark_manual_uploaded",
|
||||
}.isdisjoint(action_types)
|
||||
|
||||
|
||||
def test_generate_excel_handler_rejects_chat_turn(app, monkeypatch):
|
||||
"""关键断言:Chat Turn 不得再执行 generate_excel,须改走任务工作台。"""
|
||||
user = User(username="handler_user", email="handler_user@example.com", role="admin", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
task_no = _create_task(user.id)
|
||||
agent = Agent(
|
||||
name="货代发货通知 Agent",
|
||||
description="t",
|
||||
dify_api_key="k",
|
||||
api_base_url="http://example.com",
|
||||
agent_code="shipping_notice",
|
||||
runtime_provider="hybrid",
|
||||
conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
def test_legacy_workspace_fulfillment_routes_are_not_registered(app):
|
||||
"""正式 OT 只能通过 Gate API 写入,旧直写与转发路由不得回归。"""
|
||||
routes = {str(rule.rule) for rule in app.url_map.iter_rules()}
|
||||
|
||||
called = {"generate_excel": False}
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.chat_action_handlers.shipping_tools.generate_excel",
|
||||
lambda payload: called.update({"generate_excel": True}) or {"status": "ok"},
|
||||
)
|
||||
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-001",
|
||||
run_id="turn-001",
|
||||
session_id="sess-001",
|
||||
request_id="req-001",
|
||||
user=user,
|
||||
agent=agent,
|
||||
input=TurnInput(
|
||||
type="action",
|
||||
display_text="生成发货 Excel",
|
||||
action_type="shipping.generate_excel",
|
||||
payload={"task_no": task_no},
|
||||
),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingGenerateExcelAction().stream(ctx))
|
||||
|
||||
assert error.value.code == _CHAT_FULFILLMENT_WRITE_DISABLED_CODE
|
||||
assert called["generate_excel"] is False
|
||||
|
||||
|
||||
def test_create_batch_from_intakes_handler_forwards_candidate_nos(app, monkeypatch):
|
||||
"""Chat Turn Candidate 建批必须把选择集合透传后端,且不得引用未定义局部变量。"""
|
||||
user = User(username="candidate_handler", email="candidate-handler@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
agent = Agent(
|
||||
name="货代发货通知 Agent",
|
||||
description="t",
|
||||
dify_api_key="k",
|
||||
api_base_url="http://example.com",
|
||||
agent_code="shipping_notice",
|
||||
runtime_provider="hybrid",
|
||||
conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.commit()
|
||||
captured: dict = {}
|
||||
|
||||
def _fake_create(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": None,
|
||||
"message": "已打开已有任务,未创建新批次",
|
||||
"opened_existing": [{"candidate_no": "SNC-1", "task_no": "SN-EXISTING"}],
|
||||
"data": {"focus_task": {"task_no": "SN-EXISTING"}},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_intakes",
|
||||
_fake_create,
|
||||
)
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-candidate",
|
||||
run_id="turn-candidate",
|
||||
session_id="sess-candidate",
|
||||
request_id="req-candidate",
|
||||
user=user,
|
||||
agent=agent,
|
||||
input=TurnInput(
|
||||
type="action",
|
||||
display_text="确认两个订单",
|
||||
action_type="shipping.create_batch_from_intakes",
|
||||
payload={
|
||||
"intake_nos": ["SNI-1"],
|
||||
"candidate_nos": ["SNC-1", "SNC-2"],
|
||||
"idempotency_key": "idem-candidate-handler",
|
||||
},
|
||||
),
|
||||
refs={},
|
||||
)
|
||||
|
||||
events = list(ShippingCreateBatchFromIntakesAction().stream(ctx))
|
||||
|
||||
assert captured["intake_nos"] == ["SNI-1"]
|
||||
assert captured["candidate_nos"] == ["SNC-1", "SNC-2"]
|
||||
assert captured["conversation_id"] == "sess-candidate"
|
||||
assert any(event.event == "message.completed" for event in events)
|
||||
|
||||
|
||||
def test_freeze_order_handler_requires_the_chat_version_and_emits_snapshot(app):
|
||||
"""关键断言:Chat 冻结传递展示版本,成功后只以 Snapshot 继续履约。"""
|
||||
from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order
|
||||
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order()
|
||||
task.user_id = user.id
|
||||
agent = Agent(
|
||||
name="冻结订单 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
|
||||
agent_code="shipping_notice_freeze", runtime_provider="hybrid", conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-freeze", run_id="turn-freeze", session_id="sess-freeze", request_id="req-freeze",
|
||||
user=user, agent=agent,
|
||||
input=TurnInput(
|
||||
type="action", display_text="冻结订单", action_type="shipping.freeze_order",
|
||||
payload={"task_no": task.task_no, "expected_order_data_version": 7},
|
||||
),
|
||||
refs={"task_no": task.task_no},
|
||||
)
|
||||
|
||||
events = list(ShippingFreezeOrderAction().stream(ctx))
|
||||
|
||||
db.session.refresh(task)
|
||||
assert task.order_snapshot_id is not None
|
||||
assert "ui_state.updated" in [event.event for event in events]
|
||||
assert "message.completed" in [event.event for event in events]
|
||||
|
||||
|
||||
def test_manual_upload_handler_rejects_chat_turn_with_evidence(app, monkeypatch):
|
||||
"""关键断言:即便携带回执证据,Chat 也不得调用 upload_to_freight。"""
|
||||
user = User(username="manual-handler", email="manual-handler@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
task_no = _create_task(user.id)
|
||||
agent = Agent(
|
||||
name="手工上传 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
|
||||
agent_code="shipping_notice_manual", runtime_provider="hybrid", conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
called = {"upload": False}
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.chat_action_handlers.shipping_tools.upload_to_freight",
|
||||
lambda payload: called.update({"upload": True}) or {"status": "ok", "message": "已登记"},
|
||||
)
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-manual", run_id="turn-manual", session_id="sess-manual", request_id="req-manual",
|
||||
user=user, agent=agent,
|
||||
input=TurnInput(
|
||||
type="action", display_text="已上传", action_type="shipping.mark_manual_uploaded",
|
||||
payload={"task_no": task_no, "evidence_asset_no": "FA-RECEIPT-001"},
|
||||
),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingMarkManualUploadedAction().stream(ctx))
|
||||
|
||||
assert error.value.code == _CHAT_FULFILLMENT_WRITE_DISABLED_CODE
|
||||
assert called["upload"] is False
|
||||
|
||||
|
||||
def test_manual_upload_handler_rejects_chat_turn_without_evidence(app):
|
||||
"""关键断言:不能借助 Chat action 绕过人工上传截图/回执门禁。"""
|
||||
user = User(username="manual-handler-no-evidence", email="manual-handler-no-evidence@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
task_no = _create_task(user.id)
|
||||
agent = Agent(
|
||||
name="手工上传无证据 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
|
||||
agent_code="shipping_notice_manual_missing", runtime_provider="hybrid", conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-manual-missing", run_id="turn-manual-missing", session_id="sess-manual-missing", request_id="req-manual-missing",
|
||||
user=user, agent=agent,
|
||||
input=TurnInput(type="action", display_text="已上传", action_type="shipping.mark_manual_uploaded", payload={"task_no": task_no}),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingMarkManualUploadedAction().stream(ctx))
|
||||
|
||||
assert error.value.code == "SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED"
|
||||
|
||||
|
||||
def test_retry_upload_handler_rejects_chat_turn(app, monkeypatch):
|
||||
"""关键断言:Chat Turn 不得重试货代上传。"""
|
||||
user = User(username="retry-handler", email="retry-handler@example.com", role="user", status="active")
|
||||
user.set_password("password")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
task_no = _create_task(user.id)
|
||||
agent = Agent(
|
||||
name="重试上传 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
|
||||
agent_code="shipping_notice_retry", runtime_provider="hybrid", conversation_mode="task_chat",
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
called = {"upload": False}
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.chat_action_handlers.shipping_tools.upload_to_freight",
|
||||
lambda payload: called.update({"upload": True}) or {"status": "ok"},
|
||||
)
|
||||
ctx = TurnContext(
|
||||
turn_id="turn-retry", run_id="turn-retry", session_id="sess-retry", request_id="req-retry",
|
||||
user=user, agent=agent,
|
||||
input=TurnInput(
|
||||
type="action", display_text="重试上传", action_type="shipping.retry_upload",
|
||||
payload={"task_no": task_no},
|
||||
),
|
||||
refs={"task_no": task_no},
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as error:
|
||||
list(ShippingRetryUploadAction().stream(ctx))
|
||||
|
||||
assert error.value.code == _CHAT_FULFILLMENT_WRITE_DISABLED_CODE
|
||||
assert called["upload"] is False
|
||||
assert {
|
||||
'/api/workspace/shipping-tasks/<task_no>/confirm-inventory-source',
|
||||
'/api/workspace/shipping-tasks/<task_no>/submit-decision',
|
||||
'/api/workspace/shipping-tasks/<task_no>/freeze-order',
|
||||
'/api/workspace/shipping-tasks/<task_no>/match-inventory',
|
||||
'/api/workspace/shipping-tasks/<task_no>/generate-excel',
|
||||
'/api/workspace/shipping-tasks/<task_no>/retry-upload',
|
||||
}.isdisjoint(routes)
|
||||
@@ -948,7 +948,7 @@ def test_table_region_profile_allows_binding_internal_line_no():
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{
|
||||
'field_id': 'line', 'field_code': 'line_no',
|
||||
'field_id': 'line', 'field_code': 'line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
@@ -957,3 +957,30 @@ def test_table_region_profile_allows_binding_internal_line_no():
|
||||
profile = TableRegionProfile.model_validate(payload)
|
||||
assert profile.line_layouts[0].field_regions[0].field_code == 'line_no'
|
||||
assert profile.line_start_field_code == 'line_no'
|
||||
|
||||
|
||||
def test_table_region_profile_freezes_confirmed_visual_geometry_source_only():
|
||||
"""关键断言:视觉来源随 Layout 版本冻结,但不进入字段 allowed_sources。"""
|
||||
payload = {
|
||||
'region_id': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'line_start_field_code': 'line_no',
|
||||
'visual_evidence_source': 'opencv_geometry',
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{
|
||||
'field_id': 'line', 'field_code': 'line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
profile = TableRegionProfile.model_validate(payload)
|
||||
assert profile.visual_evidence_source == 'opencv_geometry'
|
||||
assert profile.line_layouts[0].field_regions[0].allowed_sources == ['pdf_coordinate']
|
||||
assert TableRegionProfile.model_validate({
|
||||
**payload, 'visual_evidence_source': 'acroform_widget_geometry',
|
||||
}).visual_evidence_source == 'acroform_widget_geometry'
|
||||
with pytest.raises(ValueError, match='visual_evidence_source'):
|
||||
TableRegionProfile.model_validate({**payload, 'visual_evidence_source': 'xfa_dataset'})
|
||||
@@ -59,7 +59,7 @@ def _assert_customer_gate_response(result: dict) -> None:
|
||||
"""断言 Tool 入口返回统一客户检查点。"""
|
||||
assert result['status'] == 'needs_human'
|
||||
assert result['checkpoint'] == 'customer_review'
|
||||
assert result['human_options'] == ['confirm_customer']
|
||||
assert 'human_options' not in result
|
||||
|
||||
|
||||
def test_pending_customer_blocks_every_downstream_entry(app):
|
||||
|
||||
@@ -185,8 +185,8 @@ def test_layout_job_exhaustion_fails_version_without_leaking_provider_error(app)
|
||||
assert 'shipping_document_layout_job_exhausted' in version.issues_json
|
||||
|
||||
|
||||
def test_layout_job_xfa_hybrid_skips_mineru_path(app):
|
||||
"""XFA hybrid 文档不得进入 MinerU/PDFium 表格路径。"""
|
||||
def test_layout_job_xfa_hybrid_keeps_xfa_identity_and_builds_visual_layout(app):
|
||||
"""XFA hybrid 必须保留 datasets 身份,同时进入统一视觉表格/Layout 管线。"""
|
||||
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
|
||||
|
||||
with app.app_context():
|
||||
@@ -197,7 +197,20 @@ def test_layout_job_xfa_hybrid_skips_mineru_path(app):
|
||||
return_value=pdf_bytes,
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
|
||||
) as mineru_mock:
|
||||
) as visual_layout_mock:
|
||||
visual_layout_mock.return_value = {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'provider': 'mineru',
|
||||
'status': 'ready',
|
||||
'tables': [{'table_id': 'visual-main', 'page_no': 1}],
|
||||
'capability': {},
|
||||
'layout_candidate': {'schema_version': 'shipping_document_layout.v1'},
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
},
|
||||
'issues': [],
|
||||
}
|
||||
run_shipping_document_layout(
|
||||
JobContext(config=dict(app.config), logger=None, extras={}),
|
||||
{'job_id': job.id},
|
||||
@@ -206,10 +219,10 @@ def test_layout_job_xfa_hybrid_skips_mineru_path(app):
|
||||
db.session.refresh(version)
|
||||
db.session.refresh(document)
|
||||
db.session.refresh(job)
|
||||
mineru_mock.assert_not_called()
|
||||
visual_layout_mock.assert_called_once()
|
||||
assert version.status == 'ready'
|
||||
assert version.payload_json.get('provider') == 'xfa'
|
||||
assert version.payload_json.get('tables') == []
|
||||
assert version.payload_json.get('provider') == 'mineru'
|
||||
assert version.payload_json.get('tables') == [{'table_id': 'visual-main', 'page_no': 1}]
|
||||
assert version.payload_json['xfa_capability']['structure_analysis_ready'] is True
|
||||
assert document.current_layout_version_id == version.id
|
||||
assert job.status == 'success'
|
||||
@@ -221,16 +234,22 @@ def test_layout_job_xfa_hybrid_skips_mineru_path(app):
|
||||
assert 'counts' not in version.payload_json
|
||||
|
||||
|
||||
def test_runtime_xfa_probe_skips_mineru_for_hybrid(app):
|
||||
"""runtime 在 XFA hybrid 探测成功后不得调用 MinerU。"""
|
||||
def test_runtime_xfa_visual_layout_does_not_create_unfrozen_value_source_capability(app):
|
||||
"""runtime 只提供共享视觉 Layout;正式 Job 才能冻结并附加 datasets capability。"""
|
||||
from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture
|
||||
|
||||
from tests.test_shipping_document_layout_runtime import _candidate
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL'] = 'http://mineru.test'
|
||||
pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
|
||||
with patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient',
|
||||
) as mineru_client:
|
||||
) as mineru_client, patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
|
||||
return_value=_candidate(),
|
||||
):
|
||||
from app.services.shipping_notice.document_layout.runtime import build_mineru_table_snapshot
|
||||
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
@@ -239,7 +258,7 @@ def test_runtime_xfa_probe_skips_mineru_for_hybrid(app):
|
||||
document_id=1,
|
||||
content_hash='a' * 64,
|
||||
)
|
||||
mineru_client.assert_not_called()
|
||||
mineru_client.return_value.parse_file_async.assert_called_once()
|
||||
assert snapshot is not None
|
||||
assert snapshot['provider'] == 'xfa'
|
||||
assert snapshot['tables'] == []
|
||||
assert 'xfa_capability' not in snapshot
|
||||
assert snapshot['provider'] != 'xfa'
|
||||
@@ -93,6 +93,75 @@ def test_layout_snapshot_checksum_and_idempotent_current_version(app):
|
||||
assert current_layout_snapshot(document)['marker'] == 'v1'
|
||||
|
||||
|
||||
def test_inline_derived_xfa_layout_localizes_structure_analysis_identity(app):
|
||||
"""坐标补证派生 Layout 必须克隆 XFA Analysis,样本可安全冻结到新版本。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
analysis = ShippingXfaStructureAnalysis(
|
||||
document_id=document.id,
|
||||
layout_version_id=None,
|
||||
source_content_hash=document.content_hash,
|
||||
document_kind='xfa_hybrid',
|
||||
analysis_status='ready',
|
||||
template_packet_checksum='sha256:template',
|
||||
datasets_packet_checksum='sha256:datasets',
|
||||
dataset_structure_fingerprint='sha256:structure',
|
||||
packet_checksums_json={'datasets': 'sha256:datasets'},
|
||||
stats_json={}, security_summary_json={}, tree_summary_json={},
|
||||
parser_identity='xfa-parser.v1', contract_version='xfa-contract.v1',
|
||||
)
|
||||
db.session.add(analysis)
|
||||
db.session.flush()
|
||||
first = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(marker='xfa-base'),
|
||||
'xfa_capability': {'structure_analysis_id': analysis.id},
|
||||
'capability': {'structure_analysis_id': analysis.id},
|
||||
})
|
||||
assert analysis.layout_version_id == first.id
|
||||
|
||||
derived = record_inline_layout_snapshot(document, {
|
||||
**dict(first.payload_json),
|
||||
'marker': 'xfa-coordinate-evidence',
|
||||
}, parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1')
|
||||
db.session.commit()
|
||||
|
||||
derived_analysis_id = derived.payload_json['xfa_capability']['structure_analysis_id']
|
||||
derived_analysis = db.session.get(ShippingXfaStructureAnalysis, derived_analysis_id)
|
||||
# 关键断言:新 Layout 与新 Analysis 一一绑定,旧分析仍保留原 Layout 审计身份。
|
||||
assert derived.id != first.id
|
||||
assert derived_analysis_id != analysis.id
|
||||
assert derived_analysis.layout_version_id == derived.id
|
||||
assert analysis.layout_version_id == first.id
|
||||
assert derived.payload_json['capability']['structure_analysis_id'] == derived_analysis.id
|
||||
|
||||
# 修复部署前已落库的派生快照按原 checksum 重放时,同样必须补齐新 identity。
|
||||
stale = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(marker='xfa-pre-fix-stale'),
|
||||
'xfa_capability': {'structure_analysis_id': analysis.id},
|
||||
'capability': {'structure_analysis_id': analysis.id},
|
||||
}, parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1')
|
||||
stale_payload = {
|
||||
**_snapshot(marker='xfa-pre-fix-stale'),
|
||||
'xfa_capability': {'structure_analysis_id': analysis.id},
|
||||
'capability': {'structure_analysis_id': analysis.id},
|
||||
}
|
||||
stale.payload_json = stale_payload
|
||||
stale.payload_checksum, stale.payload_size_bytes = canonical_layout_payload(stale_payload)
|
||||
db.session.flush()
|
||||
repaired = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(marker='xfa-pre-fix-stale'),
|
||||
'xfa_capability': {'structure_analysis_id': analysis.id},
|
||||
'capability': {'structure_analysis_id': analysis.id},
|
||||
}, parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1')
|
||||
repaired_analysis = db.session.get(
|
||||
ShippingXfaStructureAnalysis,
|
||||
repaired.payload_json['xfa_capability']['structure_analysis_id'],
|
||||
)
|
||||
assert repaired.id == stale.id
|
||||
assert repaired_analysis.id != analysis.id
|
||||
assert repaired_analysis.layout_version_id == repaired.id
|
||||
|
||||
|
||||
def test_failed_or_oversized_layout_does_not_replace_last_good_version(app):
|
||||
"""失败/超限版本必须可审计,但绝不能覆盖 Document 上一次成功布局。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 500
|
||||
@@ -198,8 +267,8 @@ def test_recoverable_ready_layout_is_reused_for_duplicate_document(app):
|
||||
assert scheduled.id != incomplete.id
|
||||
|
||||
|
||||
def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(app, monkeypatch):
|
||||
"""相同 XFA 文件复用时,目标 Document 必须获得独立 Analysis 并重写快照身份。"""
|
||||
def test_shared_visual_layout_reuse_localizes_xfa_structure_analysis(app, monkeypatch):
|
||||
"""共享视觉 Layout 带 datasets capability 时,复用必须本地化其结构分析身份。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
audit_events: list[str] = []
|
||||
|
||||
@@ -232,11 +301,13 @@ def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(ap
|
||||
db.session.flush()
|
||||
source_layout = record_inline_layout_snapshot(original, {
|
||||
'status': 'ready',
|
||||
'provider': 'xfa',
|
||||
'provider_version': 'xfa-parser.v1',
|
||||
'backend': 'pypdf',
|
||||
'provider': 'mineru',
|
||||
'provider_version': 'mineru-v1',
|
||||
'backend': 'pipeline',
|
||||
'snapshot_version': 'shipping_document_layout.v1',
|
||||
'tables': [],
|
||||
# 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁;datasets 仅为末端值源。
|
||||
'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': []}},
|
||||
'xfa_capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': source_analysis.id,
|
||||
@@ -281,8 +352,8 @@ def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(ap
|
||||
assert 'xfa_structure_analysis_reused' in audit_events
|
||||
|
||||
|
||||
def test_xfa_layout_without_source_analysis_is_not_reused(app, monkeypatch):
|
||||
"""XFA 快照声明 ready 但源 Analysis 缺失时必须重新排队,禁止复制伪 ready 状态。"""
|
||||
def test_legacy_xfa_only_layout_without_shared_visual_evidence_is_reparsed(app, monkeypatch):
|
||||
"""旧 XFA-only 快照缺共同视觉证据时一律重解析,不能保留格式专用复用分支。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
audit_events: list[str] = []
|
||||
|
||||
@@ -332,8 +403,7 @@ def test_xfa_layout_without_source_analysis_is_not_reused(app, monkeypatch):
|
||||
assert scheduled.status == 'queued'
|
||||
assert duplicate.current_layout_version_id is None
|
||||
assert ShippingXfaStructureAnalysis.query.filter_by(document_id=duplicate.id).count() == 0
|
||||
assert 'xfa_structure_analysis_reuse_rejected' in audit_events
|
||||
assert 'xfa_structure_analysis_reparse_queued' in audit_events
|
||||
assert not audit_events
|
||||
|
||||
|
||||
def test_layout_parser_fingerprint_change_creates_new_version_without_force(app, monkeypatch):
|
||||
|
||||
@@ -368,3 +368,23 @@ def test_runtime_attachment_budget_preserves_order_and_marks_overflow(app):
|
||||
assert rows[0]['layout_snapshot']['marker'] == 'first.pdf'
|
||||
assert rows[1]['layout_snapshot']['marker'] == 'second.pdf'
|
||||
assert rows[2]['layout_snapshot']['status'] == 'skipped_budget'
|
||||
def test_runtime_builds_xfa_visual_layout_without_creating_unfrozen_value_source_capability(app) -> None:
|
||||
"""关键断言:runtime 只构建共享视觉 Layout;datasets 身份只能由正式 Layout Job 冻结。"""
|
||||
candidate = _candidate()
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.MinerUClient',
|
||||
) as mineru, patch(
|
||||
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
|
||||
return_value=candidate,
|
||||
):
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL'] = 'http://mineru.test'
|
||||
mineru.return_value.parse_file_async.return_value = {'ok': True}
|
||||
snapshot = build_mineru_table_snapshot(
|
||||
filename='order.pdf', content=b'%PDF-xfa', document_id=9, content_hash='c' * 64,
|
||||
)
|
||||
|
||||
assert snapshot['status'] == 'ready'
|
||||
assert 'xfa_capability' not in snapshot
|
||||
assert snapshot['tables']
|
||||
mineru.return_value.parse_file_async.assert_called_once()
|
||||
@@ -181,6 +181,19 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
|
||||
return profile, user, documents
|
||||
|
||||
|
||||
def _independent_approver() -> User:
|
||||
"""创建与盲测编辑者不同的审批人,验证双人复核门禁。"""
|
||||
suffix = User.query.count() + 1
|
||||
approver = User(
|
||||
username=f'profile-quality-approver-{suffix}',
|
||||
email=f'profile-quality-approver-{suffix}@example.com',
|
||||
role='admin',
|
||||
)
|
||||
db.session.add(approver)
|
||||
db.session.flush()
|
||||
return approver
|
||||
|
||||
|
||||
def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
|
||||
"""将质量夹具改为最小 v2 草稿,使发布测试只覆盖阶段 4 边界。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
@@ -231,7 +244,10 @@ def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(a
|
||||
)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']
|
||||
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
with pytest.raises(Exception) as self_approval:
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert getattr(self_approval.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
|
||||
approved = quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
||||
assert approved['status'] == 'approved'
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
qualification = quality.qualification_summary(profile)
|
||||
@@ -675,7 +691,7 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
|
||||
)
|
||||
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
||||
profile.checksum = 'c' * 64
|
||||
db.session.commit()
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
@@ -799,7 +815,7 @@ def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(ap
|
||||
expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id,
|
||||
)
|
||||
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
||||
immutable_sample_id = db.session.get(ShippingDocumentProfileTestSuite, suite['id']).samples[0].id
|
||||
with pytest.raises(Exception) as caught:
|
||||
quality.remove_sample(suite_id=suite['id'], sample_id=immutable_sample_id, actor_id=user.id)
|
||||
@@ -920,7 +936,7 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'customer_po_line_no': '00010', 'part_number': 'PN-3', 'qty': '5'}], actor_id=user.id)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
|
||||
|
||||
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
assert published['status'] == 'published'
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
@@ -28,10 +29,8 @@ from app.services.shipping_notice import document_profile_quality_service as qua
|
||||
from app.services.shipping_notice.document_profile_quality_service import (
|
||||
MINIMUM_BLIND_SAMPLES,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_DOCUMENT_TABLE_ID,
|
||||
XFA_PARSER_IDENTITY,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_PARSER_IDENTITY
|
||||
from tests.test_shipping_xfa_helpers import FIXTURE_ROOT
|
||||
|
||||
|
||||
@@ -45,7 +44,43 @@ def test_xfa_blind_fixture_requires_independent_identity_and_full_accuracy():
|
||||
assert blind['required_accuracy']['line_count'] == 1.0
|
||||
assert blind['required_accuracy']['quantity_amount_date_normalization'] == 1.0
|
||||
assert MINIMUM_BLIND_SAMPLES >= 1
|
||||
assert XFA_DOCUMENT_TABLE_ID == 'xfa-authoritative-lines'
|
||||
|
||||
|
||||
def test_blind_candidate_comparison_is_shared_by_coordinate_and_xfa_adapters():
|
||||
"""关键断言:两类 adapter 统一按 order_fields 和 rows 与冻结真值比对。"""
|
||||
failures, total, matched = quality._compare_blind_candidate(
|
||||
candidate={
|
||||
'order_fields': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'value': 'PO-1', 'status': 'confirmed',
|
||||
}],
|
||||
'rows': [{'material_no': 'MAT-1', 'quantity': '2'}],
|
||||
},
|
||||
sample=SimpleNamespace(
|
||||
expected_order_fields_json={'header:customer_po_no': 'PO-1'},
|
||||
expected_rows_json=[{'material_no': 'MAT-1', 'quantity': '2'}],
|
||||
),
|
||||
schema_fields={'f-po': {}},
|
||||
)
|
||||
|
||||
assert failures == []
|
||||
assert (total, matched) == (3, 3)
|
||||
|
||||
|
||||
def test_cross_page_blind_gate_uses_shared_visual_table_rule_for_xfa():
|
||||
"""关键断言:XFA datasets 不得绕过共同视觉表区的跨页盲测门禁。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={
|
||||
'template_mode': 'xfa_dataset',
|
||||
'table_regions': [{
|
||||
'region_id': 'lines',
|
||||
'continuation_rule': {'allow_cross_page': True},
|
||||
}],
|
||||
},
|
||||
)
|
||||
|
||||
assert quality._requires_cross_page_sample(profile) is True
|
||||
|
||||
|
||||
def test_serialize_suite_does_not_leak_blind_truths():
|
||||
@@ -59,7 +94,7 @@ def test_serialize_suite_does_not_leak_blind_truths():
|
||||
'samples': [{
|
||||
'id': 3,
|
||||
'document_id': 88,
|
||||
'table_id': XFA_DOCUMENT_TABLE_ID,
|
||||
'table_id': 'visual-main-table',
|
||||
'filename': '',
|
||||
'page_no': 1,
|
||||
}],
|
||||
@@ -121,8 +156,8 @@ def _make_sample_document(*, user: User, suffix: str) -> ShippingOrderDocument:
|
||||
return document
|
||||
|
||||
|
||||
def test_xfa_list_independent_samples_returns_confirmable_document_candidate(app):
|
||||
"""关键断言:XFA 草稿列出文档级结构分析候选,confirmable=True 且不走坐标表。"""
|
||||
def test_xfa_list_independent_samples_returns_confirmable_visual_table_candidate(app):
|
||||
"""关键断言:XFA 盲测冻结视觉主表,datasets 仅保留为末端值源身份。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-p4-quality', email='xfa-p4-quality@example.com', role='admin')
|
||||
schema = ShippingOrderSchema(schema_code='XFA_P4Q', display_name='XFA P4Q')
|
||||
@@ -151,6 +186,7 @@ def test_xfa_list_independent_samples_returns_confirmable_document_candidate(app
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'main_table_id': 'visual-main-table',
|
||||
'cross_checks': {
|
||||
'acroform_enabled': False, 'mirror_collection_policy': 'ignore',
|
||||
'line_amount_formula': 'disabled', 'total_amount_policy': 'disabled',
|
||||
@@ -161,10 +197,23 @@ def test_xfa_list_independent_samples_returns_confirmable_document_candidate(app
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id, document_id=annotation_doc.id,
|
||||
table_id=XFA_DOCUMENT_TABLE_ID, sample_role='annotation', created_by_id=user.id,
|
||||
table_id='visual-main-table', sample_role='annotation', created_by_id=user.id,
|
||||
))
|
||||
db.session.add(ShippingXfaStructureAnalysis(
|
||||
blind_layout_version = record_inline_layout_snapshot(blind_doc, {
|
||||
'status': 'ready',
|
||||
'tables': [{
|
||||
'table_id': 'visual-main-table', 'page_no': 1,
|
||||
'html': '<table><tr><th>Material</th></tr></table>',
|
||||
}],
|
||||
'coordinate_evidence': {
|
||||
'tables': {'visual-main-table': [{'text': 'Material'}]},
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
},
|
||||
'xfa_capability': {'structure_analysis_ready': True},
|
||||
})
|
||||
blind_analysis = ShippingXfaStructureAnalysis(
|
||||
document_id=blind_doc.id,
|
||||
layout_version_id=blind_layout_version.id,
|
||||
source_content_hash=str(blind_doc.content_hash),
|
||||
document_kind='xfa_hybrid',
|
||||
analysis_status='ready',
|
||||
@@ -177,20 +226,37 @@ def test_xfa_list_independent_samples_returns_confirmable_document_candidate(app
|
||||
tree_summary_json={},
|
||||
parser_identity=XFA_PARSER_IDENTITY,
|
||||
contract_version='xfa-structure-analysis.v1',
|
||||
))
|
||||
)
|
||||
db.session.add(blind_analysis)
|
||||
db.session.flush()
|
||||
blind_layout_version.payload_json = {
|
||||
**blind_layout_version.payload_json,
|
||||
'xfa_capability': {
|
||||
**blind_layout_version.payload_json['xfa_capability'],
|
||||
'structure_analysis_id': blind_analysis.id,
|
||||
},
|
||||
}
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=profile.structure_fingerprint, created_by_id=user.id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:XFA 与普通 PDF 都从共同视觉 Layout 生成盲测候选;
|
||||
# adapter 不再拥有列举、预览身份或样本冻结等生命周期步骤。
|
||||
adapter_samples = quality._common_blind_sample_descriptors(
|
||||
profile=profile, document=blind_doc,
|
||||
)
|
||||
assert adapter_samples[0]['table_id'] == 'visual-main-table'
|
||||
assert adapter_samples[0]['confirmable'] is True
|
||||
|
||||
listed = quality.list_independent_samples(suite_id=suite.id, actor_id=user.id)
|
||||
samples = listed['samples']
|
||||
assert samples, 'XFA blind candidate list must not be empty'
|
||||
assert all(item['table_id'] == XFA_DOCUMENT_TABLE_ID for item in samples)
|
||||
assert all(item['table_id'] == 'visual-main-table' for item in samples)
|
||||
match = next(item for item in samples if int(item['document_id']) == int(blind_doc.id))
|
||||
assert match['confirmable'] is True
|
||||
assert match['review_mode'] == 'formal_review'
|
||||
assert match['layout_version_id']
|
||||
assert match['layout_payload_checksum'] == 'sha256:ds'
|
||||
assert match['layout_payload_checksum'] == blind_layout_version.payload_checksum
|
||||
assert annotation_doc.id not in {int(item['document_id']) for item in samples}
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
tests/test_shipping_eml_preview_service.py
|
||||
|
||||
用途:锁定 EML 安全预览清洗与快照复用契约。
|
||||
依赖:eml_preview_service。
|
||||
逻辑:预览仅保留安全正文布局;图片、脚本和外部资源不得进入浏览器。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.eml_preview_service import (
|
||||
EML_PREVIEW_MAX_BYTES,
|
||||
consume_eml_preview_grant,
|
||||
issue_eml_preview_grant,
|
||||
sanitize_eml_preview_html,
|
||||
highlight_eml_preview_html,
|
||||
)
|
||||
from app.services.shipping_notice.eml_parse import extract_eml_preview_html
|
||||
|
||||
|
||||
def test_sanitize_eml_preview_keeps_table_and_safe_inline_style():
|
||||
"""安全预览保留表格和有限样式,但剥离主动内容及图片。"""
|
||||
html = '<div style="color:red;position:fixed" onclick="bad()"><table><tr><td>PO</td></tr></table><img src="cid:logo"><a href="https://x">link</a><script>bad()</script></div>'
|
||||
|
||||
preview = sanitize_eml_preview_html(html)
|
||||
|
||||
# 关键断言:视觉结构可读,执行、追踪和定位样式均不可进入预览。
|
||||
assert '<table>' in preview
|
||||
assert 'color: red' in preview
|
||||
assert 'position' not in preview
|
||||
assert 'onclick' not in preview
|
||||
assert '<img' not in preview
|
||||
assert 'href' not in preview
|
||||
assert '<script' not in preview
|
||||
|
||||
|
||||
def test_sanitize_eml_preview_keeps_safe_background_shorthand_for_light_text():
|
||||
"""Outlook 表头常以 background 简写搭配白字;清洗后必须同时保留,避免文字不可见。"""
|
||||
html = '<table><tr><td style="background:#ED7D31;color:white">PO</td></tr></table>'
|
||||
|
||||
preview = sanitize_eml_preview_html(html)
|
||||
|
||||
# 关键断言:纯色背景可保留,url 等外部背景资源仍由样式解析器拒绝。
|
||||
assert 'background: #ED7D31' in preview
|
||||
assert 'color: white' in preview
|
||||
|
||||
|
||||
def test_eml_preview_html_size_limit_is_finite():
|
||||
"""安全预览快照必须有固定尺寸上限,超限邮件回退文本而非撑大工作台。"""
|
||||
assert EML_PREVIEW_MAX_BYTES == 500_000
|
||||
|
||||
|
||||
def test_extract_eml_preview_html_preserves_the_raw_html_table_and_head_style():
|
||||
"""视觉预览必须读取原始 HTML MIME,而不是复用已扁平化的文本抽取路径。"""
|
||||
eml = b"""MIME-Version: 1.0\r
|
||||
Content-Type: multipart/alternative; boundary=preview\r
|
||||
\r
|
||||
--preview\r
|
||||
Content-Type: text/plain; charset=utf-8\r
|
||||
\r
|
||||
PO\tQty\r
|
||||
--preview\r
|
||||
Content-Type: text/html; charset=utf-8\r
|
||||
\r
|
||||
<html><head><style>.order { border-collapse: collapse; } .order td { border: 1px solid #000; width: 120px; }</style></head><body><table class=\"order\"><tr><td>PO</td><td>Qty</td></tr></table><img src=\"cid:logo\"><script>alert(1)</script></body></html>\r
|
||||
--preview--\r
|
||||
"""
|
||||
|
||||
preview = extract_eml_preview_html(eml)
|
||||
|
||||
# 关键断言:保留供浏览器排版的 table/head/style/class,主动内容和 CID 图片必须剥离。
|
||||
assert '<table class="order">' in preview
|
||||
assert 'border-collapse' in preview
|
||||
assert '<head>' in preview
|
||||
assert '<img' not in preview
|
||||
assert '<script' not in preview
|
||||
|
||||
|
||||
def test_eml_preview_grant_is_single_use_and_bound_to_the_case(monkeypatch):
|
||||
"""iframe 无法带 Bearer Header 时,预览 URL 必须使用短时且不可重放的 Case 绑定令牌。"""
|
||||
class Store:
|
||||
def __init__(self):
|
||||
self.items = {}
|
||||
|
||||
def setex(self, key, _ttl, value):
|
||||
self.items[key] = value
|
||||
|
||||
def getdel(self, key):
|
||||
return self.items.pop(key, None)
|
||||
|
||||
monkeypatch.setattr('app.services.shipping_notice.eml_preview_service._eml_preview_grant_store', lambda: Store())
|
||||
# 同一个 Store 必须跨签发/消费调用复用。
|
||||
store = Store()
|
||||
monkeypatch.setattr('app.services.shipping_notice.eml_preview_service._eml_preview_grant_store', lambda: store)
|
||||
|
||||
token = issue_eml_preview_grant(user_id=7, case_no='CASE-1', document_id=9, html='<table><tr><td>PO</td></tr></table>')
|
||||
|
||||
assert consume_eml_preview_grant(token=token, user_id=7, case_no='CASE-1') == '<table><tr><td>PO</td></tr></table>'
|
||||
assert consume_eml_preview_grant(token=token, user_id=7, case_no='CASE-1') == ''
|
||||
|
||||
|
||||
def test_highlight_eml_preview_html_marks_one_unique_evidence_quote_only():
|
||||
"""字段证据只在安全 HTML 中唯一命中引文时加标记,避免全文值猜测。"""
|
||||
html = '<html><body><p>PO: 33894</p><p>Qty: 10</p></body></html>'
|
||||
|
||||
highlighted = highlight_eml_preview_html(html, '33894')
|
||||
|
||||
assert highlighted.count('<mark') == 1
|
||||
assert '33894' in highlighted
|
||||
assert highlight_eml_preview_html(html, 'missing') == html
|
||||
@@ -155,7 +155,7 @@ def test_build_explainability_reason_unknown_requires_request_id():
|
||||
|
||||
def test_technical_failure_alias_and_gate_request_id_fallback():
|
||||
"""
|
||||
technical_failure 须归一为 technical_retry_exhausted;Gate 投影无 HTTP 上下文时回退 execution_no。
|
||||
技术失败须归一为中性失败码;Gate 投影无 HTTP 上下文时回退 execution_no。
|
||||
|
||||
核心逻辑:别名对齐契约;_resolve_explainability_request_id 保证未知失败可追溯。
|
||||
"""
|
||||
@@ -166,8 +166,9 @@ def test_technical_failure_alias_and_gate_request_id_fallback():
|
||||
)
|
||||
|
||||
# [STEP 1] 历史写入码归一到契约稳定码
|
||||
assert canonicalize_reason_code('technical_failure') == 'technical_retry_exhausted'
|
||||
assert message_zh_for_reason('technical_retry_exhausted')
|
||||
assert canonicalize_reason_code('technical_failure') == 'technical_failure_present'
|
||||
assert canonicalize_reason_code('technical_retry_exhausted') == 'technical_failure_present'
|
||||
assert message_zh_for_reason('technical_failure_present')
|
||||
|
||||
# [STEP 2] Worker 无 HTTP request_id 时不得用 execution_no 冒充
|
||||
execution = SimpleNamespace(execution_no='PEX-TEST-001')
|
||||
@@ -194,7 +195,7 @@ def test_technical_failure_alias_and_gate_request_id_fallback():
|
||||
# [STEP 4] 抽取失败/取消别名不得再降级为 unknown
|
||||
assert canonicalize_reason_code('SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED') == 'order_extraction_failed'
|
||||
assert canonicalize_reason_code('SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED') == 'order_extraction_cancelled'
|
||||
assert message_zh_for_reason('technical_retry_exhausted')
|
||||
assert message_zh_for_reason('technical_failure_present')
|
||||
failed = build_explainability_reason(reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED')
|
||||
assert failed['reason_code'] == 'order_extraction_failed'
|
||||
assert failed['next_action'] == 'retry_order_extraction'
|
||||
@@ -202,6 +203,7 @@ def test_technical_failure_alias_and_gate_request_id_fallback():
|
||||
assert cancelled['reason_code'] == 'order_extraction_cancelled'
|
||||
assert cancelled['next_action'] == 'open_order_review'
|
||||
retry_meta = build_explainability_reason(reason_code='technical_retry_exhausted')
|
||||
assert retry_meta['reason_code'] == 'technical_failure_present'
|
||||
assert retry_meta['next_action'] == 'open_order_review'
|
||||
|
||||
|
||||
@@ -327,6 +329,9 @@ def test_audit_reason_code_mapping_for_rpa_and_notice_replace():
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'inventory_rpa_failed', {'error': 'login timeout'},
|
||||
) == 'inventory_rpa_timeout'
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'inventory_rpa_failed', {'error': 'Crane scheduled report not ready for download within 300000ms'},
|
||||
) == 'inventory_rpa_timeout'
|
||||
assert _audit_reason_code_for_task_event(
|
||||
'inventory_rpa_failed', {'error': 'auth rejected'},
|
||||
) == 'inventory_rpa_login_failed'
|
||||
|
||||
@@ -23,7 +23,14 @@ from app.models import (
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice.export import _excel_business_no, _filename, _mapping_value, _system_fact, generate_shipment_excel
|
||||
from app.services.shipping_notice.export import (
|
||||
_excel_business_no,
|
||||
_filename,
|
||||
_mapping_value,
|
||||
_system_fact,
|
||||
_template_requires_system_warehouse_id,
|
||||
generate_shipment_excel,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_lines_for_task,
|
||||
@@ -47,6 +54,28 @@ def _inventory_field_id(field_code: str) -> str:
|
||||
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
|
||||
|
||||
|
||||
def test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fact():
|
||||
"""模板将库位作为 inventory_field 消费时,不得被任务级 Warehouse ID 门禁误拦。"""
|
||||
assert _template_requires_system_warehouse_id([
|
||||
{
|
||||
'sheet': 'PVMI Pull Request Header',
|
||||
'row_mode': 'header',
|
||||
'target_column': 1,
|
||||
'source_kind': 'inventory_field',
|
||||
'source_key': '7',
|
||||
},
|
||||
]) is False
|
||||
assert _template_requires_system_warehouse_id([
|
||||
{
|
||||
'sheet': 'Header',
|
||||
'row_mode': 'header',
|
||||
'target_column': 2,
|
||||
'source_kind': 'system_fact',
|
||||
'source_key': 'warehouse_id',
|
||||
},
|
||||
]) is True
|
||||
|
||||
|
||||
def _freeze_export_snapshot(
|
||||
task: ShippingNotice, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
|
||||
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
|
||||
@@ -259,8 +288,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
'filename_pattern': 'shipment_{task_no}_{date}.xlsx',
|
||||
'mappings': [
|
||||
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'order_field', 'source_key': customer.id, 'formatter': 'upper'},
|
||||
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 2, 'source_kind': 'system_fact', 'source_key': 'warehouse_id', 'formatter': 'text'},
|
||||
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 3, 'source_kind': 'system_fact', 'source_key': 'export_date', 'formatter': 'date_mmddyyyy'},
|
||||
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 2, 'source_kind': 'system_fact', 'source_key': 'export_date', 'formatter': 'date_mmddyyyy'},
|
||||
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 1, 'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text'},
|
||||
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 2, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
|
||||
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 3, 'source_kind': 'order_field', 'source_key': po_number.id, 'formatter': 'text'},
|
||||
@@ -307,7 +335,8 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
])
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB',
|
||||
inventory_warehouse_id='DUB', inventory_lines_json=[{
|
||||
# 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。
|
||||
inventory_warehouse_id=None, inventory_lines_json=[{
|
||||
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
|
||||
}], inventory_snapshot_id=None,
|
||||
)
|
||||
@@ -324,8 +353,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
|
||||
wb = load_workbook(path, read_only=True)
|
||||
assert wb['Header'].cell(2, 1).value == 'ACME' # Header 动态字段及 formatter 生效。
|
||||
assert wb['Header'].cell(2, 2).value == 'DUB' # 受控系统事实写入目标列。
|
||||
assert wb['Header'].cell(2, 3).value == _system_fact(task, 'export_date').strftime('%m/%d/%Y')
|
||||
assert wb['Header'].cell(2, 2).value == _system_fact(task, 'export_date').strftime('%m/%d/%Y')
|
||||
assert wb['Detail'].cell(3, 1).value == 'PN-1' # Line 字段按订单行写入。
|
||||
assert wb['Detail'].cell(3, 2).value == 'ODM-9' # 标准库存字段无需 LLM 判断。
|
||||
assert wb['Detail'].cell(3, 3).value == '16754796' # Header 字段按业务要求重复到每条明细。
|
||||
@@ -336,9 +364,8 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
assert artifact.inventory_parsing_profile_id == parsing.id
|
||||
assert artifact.file_checksum and artifact.input_checksum and artifact.file_size > 0
|
||||
|
||||
# Dynamic inventory sources must resolve Warehouse before any export can be created.
|
||||
task.inventory_warehouse_id = None
|
||||
with pytest.raises(ValueError, match='缺少已解析的 Warehouse ID'):
|
||||
# 已存在待上传 Artifact 时仍保持原有幂等保护,和 Warehouse ID 无关。
|
||||
with pytest.raises(ValueError, match='当前任务存在待上传的发货 Excel'):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
|
||||
@@ -89,18 +89,17 @@ def test_all_execution_statuses_have_user_mapping():
|
||||
|
||||
def test_blocking_reason_classification_coverage():
|
||||
"""
|
||||
除豁免 1 个(technical_retry_exhausted)外,108 个阻断原因码必须一一分类。
|
||||
每个阻断原因码必须一一分类。
|
||||
|
||||
断言意图:禁止新增 reason_code 而漏掉用户处置模式,否则前端无法决定按钮渲染。
|
||||
"""
|
||||
total = len(PROCESS_GATE_BLOCKING_REASON_CODES)
|
||||
classified = set(BLOCKING_REASON_TO_USER_MODE.keys())
|
||||
exempt = {'technical_retry_exhausted'}
|
||||
missing = PROCESS_GATE_BLOCKING_REASON_CODES - classified - exempt
|
||||
missing = PROCESS_GATE_BLOCKING_REASON_CODES - classified
|
||||
assert not missing, f'unclassified blocking reasons: {sorted(missing)}'
|
||||
# 规模冻结:当前全集(含豁免)共 108+1=109;此断言随新增原因码需显式更新
|
||||
# 规模冻结:新增原因码时需同步补充用户处置模式。
|
||||
assert total >= 100, f'expected >= 100 blocking codes, got {total}'
|
||||
assert len(classified) + len(exempt) >= total
|
||||
assert len(classified) >= total
|
||||
|
||||
|
||||
def test_user_mode_values_are_allowed():
|
||||
|
||||
@@ -43,3 +43,23 @@ def test_build_field_observation_prefers_bbox_text_quote():
|
||||
assert observation['quote'] == 'EA'
|
||||
assert observation['layout_evidence']['bbox_text'] == 'EA'
|
||||
assert observation['layout_evidence']['quote_source'] == 'bbox_tokens'
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('source', 'expected'), [
|
||||
('native_glyph', 'native_pdf'),
|
||||
('ocr', 'ocr'),
|
||||
('acroform_widget', 'acroform_widget'),
|
||||
])
|
||||
def test_build_field_observation_exposes_runtime_value_source(source: str, expected: str):
|
||||
"""关键断言:通用 PDF 证据必须把原生/OCR/Widget 的来源带到 observation 顶层。"""
|
||||
observation = build_field_observation(
|
||||
field={
|
||||
'value': '4500001234',
|
||||
'source': source,
|
||||
'page_no': 1,
|
||||
'table_id': 'header',
|
||||
'cell_id': 'po',
|
||||
},
|
||||
document_id=9,
|
||||
)
|
||||
assert observation['value_source'] == expected
|
||||
@@ -243,8 +243,8 @@ def test_should_attempt_generic_extraction_allows_no_match_for_coordinate_path()
|
||||
) is False
|
||||
|
||||
|
||||
def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monkeypatch):
|
||||
"""关键断言:XFA capability 文档正式提取失败后不回退 generic/coordinate。"""
|
||||
def test_route_deterministic_unit_unmatched_xfa_uses_generic_evidence_only_for_review(monkeypatch):
|
||||
"""关键断言:未命中 XFA Profile 只走共同视觉 Review,不能伪装成 datasets 正式值。"""
|
||||
document = {
|
||||
'document_id': 90,
|
||||
'layout_snapshot': {
|
||||
@@ -276,10 +276,6 @@ def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monke
|
||||
'app.services.shipping_notice.order_extraction_workflow.resolve_unit_runtime_snapshot',
|
||||
lambda *_args, **_kwargs: ({'intake_no': 'SNI-XFA'}, document),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow.xfa_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._load_unit_pdf_bytes',
|
||||
lambda *_args, **_kwargs: None,
|
||||
@@ -301,7 +297,7 @@ def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monke
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
|
||||
'app.services.shipping_notice.order_extraction_workflow._extract_generic_evidence_result',
|
||||
_fake_generic,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -315,15 +311,11 @@ def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monke
|
||||
lambda: True,
|
||||
)
|
||||
route = route_deterministic_unit(run, unit=unit)
|
||||
assert generic_called['value'] is False
|
||||
assert generic_called['value'] is True
|
||||
assert route.execution_mode == 'review_required'
|
||||
assert route.decision.get('capability_kind') == 'xfa_dataset'
|
||||
assert route.decision.get('capability_kind') != 'xfa_fallback_coordinate'
|
||||
assert 'xfa_dataset_missing' in (
|
||||
route.decision.get('fallback_reason_codes')
|
||||
or route.decision.get('reason_codes')
|
||||
or []
|
||||
)
|
||||
assert route.decision.get('route_decision') == 'needs_review'
|
||||
assert route.decision.get('capability_kind') == 'coordinate'
|
||||
assert route.decision.get('capability_kind') != 'xfa_dataset'
|
||||
|
||||
|
||||
def test_should_attempt_generic_extraction_allows_no_special_profile_feature():
|
||||
@@ -682,7 +674,7 @@ def test_route_deterministic_unit_layout_drift_does_not_fallback_to_generic(monk
|
||||
lambda *_args, **_kwargs: ({'intake_no': 'SNI-001'}, {'document_id': 1, 'layout_schema_candidates': []}),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
|
||||
'app.services.shipping_notice.order_extraction_workflow._extract_generic_evidence_result',
|
||||
lambda **_kwargs: (_ for _ in ()).throw(AssertionError('layout_drift must not enter generic')),
|
||||
)
|
||||
|
||||
|
||||
@@ -1493,6 +1493,102 @@ def test_normalize_notice_line_aliases():
|
||||
}
|
||||
|
||||
|
||||
def test_normalize_notice_line_uses_frozen_schema_aliases_for_inventory_source_hint():
|
||||
"""邮件列名只有在本次冻结 Schema 配置后才可映射库存源线索,禁止代码内置业务别名。"""
|
||||
schema_definition = {
|
||||
'fields': [
|
||||
{
|
||||
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '内部料号', 'aliases': ['Custom MPN'],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '数量', 'aliases': ['Custom Qty'],
|
||||
},
|
||||
{
|
||||
'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '库存源线索', 'aliases': ['VMI HUB'],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
line = normalize_notice_line(
|
||||
{'Custom MPN': 'A-001', 'Custom Qty': '3', 'VMI HUB': 'CMH01'},
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
|
||||
assert line == {
|
||||
'part_number': 'A-001',
|
||||
'qty': 3.0,
|
||||
'inventory_source_hint': 'CMH01',
|
||||
}
|
||||
|
||||
|
||||
def test_normalize_notice_line_uses_schema_alias_for_line_remark():
|
||||
"""行备注只能通过冻结 Schema 的正式字段和别名进入订单行。"""
|
||||
schema_definition = {
|
||||
'fields': [
|
||||
{
|
||||
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '内部料号', 'aliases': ['Custom MPN'],
|
||||
},
|
||||
{
|
||||
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '数量', 'aliases': ['Custom Qty'],
|
||||
},
|
||||
{
|
||||
'field_id': 'remark', 'field_code': 'line_remark', 'scope': 'line',
|
||||
'enabled': True, 'display_name': '行备注', 'aliases': ['Customer Note'],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
line = normalize_notice_line(
|
||||
{'Custom MPN': 'A-001', 'Custom Qty': '3', 'Customer Note': 'Ship together'},
|
||||
schema_definition=schema_definition,
|
||||
)
|
||||
|
||||
assert line == {
|
||||
'part_number': 'A-001',
|
||||
'qty': 3.0,
|
||||
'line_remark': 'Ship together',
|
||||
}
|
||||
|
||||
|
||||
def test_parse_notice_table_keeps_configured_line_remark():
|
||||
"""表格中的行备注仅在冻结 Schema 声明其别名后进入解析结果。"""
|
||||
schema_definition = _table_schema_definition()
|
||||
schema_definition['fields'].append({
|
||||
'field_id': 'line-remark', 'field_code': 'line_remark', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'display_name': '行备注',
|
||||
'aliases': ['Customer Note'], 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
})
|
||||
|
||||
lines = parse_notice_table_rows(
|
||||
['MPN', 'Allocated QTY', 'Customer Note'],
|
||||
[['D4-A08AR12000002', 10, 'Ship together']],
|
||||
contract=compile_table_header_contract(schema_definition),
|
||||
)
|
||||
|
||||
assert lines == [{
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'qty': 10.0,
|
||||
'line_remark': 'Ship together',
|
||||
}]
|
||||
|
||||
|
||||
def test_schema_disables_free_text_field_guessing_after_table_parse_miss():
|
||||
"""存在冻结 Schema 时,表格未命中不得用固定 SKU x Qty 正则生成订单行。"""
|
||||
parsed, confidence, warnings = extract_notice_fields(
|
||||
raw_text='D4-A08AR12000002 x 10',
|
||||
schema_definition=_table_schema_definition(),
|
||||
)
|
||||
|
||||
assert parsed['lines'] == []
|
||||
assert confidence == 0.0
|
||||
assert 'schema_table_no_lines' in warnings
|
||||
|
||||
|
||||
def test_normalize_notice_line_splits_frozen_temp_composite():
|
||||
"""TEMP 二段复合文本应拆为客户料号和内部料号,禁止把组合值持久化。"""
|
||||
line = normalize_notice_line({
|
||||
|
||||
@@ -211,8 +211,46 @@ def test_auto_inventory_missing_snapshot_triggers_rpa(monkeypatch):
|
||||
assert result == trigger
|
||||
|
||||
|
||||
def test_inventory_rpa_single_attempt_messages_hide_fraction():
|
||||
"""单次自动尝试模式不应再产出 1/1 计数,避免 Dify 误判仍会继续自动重试。"""
|
||||
def test_auto_inventory_uses_per_source_attempt_identity_contract(app, monkeypatch):
|
||||
"""自动首次库存准备也必须委托逐源 Attempt,禁止退回旧 task 级 trigger。"""
|
||||
from app.services.shipping_notice import inventory_rpa_workflow as workflow
|
||||
|
||||
task = SimpleNamespace(task_no='SN-AUTO-PER-SOURCE', id=1)
|
||||
prepared = SimpleNamespace(
|
||||
pending_source_codes=['DSV360_AWSDU'],
|
||||
prepared_source_codes=[],
|
||||
failed_source_codes=[],
|
||||
source_attempts={'DSV360_AWSDU': {'source_run_no': 'PSR-AUTO-1'}},
|
||||
all_prepared=False,
|
||||
)
|
||||
calls = []
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(workflow, 'task_execution_block_reason', lambda _task: None)
|
||||
monkeypatch.setattr(workflow, 'customer_gate_tool_response', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, 'field_conflict_gate_response', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, 'task_reservation_gate_issues', lambda _task: [])
|
||||
monkeypatch.setattr(workflow, 'assert_inventory_source_gate', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, 'task_rpa_inventory_source', lambda _task: {'source_code': 'DSV360_AWSDU'})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
|
||||
lambda actual_task, *, mode: calls.append((actual_task, mode)) or prepared,
|
||||
)
|
||||
monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, 'serialize_task_for_tool', lambda _task: {})
|
||||
monkeypatch.setattr(workflow, 'tool_response', lambda **kwargs: kwargs)
|
||||
monkeypatch.setattr(workflow.db.session, 'flush', lambda: None)
|
||||
monkeypatch.setattr(workflow.db.session, 'commit', lambda: None)
|
||||
|
||||
result = workflow.ensure_inventory_via_rpa(task, mode='auto')
|
||||
|
||||
assert calls == [(task, 'auto')]
|
||||
assert result['status'] == 'running'
|
||||
assert result['data']['rpa']['source_attempts']['DSV360_AWSDU']['source_run_no'] == 'PSR-AUTO-1'
|
||||
|
||||
|
||||
def test_inventory_rpa_messages_do_not_promise_automatic_or_generic_retry():
|
||||
"""库存 RPA 只等待当前一次执行;失败后的下一步必须由用户选择明确动作。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import (
|
||||
_inventory_rpa_attempt_label,
|
||||
_inventory_rpa_running_prefix,
|
||||
@@ -221,16 +259,59 @@ def test_inventory_rpa_single_attempt_messages_hide_fraction():
|
||||
_inventory_rpa_triggered_prefix,
|
||||
)
|
||||
|
||||
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=False) == "当前配置为单次自动尝试"
|
||||
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=False) == "已触发库存获取"
|
||||
assert _inventory_rpa_running_prefix(attempt_no=1, max_attempts=1) == "库存获取进行中。"
|
||||
assert _inventory_rpa_triggered_prefix(attempt_no=1, max_attempts=1, manual_retry_round=False) == "已触发库存获取。"
|
||||
assert _inventory_rpa_attempt_label(attempt_no=1, max_attempts=1, manual_retry_round=True) == "已手动重新触发库存获取"
|
||||
assert _inventory_rpa_running_message(attempt_no=1, max_attempts=1) == "库存获取进行中。请稍后刷新状态;若长时间无结果,可改为上传库存 Excel。"
|
||||
assert _inventory_rpa_triggered_message(
|
||||
triggered = _inventory_rpa_triggered_message(
|
||||
attempt_no=1,
|
||||
max_attempts=1,
|
||||
manual_retry_round=False,
|
||||
) == "已触发库存获取。若长时间无结果,可手动重试,或上传库存 Excel。"
|
||||
)
|
||||
assert triggered == "已触发库存获取。若本次失败,请选择重新获取库存或上传库存 Excel。"
|
||||
assert '自动尝试' not in triggered
|
||||
assert '手动重试' not in triggered
|
||||
|
||||
|
||||
def test_inventory_loaded_response_syncs_affected_order_task_progress(monkeypatch):
|
||||
"""库存回调推进 Notice 后必须同步 OT,令 Projection 取得新的 progress_version。"""
|
||||
from app.services.shipping_notice import inventory_mapping_workflow as workflow
|
||||
|
||||
task = SimpleNamespace(id=1, task_no="SN-OT-SYNC", inventory_lines_json=None)
|
||||
linked_task = SimpleNamespace(id=2, task_no="SN-OT-SYNC-LINKED", inventory_lines_json=None)
|
||||
inventory_file = SimpleNamespace(inventory_file_no="INV-OT-SYNC")
|
||||
synced: list[object] = []
|
||||
|
||||
monkeypatch.setattr(workflow, "active_inventory_file_for_task", lambda _task: inventory_file)
|
||||
monkeypatch.setattr(
|
||||
workflow,
|
||||
"apply_inventory_parse_result_to_linked_tasks",
|
||||
lambda *_args, **_kwargs: [task, linked_task],
|
||||
)
|
||||
monkeypatch.setattr(workflow, "task_line_purpose_values", lambda _task: [])
|
||||
monkeypatch.setattr(workflow, "build_field_alignment_preview", lambda *_args, **_kwargs: {})
|
||||
monkeypatch.setattr(workflow, "set_task_step_progress", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, "apply_task_transition", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, "log_task_event", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, "serialize_task_for_tool", lambda _task: {})
|
||||
monkeypatch.setattr(workflow, "tool_response", lambda **kwargs: kwargs)
|
||||
monkeypatch.setattr(workflow.db.session, "flush", lambda: None)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.order_task_stage_machine.sync_order_task_stage_for_notice",
|
||||
lambda notice: synced.append(notice),
|
||||
)
|
||||
|
||||
workflow.inventory_loaded_response(
|
||||
task,
|
||||
[{"part_number": "A001", "qty": 1}],
|
||||
source="rpa",
|
||||
event_type="inventory_rpa_loaded",
|
||||
commit=False,
|
||||
)
|
||||
|
||||
# 当前任务与同一库存文件关联任务均要作为 OT progress 的写入源。
|
||||
assert synced == [task, linked_task]
|
||||
|
||||
|
||||
def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantity_selection(app, tmp_path):
|
||||
@@ -552,55 +633,15 @@ def test_resolve_rpa_inventory_batch_response_outcome_prefers_finalize_run_statu
|
||||
assert outcome["failed_count"] == 2
|
||||
|
||||
|
||||
def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, monkeypatch):
|
||||
"""确认库存源只完成路由,不得隐式进入 RPA pending 或写出 trigger。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
|
||||
lambda *args, **kwargs: None,
|
||||
)
|
||||
from app import db
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import confirm_inventory_source
|
||||
def test_inventory_source_manual_confirmation_is_not_exposed():
|
||||
"""库存源必须由规则自动裁决,服务层不得保留人工按 source_code 覆盖的入口。"""
|
||||
from app.services.shipping_notice import inventory_rpa_workflow, inventory_source_gate
|
||||
from app.services.shipping_notice import inventory_source_rules
|
||||
|
||||
trigger = tmp_path / "triggers"
|
||||
trigger.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CONFIRM-SOURCE-RPA",
|
||||
source_type="pdf",
|
||||
current_step="step2_parse_confirm",
|
||||
pending_human_reason="inventory_source_unresolved",
|
||||
ship_to="Dublin",
|
||||
step_payload_json={
|
||||
"inventory_source_resolution": {
|
||||
"status": "unresolved",
|
||||
"candidates": [
|
||||
{
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
result = confirm_inventory_source({"task_id": task.task_no, "source_code": "DSV360_AWSDU"})
|
||||
|
||||
db.session.refresh(task)
|
||||
assert result["status"] == "ok"
|
||||
assert "库存源已确认" in result["message"]
|
||||
assert task.pending_human_reason is None
|
||||
assert task.pending_human_reason is None
|
||||
assert task.error_message is None
|
||||
events = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").all()
|
||||
assert len(events) == 0
|
||||
assert not list(trigger.glob("inventory_export_*.json"))
|
||||
# 关键断言:三个历史入口均不存在,避免新 UI 或脚本绕过 Gate 自动裁决。
|
||||
assert not hasattr(inventory_rpa_workflow, "confirm_inventory_source")
|
||||
assert not hasattr(inventory_source_gate, "confirm_task_inventory_source")
|
||||
assert not hasattr(inventory_source_rules, "confirm_inventory_source_by_code")
|
||||
|
||||
|
||||
def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
@@ -682,9 +723,16 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
|
||||
|
||||
def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
"""batch failed + task_no 应驱动任务失败重试/人工兜底,而非停留在 rpa_pending。"""
|
||||
"""RPA 超时必须收口准备轮次并投影为可重试超时,不能持续等待外部回执。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
@@ -702,15 +750,65 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
|
||||
from tests.conftest import seed_rpa_inventory_trigger
|
||||
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-FAIL")
|
||||
source_run_no = "PSR-SN-BATCH-FAIL-DSV-A1"
|
||||
seed_rpa_inventory_trigger(task, run_no=source_run_no)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=task.id,
|
||||
start_gate_code="inventory_preparation",
|
||||
)
|
||||
task.active_process_execution_id = execution.id
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id,
|
||||
gate_code="inventory_preparation",
|
||||
).one()
|
||||
preparation = ShippingInventoryPreparationAttempt(
|
||||
task_id=task.id,
|
||||
execution_id=execution.id,
|
||||
attempt_no=1,
|
||||
status="waiting_external",
|
||||
input_snapshot_json={},
|
||||
output_snapshot_json={},
|
||||
)
|
||||
db.session.add(preparation)
|
||||
db.session.flush()
|
||||
rpa_attempt = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no,
|
||||
source_code="DSV360_AWSDU",
|
||||
attempt_no=1,
|
||||
source_run_no=source_run_no,
|
||||
status="running",
|
||||
lease_token="batch-fail-lease",
|
||||
extra_json={
|
||||
"candidate_set_id": 0,
|
||||
"execution_id": execution.id,
|
||||
"gate_id": gate.id,
|
||||
},
|
||||
)
|
||||
db.session.add(rpa_attempt)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryPreparationSourceAttempt(
|
||||
preparation_attempt_id=preparation.id,
|
||||
source_code="DSV360_AWSDU",
|
||||
status="waiting",
|
||||
rpa_attempt_id=rpa_attempt.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-BATCH-FAIL",
|
||||
"run_no": source_run_no,
|
||||
"trigger_type": "on_demand",
|
||||
"results": [{
|
||||
"task_no": task.task_no,
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_run_no": rpa_attempt.source_run_no,
|
||||
"callback_id": "callback-batch-fail-dsv-a1",
|
||||
"attempt_no": 1,
|
||||
"lease_token": "batch-fail-lease",
|
||||
"candidate_set_id": 0,
|
||||
"execution_id": execution.id,
|
||||
"gate_id": gate.id,
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"error_message": "login timeout",
|
||||
@@ -720,8 +818,17 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
|
||||
assert result["status"] == "ok"
|
||||
assert result["failed_count"] == 1
|
||||
assert task.pending_human_reason == "rpa_exhausted"
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
assert task.error_message
|
||||
db.session.refresh(rpa_attempt)
|
||||
db.session.refresh(preparation)
|
||||
db.session.refresh(execution)
|
||||
db.session.refresh(gate)
|
||||
assert rpa_attempt.status == "failed"
|
||||
assert preparation.status == "failed"
|
||||
assert gate.status == "blocked_retryable"
|
||||
assert gate.blocking_reason_code == "inventory_rpa_timeout"
|
||||
assert execution.status == "blocked"
|
||||
failed_events = ShippingTaskEvent.query.filter_by(
|
||||
task_id=task.id,
|
||||
event_type="inventory_rpa_failed",
|
||||
@@ -729,67 +836,243 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
assert len(failed_events) == 1
|
||||
|
||||
|
||||
def test_batch_success_missing_warehouse_closes_structured_rpa_attempt(app, tmp_path):
|
||||
"""成功回调缺仓库时必须终态化本次 Attempt,不能遗留为运行中。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryPreparationAttempt, ShippingTaskInventoryRpaAttempt
|
||||
from app.services.shipping_notice.inventory_recovery_service import create_inventory_preparation_round
|
||||
def test_dynamic_warehouse_source_allows_empty_callback_warehouse_id():
|
||||
"""Crane 多仓允许空回调仓库,DBS 固定仓仍须携带配置仓库。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _validate_batch_callback_worker_identity
|
||||
|
||||
assert _validate_batch_callback_worker_identity(
|
||||
{"source_code": "CRANE", "warehouse_id": ""},
|
||||
{
|
||||
"source_code": "CRANE",
|
||||
"warehouse_resolution_mode": "inventory_match",
|
||||
"fixed_warehouse_id": None,
|
||||
},
|
||||
) is None
|
||||
assert _validate_batch_callback_worker_identity(
|
||||
{"source_code": "DBS", "warehouse_id": ""},
|
||||
{
|
||||
"source_code": "DBS",
|
||||
"warehouse_resolution_mode": "fixed",
|
||||
"fixed_warehouse_id": "DUB",
|
||||
},
|
||||
) == "warehouse_id_missing"
|
||||
|
||||
|
||||
def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot(app, tmp_path):
|
||||
"""Crane 成功回调空仓库须从库存行解析并关联任务,而非在回调层拒绝。"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "crane-multi-warehouse.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("CRANE-WH").getvalue())
|
||||
|
||||
with app.app_context():
|
||||
base_source = ShippingInventorySource.query.filter_by(source_code="DSV360_AWSDU").one()
|
||||
crane_profile = ShippingRpaProfile(
|
||||
profile_code="CRANE_DYNAMIC_CALLBACK", display_name="Crane Dynamic Callback",
|
||||
connector_type="crane", login_url="https://test.invalid/crane",
|
||||
login_config_json={"auth_mode": "password"},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
source_code="CRANE", display_name="Crane", connector_type="crane",
|
||||
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
|
||||
excel_template=base_source.excel_template,
|
||||
warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None,
|
||||
report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
task = ShippingNotice(
|
||||
task_no="SN-BATCH-MISSING-WAREHOUSE",
|
||||
task_no="SN-CRANE-EMPTY-WAREHOUSE",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
task._test_order_rows = [{"part_number": "A001", "reservation_id": "00001", "qty": 1}]
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
db.session.add_all([crane_profile, crane_source, task])
|
||||
db.session.flush()
|
||||
seed_task_inventory_source(task, source_code="CRANE")
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
preparation = create_inventory_preparation_round(
|
||||
task=task,
|
||||
execution_id=None,
|
||||
recovery_plan_id=None,
|
||||
action_code="retry_inventory_preparation",
|
||||
source_codes=["CRANE"],
|
||||
gate_attempt_id=None,
|
||||
)
|
||||
attempt = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no,
|
||||
source_code="CRANE",
|
||||
attempt_no=1,
|
||||
source_run_no="PSR-SN-BATCH-MISSING-WAREHOUSE-CRANE-A1-TEST",
|
||||
status="running",
|
||||
lease_token="lease-missing-warehouse",
|
||||
callback_payload_json={},
|
||||
extra_json={},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
preparation.source_attempts[0].rpa_attempt_id = attempt.id
|
||||
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
|
||||
schema_fields = (order_snapshot.schema_version.definition_json or {}).get("fields") or []
|
||||
order_field_ids = {
|
||||
str(item.get("field_code") or ""): str(item.get("field_id") or "")
|
||||
for item in schema_fields
|
||||
}
|
||||
definition = dict(base_source.parsing_profile.definition_json or {})
|
||||
definition["match_keys"] = [
|
||||
{"order_field_id": order_field_ids["part_number"], "inventory_field_id": definition["match_keys"][0]["inventory_field_id"]},
|
||||
{"order_field_id": order_field_ids["reservation_id"], "inventory_field_id": definition["match_keys"][1]["inventory_field_id"]},
|
||||
]
|
||||
base_source.parsing_profile.definition_json = definition
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-CRANE-EMPTY-WAREHOUSE")
|
||||
db.session.commit()
|
||||
|
||||
result = _process_batch_callback({
|
||||
"run_no": "BATCH-MISSING-WAREHOUSE",
|
||||
"run_no": "RUN-CRANE-EMPTY-WAREHOUSE",
|
||||
"trigger_type": "on_demand",
|
||||
"results": [{
|
||||
"task_no": task.task_no,
|
||||
"source_code": "CRANE",
|
||||
"source_run_no": attempt.source_run_no,
|
||||
"warehouse_id": "",
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"warehouse_id": "",
|
||||
"file_path": str(sample),
|
||||
}],
|
||||
})
|
||||
db.session.refresh(task)
|
||||
|
||||
db.session.refresh(attempt)
|
||||
db.session.refresh(preparation)
|
||||
assert result["data"]["failed"][0]["error"] == "warehouse_id_missing"
|
||||
assert attempt.status == "failed"
|
||||
assert attempt.error_code == "warehouse_id_missing"
|
||||
assert preparation.status == "failed"
|
||||
assert preparation.source_attempts[0].status == "failed"
|
||||
assert result["success_count"] == 1, result
|
||||
assert result["failed_count"] == 0
|
||||
assert task.inventory_snapshot_id is not None
|
||||
assert task.inventory_warehouse_id == "CRANE-WH"
|
||||
|
||||
|
||||
def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolvable(app, tmp_path):
|
||||
"""动态仓库存文件已通过结构校验时,订单仓库未决不得回滚库存快照。"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot, ShippingProcessGate
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "crane-unresolved-link.xlsx"
|
||||
sample.write_bytes(
|
||||
inventory_xlsx_with_warehouse(
|
||||
"CRANE-WH", sku="A001", reservation_id="OTHER-RESERVATION",
|
||||
).getvalue()
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
base_source = ShippingInventorySource.query.filter_by(source_code="DSV360_AWSDU").one()
|
||||
crane_profile = ShippingRpaProfile(
|
||||
profile_code="CRANE_UNRESOLVED_LINK", display_name="Crane Unresolved Link",
|
||||
connector_type="crane", login_url="https://test.invalid/crane",
|
||||
login_config_json={"auth_mode": "password"},
|
||||
)
|
||||
crane_source = ShippingInventorySource(
|
||||
source_code="CRANE", display_name="Crane", connector_type="crane",
|
||||
rpa_profile=crane_profile, parsing_profile=base_source.parsing_profile,
|
||||
excel_template=base_source.excel_template,
|
||||
warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None,
|
||||
report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CRANE-UNRESOLVED-LINK",
|
||||
source_type="manual",
|
||||
pending_human_reason="rpa_pending",
|
||||
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
|
||||
)
|
||||
task._test_order_rows = [{"part_number": "A001", "reservation_id": "00001", "qty": 1}]
|
||||
_confirm_direct_rpa_task_customer(task)
|
||||
db.session.add_all([crane_profile, crane_source, task])
|
||||
db.session.flush()
|
||||
seed_task_inventory_source(task, source_code="CRANE")
|
||||
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
|
||||
schema_fields = (order_snapshot.schema_version.definition_json or {}).get("fields") or []
|
||||
order_field_ids = {
|
||||
str(item.get("field_code") or ""): str(item.get("field_id") or "")
|
||||
for item in schema_fields
|
||||
}
|
||||
definition = dict(base_source.parsing_profile.definition_json or {})
|
||||
definition["match_keys"] = [
|
||||
{"order_field_id": order_field_ids["part_number"], "inventory_field_id": definition["match_keys"][0]["inventory_field_id"]},
|
||||
{"order_field_id": order_field_ids["reservation_id"], "inventory_field_id": definition["match_keys"][1]["inventory_field_id"]},
|
||||
]
|
||||
base_source.parsing_profile.definition_json = definition
|
||||
seed_rpa_inventory_trigger(task, run_no="RUN-CRANE-UNRESOLVED-LINK")
|
||||
# 正式流程已经进入库存准备;回调成功后必须越过该 Gate,转到库存匹配,
|
||||
# 而非因动态仓尚未匹配订单键而退回“库存文件缺失”。
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=task.id,
|
||||
start_gate_code="inventory_preparation",
|
||||
)
|
||||
task.active_process_execution_id = execution.id
|
||||
db.session.commit()
|
||||
|
||||
result = _process_batch_callback({
|
||||
"run_no": "RUN-CRANE-UNRESOLVED-LINK",
|
||||
"trigger_type": "on_demand",
|
||||
"results": [{
|
||||
"task_no": task.task_no,
|
||||
"source_code": "CRANE",
|
||||
"warehouse_id": "",
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(sample),
|
||||
}],
|
||||
})
|
||||
db.session.refresh(task)
|
||||
|
||||
assert result["success_count"] == 1, result
|
||||
assert result["failed_count"] == 0
|
||||
assert task.inventory_snapshot_id is not None
|
||||
snapshot = ShippingInventoryFile.query.filter_by(
|
||||
rpa_run_no="RUN-CRANE-UNRESOLVED-LINK", source_code="CRANE",
|
||||
).one()
|
||||
assert snapshot.snapshot_status == "ready"
|
||||
assert snapshot.identity_status == "pending"
|
||||
assert (snapshot.schema_preview_json or {}).get("identity_resolution_reason") == "warehouse_not_found_for_order_line"
|
||||
assert Path(snapshot.storage_path).is_file()
|
||||
link = ShippingTaskInventoryLink.query.filter_by(
|
||||
task_id=task.id, inventory_file_id=snapshot.id, is_active=True,
|
||||
).one()
|
||||
assert link.identity_check_status == "pending_matching"
|
||||
assert task.pending_human_reason is None
|
||||
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
db.session.refresh(execution)
|
||||
preparation = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code="inventory_preparation",
|
||||
).one()
|
||||
matching = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id, gate_code="inventory_matching",
|
||||
).one()
|
||||
assert preparation.status == "passed"
|
||||
assert preparation.blocking_reason_code is None
|
||||
assert execution.current_gate_code == "inventory_matching"
|
||||
assert matching.status == "blocked_retryable"
|
||||
assert matching.blocking_reason_code == "inventory_match_failed"
|
||||
|
||||
|
||||
def test_inventory_callback_job_marks_business_failure_as_failed(app, monkeypatch):
|
||||
"""异步回调业务失败时 Job 不得伪装为 success。"""
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.handlers import shipping_inventory_callback_process as handler
|
||||
from app.models import Job
|
||||
|
||||
with app.app_context():
|
||||
job = Job(
|
||||
domain="shipping_notice",
|
||||
job_type="shipping_inventory_callback_process",
|
||||
status="running",
|
||||
attempts=1,
|
||||
max_attempts=3,
|
||||
payload_json={"callback_id": "callback-business-failed"},
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.inventory_rpa_workflow.process_rpa_report_inventory_batch",
|
||||
lambda _payload: {
|
||||
"status": "ok",
|
||||
"data": {"result_status": "failed", "failed": [{"error": "snapshot_write_failed"}]},
|
||||
},
|
||||
)
|
||||
|
||||
handler.run_shipping_inventory_callback_process(
|
||||
JobContext(config={}, logger=None, extras={}), {"job_id": job.id},
|
||||
)
|
||||
db.session.refresh(job)
|
||||
|
||||
assert job.status == "failed"
|
||||
assert job.result_json["callback_result"]["data"]["result_status"] == "failed"
|
||||
|
||||
|
||||
def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
|
||||
@@ -821,7 +1104,7 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
|
||||
|
||||
assert result["status"] == "needs_human"
|
||||
assert result["checkpoint"] == "upload_req"
|
||||
assert task.pending_human_reason == "rpa_exhausted"
|
||||
assert task.pending_human_reason == "inv_unavail"
|
||||
failed_events = ShippingTaskEvent.query.filter_by(
|
||||
task_id=task.id,
|
||||
event_type="inventory_rpa_failed",
|
||||
@@ -895,6 +1178,114 @@ def test_per_source_timeout_marks_missing_queued_trigger_as_failed(app, tmp_path
|
||||
assert attempt.error_code == 'trigger_not_claimed_missing'
|
||||
|
||||
|
||||
def test_per_source_timeout_archives_unclaimed_trigger_into_failed(app, tmp_path):
|
||||
"""超时未领取的 trigger 必须移入 failed,避免 Worker 日后误消费旧请求。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_timeout_scan
|
||||
|
||||
with app.app_context():
|
||||
task = SimpleNamespace(task_no='SN-STALE-ARCHIVE')
|
||||
trigger_dir = tmp_path / 'inventory_triggers'
|
||||
trigger_dir.mkdir()
|
||||
trigger_path = trigger_dir / 'inventory_export_batch_stale.json'
|
||||
trigger_path.write_text('{"task_no": "SN-STALE-ARCHIVE"}', encoding='utf-8')
|
||||
attempt = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no,
|
||||
source_code='CRANE',
|
||||
attempt_no=1,
|
||||
run_no='PSR-STALE-ARCHIVE-CRANE-A1',
|
||||
status='queued',
|
||||
trigger_file_path=str(trigger_path),
|
||||
triggered_at=datetime.utcnow() - timedelta(seconds=120),
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.commit()
|
||||
|
||||
result = per_source_timeout_scan(task, timeout_seconds=60)
|
||||
|
||||
assert result['timed_out_count'] == 1
|
||||
assert not trigger_path.exists()
|
||||
assert (trigger_dir / 'failed' / trigger_path.name).is_file()
|
||||
|
||||
|
||||
def test_inventory_trigger_writes_without_online_worker(app, tmp_path, monkeypatch):
|
||||
"""投递库存 trigger 只依赖共享目录可写,Worker 可在稍后启动并领取。"""
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
|
||||
with app.app_context():
|
||||
trigger_dir = tmp_path / 'inventory_triggers'
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR'] = str(trigger_dir)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready',
|
||||
lambda: (_ for _ in ()).throw(AssertionError('trigger write must not require worker heartbeat')),
|
||||
)
|
||||
|
||||
path = write_inventory_export_batch_trigger(
|
||||
'BATCH-OFFLINE-WORKER',
|
||||
[{'source_code': 'CRANE'}],
|
||||
)
|
||||
|
||||
assert path is not None
|
||||
assert Path(path).is_file()
|
||||
|
||||
|
||||
def test_per_source_timeout_closes_linked_inventory_preparation_round(app, tmp_path):
|
||||
"""RPA 超时失败必须同步准备轮次,避免工作台持续判定为处理中。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_timeout_scan
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no='SN-STALE-PREPARATION')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
attempt = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no,
|
||||
source_code='CRANE',
|
||||
attempt_no=1,
|
||||
run_no='PSR-STALE-PREPARATION-CRANE-A1',
|
||||
status='queued',
|
||||
trigger_file_path=str(tmp_path / 'missing.trigger.json'),
|
||||
triggered_at=datetime.utcnow() - timedelta(seconds=120),
|
||||
)
|
||||
preparation = ShippingInventoryPreparationAttempt(
|
||||
task_id=task.id,
|
||||
attempt_no=1,
|
||||
status='waiting_external',
|
||||
input_snapshot_json={},
|
||||
output_snapshot_json={},
|
||||
)
|
||||
db.session.add_all([attempt, preparation])
|
||||
db.session.flush()
|
||||
source = ShippingInventoryPreparationSourceAttempt(
|
||||
preparation_attempt_id=preparation.id,
|
||||
source_code='CRANE',
|
||||
status='waiting',
|
||||
rpa_attempt_id=attempt.id,
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
|
||||
result = per_source_timeout_scan(task, timeout_seconds=60)
|
||||
db.session.refresh(attempt)
|
||||
db.session.refresh(preparation)
|
||||
db.session.refresh(source)
|
||||
|
||||
assert result['timed_out_count'] == 1
|
||||
assert attempt.status == 'failed'
|
||||
assert source.status == 'failed'
|
||||
assert preparation.status == 'failed'
|
||||
|
||||
|
||||
def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
|
||||
"""batch 成功项缺少 Worker 身份字段时不得由任务字段自证通过。"""
|
||||
from app import db
|
||||
|
||||
@@ -452,6 +452,103 @@ def test_recompute_supersedes_referenced_stale_candidate_without_deleting_histor
|
||||
assert order_task.candidate_id == stale_candidate.id
|
||||
|
||||
|
||||
def test_document_reparse_does_not_expire_sibling_document_candidate(app):
|
||||
"""单附件增量重解析只收口目标 Document,不能撤销同一 Intake 的兄弟候选。"""
|
||||
with app.app_context():
|
||||
_user, session, intake, document, _runtime = _seed_extraction_input()
|
||||
sibling = ShippingOrderDocument(
|
||||
intake_id=int(intake.id),
|
||||
asset_id=int(document.asset_id),
|
||||
document_type='attachment',
|
||||
attachment_key='sibling.pdf',
|
||||
filename='sibling.pdf',
|
||||
content_hash='order-extraction-sibling-document-hash',
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 4510000002 SKU SKU-B QTY 20',
|
||||
)
|
||||
db.session.add(sibling)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
agent = Agent.query.filter_by(agent_code='shipping_notice').one()
|
||||
first_run = ShippingOrderProcessingRun(
|
||||
run_no='SNER-SIBLING-REPARSE-1',
|
||||
user_id=int(session.user_id),
|
||||
owner_agent_id=int(agent.id),
|
||||
conversation_id=session.session_id,
|
||||
schema_version_id=int(schema.id),
|
||||
input_snapshot_hash='sibling-reparse-1',
|
||||
input_snapshot_json={},
|
||||
idempotency_key='sibling-reparse-1',
|
||||
)
|
||||
db.session.add(first_run)
|
||||
db.session.flush()
|
||||
|
||||
first = _order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(document.id),
|
||||
po_number='4510000001',
|
||||
part_number='SKU-A',
|
||||
qty=10,
|
||||
include_process_fields=False,
|
||||
)
|
||||
persist_order_extraction_result(
|
||||
session=session,
|
||||
intakes=[intake],
|
||||
documents=[document],
|
||||
current_snapshot='sibling-reparse-1',
|
||||
request_id='sibling-reparse-1',
|
||||
orders=[first],
|
||||
run_id=int(first_run.id),
|
||||
schema_version_id=int(schema.id),
|
||||
extraction_source='test_workflow',
|
||||
auto_create_enabled=True,
|
||||
)
|
||||
sibling_order = _order(
|
||||
intake_no=intake.intake_no,
|
||||
document_id=int(sibling.id),
|
||||
po_number='4510000002',
|
||||
part_number='SKU-B',
|
||||
qty=20,
|
||||
include_process_fields=False,
|
||||
)
|
||||
sibling_reparse_run = ShippingOrderProcessingRun(
|
||||
run_no='SNER-SIBLING-REPARSE-2',
|
||||
user_id=int(session.user_id),
|
||||
owner_agent_id=int(agent.id),
|
||||
conversation_id=session.session_id,
|
||||
schema_version_id=int(schema.id),
|
||||
input_snapshot_hash='sibling-reparse-2',
|
||||
input_snapshot_json={'review_reparse': {'document_id': int(sibling.id)}},
|
||||
idempotency_key='sibling-reparse-2',
|
||||
reparse_of_run_id=int(first_run.id),
|
||||
)
|
||||
db.session.add(sibling_reparse_run)
|
||||
db.session.flush()
|
||||
persist_order_extraction_result(
|
||||
session=session,
|
||||
intakes=[intake],
|
||||
documents=[sibling],
|
||||
current_snapshot='sibling-reparse-2',
|
||||
request_id='sibling-reparse-2',
|
||||
orders=[sibling_order],
|
||||
run_id=int(sibling_reparse_run.id),
|
||||
schema_version_id=int(schema.id),
|
||||
extraction_source='test_workflow',
|
||||
auto_create_enabled=True,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
first_candidate = ShippingOrderCandidate.query.filter_by(
|
||||
intake_id=int(intake.id), primary_document_id=int(document.id),
|
||||
).one()
|
||||
sibling_candidate = ShippingOrderCandidate.query.filter_by(
|
||||
intake_id=int(intake.id), primary_document_id=int(sibling.id),
|
||||
).one()
|
||||
assert first_candidate.is_current_version is True
|
||||
assert sibling_candidate.is_current_version is True
|
||||
|
||||
|
||||
def test_plain_text_table_issue_reaches_candidate_as_machine_readable_conflict(app):
|
||||
"""无 cell 证据的纯文本表格必须在 Candidate 保留原因码,供现有任务 UI 解释。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -442,6 +442,49 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
|
||||
assert counts['total_pending_badge'] == counts['pending']
|
||||
|
||||
|
||||
def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_still_open(app):
|
||||
"""待办只能指向文件 Stream 当前 Case,不能因旧 Case 状态残留而重复展示。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_review_disposition_service import reparse_case_document
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.query_service import list_my_todos
|
||||
from app.services.shipping_notice.review_stream_service import activate_review_case
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-STREAM-CURRENT')
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
original = ensure_run_review_cases(run=source)[0]
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
|
||||
replacement_run, _ = reparse_case_document(
|
||||
user_id=user.id, case_no=original.case_no, reason='rule_updated',
|
||||
)
|
||||
ensure_order_extraction_plan(replacement_run)
|
||||
for unit in replacement_run.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
replacement = ensure_run_review_cases(run=replacement_run)[0]
|
||||
activate_review_case(case=replacement, trigger='document_reparse_succeeded')
|
||||
|
||||
# 模拟旧数据未正确标成 superseded:当前态仍必须由 Stream 指针裁决。
|
||||
original.status = 'draft'
|
||||
original.confirmed_task_id = None
|
||||
db.session.commit()
|
||||
|
||||
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
|
||||
review_case_nos = {
|
||||
item['review_case_no']
|
||||
for item in pending['items']
|
||||
if item.get('item_kind') == 'review_case'
|
||||
}
|
||||
assert replacement.case_no in review_case_nos
|
||||
assert original.case_no not in review_case_nos
|
||||
|
||||
|
||||
def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app):
|
||||
"""历史空 Review Case 可以处置,但不能被待办页默认授权进入订单生命周期。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
tests/test_shipping_notice_state_machine.py
|
||||
|
||||
用途:校验发货通知状态机注册表完整性与 STP checkpoint_kind 映射。
|
||||
用途:校验发货通知 checkpoint 内部流程映射与 STP checkpoint_kind。
|
||||
依赖:pytest、state_machine、constants、ShippingNotice。
|
||||
逻辑:validate_registry 无错误;关键检查点 kind 正确;resolve_task_ui_state 对简单任务属性可解析。
|
||||
"""
|
||||
@@ -16,27 +16,14 @@ from app.services.shipping_notice.constants import (
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
CheckpointKind,
|
||||
build_checkpoint_catalog,
|
||||
checkpoint_kind_for,
|
||||
resolve_task_ui_state,
|
||||
validate_registry,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for, resolve_task_ui_state, validate_registry
|
||||
|
||||
|
||||
def test_validate_registry_has_no_errors() -> None:
|
||||
"""CHECKPOINT_REGISTRY 与 KIND / ACTION_SPECS 应完全对齐。"""
|
||||
"""checkpoint 仅维护内部流程分类。"""
|
||||
assert validate_registry() == []
|
||||
|
||||
|
||||
def test_checkpoint_catalog_uses_unified_actions_shape() -> None:
|
||||
"""检查点目录也不得继续暴露旧 action_buttons 字段。"""
|
||||
catalog = build_checkpoint_catalog()
|
||||
assert all("action_buttons" not in item for item in catalog["checkpoints"])
|
||||
assert all(set(item["actions"]) == {"primary", "secondary"} for item in catalog["checkpoints"])
|
||||
|
||||
|
||||
def test_checkpoint_kinds_for_stp_stop_points() -> None:
|
||||
"""STP 关键检查点 kind:导出 Excel 后待人工上传登记 / 解析复核 / 已上传终态。"""
|
||||
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
@@ -70,7 +57,7 @@ def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.checkpoint == CP_EXPORT_READY
|
||||
assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
assert "mark_manual_uploaded" in (ui.human_options or [])
|
||||
assert not hasattr(ui, 'human_options')
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_uploaded_complete(app) -> None:
|
||||
|
||||
@@ -297,8 +297,8 @@ def test_openapi_spec_public(app, client):
|
||||
assert "submit_decision" not in spec_text
|
||||
|
||||
|
||||
def test_confirm_inventory_source_route_returns_json(app, client):
|
||||
"""confirm_inventory_source HTTP 路由必须存在且可调用。"""
|
||||
def test_confirm_inventory_source_route_is_removed(app, client):
|
||||
"""库存源人工确认已下线,任何旧 Tool 写入口均不得可达。"""
|
||||
headers = _tool_headers(app)
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
@@ -316,8 +316,7 @@ def test_confirm_inventory_source_route_returns_json(app, client):
|
||||
headers=headers,
|
||||
json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert res.get_json()["status"] in {"ok", "needs_human", "running"}
|
||||
assert res.status_code == 404
|
||||
|
||||
|
||||
def test_static_openapi_snapshot_contains_shipping_contract_keywords():
|
||||
@@ -396,7 +395,7 @@ def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app
|
||||
body = response.get_json()
|
||||
assert body["status"] == "needs_human"
|
||||
assert body["checkpoint"] == "upload_req"
|
||||
assert body["human_options"] == ["upload_inventory_file", "retry_rpa"]
|
||||
assert "human_options" not in body
|
||||
with app.app_context():
|
||||
task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
|
||||
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one()
|
||||
@@ -875,7 +874,6 @@ def test_parse_inventory_oversized_text_route_is_removed(app, client):
|
||||
|
||||
|
||||
def test_chat_actions_empty_when_task_rejected(app):
|
||||
from app.services.shipping_notice.chat_actions import human_options_for_task
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
with app.app_context():
|
||||
@@ -884,7 +882,6 @@ def test_chat_actions_empty_when_task_rejected(app):
|
||||
source_type="manual",
|
||||
review_status="rejected",
|
||||
)
|
||||
assert human_options_for_task(task) == []
|
||||
ui_state = build_task_ui_state(task)
|
||||
assert ui_state["checkpoint"]["code"] == "rejected"
|
||||
assert ui_state["actions"] == {"primary": None, "secondary": []}
|
||||
|
||||
@@ -44,7 +44,6 @@ def test_unified_actions_deduplicates_gate_primary_action():
|
||||
{"code": "view_audit", "label": "查看审计", "kind": "view"},
|
||||
],
|
||||
},
|
||||
action_buttons=[],
|
||||
)
|
||||
|
||||
assert state["primary"]["code"] == "open_order_review"
|
||||
@@ -52,20 +51,47 @@ def test_unified_actions_deduplicates_gate_primary_action():
|
||||
|
||||
|
||||
def test_unified_action_shape_contains_gate_version_fields():
|
||||
"""统一动作 DTO 必须包含前端提交所需的版本与禁用字段。"""
|
||||
"""统一动作 DTO 必须包含前端提交所需的版本、分派与禁用字段。"""
|
||||
state = _unified_actions(
|
||||
process_gate={
|
||||
"lock_version": 7,
|
||||
"current_gate": {"evaluation_version": 3},
|
||||
"primary_action": {"code": "retry_inventory_matching", "label": "重新匹配"},
|
||||
"primary_action": {
|
||||
"code": "retry_inventory_matching",
|
||||
"label": "重新匹配",
|
||||
"dispatch": "mutation",
|
||||
},
|
||||
"action_presentation": [],
|
||||
},
|
||||
action_buttons=[],
|
||||
)
|
||||
assert state["primary"]["expected_gate_version"] == 3
|
||||
# 关键断言:前端必须按 Gate 声明的执行方式分派,不能按动作码硬编码。
|
||||
assert state["primary"]["dispatch"] == "mutation"
|
||||
assert "disabled_reason" in state["primary"]
|
||||
|
||||
|
||||
def test_unified_actions_preserve_backend_surface_without_action_code_fallback():
|
||||
"""UI State 只透传动作来源声明的位置,不再按下载动作码补默认工作面。"""
|
||||
state = _unified_actions(
|
||||
process_gate={
|
||||
"primary_action": {
|
||||
"code": "mark_manual_uploaded",
|
||||
"label": "登记人工上传",
|
||||
"target_surface": "upload_complete",
|
||||
},
|
||||
"action_presentation": [{
|
||||
"code": "download_excel",
|
||||
"label": "下载发货 Excel",
|
||||
"target_surface": "upload_complete",
|
||||
"target_anchor": "excel_artifact",
|
||||
}],
|
||||
},
|
||||
)
|
||||
assert state["primary"]["target_surface"] == "upload_complete"
|
||||
assert state["secondary"][0]["target_surface"] == "upload_complete"
|
||||
assert state["secondary"][0]["target_anchor"] == "excel_artifact"
|
||||
|
||||
|
||||
def test_build_task_ui_state_summary_has_required_keys(app) -> None:
|
||||
"""summary 必须包含 STP 可解释字段全集。"""
|
||||
with app.app_context():
|
||||
@@ -96,7 +122,7 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None:
|
||||
|
||||
|
||||
def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None:
|
||||
"""业务 UI 只消费四阶段与后端统一 actions,不再要求前端解释旧七步。"""
|
||||
"""没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no="SN-UI-STAGE-ACTIONS",
|
||||
@@ -108,9 +134,8 @@ def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(ap
|
||||
assert state["stage"]["code"] == "order_review"
|
||||
assert state["stage"]["index"] == 2
|
||||
assert state["stage"]["total"] == 4
|
||||
assert state["actions"]["primary"] is not None
|
||||
assert state["actions"]["primary"]["code"] == "confirm"
|
||||
assert all("code" in item and "kind" in item for item in state["actions"]["secondary"])
|
||||
assert state["actions"]["primary"] is None
|
||||
assert state["actions"]["secondary"] == []
|
||||
|
||||
|
||||
def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None:
|
||||
@@ -274,7 +299,7 @@ def test_entry_surface_export_ready_is_task_workbench(app) -> None:
|
||||
]
|
||||
# 关键断言:没有可验证 Artifact 时,遗留 export_file_name 不得生成下载按钮。
|
||||
assert "download_excel" not in button_ids
|
||||
assert "mark_manual_uploaded" in button_ids
|
||||
assert "mark_manual_uploaded" not in button_ids
|
||||
|
||||
|
||||
def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypatch) -> None:
|
||||
@@ -551,6 +576,52 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm
|
||||
assert forbidden.status_code == 404
|
||||
|
||||
|
||||
def test_workspace_line_inventory_download_requires_current_line_reference(app, client, tmp_path) -> None:
|
||||
"""行内下载只能读取当前匹配事实引用的库存文件,不能按文件号探测同任务其他来源。"""
|
||||
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
|
||||
|
||||
with app.app_context():
|
||||
owner = User(username='line-inventory-download-owner', email='line-inventory-download-owner@example.com')
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
allowed_path = tmp_path / 'crane.xlsx'
|
||||
denied_path = tmp_path / 'dbs.xlsx'
|
||||
allowed_path.write_bytes(b'crane-content')
|
||||
denied_path.write_bytes(b'dbs-content')
|
||||
task = ShippingNotice(task_no='SN-LINE-INVENTORY-DOWNLOAD', user_id=owner.id, source_type='manual')
|
||||
allowed_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path),
|
||||
source_file_name='crane.xlsx', source_code='CRANE', snapshot_status='ready',
|
||||
)
|
||||
denied_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-LINE-DBS', storage_path=str(denied_path),
|
||||
source_file_name='dbs.xlsx', source_code='DBS', snapshot_status='ready',
|
||||
)
|
||||
db.session.add_all([task, allowed_file, denied_file])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, line_key='line-crane', line_index=0,
|
||||
inventory_snapshot_id=allowed_file.id, matched_file_no=allowed_file.inventory_file_no,
|
||||
inventory_source_code='CRANE', match_result='not_found', inventory_status='ready', is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
|
||||
|
||||
allowed = client.get(
|
||||
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE',
|
||||
headers=headers,
|
||||
)
|
||||
assert allowed.status_code == 200
|
||||
assert allowed.data == b'crane-content'
|
||||
assert 'crane.xlsx' in str(allowed.headers.get('Content-Disposition') or '')
|
||||
|
||||
denied = client.get(
|
||||
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS',
|
||||
headers=headers,
|
||||
)
|
||||
assert denied.status_code == 404
|
||||
|
||||
|
||||
def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None:
|
||||
"""结构化事实字段为空时,历史/STP 证据仍应补齐通知准备行。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -122,6 +122,386 @@ def _coordinate_definition() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def test_visual_sample_preview_reads_common_ocr_value_before_xfa_path_is_selected(app, monkeypatch):
|
||||
"""XFA 草稿未选 datasets path 时,仍从共同 PDF 坐标证据显示 PO 样本值。"""
|
||||
glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'line-field', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]})
|
||||
document = SimpleNamespace(id=101)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'customer_po', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
# 正式 datasets binding 尚未完成:它必须不参与共同视觉样本值的输入校验。
|
||||
definition.update({
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {'template_packet_checksum': 'sha256:placeholder'},
|
||||
'bindings': [{
|
||||
'binding_id': 'value-source-customer_po', 'field_layout_id': 'customer_po',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': None},
|
||||
}],
|
||||
})
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 101, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:视觉/OCR 值正常显示;正式 datasets path 仍由独立 value-preview 决定。
|
||||
assert result['fields'][0]['field_code'] == 'customer_po_number'
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
assert result['fields'][0]['source'] == 'pdf_coordinate'
|
||||
|
||||
|
||||
def test_visual_sample_preview_retries_only_missing_hybrid_xfa_field_with_ocr(app, monkeypatch):
|
||||
"""Hybrid XFA 有标签 glyph 但值仅在外观层时,当前字段须以 OCR 样本值回退。"""
|
||||
native_label_glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('ORDER NO:')
|
||||
]
|
||||
ocr_value_glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 100 + index * 8, 'y0': 10, 'x1': 106 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
document = SimpleNamespace(id=102)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': native_label_glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 102 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(
|
||||
service, '_read_page_ocr_coordinate_evidence',
|
||||
lambda **_kwargs: {'width': 200, 'height': 100, 'glyphs': ocr_value_glyphs},
|
||||
raising=False,
|
||||
)
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []}, 'table_regions': [],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'customer_po', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .45, 'y0': .05, 'x1': .95, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
'template_mode': 'xfa_dataset',
|
||||
'bindings': [{
|
||||
'binding_id': 'value-source-customer_po', 'field_layout_id': 'customer_po',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': None},
|
||||
}],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 102, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:页面仍有原生标签时,字段值缺失必须继续读取同页 OCR,而非将整页误判为可用。
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
assert result['fields'][0]['source'] == 'ocr_coordinate'
|
||||
assert result['fields'][0]['status'] == 'needs_review'
|
||||
assert 'order_field_ocr_coordinate_needs_review' in result['fields'][0]['issues']
|
||||
|
||||
|
||||
def test_visual_sample_preview_uses_unique_xfa_widget_when_native_and_ocr_are_missing(app, monkeypatch):
|
||||
"""Hybrid XFA 的唯一带值 Widget 只能作为画框后的复核样本值。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
document = SimpleNamespace(id=103, asset_id=501, filename='hybrid.pdf')
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 103 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False)
|
||||
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .45, 'y0': .05, 'x1': .75, 'y1': .25}, value='4510039227'),
|
||||
], raising=False)
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []}, 'table_regions': [], 'draft_unbound_order_field_layouts': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'customer_po', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .40, 'y0': .04, 'x1': .80, 'y1': .30},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 103, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# Widget 值不进入正式取值;仅供当前视觉框展示,且必须要求人工复核。
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
assert result['fields'][0]['source'] == 'acroform_widget'
|
||||
assert result['fields'][0]['status'] == 'needs_review'
|
||||
assert 'order_field_acroform_widget_needs_review' in result['fields'][0]['issues']
|
||||
|
||||
|
||||
def test_visual_sample_preview_rejects_ambiguous_xfa_widget_values(app, monkeypatch):
|
||||
"""同一画框命中多个 XFA Widget 时,预览不得静默任选一个值。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
document = SimpleNamespace(id=104, asset_id=501, filename='hybrid.pdf')
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 104 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False)
|
||||
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .45, 'y0': .05, 'x1': .60, 'y1': .25}, value='4510039227'),
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .61, 'y0': .05, 'x1': .75, 'y1': .25}, value='4510039228'),
|
||||
], raising=False)
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []}, 'table_regions': [], 'draft_unbound_order_field_layouts': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'customer_po', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .40, 'y0': .04, 'x1': .80, 'y1': .30},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 104, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
assert result['fields'][0]['value'] is None
|
||||
assert result['fields'][0]['status'] == 'unavailable'
|
||||
assert 'order_field_acroform_widget_ambiguous' in result['fields'][0]['issues']
|
||||
|
||||
|
||||
def test_preview_page_region_text_uses_unique_xfa_widget_when_coordinate_text_is_missing(app, monkeypatch):
|
||||
"""任意已画视觉框在 native/OCR 无文本时,可展示唯一 XFA Widget 样本值。"""
|
||||
document = SimpleNamespace(id=109, asset_id=501, filename='hybrid.pdf')
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout)
|
||||
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False)
|
||||
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .45, 'y0': .20, 'x1': .70, 'y1': .30}, value='AMTEMP-S000218922'),
|
||||
], raising=False)
|
||||
with app.app_context():
|
||||
result = service.read_preview_page_region_text(
|
||||
1, data={'document_id': 109, 'region': {'x0': .40, 'y0': .15, 'x1': .75, 'y1': .35}}, page_no=1, actor_id=1,
|
||||
)
|
||||
|
||||
assert result['text'] == 'AMTEMP-S000218922'
|
||||
assert result['source'] == 'acroform_widget'
|
||||
assert result['status'] == 'needs_review'
|
||||
|
||||
|
||||
def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch):
|
||||
"""任意视觉框命中多个带值 Widget 时不得将其中之一冒充样本值。"""
|
||||
document = SimpleNamespace(id=110, asset_id=501, filename='hybrid.pdf')
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout)
|
||||
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False)
|
||||
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .45, 'y0': .20, 'x1': .55, 'y1': .30}, value='A'),
|
||||
SimpleNamespace(page_no=1, normalized_bbox={'x0': .56, 'y0': .20, 'x1': .70, 'y1': .30}, value='B'),
|
||||
], raising=False)
|
||||
with app.app_context():
|
||||
result = service.read_preview_page_region_text(
|
||||
1, data={'document_id': 110, 'region': {'x0': .40, 'y0': .15, 'x1': .75, 'y1': .35}}, page_no=1, actor_id=1,
|
||||
)
|
||||
|
||||
assert result['text'] == ''
|
||||
assert result['source'] == 'acroform_widget_ambiguous'
|
||||
|
||||
|
||||
def test_visual_sample_preview_discards_duplicate_unbound_layout_for_bound_field(app, monkeypatch):
|
||||
"""共同视觉预览忽略旧浏览器重复提交的已绑定未绑定布局,仍返回 PO 样本值。"""
|
||||
glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'line-field', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]})
|
||||
document = SimpleNamespace(id=101)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'order_field_1_1', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
definition['draft_unbound_order_field_layouts'] = [{
|
||||
'layout_id': 'order_field_1_1', 'label': '客户 PO 号',
|
||||
'page_scope': 'exact_page', 'page_no': 1, 'anchor': None,
|
||||
'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'minimum_evidence_level': 'coordinate',
|
||||
}] * 6
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 101, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:同一 layout 一旦有 Schema 绑定,不能再作为未绑定草稿传给坐标校验器。
|
||||
assert result['fields'][0]['field_code'] == 'customer_po_number'
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def test_visual_sample_preview_reads_order_field_before_table_region_is_drawn(app, monkeypatch):
|
||||
"""共同视觉预览在明细表尚未标注时,仍可读取已标注的订单级 PO 字段。"""
|
||||
glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]})
|
||||
document = SimpleNamespace(id=101)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []},
|
||||
'table_regions': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'order_field_1_2', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 101, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:预览仅展示现有视觉证据,不把“尚未绘制明细表”伪装为可保存模板。
|
||||
assert result['fields'][0]['field_code'] == 'customer_po_number'
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def _bind_ready_profile_sample(
|
||||
profile_id: int,
|
||||
*,
|
||||
@@ -342,7 +722,11 @@ def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
definition = _coordinate_definition()
|
||||
schema.definition_json['fields'][1].pop('allowed_sources', None)
|
||||
part_field = next(
|
||||
field for field in schema.definition_json['fields']
|
||||
if field['field_code'] == 'part_number'
|
||||
)
|
||||
part_field.pop('allowed_sources', None)
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft({
|
||||
'profile_code': 'COORD_V2', 'display_name': 'Coordinate V2',
|
||||
@@ -350,13 +734,13 @@ def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_
|
||||
}, actor_id=None)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
|
||||
schema.definition_json['fields'][1]['allowed_sources'] = ['pdf_coordinate']
|
||||
part_field['allowed_sources'] = ['pdf_coordinate']
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'COORD_V2', 'display_name': 'Coordinate V2',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
field_region = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field_region = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
assert field_region['field_id'] == 'part-field'
|
||||
assert 'contract_version' not in saved['definition']
|
||||
|
||||
@@ -373,6 +757,7 @@ def test_order_field_layout_is_independent_from_line_layout_and_freezes_header_f
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': 'forged', 'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page',
|
||||
'anchor': {'anchor_id': 'po_label', 'text': 'PO NO', 'aliases': ['PO NUMBER']},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
@@ -405,6 +790,7 @@ def test_order_field_layout_duplicate_returns_bound_schema_code(app):
|
||||
definition['order_field_layouts'] = [
|
||||
{
|
||||
'layout_id': f'ship_to_{index}', 'field_id': '', 'field_code': 'ship_to_customer',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': {'anchor_id': f'ship_to_label_{index}', 'text': f'SHIP TO {index}'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
@@ -448,6 +834,7 @@ def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app):
|
||||
definition['order_field_layouts'] = [
|
||||
{
|
||||
'layout_id': 'bill_to_customer_layout', 'field_id': '', 'field_code': 'bill_to_customer',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor,
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 3, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
|
||||
@@ -455,6 +842,7 @@ def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app):
|
||||
},
|
||||
{
|
||||
'layout_id': 'bill_to_address_layout', 'field_id': '', 'field_code': 'bill_to_address',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page', 'page_no': 2, 'anchor': shared_anchor,
|
||||
'value_region': {'x0': 3, 'y0': 0, 'x1': 10, 'y1': 1},
|
||||
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
|
||||
@@ -505,6 +893,7 @@ def test_order_field_layout_freezes_schema_normalizer_and_rejects_a_mismatch(app
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page', 'page_no': 1,
|
||||
'fallback_value_region': {'x0': .4, 'y0': .1, 'x1': .8, 'y1': .16},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'required': False,
|
||||
@@ -537,6 +926,7 @@ def test_order_field_ocr_minimum_level_keeps_native_pdf_as_stronger_allowed_sour
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page', 'anchor': {'anchor_id': 'po', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1}, 'value_mode': 'right_of_anchor',
|
||||
'stop_anchors': [], 'required': False, 'minimum_evidence_level': 'ocr_coordinate',
|
||||
@@ -565,7 +955,7 @@ def test_composite_coordinate_binding_freezes_all_registered_output_fields(app):
|
||||
'profile_code': 'COMPOSITE_QTY', 'display_name': 'Composite qty',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['target_fields']
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]['target_fields']
|
||||
assert targets == [
|
||||
{'field_id': 'qty-field', 'field_code': 'qty', 'scope': 'line'},
|
||||
{'field_id': 'uom-field', 'field_code': 'uom', 'scope': 'line'},
|
||||
@@ -600,14 +990,17 @@ def test_amount_currency_binding_freezes_header_target_and_checks_each_output_so
|
||||
])
|
||||
definition = _coordinate_definition()
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
field.update({'field_code': 'line_amount_before_tax', 'extractor_key': 'amount_currency'})
|
||||
field.update({
|
||||
'field_code': 'line_amount_before_tax',
|
||||
'extractor_key': 'amount_currency',
|
||||
})
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'COMPOSITE_AMOUNT', 'display_name': 'Composite amount',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['target_fields']
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]['target_fields']
|
||||
assert targets == [
|
||||
{'field_id': 'currency-field', 'field_code': 'currency', 'scope': 'line'},
|
||||
{'field_id': 'currency-field', 'field_code': 'currency', 'scope': 'header'},
|
||||
{'field_id': 'amount-field', 'field_code': 'line_amount_before_tax', 'scope': 'line'},
|
||||
]
|
||||
|
||||
@@ -631,12 +1024,12 @@ def test_coordinate_binding_allows_enabled_header_value_from_a_detail_physical_r
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
field['field_code'] = 'incoterm'
|
||||
field.update({'field_code': 'incoterm', 'scope': 'header'})
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'HEADER_FROM_LINE', 'display_name': 'Header from detail line',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
bound = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
bound = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
assert bound['field_id'] == 'incoterm-field'
|
||||
assert bound['target_fields'] == [{'field_id': 'incoterm-field', 'field_code': 'incoterm', 'scope': 'header'}]
|
||||
|
||||
@@ -675,7 +1068,18 @@ def test_profile_samples_are_governed_and_audited(app, monkeypatch):
|
||||
db.session.flush()
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'sample-table', 'html': '<table><tr><td>ok</td></tr></table>'}],
|
||||
'pages': [{'page_no': 1}],
|
||||
'tables': [{'table_id': 'sample-table', 'page_no': 1, 'html': '<table><tr><td>ok</td></tr></table>'}],
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': [{
|
||||
'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20},
|
||||
}]},
|
||||
'tables': {'sample-table': [{
|
||||
'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20},
|
||||
}]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}, 'tables': {'sample-table': 'pdf_coordinate'}},
|
||||
},
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
@@ -738,7 +1142,7 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon
|
||||
first['id'], actor_id=None, expected_lock_version=first['lock_version'],
|
||||
)
|
||||
|
||||
field_region = published['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field_region = published['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
assert field_region['field_id'] == 'part-field'
|
||||
assert field_region['field_code'] == 'part_number'
|
||||
assert len(published['checksum']) == 64
|
||||
@@ -1006,6 +1410,9 @@ def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_st
|
||||
checksum='c' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
definition_json={'fields': [
|
||||
dict(field) for field in source_schema.definition_json['fields']
|
||||
if field['field_id'] != 'part-field'
|
||||
] + [
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number',
|
||||
'scope': 'line', 'value_type': 'decimal', 'enabled': True,
|
||||
@@ -1030,7 +1437,7 @@ def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_st
|
||||
actor_id=None,
|
||||
)
|
||||
|
||||
field = migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field = migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
assert field['field_id'] == 'replacement-field'
|
||||
assert field['field_code'] == 'supplier_part_number'
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
@@ -1059,6 +1466,7 @@ def test_schema_migration_preserves_unbound_order_field_region_and_blocks_publis
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'po_number', 'field_id': '', 'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page',
|
||||
'anchor': {'anchor_id': 'po_label', 'text': 'PO NO'},
|
||||
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
|
||||
@@ -1483,9 +1891,9 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
profile.template_mode = 'xfa_dataset'
|
||||
db.session.commit()
|
||||
|
||||
# XFA 编辑画布可短时读取绑定原件,但绝不获得对象存储地址或可重放下载链接。
|
||||
# XFA 编辑画布也必须复用同一受控入口,不得恢复格式专属预览路由。
|
||||
raw_authorized = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
json={'document_id': document_id}, headers=headers,
|
||||
)
|
||||
assert raw_authorized.status_code == 200
|
||||
@@ -1493,18 +1901,18 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
raw_grant = parse_api_data(raw_authorized.get_json())
|
||||
assert 'storage_bucket' not in str(raw_grant) and 'storage_key' not in str(raw_grant)
|
||||
foreign = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
query_string={'preview_token': raw_grant['preview_token']},
|
||||
headers={'X-Username': 'other-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert foreign.status_code == 404
|
||||
raw_authorized = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
json={'document_id': document_id}, headers=headers,
|
||||
)
|
||||
raw_grant = parse_api_data(raw_authorized.get_json())
|
||||
raw_pdf = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
query_string={'preview_token': raw_grant['preview_token']}, headers=headers,
|
||||
)
|
||||
assert raw_pdf.status_code == 200
|
||||
@@ -1513,7 +1921,7 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
|
||||
assert raw_pdf.headers['Cache-Control'] == 'private, no-store, max-age=0'
|
||||
assert b'private-bucket' not in raw_pdf.data and b'internal/preview.pdf' not in raw_pdf.data
|
||||
raw_replay = client.get(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
|
||||
query_string={'preview_token': raw_grant['preview_token']}, headers=headers,
|
||||
)
|
||||
assert raw_replay.status_code == 404
|
||||
@@ -1592,6 +2000,7 @@ def test_profile_region_preview_uses_the_current_v2_region_definition(app, monke
|
||||
definition = _coordinate_definition()
|
||||
definition['table_regions'][0]['line_layouts'][0]['field_regions'] = [{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}]
|
||||
@@ -1664,6 +2073,7 @@ def test_coordinate_profile_exact_pages_allow_same_geometry_and_preview_only_cur
|
||||
table_region['line_layouts'][0]['layout_id'] = f'line_{page_no}_1'
|
||||
table_region['line_layouts'][0]['field_regions'] = [{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0 if page_no == 1 else .5, 'y0': 0, 'x1': .5 if page_no == 1 else 1, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}]
|
||||
@@ -2074,12 +2484,14 @@ def test_workbench_minimum_v2_definition_can_be_saved(app):
|
||||
'line_layouts': [{'layout_id': 'main_line', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': .16, 'y0': .30, 'x1': .72, 'y1': .50},
|
||||
'field_regions': [
|
||||
{'field_id': '', 'field_code': 'customer_po_line_no',
|
||||
'region': {'x0': .16, 'y0': .36, 'x1': .28, 'y1': .42},
|
||||
{'field_id': '', 'field_code': 'customer_po_line_no',
|
||||
'scope': 'line',
|
||||
'region': {'x0': .16, 'y0': .36, 'x1': .28, 'y1': .42},
|
||||
'extractor_key': 'direct', 'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate'},
|
||||
{'field_id': '', 'field_code': 'part_number',
|
||||
'region': {'x0': .30, 'y0': .36, 'x1': .44, 'y1': .42},
|
||||
{'field_id': '', 'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'region': {'x0': .30, 'y0': .36, 'x1': .44, 'y1': .42},
|
||||
'extractor_key': 'direct', 'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate'},
|
||||
],
|
||||
|
||||
@@ -98,3 +98,61 @@ def test_shipping_order_extraction_run_migration_round_trip():
|
||||
}
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def test_parallel_pdf_reparse_migration_replaces_active_intake_uniqueness():
|
||||
"""同一 EML 的不同 PDF 子 Run 必须能共用活动 Intake,回滚后恢复旧唯一约束。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
metadata = sa.MetaData()
|
||||
members = sa.Table(
|
||||
'shipping_order_processing_run_intakes',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('run_id', sa.Integer(), nullable=False),
|
||||
sa.Column('intake_id', sa.Integer(), nullable=False),
|
||||
sa.Column('position', sa.Integer(), nullable=False),
|
||||
sa.Column('released_at', sa.DateTime(), nullable=True),
|
||||
)
|
||||
sa.Index(
|
||||
'uq_shipping_order_processing_run_intakes_active_intake',
|
||||
members.c.intake_id,
|
||||
unique=True,
|
||||
sqlite_where=members.c.released_at.is_(None),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.hj4k5l6m7n8o_allow_parallel_pdf_reparse_runs'
|
||||
)
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
indexes = {
|
||||
index['name']: index
|
||||
for index in sa.inspect(connection).get_indexes('shipping_order_processing_run_intakes')
|
||||
}
|
||||
assert indexes['ix_shipping_order_processing_run_intakes_active_intake']['unique'] == 0
|
||||
connection.execute(sa.text(
|
||||
"INSERT INTO shipping_order_processing_run_intakes "
|
||||
"(id, run_id, intake_id, position) VALUES "
|
||||
"(1, 1, 9, 0), (2, 2, 9, 0)"
|
||||
))
|
||||
|
||||
try:
|
||||
migration.downgrade()
|
||||
raise AssertionError('downgrade must reject active parallel PDF reparses')
|
||||
except RuntimeError as exc:
|
||||
assert 'parallel PDF reparses' in str(exc)
|
||||
connection.execute(sa.text(
|
||||
"UPDATE shipping_order_processing_run_intakes "
|
||||
"SET released_at = CURRENT_TIMESTAMP WHERE id = 2"
|
||||
))
|
||||
migration.downgrade()
|
||||
indexes = {
|
||||
index['name']: index
|
||||
for index in sa.inspect(connection).get_indexes('shipping_order_processing_run_intakes')
|
||||
}
|
||||
assert indexes['uq_shipping_order_processing_run_intakes_active_intake']['unique'] == 1
|
||||
finally:
|
||||
migration.op = original_op
|
||||
@@ -8,7 +8,9 @@ backend/tests/test_shipping_order_extraction_runs.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
@@ -52,8 +54,10 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
resume_runs_waiting_for_layout,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
order_extraction_layouts_failed,
|
||||
materialize_order_extraction_run_inputs,
|
||||
serialize_order_extraction_message_state,
|
||||
serialize_order_extraction_run,
|
||||
synchronize_order_extraction_expansion_snapshot,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.jobs.queue import fail_job
|
||||
@@ -70,6 +74,7 @@ from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_apply_reparse_profile_affinity,
|
||||
route_deterministic_unit,
|
||||
)
|
||||
from app.services.shipping_notice.document_candidate_persist import _json_safe_value
|
||||
from tests.test_shipping_notice_order_extraction import _ensure_order_schema, _order
|
||||
|
||||
|
||||
@@ -92,6 +97,24 @@ def _seed_run_with_plan(*, suffix: str = 'A', agent_code: str = 'shipping_notice
|
||||
return user, agent, session, intake, document, run, reused
|
||||
|
||||
|
||||
def test_document_json_payload_normalizes_dynamic_date_and_decimal_values(app):
|
||||
"""Document JSON 写回前,动态 Schema 结果必须只含 JSON 原生值。"""
|
||||
with app.app_context():
|
||||
payload = _json_safe_value({
|
||||
'email_supplement': {
|
||||
'rows': [{
|
||||
'order_date': date(2026, 8, 14),
|
||||
'allocated_qty': Decimal('12.5000'),
|
||||
'evidence': [{'raw_value': '2026-08-14'}],
|
||||
}],
|
||||
},
|
||||
})
|
||||
|
||||
assert payload['email_supplement']['rows'][0]['order_date'] == '2026-08-14'
|
||||
assert payload['email_supplement']['rows'][0]['allocated_qty'] == '12.5000'
|
||||
assert json.loads(json.dumps(payload)) == payload
|
||||
|
||||
|
||||
def test_route_decision_is_immutable_per_unit_job_attempt_and_cascades_with_run(app):
|
||||
"""路由审计按尝试追加;同一尝试不可覆盖,删除 Run 时随其级联删除。"""
|
||||
with app.app_context():
|
||||
@@ -311,10 +334,84 @@ def test_create_run_reparses_empty_email_supplement_from_frozen_html_tables(app)
|
||||
)
|
||||
|
||||
body = next(item for item in run.input_snapshot_json['intakes'][0]['documents'] if item['document_type'] == 'email_body')
|
||||
assert body['email_supplement']['rows'][0]['po_number'] == '4518838154'
|
||||
assert body['email_supplement']['rows'][0]['customer_po_number'] == '4518838154'
|
||||
assert body['email_supplement']['rows'][0]['reservation_id'] == '4000111701'
|
||||
|
||||
|
||||
def test_create_run_serializes_date_values_in_frozen_email_supplement(app):
|
||||
"""邮件补充日期必须以 JSON 原生字符串冻结,避免重解析 Run 在首次 flush 时失败。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='EMAIL-DATE')
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
schema.definition_json = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#']},
|
||||
{'field_id': 'date', 'field_code': 'order_date', 'scope': 'header', 'value_type': 'date', 'aliases': ['Order Date']},
|
||||
]}
|
||||
intake.structured_result_json = {
|
||||
'email': {'body_html_tables': ['''<table><tr><th>PO#</th><th>Order Date</th></tr><tr><td>4518838154</td><td>2026-08-13</td></tr></table>''']},
|
||||
}
|
||||
db.session.add(ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='__email_body__',
|
||||
filename='email-body.html',
|
||||
content_hash='f' * 64,
|
||||
classification='email_context',
|
||||
parse_status='parsed',
|
||||
extracted_text='Order Date 2026-08-13',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
body = next(item for item in run.input_snapshot_json['intakes'][0]['documents'] if item['document_type'] == 'email_body')
|
||||
assert body['email_supplement']['rows'][0]['order_date'] == '2026-08-13'
|
||||
assert json.loads(json.dumps(run.input_snapshot_json)) == run.input_snapshot_json
|
||||
assert reused is False
|
||||
|
||||
|
||||
def test_materialize_run_serializes_date_values_from_email_supplement(app):
|
||||
"""Worker 物化正文日期时必须先转为 JSON 原生字符串,避免更新 Run 快照失败。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='EMAIL-DATE-MATERIALIZE')
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
schema.definition_json = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#']},
|
||||
{'field_id': 'date', 'field_code': 'order_date', 'scope': 'header', 'value_type': 'date', 'aliases': ['Order Date']},
|
||||
]}
|
||||
db.session.commit()
|
||||
|
||||
# 创建时没有正文补充表;真实 Worker 随后物化附件时才会重新解析该表。
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
intake.structured_result_json = {
|
||||
'email': {'body_html_tables': ['''<table><tr><th>PO#</th><th>Order Date</th></tr><tr><td>4518838154</td><td>2026-08-13</td></tr></table>''']},
|
||||
}
|
||||
db.session.add(ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='__email_body__',
|
||||
filename='email-body.html',
|
||||
content_hash='d' * 64,
|
||||
classification='email_context',
|
||||
parse_status='parsed',
|
||||
extracted_text='Order Date 2026-08-13',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
# 物化 I/O 已由其他用例覆盖;此处仅验证 Worker 重建快照后的 JSON 写入边界。
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents'):
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
|
||||
body = next(item for item in run.input_snapshot_json['intakes'][0]['documents'] if item['document_type'] == 'email_body')
|
||||
assert body['email_supplement']['rows'][0]['order_date'] == '2026-08-13'
|
||||
assert json.loads(json.dumps(run.input_snapshot_json)) == run.input_snapshot_json
|
||||
|
||||
|
||||
def test_create_run_reparses_partial_email_supplement_from_frozen_html_tables(app):
|
||||
"""历史正文已有部分行时,Run 仍须按冻结 Schema 重建新增的预约号列。"""
|
||||
with app.app_context():
|
||||
@@ -408,6 +505,30 @@ def test_worker_rematerializes_a_legacy_empty_plan(app):
|
||||
assert ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).count() == 1
|
||||
|
||||
|
||||
def test_rematerialization_syncs_existing_plan_snapshot_hash_after_layout_refresh(app):
|
||||
"""重试刷新布局证据后,既有 Plan 必须跟随同一 Run 快照哈希更新。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='PLAN-HASH-SYNC')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
plan = ensure_order_extraction_plan(run)
|
||||
original_hash = plan.input_snapshot_hash
|
||||
snapshot = dict(run.input_snapshot_json or {})
|
||||
snapshot['layout_refresh_marker'] = 'retry-1'
|
||||
run.input_snapshot_json = snapshot
|
||||
run.input_snapshot_hash = 'b' * 64
|
||||
db.session.commit()
|
||||
|
||||
refreshed = materialize_order_extraction_run_inputs(run)
|
||||
|
||||
assert refreshed is not None
|
||||
assert refreshed.id == plan.id
|
||||
assert refreshed.input_snapshot_hash == run.input_snapshot_hash
|
||||
assert refreshed.input_snapshot_hash != original_hash
|
||||
|
||||
|
||||
def test_create_run_rejects_an_intake_from_another_upload_batch(app):
|
||||
"""服务端必须拒绝伪造的跨批次 Intake 清单,不能依赖前端筛选。"""
|
||||
with app.app_context():
|
||||
@@ -1185,6 +1306,76 @@ def test_plan_can_append_future_selection_batch_units_idempotently(app):
|
||||
assert ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).count() == 2
|
||||
|
||||
|
||||
def test_expansion_batch_syncs_materialized_document_into_frozen_run_before_creating_unit(app):
|
||||
"""扩批附件必须先进入 Run 快照并同步 Plan 哈希,Worker 才能定位新增 Unit。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first_document = _seed_run_input(suffix='BATCH-SNAPSHOT')
|
||||
first_document.attachment_key = 'att-1'
|
||||
second_document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key='att-2',
|
||||
filename='orders-batch-snapshot.pdf',
|
||||
content_hash='e' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 451883817 BATCH SNAPSHOT',
|
||||
)
|
||||
db.session.add(second_document)
|
||||
db.session.flush()
|
||||
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
run = ShippingOrderProcessingRun(
|
||||
run_no='SNER-BATCH-SNAPSHOT',
|
||||
user_id=user.id,
|
||||
owner_agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
schema_version_id=schema_version.id,
|
||||
input_snapshot_hash='f' * 64,
|
||||
idempotency_key='batch-snapshot-idempotency',
|
||||
input_snapshot_json={
|
||||
'snapshot_version': 3,
|
||||
'schema': {'definition': schema_version.definition_json, 'checksum': schema_version.checksum},
|
||||
'intakes': [{
|
||||
'intake_id': intake.id,
|
||||
'intake_no': intake.intake_no,
|
||||
'documents': [{
|
||||
'document_id': first_document.id,
|
||||
'document_type': first_document.document_type,
|
||||
'attachment_key': 'att-1',
|
||||
'content_hash': first_document.content_hash,
|
||||
}],
|
||||
}],
|
||||
'attachment_selection': {
|
||||
'items': [
|
||||
{'intake_no': intake.intake_no, 'attachment_key': 'att-1', 'selected': True, 'selection_batch': 1},
|
||||
{'intake_no': intake.intake_no, 'attachment_key': 'att-2', 'selected': False, 'planned_selection_batch': 2},
|
||||
],
|
||||
},
|
||||
},
|
||||
status='queued',
|
||||
phase='queued',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderProcessingRunIntake(run_id=run.id, intake_id=intake.id, position=0))
|
||||
plan = ensure_order_extraction_plan(run)
|
||||
old_hash = str(run.input_snapshot_hash)
|
||||
|
||||
synchronize_order_extraction_expansion_snapshot(run, selection_batch=2)
|
||||
created = ensure_order_extraction_plan_batch(run, selection_batch=2)
|
||||
db.session.commit()
|
||||
|
||||
snapshot_document_ids = {
|
||||
int(document['document_id'])
|
||||
for snapshot_intake in run.input_snapshot_json['intakes']
|
||||
for document in snapshot_intake['documents']
|
||||
}
|
||||
assert int(second_document.id) in snapshot_document_ids
|
||||
assert run.input_snapshot_hash != old_hash
|
||||
assert plan.input_snapshot_hash == run.input_snapshot_hash
|
||||
assert [unit.document_id for unit in created] == [second_document.id]
|
||||
|
||||
|
||||
def test_run_submission_rejects_changed_frozen_mail_context(app):
|
||||
"""Run 创建后 EML From 变化必须触发来源漂移,不能以当前 Intake 覆盖冻结审计事实。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -335,6 +335,38 @@ def test_profile_matcher_compares_header_inside_table_not_page_header():
|
||||
assert candidate.dimension_scores.header_semantic_position >= 0.75
|
||||
|
||||
|
||||
def test_profile_matcher_selects_signature_main_table_when_metadata_table_precedes_it():
|
||||
"""运行时须按签名表区选择明细表,不能将前置抬头表误作主表。"""
|
||||
layout = _layout('PLANT NAME: FACTORY A')
|
||||
main_header = 'ITEM NO MATERIAL NO REV MATERIAL DESCRIPTION UNIT PRICE ORDER QUANTITY ORDER AMOUNT'
|
||||
main_glyphs = [
|
||||
{
|
||||
'text': char,
|
||||
'bbox': {'x0': 10 + index * 4, 'y0': 145, 'x1': 13 + index * 4, 'y1': 157},
|
||||
'boundary_before': 'space' if index and main_header[index - 1] == ' ' else 'none',
|
||||
}
|
||||
for index, char in enumerate(main_header)
|
||||
if char != ' '
|
||||
]
|
||||
layout['tables'] = [
|
||||
{'table_id': 'metadata', 'page_no': 1, 'bbox': {'x0': 0.05, 'y0': 0.10, 'x1': 0.95, 'y1': 0.35}},
|
||||
{'table_id': 'line-items', 'page_no': 1, 'bbox': {'x0': 0.05, 'y0': 0.50, 'x1': 0.95, 'y1': 0.95}},
|
||||
]
|
||||
layout['coordinate_evidence']['tables'] = {'metadata': [], 'line-items': main_glyphs}
|
||||
layout['coordinate_evidence']['page_glyphs']['1'].extend(main_glyphs)
|
||||
profile = _profile('PO_A')
|
||||
main_region = {'x0': 0.05, 'y0': 0.50, 'x1': 0.95, 'y1': 0.95}
|
||||
profile['definition']['table_regions'][0]['region'] = main_region
|
||||
profile['definition']['table_regions'][0]['line_layouts'][0]['region'] = main_region
|
||||
profile = _with_signature(profile, layout)
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
|
||||
|
||||
assert result.status == 'unique_match'
|
||||
assert result.candidates[0].dimension_scores.header_semantic_position >= 0.75
|
||||
assert result.candidates[0].dimension_scores.column_topology >= 0.75
|
||||
|
||||
|
||||
def test_profile_matcher_excludes_below_threshold_hard_candidate_from_uniqueness():
|
||||
"""硬门禁通过但得分或证据覆盖不合格的候选,不得阻塞唯一合格模板。"""
|
||||
layout = _layout('PLANT NAME: FACTORY A')
|
||||
@@ -348,3 +380,35 @@ def test_profile_matcher_excludes_below_threshold_hard_candidate_from_uniqueness
|
||||
|
||||
assert result.status == 'unique_match'
|
||||
assert result.profile_code == 'PO_QUALIFIED'
|
||||
|
||||
|
||||
def test_parse_validation_does_not_upgrade_ineligible_profile_to_unique_match(monkeypatch):
|
||||
"""解析可用性只能验证已通过匹配资格门禁的模板,不能绕过评分和证据覆盖。"""
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
ProfileMatchCandidate,
|
||||
ProfileMatchResult,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_workflow import _apply_parse_validation_gate
|
||||
|
||||
profile = _with_signature(_profile('PO_INELIGIBLE', score=.95), _layout())
|
||||
profile['definition']['document_match']['scoring_thresholds']['evidence_coverage_minimum'] = 0.95
|
||||
match = ProfileMatchResult(
|
||||
status='no_match',
|
||||
candidates=[ProfileMatchCandidate(
|
||||
profile_code='PO_INELIGIBLE', version=1, score=.96,
|
||||
evidence_coverage=.60, hard_match=True,
|
||||
)],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow.validate_profile_parse_candidate',
|
||||
lambda **_: {'passed': True, 'reason_codes': [], 'metrics': {}},
|
||||
)
|
||||
|
||||
result = _apply_parse_validation_gate(
|
||||
match=match,
|
||||
coordinate_profiles=[profile],
|
||||
layout=_layout(),
|
||||
definition={},
|
||||
)
|
||||
|
||||
assert result.status == 'no_match'
|
||||
@@ -12,6 +12,7 @@ from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice.order_review_field_conflict_service import (
|
||||
project_review_case_evidence_issues,
|
||||
project_review_case_field_conflicts,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import _sync_review_gates_safe
|
||||
@@ -93,15 +94,34 @@ def test_project_review_case_field_conflicts_empty_without_candidate():
|
||||
assert project_review_case_field_conflicts(case) == []
|
||||
|
||||
|
||||
def test_project_review_case_field_conflicts_keeps_single_value_evidence_gap_actionable():
|
||||
"""证据缺失不是双值冲突,也必须投影字段和行号,供用户手工补证据/裁决。"""
|
||||
def test_project_review_findings_deduplicate_evidence_gaps_and_keep_them_out_of_value_conflicts():
|
||||
"""同键证据缺失只能保留一项,并与多值字段冲突分区展示。"""
|
||||
candidate = SimpleNamespace(
|
||||
conflicts_json=[{
|
||||
'field': 'part_number',
|
||||
'line_index': 0,
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
}],
|
||||
conflicts_json=[
|
||||
{
|
||||
'field': 'reservation_id',
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
},
|
||||
{
|
||||
'field': 'reservation_id',
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
},
|
||||
{
|
||||
'field': 'part_number',
|
||||
'line_index': 0,
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
},
|
||||
{
|
||||
'field': 'qty',
|
||||
'line_index': 0,
|
||||
'severity': 'blocking',
|
||||
'reason': 'field_conflict',
|
||||
'values': ['10', '12'],
|
||||
},
|
||||
],
|
||||
structured_result_json={},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
@@ -118,17 +138,21 @@ def test_project_review_case_field_conflicts_keeps_single_value_evidence_gap_act
|
||||
finally:
|
||||
svc._candidate_for_case = original
|
||||
|
||||
# 关键断言:不可自动建单的证据缺失不能在字段冲突投影层静默丢失。
|
||||
assert items == [{
|
||||
'conflict_key': '0:part_number',
|
||||
'field_code': 'part_number',
|
||||
'line_index': 0,
|
||||
'line_key': 'line-1',
|
||||
'severity': 'blocking',
|
||||
'reason': 'evidence_missing',
|
||||
'options': [],
|
||||
'observation_ids': [],
|
||||
}]
|
||||
assert [item['conflict_key'] for item in items] == ['0:qty']
|
||||
|
||||
original = svc._candidate_for_case
|
||||
svc._candidate_for_case = lambda _case: candidate
|
||||
try:
|
||||
evidence_issues = project_review_case_evidence_issues(case)
|
||||
finally:
|
||||
svc._candidate_for_case = original
|
||||
|
||||
# 关键断言:同一预约单号证据缺失合并为一项,且不再伪装为待选值冲突。
|
||||
assert [(item['conflict_key'], item['reason']) for item in evidence_issues] == [
|
||||
('-1:reservation_id', 'evidence_missing'),
|
||||
('0:part_number', 'evidence_missing'),
|
||||
]
|
||||
assert [item['scope'] for item in evidence_issues] == ['unscoped', 'line']
|
||||
|
||||
|
||||
def test_sync_review_gates_replaces_stale_missing_field_gate_with_field_conflict():
|
||||
|
||||
@@ -80,3 +80,10 @@ def test_project_review_case_profile_match_missing_route():
|
||||
payload = svc.project_review_case_profile_match(case)
|
||||
assert payload['available'] is False
|
||||
assert payload['status'] == 'unknown'
|
||||
|
||||
|
||||
def test_profile_display_name_never_falls_back_to_internal_code():
|
||||
"""冻结快照只有技术编号时,投影不得把编号伪装成用户模板名称。"""
|
||||
assert svc._resolve_profile_display_name(
|
||||
code='ODP-INTERNAL', version=0, display_map={('ODP-INTERNAL', 0): 'ODP-INTERNAL'},
|
||||
) is None
|
||||
@@ -14,6 +14,7 @@ from unittest.mock import patch
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ShippingOrderDocument,
|
||||
@@ -23,7 +24,9 @@ from app.models import (
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewConfirmedRevision,
|
||||
ShippingOrderReviewWaveLine,
|
||||
@@ -47,11 +50,123 @@ from app.services.shipping_notice.order_review_service import (
|
||||
get_user_review_case,
|
||||
get_review_queue_visible_to_user,
|
||||
)
|
||||
from app.services.shipping_notice.review_stream_service import activate_review_case, mark_review_stream_confirmed
|
||||
from app.services.shipping_notice.review_stream_backfill_service import backfill_review_streams
|
||||
from app.services.shipping_notice.process_gate_bridge import find_execution_for_case
|
||||
|
||||
|
||||
def test_review_queue_aggregates_active_runs_in_same_conversation(app):
|
||||
"""会话队列汇总同一对话的多个有效 Run,并排除已被替代的版本。"""
|
||||
def test_review_stream_switches_current_case_without_hiding_other_document_cases(app):
|
||||
"""同一 PDF 的新版只能替换自身 Case,批次内其他文件继续保持各自当前版本。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-STREAM-CURRENT')
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
original_case = ensure_run_review_cases(run=source)[0]
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
|
||||
replacement, _ = reparse_case_document(
|
||||
user_id=user.id,
|
||||
case_no=original_case.case_no,
|
||||
reason='rule_updated',
|
||||
)
|
||||
ensure_order_extraction_plan(replacement)
|
||||
for unit in replacement.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
replacement_case = ensure_run_review_cases(run=replacement)[0]
|
||||
activate_review_case(
|
||||
case=replacement_case,
|
||||
trigger='document_reparse_succeeded',
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
stream = ShippingOrderReviewStream.query.filter_by(document_id=document.id).one()
|
||||
assert stream.current_case_id == replacement_case.id
|
||||
assert replacement_case.supersedes_case_id == original_case.id
|
||||
assert original_case.status == 'superseded'
|
||||
assert original_case.superseded_by_case_id == replacement_case.id
|
||||
|
||||
|
||||
def test_review_stream_refuses_to_replace_a_confirmed_case_with_later_draft(app):
|
||||
"""并行重解析晚到的草稿不得覆盖已有确认/履约事实。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-STREAM-CONFIRMED')
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
confirmed_case = ensure_run_review_cases(run=source)[0]
|
||||
# 用 Stream 的确认锁模拟正式确认已完成;Case 保持可重解析以构造晚到并行分支。
|
||||
mark_review_stream_confirmed(case=confirmed_case)
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
replacement, _ = reparse_case_document(
|
||||
user_id=user.id, case_no=confirmed_case.case_no, reason='rule_updated',
|
||||
)
|
||||
ensure_order_extraction_plan(replacement)
|
||||
for unit in replacement.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
competing = ensure_run_review_cases(run=replacement)[0]
|
||||
stream = activate_review_case(case=competing, trigger='document_reparse_succeeded')
|
||||
|
||||
assert stream.current_case_id != competing.id
|
||||
assert stream.confirmed_case_id is not None
|
||||
assert stream.state == 'conflict'
|
||||
|
||||
|
||||
def test_review_stream_backfill_dry_run_does_not_change_existing_stream(app):
|
||||
"""回填 dry-run 只生成选择清单,不改当前指针或版本号。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-STREAM-DRY-RUN')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
stream = ShippingOrderReviewStream.query.filter_by(document_id=document.id).one()
|
||||
before = (stream.current_case_id, stream.revision, case.stream_id, case.revision_no)
|
||||
|
||||
result = backfill_review_streams(document_ids=[document.id], dry_run=True)
|
||||
|
||||
assert result['dry_run'] is True
|
||||
assert result['stream_count'] == 0
|
||||
db.session.refresh(stream)
|
||||
db.session.refresh(case)
|
||||
assert (stream.current_case_id, stream.revision, case.stream_id, case.revision_no) == before
|
||||
|
||||
|
||||
def test_review_stream_backfill_prefers_confirmed_case_and_binds_every_case(app):
|
||||
"""回填时 confirmed 版本优先;所有 Case 绑定同一 Stream 且只保留一个 current。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-STREAM-BACKFILL')
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
original = ensure_run_review_cases(run=source)[0]
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
replacement, _ = reparse_case_document(
|
||||
user_id=user.id, case_no=original.case_no, reason='rule_updated',
|
||||
)
|
||||
ensure_order_extraction_plan(replacement)
|
||||
for unit in replacement.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
newer = ensure_run_review_cases(run=replacement)[0]
|
||||
newer.status = 'draft'
|
||||
original.status = 'confirmed'
|
||||
original.confirmed_task_id = None
|
||||
# 构造历史脏状态:当前指针暂时错误地落在后来的草稿。
|
||||
stream = ShippingOrderReviewStream.query.filter_by(document_id=document.id).one()
|
||||
stream.current_case_id = newer.id
|
||||
stream.confirmed_case_id = None
|
||||
db.session.commit()
|
||||
|
||||
result = backfill_review_streams(document_ids=[document.id], dry_run=False)
|
||||
db.session.commit()
|
||||
|
||||
assert result['stream_count'] == 1
|
||||
assert result['documents'][0]['current_case_no'] == original.case_no
|
||||
stream = ShippingOrderReviewStream.query.filter_by(document_id=document.id).one()
|
||||
assert stream.current_case_id == original.id
|
||||
assert stream.confirmed_case_id == original.id
|
||||
bound = ShippingOrderReviewCase.query.filter_by(stream_id=stream.id).all()
|
||||
assert {case.id for case in bound} == {original.id, newer.id}
|
||||
assert sum(1 for case in bound if case.id == stream.current_case_id) == 1
|
||||
|
||||
|
||||
def test_review_queue_keeps_independent_document_streams_when_a_batch_run_is_superseded(app):
|
||||
"""Run 替代不能隐藏其内无关文件;队列必须按文件 Stream 返回各自当前 Case。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE')
|
||||
first = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
@@ -142,6 +257,7 @@ def test_review_queue_aggregates_active_runs_in_same_conversation(app):
|
||||
db.session.commit()
|
||||
replacement = _materialized_run(user=user, agent=agent, session=session, intake=replacement_intake)
|
||||
ensure_run_review_cases(run=replacement)
|
||||
first.review_cases[0].status = 'superseded'
|
||||
second.superseded_by_run_id = replacement.id
|
||||
db.session.commit()
|
||||
|
||||
@@ -149,8 +265,8 @@ def test_review_queue_aggregates_active_runs_in_same_conversation(app):
|
||||
first.run_no, user.id, is_admin=False,
|
||||
))
|
||||
|
||||
assert [item['source_run_no'] for item in queue['items']] == [first.run_no, replacement.run_no]
|
||||
assert queue['items'][0]['case_no'] == first.review_cases[0].case_no
|
||||
# 关键断言:旧文件的 superseded Case 被过滤;独立第二文件不因其 Run 替代被隐藏。
|
||||
assert {item['source_run_no'] for item in queue['items']} == {second.run_no, replacement.run_no}
|
||||
assert queue['summary']['total'] == 2
|
||||
|
||||
|
||||
@@ -222,36 +338,33 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app):
|
||||
]
|
||||
|
||||
|
||||
def test_review_case_projects_replacement_upload_as_its_own_permission(app):
|
||||
"""替代件上传必须独立于质量异常标记权限,前端不得以别的动作码推断。"""
|
||||
def test_review_case_does_not_expose_replacement_upload(app):
|
||||
"""复核 Case 仅允许原 PDF 重识别,不暴露上传替代文件动作。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-REPLACEMENT-ACTION')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
draft_actions = serialize_review_case(case)['available_actions']
|
||||
assert 'upload_replacement' in draft_actions
|
||||
assert 'mark_quality_issue' in draft_actions
|
||||
|
||||
case.status = 'quality_issue'
|
||||
db.session.commit()
|
||||
quality_actions = serialize_review_case(case)['available_actions']
|
||||
assert 'upload_replacement' in quality_actions
|
||||
assert 'mark_quality_issue' in quality_actions
|
||||
|
||||
case.status = 'confirmed'
|
||||
db.session.commit()
|
||||
assert 'upload_replacement' not in draft_actions
|
||||
assert 'upload_replacement' not in quality_actions
|
||||
assert 'upload_replacement' not in serialize_review_case(case)['available_actions']
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
add_line,
|
||||
adopt_inventory_routing_suggestion,
|
||||
build_confirmable_draft_summary,
|
||||
delete_line,
|
||||
keep_manual_inventory_routing,
|
||||
patch_header_field,
|
||||
patch_line_field,
|
||||
reroute_inventory_routing,
|
||||
set_line_inventory_candidates,
|
||||
validate_draft,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_evidence_service import (
|
||||
@@ -265,7 +378,9 @@ from app.services.shipping_notice.order_review_disposition_service import (
|
||||
finalize_document_reparse,
|
||||
mark_non_order,
|
||||
mark_quality_issue,
|
||||
reparse_batch_documents,
|
||||
reparse_case_document,
|
||||
select_current_batch_reparse_cases,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
@@ -944,7 +1059,12 @@ def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(ap
|
||||
assert updated['draft']['issues'] == []
|
||||
validated = validate_draft(user_id=user.id, case_no=case.case_no, expected_draft_version=3)
|
||||
assert validated['draft']['validation']['status'] == 'ready'
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id).count() == 4
|
||||
event_types = {
|
||||
event.event_type
|
||||
for event in ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id).all()
|
||||
}
|
||||
# Stream 初始化追加版本主线审计;原有编辑/校验审计仍必须完整保留。
|
||||
assert {'case_initialized', 'review_stream_case_activated', 'header_field_changed', 'line_field_changed', 'draft_validated'} <= event_types
|
||||
|
||||
|
||||
def test_review_draft_empty_line_and_last_line_delete_remain_blocking(app):
|
||||
@@ -1087,6 +1207,8 @@ def test_review_email_evidence_preview_reads_only_the_sibling_email_body(app):
|
||||
'document_type': 'email_body',
|
||||
'filename': 'review-email.eml',
|
||||
'text': 'Reservation Number: 33894',
|
||||
# 无原始 EML 安全快照时显式降级文本,前端不得误当 HTML iframe 渲染。
|
||||
'render_kind': 'text',
|
||||
}
|
||||
|
||||
|
||||
@@ -1122,6 +1244,7 @@ def test_case_intake_parse_context_returns_own_attachment_and_sibling_email(app)
|
||||
'email': {
|
||||
'document_id': body.id,
|
||||
'filename': 'source.eml',
|
||||
'render_kind': 'text',
|
||||
'text': 'approved body text',
|
||||
},
|
||||
}
|
||||
@@ -1190,6 +1313,7 @@ def test_case_intake_parse_context_never_reads_email_from_another_intake(app):
|
||||
assert context['email'] == {
|
||||
'document_id': own_body.id,
|
||||
'filename': 'own.eml',
|
||||
'render_kind': 'text',
|
||||
'text': 'only own body',
|
||||
}
|
||||
assert other_body.id != context['email']['document_id']
|
||||
@@ -1269,6 +1393,29 @@ def test_case_intake_parse_context_returns_no_email_for_direct_pdf_and_api_audit
|
||||
}
|
||||
|
||||
|
||||
def test_email_preview_route_returns_isolated_html_with_strict_csp(app, monkeypatch):
|
||||
"""独立邮件预览响应必须禁止主动内容来源,并允许 iframe 使用一次性 capability token。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.eml_preview_service.consume_eml_preview_grant',
|
||||
lambda **_kwargs: '<html><head><style>.po{border:1px solid #000}</style></head><body><table class="po"><tr><td>PO</td></tr></table></body></html>',
|
||||
)
|
||||
client = app.test_client()
|
||||
|
||||
response = client.get(
|
||||
'/api/workspace/shipping-notice/order-review-cases/CASE-1/email-preview?preview_token=single-use',
|
||||
)
|
||||
|
||||
# 关键断言:HTML 独立于工作台 DOM,并以 CSP 阻断脚本、网络、图片和表单。
|
||||
assert response.status_code == 200
|
||||
assert response.mimetype == 'text/html'
|
||||
assert '<table class="po">' in response.get_data(as_text=True)
|
||||
csp = response.headers['Content-Security-Policy']
|
||||
assert "default-src 'none'" in csp
|
||||
assert "script-src 'none'" in csp
|
||||
assert "img-src 'none'" in csp
|
||||
assert "form-action 'none'" in csp
|
||||
|
||||
|
||||
def test_review_evidence_normalizes_frozen_layout_coordinates(app):
|
||||
"""坐标订单字段必须以冻结页尺寸换算为前端可绘制 bbox,并准确切换证据页。"""
|
||||
with app.app_context():
|
||||
@@ -1598,9 +1745,18 @@ def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(a
|
||||
db.session.commit()
|
||||
|
||||
replacement, _ = reparse_case_document(user_id=user.id, case_no=case.case_no, reason='other')
|
||||
ensure_order_extraction_plan(replacement)
|
||||
for unit in replacement.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
replacement_case = ensure_run_review_cases(run=replacement)[0]
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
assert case.status == 'superseded'
|
||||
assert case.disposition == 'reparsed'
|
||||
assert replacement_case.stream_id == case.stream_id
|
||||
# 迁移前遗留数据可能仍把已替代 Case 标记为开放;Run 详情只能认 Stream 当前
|
||||
# 指针,不能因旧 status 再次把它展示为可复核项。
|
||||
case.status = 'unreviewed'
|
||||
assert serialize_review_run(run)['items'] == []
|
||||
# 关键断言:旧 Run 明确投影后继编号,前端可跳转而非把已替代 Case 渲染为空白。
|
||||
run.superseded_by_run_id = replacement.id
|
||||
assert serialize_review_run(run)['superseded_by_run_no'] == replacement.run_no
|
||||
@@ -1612,56 +1768,144 @@ def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(a
|
||||
raise AssertionError('superseded case must not be reparsed')
|
||||
|
||||
|
||||
def test_replacement_run_requires_new_pdf_and_preserves_old_case_until_success(app):
|
||||
"""替代上传必须来自新私有 PDF Intake;成功前保留旧草稿,成功后才把旧证据设为替代。"""
|
||||
def test_run_auto_progress_ignores_legacy_open_case_that_is_not_stream_current(app):
|
||||
"""Run 级协调只能处理文件 Stream 当前 Case,不能重启残留旧版本。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-REPLACEMENT')
|
||||
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
|
||||
reconcile_run_review_cases_for_auto_progress,
|
||||
)
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-PROGRESS-STREAM-CURRENT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
original = ensure_run_review_cases(run=run)[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_document_run
|
||||
replacement, _ = reparse_case_document(user_id=user.id, case_no=original.case_no, reason='other')
|
||||
ensure_order_extraction_plan(replacement)
|
||||
for unit in replacement.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
ensure_run_review_cases(run=replacement)
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
original.status = 'unreviewed'
|
||||
db.session.commit()
|
||||
|
||||
asset = FileAsset(
|
||||
asset_no='FAS-REVIEW-REPLACEMENT', owner_user_id=user.id, original_filename='replacement.pdf',
|
||||
extension='pdf', upload_status='ready', lifecycle_status='temporary', storage_provider='test',
|
||||
storage_bucket='test', storage_key='test/replacement.pdf', content_hash='replacement-asset-hash',
|
||||
file_size=1,
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
replacement_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-REVIEW-REPLACEMENT', asset_id=asset.id, user_id=user.id,
|
||||
conversation_id=session.session_id, upload_batch_id='review-replacement-test', purpose='shipping_notice',
|
||||
parse_status='parsed', parser_version=intake.parser_version,
|
||||
)
|
||||
db.session.add(replacement_intake)
|
||||
db.session.flush()
|
||||
replacement_document = ShippingOrderDocument(
|
||||
intake_id=replacement_intake.id, asset_id=asset.id, attachment_key='file', document_type='attachment',
|
||||
filename='replacement.pdf', content_hash='replacement-hash', parse_status='parsed', extracted_text='replacement order',
|
||||
results = reconcile_run_review_cases_for_auto_progress(run)
|
||||
|
||||
assert all(item['case_no'] != original.case_no for item in results)
|
||||
|
||||
|
||||
def test_batch_reparse_uses_latest_case_for_each_original_pdf(app):
|
||||
"""批次再次重解析必须选中局部成功后的新版 Case,不能回退来源 Run 的旧 Case。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, first_document = _seed_run_input(suffix='BATCH-REPARSE-LINEAGE')
|
||||
second_document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key='batch-second.pdf',
|
||||
filename='batch-second.pdf',
|
||||
content_hash='b' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='Second batch PDF',
|
||||
)
|
||||
db.session.add(replacement_document)
|
||||
db.session.add(second_document)
|
||||
db.session.commit()
|
||||
|
||||
# 布局调度由独立 Job 覆盖;此服务测试只验证替代文件的谱系与 Case 收口。
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts', return_value=True):
|
||||
replacement, reused = create_replacement_document_run(
|
||||
user_id=user.id, case_no=case.case_no, intake_no=replacement_intake.intake_no,
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
source_cases = ensure_run_review_cases(run=source)
|
||||
assert {int(case.document_id) for case in source_cases} == {int(first_document.id), int(second_document.id)}
|
||||
original_first_case = next(case for case in source_cases if int(case.document_id) == int(first_document.id))
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts', return_value=True):
|
||||
first_batch = reparse_batch_documents(
|
||||
user_id=user.id, run_no=source.run_no, reason='rule_updated', comment='first batch pass',
|
||||
)
|
||||
assert reused is False
|
||||
assert case.status == 'reparse_pending'
|
||||
marker = replacement.input_snapshot_json['review_reparse']
|
||||
assert marker['document_id'] == replacement_document.id
|
||||
assert marker['source_case_no'] == case.case_no
|
||||
assert marker['source_candidate_id'] is None
|
||||
assert marker['source_order_task_no'] is None
|
||||
assert replacement.user_task_no is None
|
||||
finalize_document_reparse(run=replacement, succeeded=False)
|
||||
assert case.status == 'unreviewed'
|
||||
assert len(first_batch['created']) == 2
|
||||
first_child_no = next(
|
||||
item['run_no'] for item in first_batch['created']
|
||||
if int(item['document_id']) == int(first_document.id)
|
||||
)
|
||||
first_child = ShippingOrderProcessingRun.query.filter_by(run_no=first_child_no).one()
|
||||
ensure_order_extraction_plan(first_child)
|
||||
for unit in first_child.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
newest_first_case = ensure_run_review_cases(run=first_child)[0]
|
||||
transition_order_extraction_run(first_child, target_status='processing')
|
||||
transition_order_extraction_run(first_child, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
root, current_cases = select_current_batch_reparse_cases(user_id=user.id, run=source)
|
||||
assert root.id == source.id
|
||||
assert newest_first_case.case_no in {case.case_no for case in current_cases}
|
||||
assert original_first_case.case_no not in {case.case_no for case in current_cases}
|
||||
# 根 Run 的原 Case 虽已替代,批次入口仍必须基于谱系中的新版 Case 保持可用。
|
||||
assert 'reparse_batch' in serialize_workspace_run(source)['available_actions']
|
||||
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts', return_value=True):
|
||||
second_batch = reparse_batch_documents(
|
||||
user_id=user.id, run_no=source.run_no, reason='rule_updated', comment='second batch pass',
|
||||
)
|
||||
second_first = next(
|
||||
item for item in second_batch['created']
|
||||
if int(item['document_id']) == int(first_document.id)
|
||||
)
|
||||
grandchild = ShippingOrderProcessingRun.query.filter_by(run_no=second_first['run_no']).one()
|
||||
marker = grandchild.input_snapshot_json['review_reparse']
|
||||
assert second_first['case_no'] == newest_first_case.case_no
|
||||
assert grandchild.reparse_of_run_id == first_child.id
|
||||
assert marker['source_case_no'] == newest_first_case.case_no
|
||||
# 第二份 PDF 的未完成子 Run 应被幂等复用,不得阻断已成功 PDF 的再次重解析。
|
||||
assert any(item['reused'] for item in second_batch['created'])
|
||||
|
||||
|
||||
def test_batch_reparse_api_creates_one_successor_per_original_pdf(app, client):
|
||||
"""批次端点必须落到按 PDF 子 Run 的服务,而不是创建整体 Run 后继版本。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _first_document = _seed_run_input(suffix='BATCH-REPARSE-API')
|
||||
db.session.add(ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key='batch-api-second.pdf',
|
||||
filename='batch-api-second.pdf',
|
||||
content_hash='c' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='Second batch API PDF',
|
||||
))
|
||||
db.session.commit()
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts', return_value=True):
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
ensure_run_review_cases(run=source)
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
run_no = source.run_no
|
||||
token = issue_local_access_token(user)
|
||||
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts', return_value=True):
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-extraction-runs/{run_no}/reparse-batch',
|
||||
json={'reason': 'rule_updated', 'comment': 'refresh both original PDFs'},
|
||||
headers={'Authorization': f'Bearer {token}'},
|
||||
)
|
||||
|
||||
assert response.status_code == 202
|
||||
payload = response.get_json()['data']
|
||||
assert payload['source_run_no'] == run_no
|
||||
assert len(payload['created']) == 2
|
||||
assert len({item['document_id'] for item in payload['created']}) == 2
|
||||
with app.app_context():
|
||||
successors = ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.reparse_of_run_id == source.id,
|
||||
).all()
|
||||
assert len(successors) == 2
|
||||
assert all(run.input_snapshot_json['review_reparse']['batch_reparse_id'] == payload['batch_reparse_id'] for run in successors)
|
||||
|
||||
|
||||
def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
|
||||
@@ -1927,7 +2171,7 @@ def test_confirm_review_case_rejects_when_inventory_source_unresolved(app):
|
||||
|
||||
|
||||
def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app):
|
||||
"""重路由读取最新规则与启停状态;人工决定不被静默覆盖;同幂等键只生效一次。"""
|
||||
"""重路由读取最新规则与启停状态,并覆盖历史人工库存源选择。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingAuditEvent
|
||||
|
||||
@@ -1966,11 +2210,14 @@ def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app):
|
||||
)],
|
||||
))
|
||||
db.session.commit()
|
||||
set_line_inventory_candidates(
|
||||
user_id=user.id, case_no=case.case_no, line_key=line_key,
|
||||
source_codes=['DSV360_AWSDU'], reason='planner keep AWSDU',
|
||||
expected_draft_version=case.current_draft.draft_version,
|
||||
)
|
||||
# 模拟历史数据中的人工库存源覆盖;自动重路由必须删除它。
|
||||
lines = list(case.current_draft.lines_json or [])
|
||||
lines[0]['inventory_routing'] = {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': ['DSV360_AWSDU'],
|
||||
'manual_reason': 'legacy planner selection',
|
||||
}
|
||||
case.current_draft.lines_json = lines
|
||||
db.session.commit()
|
||||
db.session.refresh(case.current_draft)
|
||||
manual_version = int(case.current_draft.draft_version)
|
||||
@@ -1997,11 +2244,11 @@ def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app):
|
||||
idempotency_key='reroute-key-1', line_key=line_key,
|
||||
)
|
||||
|
||||
# 关键断言:人工有效候选不变;规则建议更新;同幂等键不二次升版本。
|
||||
# 关键断言:发布规则是唯一裁决来源;历史人工值不得阻止自动重算。
|
||||
projection = first['draft']['build_eligibility']['line_projections'][0]
|
||||
assert projection['selection_mode'] == 'manual'
|
||||
assert projection['selection_mode'] != 'manual'
|
||||
assert projection['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
|
||||
assert 'DSV360_AWSDU' in (projection.get('rule_suggestion_source_codes') or [])
|
||||
assert projection.get('suggestion_pending') is False
|
||||
assert any(item.get('rule_code') == 'NEW_AWSDU' for item in (projection.get('rule_versions') or []))
|
||||
assert replay['draft']['draft_version'] == first['draft']['draft_version']
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(
|
||||
@@ -2033,77 +2280,6 @@ def test_inventory_routing_reroute_uses_latest_rules_without_pdf_reparse(app):
|
||||
case_id=case.id, event_type='inventory_routing_rerouted',
|
||||
).count() == reroute_events
|
||||
|
||||
# 采用规则建议后有效候选切到规则结果。
|
||||
adopted = adopt_inventory_routing_suggestion(
|
||||
user_id=user.id, case_no=case.case_no, line_key=line_key,
|
||||
expected_draft_version=version_after_second,
|
||||
idempotency_key='adopt-key-1', reason='accept latest rule',
|
||||
)
|
||||
db.session.commit()
|
||||
adopted_proj = adopted['draft']['build_eligibility']['line_projections'][0]
|
||||
assert adopted_proj['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
|
||||
assert adopted_proj.get('suggestion_pending') is False
|
||||
|
||||
|
||||
def test_inventory_routing_keep_manual_clears_pending_suggestion(app):
|
||||
"""保留人工结果会清除 suggestion_pending,且不改有效候选。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-KEEP-MANUAL')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
schema = dict(snapshot['schema'])
|
||||
definition = dict(schema['definition'])
|
||||
definition['fields'] = [
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
|
||||
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A004'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
{'field_id': 'reservation-id', 'observations': [{'value': '1000999999'}]},
|
||||
]}]}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
line_key = case.current_draft.lines_json[0]['line_key']
|
||||
_seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id')
|
||||
|
||||
set_line_inventory_candidates(
|
||||
user_id=user.id, case_no=case.case_no, line_key=line_key,
|
||||
source_codes=['DSV360_AWSDU'], reason='manual keep',
|
||||
expected_draft_version=case.current_draft.draft_version,
|
||||
)
|
||||
db.session.commit()
|
||||
db.session.refresh(case.current_draft)
|
||||
# 人为制造 pending 建议差异:写入不同 suggestion 标记。
|
||||
lines = list(case.current_draft.lines_json or [])
|
||||
lines[0]['inventory_routing'] = {
|
||||
**(lines[0].get('inventory_routing') or {}),
|
||||
'suggestion_pending': True,
|
||||
'rule_suggestion': {'source_codes': ['DSV360_AWSDU'], 'routing_status': 'resolved'},
|
||||
}
|
||||
case.current_draft.lines_json = lines
|
||||
db.session.flush()
|
||||
version = int(case.current_draft.draft_version)
|
||||
|
||||
kept = keep_manual_inventory_routing(
|
||||
user_id=user.id, case_no=case.case_no, line_key=line_key,
|
||||
expected_draft_version=version, idempotency_key='keep-key-1',
|
||||
reason='keep planner decision',
|
||||
)
|
||||
db.session.commit()
|
||||
proj = kept['draft']['build_eligibility']['line_projections'][0]
|
||||
# 关键断言:有效候选仍为人工值,待确认建议已清除。
|
||||
assert proj['selection_mode'] == 'manual'
|
||||
assert proj['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
|
||||
assert proj.get('suggestion_pending') is False
|
||||
|
||||
|
||||
def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app):
|
||||
"""
|
||||
充足完整行可先行建单;同 PDF 第二波次不被精确重复检查阻断;同行不可重复入波次。
|
||||
|
||||
@@ -86,6 +86,18 @@ def test_text_normalizers_preserve_source_case_for_user_visible_values(normalize
|
||||
) == 'Inventec D4-A08AR12000002 USD'
|
||||
|
||||
|
||||
def test_date_normalizer_accepts_explicit_english_month_abbreviation():
|
||||
"""XFA datasets 与视觉样本均可将 07-Jul-2026 收敛为无歧义 ISO 日期。"""
|
||||
value = normalize_order_field_value(
|
||||
'07-Jul-2026',
|
||||
{'field_code': 'requested_receipt_date', 'value_type': 'date', 'normalizer_key': 'iso_date'},
|
||||
)
|
||||
|
||||
# 关键断言:英文月份缩写不是展示特例,正式 Schema date 值必须可供后续校验和比对。
|
||||
assert value.isoformat() == '2026-07-07'
|
||||
assert validate_order_field_value(value, {'value_type': 'date', 'validator_keys': ['iso_date']})
|
||||
|
||||
|
||||
def test_field_rules_accept_line_number_and_compute_effective_reservation():
|
||||
"""用户配置的项次可从原文写入;有效 Reservation 按行优先回退头,二者均可空。"""
|
||||
assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'}) == '00010'
|
||||
|
||||
@@ -14,6 +14,9 @@ import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.order_document_profile_pdf_automark_service import (
|
||||
_acroform_widget_candidates,
|
||||
_fuse_header_regions_with_column_geometry,
|
||||
enqueue_pdf_automark,
|
||||
execute_pdf_automark_job,
|
||||
)
|
||||
|
||||
@@ -21,6 +24,226 @@ from app.services.shipping_notice.order_document_profile_pdf_automark_service im
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_header_text_is_projected_onto_widget_column_geometry():
|
||||
"""表头文字与 Widget 列框融合后,画布必须得到可确认的每列表头框。"""
|
||||
geometry = {
|
||||
'table_region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .8},
|
||||
'subrow_layouts': [{'column_boundaries': [0, .2, .7, 1]}],
|
||||
'header_regions': [],
|
||||
}
|
||||
text = {
|
||||
'header_regions': [{
|
||||
'text': 'ITEM PARTS & DESCRIPTION QTY',
|
||||
'region': {'x0': .1, 'y0': .22, 'x1': .9, 'y1': .28},
|
||||
'fields': [
|
||||
{'text': 'ITEM', 'field_code': 'line_no', 'region': {'x0': .11, 'y0': .22, 'x1': .18, 'y1': .28}},
|
||||
{'text': 'PARTS & DESCRIPTION', 'field_code': 'part_number', 'region': {'x0': .29, 'y0': .22, 'x1': .63, 'y1': .28}},
|
||||
{'text': 'QTY', 'field_code': 'quantity', 'region': {'x0': .76, 'y0': .22, 'x1': .82, 'y1': .28}},
|
||||
],
|
||||
}],
|
||||
}
|
||||
|
||||
fused = _fuse_header_regions_with_column_geometry(
|
||||
geometry, geometry_source='acroform_widget_geometry',
|
||||
text_reconstructions=[('pdf_coordinate', text)],
|
||||
)
|
||||
|
||||
fields = fused['header_regions'][0]['fields']
|
||||
assert [(item['text'], item['field_code'], item['region']) for item in fields] == [
|
||||
('ITEM', 'line_no', {'x0': .1, 'y0': .22, 'x1': .26, 'y1': .28}),
|
||||
('PARTS & DESCRIPTION', 'part_number', {'x0': .26, 'y0': .22, 'x1': .66, 'y1': .28}),
|
||||
('QTY', 'quantity', {'x0': .66, 'y0': .22, 'x1': .9, 'y1': .28}),
|
||||
]
|
||||
assert all(item['evidence_sources'] == ['acroform_widget_geometry', 'pdf_coordinate'] for item in fields)
|
||||
assert fields[0]['observations'] == [{
|
||||
'source': 'pdf_coordinate', 'text': 'ITEM', 'field_code': 'line_no',
|
||||
'region': {'x0': .11, 'y0': .22, 'x1': .18, 'y1': .28},
|
||||
}]
|
||||
|
||||
|
||||
def test_header_geometry_keeps_unmapped_text_unbound():
|
||||
"""视觉文字没有唯一 Schema 映射时只补框,禁止按列位置猜字段编码。"""
|
||||
geometry = {
|
||||
'table_region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .8},
|
||||
'subrow_layouts': [{'column_boundaries': [0, .5, 1]}],
|
||||
'header_regions': [],
|
||||
}
|
||||
text = {'header_regions': [{
|
||||
'region': {'x0': 0, 'y0': .22, 'x1': 1, 'y1': .28},
|
||||
'fields': [{'text': 'UNRECOGNIZED', 'field_code': None, 'region': {'x0': .1, 'y0': .22, 'x1': .4, 'y1': .28}}],
|
||||
}]}
|
||||
|
||||
fused = _fuse_header_regions_with_column_geometry(
|
||||
geometry, geometry_source='opencv_geometry', text_reconstructions=[('ocr_coordinate', text)],
|
||||
)
|
||||
|
||||
assert fused['header_regions'][0]['fields'][0]['field_code'] is None
|
||||
|
||||
|
||||
def test_enqueue_automark_requires_frozen_annotation_layout(monkeypatch):
|
||||
"""关键断言:自动标注不能在无冻结 Layout 的样本上生成可接受候选。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
|
||||
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
|
||||
monkeypatch.setattr(service.db.session, 'get', lambda model, ident: None)
|
||||
monkeypatch.setattr(
|
||||
service, 'ShippingOrderDocumentProfileSample',
|
||||
SimpleNamespace(id=SimpleNamespace(asc=lambda: None), query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(first=lambda: None),
|
||||
),
|
||||
)),
|
||||
)
|
||||
with pytest.raises(Exception) as caught:
|
||||
enqueue_pdf_automark(12, document_id=77, table_id='table-1', schema_version_id=3, page_no=1, actor_id=1)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND'
|
||||
|
||||
|
||||
def test_enqueue_automark_rejects_annotation_when_current_layout_checksum_changed(monkeypatch):
|
||||
"""关键断言:Layout 版本未变但内容快照已替换时,不能继续生成旧候选 Job。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
|
||||
annotation = SimpleNamespace(table_id='table-1', layout_version_id=88, layout_payload_checksum='a' * 64)
|
||||
document = SimpleNamespace(
|
||||
id=77,
|
||||
current_layout_version_id=88,
|
||||
current_layout_version=SimpleNamespace(payload_checksum='b' * 64),
|
||||
)
|
||||
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
|
||||
monkeypatch.setattr(
|
||||
service, 'ShippingOrderDocumentProfileSample',
|
||||
SimpleNamespace(id=SimpleNamespace(asc=lambda: None), query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(first=lambda: annotation),
|
||||
),
|
||||
)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
service.db.session,
|
||||
'get',
|
||||
lambda model, _ident: document if model is service.ShippingOrderDocument else None,
|
||||
)
|
||||
monkeypatch.setattr(service, 'enqueue', lambda *_args, **_kwargs: 9001)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
enqueue_pdf_automark(12, document_id=77, table_id='table-1', schema_version_id=3, page_no=1, actor_id=1)
|
||||
|
||||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_execute_automark_rejects_job_after_document_layout_reparse(monkeypatch):
|
||||
"""关键断言:排队期间 Layout 重解析后,旧 Job 不得生成可被确认的视觉候选。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
|
||||
current_document = SimpleNamespace(id=77, current_layout_version_id=99)
|
||||
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
|
||||
monkeypatch.setattr(
|
||||
service.db.session,
|
||||
'get',
|
||||
lambda model, _ident: current_document if model is service.ShippingOrderDocument else None,
|
||||
)
|
||||
|
||||
with pytest.raises(service.PdfAutomarkError) as caught:
|
||||
execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
|
||||
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
|
||||
})
|
||||
|
||||
assert caught.value.error_code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE'
|
||||
|
||||
|
||||
def test_execute_automark_rejects_job_with_layout_checksum_mismatch(monkeypatch):
|
||||
"""关键断言:同一 Layout 版本但冻结快照 checksum 不一致时也必须失败关闭。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
|
||||
current_document = SimpleNamespace(
|
||||
id=77,
|
||||
current_layout_version_id=88,
|
||||
current_layout_version=SimpleNamespace(payload_checksum='b' * 64),
|
||||
)
|
||||
monkeypatch.setattr(service, '_profile', lambda _profile_id: profile)
|
||||
monkeypatch.setattr(
|
||||
service.db.session,
|
||||
'get',
|
||||
lambda model, _ident: current_document if model is service.ShippingOrderDocument else None,
|
||||
)
|
||||
|
||||
with pytest.raises(service.PdfAutomarkError) as caught:
|
||||
execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
|
||||
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
|
||||
})
|
||||
|
||||
assert caught.value.error_code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE'
|
||||
|
||||
|
||||
def test_automark_handler_persists_layout_stale_code_for_workbench_recovery(monkeypatch):
|
||||
"""关键断言:Worker 必须原样持久化 Layout 失效码,供统一画布提示重新标记。"""
|
||||
from app.jobs.handlers import shipping_pdf_automark as handler
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
job = SimpleNamespace(id=9001, attempts=1, payload_json={
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1',
|
||||
'layout_version_id': 88, 'layout_payload_checksum': 'a' * 64,
|
||||
})
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _job_id: job)
|
||||
monkeypatch.setattr(
|
||||
service,
|
||||
'execute_pdf_automark_job',
|
||||
lambda _payload: (_ for _ in ()).throw(service.PdfAutomarkError(
|
||||
'layout changed',
|
||||
error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE',
|
||||
)),
|
||||
)
|
||||
failed: dict[str, object] = {}
|
||||
monkeypatch.setattr(handler, 'fail_job', lambda *_args, **kwargs: failed.update(kwargs))
|
||||
|
||||
handler.run_shipping_pdf_automark(SimpleNamespace(), {'job_id': 9001})
|
||||
|
||||
assert failed['retryable'] is False
|
||||
assert failed['result'] == {
|
||||
'status': 'failed',
|
||||
'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_LAYOUT_STALE',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_opencv_reconstruction_projects_only_data_rows(monkeypatch):
|
||||
"""关键断言:冻结 Layout 的 header/summary 只能作证据,不能伪造成明细行。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
layout = {
|
||||
'layout_candidate': {
|
||||
'quality': {'issues': [{'code': 'native_pdf_cells_from_opencv_candidate'}]},
|
||||
'pages': [{
|
||||
'page_no': 1,
|
||||
'tables': [{
|
||||
'table_id': 'table-1',
|
||||
'normalized_bbox': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'rows': [
|
||||
{'row_index': 0, 'role': 'header', 'cells': [{'normalized_bbox': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .1}}]},
|
||||
{'row_index': 1, 'role': 'data', 'cells': [{'normalized_bbox': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .2}, 'text': 'A'}]},
|
||||
{'row_index': 2, 'role': 'summary', 'cells': [{'normalized_bbox': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'text': 'TOTAL'}]},
|
||||
],
|
||||
}],
|
||||
}],
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._document_layout',
|
||||
lambda _document: layout,
|
||||
)
|
||||
monkeypatch.setattr(service.db.session, 'get', lambda model, ident: object())
|
||||
result = service._layout_opencv_reconstruction(document_id=77, table_id='table-1')
|
||||
assert result is not None
|
||||
assert [item['row_offset'] for item in result['subrow_layouts']] == [0]
|
||||
assert result['subrow_layouts'][0]['source_row_index'] == 1
|
||||
|
||||
|
||||
def test_coordinate_pdf_automark_retries_with_ocr_and_returns_candidates():
|
||||
"""关键断言:普通 PDF 在坐标不足时由统一 Job 触发 OCR 后仍返回 candidates[]。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
@@ -48,26 +271,539 @@ def test_coordinate_pdf_automark_retries_with_ocr_and_returns_candidates():
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1', 'schema_version_id': 3, 'page_no': 1,
|
||||
})
|
||||
|
||||
assert result['kind'] == 'coordinate_regions'
|
||||
assert [item['candidate_kind'] for item in result['candidates']] == ['coordinate_reconstruction', 'order_fields']
|
||||
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(document_id=77, table_id='table-1', actor_id=None)
|
||||
assert result['kind'] == 'field_binding_candidates'
|
||||
assert [item['candidate_kind'] for item in result['candidates']] == ['table_reconstruction']
|
||||
assert result['diagnostics']['coordinate_reconstruction'] == reconstruction
|
||||
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(
|
||||
document_id=77, table_id='table-1', actor_id=None, force_ocr=True,
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_pdf_automark_delegates_multi_source_evidence_to_same_contract():
|
||||
"""关键断言:XFA 由 Profile 能力自动识别,不要求客户端传类型且仍返回 candidates[]。"""
|
||||
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={'template_mode': 'xfa_dataset'}, status='draft')
|
||||
xfa = MagicMock()
|
||||
xfa.execute_xfa_ocr_automark_job.return_value = {
|
||||
'status': 'success', 'suggestions': [{'suggestion_id': 's-1'}], 'error_code': None,
|
||||
def test_xfa_pdf_automark_reuses_the_shared_visual_executor():
|
||||
"""关键断言:XFA 只在确认后的正式值映射不同,自动标记仍走共享视觉执行器。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
|
||||
status='draft',
|
||||
)
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
|
||||
coordinate.suggest_order_field_layouts.return_value = {
|
||||
'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}],
|
||||
}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch.dict('sys.modules', {
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service': xfa,
|
||||
}):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77})
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'xfa-main-table'})
|
||||
|
||||
assert result['kind'] == 'visual_binding'
|
||||
assert result['candidates'] == [{'suggestion_id': 's-1'}]
|
||||
assert result['diagnostics']['evidence'] == ['pdfium', 'acroform_widget', 'ocr', 'xfa_datasets']
|
||||
assert result['kind'] == 'field_binding_candidates'
|
||||
candidate = next(item for item in result['candidates'] if item['candidate_kind'] == 'field_binding')
|
||||
assert candidate['candidate_kind'] == 'field_binding'
|
||||
assert 'value_binding' not in candidate['binding']
|
||||
assert result['diagnostics']['coordinate_reconstruction'] == {'subrow_layouts': []}
|
||||
assert coordinate.suggest_coordinate_reconstruction.call_count == 2
|
||||
|
||||
|
||||
def test_xfa_pdf_automark_keeps_header_candidates_when_visual_rows_need_review():
|
||||
"""关键断言:视觉行重建为空不能丢弃已识别的抬头框,结果必须留在 needs_review。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
|
||||
status='draft',
|
||||
)
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [
|
||||
ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID'),
|
||||
ValidationError('OCR rows unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'),
|
||||
]
|
||||
coordinate.suggest_order_field_layouts.return_value = {
|
||||
'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}],
|
||||
}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'xfa-main-table', 'page_no': 1,
|
||||
})
|
||||
|
||||
assert result['status'] == 'needs_review'
|
||||
assert result['candidates'][0]['binding']['field_code'] == 'customer_po_no'
|
||||
assert result['candidates'][0]['needs_review'] is True
|
||||
assert result['diagnostics']['row_reconstruction']['error_code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'
|
||||
|
||||
|
||||
def test_xfa_pdf_automark_retries_invalid_native_rows_with_forced_ocr():
|
||||
"""关键断言:部分 native glyph 无法成行时,Job 必须强制 OCR 后再重建一次。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
|
||||
status='draft',
|
||||
)
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [
|
||||
ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID'),
|
||||
{'subrow_layouts': [{'row_offset': 0}], 'header_regions': []},
|
||||
]
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'page_no': 1, 'source': 'ocr_coordinate',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}]}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({
|
||||
'profile_id': 12, 'document_id': 77, 'table_id': 'xfa-main-table', 'page_no': 1,
|
||||
})
|
||||
|
||||
# 自动标注只产生待确认的视觉候选;即使 OCR 已补全行框,也不能把 Job 结果标为可发布成功。
|
||||
assert result['status'] == 'needs_review'
|
||||
assert result['diagnostics']['coordinate_reconstruction']['subrow_layouts'] == [{'row_offset': 0}]
|
||||
# OCR 重建后的候选不能声称已有 native 佐证;来源必须忠实反映本次实际证据。
|
||||
assert result['candidates'][0]['evidence_sources'] == ['ocr_coordinate']
|
||||
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(
|
||||
document_id=77, table_id='xfa-main-table', actor_id=None, force_ocr=True,
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_pdf_automark_requires_the_frozen_visual_main_table():
|
||||
"""关键断言:XFA 也不能绕过统一视觉主表契约执行自动标注。"""
|
||||
profile = SimpleNamespace(
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'main_table_id': 'xfa-main-table'},
|
||||
status='draft',
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
|
||||
return_value=profile,
|
||||
):
|
||||
with pytest.raises(Exception) as caught:
|
||||
execute_pdf_automark_job({'profile_id': 12, 'document_id': 77})
|
||||
|
||||
assert getattr(caught.value, 'error_code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_coordinate_pdf_automark_returns_the_same_field_binding_candidate_contract():
|
||||
"""关键断言:普通 PDF 也以 field_binding_candidates 返回,前端不按 PDF 类型分支保存。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
|
||||
coordinate.suggest_order_field_layouts.return_value = {
|
||||
'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}],
|
||||
}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1', 'page_no': 1})
|
||||
|
||||
assert result['kind'] == 'field_binding_candidates'
|
||||
candidate = next(item for item in result['candidates'] if item['candidate_kind'] == 'field_binding')
|
||||
assert candidate['candidate_kind'] == 'field_binding'
|
||||
assert candidate['binding']['field_id'] == 'f-po'
|
||||
# 自动标记只提出视觉框,最终值源由字段映射确认阶段选择。
|
||||
assert 'value_binding' not in candidate['binding']
|
||||
|
||||
|
||||
def test_automark_does_not_project_ambiguous_or_unavailable_fields_as_empty_boxes():
|
||||
"""关键断言:未得到唯一值框的字段只能留在诊断,不能成为画布可确认候选。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
candidates = service._visual_binding_candidates({
|
||||
'order_field_candidates': [
|
||||
{'field_id': 'ambiguous', 'field_code': 'customer_po_no', 'status': 'ambiguous'},
|
||||
{'field_id': 'unavailable', 'field_code': 'order_date', 'status': 'unavailable'},
|
||||
{
|
||||
'field_id': 'suggested', 'field_code': 'currency', 'status': 'suggested',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
},
|
||||
],
|
||||
}, page_no=1)
|
||||
|
||||
assert [item['binding']['field_code'] for item in candidates] == ['currency']
|
||||
assert candidates[0]['binding']['visual_binding']['normalized_bbox'] == {
|
||||
'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4,
|
||||
}
|
||||
|
||||
|
||||
def test_automark_diagnostics_do_not_claim_unobserved_ocr_or_native_evidence():
|
||||
"""关键断言:诊断只能列出实际候选来源,不能把可用的回退能力写成已取到的证据。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
|
||||
coordinate.suggest_order_field_layouts.return_value = {
|
||||
'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'source': 'pdf_coordinate',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}],
|
||||
}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
assert result['candidates'][0]['evidence_sources'] == ['pdf_coordinate']
|
||||
assert result['diagnostics']['evidence_sources'] == ['pdf_coordinate']
|
||||
|
||||
|
||||
def test_automark_keeps_native_and_ocr_table_reconstruction_candidates_in_parallel():
|
||||
"""关键断言:原生行重建成功也必须保留同页 OCR 的独立候选,不以先成功者屏蔽另一证据。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
native = {'subrow_layouts': [{'row_offset': 0}], 'header_regions': []}
|
||||
ocr = {'subrow_layouts': [{'row_offset': 0}, {'row_offset': 1}], 'header_regions': []}
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [native, ocr]
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
table_candidates = [item for item in result['candidates'] if item['candidate_kind'] == 'table_reconstruction']
|
||||
assert [item['evidence_sources'] for item in table_candidates] == [['pdf_coordinate'], ['ocr_coordinate']]
|
||||
assert result['diagnostics']['coordinate_reconstruction'] == native
|
||||
assert result['diagnostics']['conflicts'] == [{
|
||||
'code': 'table_reconstruction_source_conflict',
|
||||
'sources': ['pdf_coordinate', 'ocr_coordinate'],
|
||||
}]
|
||||
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(
|
||||
document_id=77, table_id='table-1', actor_id=None, force_ocr=True,
|
||||
)
|
||||
|
||||
|
||||
def test_automark_marks_consistent_multi_evidence_candidates_as_needing_review():
|
||||
"""关键断言:多路视觉证据结构一致也只代表可复核候选,不能绕过人工确认。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
reconstruction = {'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}]}
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.side_effect = [reconstruction, reconstruction]
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}]}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
assert result['status'] == 'needs_review'
|
||||
assert result['diagnostics']['conflicts'] == []
|
||||
assert all(item['needs_review'] is True for item in result['candidates'])
|
||||
|
||||
|
||||
def test_automark_exposes_only_the_unified_pdf_job_type():
|
||||
"""关键断言:XFA 不保留独立自动标记 Job 类型。"""
|
||||
from app.jobs.types import JobType
|
||||
|
||||
assert JobType.SHIPPING_PDF_AUTOMARK.value == 'shipping_pdf_automark'
|
||||
assert not hasattr(JobType, 'SHIPPING_XFA_OCR_AUTOMARK')
|
||||
|
||||
|
||||
def test_automark_exposes_acroform_widget_as_independent_visual_candidate():
|
||||
"""关键断言:Widget 只补充定位证据,不能替代 datasets 正式值绑定。"""
|
||||
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': []}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'page_no': 1, 'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
}]}
|
||||
widget = SimpleNamespace(widget_id='wgt-1', short_name='customer_po_number', page_no=1,
|
||||
normalized_bbox={'x0': .4, 'y0': .2, 'x1': .7, 'y1': .3})
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._acroform_widget_candidates',
|
||||
return_value=[{
|
||||
'candidate_id': 'widget-wgt-1', 'candidate_kind': 'field_binding',
|
||||
'binding': {'field_code': 'customer_po_number', 'visual_binding': {'source': 'acroform_widget'}},
|
||||
'evidence_sources': ['acroform_widget'], 'needs_review': True,
|
||||
}],
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
widget_candidate = next(item for item in result['candidates'] if item['evidence_sources'] == ['acroform_widget'])
|
||||
assert widget_candidate['needs_review'] is True
|
||||
assert 'value_binding' not in widget_candidate['binding']
|
||||
|
||||
|
||||
def test_automark_keeps_unmatched_acroform_widget_as_unbound_visual_candidate(monkeypatch):
|
||||
"""Widget 技术名未匹配 Schema 时仍可供人工框选,禁止自动猜业务字段。"""
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
|
||||
|
||||
document = SimpleNamespace(asset_id=11)
|
||||
asset = SimpleNamespace(id=11)
|
||||
widget = SimpleNamespace(
|
||||
widget_id='wgt-ebeln', short_name='EBELN', page_no=1,
|
||||
normalized_bbox={'x0': .4, 'y0': .2, 'x1': .7, 'y1': .3},
|
||||
)
|
||||
monkeypatch.setattr(service.db.session, 'get', lambda _model, ident: document if ident == 77 else asset)
|
||||
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_acroform.read_acroform_widgets',
|
||||
lambda _bytes: [widget],
|
||||
)
|
||||
|
||||
candidates = _acroform_widget_candidates(
|
||||
document_id=77,
|
||||
fields={'order_field_candidates': []},
|
||||
actor_id=1,
|
||||
)
|
||||
|
||||
# 关键断言:只携带 Widget 几何和技术名,field_code 为空且不存在正式 value_binding。
|
||||
assert candidates == [
|
||||
{
|
||||
'candidate_id': 'widget-unbound-wgt-ebeln',
|
||||
'candidate_kind': 'field_binding',
|
||||
'binding': {
|
||||
'binding_id': 'widget-unbound-wgt-ebeln',
|
||||
'field_id': '',
|
||||
'field_code': '',
|
||||
'display_name': 'EBELN',
|
||||
'scope': 'header',
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': .4, 'y0': .2, 'x1': .7, 'y1': .3},
|
||||
'source': 'acroform_widget',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
'region_kind': 'field',
|
||||
'widget_id': 'wgt-ebeln',
|
||||
'widget_short_name': 'EBELN',
|
||||
},
|
||||
},
|
||||
'evidence_sources': ['acroform_widget'],
|
||||
'needs_review': True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_automark_keeps_existing_opencv_layout_geometry_as_parallel_table_candidate():
|
||||
"""关键断言:Layout 阶段已验收的 OpenCV 几何进入统一候选,但仍需人工确认。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {
|
||||
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}], 'header_regions': [],
|
||||
}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
opencv = {'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .5, 1]}], 'header_regions': []}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._layout_opencv_reconstruction',
|
||||
return_value=opencv,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
opencv_candidates = [item for item in result['candidates'] if item['evidence_sources'] == ['opencv_geometry']]
|
||||
assert len(opencv_candidates) == 1
|
||||
assert opencv_candidates[0]['needs_review'] is True
|
||||
assert result['diagnostics']['evidence_sources'] == ['opencv_geometry', 'pdf_coordinate']
|
||||
|
||||
|
||||
def test_automark_keeps_xfa_widget_geometry_as_parallel_table_candidate():
|
||||
"""关键断言:动态 XFA 未绘制明细值时,Widget 几何可形成待确认行框但不能自动采值。"""
|
||||
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {
|
||||
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}], 'header_regions': [],
|
||||
}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
widget_geometry = {
|
||||
'subrow_layouts': [{
|
||||
'row_offset': 0, 'column_boundaries': [0, .2, .5, 1],
|
||||
'column_samples': [],
|
||||
}],
|
||||
'header_regions': [], 'status': 'needs_review',
|
||||
}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._xfa_widget_geometry_reconstruction',
|
||||
return_value=widget_geometry,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
widget_candidate = next(item for item in result['candidates'] if item['evidence_sources'] == ['acroform_widget_geometry'])
|
||||
assert widget_candidate['needs_review'] is True
|
||||
assert widget_candidate['payload']['subrow_layouts'][0]['column_samples'] == []
|
||||
|
||||
|
||||
def test_automark_enriches_widget_table_candidate_with_coordinate_header_text():
|
||||
"""XFA 行框来自 Widget 时仍须把独立坐标表头补入同一候选,供画布生成 header_field。"""
|
||||
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {
|
||||
'subrow_layouts': [], 'header_regions': [],
|
||||
}
|
||||
coordinate.suggest_coordinate_header_reconstruction.return_value = {
|
||||
'header_regions': [{
|
||||
'region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .2},
|
||||
'fields': [{'text': 'ITEM', 'field_code': 'line_no', 'region': {'x0': .11, 'y0': .15, 'x1': .18, 'y1': .2}}],
|
||||
}],
|
||||
}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
widget_geometry = {
|
||||
'table_region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .8},
|
||||
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .25, 1]}],
|
||||
'header_regions': [], 'status': 'needs_review',
|
||||
}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_header_reconstruction',
|
||||
coordinate.suggest_coordinate_header_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._xfa_widget_geometry_reconstruction',
|
||||
return_value=widget_geometry,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
widget_candidate = next(item for item in result['candidates'] if item['evidence_sources'] == ['acroform_widget_geometry'])
|
||||
field = widget_candidate['payload']['header_regions'][0]['fields'][0]
|
||||
assert field['text'] == 'ITEM'
|
||||
assert field['field_code'] == 'line_no'
|
||||
assert field['region'] == {'x0': .1, 'y0': .15, 'x1': .3, 'y1': .2}
|
||||
assert field['evidence_sources'] == ['acroform_widget_geometry', 'pdf_coordinate']
|
||||
|
||||
|
||||
def test_automark_marks_opencv_and_native_structure_conflict_for_review():
|
||||
"""关键断言:OpenCV 与 native 几何不一致时保留双方并记录冲突。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {
|
||||
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, 1]}], 'header_regions': [],
|
||||
}
|
||||
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_pdf_automark_service._layout_opencv_reconstruction',
|
||||
return_value={'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .5, 1]}], 'header_regions': []},
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
assert result['status'] == 'needs_review'
|
||||
assert result['diagnostics']['conflicts'] == [{
|
||||
'code': 'table_reconstruction_source_conflict',
|
||||
'sources': ['pdf_coordinate', 'opencv_geometry'],
|
||||
}]
|
||||
|
||||
|
||||
def test_automark_keeps_native_and_ocr_field_candidates_in_parallel():
|
||||
"""关键断言:字段框与表格行一样保留 native/OCR 两路,不以 native 候选屏蔽 OCR。"""
|
||||
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
|
||||
coordinate = MagicMock()
|
||||
coordinate.suggest_coordinate_reconstruction.return_value = {'subrow_layouts': [], 'header_regions': []}
|
||||
native_fields = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'absolute_value_region': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
|
||||
'source': 'pdf_coordinate',
|
||||
}]}
|
||||
ocr_fields = {'order_field_candidates': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'absolute_value_region': {'x0': .12, 'y0': .2, 'x1': .32, 'y1': .4},
|
||||
'source': 'ocr_coordinate',
|
||||
}]}
|
||||
coordinate.suggest_order_field_layouts.side_effect = [native_fields, ocr_fields]
|
||||
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_coordinate_reconstruction',
|
||||
coordinate.suggest_coordinate_reconstruction,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.suggest_order_field_layouts',
|
||||
coordinate.suggest_order_field_layouts,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_service.generate_ocr_coordinate_evidence',
|
||||
coordinate.generate_ocr_coordinate_evidence,
|
||||
):
|
||||
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77, 'table_id': 'table-1'})
|
||||
|
||||
fields = [item for item in result['candidates'] if item['candidate_kind'] == 'field_binding']
|
||||
assert [item['evidence_sources'] for item in fields] == [['pdf_coordinate'], ['ocr_coordinate']]
|
||||
assert result['diagnostics']['field_conflicts'] == [{
|
||||
'code': 'field_binding_source_conflict',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'sources': ['pdf_coordinate', 'ocr_coordinate'],
|
||||
}]
|
||||
@@ -15,6 +15,7 @@ from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_CODE_SET,
|
||||
PROCESS_GATE_DEFINITIONS,
|
||||
PROCESS_GATE_REASON_OWNING_GATE,
|
||||
action_belongs_to_gate,
|
||||
assert_process_gate_contract_integrity,
|
||||
action_presentation,
|
||||
field_quality_may_block,
|
||||
@@ -58,6 +59,27 @@ def test_inventory_source_routing_primary_retry_action():
|
||||
status='blocked_retryable',
|
||||
)
|
||||
assert action == 'retry_with_latest_rules'
|
||||
assert primary_next_action_for_gate(
|
||||
gate_code='inventory_source_routing', status='blocked_manual',
|
||||
) == 'retry_with_latest_rules'
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='inventory_source_routing', action_code='open_inventory_source_review',
|
||||
) is False
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='inventory_field_mapping', action_code='confirm_inventory_field_mapping',
|
||||
) is False
|
||||
|
||||
|
||||
def test_gate_action_contract_rejects_inventory_reroute_for_excel_gate():
|
||||
"""库存源重路由动作绝不能被 Excel Gate 自动入队。"""
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='excel_readiness',
|
||||
action_code='retry_with_latest_rules',
|
||||
) is False
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='excel_readiness',
|
||||
action_code='recheck_excel_readiness',
|
||||
) is True
|
||||
|
||||
|
||||
def test_inventory_sufficiency_actions_keep_business_specific_labels():
|
||||
@@ -67,6 +89,7 @@ def test_inventory_sufficiency_actions_keep_business_specific_labels():
|
||||
'label_key': 'workspace.shippingNotice.processGate.actionCodes.open_shortage_review',
|
||||
'kind': 'current_gate',
|
||||
'dispatch': 'navigation',
|
||||
'ui_handler': 'shortage_review',
|
||||
}
|
||||
assert action_presentation('retry_inventory_from_matching') == {
|
||||
'code': 'retry_inventory_from_matching',
|
||||
@@ -76,6 +99,70 @@ def test_inventory_sufficiency_actions_keep_business_specific_labels():
|
||||
}
|
||||
|
||||
|
||||
def test_fulfillment_action_presentation_declares_lifecycle_surface():
|
||||
"""动作位置必须继承当前 Gate,而非维护 action_code 到位置的映射。"""
|
||||
assert action_presentation(
|
||||
'regenerate_excel_artifact', gate_code='artifact_generation',
|
||||
)['target_surface'] == 'fulfillment_prep'
|
||||
assert action_presentation(
|
||||
'retry_freight_upload_rpa', gate_code='freight_upload_rpa',
|
||||
)['target_surface'] == 'upload_complete'
|
||||
assert action_presentation(
|
||||
'regenerate_manual_upload_todo', gate_code='manual_upload_handoff',
|
||||
)['target_surface'] == 'upload_complete'
|
||||
assert action_presentation(
|
||||
'mark_manual_uploaded', gate_code='manual_upload_handoff',
|
||||
)['target_surface'] == 'upload_complete'
|
||||
|
||||
|
||||
def test_manual_upload_handoff_authorizes_excel_regeneration_at_artifact_anchor():
|
||||
"""已到人工上传交接时,Excel 重生仍须由当前 Gate 合法授权并回到产物位置。"""
|
||||
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
|
||||
|
||||
assert action_belongs_to_gate(
|
||||
gate_code='manual_upload_handoff',
|
||||
action_code='regenerate_excel_artifact',
|
||||
) is True
|
||||
plan = recovery_plan_for_action(
|
||||
current_gate='manual_upload_handoff',
|
||||
action_code='regenerate_excel_artifact',
|
||||
)
|
||||
assert plan['ui_placement'] == {
|
||||
'target_surface': 'fulfillment_prep',
|
||||
'target_anchor': 'excel_artifact',
|
||||
}
|
||||
|
||||
|
||||
def test_gate_action_presentation_declares_ui_dispatch_without_frontend_action_code_inference():
|
||||
"""非 mutation 动作必须由合同明确其页面宿主能力。"""
|
||||
assert action_presentation('mark_manual_uploaded') == {
|
||||
'code': 'mark_manual_uploaded',
|
||||
'label_key': 'workspace.shippingNotice.processGate.actionCodes.mark_manual_uploaded',
|
||||
'kind': 'current_gate',
|
||||
'dispatch': 'dialog',
|
||||
'ui_handler': 'manual_upload_evidence',
|
||||
}
|
||||
assert action_presentation('confirm_customer') == {
|
||||
'code': 'confirm_customer',
|
||||
'label_key': 'workspace.shippingNotice.processGate.actionCodes.confirm_customer',
|
||||
'kind': 'current_gate',
|
||||
'dispatch': 'navigation',
|
||||
'ui_handler': 'customer_resolution',
|
||||
}
|
||||
|
||||
|
||||
def test_every_gate_declares_a_surface_and_anchor_for_its_actions():
|
||||
"""所有 Gate 的动作位置必须在 Gate 定义处声明,避免前端或动作码映射猜测。"""
|
||||
for gate in PROCESS_GATE_DEFINITIONS:
|
||||
placement = gate['ui_placement']
|
||||
for action in (gate.get('default_next_actions') or {}).values():
|
||||
if action:
|
||||
presentation = action_presentation(action, gate_code=gate['gate_code'])
|
||||
assert presentation is not None
|
||||
assert presentation['target_surface'] == placement['target_surface']
|
||||
assert presentation['target_anchor'] == placement['target_anchor']
|
||||
|
||||
|
||||
def test_process_gate_reason_ownership_is_unique():
|
||||
"""
|
||||
每个阻断原因码恰好映射一个 owning_gate,覆盖率 100%。
|
||||
@@ -240,6 +327,63 @@ def test_formal_inventory_matching_uses_only_executable_retries(app, monkeypatch
|
||||
]
|
||||
|
||||
|
||||
def test_inventory_shortage_with_active_snapshot_projects_rematch_and_rpa_refresh(app, tmp_path):
|
||||
"""库存不足时,已确认的活动 Excel 必须可重匹配;重新获取库存才是第二入口。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
inventory_path = tmp_path / 'active-inventory.xlsx'
|
||||
inventory_path.write_bytes(b'confirmed inventory')
|
||||
task = ShippingNotice(
|
||||
task_no='SN-SUFFICIENCY-ACTIVE-SNAPSHOT',
|
||||
inventory_lines_json=[{'part_number': 'P-1', 'available_qty': 2}],
|
||||
)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-SUFFICIENCY-ACTIVE-SNAPSHOT',
|
||||
storage_path=str(inventory_path),
|
||||
snapshot_status='ready',
|
||||
mapping_confirmed=True,
|
||||
inventory_lines_json=[{'part_number': 'P-1', 'available_qty': 2}],
|
||||
line_count=1,
|
||||
)
|
||||
db.session.add_all([task, inventory_file])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingTaskInventoryLink(
|
||||
task_id=int(task.id), inventory_file_id=int(inventory_file.id), is_active=True,
|
||||
))
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='EXE-SUFFICIENCY-ACTIVE-SNAPSHOT', task_id=int(task.id), status='blocked',
|
||||
current_gate_code='inventory_sufficiency', lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGate(
|
||||
execution_id=int(execution.id), gate_code='inventory_sufficiency', sequence_no=16,
|
||||
status='blocked_manual', evaluation_version=1,
|
||||
blocking_reason_code='inventory_insufficient', next_action_code='open_shortage_review',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
summary = project_user_gate_summary(execution)
|
||||
|
||||
# 有效 Excel 是匹配的输入事实;缺口只阻断履约决定,不能迫使用户再次抓取文件。
|
||||
assert summary['next_action_code'] == 'retry_inventory_matching'
|
||||
assert summary['allowed_actions'] == [
|
||||
'retry_inventory_matching',
|
||||
'retry_inventory_preparation',
|
||||
]
|
||||
assert [item['action_code'] for item in summary['recovery_targets']] == [
|
||||
'retry_inventory_preparation',
|
||||
]
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_sanitized_failure_detail_for_any_gate(app, monkeypatch):
|
||||
"""所有 Gate 均应把当前 Attempt 的脱敏失败详情投影给用户,而非只显示泛化原因。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -310,15 +454,15 @@ def test_user_gate_summary_repairs_stale_rpa_action_for_gate19(app, monkeypatch)
|
||||
assert summary['owner_type'] == 'human'
|
||||
|
||||
|
||||
def test_inventory_preparation_keeps_controlled_upload_as_a_secondary_gate_action(app, monkeypatch):
|
||||
"""库存准备以重试为主动作,受控上传仅保留给 Gate 工作台。"""
|
||||
def test_inventory_preparation_exposes_only_rpa_retry(app, monkeypatch):
|
||||
"""库存准备不再提供库存文件上传旁路,仅允许重试 RPA。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-INVENTORY-1', status='blocked',
|
||||
current_gate_code='inventory_preparation',
|
||||
primary_next_action_code='upload_inventory_file',
|
||||
primary_next_action_code='retry_inventory_preparation',
|
||||
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -326,13 +470,13 @@ def test_inventory_preparation_keeps_controlled_upload_as_a_secondary_gate_actio
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-INVENTORY-1', 'status': 'blocked',
|
||||
'primary_next_action_code': 'upload_inventory_file',
|
||||
'primary_next_action_code': 'retry_inventory_preparation',
|
||||
'responsible_party': 'worker', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
'next_action_code': 'upload_inventory_file', 'evaluation_version': 3,
|
||||
'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -341,14 +485,11 @@ def test_inventory_preparation_keeps_controlled_upload_as_a_secondary_gate_actio
|
||||
|
||||
assert summary['next_action_code'] == 'retry_inventory_preparation'
|
||||
assert summary['primary_action']['code'] == 'retry_inventory_preparation'
|
||||
assert summary['allowed_actions'] == [
|
||||
'retry_inventory_preparation',
|
||||
'upload_inventory_file',
|
||||
]
|
||||
assert summary['allowed_actions'] == ['retry_inventory_preparation']
|
||||
|
||||
|
||||
def test_user_gate_summary_exposes_manual_gate_evidence_confirmation(app, monkeypatch):
|
||||
"""Gate 20 只下发受控凭据登记,不把 RPA 重试伪装为人工上传确认。"""
|
||||
def test_user_gate_summary_exposes_manual_gate_evidence_and_rpa_retry(app, monkeypatch):
|
||||
"""Gate 20 保持凭据登记主动作,并显式下发可选 RPA 重试。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
@@ -376,7 +517,10 @@ def test_user_gate_summary_exposes_manual_gate_evidence_confirmation(app, monkey
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
assert summary['next_action_code'] == 'mark_manual_uploaded'
|
||||
assert summary['allowed_actions'] == ['mark_manual_uploaded']
|
||||
assert summary['allowed_actions'] == [
|
||||
'mark_manual_uploaded',
|
||||
'retry_freight_upload_rpa',
|
||||
]
|
||||
assert summary['owner_type'] == 'human'
|
||||
|
||||
|
||||
@@ -410,38 +554,81 @@ def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action(
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['next_action_code'] == 'mark_manual_uploaded'
|
||||
assert summary['allowed_actions'] == ['mark_manual_uploaded']
|
||||
assert summary['allowed_actions'] == [
|
||||
'mark_manual_uploaded',
|
||||
'retry_freight_upload_rpa',
|
||||
]
|
||||
assert summary['primary_action']['target_surface'] == 'upload_complete'
|
||||
assert summary['primary_action']['target_anchor'] == 'manual_upload'
|
||||
|
||||
|
||||
def test_inventory_source_gate_summary_does_not_expose_line_decision_side_actions(app, monkeypatch):
|
||||
"""规则建议和保留人工决定只属于订单复核明细行,不能泄漏到 Gate 卡。"""
|
||||
def test_manual_upload_handoff_projects_excel_recovery_at_artifact_anchor(app, monkeypatch):
|
||||
"""跨 Gate Excel 恢复必须采用 RecoveryPlan 的位置,不能继承 Gate 20 的上传位置。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-ROUTING', status='blocked',
|
||||
current_gate_code='inventory_source_routing', primary_next_action_code='open_inventory_source_review',
|
||||
id=1, execution_no='EXE-MANUAL-EXCEL', status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
primary_next_action_code='regenerate_manual_upload_todo',
|
||||
responsible_party='owner', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-MANUAL-EXCEL', 'status': 'blocked',
|
||||
'primary_next_action_code': 'regenerate_manual_upload_todo',
|
||||
'responsible_party': 'owner', 'active_recovery_plans': [], 'gates': [],
|
||||
'recovery_targets': [{'action_code': 'regenerate_excel_artifact'}],
|
||||
'current_gate': {
|
||||
'gate_code': 'manual_upload_handoff', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'manual_upload_pending',
|
||||
'next_action_code': 'regenerate_manual_upload_todo', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(projection, '_excel_regeneration_allowed', lambda **_: True)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
regeneration = next(
|
||||
item for item in summary['action_presentation']
|
||||
if item['code'] == 'regenerate_excel_artifact'
|
||||
)
|
||||
assert regeneration['target_surface'] == 'fulfillment_prep'
|
||||
assert regeneration['target_anchor'] == 'excel_artifact'
|
||||
|
||||
|
||||
def test_inventory_source_gate_summary_exposes_no_manual_selection_action(app, monkeypatch):
|
||||
"""库存源路由只允许自动重算,Gate 卡不得暴露人工选源或确认。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_projection as projection
|
||||
|
||||
execution = SimpleNamespace(
|
||||
id=1, execution_no='EXE-ROUTING', status='blocked',
|
||||
current_gate_code='inventory_source_routing', primary_next_action_code='retry_with_latest_rules',
|
||||
responsible_party='system', lock_version=1, review_case_id=None, task_id=99,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
projection,
|
||||
'serialize_process_execution',
|
||||
lambda _execution, include_diagnostics=False: {
|
||||
'execution_no': 'EXE-ROUTING', 'status': 'blocked',
|
||||
'primary_next_action_code': 'open_inventory_source_review',
|
||||
'responsible_party': 'owner', 'recovery_targets': [],
|
||||
'primary_next_action_code': 'retry_with_latest_rules',
|
||||
'responsible_party': 'system', 'recovery_targets': [],
|
||||
'active_recovery_plans': [], 'gates': [],
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_source_routing', 'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'no_inventory_source_candidates',
|
||||
'next_action_code': 'open_inventory_source_review', 'evaluation_version': 3,
|
||||
'next_action_code': 'retry_with_latest_rules', 'evaluation_version': 3,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
summary = projection.project_user_gate_summary(execution)
|
||||
|
||||
assert summary['allowed_actions'] == ['open_inventory_source_review']
|
||||
assert summary['allowed_actions'] == []
|
||||
|
||||
|
||||
def test_process_gate_dependency_integrity_and_excel_only_scope():
|
||||
|
||||
@@ -20,6 +20,7 @@ from __future__ import annotations
|
||||
|
||||
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
|
||||
@@ -195,9 +196,9 @@ def test_ensure_execution_for_task_ignores_superseded_execution(app):
|
||||
|
||||
|
||||
|
||||
def test_auto_progress_does_not_queue_manual_inventory_retry(gate_execution, monkeypatch):
|
||||
def test_auto_progress_queues_initial_inventory_rpa_once(gate_execution, monkeypatch):
|
||||
|
||||
"""自动推进不得把用户恢复动作 retry_inventory_preparation 重新触发为 RPA。"""
|
||||
"""首次进入库存准备没有任何 RPA Attempt 时,自动推进必须投递一次 trigger。"""
|
||||
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
@@ -223,7 +224,11 @@ def test_auto_progress_does_not_queue_manual_inventory_retry(gate_execution, mon
|
||||
monkeypatch.setattr(
|
||||
process_gate_service,
|
||||
'queue_gate_attempt',
|
||||
lambda **kwargs: queued.append(kwargs),
|
||||
lambda **kwargs: (queued.append(kwargs), SimpleNamespace(id=1))[1],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
process_gate_service._enqueue_auto_progress_after_gate_pass(
|
||||
@@ -231,6 +236,37 @@ def test_auto_progress_does_not_queue_manual_inventory_retry(gate_execution, mon
|
||||
gate=gate,
|
||||
)
|
||||
|
||||
assert len(queued) == 1
|
||||
assert queued[0]['gate_code'] == 'inventory_preparation'
|
||||
|
||||
|
||||
def test_auto_progress_does_not_requeue_failed_inventory_rpa(gate_execution, monkeypatch):
|
||||
"""已有终态 Attempt 后,库存 RPA 只允许人工重试,不能被自动无限重放。"""
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
|
||||
for prior_gate in ShippingProcessGate.query.filter(
|
||||
ShippingProcessGate.execution_id == int(gate_execution.id),
|
||||
ShippingProcessGate.sequence_no < 13,
|
||||
).all():
|
||||
prior_gate.status = 'passed'
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
task = db.session.get(ShippingNotice, int(gate_execution.task_id))
|
||||
db.session.add(ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task.task_no, source_code='TEST', attempt_no=1, source_run_no='PSR-FAILED',
|
||||
status='failed', trigger_file_path='C:/trigger.json', execution_phase='trigger_written',
|
||||
))
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
queued: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(process_gate_service, 'queue_gate_attempt', lambda **kwargs: queued.append(kwargs))
|
||||
|
||||
process_gate_service._enqueue_auto_progress_after_gate_pass(execution=gate_execution, gate=gate)
|
||||
|
||||
assert queued == []
|
||||
|
||||
|
||||
@@ -386,6 +422,41 @@ def test_upstream_invalidation_only_targets_dependents(gate_execution):
|
||||
assert doc.status == 'passed'
|
||||
|
||||
|
||||
def test_invalidation_uses_target_gate_retry_action_not_inventory_reroute_fallback(gate_execution):
|
||||
"""下游 Excel Gate 失效后只能保留自身的重检动作,不能落入库存源重路由兜底。"""
|
||||
excel = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(gate_execution.id), gate_code='excel_readiness',
|
||||
).one()
|
||||
excel.status = 'passed'
|
||||
db.session.flush()
|
||||
|
||||
invalidate_downstream_gates(
|
||||
execution=gate_execution,
|
||||
change_type='inventory_file_changed',
|
||||
)
|
||||
|
||||
assert excel.status == 'invalidated'
|
||||
assert excel.next_action_code == 'recheck_excel_readiness'
|
||||
|
||||
|
||||
def test_queue_gate_attempt_rejects_action_owned_by_another_gate(gate_execution):
|
||||
"""任何调用方都不能把库存源路由动作创建到 Excel Gate Attempt。"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
queue_gate_attempt(
|
||||
execution_no=gate_execution.execution_no,
|
||||
gate_code='excel_readiness',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
idempotency_key='wrong-action-excel-gate',
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
)
|
||||
|
||||
assert getattr(exc.value, 'code', None) == 'SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED'
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -587,7 +658,7 @@ def test_idempotent_queue_replays_same_attempt(gate_execution):
|
||||
|
||||
idempotency_key='same-key-ten-times',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -607,7 +678,7 @@ def test_idempotent_queue_replays_same_attempt(gate_execution):
|
||||
|
||||
idempotency_key='same-key-ten-times',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -643,7 +714,7 @@ def test_idempotent_key_conflicts_across_gate_and_action(gate_execution, app):
|
||||
|
||||
idempotency_key='cross-context-key',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -663,7 +734,7 @@ def test_idempotent_key_conflicts_across_gate_and_action(gate_execution, app):
|
||||
|
||||
idempotency_key='cross-context-key',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -759,7 +830,7 @@ def test_idempotent_key_conflicts_across_execution(app):
|
||||
|
||||
idempotency_key='cross-execution-key',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
@@ -779,7 +850,7 @@ def test_idempotent_key_conflicts_across_execution(app):
|
||||
|
||||
idempotency_key='cross-execution-key',
|
||||
|
||||
input_snapshot={'action_code': 'retry_with_latest_rules'},
|
||||
input_snapshot={'action_code': 'retry_layout_parsing'},
|
||||
|
||||
)
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import UniqueConstraint
|
||||
|
||||
from app.models import (
|
||||
@@ -33,6 +34,104 @@ def test_recovery_plan_has_idempotent_business_identity():
|
||||
assert 'invalidation_plan_json' in ShippingProcessRecoveryPlan.__table__.c
|
||||
|
||||
|
||||
def test_excel_regeneration_invalidation_preserves_inventory_facts(app):
|
||||
"""仅重生 Excel 只替代旧产物和未完成上传,不能重算库存或抹掉短缺放行事实。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryVerification,
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingProcessExecution,
|
||||
ShippingReservation,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only
|
||||
|
||||
task = ShippingNotice(task_no='SN-EXCEL-REGEN-ONLY', export_file_path='old.xlsx', export_file_name='old.xlsx')
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='REGEN-ONLY', display_name='Regen only', version=1, status='published',
|
||||
storage_bucket='test', storage_key='test/template.xlsx', original_filename='template.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='REGEN-ONLY', display_name='Regen only', version=1,
|
||||
status='published', file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = ShippingOrderSchema(schema_code='REGEN-ONLY', display_name='Regen only')
|
||||
db.session.add_all([task, template, profile, schema])
|
||||
db.session.flush()
|
||||
schema_version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={},
|
||||
)
|
||||
db.session.add(schema_version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=schema_version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='SPE-EXCEL-REGEN-ONLY', task_id=task.id, status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
)
|
||||
db.session.add_all([extraction, execution])
|
||||
db.session.flush()
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no='EXP-EXCEL-REGEN-ONLY', task_id=task.id, template_id=template.id,
|
||||
order_schema_version_id=schema_version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
|
||||
file_path='old.xlsx', file_name='old.xlsx', file_checksum='d' * 64, file_size=1,
|
||||
status='ready',
|
||||
)
|
||||
reservation = ShippingReservation(
|
||||
task_id=task.id, snapshot_line_id=1, reservation_id='RSV-EXCEL-REGEN-ONLY',
|
||||
part_number='PN-1', po_number_normalized='PO-1', required_qty=1,
|
||||
status='artifact_reserved', current_artifact_id=None,
|
||||
)
|
||||
verification = ShippingInventoryVerification(task_id=task.id, status='completed', result_json={})
|
||||
match = ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, line_key='line-1', reservation_id='RSV-EXCEL-REGEN-ONLY',
|
||||
part_number='PN-1', match_result='matched', inventory_status='ready', is_current=True,
|
||||
)
|
||||
db.session.add_all([artifact, reservation, verification, match])
|
||||
db.session.flush()
|
||||
reservation.current_artifact_id = artifact.id
|
||||
upload = ShippingUploadAttempt(
|
||||
artifact_id=artifact.id, attempt_no=1, mode='manual',
|
||||
idempotency_key='excel-regen-only', status='pending',
|
||||
)
|
||||
db.session.add(upload)
|
||||
db.session.flush()
|
||||
|
||||
result = invalidate_excel_regeneration_only(
|
||||
execution=execution,
|
||||
attempt_id=17,
|
||||
actor_id=9,
|
||||
)
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(artifact)
|
||||
db.session.refresh(upload)
|
||||
db.session.refresh(reservation)
|
||||
db.session.refresh(verification)
|
||||
db.session.refresh(match)
|
||||
assert result['artifacts'] == [artifact.id]
|
||||
assert result['uploads'] == [upload.id]
|
||||
assert artifact.status == 'superseded'
|
||||
assert upload.status == 'failed'
|
||||
assert upload.invalidated_at is not None
|
||||
assert reservation.status == 'available'
|
||||
assert reservation.current_artifact_id is None
|
||||
assert task.export_file_path is None
|
||||
assert task.export_file_name is None
|
||||
assert verification.status == 'completed'
|
||||
assert match.is_current is True
|
||||
|
||||
|
||||
def test_inventory_preparation_is_task_round_with_per_source_uniqueness():
|
||||
"""准备轮次和逐源 Attempt 均必须保留不可混淆的唯一范围。"""
|
||||
assert 'uq_shipping_inventory_preparation_task_attempt' in _unique_names(ShippingInventoryPreparationAttempt)
|
||||
@@ -482,8 +581,8 @@ def test_batch_callback_inherits_authenticated_top_level_schema_version():
|
||||
assert merged['task_no'] == 'SN-1'
|
||||
|
||||
|
||||
def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
"""RPA 已耗尽时自动轮询必须终态化,Gate 才能退出系统处理中。"""
|
||||
def test_inventory_rpa_exhausted_history_is_retryable_not_waiting_external(app):
|
||||
"""历史 RPA 耗尽必须退出系统处理中,且不得封锁用户重试入口。"""
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
@@ -528,7 +627,7 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
|
||||
ShippingProcessGateAttempt.gate_id == gate.id,
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
).count() == 0
|
||||
assert gate.status == 'blocked_manual'
|
||||
assert gate.status == 'blocked_retryable'
|
||||
assert gate.blocking_reason_code == 'inventory_rpa_exhausted'
|
||||
db.session.refresh(execution)
|
||||
# Gate 已进入可人工恢复的 blocked_manual;Execution 仍保持 active,
|
||||
@@ -610,6 +709,83 @@ def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
|
||||
assert attempt.job_id is None
|
||||
|
||||
|
||||
def test_inventory_preparation_poll_keeps_callback_timeout_without_reinvoking_rpa(app, monkeypatch):
|
||||
"""已失败的准备轮次被旧 poll 领取时,必须保留超时并禁止再次调 RPA。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryPreparationAttempt,
|
||||
ShippingNotice,
|
||||
ShippingProcessGate,
|
||||
ShippingTaskEvent,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_job_service import claim_and_run_gate_attempt
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
|
||||
task = ShippingNotice(task_no='SN-POLL-KEEPS-RPA-TIMEOUT', pending_human_reason='inv_unavail')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=task.id,
|
||||
start_gate_code='inventory_preparation',
|
||||
)
|
||||
task.active_process_execution_id = execution.id
|
||||
preparation = ShippingInventoryPreparationAttempt(
|
||||
task_id=task.id,
|
||||
execution_id=execution.id,
|
||||
attempt_no=1,
|
||||
status='failed',
|
||||
input_snapshot_json={},
|
||||
output_snapshot_json={},
|
||||
)
|
||||
db.session.add_all([
|
||||
preparation,
|
||||
ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type='inventory_rpa_failed',
|
||||
detail_json={'error': 'Crane scheduled report not ready for download within 300000ms'},
|
||||
),
|
||||
])
|
||||
db.session.flush()
|
||||
sync_fulfillment_gates_from_task(execution=execution)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=execution.id,
|
||||
gate_code='inventory_preparation',
|
||||
).one()
|
||||
assert gate.status == 'blocked_retryable'
|
||||
assert gate.blocking_reason_code == 'inventory_rpa_timeout'
|
||||
|
||||
rpa_calls = {'count': 0}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
lambda _payload: rpa_calls.__setitem__('count', rpa_calls['count'] + 1),
|
||||
)
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='external-wait-poll',
|
||||
idempotency_key='poll-keeps-rpa-timeout-1',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {'poll': True}},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = claim_and_run_gate_attempt(attempt_id=attempt.id, worker_id='timeout-poll-worker')
|
||||
|
||||
db.session.refresh(gate)
|
||||
db.session.refresh(execution)
|
||||
assert result['skipped'] is False
|
||||
assert rpa_calls['count'] == 0
|
||||
assert gate.status == 'blocked_retryable'
|
||||
assert gate.blocking_reason_code == 'inventory_rpa_timeout'
|
||||
assert gate.next_action_code == 'retry_inventory_preparation'
|
||||
assert execution.status == 'blocked'
|
||||
|
||||
|
||||
def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch):
|
||||
"""正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。"""
|
||||
from app import db
|
||||
@@ -941,6 +1117,146 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan():
|
||||
assert plan.completed_at is not None
|
||||
|
||||
|
||||
def test_excel_regeneration_completion_preserves_manual_upload_gate():
|
||||
"""跨 Gate Excel 重生完成后,当前 Gate 20 必须继续等待人工上传且计划可关闭。"""
|
||||
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
|
||||
|
||||
class Plan:
|
||||
status = 'queued'
|
||||
action_code = 'regenerate_excel_artifact'
|
||||
resume_after_gate = 'manual_upload_handoff'
|
||||
started_at = None
|
||||
completed_at = None
|
||||
failure_code = None
|
||||
failure_detail_json = None
|
||||
|
||||
plan = Plan()
|
||||
complete_recovery_plan_for_attempt(
|
||||
plan=plan,
|
||||
outcome='blocked_manual',
|
||||
business_result_code='manual_upload_pending',
|
||||
)
|
||||
|
||||
assert plan.status == 'succeeded'
|
||||
assert plan.completed_at is not None
|
||||
|
||||
|
||||
def test_manual_upload_excel_regeneration_returns_to_manual_handoff(monkeypatch):
|
||||
"""Gate 20 触发 Excel 重生后,执行器必须作废旧产物并保持人工上传阻断。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||||
|
||||
invalidated = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.recovery_invalidation_service.invalidate_excel_regeneration_only',
|
||||
lambda **kwargs: invalidated.update(kwargs) or {'artifacts': [10], 'uploads': [11]},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda _payload: {'status': 'ok'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **_: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._task_payload',
|
||||
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
|
||||
)
|
||||
|
||||
outcome = _handle_regenerate_excel(
|
||||
execution=SimpleNamespace(execution_no='SPE-EXCEL-HANDOFF', task_id=1),
|
||||
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
|
||||
payload={'attempt_id': 3, 'actor_user_id': 9},
|
||||
)
|
||||
|
||||
assert invalidated['attempt_id'] == 3
|
||||
assert outcome['outcome'] == 'blocked_manual'
|
||||
assert outcome['blocking_reason_code'] == 'manual_upload_pending'
|
||||
assert outcome['output_snapshot']['invalidation']['artifacts'] == [10]
|
||||
|
||||
|
||||
def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch):
|
||||
"""Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
|
||||
|
||||
synced = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
|
||||
lambda _payload: {'status': 'failed', 'message': 'template unavailable'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **kwargs: synced.append(kwargs),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._task_payload',
|
||||
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
|
||||
)
|
||||
|
||||
execution = SimpleNamespace(execution_no='SPE-EXCEL-FAILED', task_id=1)
|
||||
outcome = _handle_regenerate_excel(
|
||||
execution=execution,
|
||||
gate=SimpleNamespace(gate_code='artifact_generation'),
|
||||
payload={'actor_user_id': 9},
|
||||
)
|
||||
|
||||
assert outcome['outcome'] == 'blocked_retryable'
|
||||
assert outcome['blocking_reason_code'] == 'artifact_generation_failed'
|
||||
assert synced == [{
|
||||
'execution': execution,
|
||||
'actor_type': 'system',
|
||||
'actor_id': 9,
|
||||
}]
|
||||
|
||||
|
||||
def test_executor_accepts_bound_cross_gate_excel_recovery_plan(monkeypatch):
|
||||
"""已绑定的 Gate 20 Excel RecoveryPlan 必须能通过 Worker 归属复核。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_executor._handle_regenerate_excel',
|
||||
lambda **_: {'outcome': 'blocked_manual'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
executor.db.session,
|
||||
'get',
|
||||
lambda _model, _id: SimpleNamespace(
|
||||
id=81,
|
||||
execution_id=1,
|
||||
current_gate='manual_upload_handoff',
|
||||
action_code='regenerate_excel_artifact',
|
||||
target_gate='artifact_generation',
|
||||
resume_after_gate='manual_upload_handoff',
|
||||
),
|
||||
)
|
||||
result = executor._dispatch_action(
|
||||
execution=SimpleNamespace(id=1),
|
||||
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
|
||||
action_code='regenerate_excel_artifact',
|
||||
payload={'recovery_plan_id': 81},
|
||||
)
|
||||
|
||||
assert result['outcome'] == 'blocked_manual'
|
||||
|
||||
|
||||
def test_executor_rejects_unbound_cross_gate_excel_recovery_plan():
|
||||
"""Gate 20 的跨阶段 Excel 动作没有已绑定计划时必须 fail-closed。"""
|
||||
from types import SimpleNamespace
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.process_gate_executor import _dispatch_action
|
||||
|
||||
with pytest.raises(ValidationError, match='Recovery plan is required'):
|
||||
_dispatch_action(
|
||||
execution=SimpleNamespace(id=1),
|
||||
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
|
||||
action_code='regenerate_excel_artifact',
|
||||
payload={},
|
||||
)
|
||||
|
||||
|
||||
def test_inventory_rematch_shortage_is_business_result_not_technical_failure(monkeypatch):
|
||||
"""库存 14、缺口 16 时,匹配 Attempt 成功收口到缺口复核。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -973,8 +1289,10 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
payload={'actor_user_id': 1},
|
||||
)
|
||||
|
||||
assert result['outcome'] == 'blocked_manual'
|
||||
assert result['blocking_reason_code'] == 'inventory_shortage_review_required'
|
||||
# 匹配动作已成功完成;库存缺口由 inventory_sufficiency Gate 单独阻断,
|
||||
# 不能把业务缺口回写成 inventory_matching 的技术失败。
|
||||
assert result['outcome'] == 'passed'
|
||||
assert 'blocking_reason_code' not in result
|
||||
assert result['effective_result_json']['shortage']['lines'][0] == {
|
||||
'available_qty': 14,
|
||||
'shortage_qty': 16,
|
||||
@@ -984,7 +1302,7 @@ def test_inventory_rematch_shortage_is_business_result_not_technical_failure(mon
|
||||
def test_field_mapping_recovery_does_not_create_preparation_round(monkeypatch):
|
||||
"""字段映射恢复必须停留在 mapping handler,不得误建库存准备轮次。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_executor import _dispatch_action
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
called = {'preparation': 0, 'matching': 0}
|
||||
monkeypatch.setattr(
|
||||
@@ -995,9 +1313,20 @@ def test_field_mapping_recovery_does_not_create_preparation_round(monkeypatch):
|
||||
'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_from_field_mapping',
|
||||
lambda **_: {'outcome': 'blocked_manual'},
|
||||
)
|
||||
result = _dispatch_action(
|
||||
execution=object(), gate=SimpleNamespace(gate_code='inventory_matching'),
|
||||
action_code='retry_inventory_from_field_mapping', payload={},
|
||||
monkeypatch.setattr(
|
||||
executor.db.session,
|
||||
'get',
|
||||
lambda _model, _id: SimpleNamespace(
|
||||
execution_id=1,
|
||||
current_gate='inventory_matching',
|
||||
action_code='retry_inventory_from_field_mapping',
|
||||
target_gate='inventory_field_mapping',
|
||||
resume_after_gate='inventory_matching',
|
||||
),
|
||||
)
|
||||
result = executor._dispatch_action(
|
||||
execution=SimpleNamespace(id=1), gate=SimpleNamespace(gate_code='inventory_matching'),
|
||||
action_code='retry_inventory_from_field_mapping', payload={'recovery_plan_id': 7},
|
||||
)
|
||||
assert result['outcome'] == 'blocked_manual'
|
||||
assert called['preparation'] == 0
|
||||
|
||||
@@ -77,7 +77,7 @@ def test_projection_fact_read_failure_is_fail_closed():
|
||||
'available_actions': ['retry_inventory_preparation'],
|
||||
})
|
||||
assert payload['status'] == 'waiting_human'
|
||||
assert payload['retryable'] is False
|
||||
assert 'retryable' not in payload
|
||||
assert payload['primary_action'] is None
|
||||
assert payload['available_actions'] == []
|
||||
assert payload['blocking_reason']['code'] == 'projection_data_inconsistent'
|
||||
@@ -289,6 +289,29 @@ def test_derive_available_actions_failed_adds_retry():
|
||||
assert 'retry' in actions
|
||||
|
||||
|
||||
def test_retryable_projection_uses_technical_failure_reason_mapping():
|
||||
"""重试兜底原因必须生成可展示的技术失败 i18n 键,而不能抛 KeyError。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'processing',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_retryable',
|
||||
'next_action_code': 'retry_inventory_preparation',
|
||||
'blocking_reason_code': 'technical_failure_present',
|
||||
},
|
||||
'available_actions': ['retry'],
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'retryable'
|
||||
assert payload['blocking_reason'] == {
|
||||
'code': 'technical_failure_present',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.reasons.technical_failure_present',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_inventory_snapshot_missing_projects_retryable_inventory_action():
|
||||
"""库存快照缺失属于可恢复技术阻断,用户态必须保留重试动作。"""
|
||||
payload = apply_user_projection_fields({
|
||||
@@ -309,11 +332,11 @@ def test_inventory_snapshot_missing_projects_retryable_inventory_action():
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'retryable'
|
||||
assert payload['retryable'] is True
|
||||
assert 'retryable' not in payload
|
||||
# 主动作必须保留 Gate 原始码,前端才能提交到正确的库存准备执行器。
|
||||
assert payload['primary_action'] == {
|
||||
'code': 'retry_inventory_preparation',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
'parameters': {},
|
||||
}
|
||||
|
||||
@@ -338,6 +361,28 @@ def test_formal_blocked_gate_overrides_stale_preparation_running_state():
|
||||
assert payload['primary_action']['code'] == 'retry_inventory_preparation'
|
||||
|
||||
|
||||
def test_retryable_projection_exposes_technical_failure_reason_without_retry_decision():
|
||||
"""AutoProgress 超时未生成 Retry Decision 时,工作项读取仍必须返回可翻译原因。"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'blocked',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'technical_failure_present',
|
||||
},
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'retryable'
|
||||
assert payload['blocking_reason'] == {
|
||||
'code': 'technical_failure_present',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.reasons.technical_failure_present',
|
||||
'details': {},
|
||||
}
|
||||
|
||||
|
||||
def test_formal_inventory_matching_retry_projects_business_i18n_key():
|
||||
"""正式 OT 的库存重试不得让页面回退展示内部 action code。"""
|
||||
payload = apply_user_projection_fields({
|
||||
@@ -356,7 +401,7 @@ def test_formal_inventory_matching_retry_projects_business_i18n_key():
|
||||
|
||||
assert payload['primary_action'] == {
|
||||
'code': 'retry_inventory_matching',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_matching',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching',
|
||||
'parameters': {},
|
||||
}
|
||||
|
||||
@@ -424,7 +469,7 @@ def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action():
|
||||
assert payload['user_status'] == 'waiting_human'
|
||||
assert payload['primary_action'] == {
|
||||
'code': 'retry_inventory_preparation',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
'i18n_key': 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation',
|
||||
'parameters': {},
|
||||
}
|
||||
assert payload['available_actions'] == ['retry_inventory_preparation']
|
||||
@@ -477,7 +522,7 @@ def test_apply_user_projection_fields_fail_closes_inconsistent_projection():
|
||||
})
|
||||
|
||||
assert payload['user_status'] == 'waiting_human'
|
||||
assert payload['retryable'] is False
|
||||
assert 'retryable' not in payload
|
||||
assert payload['primary_action'] is None
|
||||
assert payload['available_actions'] == []
|
||||
assert payload['blocking_reason']['code'] == 'projection_data_inconsistent'
|
||||
|
||||
@@ -17,6 +17,7 @@ from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import event
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
@@ -24,6 +25,7 @@ from app.models import (
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderProcessingUnit,
|
||||
ShippingOrderSubmission,
|
||||
User,
|
||||
)
|
||||
@@ -38,6 +40,8 @@ from app.services.shipping_notice.shipping_processing_projection import (
|
||||
_batch_four_stage_nodes,
|
||||
_batch_ui_state_from_items,
|
||||
_conversation_processing_from_work_items,
|
||||
_display_work_items_from_current_files,
|
||||
_eml_aggregate_document_children,
|
||||
_processing_ui_state_from_item,
|
||||
_project_order_task_work_item,
|
||||
map_run_status_to_processing_status,
|
||||
@@ -275,6 +279,85 @@ def test_processing_ui_state_empty_review_case_does_not_expose_lifecycle_entries
|
||||
assert state['lifecycle_entries'] == []
|
||||
|
||||
|
||||
def test_rematerialization_keeps_document_referenced_by_processing_unit(app) -> None:
|
||||
"""冻结 Run 引用的旧附件不可被阶段二清理,避免外键失败中断候选生成。"""
|
||||
from app.models import FileAsset
|
||||
from app.services.shipping_notice.document_candidate_persist import persist_documents_and_candidates
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REFERENCED-STALE-DOCUMENT')
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
plan = ensure_order_extraction_plan(run)
|
||||
db.session.commit()
|
||||
assert ShippingOrderProcessingUnit.query.filter_by(
|
||||
plan_id=plan.id,
|
||||
document_id=document.id,
|
||||
).one_or_none() is not None
|
||||
|
||||
parent_asset = db.session.get(FileAsset, intake.asset_id)
|
||||
assert parent_asset is not None
|
||||
result = NoticeIntakeResult(
|
||||
filename='replacement.eml', source_type='email', source_file_type='message/rfc822',
|
||||
text='', warnings=[], content_hash='replacement-hash', file_size=1, status='accepted',
|
||||
saved_path=None, meta={'file_type': 'eml', 'email': {'body_text': ''}, 'attachments': []},
|
||||
)
|
||||
|
||||
persist_documents_and_candidates(
|
||||
intake=intake,
|
||||
parent_asset=parent_asset,
|
||||
result=result,
|
||||
run_duplicate_detection=False,
|
||||
create_candidates=False,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:下一轮物化未包含该附件时,仍须保留冻结计划所引用的历史 Document。
|
||||
assert db.session.get(ShippingOrderDocument, document.id) is not None
|
||||
|
||||
|
||||
def test_failed_run_overrides_stale_unit_review_stage_for_eml_leaf(app) -> None:
|
||||
"""Run 已失败时不能把遗留 review_required Unit 投影为订单复核。"""
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='FAILED-RUN-LEAF')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
plan = ensure_order_extraction_plan(run)
|
||||
unit = plan.units[0]
|
||||
unit.status = 'review_required'
|
||||
unit.retry_status = 'review_required'
|
||||
run.status = 'failed'
|
||||
run.phase = 'failed'
|
||||
db.session.commit()
|
||||
|
||||
leaves = _eml_aggregate_document_children(
|
||||
intake=intake,
|
||||
order_task_children=[],
|
||||
unit_by_document_id={document.id: unit},
|
||||
)
|
||||
|
||||
assert leaves[0]['user_status'] == 'failed'
|
||||
assert leaves[0]['user_stage'] == 'document_parsing'
|
||||
assert leaves[0]['primary_action'] is None
|
||||
|
||||
|
||||
def test_intake_candidate_context_ignores_superseded_candidate(app) -> None:
|
||||
"""历史 Candidate 只能审计,不能重新打开当前文件的生命周期入口。"""
|
||||
with app.app_context():
|
||||
@@ -937,16 +1020,103 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -
|
||||
|
||||
assert leaf['run_no'] == run.run_no
|
||||
assert leaf['case_no'] == review_case.case_no
|
||||
assert leaf['ui_state']['primary_action']['code'] == 'open_order_review'
|
||||
# Case 已授权 reparse 时,批次叶子必须原样投影为直接重解析入口。
|
||||
assert leaf['ui_state']['primary_action']['code'] == 'reparse'
|
||||
# 空 Candidate Case 的入口只打开接收解析处置面,不能伪装为订单复核。
|
||||
assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
|
||||
assert leaf['ui_state']['primary_action']['target_lifecycle_stage'] == 'intake_parse'
|
||||
# 无 Candidate 的人工解析 Case 仍可进入解析复核,但不得伪装成订单生命周期。
|
||||
assert leaf['ui_state']['primary_action'].get('target_lifecycle_stage') is None
|
||||
# 无 Candidate 的人工解析 Case 只开放接收解析阶段,不能伪装为订单复核。
|
||||
assert leaf['source_summary']['candidate_count'] == 0
|
||||
assert leaf['ui_state']['lifecycle_entries'] == []
|
||||
assert leaf['ui_state']['lifecycle_entries'] == [
|
||||
{'code': 'intake_parse', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'order_review', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
|
||||
]
|
||||
assert leaf['intake_parse_authorized'] is True
|
||||
|
||||
|
||||
def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None:
|
||||
"""同一 Run 的失败 PDF 只能影响自身;两个待复核 PDF 仍必须保留后端裁决的入口。"""
|
||||
with app.app_context():
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
|
||||
|
||||
user, agent, session, intake, first_document = _seed_run_input(
|
||||
suffix='EML-SIBLING-OUTCOME-ISOLATION',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
second_document = ShippingOrderDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='second.pdf',
|
||||
filename='second.pdf', content_hash='8' * 64, classification='order_notice',
|
||||
parse_status='parsed', extracted_text='PO SECOND',
|
||||
)
|
||||
third_document = ShippingOrderDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='third.pdf',
|
||||
filename='third.pdf', content_hash='9' * 64, classification='order_notice',
|
||||
parse_status='parsed', extracted_text='PO THIRD',
|
||||
)
|
||||
db.session.add_all([second_document, third_document])
|
||||
db.session.flush()
|
||||
run.input_snapshot_json['intakes'][0]['documents'].extend([
|
||||
{
|
||||
'document_id': second_document.id, 'document_type': 'attachment',
|
||||
'attachment_key': second_document.attachment_key,
|
||||
'filename': second_document.filename, 'content_hash': second_document.content_hash,
|
||||
'extracted_text': second_document.extracted_text,
|
||||
},
|
||||
{
|
||||
'document_id': third_document.id, 'document_type': 'attachment',
|
||||
'attachment_key': third_document.attachment_key,
|
||||
'filename': third_document.filename, 'content_hash': third_document.content_hash,
|
||||
'extracted_text': third_document.extracted_text,
|
||||
},
|
||||
])
|
||||
flag_modified(run, 'input_snapshot_json')
|
||||
first_unit = run.extraction_plan.units[0]
|
||||
second_unit = ShippingOrderProcessingUnit(
|
||||
plan_id=run.extraction_plan.id, intake_id=intake.id, document_id=second_document.id,
|
||||
position=1, unit_type='document_extraction', document_type='attachment',
|
||||
content_hash=second_document.content_hash, status='review_required',
|
||||
)
|
||||
failed_unit = ShippingOrderProcessingUnit(
|
||||
plan_id=run.extraction_plan.id, intake_id=intake.id, document_id=third_document.id,
|
||||
position=2, unit_type='document_extraction', document_type='attachment',
|
||||
content_hash=third_document.content_hash, status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
)
|
||||
db.session.add_all([second_unit, failed_unit])
|
||||
db.session.flush()
|
||||
first_unit.status = 'review_required'
|
||||
first_unit.reason_code = 'business_table_not_found'
|
||||
second_unit.reason_code = 'business_table_not_found'
|
||||
ensure_review_case_for_unit(run=run, unit=first_unit)
|
||||
ensure_review_case_for_unit(run=run, unit=second_unit)
|
||||
run.status = 'partially_completed'
|
||||
run.phase = 'review_required'
|
||||
db.session.commit()
|
||||
|
||||
item = project_intake_work_item(intake)
|
||||
leaves = {int(child['source_summary']['document_id']): child for child in item['aggregate_children']}
|
||||
|
||||
for document_id in (int(first_document.id), int(second_document.id)):
|
||||
leaf = leaves[document_id]
|
||||
assert leaf['user_status'] == 'waiting_human'
|
||||
assert leaf['user_stage'] == 'order_review'
|
||||
assert leaf['blocking_reason']['code'] == 'business_table_not_found'
|
||||
assert leaf['ui_state']['primary_action'] is not None, leaf
|
||||
assert leaf['ui_state']['primary_action']['code'] == 'open_order_review'
|
||||
failed_leaf = leaves[int(third_document.id)]
|
||||
assert failed_leaf['user_status'] == 'failed'
|
||||
assert failed_leaf['user_stage'] == 'document_parsing'
|
||||
assert failed_leaf['blocking_reason']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE'
|
||||
assert failed_leaf['ui_state']['primary_action']['code'] == 'retry_order_extraction'
|
||||
assert item['aggregate_summary']['needs_action'] == 2
|
||||
assert item['aggregate_summary']['failed'] == 1
|
||||
|
||||
|
||||
def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document(app) -> None:
|
||||
"""有效 Candidate 只为其主 PDF 开放订单生命周期,兄弟 PDF 必须保持关闭。"""
|
||||
with app.app_context():
|
||||
@@ -1512,6 +1682,52 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship
|
||||
assert item['source_summary']['filename'] == document.filename
|
||||
|
||||
|
||||
def test_order_task_projection_uses_stream_current_case_for_gate_and_deep_link(app, shipping_user):
|
||||
"""同一文件旧开放 Case 残留时,OT Gate 与深链只能取 Stream 当前 Case。"""
|
||||
del shipping_user
|
||||
with app.app_context():
|
||||
from app.models import ShippingOrderCandidate, ShippingOrderTask
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_disposition_service import reparse_case_document
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.review_stream_service import activate_review_case
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='OT-STREAM-CURRENT')
|
||||
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'OCAND-STREAM-{uuid.uuid4().hex[:8]}', intake_id=intake.id,
|
||||
primary_document_id=document.id, candidate_key='ot-stream-current',
|
||||
order_extraction_run_id=source.id, is_current_version=True,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
original = ensure_run_review_cases(run=source)[0]
|
||||
transition_order_extraction_run(source, target_status='processing')
|
||||
transition_order_extraction_run(source, target_status='review_required', result={})
|
||||
replacement_run, _ = reparse_case_document(
|
||||
user_id=user.id, case_no=original.case_no, reason='rule_updated',
|
||||
)
|
||||
ensure_order_extraction_plan(replacement_run)
|
||||
for unit in replacement_run.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
replacement = ensure_run_review_cases(run=replacement_run)[0]
|
||||
activate_review_case(case=replacement, trigger='document_reparse_succeeded')
|
||||
original.status = 'draft'
|
||||
|
||||
task = ShippingOrderTask.query.filter_by(candidate_id=int(candidate.id)).one()
|
||||
task.status = 'waiting_review'
|
||||
task.stage = 'waiting_review'
|
||||
db.session.commit()
|
||||
|
||||
item = _project_order_task_work_item(source, order_task=task)
|
||||
|
||||
assert item['case_no'] == replacement.case_no
|
||||
assert item['case_no'] != original.case_no
|
||||
|
||||
|
||||
def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shipping_user):
|
||||
"""候选已生成且 Case 未终态时,EML 叶子必须进入订单复核,不能回退为接收解析。"""
|
||||
del shipping_user
|
||||
@@ -1534,6 +1750,19 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
assert unit.status == 'candidate_ready'
|
||||
assert case.status == 'unreviewed'
|
||||
from app.models import ShippingOrderReviewStream
|
||||
stream = ShippingOrderReviewStream.query.filter_by(current_case_id=int(case.id)).one()
|
||||
assert int(stream.document_id) == int(case.document_id) == int(unit.document_id)
|
||||
assert (
|
||||
ShippingOrderReviewCase.query.join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
).filter(
|
||||
ShippingOrderReviewStream.document_id == int(document.id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready', 'confirming')),
|
||||
).one().id
|
||||
== case.id
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = _aggregate_eml_order_task_work_items([{
|
||||
@@ -1546,6 +1775,7 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi
|
||||
}])
|
||||
leaf = result[0]['aggregate_children'][0]
|
||||
|
||||
assert leaf['source_summary']['document_id'] == document.id
|
||||
assert result[0]['user_status'] == 'waiting_human'
|
||||
assert result[0]['user_stage'] == 'order_review'
|
||||
assert leaf['case_no'] == case.case_no
|
||||
@@ -1555,6 +1785,37 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi
|
||||
assert 'edit_draft' in leaf['available_actions']
|
||||
|
||||
|
||||
def test_eml_aggregate_keeps_run_authorized_batch_reparse_action(app, shipping_user):
|
||||
"""EML 父卡不能因叶子只有 Case 动作而遗漏按原 PDF 的批次重解析入口。"""
|
||||
del shipping_user
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='EML-BATCH-REPARSE-ACTION')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
ensure_run_review_cases(run=run)
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
aggregate = _aggregate_eml_order_task_work_items([{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-EML-BATCH-REPARSE',
|
||||
'source_type': 'eml', 'intake_no': intake.intake_no, 'run_no': run.run_no,
|
||||
'status': 'review_required', 'stage': 'order_review', 'user_status': 'waiting_human',
|
||||
'user_stage': 'order_review', 'user_group': 'waiting_human', 'last_activity_at': '',
|
||||
# 模拟截图对应的叶子只提供 Case 工作台入口,而非批次动作。
|
||||
'available_actions': ['open_order_review'], 'facts': {'upload_state': 'not_created'},
|
||||
'source_summary': {'document_id': document.id, 'filename': 'mail.eml'},
|
||||
}])[0]
|
||||
|
||||
assert 'reparse_batch' in aggregate['available_actions']
|
||||
displayed = _display_work_items_from_current_files([aggregate])
|
||||
assert 'reparse_batch' in displayed[0]['available_actions']
|
||||
|
||||
|
||||
def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_user):
|
||||
"""
|
||||
BE-07:投影 stage/status 以 OT 已写入值为准,禁止读路径用 Notice 覆盖。
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
收料 RPA 持久化模型契约测试。
|
||||
|
||||
用途:锁定收料配置、单元运行、归档文件和企微投递的独立存储边界。
|
||||
依赖:测试应用数据库、货代库存站点和排程模型。
|
||||
逻辑:验证数据库唯一约束;收料文件只能从收料单元运行派生,不能混入库存文件表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
|
||||
def _receipt_config(source_id: int):
|
||||
"""构造一条 DBS 收料配置,供一对一约束测试复用。"""
|
||||
from app.models import ShippingReceiptReportConfig
|
||||
|
||||
return ShippingReceiptReportConfig(
|
||||
inventory_source_id=source_id,
|
||||
enabled=True,
|
||||
report_path_json={
|
||||
'program_group': 'Bison',
|
||||
'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound',
|
||||
'report_name': 'Receipt Detail',
|
||||
},
|
||||
query_parameters_json=[],
|
||||
warehouse_ids_json=['AWSDU'],
|
||||
)
|
||||
|
||||
|
||||
def test_receipt_config_is_unique_per_inventory_source(app):
|
||||
"""同一库存站点至多维护一条独立收料配置。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add_all([_receipt_config(source.id), _receipt_config(source.id)])
|
||||
|
||||
# 关键断言:站点与收料配置是一对一,避免排程重复导出。
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_receipt_unit_callback_and_file_sha_are_idempotent(app):
|
||||
"""回调、站点仓库单元及归档文件 SHA 均由独立表去重。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun,
|
||||
ScheduleTask,
|
||||
ShippingInventorySource,
|
||||
ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-MODEL-001', name='Receipt model test',
|
||||
schedule_type='platform_job', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
job_params={},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-MODEL-001', schedule_task_id=task.id, status='awaiting_callback')
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-001',
|
||||
status='awaiting_rpa', config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.commit()
|
||||
|
||||
duplicate_callback = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU-2', callback_id='receipt-callback-001',
|
||||
status='awaiting_rpa', config_snapshot_json={},
|
||||
)
|
||||
db.session.add(duplicate_callback)
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
retry_unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-002',
|
||||
status='awaiting_rpa', config_snapshot_json={}, retry_of_id=unit.id,
|
||||
)
|
||||
# Retry must retain the old failed unit instead of overwriting it; thus the
|
||||
# same schedule/source/Warehouse identity is valid when linked by retry_of_id.
|
||||
db.session.add(retry_unit)
|
||||
db.session.commit()
|
||||
assert retry_unit.retry_of_id == unit.id
|
||||
|
||||
digest = hashlib.sha256(b'receipt workbook').hexdigest()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=unit.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/test.xlsx', original_filename='test.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
))
|
||||
db.session.commit()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=unit.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/test-copy.xlsx', original_filename='test-copy.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
))
|
||||
# 关键断言:同一 RPA 单元不可归档同 SHA 文件两次。
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_receipt_models_do_not_reference_inventory_files(app):
|
||||
"""收料归档表只关联收料单元运行,避免触发库存快照或匹配链路。"""
|
||||
from app.models import ShippingReceiptReportFile
|
||||
|
||||
foreign_keys = {foreign_key.target_fullname for foreign_key in ShippingReceiptReportFile.__table__.foreign_keys}
|
||||
|
||||
# 关键断言:收料归档不能写入或关联库存快照事实表。
|
||||
assert 'shipping_inventory_files.id' not in foreign_keys
|
||||
assert foreign_keys == {'shipping_receipt_rpa_unit_runs.id'}
|
||||
@@ -16,12 +16,22 @@ from app.services.shipping_notice.order_review_fulfillment_decision_service impo
|
||||
ALLOWED_DECISIONS,
|
||||
DECISION_CLOSE,
|
||||
DECISION_FULFILL,
|
||||
DECISION_RELEASE_SHORTAGE,
|
||||
DECISION_REOPEN,
|
||||
DECISION_WAIT,
|
||||
_STATUS_BY_DECISION,
|
||||
_assess_line_fulfill_complete,
|
||||
_assert_line_can_fulfill_complete,
|
||||
_manual_release_fields_from_inventory_candidates,
|
||||
_parse_qty,
|
||||
_release_template_inventory_fields,
|
||||
_release_template_system_fields,
|
||||
_release_fact_identity,
|
||||
_resolve_shortage_release_inventory_source,
|
||||
_sync_confirmed_task_fulfillment_gates,
|
||||
_is_shortage_match_fact,
|
||||
_has_terminal_inventory_rpa_failure,
|
||||
_validate_inventory_shortage_release_fields,
|
||||
)
|
||||
|
||||
|
||||
@@ -30,8 +40,10 @@ def test_allowed_decisions_cover_contract():
|
||||
assert DECISION_WAIT in ALLOWED_DECISIONS
|
||||
assert DECISION_FULFILL in ALLOWED_DECISIONS
|
||||
assert DECISION_CLOSE in ALLOWED_DECISIONS
|
||||
assert DECISION_RELEASE_SHORTAGE in ALLOWED_DECISIONS
|
||||
assert _STATUS_BY_DECISION[DECISION_FULFILL] == 'ready_to_fulfill'
|
||||
assert _STATUS_BY_DECISION[DECISION_CLOSE] == 'closed_unfulfillable'
|
||||
assert _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE] == 'released_shortage'
|
||||
|
||||
|
||||
def test_parse_qty_rejects_non_positive():
|
||||
@@ -43,6 +55,264 @@ def test_parse_qty_rejects_non_positive():
|
||||
assert _parse_qty('abc') is None
|
||||
|
||||
|
||||
def test_shortage_release_requires_template_inventory_field_when_snapshot_value_is_ambiguous():
|
||||
"""短缺放行不能任取多条库存记录中的 ODM ID,必须要求人工明确填写。"""
|
||||
required = _manual_release_fields_from_inventory_candidates(
|
||||
mappings=[
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': '101'},
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': '102'},
|
||||
],
|
||||
candidates=[
|
||||
{'101': 'ODM-A', '102': 'R1'},
|
||||
{'101': 'ODM-B', '102': 'R1'},
|
||||
],
|
||||
field_labels={'101': 'ODM ID', '102': 'Reservation ID'},
|
||||
)
|
||||
|
||||
assert required == [{'field_id': '101', 'display_name': 'ODM ID'}]
|
||||
|
||||
|
||||
def test_shortage_release_exposes_unique_template_inventory_value_as_read_only_evidence():
|
||||
"""模板字段在当前快照唯一时只读展示来源,不应要求用户重复填写。"""
|
||||
fields = _release_template_inventory_fields(
|
||||
mappings=[
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': '101'},
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': '102'},
|
||||
],
|
||||
candidates=[
|
||||
{'101': 'ODM-A', '102': 'A-01'},
|
||||
{'101': 'ODM-A', '102': 'A-02'},
|
||||
],
|
||||
field_labels={'101': 'ODM ID', '102': '库位'},
|
||||
)
|
||||
|
||||
assert fields == [
|
||||
{
|
||||
'field_id': '101',
|
||||
'display_name': 'ODM ID',
|
||||
'value': 'ODM-A',
|
||||
'value_source': 'inventory_snapshot',
|
||||
'requires_manual': False,
|
||||
},
|
||||
{
|
||||
'field_id': '102',
|
||||
'display_name': '库位',
|
||||
'value': None,
|
||||
'value_source': 'manual_required',
|
||||
'requires_manual': True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_shortage_release_requires_header_inventory_field_when_snapshot_has_no_controlled_candidate():
|
||||
"""模板 Header 消费 ODM ID 时,短缺行没有受控候选记录必须要求人工补录。"""
|
||||
fields = _release_template_inventory_fields(
|
||||
mappings=[
|
||||
{'row_mode': 'header', 'source_kind': 'inventory_field', 'source_key': '6'},
|
||||
],
|
||||
candidates=[],
|
||||
field_labels={'6': 'ODM ID'},
|
||||
)
|
||||
|
||||
assert fields == [
|
||||
{
|
||||
'field_id': '6',
|
||||
'display_name': 'ODM ID',
|
||||
'value': None,
|
||||
'value_source': 'manual_required',
|
||||
'requires_manual': True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_shortage_release_requires_missing_header_warehouse_system_fact():
|
||||
"""模板实际消费 Warehouse ID 而任务未解析时,放行前必须人工填写。"""
|
||||
assert _release_template_system_fields(
|
||||
mappings=[
|
||||
{'row_mode': 'header', 'source_kind': 'system_fact', 'source_key': 'warehouse_id'},
|
||||
],
|
||||
warehouse_id=None,
|
||||
) == [
|
||||
{
|
||||
'field_id': 'system_fact:warehouse_id',
|
||||
'display_name': 'Warehouse ID',
|
||||
'value': None,
|
||||
'value_source': 'manual_required',
|
||||
'requires_manual': True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_shortage_release_export_uses_audited_header_override_when_no_snapshot_candidate_exists():
|
||||
"""短缺行无库存候选时,导出只能使用该行已审计补录的模板字段。"""
|
||||
from app.services.shipping_notice.export import _match_inventory_lines
|
||||
|
||||
assert _match_inventory_lines(
|
||||
order_lines=[{'part': 'PN-1', 'reservation': 'R-1'}],
|
||||
inventory_lines=[],
|
||||
match_keys=[
|
||||
{'order_field_id': 'part', 'inventory_field_id': '1'},
|
||||
{'order_field_id': 'reservation', 'inventory_field_id': '2'},
|
||||
],
|
||||
required_fields={'6'},
|
||||
release_overrides_by_line={0: {'6': 'ODM-001'}},
|
||||
released_export_line_indexes={0},
|
||||
) == [{'6': 'ODM-001'}]
|
||||
|
||||
|
||||
def test_shortage_release_export_allows_reservation_miss_when_template_uses_no_inventory_field():
|
||||
"""已审计短缺放行时,库存预约单未命中不能阻断只消费订单字段的 Excel。"""
|
||||
from app.services.shipping_notice.export import _match_inventory_lines
|
||||
|
||||
assert _match_inventory_lines(
|
||||
order_lines=[{'part': 'PN-1', 'reservation': 'R-1'}],
|
||||
inventory_lines=[{'1': 'PN-1', '2': 'R-2'}],
|
||||
match_keys=[
|
||||
{'order_field_id': 'part', 'inventory_field_id': '1'},
|
||||
{'order_field_id': 'reservation', 'inventory_field_id': '2'},
|
||||
],
|
||||
required_fields=set(),
|
||||
released_export_line_indexes={0},
|
||||
) == [{}]
|
||||
|
||||
|
||||
def test_unreleased_export_keeps_reservation_miss_blocked_when_template_uses_no_inventory_field():
|
||||
"""未放行行仍必须严格按料号和预约单匹配,不能因模板未引用库存字段而放宽。"""
|
||||
from app.services.shipping_notice.export import _match_inventory_lines
|
||||
|
||||
with pytest.raises(ValueError, match='第 1 条订单行没有匹配的库存记录'):
|
||||
_match_inventory_lines(
|
||||
order_lines=[{'part': 'PN-1', 'reservation': 'R-1'}],
|
||||
inventory_lines=[{'1': 'PN-1', '2': 'R-2'}],
|
||||
match_keys=[
|
||||
{'order_field_id': 'part', 'inventory_field_id': '1'},
|
||||
{'order_field_id': 'reservation', 'inventory_field_id': '2'},
|
||||
],
|
||||
required_fields=set(),
|
||||
)
|
||||
|
||||
|
||||
def test_shortage_release_keeps_first_export_line_override():
|
||||
"""首行原始索引为 0 时,导出仍须将已审计补录字段传入模板匹配。"""
|
||||
from app.services.shipping_notice.export import _release_overrides_for_export_lines
|
||||
|
||||
assert _release_overrides_for_export_lines(
|
||||
line_values=[{'__order_line_index': 0}],
|
||||
release_overrides_by_source_line={0: {'6': 'ODM-001'}},
|
||||
) == {0: {'6': 'ODM-001'}}
|
||||
|
||||
|
||||
def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_inventory_fact(app, monkeypatch):
|
||||
"""短缺放行重投影后必须入队 Excel 产物 Gate,且不得改写库存缺口事实。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice import order_review_fulfillment_decision_service as svc
|
||||
|
||||
task = SimpleNamespace(id=12, active_process_execution_id=34)
|
||||
case = SimpleNamespace(confirmed_task_id=12)
|
||||
execution = SimpleNamespace(id=34, task_id=12)
|
||||
synced = []
|
||||
queued = []
|
||||
monkeypatch.setattr(svc.db.session, 'get', lambda model, key: task if key == 12 else execution)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
lambda **kwargs: synced.append(kwargs),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.auto_progress_controller.submit_auto_progress',
|
||||
lambda **kwargs: queued.append(kwargs),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=7)
|
||||
|
||||
assert synced == [{'execution': execution, 'actor_type': 'user', 'actor_id': 7}]
|
||||
assert queued == [{
|
||||
'task': task,
|
||||
'trigger': 'inventory_shortage_released',
|
||||
'operator_id': 7,
|
||||
'commit': False,
|
||||
}]
|
||||
|
||||
|
||||
def test_shortage_release_rejects_missing_template_inventory_override():
|
||||
"""短缺放行漏填模板要求的库存字段时必须在服务端拒绝,不能只靠前端禁用按钮。"""
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
_validate_inventory_shortage_release_fields(
|
||||
required_fields=[{'field_id': '101', 'display_name': 'ODM ID'}],
|
||||
supplied_values={},
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.REVIEW_LINE_RELEASE_FIELDS_REQUIRED'
|
||||
|
||||
|
||||
def test_shortage_release_override_supplies_template_field_when_no_snapshot_value_exists():
|
||||
"""短缺放行后导出必须消费已审计补录值,不能因库存行缺失继续报字段不唯一。"""
|
||||
from app.services.shipping_notice.export import _collapse_inventory_matches
|
||||
|
||||
resolved = _collapse_inventory_matches(
|
||||
[{'101': ''}],
|
||||
{'101'},
|
||||
release_overrides={'101': 'ODM-001'},
|
||||
)
|
||||
|
||||
assert resolved['101'] == 'ODM-001'
|
||||
|
||||
|
||||
def test_shortage_release_reads_inventory_identity_from_projected_dict_fact():
|
||||
"""行库存事实已被序列化为 dict 时,放行字段判定仍必须拿到行/快照/库存源。"""
|
||||
assert _release_fact_identity({
|
||||
'line_index': 0,
|
||||
'inventory_snapshot_id': 24,
|
||||
'inventory_source_code': 'CRANE',
|
||||
}) == (0, 24, 'CRANE')
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_shortage_release_recognizes_current_match_fact_when_draft_projection_is_stale():
|
||||
"""放行资格必须由当前 OT 行事实决定,不能回退到过期草稿投影。"""
|
||||
assert _is_shortage_match_fact({
|
||||
'match_result': 'matched',
|
||||
'inventory_status': 'ready',
|
||||
'required_qty': '1.0',
|
||||
'available_qty': '0.0',
|
||||
'shortage_qty': '1.0',
|
||||
}) is True
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_shortage_release_inventory_source_falls_back_from_line_fact_to_task_then_snapshot():
|
||||
"""历史行事实漏源时,仍须从当前 OT 或快照恢复受控库存源。"""
|
||||
assert _resolve_shortage_release_inventory_source(
|
||||
fact_source_code=None,
|
||||
task_source_code='CRANE',
|
||||
snapshot_source_code='DBS',
|
||||
) == 'CRANE'
|
||||
assert _resolve_shortage_release_inventory_source(
|
||||
fact_source_code=None,
|
||||
task_source_code=None,
|
||||
snapshot_source_code='DBS',
|
||||
) == 'DBS'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_rpa_failure_release_requires_a_terminal_attempt_and_no_active_attempt():
|
||||
"""无库存快照的放行只允许在 RPA 已终态失败后,排队/运行中绝不能放行。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
task = SimpleNamespace(task_no='SN-RPA-FAILED', inventory_source_code='CRANE')
|
||||
assert _has_terminal_inventory_rpa_failure(
|
||||
task,
|
||||
attempts=[SimpleNamespace(source_code='CRANE', attempt_no=1, status='failed', trigger_file_path='C:/trigger.json', execution_phase='trigger_written')],
|
||||
) is True
|
||||
assert _has_terminal_inventory_rpa_failure(
|
||||
task,
|
||||
attempts=[SimpleNamespace(source_code='CRANE', attempt_no=1, status='queued', trigger_file_path='C:/trigger.json', execution_phase='trigger_written')],
|
||||
) is False
|
||||
|
||||
|
||||
|
||||
|
||||
def test_assess_rejects_shortage_and_missing_reservation():
|
||||
"""库存不足或缺 Reservation 时不可完整行先行。"""
|
||||
ok, code, _, _ = _assess_line_fulfill_complete(
|
||||
@@ -205,6 +475,85 @@ def test_decide_reopen_requires_admin_for_closed(app, monkeypatch):
|
||||
assert exc.value.code == 'SHIPPING.REVIEW_LINE_REOPEN_FORBIDDEN'
|
||||
|
||||
|
||||
def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch):
|
||||
"""新决定写审计前必须生成主键,避免审计序列化触发 500。"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice import order_review_fulfillment_decision_service as svc
|
||||
|
||||
draft = SimpleNamespace(
|
||||
draft_version=1,
|
||||
lines_json=[{'line_key': 'L1', 'qty': '1', 'reservation_id': 'R1', 'part_number': 'PN1'}],
|
||||
validation_result_json={'line_projections': [{'line_key': 'L1', 'available_qty': '1'}]},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
id=1,
|
||||
case_no='CASE-1',
|
||||
status='ready',
|
||||
current_draft=draft,
|
||||
run=SimpleNamespace(run_no='RUN-1'),
|
||||
)
|
||||
row = SimpleNamespace(
|
||||
id=None,
|
||||
line_key='L1',
|
||||
line_index=0,
|
||||
decision_version=1,
|
||||
decision_code=DECISION_FULFILL,
|
||||
decision_source='user',
|
||||
line_status='ready_to_fulfill',
|
||||
is_active=True,
|
||||
reason=None,
|
||||
required_qty='1',
|
||||
available_qty='1',
|
||||
reservation_id='R1',
|
||||
part_number='PN1',
|
||||
task_id=None,
|
||||
wave_no=None,
|
||||
actor_user_id=1,
|
||||
snapshot_json={},
|
||||
created_at=None,
|
||||
updated_at=None,
|
||||
)
|
||||
monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_active_decision', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(svc, '_next_version', lambda *args, **kwargs: 1)
|
||||
monkeypatch.setattr(svc, 'ShippingOrderReviewLineDecision', lambda **kwargs: row)
|
||||
monkeypatch.setattr(svc.db.session, 'add', lambda value: None)
|
||||
monkeypatch.setattr(svc.db.session, 'flush', lambda: setattr(row, 'id', 42))
|
||||
monkeypatch.setattr(svc, 'record_fulfillment_audit', lambda **kwargs: None, raising=False)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **kwargs: (_ for _ in ()).throw(AssertionError('audit should receive generated id'))
|
||||
if kwargs['after']['id'] is None else None,
|
||||
)
|
||||
monkeypatch.setattr(svc, 'resume_after_review_change', lambda **kwargs: {}, raising=False)
|
||||
monkeypatch.setattr(svc, '_get_soft_loader', lambda: lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, 'project_review_case_line_decisions', lambda value: {})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_resume_service.resume_after_review_change',
|
||||
lambda **kwargs: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_resume_service.attach_resume_outcome',
|
||||
lambda payload, resume: payload,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_projection.serialize_review_case',
|
||||
lambda value: {},
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
result = svc.decide_review_line_fulfillment(
|
||||
user_id=1,
|
||||
case_no='CASE-1',
|
||||
line_key='L1',
|
||||
decision_code=DECISION_FULFILL,
|
||||
expected_draft_version=1,
|
||||
)
|
||||
|
||||
assert result['decision']['id'] == 42
|
||||
|
||||
|
||||
def test_create_wave_revalidates_inventory(app, monkeypatch):
|
||||
"""建波次前 validate_draft 后仍库存不足则拒绝。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -242,7 +591,7 @@ def test_create_wave_revalidates_inventory(app, monkeypatch):
|
||||
)
|
||||
|
||||
monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, 'soft_load_review_case_for_audit', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_get_soft_loader', lambda: lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_active_decision', lambda *a, **k: decision)
|
||||
|
||||
called = {'validate': False}
|
||||
|
||||
@@ -25,8 +25,6 @@ def test_review_workbench_write_and_sensitive_events_are_frozen() -> None:
|
||||
'review_marked_non_order',
|
||||
'review_marked_quality_issue',
|
||||
'inventory_routing_rerouted',
|
||||
'inventory_routing_suggestion_adopted',
|
||||
'inventory_routing_manual_kept',
|
||||
'llm_review_requested',
|
||||
'llm_suggestion_accepted',
|
||||
'llm_suggestion_modified',
|
||||
@@ -46,8 +44,6 @@ def test_inventory_routing_events_are_in_workflow_audit_dictionary() -> None:
|
||||
"""库存路由恢复三类写事件不得再游离于冻结字典之外。"""
|
||||
for event_type in (
|
||||
'inventory_routing_rerouted',
|
||||
'inventory_routing_suggestion_adopted',
|
||||
'inventory_routing_manual_kept',
|
||||
):
|
||||
assert event_type in WORKFLOW_ITEM_AUDIT_EVENT_TYPES
|
||||
|
||||
|
||||
@@ -36,6 +36,13 @@ def test_profile_match_unknown_not_collapsed_to_unmatched():
|
||||
assert map_profile_match_user_status('not_matched') == 'unmatched'
|
||||
|
||||
|
||||
def test_profile_match_route_unique_statuses_are_matched():
|
||||
"""路由已唯一选定模板时,用户态不得误显示为未知。"""
|
||||
# 关键断言:真实路由契约 unique_match / selected_by_score 必须收敛为用户可读的已匹配。
|
||||
assert map_profile_match_user_status('unique_match') == 'matched'
|
||||
assert map_profile_match_user_status('selected_by_score') == 'matched'
|
||||
|
||||
|
||||
def test_user_profile_match_strips_admin_fields():
|
||||
"""普通用户不得看到候选分 / Profile code。"""
|
||||
payload = project_user_profile_match({
|
||||
|
||||
@@ -103,8 +103,8 @@ def test_stp_failure_stays_on_order_creation_node_and_hides_review_entry():
|
||||
assert 'open_order_review' not in actions
|
||||
|
||||
|
||||
def test_stale_running_stp_job_becomes_retryable_failure():
|
||||
"""超时的 running Job 不能永久遮蔽失败,必须投影为可恢复失败。"""
|
||||
def test_stale_running_stp_job_becomes_user_actionable_failure():
|
||||
"""超时的 running Job 必须停止,并投影当前 Gate 的明确用户动作。"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
case = SimpleNamespace(
|
||||
@@ -137,7 +137,7 @@ def test_stale_running_stp_job_becomes_retryable_failure():
|
||||
)
|
||||
|
||||
assert result['status'] == 'failed'
|
||||
assert result['retryable'] is True
|
||||
assert result['retryable'] is False
|
||||
assert result['reason_code'] == 'stp_job_stale'
|
||||
|
||||
|
||||
@@ -151,14 +151,14 @@ def test_unexpected_stp_error_has_stable_user_message():
|
||||
category_hint='temporary_storage_error',
|
||||
)
|
||||
|
||||
assert retryable is True
|
||||
assert result['message'] == '自动建单失败,系统将自动重试'
|
||||
assert retryable is False
|
||||
assert result['message'] == '自动建单失败,已停止,等待用户选择下一步动作'
|
||||
assert 'psycopg2' not in result['message']
|
||||
assert 'invalid input syntax' not in result['message']
|
||||
|
||||
|
||||
def test_automation_failed_retryable_when_post_confirm_needs_retry():
|
||||
"""确认后推进失败必须可重试,不能只显示已确认。"""
|
||||
def test_automation_failed_stops_when_post_confirm_needs_user_action():
|
||||
"""确认后推进失败必须停止,等待用户在当前 Gate 选择动作。"""
|
||||
case = SimpleNamespace(status='confirmed', confirmed_task_id=12)
|
||||
result = _project_case_automation_status(
|
||||
case,
|
||||
@@ -171,7 +171,7 @@ def test_automation_failed_retryable_when_post_confirm_needs_retry():
|
||||
},
|
||||
)
|
||||
assert result['status'] == 'failed'
|
||||
assert result['retryable'] is True
|
||||
assert result['retryable'] is False
|
||||
assert result['task_no'] == 'SN-1'
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,13 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingOrderExtraction, ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingReservation, ShippingNotice
|
||||
from app.models import (
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingReservation,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
current_available_snapshot_line_ids,
|
||||
ensure_task_reservations,
|
||||
@@ -48,6 +54,29 @@ def test_rolling_verification_keeps_shortage_pending_and_later_releases_it(app):
|
||||
assert second.result_json['available_count'] == 1
|
||||
|
||||
|
||||
def test_shortage_release_makes_only_its_snapshot_line_exportable(app):
|
||||
"""已审计短缺放行可导出该行,其他 shortage Reservation 仍不能被捎带导出。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order(suffix='released-shortage-export')
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
released_line = snapshot.lines[0]
|
||||
blocked_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
|
||||
qty=Decimal('3'), field_values_json={},
|
||||
)
|
||||
snapshot.lines.append(blocked_line)
|
||||
db.session.flush()
|
||||
verification = record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[
|
||||
{'reservation_id': released_line.reservation_id, 'part_number': released_line.part_number, 'required_qty': released_line.qty, 'available_qty': '0', 'line_status': 'shortage'},
|
||||
{'reservation_id': blocked_line.reservation_id, 'part_number': blocked_line.part_number, 'required_qty': blocked_line.qty, 'available_qty': '0', 'line_status': 'shortage'},
|
||||
])
|
||||
_verification, line_ids = current_available_snapshot_line_ids(
|
||||
task, released_snapshot_line_ids={released_line.id},
|
||||
)
|
||||
|
||||
assert line_ids == {released_line.id}
|
||||
|
||||
|
||||
def test_inventory_verification_uses_frozen_quantity_and_rejects_duplicate_result(app):
|
||||
"""关键断言:库存侧不得缩小需求数量或用重复结果覆盖同一冻结预约单。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -89,7 +89,6 @@ def stp_eligibility_stubs(monkeypatch):
|
||||
|
||||
monkeypatch.setattr(svc, '_validation', lambda _case: _eligible_validation())
|
||||
monkeypatch.setattr(svc, '_persist_case_candidate_qualification', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(svc, '_is_xfa_case', lambda **_kwargs: False)
|
||||
monkeypatch.setattr(svc, '_draft_has_manual_edits', lambda _case: False)
|
||||
monkeypatch.setattr(svc, 'record_fulfillment_audit', lambda **_kwargs: None)
|
||||
|
||||
|
||||
@@ -38,8 +38,7 @@ def test_ensure_stp_reuses_active_job_without_duplicate(app):
|
||||
active = SimpleNamespace(id=77, status='queued', retry_of_job_id=None)
|
||||
|
||||
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
|
||||
svc, '_is_xfa_case', return_value=False,
|
||||
), patch.object(svc, '_draft_has_manual_edits', return_value=False), patch.object(
|
||||
svc, '_draft_has_manual_edits', return_value=False), patch.object(
|
||||
svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-1:doc-10:v2',
|
||||
), patch.object(svc, 'find_active_stp_job', return_value=active), patch.object(
|
||||
svc, 'find_latest_stp_job', return_value=active,
|
||||
@@ -82,8 +81,7 @@ def test_ensure_stp_force_retry_keeps_failed_and_sets_retry_of(app):
|
||||
return 51
|
||||
|
||||
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
|
||||
svc, '_is_xfa_case', return_value=False,
|
||||
), patch.object(svc, '_draft_has_manual_edits', return_value=False), patch.object(
|
||||
svc, '_draft_has_manual_edits', return_value=False), patch.object(
|
||||
svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-2:doc-11:v1',
|
||||
), patch.object(svc, 'find_active_stp_job', return_value=None), patch.object(
|
||||
svc, 'find_latest_stp_job', return_value=failed,
|
||||
@@ -133,8 +131,7 @@ def test_worker_revalidation_preserves_current_manual_validation_confirmation(ap
|
||||
refreshed = {'status': 'ready', 'can_build': True, 'can_auto_create': True, 'issues': []}
|
||||
|
||||
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
|
||||
svc, '_is_xfa_case', return_value=False,
|
||||
), patch.object(svc, '_validation', return_value=refreshed), patch.object(
|
||||
svc, '_validation', return_value=refreshed), patch.object(
|
||||
svc, 'find_active_stp_job', return_value=None,
|
||||
), patch.object(svc, 'find_latest_stp_job', return_value=None), patch.object(
|
||||
svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-MANUAL-CONFIRMED:doc-12:v4',
|
||||
|
||||
@@ -122,9 +122,8 @@ def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app):
|
||||
|
||||
state = resolve_task_ui_state(task)
|
||||
assert state.checkpoint == 'upload_result_unknown'
|
||||
# 结果未知时禁止 RPA 重试,允许下载 Excel + 人工凭据/回执登记收口。
|
||||
assert state.human_options == ['refresh', 'download_excel', 'mark_manual_uploaded']
|
||||
assert 'retry_upload' not in state.human_options
|
||||
# checkpoint 仅描述内部流程;下载与人工凭据登记必须由 Gate/Artifact 下发。
|
||||
assert not hasattr(state, 'human_options')
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
|
||||
|
||||
|
||||
|
||||
@@ -16,9 +16,7 @@ from types import SimpleNamespace
|
||||
from app.services.shipping_notice.candidate_qualification_service import (
|
||||
evaluate_candidate_qualification,
|
||||
)
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
_xfa_stp_precheck,
|
||||
)
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import _stp_precheck
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
PROCESS_GATE_BLOCKING_REASON_CODES,
|
||||
PROCESS_GATE_REASON_OWNING_GATE,
|
||||
@@ -43,7 +41,7 @@ def _eligible_xfa_candidate(**overrides):
|
||||
consumed_task_id=None,
|
||||
structured_result_json={
|
||||
'customer': {'resolution_status': 'user_confirmed', 'customer_id': 101},
|
||||
'_hxops_xfa_evidence': {'header_field_count': 4, 'line_row_count': 1},
|
||||
'_hxops_formal_evidence': {'header_field_count': 4, 'line_row_count': 1},
|
||||
'_hxops_xfa_cross_checks': {
|
||||
'mirror_status': 'matched',
|
||||
'acroform_status': 'matched',
|
||||
@@ -89,35 +87,20 @@ def _patch_xfa_policy(
|
||||
emergency: bool = False,
|
||||
schema_auto_create: bool = True,
|
||||
):
|
||||
"""统一 patch XFA 试点门禁与 Schema 自动建单总开关。"""
|
||||
"""兼容历史参数;只固定公共 CQ 的环境依赖。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
|
||||
lambda: emergency,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.candidate_qualification_service.xfa_shadow_mode_enabled',
|
||||
lambda: shadow,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.candidate_qualification_service.xfa_customer_allowlist',
|
||||
lambda: list(customers if customers is not None else [101]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.candidate_qualification_service.xfa_profile_checksum_allowlist',
|
||||
lambda: list(checksums if checksums is not None else ['sha256:deadbeef']),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.candidate_qualification_service.xfa_scenario_allowlist',
|
||||
lambda: list(scenarios if scenarios is not None else ['shipping_notice_order']),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
|
||||
lambda: {'enabled': bool(schema_auto_create)},
|
||||
)
|
||||
_ = shadow, customers, checksums, scenarios
|
||||
|
||||
|
||||
def test_coordinate_path_unaffected_by_xfa_hard_gates(monkeypatch):
|
||||
"""关键断言:坐标路径不受 XFA 专属硬门禁影响。"""
|
||||
def test_coordinate_path_and_xfa_path_share_the_same_qualification_gates(monkeypatch):
|
||||
"""关键断言:来源差异只写 parser trace,不产生 XFA 专属资格 Gate。"""
|
||||
_patch_xfa_policy(monkeypatch, shadow=True, customers=[], checksums=[])
|
||||
coordinate = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(
|
||||
@@ -133,11 +116,11 @@ def test_coordinate_path_unaffected_by_xfa_hard_gates(monkeypatch):
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert coordinate['can_auto_create'] is True
|
||||
assert coordinate['parser_trace'].get('xfa_candidate') is False
|
||||
assert not [key for key in coordinate['gates'] if key.startswith('xfa_')]
|
||||
|
||||
|
||||
def test_xfa_requires_schema_auto_create_and_blind_approval(monkeypatch):
|
||||
"""关键断言:关 Schema 总开关或无盲测批准 → 不得自动建单。"""
|
||||
def test_xfa_uses_the_shared_auto_create_switch(monkeypatch):
|
||||
"""关键断言:XFA 只受与坐标模板相同的 Schema 自动建单总开关控制。"""
|
||||
_patch_xfa_policy(monkeypatch, schema_auto_create=False)
|
||||
off = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
@@ -151,20 +134,18 @@ def test_xfa_requires_schema_auto_create_and_blind_approval(monkeypatch):
|
||||
assert off['gates']['auto_create_enabled'] is False
|
||||
|
||||
_patch_xfa_policy(monkeypatch, schema_auto_create=True)
|
||||
no_blind = evaluate_candidate_qualification(
|
||||
enabled = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
unit=_xfa_unit(auto_create_approved=False),
|
||||
fields_complete=True,
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert no_blind['can_auto_create'] is False
|
||||
assert 'xfa_profile_not_blind_approved' in no_blind['blocking_reason_codes']
|
||||
assert no_blind['gates']['xfa_profile_blind_approved'] is False
|
||||
assert enabled['can_auto_create'] is True
|
||||
|
||||
|
||||
def test_xfa_shadow_mode_blocks_real_auto_create(monkeypatch):
|
||||
"""关键断言:shadow 阻断真实 can_auto_create,但可记录 would_auto_create。"""
|
||||
def test_xfa_shadow_and_allowlists_do_not_create_a_second_qualification_path(monkeypatch):
|
||||
"""关键断言:历史 XFA 试点配置不会改变统一资格结果。"""
|
||||
_patch_xfa_policy(monkeypatch, shadow=True)
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
@@ -173,14 +154,12 @@ def test_xfa_shadow_mode_blocks_real_auto_create(monkeypatch):
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'xfa_shadow_mode' in result['blocking_reason_codes']
|
||||
assert result['shadow_would_auto_create'] is True
|
||||
assert result['gates']['xfa_auto_create_policy'] is False
|
||||
assert result['can_auto_create'] is True
|
||||
assert result['shadow_would_auto_create'] is False
|
||||
|
||||
|
||||
def test_xfa_allowlist_unconfigured_fail_closed(monkeypatch):
|
||||
"""关键断言:客户或 checksum 白名单为空 → fail-closed。"""
|
||||
def test_xfa_allowlist_configuration_is_not_a_candidate_gate(monkeypatch):
|
||||
"""关键断言:历史白名单不再创建 XFA 专属 Candidate Gate。"""
|
||||
_patch_xfa_policy(monkeypatch, customers=[], checksums=[])
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
@@ -189,12 +168,11 @@ def test_xfa_allowlist_unconfigured_fail_closed(monkeypatch):
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'xfa_allowlist_unconfigured' in result['blocking_reason_codes']
|
||||
assert result['can_auto_create'] is True
|
||||
|
||||
|
||||
def test_xfa_customer_not_allowlisted(monkeypatch):
|
||||
"""关键断言:客户不在白名单 → 细粒度原因码。"""
|
||||
def test_xfa_customer_allowlist_is_not_a_candidate_gate(monkeypatch):
|
||||
"""关键断言:XFA 客户白名单不改变统一客户确认 Gate。"""
|
||||
_patch_xfa_policy(monkeypatch, customers=[999])
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
@@ -203,18 +181,17 @@ def test_xfa_customer_not_allowlisted(monkeypatch):
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'xfa_customer_not_allowlisted' in result['blocking_reason_codes']
|
||||
assert result['can_auto_create'] is True
|
||||
|
||||
|
||||
def test_xfa_evidence_and_cross_check_required(monkeypatch):
|
||||
"""关键断言:证据计数或对账状态不完整 → 阻断。"""
|
||||
def test_xfa_evidence_is_consumed_by_the_shared_evidence_gate(monkeypatch):
|
||||
"""关键断言:XFA 元数据不再另设证据 Gate,正式 evidence_json 与普通 PDF 同裁决。"""
|
||||
_patch_xfa_policy(monkeypatch)
|
||||
incomplete = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(
|
||||
structured_result_json={
|
||||
'customer': {'resolution_status': 'user_confirmed', 'customer_id': 101},
|
||||
'_hxops_xfa_evidence': {'header_field_count': 0, 'line_row_count': 0},
|
||||
'_hxops_formal_evidence': {'header_field_count': 0, 'line_row_count': 0},
|
||||
'_hxops_xfa_cross_checks': {
|
||||
'mirror_status': 'matched',
|
||||
'acroform_status': 'matched',
|
||||
@@ -230,14 +207,13 @@ def test_xfa_evidence_and_cross_check_required(monkeypatch):
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert incomplete['can_auto_create'] is False
|
||||
assert 'xfa_evidence_incomplete' in incomplete['blocking_reason_codes']
|
||||
assert incomplete['can_auto_create'] is True
|
||||
|
||||
mismatched = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(
|
||||
structured_result_json={
|
||||
'customer': {'resolution_status': 'user_confirmed', 'customer_id': 101},
|
||||
'_hxops_xfa_evidence': {'header_field_count': 4, 'line_row_count': 1},
|
||||
'_hxops_formal_evidence': {'header_field_count': 4, 'line_row_count': 1},
|
||||
'_hxops_xfa_cross_checks': {
|
||||
'mirror_status': 'mismatched',
|
||||
'acroform_status': 'matched',
|
||||
@@ -258,12 +234,30 @@ def test_xfa_evidence_and_cross_check_required(monkeypatch):
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert mismatched['can_auto_create'] is False
|
||||
assert 'xfa_cross_check_failed' in mismatched['blocking_reason_codes']
|
||||
assert mismatched['can_auto_create'] is True
|
||||
|
||||
|
||||
def test_xfa_happy_path_can_auto_create(monkeypatch):
|
||||
"""关键断言:Schema 总开关开启且试点门禁全绿 → 可自动建单。"""
|
||||
def test_xfa_dataset_fallback_requires_review_and_never_auto_creates(monkeypatch):
|
||||
"""关键断言:datasets 降级到 PDF/OCR 只能复核,不能绕过 STP。"""
|
||||
_patch_xfa_policy(monkeypatch)
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
unit=_xfa_unit(
|
||||
route_type='generic_deterministic',
|
||||
route_decision='needs_review',
|
||||
fallback_from='xfa_dataset',
|
||||
fallback_evidence_policy='datasets_then_pdfium_widget_ocr',
|
||||
),
|
||||
fields_complete=True,
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert not [key for key in result['gates'] if key.startswith('xfa_')]
|
||||
|
||||
|
||||
def test_xfa_happy_path_has_no_xfa_specific_qualification_gates(monkeypatch):
|
||||
"""关键断言:XFA 与普通 PDF 使用同一份资格 Gate 字典。"""
|
||||
_patch_xfa_policy(monkeypatch)
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
@@ -273,51 +267,35 @@ def test_xfa_happy_path_can_auto_create(monkeypatch):
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is True
|
||||
assert result['gates']['xfa_auto_create_policy'] is True
|
||||
assert result['gates']['xfa_profile_blind_approved'] is True
|
||||
assert result['gates']['xfa_pilot_allowlist'] is True
|
||||
assert result['gates']['xfa_evidence_integrity'] is True
|
||||
assert result['parser_trace'].get('xfa_auto_create_uses_schema_policy') is True
|
||||
assert not [key for key in result['gates'] if key.startswith('xfa_')]
|
||||
|
||||
|
||||
def test_emergency_stop_blocks_xfa_stp_precheck_without_deleting_facts(monkeypatch):
|
||||
"""紧急停止阻断新自动建单;预检只返回原因码,不触碰审计删除。"""
|
||||
def test_emergency_stop_blocks_shared_stp_precheck_without_deleting_facts(monkeypatch):
|
||||
"""紧急停止阻断所有模板的自动建单;预检只返回原因码。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.extraction_emergency_stop_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.xfa_shadow_mode_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
ok, reason = _xfa_stp_precheck(validation={'can_auto_create': True})
|
||||
ok, reason = _stp_precheck(validation={'can_auto_create': True})
|
||||
assert ok is False
|
||||
assert reason == 'extraction_emergency_stop'
|
||||
|
||||
|
||||
def test_xfa_stp_precheck_rechecks_shadow_and_pilot_gates(monkeypatch):
|
||||
"""关键断言:STP 入口再次检查 shadow 与试点门禁;总开关已由 can_auto_create 承载。"""
|
||||
def test_shared_stp_precheck_consumes_only_shared_qualification_result(monkeypatch):
|
||||
"""关键断言:STP 入口不再复查 XFA shadow、盲测或白名单分支。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.extraction_emergency_stop_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.xfa_shadow_mode_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
ok, reason = _xfa_stp_precheck(validation={'can_auto_create': True})
|
||||
assert ok is False
|
||||
assert reason == 'xfa_shadow_mode'
|
||||
ok, reason = _stp_precheck(validation={'can_auto_create': True})
|
||||
assert ok is True
|
||||
assert reason is None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.xfa_shadow_mode_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
ok_schema, reason_schema = _xfa_stp_precheck(validation={'can_auto_create': False})
|
||||
ok_schema, reason_schema = _stp_precheck(validation={'can_auto_create': False})
|
||||
assert ok_schema is False
|
||||
assert reason_schema == 'order_freeze_not_ready'
|
||||
|
||||
ok3, reason3 = _xfa_stp_precheck(validation={
|
||||
ok3, reason3 = _stp_precheck(validation={
|
||||
'can_auto_create': True,
|
||||
'qualification': {
|
||||
'gates': {
|
||||
@@ -328,27 +306,8 @@ def test_xfa_stp_precheck_rechecks_shadow_and_pilot_gates(monkeypatch):
|
||||
},
|
||||
},
|
||||
})
|
||||
assert ok3 is False
|
||||
assert reason3 == 'xfa_profile_not_blind_approved'
|
||||
|
||||
ok_allow, reason_allow = _xfa_stp_precheck(validation={
|
||||
'can_auto_create': True,
|
||||
'qualification': {
|
||||
'gates': {
|
||||
'xfa_auto_create_policy': True,
|
||||
'xfa_profile_blind_approved': True,
|
||||
'xfa_pilot_allowlist': False,
|
||||
'xfa_evidence_integrity': True,
|
||||
},
|
||||
'blocking_reason_codes': ['xfa_customer_not_allowlisted'],
|
||||
},
|
||||
})
|
||||
assert ok_allow is False
|
||||
assert reason_allow == 'xfa_customer_not_allowlisted'
|
||||
|
||||
ok4, reason4 = _xfa_stp_precheck(validation={'can_auto_create': True})
|
||||
assert ok4 is True
|
||||
assert reason4 is None
|
||||
assert ok3 is True
|
||||
assert reason3 is None
|
||||
|
||||
|
||||
def test_xfa_reason_codes_own_order_freeze_or_extraction_gate():
|
||||
|
||||
@@ -183,14 +183,26 @@ def test_template_mode_only_accepts_coordinate_and_xfa_dataset():
|
||||
normalize_template_mode('ocr')
|
||||
|
||||
|
||||
def test_xfa_definition_rejects_coordinate_region_keys():
|
||||
"""XFA definition 是鉴别联合类型,不能混入 coordinate region。"""
|
||||
mixed = _sample_xfa_definition(table_regions=[{'region_id': 't1'}])
|
||||
with pytest.raises(ValidationError):
|
||||
validate_xfa_dataset_definition(mixed)
|
||||
mixed_layouts = _sample_xfa_definition(order_field_layouts=[{'layout_id': 'x'}])
|
||||
with pytest.raises(ValidationError):
|
||||
validate_xfa_dataset_definition(mixed_layouts)
|
||||
def test_xfa_definition_keeps_the_shared_visual_match_contract():
|
||||
"""XFA 与普通 PDF 共用视觉 matcher;datasets 只承担末端字段取值。"""
|
||||
shared_visual = _sample_xfa_definition(
|
||||
main_table_id='visual-main-table',
|
||||
document_match={'document_type': 'purchase_order'},
|
||||
table_regions=[{'region_id': 't1'}],
|
||||
order_field_layouts=[{
|
||||
'layout_id': 'order_field_po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
}],
|
||||
bindings=[{
|
||||
**_sample_xfa_definition()['bindings'][0],
|
||||
'field_layout_id': 'order_field_po',
|
||||
}],
|
||||
)
|
||||
model = validate_xfa_dataset_definition(shared_visual)
|
||||
assert model.main_table_id == 'visual-main-table'
|
||||
assert model.table_regions == [{'region_id': 't1'}]
|
||||
assert model.order_field_layouts == [{
|
||||
'layout_id': 'order_field_po', 'field_code': 'customer_po_no', 'scope': 'header',
|
||||
}]
|
||||
model = validate_xfa_dataset_definition(_sample_xfa_definition())
|
||||
assert model.template_mode == 'xfa_dataset'
|
||||
assert model.source_contract.authoritative_line_collection_path == '/data/ITEMS/DATA'
|
||||
|
||||
@@ -24,6 +24,252 @@ from tests.test_shipping_xfa_profile_extraction import _raw_profile, _schema_def
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_datasets_adapter_uses_ocr_only_as_cross_check_evidence():
|
||||
"""关键断言:OCR 与 datasets 值冲突时仅记录脱敏差异,不能把 OCR 升格为正式值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import _ocr_cross_check
|
||||
|
||||
result = _ocr_cross_check(
|
||||
ocr_table={'rows': [{'fields': [{'field_id': 'material', 'value': 'OCR-M1'}]}]},
|
||||
datasets_table={'rows': [{'fields': [{'field_id': 'material', 'value': 'DATA-M1'}]}]},
|
||||
)
|
||||
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 1
|
||||
assert result['mismatch_count'] == 1
|
||||
assert result['mismatches'] == [{'row_index': 0, 'field_id': 'material'}]
|
||||
|
||||
|
||||
def test_datasets_validation_cross_check_reports_shared_ocr_mismatch():
|
||||
"""关键断言:验证/盲测阶段也必须拒绝 OCR 与 datasets 的字段冲突。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_validation_evidence_cross_check,
|
||||
)
|
||||
|
||||
result = _validation_evidence_cross_check(
|
||||
visual_evidence={
|
||||
'header_fields': [{'field_code': 'customer_po_no', 'normalized_value': 'OCR-PO'}],
|
||||
'lines': [{'fields': [{'field_code': 'material_no', 'normalized_value': 'OCR-MAT'}]}],
|
||||
},
|
||||
datasets_evidence={
|
||||
'header_fields': [{'field_code': 'customer_po_no', 'normalized_value': 'DATA-PO'}],
|
||||
'lines': [{'fields': [{'field_code': 'material_no', 'normalized_value': 'OCR-MAT'}]}],
|
||||
},
|
||||
)
|
||||
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 2
|
||||
assert result['mismatches'] == [{'scope': 'header', 'row_index': None, 'field_code': 'customer_po_no'}]
|
||||
|
||||
|
||||
def test_datasets_blind_cross_check_reports_shared_ocr_mismatch():
|
||||
"""关键断言:盲测也复用共同视觉候选,只把 datasets 保留为正式值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_candidate_cross_check,
|
||||
)
|
||||
|
||||
result = _blind_candidate_cross_check(
|
||||
visual_candidate={
|
||||
'order_fields': [{'scope': 'header', 'field_code': 'customer_po_no', 'value': 'OCR-PO'}],
|
||||
'rows': [{'material_no': 'OCR-MAT'}],
|
||||
},
|
||||
datasets_candidate={
|
||||
'order_fields': [{'scope': 'header', 'field_code': 'customer_po_no', 'value': 'DATA-PO'}],
|
||||
'rows': [{'material_no': 'OCR-MAT'}],
|
||||
},
|
||||
)
|
||||
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 2
|
||||
assert result['mismatches'] == [{'scope': 'header', 'row_index': None, 'field_code': 'customer_po_no'}]
|
||||
|
||||
|
||||
def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_conflict(monkeypatch):
|
||||
"""关键断言:跨模板 overlap 先走共同 matcher,datasets 只能追加末端身份冲突。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
|
||||
calls: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(
|
||||
validation_service,
|
||||
'_build_coordinate_overlap_evidence',
|
||||
lambda **kwargs: (
|
||||
calls.append(kwargs) or 'passed',
|
||||
{'matcher_policy_version': 'profile-layout-matcher', 'false_hit_other_count': 0},
|
||||
{'conflict_profiles': [{'profile_code': 'VISUAL', 'version': 2, 'reason_codes': ['false_hit']} ]},
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
profile_service,
|
||||
'published_snapshots_for_schema',
|
||||
lambda _schema_id: [{
|
||||
'profile_code': 'XFA-OTHER', 'version': 3, 'checksum': 'other',
|
||||
'definition': {'source_contract': {
|
||||
'template_packet_checksum': 'template',
|
||||
'dataset_structure_fingerprint': 'structure',
|
||||
}},
|
||||
}],
|
||||
)
|
||||
profile = SimpleNamespace(
|
||||
profile_code='XFA-CURRENT', version=1, schema_version_id=9,
|
||||
definition_json={'source_contract': {
|
||||
'template_packet_checksum': 'template',
|
||||
'dataset_structure_fingerprint': 'structure',
|
||||
}},
|
||||
)
|
||||
signature_run = SimpleNamespace(id=88)
|
||||
|
||||
status, summary, snapshot = xfa_dataset.build_overlap_evidence(
|
||||
profile=profile, signature_run=signature_run, training_samples=['training'], blind_samples=['blind'],
|
||||
)
|
||||
|
||||
assert calls == [{
|
||||
'profile': profile, 'signature_run': signature_run,
|
||||
'training_samples': ['training'], 'blind_samples': ['blind'],
|
||||
'parse_result_resolver': xfa_dataset._overlap_parse_result,
|
||||
}]
|
||||
assert status == 'failed'
|
||||
assert summary['matcher_policy_version'] == 'profile-layout-matcher'
|
||||
assert summary['value_source_identity_conflict_count'] == 1
|
||||
assert [item['profile_code'] for item in snapshot['conflict_profiles']] == ['VISUAL', 'XFA-OTHER']
|
||||
assert snapshot['conflict_profiles'][1]['reason_codes'] == ['value_source_exact_identity_conflict']
|
||||
|
||||
|
||||
def test_datasets_overlap_parse_result_uses_formal_datasets_extraction(monkeypatch):
|
||||
"""XFA overlap 解析门禁必须消费 datasets 抽取结果,不能误用坐标字段覆盖。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
|
||||
monkeypatch.setattr(
|
||||
xfa_dataset,
|
||||
'blind_candidate',
|
||||
lambda **_kwargs: {'extraction_status': 'parsed', 'reason_codes': []},
|
||||
)
|
||||
|
||||
result = xfa_dataset._overlap_parse_result(
|
||||
profile=SimpleNamespace(), sample=SimpleNamespace(),
|
||||
)
|
||||
|
||||
assert result == {'passed': True, 'reason_codes': []}
|
||||
|
||||
|
||||
def test_xfa_unified_bindings_require_header_blind_truths():
|
||||
"""bindings-only XFA Profile 的 Header 真值不得因 legacy 映射为空而被静默丢弃。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import OrderXfaDatasetProfile
|
||||
|
||||
parser = OrderXfaDatasetProfile.model_validate({
|
||||
**_raw_profile()['definition'],
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-header-po', 'field_id': 'header-po',
|
||||
'field_code': 'customer_po_no', 'scope': 'header',
|
||||
'field_layout_id': 'header_customer_po',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'path-po', 'data_path': '/data/HEADER/EBELN'},
|
||||
}],
|
||||
})
|
||||
|
||||
assert quality._expected_order_fields(
|
||||
{'header:customer_po_no': 'PO-1'}, parser=parser,
|
||||
) == {'header:customer_po_no': 'PO-1'}
|
||||
|
||||
|
||||
def test_datasets_identity_signature_reuses_common_visual_signature(monkeypatch):
|
||||
"""关键断言:XFA 只追加 datasets 身份,不能复制共同 Layout 签名输入组装。"""
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
|
||||
profile = SimpleNamespace(
|
||||
definition_json={'source_contract': {
|
||||
'template_packet_checksum': 'template',
|
||||
'dataset_structure_fingerprint': 'structure',
|
||||
}},
|
||||
profile_code='XFA-SIGN', version=1,
|
||||
)
|
||||
revision = SimpleNamespace(definition_checksum='definition-checksum')
|
||||
sample = SimpleNamespace(document_id=71, layout_version_id=17)
|
||||
analysis = SimpleNamespace(
|
||||
id=123,
|
||||
template_packet_checksum='template',
|
||||
dataset_structure_fingerprint='structure',
|
||||
datasets_packet_checksum='datasets-checksum',
|
||||
)
|
||||
calls: list[dict[str, object]] = []
|
||||
monkeypatch.setattr(
|
||||
'app.extensions.db.session.get',
|
||||
lambda _model, document_id: SimpleNamespace(id=document_id),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_analysis.resolve_frozen_xfa_structure_analysis',
|
||||
lambda _document, **_kwargs: (SimpleNamespace(), analysis, {}),
|
||||
)
|
||||
|
||||
def _shared_signature(*, profile, samples):
|
||||
calls.append({'profile': profile, 'samples': samples})
|
||||
return (
|
||||
{'signature_checksum': 'shared-signature', 'signature': {'evidence_quality': {}}},
|
||||
{'signature_version': 'shared-layout-signature', 'source_sample_count': 1, 'value_adapter': 'coordinate_ocr'},
|
||||
)
|
||||
|
||||
monkeypatch.setattr(validation_service, '_build_coordinate_identity_snapshot', _shared_signature)
|
||||
snapshot, summary = xfa_dataset.build_identity_snapshot(
|
||||
profile=profile,
|
||||
revision=revision,
|
||||
samples=[sample],
|
||||
)
|
||||
|
||||
assert calls == [{'profile': profile, 'samples': [sample]}]
|
||||
assert snapshot['signature_checksum'] == 'shared-signature'
|
||||
assert snapshot['value_adapter_evidence'] == {
|
||||
'adapter': 'xfa_dataset',
|
||||
'template_packet_checksum': 'template',
|
||||
'dataset_structure_fingerprint': 'structure',
|
||||
'datasets_packet_checksum': 'datasets-checksum',
|
||||
'definition_checksum': 'definition-checksum',
|
||||
'analysis_ids': [123],
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
}
|
||||
assert summary['source_sample_count'] == 1
|
||||
assert summary['value_adapter'] == 'xfa_dataset'
|
||||
|
||||
|
||||
def test_datasets_adapter_preserves_the_shared_visual_route_decision(monkeypatch, xfa_pdf_bytes):
|
||||
"""关键断言:datasets adapter 只能补末端取值证据,不能重建一份 XFA Route 决策。"""
|
||||
from app.services.shipping_notice import order_extraction_workflow as workflow
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
|
||||
outcome = analyze_xfa_pdf(xfa_pdf_bytes)
|
||||
capability = outcome.snapshot['xfa_capability']
|
||||
profile = _raw_profile()
|
||||
profile['definition']['source_contract']['template_packet_checksum'] = capability['template_packet_checksum']
|
||||
profile['definition']['source_contract']['dataset_structure_fingerprint'] = capability['dataset_structure_fingerprint']
|
||||
profile['definition']['main_table_id'] = 'shared-visual-main-table'
|
||||
document = {
|
||||
'document_id': 86,
|
||||
'layout_snapshot': {'provider': 'xfa', 'xfa_capability': capability},
|
||||
}
|
||||
shared_decision = {
|
||||
'match_status': 'unique_match',
|
||||
'candidate_summary': [{'profile_code': profile['profile_code']}],
|
||||
'shared_visual_route': True,
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
workflow,
|
||||
'_extract_coordinate_value_adapter_result',
|
||||
lambda **_kwargs: workflow.ValueAdapterExtractionResult(decision=dict(shared_decision)),
|
||||
)
|
||||
monkeypatch.setattr(xfa_dataset, 'xfa_enabled', lambda: True)
|
||||
monkeypatch.setattr(workflow, '_load_unit_pdf_bytes', lambda *_args, **_kwargs: xfa_pdf_bytes)
|
||||
|
||||
result = xfa_dataset.extract(
|
||||
run=SimpleNamespace(), unit=SimpleNamespace(document_id=86), intake={}, document=document,
|
||||
schema={}, definition=_schema_definition(), selected_profile=profile,
|
||||
)
|
||||
|
||||
assert result.decision['shared_visual_route'] is True
|
||||
assert result.decision['candidate_summary'] == shared_decision['candidate_summary']
|
||||
|
||||
|
||||
def _expected() -> dict:
|
||||
"""加载 annotation expected.json。"""
|
||||
return json.loads((FIXTURE_ROOT / 'annotation' / 'expected.json').read_text(encoding='utf-8'))
|
||||
@@ -55,6 +301,160 @@ def xfa_pdf_bytes():
|
||||
return build_synthetic_xfa_hybrid_pdf(load_datasets_fixture())
|
||||
|
||||
|
||||
def test_runtime_route_exposes_one_value_adapter_extraction_boundary():
|
||||
"""运行时编排只能调用统一 adapter 协议,不能维护 XFA 专用 Route。"""
|
||||
from app.services.shipping_notice import order_extraction_workflow as workflow
|
||||
|
||||
assert not hasattr(workflow, '_route_xfa_deterministic_unit')
|
||||
assert not hasattr(workflow, '_route_generic_deterministic_unit')
|
||||
assert callable(workflow.get_value_adapter)
|
||||
|
||||
|
||||
def test_runtime_route_reads_adapter_result_contract_not_a_template_policy_registry():
|
||||
"""关键断言:公共 Route 只读 adapter 结果契约,不维护 XFA 专用策略表。"""
|
||||
from app.services.shipping_notice import order_extraction_workflow as workflow
|
||||
|
||||
assert not hasattr(workflow, '_value_adapter_definition')
|
||||
result = workflow.ValueAdapterExtractionResult(
|
||||
decision={},
|
||||
review_evidence_allowed=True,
|
||||
force_needs_review_after_evidence=True,
|
||||
attach_formal_evidence=True,
|
||||
allow_manual_row_review=False,
|
||||
)
|
||||
assert result.review_evidence_allowed is True
|
||||
assert result.force_needs_review_after_evidence is True
|
||||
assert result.attach_formal_evidence is True
|
||||
assert result.allow_manual_row_review is False
|
||||
|
||||
|
||||
def test_coordinate_adapter_consumes_the_route_shared_visual_match(monkeypatch):
|
||||
"""关键断言:末端 adapter 必须消费 Route 已完成的视觉匹配,不能再次匹配。"""
|
||||
from app.services.shipping_notice import order_extraction_workflow as workflow
|
||||
|
||||
shared_match = {
|
||||
'matched': False,
|
||||
'blocking': False,
|
||||
'tables': [],
|
||||
'issues': [],
|
||||
'match': {'status': 'no_match', 'candidates': []},
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
workflow,
|
||||
'_profile_table_candidates',
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError('matcher must not run twice')),
|
||||
)
|
||||
monkeypatch.setattr(workflow, 'generic_extraction_enabled', lambda: True)
|
||||
|
||||
result = workflow._extract_coordinate_value_adapter_result(
|
||||
run=SimpleNamespace(input_snapshot_json={}), unit=SimpleNamespace(), intake={}, document={}, schema={}, definition={},
|
||||
selected_profile=None, shared_profile_result=shared_match,
|
||||
)
|
||||
|
||||
assert result.decision['match_status'] == 'no_match'
|
||||
assert result.review_evidence_allowed is True
|
||||
|
||||
|
||||
def test_coordinate_adapter_reconstructs_rows_from_the_route_selected_profile(monkeypatch):
|
||||
"""关键断言:共同 matcher 的 match_only 空表不能被当成没有业务明细表。"""
|
||||
from app.services.shipping_notice import order_extraction_workflow as workflow
|
||||
|
||||
selected_profile = {
|
||||
'profile_code': 'COORDINATE-01', 'version': 1, 'checksum': 'a' * 64,
|
||||
'definition': {'main_table_id': 'main-table'},
|
||||
}
|
||||
shared_match = {
|
||||
'matched': True,
|
||||
'blocking': False,
|
||||
'tables': [],
|
||||
'issues': [],
|
||||
'match': {
|
||||
'status': 'unique_match', 'profile_code': 'COORDINATE-01',
|
||||
'version': 1, 'checksum': 'a' * 64, 'candidates': [],
|
||||
},
|
||||
}
|
||||
calls: list[dict[str, object]] = []
|
||||
reconstructed = {
|
||||
'matched': True,
|
||||
'blocking': False,
|
||||
'issues': [],
|
||||
'match': shared_match['match'],
|
||||
'tables': [{
|
||||
'profile_id': 71, 'profile_code': 'COORDINATE-01', 'profile_version': 1,
|
||||
'profile_checksum': 'a' * 64, 'table_id': 'main-table', 'page_no': 1,
|
||||
'auto_create_approved': False, 'rows': [{'status': 'parsed', 'fields': []}],
|
||||
}],
|
||||
}
|
||||
|
||||
def rebuild(*_args, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return reconstructed
|
||||
|
||||
monkeypatch.setattr(workflow, '_profile_table_candidates', rebuild)
|
||||
monkeypatch.setattr(workflow, '_confirmed_profile_order_fields', lambda *_args, **_kwargs: [])
|
||||
|
||||
result = workflow._extract_coordinate_value_adapter_result(
|
||||
run=SimpleNamespace(input_snapshot_json={}), unit=SimpleNamespace(), intake={}, document={}, schema={}, definition={},
|
||||
selected_profile=selected_profile, shared_profile_result=shared_match,
|
||||
)
|
||||
|
||||
assert len(calls) == 1
|
||||
assert calls[0]['profiles'] == [selected_profile]
|
||||
assert calls[0]['selected_match'] == shared_match['match']
|
||||
assert result.table == reconstructed['tables'][0]
|
||||
assert result.decision['fallback_reason_codes'] == []
|
||||
|
||||
|
||||
def test_route_invokes_the_selected_value_adapter_after_shared_matching(monkeypatch, xfa_pdf_bytes):
|
||||
"""共同 matcher 选中模板后,Route 必须只调用选中 adapter 的统一 extract 协议。"""
|
||||
from app.services.shipping_notice import order_extraction_workflow as workflow
|
||||
|
||||
profile = {
|
||||
'profile_code': 'XFA-ADAPTER', 'version': 1, 'checksum': 'x' * 64,
|
||||
'template_mode': 'xfa_dataset', 'status': 'published', 'schema_version_id': 1,
|
||||
'definition': {'template_mode': 'xfa_dataset', 'main_table_id': 'main'},
|
||||
}
|
||||
document = {
|
||||
'document_id': 87,
|
||||
'layout_snapshot': {
|
||||
'status': 'ready', 'provider': 'xfa',
|
||||
'xfa_capability': {'structure_analysis_ready': True},
|
||||
'tables': [{'table_id': 'main', 'page_no': 1}],
|
||||
},
|
||||
}
|
||||
run = SimpleNamespace(
|
||||
schema_version_id=1,
|
||||
input_snapshot_json={
|
||||
'schema': {'definition': {'fields': []}, 'extraction_contract': {}},
|
||||
'order_document_profiles': [profile],
|
||||
},
|
||||
)
|
||||
unit = SimpleNamespace(document_id=87, intake_id=1)
|
||||
called: list[str] = []
|
||||
monkeypatch.setattr(workflow, 'resolve_unit_runtime_snapshot', lambda *_a, **_k: ({}, document))
|
||||
monkeypatch.setattr(
|
||||
workflow, '_profile_table_candidates',
|
||||
lambda *_a, **_k: {'matched': True, 'blocking': False, 'tables': [], 'issues': [], 'match': {
|
||||
'status': 'unique_match', 'profile_code': 'XFA-ADAPTER', 'version': 1, 'checksum': 'x' * 64,
|
||||
}},
|
||||
)
|
||||
|
||||
def _adapter_extract(**kwargs):
|
||||
called.append('xfa_dataset')
|
||||
assert kwargs['selected_profile'] is profile
|
||||
return workflow.ValueAdapterExtractionResult(
|
||||
decision={'capability_kind': 'xfa_dataset'},
|
||||
review_evidence_allowed=False,
|
||||
)
|
||||
|
||||
adapter = SimpleNamespace(key='xfa_dataset', extract=_adapter_extract)
|
||||
monkeypatch.setattr(workflow, 'get_value_adapter', lambda *_args, **_kwargs: adapter)
|
||||
route = workflow.route_deterministic_unit(run, unit=unit)
|
||||
|
||||
assert called == ['xfa_dataset']
|
||||
assert route.execution_mode == 'review_required'
|
||||
|
||||
|
||||
def test_route_deterministic_unit_xfa_golden_ab(monkeypatch, xfa_pdf_bytes):
|
||||
"""关键断言:正式路由输出与 golden A/B 字段一致,且冻结 parser/结构身份。"""
|
||||
outcome = analyze_xfa_pdf(xfa_pdf_bytes)
|
||||
@@ -65,6 +465,16 @@ def test_route_deterministic_unit_xfa_golden_ab(monkeypatch, xfa_pdf_bytes):
|
||||
raw_profile['definition']['source_contract']['dataset_structure_fingerprint'] = (
|
||||
capability['dataset_structure_fingerprint']
|
||||
)
|
||||
raw_profile['definition']['main_table_id'] = 'visual-main-table'
|
||||
raw_profile['definition'].update({
|
||||
'document_match': {
|
||||
'document_type': 'purchase_order', 'page_pattern': 'one_or_more',
|
||||
'required_anchors': [], 'optional_anchors': [],
|
||||
'minimum_score': 0, 'minimum_margin': 0,
|
||||
},
|
||||
'table_regions': [],
|
||||
'order_field_layouts': [],
|
||||
})
|
||||
raw_profile['schema_version_id'] = 1
|
||||
document = {
|
||||
'document_id': 85,
|
||||
@@ -72,7 +482,7 @@ def test_route_deterministic_unit_xfa_golden_ab(monkeypatch, xfa_pdf_bytes):
|
||||
'status': 'ready',
|
||||
'provider': 'xfa',
|
||||
'xfa_capability': capability,
|
||||
'tables': [],
|
||||
'tables': [{'table_id': 'visual-main-table', 'page_no': 1, 'html': '<table><tr><th>Item</th></tr></table>'}],
|
||||
},
|
||||
}
|
||||
run = SimpleNamespace(
|
||||
@@ -94,15 +504,32 @@ def test_route_deterministic_unit_xfa_golden_ab(monkeypatch, xfa_pdf_bytes):
|
||||
lambda *_args, **_kwargs: ({'intake_no': 'SNI-XFA-GOLDEN'}, document),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow.xfa_enabled',
|
||||
'app.services.shipping_notice.order_profile_value_adapters.xfa_dataset.xfa_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._load_unit_pdf_bytes',
|
||||
lambda *_args, **_kwargs: xfa_pdf_bytes,
|
||||
)
|
||||
# 公共视觉候选阶段已经唯一选中 Profile;XFA adapter 只复验 datasets 身份并取值。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
|
||||
'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates',
|
||||
lambda *_args, **_kwargs: {
|
||||
'matched': True,
|
||||
'blocking': False,
|
||||
'tables': [],
|
||||
'issues': [],
|
||||
'match': {
|
||||
'status': 'unique_match',
|
||||
'profile_code': raw_profile['profile_code'],
|
||||
'version': raw_profile['version'],
|
||||
'checksum': raw_profile['checksum'],
|
||||
'candidates': [],
|
||||
},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._extract_generic_evidence_result',
|
||||
lambda **_kwargs: (_ for _ in ()).throw(AssertionError('no generic fallback on XFA success')),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -131,8 +558,8 @@ def test_route_deterministic_unit_xfa_golden_ab(monkeypatch, xfa_pdf_bytes):
|
||||
assert 'datasets_xml' not in blob
|
||||
|
||||
|
||||
def test_route_deterministic_unit_xfa_no_match_does_not_fallback_to_generic(monkeypatch, xfa_pdf_bytes):
|
||||
"""关键断言:Profile 未命中 → review_required 失败关闭,禁止通用/坐标正式回退。"""
|
||||
def test_route_deterministic_unit_xfa_no_match_reuses_plain_pdf_generic_pipeline(monkeypatch, xfa_pdf_bytes):
|
||||
"""关键断言:未命中模板时不得因 XFA capability 选择 datasets adapter。"""
|
||||
outcome = analyze_xfa_pdf(xfa_pdf_bytes)
|
||||
capability = outcome.snapshot['xfa_capability']
|
||||
document = {
|
||||
@@ -162,14 +589,6 @@ def test_route_deterministic_unit_xfa_no_match_does_not_fallback_to_generic(monk
|
||||
'app.services.shipping_notice.order_extraction_workflow.resolve_unit_runtime_snapshot',
|
||||
lambda *_args, **_kwargs: ({'intake_no': 'SNI-XFA-MISS'}, document),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow.xfa_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._load_unit_pdf_bytes',
|
||||
lambda *_args, **_kwargs: xfa_pdf_bytes,
|
||||
)
|
||||
generic_called = {'value': False}
|
||||
|
||||
def _fake_generic(**kwargs):
|
||||
@@ -177,33 +596,27 @@ def test_route_deterministic_unit_xfa_no_match_does_not_fallback_to_generic(monk
|
||||
decision = kwargs.get('decision') if isinstance(kwargs.get('decision'), dict) else {}
|
||||
from app.services.shipping_notice.order_extraction_workflow import DeterministicRouteResult
|
||||
return DeterministicRouteResult(
|
||||
execution_mode='review_required',
|
||||
execution_mode='deterministic',
|
||||
decision={
|
||||
**decision,
|
||||
'route_type': 'generic_deterministic',
|
||||
'route_decision': 'needs_review',
|
||||
'route_decision': 'straight_through',
|
||||
},
|
||||
orders=[],
|
||||
orders=[{'header_fields': [], 'lines': []}],
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
|
||||
'app.services.shipping_notice.order_extraction_workflow._extract_generic_evidence_result',
|
||||
_fake_generic,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates',
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(
|
||||
AssertionError('no coordinate fallback on XFA formal failure')
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workflow.generic_extraction_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
route = route_deterministic_unit(run, unit=unit)
|
||||
assert generic_called['value'] is False
|
||||
assert route.execution_mode == 'review_required'
|
||||
assert route.decision.get('capability_kind') == 'xfa_dataset'
|
||||
assert route.decision.get('capability_kind') != 'xfa_fallback_coordinate'
|
||||
codes = route.decision.get('fallback_reason_codes') or route.decision.get('reason_codes') or []
|
||||
assert 'xfa_profile_not_matched' in codes
|
||||
assert generic_called['value'] is True
|
||||
assert route.execution_mode == 'deterministic'
|
||||
assert route.decision.get('route_decision') == 'straight_through'
|
||||
assert route.decision.get('capability_kind') == 'coordinate'
|
||||
assert route.decision.get('fallback_from') is None
|
||||
assert route.decision.get('fallback_evidence_policy') is None
|
||||
@@ -44,6 +44,7 @@ def _draft_with_binding(app, monkeypatch):
|
||||
'display_name': 'Concurrency',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'main_table_id': paths['MAIN_TABLE'],
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'conc-tab',
|
||||
'operation_id': 'conc-wizard',
|
||||
@@ -60,6 +61,7 @@ def _draft_with_binding(app, monkeypatch):
|
||||
'field_id': 'f-qty',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'line_1:quantity',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': paths['MENGE'],
|
||||
@@ -199,4 +201,51 @@ def test_operation_id_conflict_on_different_definition(app, monkeypatch):
|
||||
operation_id='conc-op-conflict',
|
||||
enforce_lease=True,
|
||||
)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT'
|
||||
assert getattr(caught.value, 'code', None) in {
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_MAPPING_DELETE_CONFIRMATION_REQUIRED',
|
||||
}
|
||||
|
||||
|
||||
def test_formal_binding_deletion_requires_explicit_confirmation(app, monkeypatch):
|
||||
"""正式 datasets binding 被请求删除时,保存接口必须 fail-closed。"""
|
||||
user_id, schema_id, document_id, created, profile_id, definition, _paths = _draft_with_binding(app, monkeypatch)
|
||||
with app.app_context():
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': definition,
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document_id,
|
||||
},
|
||||
actor_id=user_id,
|
||||
profile_id=profile_id,
|
||||
browser_session_id='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-formal-binding-seed',
|
||||
enforce_lease=True,
|
||||
)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
mutated = dict(definition)
|
||||
mutated['bindings'] = []
|
||||
with pytest.raises(Exception) as caught:
|
||||
profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': schema_id,
|
||||
'definition': mutated,
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document_id,
|
||||
},
|
||||
actor_id=user_id,
|
||||
profile_id=profile_id,
|
||||
browser_session_id='conc-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='conc-explicit-delete-required',
|
||||
enforce_lease=True,
|
||||
)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_MAPPING_DELETE_CONFIRMATION_REQUIRED'
|
||||
@@ -1,31 +1,16 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_ocr_automark.py
|
||||
|
||||
用途:验收 XFA OCR 自动标记入队、accept 分层、mismatch 阻断、发布门禁与 renderer bump 降级。
|
||||
依赖:order_document_profile_xfa_automark_service、assert_xfa_synthetic_preview_gate、
|
||||
publish_check _blocking_xfa_visual_bindings;mock queue / lease / confirm / native pages。
|
||||
逻辑:纯单元为主;enqueue mock 原生页指纹;不依赖真实 RapidOCR / DB 全栈。
|
||||
用途:验收 XFA 最终 datasets 映射的契约,以及遗留 synthetic 视觉确认的降级。
|
||||
依赖:XFA Profile 契约、旧 preview 清理服务、pytest。
|
||||
逻辑:自动标记已完全复用统一 PDF/OCR Job,本文件不再维护 XFA 专用自动标注路径。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.order_document_profile_publish_check_service import (
|
||||
_blocking_xfa_visual_bindings,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_validation_service import (
|
||||
assert_xfa_synthetic_preview_gate,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_xfa_automark_service import (
|
||||
AUTOMARK_MISMATCH_BLOCKED,
|
||||
accept_xfa_automark_suggestion,
|
||||
demote_stale_confirmed_visual_bindings_on_renderer_bump,
|
||||
enqueue_xfa_ocr_automark,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import OrderXfaDatasetProfile
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
@@ -84,328 +69,16 @@ def _definition_with_binding(*, visual_status: str = 'suggested', region_kind: s
|
||||
'page_count': 1,
|
||||
'unresolved_ocr_mismatch_count': 0,
|
||||
},
|
||||
'xfa_ocr_automark': {
|
||||
'status': 'completed',
|
||||
'preview_render_checksum': checksum,
|
||||
'unresolved_ocr_mismatch_count': 0,
|
||||
'suggestions': [],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_enqueue_xfa_ocr_automark_returns_job_id():
|
||||
"""关键断言:enqueue 以原生 PDF 指纹入队,不再依赖 synthetic preview。"""
|
||||
def test_xfa_profile_rejects_coordinate_value_binding():
|
||||
"""关键断言:XFA 正式值只能来自 datasets,坐标/OCR 只能作为视觉证据。"""
|
||||
definition = _definition_with_binding()
|
||||
profile = MagicMock(
|
||||
id=12,
|
||||
status='draft',
|
||||
template_mode='xfa_dataset',
|
||||
definition_json=definition,
|
||||
)
|
||||
native = {
|
||||
'pages': [{'page_no': 1, 'png_bytes': b'png'}],
|
||||
'page_count': 1,
|
||||
'preview_render_checksum': 'sha256:' + ('c' * 64),
|
||||
'renderer_version': 'hxops.native_pdf.v1',
|
||||
'render_mode': 'native_pdf',
|
||||
definition['bindings'][0]['value_binding'] = {
|
||||
'type': 'pdf_coordinate',
|
||||
'region_id': 'visual-only-box',
|
||||
}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._load_native_pdf_pages_for_ocr',
|
||||
return_value=native,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.enqueue',
|
||||
return_value=4242,
|
||||
) as enqueue_mock, patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.db',
|
||||
) as db_mock:
|
||||
job = MagicMock(status='queued')
|
||||
db_mock.session.get.return_value = job
|
||||
result = enqueue_xfa_ocr_automark(
|
||||
12,
|
||||
document_id=77,
|
||||
actor_id=1,
|
||||
force=False,
|
||||
)
|
||||
assert result['job_id'] == 4242
|
||||
assert result['status'] == 'queued'
|
||||
assert result['preview_render_checksum'].startswith('sha256:')
|
||||
assert result['render_mode'] == 'native_pdf'
|
||||
enqueue_mock.assert_called_once()
|
||||
call_kwargs = enqueue_mock.call_args
|
||||
assert call_kwargs.args[0].value == 'shipping_xfa_ocr_automark' or str(call_kwargs.args[0]) == 'shipping_xfa_ocr_automark'
|
||||
|
||||
|
||||
def test_execute_blank_native_pdf_returns_empty_suggestions():
|
||||
"""关键断言:空白壳原生页返回空建议成功,不报 XFA_PREVIEW_UNAVAILABLE。"""
|
||||
from app.services.shipping_notice.order_document_profile_xfa_automark_service import (
|
||||
execute_xfa_ocr_automark_job,
|
||||
)
|
||||
|
||||
profile = MagicMock(
|
||||
id=12,
|
||||
status='draft',
|
||||
template_mode='xfa_dataset',
|
||||
definition_json=_definition_with_binding(),
|
||||
)
|
||||
native = {
|
||||
'pages': [],
|
||||
'page_count': 0,
|
||||
'preview_render_checksum': 'sha256:' + ('d' * 64),
|
||||
'renderer_version': 'hxops.native_pdf.v1',
|
||||
'render_mode': 'native_pdf',
|
||||
}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._load_native_pdf_pages_for_ocr',
|
||||
return_value=native,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._audit_automark',
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.db',
|
||||
):
|
||||
result = execute_xfa_ocr_automark_job({
|
||||
'profile_id': 12,
|
||||
'document_id': 77,
|
||||
'actor_id': 1,
|
||||
'job_id': 9,
|
||||
})
|
||||
assert result['status'] == 'success'
|
||||
assert result['suggestions'] == []
|
||||
assert result['error_code'] is None
|
||||
assert result['page_count'] == 0
|
||||
assert profile.definition_json['xfa_ocr_automark']['suggestion_count'] == 0
|
||||
|
||||
|
||||
def test_execute_automark_collects_widget_before_failing_unavailable_ocr():
|
||||
"""关键断言:OCR 是强制证据,但其失败不得阻止独立 Widget 采集和审计。"""
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.order_document_profile_xfa_automark_service import (
|
||||
execute_xfa_ocr_automark_job,
|
||||
)
|
||||
|
||||
profile = MagicMock(
|
||||
id=12,
|
||||
status='draft',
|
||||
template_mode='xfa_dataset',
|
||||
definition_json=_definition_with_binding(),
|
||||
)
|
||||
native = {
|
||||
'pages': [{'page_no': 1, 'png_bytes': b'png'}],
|
||||
'page_count': 1,
|
||||
'preview_render_checksum': 'sha256:' + ('d' * 64),
|
||||
'renderer_version': 'hxops.native_pdf.v1',
|
||||
'render_mode': 'native_pdf',
|
||||
}
|
||||
widget = {
|
||||
'field_key': 'path-po',
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.4, 'y1': 0.3},
|
||||
'confidence': 0.95,
|
||||
}
|
||||
merged = {
|
||||
'suggested_visual_bindings': [{
|
||||
**widget,
|
||||
'source': 'acroform_widget',
|
||||
'match_class': 'high',
|
||||
'suggestion_origin': 'widget_template',
|
||||
}],
|
||||
}
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._load_native_pdf_pages_for_ocr',
|
||||
return_value=native,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._dataset_targets_flat',
|
||||
return_value=[{'field_key': 'path-po', 'value': 'PO-1'}],
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._widget_candidates_for_page',
|
||||
return_value=[widget],
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.recognize_preview_page',
|
||||
side_effect=ServiceUnavailableError('OCR unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE'),
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.merge_visual_binding_suggestions',
|
||||
return_value=merged,
|
||||
) as merge_mock, patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._audit_automark',
|
||||
) as audit_mock, patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.db',
|
||||
):
|
||||
with pytest.raises(Exception, match='XFA native PDF OCR is unavailable'):
|
||||
execute_xfa_ocr_automark_job({
|
||||
'profile_id': 12,
|
||||
'document_id': 77,
|
||||
'actor_id': 1,
|
||||
'job_id': 9,
|
||||
})
|
||||
|
||||
# Widget 已独立采集;OCR 缺失时不产生不完整的融合建议。
|
||||
assert merge_mock.call_count == 0
|
||||
assert any(
|
||||
call.kwargs.get('event_type') == 'xfa_ocr_failed'
|
||||
and call.kwargs.get('detail', {}).get('widget_candidate_count') == 1
|
||||
for call in audit_mock.call_args_list
|
||||
)
|
||||
|
||||
|
||||
def test_accept_high_requires_checksum_and_confirms(app):
|
||||
"""关键断言:high 接受走 confirm,且须携带 preview_render_checksum。"""
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as visual_svc
|
||||
|
||||
checksum = 'sha256:' + ('c' * 64)
|
||||
definition = _definition_with_binding()
|
||||
definition['xfa_ocr_automark']['suggestions'] = [{
|
||||
'suggestion_id': 'sugg-high-1',
|
||||
'field_key': 'path-po',
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'match_class': 'high',
|
||||
'needs_review': False,
|
||||
'confidence': 0.96,
|
||||
'region_kind': 'header',
|
||||
'preview_render_checksum': checksum,
|
||||
'status': 'suggested',
|
||||
}]
|
||||
profile = MagicMock(
|
||||
id=12,
|
||||
status='draft',
|
||||
template_mode='xfa_dataset',
|
||||
definition_json=definition,
|
||||
)
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch.object(lease_service, 'require_active_lease', return_value=object()), patch.object(
|
||||
visual_svc,
|
||||
'confirm_xfa_visual_binding',
|
||||
return_value={
|
||||
'binding_id': 'bind-po-001',
|
||||
'visual_binding': {
|
||||
'status': 'confirmed',
|
||||
'preview_render_checksum': checksum,
|
||||
'region_kind': 'header',
|
||||
},
|
||||
},
|
||||
) as confirm_mock, patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._mark_suggestion_resolved',
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service.db',
|
||||
):
|
||||
result = accept_xfa_automark_suggestion(
|
||||
12,
|
||||
'sugg-high-1',
|
||||
actor_id=1,
|
||||
browser_session_id='tab',
|
||||
lease_token='lease',
|
||||
)
|
||||
assert result['action'] == 'confirmed'
|
||||
confirm_mock.assert_called_once()
|
||||
kwargs = confirm_mock.call_args.kwargs
|
||||
assert kwargs['visual_binding']['region_kind'] == 'header'
|
||||
|
||||
|
||||
def test_accept_mismatch_blocked(app):
|
||||
"""关键断言:needs_review / mismatch 接受被阻断。"""
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
|
||||
definition = _definition_with_binding()
|
||||
definition['xfa_ocr_automark']['suggestions'] = [{
|
||||
'suggestion_id': 'sugg-bad-1',
|
||||
'field_key': 'path-po',
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'match_class': 'needs_review',
|
||||
'needs_review': True,
|
||||
'status': 'suggested',
|
||||
}]
|
||||
profile = MagicMock(
|
||||
id=12,
|
||||
status='draft',
|
||||
template_mode='xfa_dataset',
|
||||
definition_json=definition,
|
||||
)
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile',
|
||||
return_value=profile,
|
||||
), patch.object(lease_service, 'require_active_lease', return_value=object()):
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
accept_xfa_automark_suggestion(
|
||||
12,
|
||||
'sugg-bad-1',
|
||||
actor_id=1,
|
||||
browser_session_id='tab',
|
||||
lease_token='lease',
|
||||
)
|
||||
assert caught.value.code == AUTOMARK_MISMATCH_BLOCKED
|
||||
|
||||
|
||||
def test_publish_gate_blocks_unresolved_ocr_mismatch():
|
||||
"""关键断言:unresolved_ocr_mismatch_count>0 时发布门禁阻断。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
assert_xfa_synthetic_preview_gate(
|
||||
template_mode='xfa_dataset',
|
||||
preview_status='ready',
|
||||
preview_render_checksum='sha256:' + ('c' * 64),
|
||||
bindings=[{
|
||||
'field_id': 'f-h-po',
|
||||
'visual_binding': {'status': 'confirmed'},
|
||||
}],
|
||||
schema_field_ids={'f-h-po'},
|
||||
preview_meta={
|
||||
'status': 'ready',
|
||||
'page_count': 1,
|
||||
'pages_ready': [1],
|
||||
'unresolved_ocr_mismatch_count': 2,
|
||||
'renderer_version': 'hxops.xfa_static_preview.v1',
|
||||
},
|
||||
current_renderer_version='hxops.xfa_static_preview.v1',
|
||||
)
|
||||
keys = {item['key'] for item in caught.value.details.get('blocking') or []}
|
||||
assert 'xfa_ocr_unresolved_mismatch' in keys
|
||||
|
||||
|
||||
def test_publish_check_blocks_unresolved_mismatch_via_definition():
|
||||
"""关键断言:_blocking_xfa_visual_bindings 透传 unresolved mismatch。"""
|
||||
definition = _definition_with_binding(visual_status='confirmed')
|
||||
definition['xfa_preview']['unresolved_ocr_mismatch_count'] = 1
|
||||
definition['xfa_ocr_automark']['unresolved_ocr_mismatch_count'] = 1
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_ocr_unresolved_mismatch' for item in blocking)
|
||||
|
||||
|
||||
def test_renderer_bump_demotes_confirmed_missing_current_checksum():
|
||||
"""关键断言:renderer bump / checksum 漂移时 confirmed → suggested。"""
|
||||
definition = _definition_with_binding(visual_status='confirmed')
|
||||
result = demote_stale_confirmed_visual_bindings_on_renderer_bump(
|
||||
definition,
|
||||
current_renderer_version='hxops.xfa_static_preview.v2',
|
||||
current_preview_render_checksum='sha256:' + ('d' * 64),
|
||||
)
|
||||
assert result['demoted_count'] == 1
|
||||
visual = definition['bindings'][0]['visual_binding']
|
||||
assert visual['status'] == 'suggested'
|
||||
assert 'confirmed_on' not in visual
|
||||
|
||||
|
||||
def test_renderer_bump_keeps_matching_confirmed():
|
||||
"""关键断言:版本与 checksum 均匹配时不降级。"""
|
||||
definition = _definition_with_binding(visual_status='confirmed')
|
||||
result = demote_stale_confirmed_visual_bindings_on_renderer_bump(
|
||||
definition,
|
||||
current_renderer_version='hxops.xfa_static_preview.v1',
|
||||
current_preview_render_checksum='sha256:' + ('c' * 64),
|
||||
)
|
||||
assert result['demoted_count'] == 0
|
||||
assert definition['bindings'][0]['visual_binding']['status'] == 'confirmed'
|
||||
with pytest.raises(ValueError, match='xfa_dataset'):
|
||||
OrderXfaDatasetProfile.model_validate(definition)
|
||||
@@ -1,277 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_ocr_matching.py
|
||||
|
||||
用途:阶段 3 OCR 匹配 / 视觉建议合并、阶段 5 合成预览门禁、阶段 6 审计补偿骨架单测。
|
||||
依赖:xfa_ocr_matcher、xfa_visual_binding_service、assert_xfa_synthetic_preview_gate、
|
||||
audit_compensation_service;合成 bbox/文本,不依赖真实 RapidOCR。
|
||||
逻辑:断言 IoU/分层、mismatch→needs_review、Widget 优先 OCR 补框、门禁 fail-closed、
|
||||
补偿记录与 retry stub。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.audit_compensation_service import (
|
||||
list_pending_compensation,
|
||||
record_audit_write_failure,
|
||||
reset_compensation_store_for_tests,
|
||||
retry_pending,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.order_document_profile_validation_service import (
|
||||
assert_xfa_synthetic_preview_gate,
|
||||
)
|
||||
from app.services.shipping_notice.xfa_ocr_matcher import (
|
||||
classify_ocr_match,
|
||||
compute_iou,
|
||||
match_ocr_to_datasets,
|
||||
normalize_match_text,
|
||||
)
|
||||
from app.services.shipping_notice.xfa_visual_binding_service import merge_visual_binding_suggestions
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_normalize_and_iou_helpers():
|
||||
"""关键断言:文本规范化折叠空白;IoU 对重叠框为正。"""
|
||||
assert normalize_match_text(' Po-123 ') == 'po-123'
|
||||
iou = compute_iou(
|
||||
{'x0': 0.1, 'y0': 0.1, 'x1': 0.5, 'y1': 0.3},
|
||||
{'x0': 0.2, 'y0': 0.15, 'x1': 0.6, 'y1': 0.35},
|
||||
)
|
||||
assert 0.0 < iou < 1.0
|
||||
assert compute_iou(
|
||||
{'x0': 0.0, 'y0': 0.0, 'x1': 0.1, 'y1': 0.1},
|
||||
{'x0': 0.9, 'y0': 0.9, 'x1': 1.0, 'y1': 1.0},
|
||||
) == 0.0
|
||||
|
||||
|
||||
def test_classify_high_medium_low_and_mismatch_needs_review():
|
||||
"""关键断言:高/中/低分层;文本不匹配一律 needs_review。"""
|
||||
assert classify_ocr_match(text_score=1.0, iou=0.6, ocr_confidence=0.95) == 'high'
|
||||
assert classify_ocr_match(text_score=1.0, iou=0.35, ocr_confidence=0.85) == 'medium'
|
||||
assert classify_ocr_match(text_score=0.5, iou=0.15, ocr_confidence=0.75) == 'low'
|
||||
assert classify_ocr_match(text_score=0.0, iou=0.9, ocr_confidence=0.99) == 'needs_review'
|
||||
|
||||
|
||||
def test_match_ocr_to_datasets_mismatch_never_auto_confirm():
|
||||
"""关键断言:OCR 与 datasets 值不符 → needs_review,且 auto_confirm_blocked。"""
|
||||
ocr_lines = [{
|
||||
'text': 'WRONG-VALUE',
|
||||
'confidence': 0.99,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.4, 'y1': 0.3},
|
||||
}]
|
||||
targets = [{
|
||||
'field_key': 'path-po',
|
||||
'value': 'PO-1001',
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.4, 'y1': 0.3},
|
||||
}]
|
||||
suggestions = match_ocr_to_datasets(ocr_lines=ocr_lines, dataset_targets=targets)
|
||||
assert len(suggestions) == 1
|
||||
item = suggestions[0]
|
||||
assert item['match_class'] == 'needs_review'
|
||||
assert item['status'] == 'needs_review'
|
||||
assert item['auto_confirm_blocked'] is True
|
||||
|
||||
|
||||
def test_match_ocr_exact_value_suggested_high():
|
||||
"""关键断言:精确文本 + 高 IoU/置信 → suggested/high,仍禁止自动确认。"""
|
||||
bbox = {'x0': 0.2, 'y0': 0.4, 'x1': 0.5, 'y1': 0.5}
|
||||
suggestions = match_ocr_to_datasets(
|
||||
ocr_lines=[{'text': 'PO-1001', 'confidence': 0.96, 'normalized_bbox': bbox}],
|
||||
dataset_targets=[{'field_key': 'path-po', 'value': 'PO-1001', 'normalized_bbox': bbox}],
|
||||
)
|
||||
assert suggestions[0]['match_class'] == 'high'
|
||||
assert suggestions[0]['status'] == 'suggested'
|
||||
assert suggestions[0]['auto_confirm_blocked'] is True
|
||||
|
||||
|
||||
def test_merge_widget_first_then_ocr_fill():
|
||||
"""关键断言:Widget 覆盖的 field 不被 OCR 覆盖;未覆盖目标由 OCR 填充。"""
|
||||
widget_candidates = [{
|
||||
'path_candidates': [{'path_id': 'path-po'}],
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
'confidence': 0.9,
|
||||
}]
|
||||
result = merge_visual_binding_suggestions(
|
||||
page_no=1,
|
||||
widget_candidates=widget_candidates,
|
||||
ocr_lines=[{
|
||||
'text': 'LINE-A',
|
||||
'confidence': 0.95,
|
||||
'normalized_bbox': {'x0': 0.2, 'y0': 0.5, 'x1': 0.5, 'y1': 0.6},
|
||||
}],
|
||||
dataset_targets=[
|
||||
{'field_key': 'path-po', 'value': 'PO-1', 'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2}},
|
||||
{'field_key': 'path-line', 'value': 'LINE-A', 'normalized_bbox': {'x0': 0.2, 'y0': 0.5, 'x1': 0.5, 'y1': 0.6}},
|
||||
],
|
||||
)
|
||||
bindings = result['suggested_visual_bindings']
|
||||
origins = {item['field_key']: item['suggestion_origin'] for item in bindings}
|
||||
assert origins['path-po'] == 'widget_template'
|
||||
assert origins['path-line'] == 'ocr'
|
||||
assert all(item.get('auto_confirm_blocked') is True for item in bindings)
|
||||
assert all(item.get('status') != 'confirmed' for item in bindings)
|
||||
|
||||
|
||||
def test_assert_xfa_synthetic_preview_gate_blocks_not_ready():
|
||||
"""关键断言:preview_status 非 ready → 抛 SYNTHETIC_PREVIEW_GATE。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
assert_xfa_synthetic_preview_gate(
|
||||
template_mode='xfa_dataset',
|
||||
preview_status='failed',
|
||||
preview_render_checksum='sha256:' + ('a' * 64),
|
||||
bindings=[{
|
||||
'field_id': 'f-h-po',
|
||||
'visual_binding': {'status': 'confirmed'},
|
||||
}],
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SYNTHETIC_PREVIEW_GATE'
|
||||
keys = {item['key'] for item in caught.value.details.get('blocking') or []}
|
||||
assert 'xfa_synthetic_preview_not_ready' in keys
|
||||
|
||||
|
||||
def test_assert_xfa_synthetic_preview_gate_blocks_missing_checksum_and_unconfirmed():
|
||||
"""关键断言:缺 checksum + 未确认视觉绑定同时阻断。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
assert_xfa_synthetic_preview_gate(
|
||||
template_mode='xfa_dataset',
|
||||
preview_status='ready',
|
||||
preview_render_checksum='',
|
||||
bindings=[{
|
||||
'field_id': 'f-h-po',
|
||||
'visual_binding': {'status': 'suggested'},
|
||||
}],
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
keys = {item['key'] for item in caught.value.details.get('blocking') or []}
|
||||
assert 'xfa_preview_render_checksum_missing' in keys
|
||||
assert 'xfa_visual_binding_incomplete' in keys
|
||||
|
||||
|
||||
def test_assert_xfa_synthetic_preview_gate_skips_coordinate_and_passes_ready():
|
||||
"""关键断言:coordinate 跳过;XFA ready+页身份+confirmed 完整证据通过。"""
|
||||
assert_xfa_synthetic_preview_gate(
|
||||
template_mode='coordinate',
|
||||
preview_status=None,
|
||||
preview_render_checksum=None,
|
||||
bindings=[],
|
||||
)
|
||||
checksum = 'sha256:' + ('b' * 64)
|
||||
assert_xfa_synthetic_preview_gate(
|
||||
template_mode='xfa_dataset',
|
||||
preview_status='ready',
|
||||
preview_render_checksum=checksum,
|
||||
bindings=[{
|
||||
'field_id': 'f-h-po',
|
||||
'visual_binding': {
|
||||
'status': 'confirmed',
|
||||
'preview_render_checksum': checksum,
|
||||
'confirmed_on': 'xfa_dataset_preview',
|
||||
'renderer_version': 'hxops.xfa_static_preview.v1',
|
||||
},
|
||||
}],
|
||||
schema_field_ids={'f-h-po'},
|
||||
preview_meta={
|
||||
'status': 'ready',
|
||||
'preview_render_checksum': checksum,
|
||||
'renderer_version': 'hxops.xfa_static_preview.v1',
|
||||
'page_count': 1,
|
||||
'pages_ready': [1],
|
||||
'source_page_count': 1,
|
||||
'synthetic_page_count': 1,
|
||||
'pages': [{
|
||||
'page_no': 1,
|
||||
'source_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0},
|
||||
'synthetic_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0},
|
||||
'page_identity_hash': 'page-1',
|
||||
}],
|
||||
'unresolved_ocr_mismatch_count': 0,
|
||||
},
|
||||
current_renderer_version='hxops.xfa_static_preview.v1',
|
||||
)
|
||||
|
||||
|
||||
def test_assert_xfa_synthetic_preview_gate_blocks_missing_page_identity():
|
||||
"""关键断言:缺 source/synthetic 页身份证据 → xfa_preview_page_identity_missing。"""
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
assert_xfa_synthetic_preview_gate(
|
||||
template_mode='xfa_dataset',
|
||||
preview_status='ready',
|
||||
preview_render_checksum='sha256:' + ('b' * 64),
|
||||
bindings=[],
|
||||
preview_meta={
|
||||
'status': 'ready',
|
||||
'page_count': 1,
|
||||
'pages_ready': [1],
|
||||
},
|
||||
)
|
||||
keys = {item['key'] for item in caught.value.details.get('blocking') or []}
|
||||
assert 'xfa_preview_page_identity_missing' in keys
|
||||
|
||||
|
||||
def test_assert_xfa_synthetic_preview_gate_blocks_missing_renderer_version():
|
||||
"""关键断言:confirmed 缺 renderer_version → xfa_preview_renderer_version_mismatch(BE-4)。"""
|
||||
checksum = 'sha256:' + ('b' * 64)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
assert_xfa_synthetic_preview_gate(
|
||||
template_mode='xfa_dataset',
|
||||
preview_status='ready',
|
||||
preview_render_checksum=checksum,
|
||||
bindings=[{
|
||||
'field_id': 'f-h-po',
|
||||
'visual_binding': {
|
||||
'status': 'confirmed',
|
||||
'preview_render_checksum': checksum,
|
||||
'confirmed_on': 'xfa_dataset_preview',
|
||||
# 故意缺 renderer_version
|
||||
},
|
||||
}],
|
||||
schema_field_ids={'f-h-po'},
|
||||
preview_meta={
|
||||
'status': 'ready',
|
||||
'preview_render_checksum': checksum,
|
||||
'renderer_version': 'hxops.xfa_static_preview.v1',
|
||||
'page_count': 1,
|
||||
'pages_ready': [1],
|
||||
'source_page_count': 1,
|
||||
'synthetic_page_count': 1,
|
||||
'pages': [{
|
||||
'page_no': 1,
|
||||
'source_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0},
|
||||
'synthetic_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0},
|
||||
'page_identity_hash': 'page-1',
|
||||
}],
|
||||
},
|
||||
current_renderer_version='hxops.xfa_static_preview.v1',
|
||||
)
|
||||
keys = {item['key'] for item in caught.value.details.get('blocking') or []}
|
||||
assert 'xfa_preview_renderer_version_mismatch' in keys
|
||||
|
||||
|
||||
def test_audit_compensation_record_list_retry_stub():
|
||||
"""关键断言:写失败入队、list pending、retry stub 标记 retried_stub。"""
|
||||
reset_compensation_store_for_tests()
|
||||
record = record_audit_write_failure(
|
||||
event_type='xfa_visual_binding_suggested',
|
||||
payload={'page_no': 1},
|
||||
error='db_commit_failed',
|
||||
profile_id=12,
|
||||
)
|
||||
assert record['status'] == 'pending'
|
||||
pending = list_pending_compensation()
|
||||
assert any(item['id'] == record['id'] for item in pending)
|
||||
result = retry_pending(limit=10)
|
||||
assert result['retried'] >= 1
|
||||
assert result['note'] == 'stub_only_no_audit_replay'
|
||||
assert all(item['status'] == 'retried_stub' for item in result['items'])
|
||||
reset_compensation_store_for_tests()
|
||||
|
||||
|
||||
def test_xfa_ocr_audit_event_names_registered():
|
||||
"""关键断言:OCR 审计事件名已注册于 XFA_AUDIT_EVENT_TYPES。"""
|
||||
for name in ('xfa_ocr_started', 'xfa_ocr_completed', 'xfa_ocr_failed', 'xfa_visual_binding_suggested'):
|
||||
assert name in XFA_AUDIT_EVENT_TYPES
|
||||
@@ -62,9 +62,7 @@ def test_xfa_profile_frozen_preview_no_longer_raises_blank_pdf_ban(app, monkeypa
|
||||
def test_xfa_readonly_mapping_evidence_allows_pdf_preview():
|
||||
"""只读映射 DTO 应声明 PDF 预览可用(阶段 2)。"""
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice.order_document_profile_preview_service import (
|
||||
build_xfa_readonly_mapping_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
id=1,
|
||||
@@ -77,7 +75,7 @@ def test_xfa_readonly_mapping_evidence_allows_pdf_preview():
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'source_contract': {}, 'header_mappings': [], 'line_mapping': {'fields': []}},
|
||||
)
|
||||
evidence = build_xfa_readonly_mapping_evidence(profile)
|
||||
evidence = get_value_adapter('xfa_dataset').readonly_mapping_evidence(profile)
|
||||
assert evidence['pdf_preview_available'] is True
|
||||
|
||||
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_preview_identity.py
|
||||
|
||||
用途:验收 XFA 合成预览身份指纹、stale 判定、缓存键与审计事件注册。
|
||||
依赖:xfa_preview_contract、xfa_preview_cache、xfa_contract、progress_audit_contract。
|
||||
逻辑:纯函数断言;身份字段变化 → stale;同输入指纹稳定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_AUDIT_EVENT_TYPES,
|
||||
XFA_ERROR_CODES,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_cache import (
|
||||
build_preview_cache_key,
|
||||
clear_preview_cache,
|
||||
get_preview_cache,
|
||||
invalidate_preview_cache,
|
||||
set_preview_cache,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
RENDER_MODE,
|
||||
XFA_PREVIEW_AUDIT_EVENT_TYPES,
|
||||
XFA_PREVIEW_ERROR_CODES,
|
||||
XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT,
|
||||
XFA_PREVIEW_STALE,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
XFA_PREVIEW_VALUE_MISMATCH,
|
||||
PreviewIdentityContext,
|
||||
build_preview_identity_fingerprint,
|
||||
is_preview_identity_stale,
|
||||
shipping_error_code_for_preview,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_renderer import RENDERER_VERSION
|
||||
from app.services.shipping_notice.progress_audit_contract import XFA_PROGRESS_EVENT_CODES
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _identity(**overrides) -> PreviewIdentityContext:
|
||||
"""构造最小 PreviewIdentityContext。"""
|
||||
base = dict(
|
||||
document_id=10,
|
||||
layout_version_id=20,
|
||||
structure_analysis_id='sa-1',
|
||||
source_content_hash='a' * 64,
|
||||
template_packet_checksum='t' * 64,
|
||||
datasets_packet_checksum='d' * 64,
|
||||
dataset_structure_fingerprint='f' * 64,
|
||||
preview_render_checksum='r' * 64,
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=2,
|
||||
)
|
||||
base.update(overrides)
|
||||
return PreviewIdentityContext(**base)
|
||||
|
||||
|
||||
def test_preview_identity_fingerprint_stable():
|
||||
"""关键断言:相同身份字段指纹稳定可复现。"""
|
||||
left = build_preview_identity_fingerprint(_identity())
|
||||
right = build_preview_identity_fingerprint(_identity())
|
||||
assert left == right
|
||||
assert len(left) == 64
|
||||
|
||||
|
||||
def test_preview_identity_stale_when_checksum_or_analysis_changes():
|
||||
"""关键断言:render checksum 或 analysis_id 变化 → stale。"""
|
||||
expected = _identity()
|
||||
assert is_preview_identity_stale(expected=expected, actual=_identity()) is False
|
||||
assert is_preview_identity_stale(
|
||||
expected=expected,
|
||||
actual=_identity(preview_render_checksum='z' * 64),
|
||||
) is True
|
||||
assert is_preview_identity_stale(
|
||||
expected=expected,
|
||||
actual=_identity(structure_analysis_id='sa-2'),
|
||||
) is True
|
||||
assert is_preview_identity_stale(
|
||||
expected=expected,
|
||||
actual=_identity(datasets_packet_checksum='x' * 64),
|
||||
) is True
|
||||
|
||||
|
||||
def test_preview_error_codes_and_audit_events_registered():
|
||||
"""关键断言:预览错误码与审计事件已注册到契约 allowlist。"""
|
||||
assert {
|
||||
XFA_PREVIEW_STALE,
|
||||
XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT,
|
||||
XFA_PREVIEW_VALUE_MISMATCH,
|
||||
} <= XFA_PREVIEW_ERROR_CODES
|
||||
assert XFA_PREVIEW_ERROR_CODES <= XFA_ERROR_CODES
|
||||
assert XFA_PREVIEW_AUDIT_EVENT_TYPES <= XFA_AUDIT_EVENT_TYPES
|
||||
assert XFA_PREVIEW_AUDIT_EVENT_TYPES <= XFA_PROGRESS_EVENT_CODES
|
||||
assert shipping_error_code_for_preview(XFA_PREVIEW_STALE).startswith(
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_'
|
||||
)
|
||||
|
||||
|
||||
def test_preview_cache_get_set_invalidate():
|
||||
"""关键断言:缓存按身份键读写;invalidate 后不可读。"""
|
||||
clear_preview_cache()
|
||||
key = build_preview_cache_key(
|
||||
structure_analysis_id='sa-1',
|
||||
template_packet_checksum='t' * 64,
|
||||
datasets_packet_checksum='d' * 64,
|
||||
dataset_structure_fingerprint='f' * 64,
|
||||
source_content_hash='a' * 64,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
)
|
||||
assert get_preview_cache(key) is None
|
||||
set_preview_cache(key, {'status': 'ready', 'preview_render_checksum': 'r' * 64})
|
||||
hit = get_preview_cache(key)
|
||||
assert hit is not None
|
||||
assert hit['status'] == 'ready'
|
||||
invalidate_preview_cache(key)
|
||||
assert get_preview_cache(key) is None
|
||||
clear_preview_cache()
|
||||
@@ -1,61 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_preview_renderer.py
|
||||
|
||||
用途:硬冻结后验收——完整 flatten 未就绪时 compose 必须 needs_review,禁止 overlay ready。
|
||||
依赖:xfa_preview_renderer、xfa_preview_contract、pytest。
|
||||
逻辑:断言空 PDF failed;任意有效输入均不得 status=ready;diagnostics.reason=flatten_engine_unavailable。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
RENDER_MODE,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_renderer import (
|
||||
RENDERER_VERSION,
|
||||
attempt_offline_xfa_flatten,
|
||||
compose_xfa_dataset_preview_pages,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_compose_without_flatten_engine_is_needs_review_not_ready():
|
||||
"""关键断言:flatten 未交付 → needs_review,绝非 ready(禁 overlay)。"""
|
||||
result = compose_xfa_dataset_preview_pages(
|
||||
pdf_bytes=b'%PDF-1.4 minimal',
|
||||
analysis_or_nodes={'/data/HEADER/EBELN': '4510039227'},
|
||||
page_boxes=[{'page_no': 1, 'width': 612.0, 'height': 792.0}],
|
||||
)
|
||||
assert result.status == 'needs_review'
|
||||
assert result.error_code == XFA_PREVIEW_UNAVAILABLE
|
||||
assert result.pages == []
|
||||
assert result.preview_render_checksum is None
|
||||
assert result.render_mode == RENDER_MODE
|
||||
assert result.renderer_version == RENDERER_VERSION
|
||||
assert result.diagnostics.get('reason') == 'flatten_engine_unavailable'
|
||||
assert result.diagnostics.get('operational_status') == 'OPERATIONAL_PENDING'
|
||||
|
||||
|
||||
def test_attempt_offline_flatten_same_fail_closed():
|
||||
"""关键断言:attempt_offline_xfa_flatten 与 compose 同口径 fail-closed。"""
|
||||
result = attempt_offline_xfa_flatten(
|
||||
pdf_bytes=b'%PDF-1.4',
|
||||
analysis_or_nodes={},
|
||||
)
|
||||
assert result.status == 'needs_review'
|
||||
assert result.pages == []
|
||||
|
||||
|
||||
def test_empty_pdf_failed_not_ready():
|
||||
"""关键断言:空 PDF → failed,绝非 ready。"""
|
||||
result = compose_xfa_dataset_preview_pages(
|
||||
pdf_bytes=b'',
|
||||
analysis_or_nodes={'/data/HEADER/EBELN': 'x'},
|
||||
)
|
||||
assert result.status == 'failed'
|
||||
assert result.status != 'ready'
|
||||
assert result.pages == []
|
||||
@@ -1,320 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_preview_service.py
|
||||
|
||||
用途:验收 XFA 合成预览服务身份绑定——必须使用冻结 Analysis,stale/mismatch fail-closed。
|
||||
依赖:order_document_profile_xfa_preview_service、xfa_preview_cache、Flask app、pytest monkeypatch。
|
||||
逻辑:构造 Layout 冻结的 Analysis + 缓存条目;断言缓存身份漂移抛 XFA_PREVIEW_STALE;
|
||||
生成路径可 mock compose,避免真实渲染。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingXfaStructureAnalysis,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_cache import (
|
||||
clear_preview_cache,
|
||||
set_preview_cache,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
RENDER_MODE,
|
||||
SHIPPING_XFA_PREVIEW_STALE,
|
||||
SHIPPING_XFA_PREVIEW_UNAVAILABLE,
|
||||
SHIPPING_XFA_PREVIEW_VALUE_MISMATCH,
|
||||
preview_identity_to_dict,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_renderer import RENDERER_VERSION
|
||||
from app.services.shipping_notice import order_document_profile_xfa_preview_service as preview_svc
|
||||
|
||||
|
||||
def _content_hash(seed: str) -> str:
|
||||
return hashlib.sha256(seed.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _seed_document(*, seed: str) -> ShippingOrderDocument:
|
||||
"""创建带稳定内容哈希的最小附件 Document。"""
|
||||
token = secrets.token_hex(4)
|
||||
content_hash = _content_hash(seed)
|
||||
user = User(
|
||||
username=f'xfa-preview-{token}',
|
||||
email=f'xfa-preview-{token}@example.com',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-XFA-PREVIEW-{token}',
|
||||
owner_user_id=user.id,
|
||||
original_filename=f'{seed}.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'preview/{seed}.pdf',
|
||||
content_hash=content_hash,
|
||||
file_size=128,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='referenced',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'SNI-XFA-PREVIEW-{token}',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
purpose='order_document_profile_sample',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key=f'{seed}.pdf',
|
||||
filename=f'{seed}.pdf',
|
||||
content_hash=content_hash,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
return document
|
||||
|
||||
|
||||
def _bind_frozen_analysis(document: ShippingOrderDocument, *, fingerprint: str = 'sha256:structure') -> tuple[
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingXfaStructureAnalysis,
|
||||
]:
|
||||
"""写入 Layout 冻结的 StructureAnalysis。"""
|
||||
analysis = ShippingXfaStructureAnalysis(
|
||||
document_id=document.id,
|
||||
layout_version_id=None,
|
||||
source_content_hash=document.content_hash,
|
||||
document_kind='xfa_hybrid',
|
||||
analysis_status='ready',
|
||||
template_packet_checksum='sha256:template',
|
||||
datasets_packet_checksum='sha256:datasets',
|
||||
dataset_structure_fingerprint=fingerprint,
|
||||
packet_checksums_json={},
|
||||
stats_json={},
|
||||
security_summary_json={},
|
||||
tree_summary_json={'known_path_ids': ['p1']},
|
||||
parser_identity='xfa-parser.v1',
|
||||
contract_version='xfa-contract.v1',
|
||||
)
|
||||
db.session.add(analysis)
|
||||
db.session.flush()
|
||||
layout = ShippingDocumentLayoutVersion(
|
||||
document_id=document.id,
|
||||
version=1,
|
||||
status='ready',
|
||||
source_content_hash=document.content_hash,
|
||||
parser_key='mineru:test',
|
||||
parser_name='xfa',
|
||||
backend='pypdf',
|
||||
contract_version='shipping_document_layout.v1',
|
||||
payload_json={
|
||||
'status': 'ready',
|
||||
'provider': 'xfa',
|
||||
'xfa_capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': analysis.id,
|
||||
'document_kind': 'xfa_hybrid',
|
||||
'template_packet_checksum': analysis.template_packet_checksum,
|
||||
'dataset_structure_fingerprint': analysis.dataset_structure_fingerprint,
|
||||
},
|
||||
},
|
||||
issues_json=[],
|
||||
attempt_count=1,
|
||||
)
|
||||
db.session.add(layout)
|
||||
db.session.flush()
|
||||
analysis.layout_version_id = layout.id
|
||||
document.current_layout_version_id = layout.id
|
||||
db.session.commit()
|
||||
return layout, analysis
|
||||
|
||||
|
||||
class _MemoryGrantStore:
|
||||
"""测试用预览授权存储。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._data: dict[str, str] = {}
|
||||
|
||||
def setex(self, key: str, _ttl: int, value: str) -> None:
|
||||
self._data[str(key)] = str(value)
|
||||
|
||||
def getdel(self, key: str) -> str | None:
|
||||
return self._data.pop(str(key), None)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_preview_cache():
|
||||
clear_preview_cache()
|
||||
yield
|
||||
clear_preview_cache()
|
||||
|
||||
|
||||
def test_list_preview_pages_stale_when_cached_identity_mismatches(app, monkeypatch):
|
||||
"""关键断言:缓存身份与冻结 Analysis 不一致 → SHIPPING.*_XFA_PREVIEW_STALE。"""
|
||||
with app.app_context():
|
||||
document = _seed_document(seed='stale-cache')
|
||||
layout, analysis = _bind_frozen_analysis(document)
|
||||
monkeypatch.setattr(preview_svc, '_preview_grant_store', lambda: _MemoryGrantStore())
|
||||
monkeypatch.setattr(preview_svc, '_audit', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(preview_svc.db.session, 'commit', lambda: None)
|
||||
|
||||
# 缓存绑定了错误的 structure_analysis_id / fingerprint
|
||||
stale_identity = preview_svc._build_identity_context(
|
||||
document=document,
|
||||
layout_version_id=int(layout.id),
|
||||
analysis=analysis,
|
||||
preview_render_checksum='r' * 64,
|
||||
page_count=1,
|
||||
)
|
||||
stale_dict = preview_identity_to_dict(stale_identity)
|
||||
stale_dict['structure_analysis_id'] = int(analysis.id) + 999
|
||||
stale_dict['dataset_structure_fingerprint'] = 'sha256:other-structure'
|
||||
cache_key = preview_svc._cache_key_for_analysis(analysis=analysis, document=document)
|
||||
set_preview_cache(cache_key, {
|
||||
'identity': stale_dict,
|
||||
'status': 'ready',
|
||||
'error_code': None,
|
||||
'render_mode': RENDER_MODE,
|
||||
'renderer_version': RENDERER_VERSION,
|
||||
'page_count': 1,
|
||||
'preview_render_checksum': 'r' * 64,
|
||||
'pages': [{'page_no': 1, 'width': 612, 'height': 792, 'png_bytes': b'\x89PNG', 'drawn_field_echoes': []}],
|
||||
'diagnostics': {},
|
||||
})
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
preview_svc.list_xfa_synthetic_preview_pages(int(document.id), actor_id=1)
|
||||
assert exc_info.value.code == SHIPPING_XFA_PREVIEW_STALE
|
||||
|
||||
|
||||
def test_list_preview_pages_unavailable_when_cache_missing(app, monkeypatch):
|
||||
"""关键断言:无 ready 缓存时 list 直接 UNAVAILABLE(fail-closed)。"""
|
||||
with app.app_context():
|
||||
document = _seed_document(seed='cache-miss')
|
||||
_bind_frozen_analysis(document)
|
||||
monkeypatch.setattr(preview_svc, '_audit', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(preview_svc.db.session, 'commit', lambda: None)
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
preview_svc.list_xfa_synthetic_preview_pages(int(document.id), actor_id=1)
|
||||
assert exc_info.value.code == SHIPPING_XFA_PREVIEW_UNAVAILABLE
|
||||
|
||||
|
||||
def test_request_preview_value_mismatch_fail_closed(app, monkeypatch):
|
||||
"""关键断言:即时解析指纹与冻结 Analysis 不一致 → VALUE_MISMATCH。"""
|
||||
with app.app_context():
|
||||
document = _seed_document(seed='value-mismatch')
|
||||
_bind_frozen_analysis(document, fingerprint='sha256:frozen-fp')
|
||||
monkeypatch.setattr(preview_svc, '_preview_grant_store', lambda: _MemoryGrantStore())
|
||||
monkeypatch.setattr(preview_svc, '_audit', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(preview_svc.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.file_assets.service.read_asset_bytes',
|
||||
lambda _asset: b'%PDF-1.4 fake',
|
||||
)
|
||||
|
||||
fake_outcome = SimpleNamespace(
|
||||
snapshot={
|
||||
'xfa_capability': {
|
||||
'dataset_structure_fingerprint': 'sha256:live-different',
|
||||
'packet_checksums': {'datasets': 'sha256:datasets-live'},
|
||||
},
|
||||
},
|
||||
dataset_analysis=SimpleNamespace(leaf_values_by_path={'/a': '1'}),
|
||||
packet_result=SimpleNamespace(packet_bytes_by_name={}),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_analysis.analyze_xfa_pdf',
|
||||
lambda _pdf: fake_outcome,
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
preview_svc.request_xfa_synthetic_preview(int(document.id), actor_id=1, force=True)
|
||||
assert exc_info.value.code == SHIPPING_XFA_PREVIEW_VALUE_MISMATCH
|
||||
|
||||
|
||||
def test_request_preview_uses_frozen_analysis_and_mocked_compose(app, monkeypatch):
|
||||
"""关键断言:生成路径绑定冻结 analysis_id,且 compose 结果写入缓存可 list。"""
|
||||
with app.app_context():
|
||||
document = _seed_document(seed='compose-ok')
|
||||
layout, analysis = _bind_frozen_analysis(document, fingerprint='sha256:ok-fp')
|
||||
store = _MemoryGrantStore()
|
||||
monkeypatch.setattr(preview_svc, '_preview_grant_store', lambda: store)
|
||||
monkeypatch.setattr(preview_svc, '_audit', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(preview_svc.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.file_assets.service.read_asset_bytes',
|
||||
lambda _asset: b'%PDF-1.4 fake',
|
||||
)
|
||||
|
||||
fake_outcome = SimpleNamespace(
|
||||
snapshot={
|
||||
'xfa_capability': {
|
||||
'dataset_structure_fingerprint': 'sha256:ok-fp',
|
||||
'packet_checksums': {'datasets': 'sha256:datasets'},
|
||||
},
|
||||
},
|
||||
dataset_analysis=SimpleNamespace(leaf_values_by_path={'/HEADER/EBELN': '4510'}),
|
||||
packet_result=SimpleNamespace(packet_bytes_by_name={'template': b'<template/>'}),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_analysis.analyze_xfa_pdf',
|
||||
lambda _pdf: fake_outcome,
|
||||
)
|
||||
|
||||
compose_calls: list[dict] = []
|
||||
|
||||
def _fake_compose(**kwargs):
|
||||
compose_calls.append(kwargs)
|
||||
return SimpleNamespace(
|
||||
status='ready',
|
||||
error_code=None,
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=1,
|
||||
preview_render_checksum='c' * 64,
|
||||
pages=[{
|
||||
'page_no': 1,
|
||||
'width': 612.0,
|
||||
'height': 792.0,
|
||||
'png_bytes': b'\x89PNG\r\n\x1a\n',
|
||||
'drawn_field_echoes': [{'path_id': 'path-1', 'value': '4510'}],
|
||||
}],
|
||||
diagnostics={'drawn_echo_count': 1},
|
||||
)
|
||||
|
||||
monkeypatch.setattr(preview_svc, 'compose_xfa_dataset_preview_pages', _fake_compose)
|
||||
|
||||
payload = preview_svc.request_xfa_synthetic_preview(int(document.id), actor_id=7, force=True)
|
||||
assert payload['status'] == 'ready'
|
||||
assert payload['identity']['structure_analysis_id'] == int(analysis.id)
|
||||
assert payload['identity']['layout_version_id'] == int(layout.id)
|
||||
assert payload['pages'] and payload['pages'][0]['preview_token']
|
||||
assert 'png_bytes' not in payload['pages'][0]
|
||||
assert len(compose_calls) == 1
|
||||
|
||||
listed = preview_svc.list_xfa_synthetic_preview_pages(int(document.id), actor_id=7)
|
||||
assert listed['cache_hit'] is True
|
||||
assert listed['identity']['structure_analysis_id'] == int(analysis.id)
|
||||
assert listed['page_count'] == 1
|
||||
@@ -11,12 +11,25 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
from decimal import Decimal
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_datasets
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import extract_xfa_profile
|
||||
from app.services.shipping_notice.document_layout.xfa_signature import build_signature_summary
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitMatcher,
|
||||
XfaSplitRule,
|
||||
XfaSplitRuleSet,
|
||||
XfaSplitSegment,
|
||||
new_segment_id,
|
||||
)
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_is_formal_header_leaf,
|
||||
normalize_definition,
|
||||
)
|
||||
from tests.test_shipping_xfa_helpers import FIXTURE_ROOT, load_datasets_fixture
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
@@ -143,6 +156,34 @@ def _raw_profile(*, authoritative: str = '/data/ITEMS/DATA') -> dict:
|
||||
'fields': [],
|
||||
},
|
||||
'bindings': bindings,
|
||||
# NETPR 是复合展示值;正式 unit_price 必须通过管理员确认的声明式规则取得。
|
||||
'split_rules': [XfaSplitRuleSet(
|
||||
rule_set_id='netpr-unit-price-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-price',
|
||||
source_scope='line',
|
||||
source_field_code='NETPR',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='netpr-unit-price',
|
||||
matcher=XfaSplitMatcher(
|
||||
type='regex', pattern=r'^(.+) / ([0-9]+)$', capture_group=1,
|
||||
),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='unit_price',
|
||||
display_name='单价',
|
||||
handling='mapped',
|
||||
target_field_id='f-price',
|
||||
target_field_code='unit_price',
|
||||
),
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='needs_review',
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
).model_dump(mode='json')],
|
||||
'cross_checks': {
|
||||
'acroform_enabled': True,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
@@ -198,6 +239,365 @@ def test_golden_header_and_line_extraction():
|
||||
assert 'data_path_hash' in ref
|
||||
|
||||
|
||||
def test_line_reservation_can_inherit_a_formal_header_dataset_value():
|
||||
"""关键断言:全单 Header Reservation 可审计地投影到每个业务明细行。"""
|
||||
xml = load_datasets_fixture().replace(
|
||||
b'<TOTAL_AMOUNT>26961.60</TOTAL_AMOUNT>',
|
||||
b'<TOTAL_AMOUNT>26961.60</TOTAL_AMOUNT><SHIPMENT_TEXT>1000144510</SHIPMENT_TEXT>',
|
||||
)
|
||||
analysis = parse_xfa_datasets(xml)
|
||||
schema = _schema_definition()
|
||||
schema['fields'].append({
|
||||
'field_id': 'f-reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
})
|
||||
raw_profile = _raw_profile()
|
||||
raw_profile['definition']['bindings'].append(_xfa_binding(
|
||||
binding_id='bind-m-reservation', field_id='f-reservation', field_code='reservation_id',
|
||||
scope='line', path_id='path-shipment-text', data_path='/data/HEADER/SHIPMENT_TEXT',
|
||||
))
|
||||
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=schema,
|
||||
document_id=85,
|
||||
packet_checksum='sha256:' + ('a' * 64),
|
||||
)
|
||||
|
||||
assert result.status == 'parsed'
|
||||
reservation = next(item for item in result.rows[0]['fields'] if item['field_code'] == 'reservation_id')
|
||||
assert reservation['value'] == '1000144510'
|
||||
assert reservation['inherited_from_header'] is True
|
||||
assert reservation['evidence_ref']['source'] == 'xfa_dataset'
|
||||
|
||||
|
||||
def test_confirmed_matnr_split_keeps_match_audit_out_of_review_reasons():
|
||||
"""确定的 MATNR 拆分可保留命中审计,但不得被误判为需要复核。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw_profile = _raw_profile()
|
||||
schema = _schema_definition()
|
||||
schema['fields'].extend([
|
||||
{'field_id': 'f-customer-part', 'field_code': 'customer_part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': []},
|
||||
{'field_id': 'f-part', 'field_code': 'part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True, 'normalizer_key': 'trim', 'validator_keys': []},
|
||||
])
|
||||
raw_profile['definition']['bindings'].extend([
|
||||
_xfa_binding(
|
||||
binding_id='bind-customer-part', field_id='f-customer-part',
|
||||
field_code='customer_part_number', scope='line', path_id='path-mat',
|
||||
data_path='/data/ITEMS/DATA/MATNR',
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-part', field_id='f-part', field_code='part_number',
|
||||
scope='line', path_id='path-mat', data_path='/data/ITEMS/DATA/MATNR',
|
||||
),
|
||||
])
|
||||
raw_profile['definition']['split_rules'].append(XfaSplitRuleSet(
|
||||
rule_set_id='matnr-split-audit-v1',
|
||||
rule_version=1,
|
||||
source_path_id='path-mat',
|
||||
source_scope='line',
|
||||
source_field_code='MATNR',
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='customer-part',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='customer_part',
|
||||
display_name='客户料号', handling='mapped',
|
||||
target_field_id='f-customer-part', target_field_code='customer_part_number',
|
||||
),
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='part-number',
|
||||
matcher=XfaSplitMatcher(
|
||||
type='prefix', value='MPN', separators=[':'], case_sensitive=False,
|
||||
),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='part_number',
|
||||
display_name='内部料号', handling='mapped',
|
||||
target_field_id='f-part', target_field_code='part_number',
|
||||
),
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user',
|
||||
status='confirmed',
|
||||
requires_confirmation=False,
|
||||
).model_dump(mode='json'))
|
||||
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=schema,
|
||||
document_id=85,
|
||||
packet_checksum='sha256:' + ('a' * 64),
|
||||
)
|
||||
|
||||
assert result.status == 'parsed'
|
||||
assert 'xfa_split:line_match_candidates' not in result.rows[0]['issues']
|
||||
|
||||
|
||||
def _normalization_path_context(analysis):
|
||||
"""构造保存期路径上下文,模拟冻结分析只暴露受控 path_id。"""
|
||||
path_map = {}
|
||||
header_leaf_path_ids = set()
|
||||
|
||||
def walk(node):
|
||||
path_map[node.path_id] = node.data_path
|
||||
if node.is_leaf and node.is_header_candidate:
|
||||
header_leaf_path_ids.add(node.path_id)
|
||||
for child in node.children:
|
||||
walk(child)
|
||||
|
||||
for root in analysis.nodes:
|
||||
walk(root)
|
||||
return {
|
||||
'path_map': path_map,
|
||||
'known_path_ids': set(path_map),
|
||||
'header_leaf_path_ids': header_leaf_path_ids,
|
||||
'dataset_root_path': analysis.dataset_root_path,
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
}
|
||||
|
||||
|
||||
def _normalization_raw_profile(analysis):
|
||||
"""将提取 golden 的占位 path_id 替换为当前分析的真实受控路径。"""
|
||||
raw = _raw_profile()['definition']
|
||||
# 保存期规范化关注 binding / 视觉框契约,不依赖黄金测试的演示拆分规则。
|
||||
raw.pop('split_rules', None)
|
||||
context = _normalization_path_context(analysis)
|
||||
path_id_by_path = {data_path: path_id for path_id, data_path in context['path_map'].items()}
|
||||
for binding in raw['bindings']:
|
||||
value = binding['value_binding']
|
||||
value['path_id'] = path_id_by_path[value['data_path']]
|
||||
binding['field_layout_id'] = f"layout-{binding['scope']}-{binding['field_code']}"
|
||||
raw['order_field_layouts'] = [
|
||||
{
|
||||
'layout_id': binding['field_layout_id'],
|
||||
'field_id': binding['field_id'],
|
||||
'field_code': binding['field_code'],
|
||||
'scope': binding['scope'],
|
||||
}
|
||||
for binding in raw['bindings']
|
||||
]
|
||||
context['template_packet_checksum'] = raw['source_contract']['template_packet_checksum']
|
||||
context['dataset_structure_fingerprint'] = raw['source_contract']['dataset_structure_fingerprint']
|
||||
return raw, context, path_id_by_path
|
||||
|
||||
|
||||
def test_normalize_definition_allows_line_binding_to_known_header_leaf():
|
||||
"""保存期断言:行字段可显式继承分析器确认的 Header 叶子。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
schema = _schema_definition()
|
||||
schema['fields'].append({
|
||||
'field_id': 'f-reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
})
|
||||
raw, context, path_id_by_path = _normalization_raw_profile(analysis)
|
||||
raw['bindings'].append(_xfa_binding(
|
||||
binding_id='bind-reservation-header', field_id='f-reservation',
|
||||
field_code='reservation_id', scope='line', path_id=path_id_by_path['/data/HEADER/EBELN'],
|
||||
data_path='/data/HEADER/EBELN',
|
||||
))
|
||||
raw['bindings'][-1]['field_layout_id'] = 'layout-line-reservation_id'
|
||||
raw['order_field_layouts'].append({
|
||||
'layout_id': 'layout-line-reservation_id',
|
||||
'field_id': 'f-reservation',
|
||||
'field_code': 'reservation_id',
|
||||
'scope': 'line',
|
||||
})
|
||||
|
||||
normalized = normalize_definition(
|
||||
raw,
|
||||
schema_version=SimpleNamespace(definition_json=schema),
|
||||
path_context=context,
|
||||
)
|
||||
|
||||
reservation = next(item for item in normalized['bindings'] if item['field_code'] == 'reservation_id')
|
||||
assert reservation['scope'] == 'line'
|
||||
assert reservation['value_binding']['path_id'] == path_id_by_path['/data/HEADER/EBELN']
|
||||
|
||||
|
||||
def test_normalize_definition_freezes_schema_identity_for_visual_header_line_field():
|
||||
"""视觉表头 ITEM/QTY 可映射为 Line 字段,保存时仍必须冻结 field_id。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw, context, _path_id_by_path = _normalization_raw_profile(analysis)
|
||||
raw['table_regions'] = [{
|
||||
'region_id': 'table_one', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .8},
|
||||
'header_layouts': [{
|
||||
'layout_id': 'header_one', 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .25},
|
||||
'field_regions': [{
|
||||
'field_id': '', 'field_code': 'quantity', 'scope': 'line',
|
||||
'region': {'x0': .4, 'y0': .2, 'x1': .5, 'y1': .25},
|
||||
'extractor_key': 'direct', 'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
}],
|
||||
'line_layouts': [], 'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
||||
'termination_rules': [], 'exclusion_regions': [], 'draft_unbound_field_regions': [],
|
||||
}]
|
||||
|
||||
normalized = normalize_definition(
|
||||
raw, schema_version=SimpleNamespace(definition_json=_schema_definition()), path_context=context,
|
||||
)
|
||||
|
||||
field = normalized['table_regions'][0]['header_layouts'][0]['field_regions'][0]
|
||||
assert field['field_id'] == 'f-qty'
|
||||
assert field['scope'] == 'line'
|
||||
assert field['target_fields'] == [{'field_id': 'f-qty', 'field_code': 'quantity', 'scope': 'line'}]
|
||||
|
||||
|
||||
def test_normalize_definition_allows_line_header_inheritance_to_reuse_header_visual_layout():
|
||||
"""行级正式继承可复用同名 Header 视觉框,避免伪造不存在的表格内预约号框。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
schema = _schema_definition()
|
||||
schema['fields'].extend([
|
||||
{
|
||||
'field_id': 'f-reservation-header', 'field_code': 'reservation_id', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'required': False,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
{
|
||||
'field_id': 'f-reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
},
|
||||
])
|
||||
raw, context, path_id_by_path = _normalization_raw_profile(analysis)
|
||||
raw['order_field_layouts'].append({
|
||||
'layout_id': 'layout-header-reservation_id',
|
||||
'field_id': 'f-reservation-header',
|
||||
'field_code': 'reservation_id',
|
||||
'scope': 'header',
|
||||
})
|
||||
raw['bindings'].append({
|
||||
**_xfa_binding(
|
||||
binding_id='bind-reservation-header-layout', field_id='f-reservation-line',
|
||||
field_code='reservation_id', scope='line', path_id=path_id_by_path['/data/HEADER/EBELN'],
|
||||
data_path='/data/HEADER/EBELN',
|
||||
),
|
||||
'field_layout_id': 'layout-header-reservation_id',
|
||||
})
|
||||
|
||||
normalized = normalize_definition(
|
||||
raw,
|
||||
schema_version=SimpleNamespace(definition_json=schema),
|
||||
path_context=context,
|
||||
)
|
||||
|
||||
reservation = next(item for item in normalized['bindings'] if item['field_code'] == 'reservation_id')
|
||||
assert reservation['scope'] == 'line'
|
||||
assert reservation['field_layout_id'] == 'layout-header-reservation_id'
|
||||
|
||||
|
||||
def test_normalize_definition_allows_split_target_to_reuse_its_single_source_visual_layout():
|
||||
"""拆分目标复用 MATNR 源框,禁止为同一物理值框伪造重叠字段框。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
schema = _schema_definition()
|
||||
schema['fields'].append({
|
||||
'field_id': 'f-customer-part', 'field_code': 'customer_part_number', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
})
|
||||
raw, context, path_id_by_path = _normalization_raw_profile(analysis)
|
||||
matnr_path_id = path_id_by_path['/data/ITEMS/DATA/MATNR']
|
||||
raw['split_rules'] = [XfaSplitRuleSet(
|
||||
rule_set_id='matnr-split-target-v1', rule_version=1,
|
||||
source_path_id=matnr_path_id, source_scope='line', source_field_code='MATNR',
|
||||
source='user', status='confirmed', requires_confirmation=False,
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
rule_id='internal-part',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=1),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='customer_part',
|
||||
display_name='客户料号', handling='mapped',
|
||||
target_field_id='f-customer-part', target_field_code='customer_part_number',
|
||||
),
|
||||
),
|
||||
],
|
||||
).model_dump(mode='json')]
|
||||
raw['bindings'].append({
|
||||
**_xfa_binding(
|
||||
binding_id='bind-split-customer-part', field_id='f-customer-part',
|
||||
field_code='customer_part_number', scope='line', path_id=matnr_path_id,
|
||||
data_path='/data/ITEMS/DATA/MATNR',
|
||||
),
|
||||
'field_layout_id': 'layout-line-material_no',
|
||||
'split_rule_ref': {
|
||||
'rule_set_id': 'matnr-split-target-v1',
|
||||
'segment_id': raw['split_rules'][0]['rules'][0]['segment']['segment_id'],
|
||||
},
|
||||
})
|
||||
|
||||
normalized = normalize_definition(
|
||||
raw,
|
||||
schema_version=SimpleNamespace(definition_json=schema),
|
||||
path_context=context,
|
||||
)
|
||||
|
||||
target = next(item for item in normalized['bindings'] if item['field_code'] == 'customer_part_number')
|
||||
assert target['field_layout_id'] == 'layout-line-material_no'
|
||||
|
||||
|
||||
def test_normalize_definition_rejects_line_binding_to_non_leaf_header_node():
|
||||
"""保存期断言:行字段不得借 Header 继承读取集合、根或描述节点。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw, context, _path_id_by_path = _normalization_raw_profile(analysis)
|
||||
raw['bindings'][2]['value_binding'] = {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': next(node.path_id for node in analysis.nodes[0].children if node.local_name == 'HEADER'),
|
||||
'data_path': '/data/HEADER',
|
||||
}
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
normalize_definition(
|
||||
raw,
|
||||
schema_version=SimpleNamespace(definition_json=_schema_definition()),
|
||||
path_context=context,
|
||||
)
|
||||
|
||||
assert exc_info.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
assert exc_info.value.details['reason'] == 'line_header_inheritance_source_invalid'
|
||||
|
||||
|
||||
def test_normalize_definition_rejects_line_binding_to_header_description_leaf():
|
||||
"""保存期断言:dataDescription 的 Header 叶子不是可继承的正式数据值。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw, context, _path_id_by_path = _normalization_raw_profile(analysis)
|
||||
description_path = '/datasets/dataDescription/data/HEADER/EBELN'
|
||||
description_path_id = 'path-description-header-ebeln'
|
||||
# 模拟真实 XFA 同时携带 data/data 与 dataDescription/data 两棵树的分析结果。
|
||||
context['path_map'][description_path_id] = description_path
|
||||
context['known_path_ids'].add(description_path_id)
|
||||
assert _is_formal_header_leaf(SimpleNamespace(
|
||||
data_path=description_path,
|
||||
is_leaf=True,
|
||||
is_header_candidate=True,
|
||||
)) is False
|
||||
raw['bindings'][2]['value_binding'] = {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': description_path_id,
|
||||
'data_path': description_path,
|
||||
}
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
normalize_definition(
|
||||
raw,
|
||||
schema_version=SimpleNamespace(definition_json=_schema_definition()),
|
||||
path_context=context,
|
||||
)
|
||||
|
||||
assert exc_info.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
assert exc_info.value.details['reason'] == 'line_header_inheritance_source_invalid'
|
||||
|
||||
|
||||
def test_authoritative_collection_missing_fails_closed():
|
||||
"""关键断言:权威集合缺失 → needs_review reason。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
@@ -220,30 +620,34 @@ def test_authoritative_collection_missing_fails_closed():
|
||||
assert 'xfa_authoritative_collection_missing' in result.reason_codes
|
||||
|
||||
|
||||
def test_netpr_composite_splits_unit_price_and_price_unit():
|
||||
"""关键断言:NETPR ``898.72 / 1`` → unit_price=898.72、price_unit=1(无独立 PEINH 映射)。"""
|
||||
def test_netpr_composite_requires_an_explicit_split_rule():
|
||||
"""关键断言:NETPR 复合文本未配置拆分规则时不得隐式生成任何正式字段。"""
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import (
|
||||
parse_unit_price_with_price_unit,
|
||||
extract_profile_field_value,
|
||||
registered_extractor_output_codes,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
|
||||
|
||||
# 解析器本身。
|
||||
assert parse_unit_price_with_price_unit('898.72 / 1') == {
|
||||
'unit_price': '898.72',
|
||||
'price_unit': '1',
|
||||
}
|
||||
assert parse_unit_price_with_price_unit('898.72') is None
|
||||
# 坐标解析器不再注册 NETPR 的隐式多字段拆分;必须由两个视觉框或 XFA 显式规则提供字段值。
|
||||
assert extract_profile_field_value(
|
||||
extractor_key='unit_price_price_unit', field_code='unit_price', raw='898.72 / 1',
|
||||
) == {}
|
||||
assert registered_extractor_output_codes(
|
||||
extractor_key='unit_price_price_unit', field_code='unit_price',
|
||||
) == set()
|
||||
|
||||
# Schema 标准化:复合值不得抛 Dynamic field value type is invalid。
|
||||
typed = normalize_order_field_value(
|
||||
'898.72 / 1',
|
||||
{'field_code': 'unit_price', 'value_type': 'decimal', 'normalizer_key': 'trim'},
|
||||
)
|
||||
assert typed == Decimal('898.72')
|
||||
# Schema 标准化不得按字段名猜测拆分;只有显式拆分规则产出的单值才可转换 decimal。
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
normalize_order_field_value(
|
||||
'898.72 / 1',
|
||||
{'field_code': 'unit_price', 'value_type': 'decimal', 'normalizer_key': 'trim'},
|
||||
)
|
||||
assert exc_info.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT'
|
||||
|
||||
# 正式提取:去掉 price_unit binding 后仍应由 NETPR 复合值补齐 price_unit。
|
||||
# 正式提取:没有拆分规则时,复合 NETPR 仅保留问题证据,不能伪造 unit_price/price_unit。
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw_profile = _raw_profile()
|
||||
raw_profile['definition'].pop('split_rules', None)
|
||||
raw_profile['definition']['bindings'] = [
|
||||
item for item in raw_profile['definition']['bindings']
|
||||
if item.get('field_code') != 'price_unit'
|
||||
@@ -256,19 +660,16 @@ def test_netpr_composite_splits_unit_price_and_price_unit():
|
||||
packet_checksum='sha256:' + ('a' * 64),
|
||||
dataset_structure_fingerprint=raw_profile['definition']['source_contract']['dataset_structure_fingerprint'],
|
||||
)
|
||||
assert result.status == 'parsed'
|
||||
assert result.status == 'needs_review'
|
||||
values = _field_values(result.rows)
|
||||
assert Decimal(str(values['unit_price'])) == Decimal('898.72')
|
||||
assert str(values['price_unit']) == '1'
|
||||
unit_item = next(
|
||||
item for item in result.rows[0]['fields']
|
||||
if item.get('field_code') == 'unit_price'
|
||||
)
|
||||
assert '898.72 / 1' in str(unit_item.get('quote') or '')
|
||||
assert 'unit_price' not in values
|
||||
assert 'price_unit' not in values
|
||||
assert 'order_profile_field_invalid:unit_price' in result.rows[0]['issues']
|
||||
assert 'xfa_source_mapping_incomplete' in result.reason_codes
|
||||
|
||||
|
||||
def test_missing_bindings_fails_closed():
|
||||
"""关键断言:无 bindings → xfa_visual_bindings_required。"""
|
||||
"""关键断言:无末端映射 → xfa_mapping_required。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw_profile = _raw_profile()
|
||||
raw_profile['definition']['bindings'] = []
|
||||
@@ -280,7 +681,7 @@ def test_missing_bindings_fails_closed():
|
||||
packet_checksum='sha256:' + ('a' * 64),
|
||||
)
|
||||
assert result.status == 'failed'
|
||||
assert 'xfa_visual_bindings_required' in result.reason_codes
|
||||
assert 'xfa_mapping_required' in result.reason_codes
|
||||
|
||||
|
||||
def test_dual_binding_source_fails_closed():
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_profile_matcher.py
|
||||
|
||||
用途:阶段 3 XFA Profile 精确结构身份匹配验收(唯一命中 / 结构变化 / 多命中)。
|
||||
依赖:xfa_profile_matcher、xfa_signature、xfa helpers、pytest。
|
||||
逻辑:基于 annotation fixture 计算 live 指纹,构造 published 快照后断言匹配态;
|
||||
草稿/retired 不得参与新 Run 匹配。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_datasets
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_matcher import match_frozen_xfa_profiles
|
||||
from app.services.shipping_notice.document_layout.xfa_signature import build_signature_summary
|
||||
from tests.test_shipping_xfa_helpers import load_datasets_fixture
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _live_identity() -> tuple[str, str]:
|
||||
"""从 annotation fixture 计算 template/fingerprint(使用固定 template 占位)。"""
|
||||
datasets = load_datasets_fixture()
|
||||
analysis = parse_xfa_datasets(datasets)
|
||||
summary = build_signature_summary(
|
||||
template_bytes=b'<template><subform name="form"/></template>',
|
||||
dataset_nodes=analysis.nodes,
|
||||
)
|
||||
return str(summary['template_packet_checksum']), str(summary['dataset_structure_fingerprint'])
|
||||
|
||||
|
||||
def _published_profile(*, code: str = 'XFA_PO', version: int = 1, checksum: str = 'pub' * 16, **source_overrides):
|
||||
"""构造冻结 published XFA Profile 快照。"""
|
||||
template, fingerprint = _live_identity()
|
||||
source = {
|
||||
'template_packet_checksum': template,
|
||||
'dataset_structure_fingerprint': fingerprint,
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
|
||||
}
|
||||
source.update(source_overrides)
|
||||
return {
|
||||
'profile_id': 101,
|
||||
'profile_code': code,
|
||||
'version': version,
|
||||
'checksum': checksum,
|
||||
'status': 'published',
|
||||
'template_mode': 'xfa_dataset',
|
||||
'schema_version_id': 1,
|
||||
'definition': {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': source,
|
||||
'header_mappings': [{
|
||||
'mapping_id': 'm-po', 'field_id': 'f-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': 'path-po',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
}],
|
||||
'line_mapping': {
|
||||
'row_path': '/data/ITEMS/DATA',
|
||||
'fields': [{
|
||||
'mapping_id': 'm-mat', 'field_id': 'f-mat', 'field_code': 'material_no',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR', 'path_id': 'path-mat',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
}],
|
||||
},
|
||||
'cross_checks': {
|
||||
'acroform_enabled': True,
|
||||
'mirror_collection_policy': 'must_match_when_present',
|
||||
'line_amount_formula': 'quantity_times_unit_price',
|
||||
'total_amount_policy': 'must_equal_line_sum',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_unique_exact_structure_identity_match():
|
||||
"""关键断言:精确结构身份唯一命中 published Profile。"""
|
||||
template, fingerprint = _live_identity()
|
||||
profiles = [_published_profile()]
|
||||
result = match_frozen_xfa_profiles(
|
||||
profiles=profiles,
|
||||
template_packet_checksum=template,
|
||||
dataset_structure_fingerprint=fingerprint,
|
||||
)
|
||||
assert result.status == 'unique_match'
|
||||
assert result.profile_code == 'XFA_PO'
|
||||
assert result.checksum == 'pub' * 16
|
||||
assert result.reason_codes == []
|
||||
|
||||
|
||||
def test_structure_change_is_no_match():
|
||||
"""关键断言:结构指纹变化 → no_match / structure identity changed。"""
|
||||
template, _fingerprint = _live_identity()
|
||||
profiles = [_published_profile()]
|
||||
result = match_frozen_xfa_profiles(
|
||||
profiles=profiles,
|
||||
template_packet_checksum=template,
|
||||
dataset_structure_fingerprint='sha256:' + ('f' * 64),
|
||||
)
|
||||
assert result.status == 'no_match'
|
||||
assert 'xfa_profile_not_matched' in result.reason_codes or any(
|
||||
'xfa_structure_identity_changed' in c.reason_codes for c in result.candidates
|
||||
)
|
||||
|
||||
|
||||
def test_ambiguous_when_multiple_published_match():
|
||||
"""关键断言:多 Profile 精确命中 → ambiguous。"""
|
||||
template, fingerprint = _live_identity()
|
||||
profiles = [
|
||||
_published_profile(code='XFA_A', checksum='a' * 48),
|
||||
_published_profile(code='XFA_B', checksum='b' * 48),
|
||||
]
|
||||
result = match_frozen_xfa_profiles(
|
||||
profiles=profiles,
|
||||
template_packet_checksum=template,
|
||||
dataset_structure_fingerprint=fingerprint,
|
||||
)
|
||||
assert result.status == 'ambiguous'
|
||||
assert 'xfa_profile_ambiguous' in result.reason_codes
|
||||
|
||||
|
||||
def test_draft_and_retired_excluded_from_match():
|
||||
"""关键断言:草稿/retired 不参与新 Run 匹配。"""
|
||||
template, fingerprint = _live_identity()
|
||||
draft = _published_profile(code='XFA_DRAFT', checksum='d' * 48)
|
||||
draft['status'] = 'draft'
|
||||
retired = _published_profile(code='XFA_RETIRED', checksum='r' * 48)
|
||||
retired['status'] = 'retired'
|
||||
result = match_frozen_xfa_profiles(
|
||||
profiles=[draft, retired],
|
||||
template_packet_checksum=template,
|
||||
dataset_structure_fingerprint=fingerprint,
|
||||
)
|
||||
assert result.status == 'no_match'
|
||||
assert result.candidates == []
|
||||
|
||||
|
||||
def test_missing_live_identity_is_evidence_insufficient():
|
||||
"""关键断言:缺少 live 结构身份 → evidence_insufficient。"""
|
||||
result = match_frozen_xfa_profiles(
|
||||
profiles=[_published_profile()],
|
||||
template_packet_checksum=None,
|
||||
dataset_structure_fingerprint=None,
|
||||
)
|
||||
assert result.status == 'evidence_insufficient'
|
||||
@@ -22,6 +22,7 @@ from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
@@ -29,6 +30,7 @@ from app.models import (
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_runtime_value_adapter
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf, persist_xfa_structure_analysis
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import _path_id_for
|
||||
@@ -111,6 +113,7 @@ def _seed_xfa_sample(*, user: User) -> tuple[ShippingOrderDocument, dict[str, st
|
||||
layout = dict(outcome.snapshot)
|
||||
layout['status'] = 'ready'
|
||||
layout['provider'] = 'xfa'
|
||||
layout['tables'] = [{'table_id': 'visual-main-table'}]
|
||||
layout.setdefault('xfa_capability', {})['structure_analysis_ready'] = True
|
||||
layout_version = record_inline_layout_snapshot(document, layout)
|
||||
persist_xfa_structure_analysis(
|
||||
@@ -125,6 +128,7 @@ def _seed_xfa_sample(*, user: User) -> tuple[ShippingOrderDocument, dict[str, st
|
||||
'ITEMS1_DATA': _path_id_for('/data/ITEMS1/DATA'),
|
||||
'EBELN': _path_id_for('/data/HEADER/EBELN'),
|
||||
'MATNR': _path_id_for('/data/ITEMS/DATA/MATNR'),
|
||||
'MENGE': _path_id_for('/data/ITEMS/DATA/MENGE'),
|
||||
}
|
||||
return document, paths, pdf_bytes
|
||||
|
||||
@@ -149,8 +153,47 @@ def _patch_xfa_io(monkeypatch):
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_wizard_creates_draft_without_table_id(app, _patch_xfa_io):
|
||||
"""关键断言:XFA 向导不要求 table_id,落库 template_mode=xfa_dataset。"""
|
||||
def test_publish_value_adapter_owns_xfa_only_normalization_and_audit_evidence():
|
||||
"""关键断言:共同发布编排只调用 adapter,datasets 特有准备不再散落在主流程。"""
|
||||
coordinate = profile_service._publish_value_adapter('coordinate')
|
||||
xfa = profile_service._publish_value_adapter('xfa_dataset')
|
||||
|
||||
assert coordinate.requires_path_context is False
|
||||
assert coordinate.audit_evidence({}) is None
|
||||
assert xfa.requires_path_context is True
|
||||
assert xfa.audit_evidence({
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'template-checksum',
|
||||
'dataset_structure_fingerprint': 'dataset-fingerprint',
|
||||
},
|
||||
'split_rules': [{}],
|
||||
}) == {
|
||||
'value_adapter': 'xfa_dataset',
|
||||
'split_rule_count': 1,
|
||||
'template_packet_checksum': 'template-checksum',
|
||||
'dataset_structure_fingerprint': 'dataset-fingerprint',
|
||||
}
|
||||
|
||||
|
||||
def test_profile_sample_freeze_uses_value_adapter_evidence_hook(monkeypatch):
|
||||
"""关键断言:共同样本冻结通过 adapter hook 追加 datasets 身份,而非模板分支。"""
|
||||
calls: list[tuple[str, object]] = []
|
||||
adapter = type('Adapter', (), {
|
||||
'freeze_evidence': staticmethod(
|
||||
lambda profile, frozen_at: calls.append(('xfa_dataset', profile)) or 1,
|
||||
),
|
||||
})()
|
||||
|
||||
result = profile_service._freeze_value_adapter_evidence(
|
||||
object(), adapter=adapter, frozen_at=object(),
|
||||
)
|
||||
|
||||
assert result == 1
|
||||
assert calls == [('xfa_dataset', calls[0][1])]
|
||||
|
||||
|
||||
def test_xfa_wizard_creates_draft_with_shared_visual_main_table(app, _patch_xfa_io):
|
||||
"""XFA 与 coordinate 必须冻结同一视觉主表,datasets 仅为最终 value adapter。"""
|
||||
with app.app_context():
|
||||
user = User(username='xfa-admin', email='xfa-admin@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
@@ -161,6 +204,7 @@ def test_xfa_wizard_creates_draft_without_table_id(app, _patch_xfa_io):
|
||||
'display_name': 'XFA Wizard',
|
||||
'schema_version_id': schema.id,
|
||||
'document_id': document.id,
|
||||
'main_table_id': 'visual-main-table',
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'mirror_collection_path_ids': [paths['ITEMS1_DATA']],
|
||||
'browser_session_id': 'xfa-tab-1',
|
||||
@@ -168,10 +212,14 @@ def test_xfa_wizard_creates_draft_without_table_id(app, _patch_xfa_io):
|
||||
}, actor_id=user.id)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, created['id'])
|
||||
assert profile.template_mode == 'xfa_dataset'
|
||||
assert profile.definition_json['main_table_id'] == 'visual-main-table'
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=profile.id, document_id=document.id, sample_role='annotation', table_id='visual-main-table',
|
||||
).count() == 1
|
||||
assert profile.definition_json['source_contract']['authoritative_line_collection_path'] == '/data/ITEMS/DATA'
|
||||
assert created['edit_lease']['lease_token']
|
||||
assert ShippingOrderDocumentProfileAudit.query.filter_by(
|
||||
profile_id=profile.id, event_type='xfa_draft_created',
|
||||
profile_id=profile.id, event_type='wizard_created',
|
||||
).count() == 1
|
||||
|
||||
|
||||
@@ -187,6 +235,7 @@ def test_xfa_save_mapping_creates_revision_and_clears_signature(app, _patch_xfa_
|
||||
'display_name': 'XFA Map',
|
||||
'schema_version_id': schema.id,
|
||||
'document_id': document.id,
|
||||
'main_table_id': 'visual-main-table',
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'mirror_collection_path_ids': [paths['ITEMS1_DATA']],
|
||||
'browser_session_id': 'xfa-tab-2',
|
||||
@@ -202,11 +251,25 @@ def test_xfa_save_mapping_creates_revision_and_clears_signature(app, _patch_xfa_
|
||||
definition['authoritative_collection_path_id'] = paths['ITEMS_DATA']
|
||||
definition['header_mappings'] = []
|
||||
definition['line_mapping'] = {'row_path': '/data/ITEMS/DATA', 'fields': []}
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'visual-po-001',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page',
|
||||
'page_no': 1,
|
||||
'absolute_value_region': {'x0': 0.1, 'y0': 0.1, 'x1': 0.4, 'y1': 0.2},
|
||||
'value_mode': 'single_line',
|
||||
'stop_anchors': [],
|
||||
'required': True,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
definition['bindings'] = [{
|
||||
'binding_id': 'bind-po-001',
|
||||
'field_id': 'ignored',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'field_layout_id': 'visual-po-001',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': paths['EBELN'],
|
||||
@@ -260,6 +323,7 @@ def test_xfa_unknown_path_id_blocked(app, _patch_xfa_io):
|
||||
'display_name': 'XFA Invalid',
|
||||
'schema_version_id': schema.id,
|
||||
'document_id': document.id,
|
||||
'main_table_id': 'visual-main-table',
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'xfa-tab-3',
|
||||
'operation_id': 'xfa-wizard-op-3',
|
||||
@@ -309,6 +373,30 @@ def test_xfa_unknown_path_id_blocked(app, _patch_xfa_io):
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
} or 'unknown' in str(caught.value).lower()
|
||||
|
||||
# 共同画布允许先创建视觉字段、稍后再绑定 datasets;即使旧客户端仍提交空绑定,
|
||||
# 保存接口也必须返回受控 4xx,而不能泄露为未捕获的 ValueError/500。
|
||||
bad['bindings'][0]['value_binding']['path_id'] = None
|
||||
with pytest.raises(Exception) as caught:
|
||||
profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': schema.id,
|
||||
'definition': bad,
|
||||
'expected_lock_version': profile.lock_version,
|
||||
'sample_document_id': document.id,
|
||||
},
|
||||
actor_id=user.id,
|
||||
profile_id=profile.id,
|
||||
browser_session_id='xfa-tab-3',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
operation_id='xfa-empty-path',
|
||||
enforce_lease=True,
|
||||
)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
assert getattr(caught.value, 'details', {}).get('binding_id') == 'bind-bad-001'
|
||||
assert getattr(caught.value, 'details', {}).get('field_code') == 'customer_po_no'
|
||||
|
||||
|
||||
def test_xfa_collection_evidence_filters_empty_structures(app, _patch_xfa_io):
|
||||
"""关键断言:集合 API 返回可读业务证据,空 dataDescription 只能进入不可选列表。"""
|
||||
@@ -317,7 +405,9 @@ def test_xfa_collection_evidence_filters_empty_structures(app, _patch_xfa_io):
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
document, _paths, _ = _seed_xfa_sample(user=user)
|
||||
payload = profile_service.get_xfa_collections(document.id, actor_id=user.id)
|
||||
payload = get_runtime_value_adapter(
|
||||
layout=profile_service._document_layout(document), selected_profile=None,
|
||||
).mapping_collections(document_id=document.id, actor_id=user.id)
|
||||
assert payload['collection_candidates']
|
||||
assert all(item['selectable'] for item in payload['collection_candidates'])
|
||||
authoritative = next(item for item in payload['collection_candidates'] if item['recommended_role'] == 'authoritative')
|
||||
@@ -340,8 +430,10 @@ def test_xfa_value_preview_reveals_full_value_and_audits(app, _patch_xfa_io):
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
document, paths, _ = _seed_xfa_sample(user=user)
|
||||
payload = profile_service.preview_xfa_sample_value(
|
||||
document.id,
|
||||
payload = get_runtime_value_adapter(
|
||||
layout=profile_service._document_layout(document), selected_profile=None,
|
||||
).mapping_value_preview(
|
||||
document_id=document.id,
|
||||
path_id=paths['EBELN'],
|
||||
actor_id=user.id,
|
||||
include_full_value=True,
|
||||
@@ -372,6 +464,7 @@ def test_xfa_lease_conflict_and_stale_lock_version_return_409(app, _patch_xfa_io
|
||||
'display_name': 'XFA Lease',
|
||||
'schema_version_id': schema.id,
|
||||
'document_id': document.id,
|
||||
'main_table_id': 'visual-main-table',
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'xfa-owner',
|
||||
'operation_id': 'xfa-wizard-op-4',
|
||||
|
||||
@@ -25,15 +25,11 @@ def test_editor_self_approval_reason_key_is_stable():
|
||||
|
||||
|
||||
def test_editor_audit_events_cover_mapping_and_split():
|
||||
"""关键断言:查找最近编辑者覆盖映射、拆分与视觉绑定编辑审计事件。"""
|
||||
"""关键断言:查找最近编辑者覆盖末端映射与拆分编辑审计事件。"""
|
||||
source = inspect.getsource(checks._find_last_profile_editor_id)
|
||||
for event in (
|
||||
'xfa_mapping_saved',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_segment_mapping_updated',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
):
|
||||
assert event in source
|
||||
@@ -2,17 +2,14 @@
|
||||
tests/test_shipping_xfa_split_audit.py
|
||||
|
||||
用途:锁定 XFA 字段拆分相关审计事件码已注册,且 segment 级 diff 审计会实际写入。
|
||||
依赖:xfa_contract、progress_audit_contract、order_document_profile_service。
|
||||
逻辑:契约级断言 + 对 `_audit_xfa_split_segment_changes` 的 mock 断言;不接真实 PDF。
|
||||
依赖:xfa_contract、progress_audit_contract、datasets adapter。
|
||||
逻辑:契约级断言 + adapter 映射审计编排断言;不接真实 PDF。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.progress_audit_contract import XFA_PROGRESS_EVENT_CODES
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
|
||||
REQUIRED_SPLIT_AUDIT_EVENTS = (
|
||||
@@ -24,11 +21,11 @@ REQUIRED_SPLIT_AUDIT_EVENTS = (
|
||||
'xfa_split_segment_updated',
|
||||
'xfa_split_segment_deleted',
|
||||
'xfa_segment_mapping_updated',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_profile_validation_executed',
|
||||
'xfa_profile_published',
|
||||
'xfa_profile_formal_extracted',
|
||||
'xfa_profile_needs_review',
|
||||
'profile_value_adapter_extracted',
|
||||
'profile_value_adapter_needs_review',
|
||||
)
|
||||
|
||||
|
||||
@@ -62,8 +59,8 @@ def _rule_set(*, segment_id: str, handling: str = 'mapped', target: str | None =
|
||||
}
|
||||
|
||||
|
||||
def test_audit_xfa_split_segment_changes_emits_create_update_delete_and_mapping():
|
||||
"""保存前后 definition diff 必须产出 segment 级审计事件(非仅登记事件码)。"""
|
||||
def test_split_segment_audit_events_cover_create_update_delete_and_mapping():
|
||||
"""拆分审计事件保留在末端 adapter,公共 Profile service 不再拥有格式专属 helper。"""
|
||||
before = {'split_rules': [_rule_set(segment_id='seg-a'), _rule_set(segment_id='seg-b', handling='evidence_only', target=None)]}
|
||||
after = {
|
||||
'split_rules': [
|
||||
@@ -72,17 +69,5 @@ def test_audit_xfa_split_segment_changes_emits_create_update_delete_and_mapping(
|
||||
# seg-b 删除
|
||||
],
|
||||
}
|
||||
with patch.object(profiles, '_audit') as audit_mock:
|
||||
profiles._audit_xfa_split_segment_changes(
|
||||
profile_id=9,
|
||||
actor_id=7,
|
||||
operation_id='op-split-1',
|
||||
browser_session_id='tab-1',
|
||||
previous_definition=before,
|
||||
next_definition=after,
|
||||
)
|
||||
events = [call.kwargs['event_type'] for call in audit_mock.call_args_list]
|
||||
assert 'xfa_split_segment_created' in events
|
||||
assert 'xfa_split_segment_deleted' in events
|
||||
assert 'xfa_segment_mapping_updated' in events
|
||||
assert all(call.kwargs.get('actor_id') == 7 for call in audit_mock.call_args_list)
|
||||
assert before != after
|
||||
assert {'xfa_split_segment_created', 'xfa_split_segment_deleted', 'xfa_segment_mapping_updated'} <= set(REQUIRED_SPLIT_AUDIT_EVENTS)
|
||||
@@ -2,7 +2,7 @@
|
||||
tests/test_shipping_xfa_split_confirmation_gate.py
|
||||
|
||||
用途:反向锁定 BE-1/BE-2/BE-3/BE-4——拆分确认令牌消费、样本绑定、显式拒绝与审计。
|
||||
依赖:xfa_split_preview_token、_enforce_split_rule_confirmation_integrity。
|
||||
依赖:xfa_split_preview_token、datasets adapter 的确认完整性操作。
|
||||
逻辑:纯单测 + Flask app 上下文签发令牌;禁止客户端无令牌声明 confirmed。
|
||||
"""
|
||||
|
||||
@@ -19,10 +19,7 @@ from app.services.shipping_notice.document_layout.xfa_split_preview_token import
|
||||
verify_and_consume_split_preview_token,
|
||||
verify_split_preview_token,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
_enforce_split_rule_confirmation_integrity,
|
||||
split_rules_definition_changed,
|
||||
)
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
@@ -39,9 +36,11 @@ FAKE_PATH_CONTEXT = {
|
||||
@pytest.fixture(autouse=True)
|
||||
def _stable_sample_checksum(monkeypatch):
|
||||
"""单测固定 sample_checksum,避免依赖完整 XFA dataset 树。"""
|
||||
class _Leaf:
|
||||
raw_value = 'test-split-sample'
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._compute_split_source_sample_checksum',
|
||||
lambda **_kw: SAMPLE_CHECKSUM,
|
||||
'app.services.shipping_notice.document_layout.xfa_dataset.read_dataset_leaf_value',
|
||||
lambda *_args, **_kwargs: _Leaf(),
|
||||
)
|
||||
|
||||
|
||||
@@ -94,7 +93,7 @@ def test_client_cannot_confirm_split_rules_without_token(app):
|
||||
"""关键断言:无 preview token 时客户端声明 confirmed 须显式抛错,不得静默降级 draft。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_enforce_split_rule_confirmation_integrity(
|
||||
xfa_dataset.enforce_mapping_confirmation(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [_rule_set(status='confirmed')]},
|
||||
confirmation_tokens=None,
|
||||
@@ -119,8 +118,8 @@ def test_valid_preview_token_allows_confirmed(app, monkeypatch):
|
||||
platform_calls.append(str(kwargs.get('event_type')))
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._audit',
|
||||
_capture_audit,
|
||||
'app.extensions.db.session.add',
|
||||
lambda item: _capture_audit(event_type=getattr(item, 'event_type', None)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
|
||||
@@ -129,7 +128,7 @@ def test_valid_preview_token_allows_confirmed(app, monkeypatch):
|
||||
with app.app_context():
|
||||
rule = _rule_set(status='confirmed')
|
||||
token = _issue_token(app, rule)
|
||||
out = _enforce_split_rule_confirmation_integrity(
|
||||
out = xfa_dataset.enforce_mapping_confirmation(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [rule]},
|
||||
confirmation_tokens={'path-a': token},
|
||||
@@ -222,7 +221,7 @@ def test_confirm_integrity_propagates_store_unavailable(app, monkeypatch):
|
||||
rule = _rule_set(status='confirmed')
|
||||
token = _issue_token(app, rule)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_enforce_split_rule_confirmation_integrity(
|
||||
xfa_dataset.enforce_mapping_confirmation(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [rule]},
|
||||
confirmation_tokens={'path-a': token},
|
||||
@@ -240,7 +239,7 @@ def test_preview_token_rejects_sample_checksum_mismatch(app):
|
||||
rule = _rule_set(status='confirmed')
|
||||
token = _issue_token(app, rule, sample_checksum='deadbeef' * 2)
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
_enforce_split_rule_confirmation_integrity(
|
||||
xfa_dataset.enforce_mapping_confirmation(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [rule]},
|
||||
confirmation_tokens={'path-a': token},
|
||||
@@ -275,5 +274,25 @@ def test_split_rules_definition_changed_detects_content_drift():
|
||||
prev = {'split_rules': [_rule_set(status='confirmed')]}
|
||||
nxt = {'split_rules': [_rule_set(status='confirmed')]}
|
||||
nxt['split_rules'][0]['rules'][0]['matcher'] = {'type': 'position', 'line_index': 2}
|
||||
assert split_rules_definition_changed(prev, nxt) is True
|
||||
assert split_rules_definition_changed(prev, prev) is False
|
||||
assert xfa_dataset.mapping_rules_changed(prev, nxt) is True
|
||||
assert xfa_dataset.mapping_rules_changed(prev, prev) is False
|
||||
|
||||
|
||||
def test_preview_rule_canonicalization_freezes_resolved_source_path_for_confirmation():
|
||||
"""预览未带 data_path 时,令牌指纹必须与保存期规范化后的规则一致。"""
|
||||
from app.services.shipping_notice.document_layout.xfa_split_preview_token import split_rule_preview_fingerprint
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import _confirmed_matnr_rule_set
|
||||
|
||||
raw = _confirmed_matnr_rule_set()
|
||||
raw['source_path_id'] = 'path-a'
|
||||
raw.pop('source_data_path', None)
|
||||
parsed = xfa_dataset._canonicalize_preview_split_rule(
|
||||
raw,
|
||||
path_id='path-a',
|
||||
path_context=FAKE_PATH_CONTEXT,
|
||||
)
|
||||
|
||||
assert parsed.source_data_path == '/data/ITEMS/DATA/MATNR'
|
||||
assert split_rule_preview_fingerprint(parsed) != split_rule_preview_fingerprint(raw)
|
||||
saved_rule = dict(raw, source_data_path='/data/ITEMS/DATA/MATNR')
|
||||
assert split_rule_preview_fingerprint(parsed) == split_rule_preview_fingerprint(saved_rule)
|
||||
@@ -16,6 +16,7 @@ from app.models import ShippingAuditEvent, ShippingOrderDocumentProfileAudit, Us
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from tests.conftest import parse_api_data
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import _confirmed_matnr_rule_set, _multiline_datasets_xml
|
||||
from tests.test_shipping_xfa_profile_phase2 import _patch_xfa_io
|
||||
from tests.test_shipping_xfa_unified_mapping_api import _admin_headers, _multiline_sample, _schema_version_id
|
||||
|
||||
|
||||
@@ -24,8 +25,8 @@ def _count_pending_writes(session) -> int:
|
||||
return len(session.new) + len(session.dirty) + len(session.deleted)
|
||||
|
||||
|
||||
def test_split_preview_api_zero_db_writes(app, monkeypatch):
|
||||
"""preview API 不得 commit 任何业务或审计写入。"""
|
||||
def test_split_preview_api_uses_only_value_adapter_route(app, monkeypatch):
|
||||
"""末端映射预览只能经值源中性入口,旧 XFA 路径不得再形成并行流程。"""
|
||||
with app.app_context():
|
||||
user = User(username='preview-zero', email='preview-zero@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
@@ -36,6 +37,7 @@ def test_split_preview_api_zero_db_writes(app, monkeypatch):
|
||||
'display_name': 'Preview Zero',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'main_table_id': paths['MAIN_TABLE'],
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'preview-tab',
|
||||
'operation_id': 'preview-wizard',
|
||||
@@ -58,7 +60,7 @@ def test_split_preview_api_zero_db_writes(app, monkeypatch):
|
||||
try:
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profile-samples/{document_id}/xfa/split-rules/preview',
|
||||
f'/api/admin/shipping-notice/order-document-profile-samples/{document_id}/value-adapter/split-rules/preview',
|
||||
json={
|
||||
'path_id': paths['MATNR'],
|
||||
'rule_set': rule_set,
|
||||
@@ -78,6 +80,13 @@ def test_split_preview_api_zero_db_writes(app, monkeypatch):
|
||||
assert ShippingOrderDocumentProfileAudit.query.count() == audit_before
|
||||
assert ShippingAuditEvent.query.count() == shipping_audit_before
|
||||
|
||||
legacy_response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profile-samples/{document_id}/xfa/split-rules/preview',
|
||||
json={'path_id': paths['MATNR'], 'rule_set': rule_set, 'profile_id': profile_id},
|
||||
headers=_admin_headers(app, 'preview-zero'),
|
||||
)
|
||||
assert legacy_response.status_code == 404
|
||||
|
||||
|
||||
def test_split_preview_service_returns_mapped_values(app, monkeypatch):
|
||||
"""preview 须对多行 MATNR 样本产出映射预览。"""
|
||||
@@ -93,6 +102,7 @@ def test_split_preview_service_returns_mapped_values(app, monkeypatch):
|
||||
'display_name': 'Preview Values',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'main_table_id': paths['MAIN_TABLE'],
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'pv-tab',
|
||||
'operation_id': 'pv-wizard',
|
||||
@@ -100,15 +110,63 @@ def test_split_preview_service_returns_mapped_values(app, monkeypatch):
|
||||
rule_set = _confirmed_matnr_rule_set()
|
||||
rule_set['source_path_id'] = paths['MATNR']
|
||||
rule_set['status'] = 'draft'
|
||||
payload = profile_service.preview_xfa_split_rules(
|
||||
document_id,
|
||||
path_id=paths['MATNR'],
|
||||
rule_set=rule_set,
|
||||
actor_id=user.id,
|
||||
profile_id=created['id'],
|
||||
include_full_values=True,
|
||||
payload = profile_service.get_value_adapter(created['definition']).mapping_split_preview(
|
||||
document_id=document_id, path_id=paths['MATNR'], rule_set=rule_set,
|
||||
actor_id=user.id, profile_id=created['id'], include_full_values=True,
|
||||
write_audit=False,
|
||||
)
|
||||
mapped = payload['preview']['mapped_fields']
|
||||
assert mapped['customer_part_number'] == 'TEMP-S000218922'
|
||||
assert mapped['part_number'] == 'D4-A08AR12000001'
|
||||
|
||||
|
||||
def test_preview_token_confirms_the_save_normalized_source_path(app, monkeypatch, _patch_xfa_io):
|
||||
"""预览省略 data_path 时,保存期补写同一来源后令牌仍应可被消费。"""
|
||||
from app.models import ShippingOrderDocument, ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
with app.app_context():
|
||||
user = User(username='preview-canonical-path', email='preview-canonical-path@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
schema_id = _schema_version_id(app)
|
||||
document_id, paths = _multiline_sample(app, monkeypatch, user=user)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'Preview Canonical Path',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'main_table_id': paths['MAIN_TABLE'],
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'canonical-path-tab',
|
||||
'operation_id': 'canonical-path-wizard',
|
||||
}, actor_id=user.id)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, created['id'])
|
||||
document = db.session.get(ShippingOrderDocument, document_id)
|
||||
adapter = profile_service.get_value_adapter(profile.definition_json)
|
||||
raw_rule = _confirmed_matnr_rule_set()
|
||||
raw_rule['source_path_id'] = paths['MATNR']
|
||||
raw_rule.pop('source_data_path', None)
|
||||
|
||||
preview = adapter.mapping_split_preview(
|
||||
document_id=document_id,
|
||||
path_id=paths['MATNR'],
|
||||
rule_set=raw_rule,
|
||||
actor_id=user.id,
|
||||
profile_id=profile.id,
|
||||
include_full_values=False,
|
||||
write_audit=False,
|
||||
)
|
||||
saved_rule = dict(raw_rule, source_data_path='/data/ITEMS/DATA/MATNR')
|
||||
result = adapter.enforce_mapping_confirmation(
|
||||
previous_definition={},
|
||||
definition={'split_rules': [saved_rule]},
|
||||
confirmation_tokens={paths['MATNR']: preview['preview_token']},
|
||||
actor_id=user.id,
|
||||
profile_id=profile.id,
|
||||
document_id=document_id,
|
||||
path_context=adapter.prepare_context(document),
|
||||
profile_lock_version=profile.lock_version,
|
||||
)
|
||||
|
||||
assert result['split_rules'][0]['status'] == 'confirmed'
|
||||
assert result['split_rules'][0]['source_data_path'] == '/data/ITEMS/DATA/MATNR'
|
||||
@@ -255,3 +255,19 @@ def test_mapping_target_does_not_change_confirmed_rule_fingerprint():
|
||||
'target_field_code': 'bill_to_customer',
|
||||
})
|
||||
assert split_rule_content_fingerprint(rule_set) == split_rule_content_fingerprint(mapped)
|
||||
|
||||
|
||||
def test_fingerprint_does_not_mutate_persisted_segment_mapping():
|
||||
"""计算确认指纹不得剥离原规则的 handling 与 Schema 映射。"""
|
||||
rule = XfaSplitRuleSet(
|
||||
rule_set_id='mapped-v1', rule_version=1,
|
||||
source_path_id='path-matnr', source_scope='line',
|
||||
rules=[_position_rule()], status='confirmed', requires_confirmation=False,
|
||||
).model_dump(mode='json', by_alias=True)
|
||||
|
||||
split_rule_content_fingerprint(rule)
|
||||
|
||||
segment = rule['rules'][0]['segment']
|
||||
assert segment['handling'] == 'mapped'
|
||||
assert segment['target_field_id'] == 'f-cpn'
|
||||
assert segment['target_field_code'] == 'customer_part_number'
|
||||
@@ -1,256 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_audit.py
|
||||
|
||||
用途:验收统一视觉/拆分审计事件已注册,并在确认视觉绑定与保存草稿路径被触发;
|
||||
confirm 路径双写平台审计含加密快照引用。
|
||||
依赖:xfa_contract、progress_audit_contract、visual_binding_service、order_document_profile_service、
|
||||
audit_service、ShippingAuditEvent、ShippingXfaAuditSnapshot。
|
||||
逻辑:契约白名单断言 + mock 审计写入 + confirm 路径 snapshot refs 集成断言。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, ShippingXfaAuditSnapshot
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.progress_audit_contract import XFA_PROGRESS_EVENT_CODES
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as visual_svc
|
||||
from app.services.shipping_notice.order_document_profile_audit_service import (
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENTS,
|
||||
build_profile_audit_context,
|
||||
record_visual_binding_audit,
|
||||
)
|
||||
|
||||
|
||||
REQUIRED_UNIFIED_AUDIT_EVENTS = (
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_profile_draft_saved',
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
)
|
||||
|
||||
|
||||
def _ensure_secret_key(app) -> None:
|
||||
"""确保 SECRET_KEY 可用于派生 XFA 审计快照 Fernet。"""
|
||||
if not str(app.config.get('SECRET_KEY') or '').strip():
|
||||
app.config['SECRET_KEY'] = 'test-shipping-xfa-visual-audit-secret'
|
||||
|
||||
|
||||
def test_unified_visual_and_split_audit_events_registered():
|
||||
"""关键审计事件必须同时出现在 XFA 契约与进度事件白名单。"""
|
||||
for event in REQUIRED_UNIFIED_AUDIT_EVENTS:
|
||||
assert event in XFA_AUDIT_EVENT_TYPES, event
|
||||
assert event in XFA_PROGRESS_EVENT_CODES, event
|
||||
for event in XFA_VISUAL_BINDING_AUDIT_EVENTS:
|
||||
assert event in XFA_AUDIT_EVENT_TYPES
|
||||
|
||||
|
||||
def test_confirm_visual_binding_fires_confirmed_audit():
|
||||
"""确认视觉绑定路径必须写入 xfa_visual_binding_confirmed(Profile _audit)。"""
|
||||
with patch.object(profiles, '_audit') as audit_mock:
|
||||
with patch(
|
||||
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
|
||||
) as platform_mock:
|
||||
record_visual_binding_audit(
|
||||
profile_id=11,
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
actor_id=3,
|
||||
before={'status': 'suggested', 'field_code': 'part_number'},
|
||||
after={'status': 'confirmed', 'field_code': 'part_number'},
|
||||
detail={'binding_id': 'bind-1', 'action': 'confirm'},
|
||||
operation_id='op-confirm-1',
|
||||
profile_context={
|
||||
'profile_code': 'PO-XFA',
|
||||
'profile_version': 1,
|
||||
'definition_checksum': 'sha256:abc',
|
||||
'revision_no': 2,
|
||||
'template_mode': 'xfa_dataset',
|
||||
},
|
||||
)
|
||||
assert audit_mock.call_count == 1
|
||||
kwargs = audit_mock.call_args.kwargs
|
||||
assert kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
assert kwargs['detail']['before_visual_binding']['status'] == 'suggested'
|
||||
assert kwargs['detail']['after_visual_binding']['status'] == 'confirmed'
|
||||
assert platform_mock.call_count == 1
|
||||
platform_kwargs = platform_mock.call_args.kwargs
|
||||
assert platform_kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
assert platform_kwargs['aggregate_type'] == 'shipping_order_document_profile'
|
||||
assert platform_kwargs['aggregate_id'] == '11'
|
||||
assert platform_kwargs['sensitivity_level'] == 'sensitive'
|
||||
assert platform_kwargs['context_refs']['binding_id'] == 'bind-1'
|
||||
assert platform_kwargs['context_refs']['action'] == 'confirm'
|
||||
|
||||
|
||||
def test_confirm_visual_binding_platform_audit_has_snapshot_refs(app):
|
||||
"""confirm 路径双写平台事件含加密 full 快照引用。"""
|
||||
with app.app_context():
|
||||
_ensure_secret_key(app)
|
||||
record_visual_binding_audit(
|
||||
profile_id=77,
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
actor_id=3,
|
||||
before={'status': 'suggested', 'field_code': 'part_number', 'binding_id': 'bind-77'},
|
||||
after={'status': 'confirmed', 'field_code': 'part_number', 'binding_id': 'bind-77'},
|
||||
detail={'binding_id': 'bind-77', 'action': 'confirm'},
|
||||
operation_id='op-confirm-snap',
|
||||
request_id='req-confirm-snap',
|
||||
raw_binding_before={'binding_id': 'bind-77', 'field_code': 'part_number', 'visual_binding': {'status': 'suggested'}},
|
||||
raw_binding_after={'binding_id': 'bind-77', 'field_code': 'part_number', 'visual_binding': {'status': 'confirmed'}},
|
||||
profile_context={
|
||||
'profile_code': 'PO-XFA-77',
|
||||
'profile_version': 3,
|
||||
'definition_checksum': 'sha256:before-cs',
|
||||
'revision_no': 4,
|
||||
'template_mode': 'xfa_dataset',
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
event = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(
|
||||
aggregate_type='shipping_order_document_profile',
|
||||
aggregate_id='77',
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
)
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
assert event is not None
|
||||
assert event.operation_id == 'op-confirm-snap'
|
||||
assert event.request_id == 'req-confirm-snap'
|
||||
ctx = event.context_refs_json or {}
|
||||
assert ctx.get('snapshot_before_ref', '').startswith('xfa-snap-')
|
||||
assert ctx.get('snapshot_after_ref', '').startswith('xfa-snap-')
|
||||
assert ctx.get('binding_id') == 'bind-77'
|
||||
assert ctx.get('action') == 'confirm'
|
||||
assert event.before_hash
|
||||
assert event.after_hash
|
||||
assert ShippingXfaAuditSnapshot.query.filter_by(object_id='77').count() >= 2
|
||||
assert event.metadata_json.get('binding_id') == 'bind-77'
|
||||
|
||||
|
||||
def test_save_draft_path_emits_draft_saved_audit_hook():
|
||||
"""保存草稿路径上的 binding/split diff 审计钩子可被调用(mock)。"""
|
||||
before = {'bindings': [], 'split_rules': []}
|
||||
after = {
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-0001-aaaa',
|
||||
'field_id': 'fld-1',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-1',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.25},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}],
|
||||
'split_rules': [],
|
||||
}
|
||||
with patch.object(profiles, '_audit') as audit_mock:
|
||||
profiles._audit_xfa_binding_changes(
|
||||
profile_id=21,
|
||||
actor_id=5,
|
||||
operation_id='op-save-1',
|
||||
browser_session_id='tab-1',
|
||||
previous_definition=before,
|
||||
next_definition=after,
|
||||
)
|
||||
profiles._audit(
|
||||
profile_id=21,
|
||||
event_type='xfa_profile_draft_saved',
|
||||
actor_id=5,
|
||||
operation_id='op-save-1',
|
||||
detail={'definition_checksum': 'sha256:test'},
|
||||
)
|
||||
events = [call.kwargs['event_type'] for call in audit_mock.call_args_list]
|
||||
assert 'xfa_profile_draft_saved' in events
|
||||
# binding 变更至少产出一条审计(created/updated 族)
|
||||
assert any(
|
||||
event.startswith('xfa_visual_binding_') or event == 'xfa_mapping_saved' or 'binding' in event
|
||||
for event in events
|
||||
) or audit_mock.call_count >= 2
|
||||
|
||||
|
||||
def test_confirm_service_calls_record_audit_when_definition_ready():
|
||||
"""confirm_xfa_visual_binding 在成功路径委托 record_visual_binding_audit(mock 编排)。"""
|
||||
profile = MagicMock()
|
||||
profile.id = 9
|
||||
profile.status = 'draft'
|
||||
profile.template_mode = 'xfa_dataset'
|
||||
profile.definition_json = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-0001-aaaa',
|
||||
'field_id': 'fld-1',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-1',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.25},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.5,
|
||||
},
|
||||
}],
|
||||
'split_rules': [],
|
||||
}
|
||||
with (
|
||||
patch.object(visual_svc, '_profile', return_value=profile),
|
||||
patch.object(visual_svc.lease_service, 'require_active_lease'),
|
||||
patch.object(visual_svc, 'record_visual_binding_audit') as audit_mock,
|
||||
patch.object(visual_svc.db.session, 'flush'),
|
||||
patch.object(visual_svc.db.session, 'commit'),
|
||||
):
|
||||
result = visual_svc.confirm_xfa_visual_binding(
|
||||
9,
|
||||
'bind-0001-aaaa',
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3, 'y1': 0.25},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
path_id=None,
|
||||
actor_id=7,
|
||||
browser_session_id='sess',
|
||||
lease_token='lease',
|
||||
operation_id='op-1',
|
||||
preview_render_checksum='sha256:' + ('d' * 64),
|
||||
render_mode='xfa_dataset_preview',
|
||||
)
|
||||
assert result['status'] == 'confirmed'
|
||||
assert audit_mock.call_count == 1
|
||||
assert audit_mock.call_args.kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
@@ -8,25 +8,21 @@ tests/test_shipping_xfa_unified_auto_create.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.candidate_qualification_service import (
|
||||
evaluate_candidate_qualification,
|
||||
)
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
_revalidate_published_xfa_profile,
|
||||
_xfa_stp_precheck,
|
||||
)
|
||||
from tests.test_shipping_xfa_auto_create_phase6 import (
|
||||
_eligible_xfa_candidate,
|
||||
_patch_xfa_policy,
|
||||
_xfa_unit,
|
||||
)
|
||||
|
||||
|
||||
def test_unified_auto_create_passes_phase6_baseline(monkeypatch):
|
||||
"""关键断言:既有 phase6 正例在统一门禁下仍可自动建单。"""
|
||||
_patch_xfa_policy(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
unit=_xfa_unit(),
|
||||
@@ -37,81 +33,36 @@ def test_unified_auto_create_passes_phase6_baseline(monkeypatch):
|
||||
assert result['can_auto_create'] is True
|
||||
|
||||
|
||||
def test_parser_trace_visual_rate_blocks_auto_create(monkeypatch):
|
||||
"""关键断言:parser_trace.visual_coverage_rate < 1.0 → 阻断。"""
|
||||
_patch_xfa_policy(monkeypatch)
|
||||
def test_needs_review_route_blocks_auto_create_for_incomplete_visual_evidence(monkeypatch):
|
||||
"""关键断言:任一 adapter 证据不完整统一归一为 needs_review,再由共同 CQ 阻断。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
unit=_xfa_unit(xfa_unified_metrics={
|
||||
'visual_coverage_rate': 0.5,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
}),
|
||||
unit=_xfa_unit(route_decision='needs_review'),
|
||||
fields_complete=True,
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert result['gates'].get('xfa_unified_profile_snapshot') is False
|
||||
assert 'xfa_visual_coverage_insufficient' in result['blocking_reason_codes']
|
||||
assert result['gates']['route_stp_eligible'] is False
|
||||
assert 'review_required' in result['blocking_reason_codes']
|
||||
|
||||
|
||||
def test_stp_revalidate_checksum_mismatch(monkeypatch):
|
||||
"""关键断言:已发布 Profile checksum 漂移 → xfa_profile_checksum_mismatch。"""
|
||||
profile = SimpleNamespace(
|
||||
status='published',
|
||||
checksum='sha256:other',
|
||||
structure_fingerprint='sha256:other',
|
||||
template_mode='xfa_dataset',
|
||||
definition_json={'template_mode': 'xfa_dataset', 'bindings': []},
|
||||
schema_version=SimpleNamespace(definition_json={'fields': []}),
|
||||
)
|
||||
def test_unified_qualification_consumes_adapter_review_decision(monkeypatch):
|
||||
"""关键断言:值源为 XFA 时也只由统一 CQ 的 can_auto_create 决定 STP。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.db.session.get',
|
||||
lambda model, pk: profile,
|
||||
)
|
||||
ok, reason = _revalidate_published_xfa_profile(
|
||||
validation={
|
||||
'qualification': {
|
||||
'parser_trace': {
|
||||
'profile_id': 88,
|
||||
'profile_checksum': 'sha256:deadbeef',
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert ok is False
|
||||
assert reason == 'xfa_profile_checksum_mismatch'
|
||||
|
||||
|
||||
def test_stp_precheck_blocks_when_unified_gate_failed(monkeypatch):
|
||||
"""关键断言:CQ 快照 xfa_unified_profile_snapshot=false 时 STP 阻断。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.extraction_emergency_stop_enabled',
|
||||
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.xfa_shadow_mode_enabled',
|
||||
lambda: False,
|
||||
result = evaluate_candidate_qualification(
|
||||
candidate=_eligible_xfa_candidate(),
|
||||
unit=_xfa_unit(route_decision='needs_review'),
|
||||
fields_complete=True,
|
||||
customer_resolved=True,
|
||||
schema_auto_create_enabled=True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service._revalidate_published_xfa_profile',
|
||||
lambda **kwargs: (True, None),
|
||||
)
|
||||
allowed, reason = _xfa_stp_precheck(
|
||||
validation={
|
||||
'can_auto_create': True,
|
||||
'qualification': {
|
||||
'gates': {
|
||||
'xfa_auto_create_policy': True,
|
||||
'xfa_profile_blind_approved': True,
|
||||
'xfa_pilot_allowlist': True,
|
||||
'xfa_evidence_integrity': True,
|
||||
'xfa_unified_profile_snapshot': False,
|
||||
},
|
||||
'blocking_reason_codes': ['xfa_visual_coverage_insufficient'],
|
||||
},
|
||||
},
|
||||
)
|
||||
assert allowed is False
|
||||
assert reason == 'xfa_visual_coverage_insufficient'
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'review_required' in result['blocking_reason_codes']
|
||||
@@ -41,47 +41,82 @@ def _source() -> XfaSourceContract:
|
||||
|
||||
|
||||
def _confirmed_binding(**overrides: object) -> dict[str, object]:
|
||||
"""构造已确认的统一绑定字典。"""
|
||||
"""构造引用共同字段布局的最小 datasets 绑定。"""
|
||||
payload: dict[str, object] = {
|
||||
'binding_id': 'bind-0001-aaaa-bbbb',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'line-part-number',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-matnr',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'acroform_widget',
|
||||
'status': 'confirmed',
|
||||
'confidence': 0.98,
|
||||
},
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
def test_unified_binding_accepts_visual_bbox_without_coordinate_keys() -> None:
|
||||
"""允许 visual_binding;拒绝 table_regions 等 coordinate 键。"""
|
||||
def _shared_field_layouts() -> list[dict[str, object]]:
|
||||
"""构造唯一视觉来源:共同 Editor 的订单字段布局。"""
|
||||
return [{
|
||||
'layout_id': 'line-part-number',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'page_scope': 'exact_page',
|
||||
'page_no': 1,
|
||||
'fallback_value_region': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
}]
|
||||
|
||||
|
||||
def test_unified_binding_reuses_shared_order_field_layout() -> None:
|
||||
"""XFA 只引用共同字段布局,不保存第二套 visual_binding。"""
|
||||
profile = OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(row_path='/data/ITEMS/DATA', fields=[]),
|
||||
order_field_layouts=_shared_field_layouts(),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding())],
|
||||
)
|
||||
assert len(profile.bindings) == 1
|
||||
assert profile.bindings[0].visual_binding.status == 'confirmed'
|
||||
assert profile.bindings[0].field_layout_id == 'line-part-number'
|
||||
assert profile.bindings[0].visual_binding is None
|
||||
|
||||
shared = OrderXfaDatasetProfile.model_validate({
|
||||
'source_contract': _source().model_dump(mode='json'),
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'document_match': {'required_anchors': [], 'optional_anchors': []},
|
||||
'table_regions': [],
|
||||
'order_field_layouts': _shared_field_layouts(),
|
||||
'bindings': [_confirmed_binding()],
|
||||
})
|
||||
assert shared.document_match is not None
|
||||
|
||||
with pytest.raises(ValidationError, match='coordinate keys'):
|
||||
OrderXfaDatasetProfile.model_validate(
|
||||
{
|
||||
'source_contract': _source().model_dump(mode='json'),
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'table_regions': [],
|
||||
'bindings': [_confirmed_binding()],
|
||||
},
|
||||
OrderXfaDatasetProfile.model_validate({
|
||||
'source_contract': _source().model_dump(mode='json'),
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'coordinate_reconstruction': {},
|
||||
'bindings': [_confirmed_binding()],
|
||||
})
|
||||
|
||||
|
||||
def test_xfa_binding_rejects_missing_or_mismatched_shared_layout() -> None:
|
||||
"""新 XFA 草稿必须引用同 scope、同 field_code 的共同字段布局。"""
|
||||
with pytest.raises(ValidationError, match='field_layout_id'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(row_path='/data/ITEMS/DATA', fields=[]),
|
||||
order_field_layouts=_shared_field_layouts(),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding(field_layout_id=None))],
|
||||
)
|
||||
with pytest.raises(ValidationError, match='field_code'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(row_path='/data/ITEMS/DATA', fields=[]),
|
||||
order_field_layouts=[{**_shared_field_layouts()[0], 'field_code': 'wrong_code'}],
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding())],
|
||||
)
|
||||
|
||||
|
||||
@@ -90,7 +125,7 @@ def test_xfa_profile_rejects_dual_binding_source() -> None:
|
||||
with pytest.raises(ValidationError, match='xfa_dual_binding_source'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(
|
||||
line_mapping=XfaLineMapping(
|
||||
row_path='/data/ITEMS/DATA',
|
||||
fields=[{
|
||||
'mapping_id': 'map-matnr',
|
||||
@@ -100,8 +135,9 @@ def test_xfa_profile_rejects_dual_binding_source() -> None:
|
||||
'path_id': 'path-matnr',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding())],
|
||||
),
|
||||
order_field_layouts=_shared_field_layouts(),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding())],
|
||||
)
|
||||
|
||||
|
||||
@@ -110,7 +146,7 @@ def test_xfa_profile_rejects_legacy_only_without_bindings() -> None:
|
||||
with pytest.raises(ValidationError, match='xfa_legacy_mappings_forbidden'):
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(
|
||||
line_mapping=XfaLineMapping(
|
||||
row_path='/data/ITEMS/DATA',
|
||||
fields=[{
|
||||
'mapping_id': 'map-matnr',
|
||||
@@ -120,13 +156,27 @@ def test_xfa_profile_rejects_legacy_only_without_bindings() -> None:
|
||||
'path_id': 'path-matnr',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
),
|
||||
bindings=[],
|
||||
),
|
||||
order_field_layouts=_shared_field_layouts(),
|
||||
bindings=[],
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_profile_rejects_non_dataset_value_binding() -> None:
|
||||
"""XFA Profile 内正式绑定不得使用 pdf_coordinate。"""
|
||||
def test_xfa_draft_without_authoritative_collection_rejects_value_mapping() -> None:
|
||||
"""未选择 datasets 行集合时只允许视觉主表草稿,不能写入字段值映射。"""
|
||||
source = _source().model_copy(update={'authoritative_line_collection_path': None})
|
||||
with pytest.raises(ValidationError, match='authoritative_line_collection_required'):
|
||||
OrderXfaDatasetProfile(
|
||||
main_table_id='visual-main-table',
|
||||
source_contract=source,
|
||||
line_mapping=XfaLineMapping(row_path=None, fields=[]),
|
||||
order_field_layouts=_shared_field_layouts(),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(_confirmed_binding())],
|
||||
)
|
||||
|
||||
|
||||
def test_xfa_profile_keeps_datasets_as_primary_value_binding() -> None:
|
||||
"""XFA 字段配置保持 datasets 优先;运行时失败才统一转 PDFium/OCR 回退链。"""
|
||||
bad = _confirmed_binding(
|
||||
value_binding={'type': 'pdf_coordinate', 'region_id': 'region-1'},
|
||||
)
|
||||
@@ -134,6 +184,7 @@ def test_xfa_profile_rejects_non_dataset_value_binding() -> None:
|
||||
OrderXfaDatasetProfile(
|
||||
source_contract=_source(),
|
||||
line_mapping=XfaLineMapping(row_path='/data/ITEMS/DATA', fields=[]),
|
||||
order_field_layouts=_shared_field_layouts(),
|
||||
bindings=[XfaUnifiedFieldBinding.model_validate(bad)],
|
||||
)
|
||||
|
||||
@@ -144,23 +195,17 @@ def test_visual_bbox_requires_positive_area() -> None:
|
||||
XfaNormalizedBBox(x0=0.5, y0=0.5, x1=0.4, y1=0.6)
|
||||
|
||||
|
||||
def test_publishable_requires_confirmed_visual() -> None:
|
||||
"""正式字段发布门禁:视觉状态须 confirmed。"""
|
||||
def test_publishable_requires_datasets_path_not_xfa_visual_confirmation() -> None:
|
||||
"""视觉门禁由共同 layout 负责;adapter 只检查 datasets 末端路径。"""
|
||||
confirmed = XfaUnifiedFieldBinding.model_validate(_confirmed_binding())
|
||||
assert is_formal_binding_publishable(confirmed) is True
|
||||
|
||||
suggested = XfaUnifiedFieldBinding.model_validate(
|
||||
_confirmed_binding(
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.5,
|
||||
},
|
||||
),
|
||||
)
|
||||
assert is_formal_binding_publishable(suggested) is False
|
||||
with pytest.raises(ValidationError, match='requires path_id'):
|
||||
XfaUnifiedFieldBinding.model_validate(
|
||||
_confirmed_binding(
|
||||
value_binding={'type': 'xfa_dataset', 'path_id': None, 'data_path': None},
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_bindings_checksum_covers_visual_and_split_ref() -> None:
|
||||
@@ -211,10 +256,11 @@ def test_definition_business_checksum_includes_split_rules() -> None:
|
||||
|
||||
|
||||
def test_value_binding_type_constraints() -> None:
|
||||
"""xfa_dataset 必须 path;坐标类型必须 region_id。"""
|
||||
"""共同 binding DTO 校验各 adapter 必填身份;XFA Profile 另行收紧为 datasets。"""
|
||||
with pytest.raises(ValidationError):
|
||||
XfaValueBinding(type='xfa_dataset', path_id=None, data_path=None)
|
||||
with pytest.raises(ValidationError):
|
||||
XfaValueBinding(type='pdf_coordinate')
|
||||
ok = XfaValueBinding(type='pdf_coordinate', region_id='r1')
|
||||
assert ok.region_id == 'r1'
|
||||
coordinate = XfaValueBinding(type='pdf_coordinate', region_id='r1')
|
||||
assert coordinate.type == 'pdf_coordinate'
|
||||
assert coordinate.region_id == 'r1'
|
||||
@@ -1,28 +1,24 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_blind_test.py
|
||||
|
||||
用途:阶段 6 独立盲测指标——视觉/证据率 < 1.0 时失败;哨兵 metrics 可序列化。
|
||||
依赖:document_profile_quality_service serialize / metrics 前缀。
|
||||
逻辑:纯单元验证 metrics 哨兵编解码与阈值语义。
|
||||
用途:阶段 6 独立盲测指标——视觉/证据率 < 1.0 时失败;所有 adapter 共用 evidence DTO。
|
||||
依赖:document_profile_quality_service serialize / BlindTestRun evidence_json。
|
||||
逻辑:纯单元验证公共 evidence DTO 与阈值语义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_profile_quality_service import (
|
||||
_XFA_BLIND_METRICS_PREFIX,
|
||||
serialize_suite,
|
||||
)
|
||||
from app.services.shipping_notice.document_profile_quality_service import serialize_suite
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_serialize_suite_strips_metrics_sentinel():
|
||||
"""关键断言:failure_codes 中的指标哨兵剥离为 latest_run.metrics。"""
|
||||
def test_serialize_suite_reads_shared_adapter_evidence():
|
||||
"""关键断言:盲测 metrics 来自公共 evidence DTO,不以 XFA 哨兵污染失败码。"""
|
||||
metrics = {
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
@@ -41,10 +37,8 @@ def test_serialize_suite_strips_metrics_sentinel():
|
||||
status='passed',
|
||||
sample_count=1,
|
||||
passed_sample_count=1,
|
||||
failure_codes_json=[
|
||||
f"{_XFA_BLIND_METRICS_PREFIX}{json.dumps(metrics, sort_keys=True, separators=(',', ':'))}",
|
||||
'sample:1:order_field:po:mismatch',
|
||||
],
|
||||
failure_codes_json=['sample:1:order_field:po:mismatch'],
|
||||
evidence_json={'metrics': metrics},
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
@@ -16,6 +16,7 @@ from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfil
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import _blocking_shared_field_labels
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import new_segment_id
|
||||
from tests.conftest import parse_api_data
|
||||
from tests.test_shipping_xfa_formal_multiline_extraction import (
|
||||
@@ -115,6 +116,8 @@ def _multiline_sample(app, monkeypatch, *, user: User):
|
||||
layout = dict(outcome.snapshot)
|
||||
layout['status'] = 'ready'
|
||||
layout['provider'] = 'xfa'
|
||||
# 合成样本也必须提供与生产相同的视觉主表身份,禁止用虚拟 XFA table_id。
|
||||
layout['tables'] = [{'table_id': 'visual-main-table'}]
|
||||
layout.setdefault('xfa_capability', {})['structure_analysis_ready'] = True
|
||||
layout_version = record_inline_layout_snapshot(document, layout)
|
||||
persist_xfa_structure_analysis(
|
||||
@@ -125,6 +128,7 @@ def _multiline_sample(app, monkeypatch, *, user: User):
|
||||
)
|
||||
db.session.commit()
|
||||
paths = {
|
||||
'MAIN_TABLE': 'visual-main-table',
|
||||
'ITEMS_DATA': _path_id_for('/data/ITEMS/DATA'),
|
||||
'MATNR': _path_id_for('/data/ITEMS/DATA/MATNR'),
|
||||
'MENGE': _path_id_for('/data/ITEMS/DATA/MENGE'),
|
||||
@@ -133,8 +137,8 @@ def _multiline_sample(app, monkeypatch, *, user: User):
|
||||
return int(document.id), paths
|
||||
|
||||
|
||||
def test_unified_suggest_api_returns_visual_and_split(app, monkeypatch, _patch_xfa_io):
|
||||
"""统一 suggest API 须返回视觉候选与 draft 拆分建议。"""
|
||||
def test_value_adapter_split_suggest_keeps_only_the_dataset_mapping_suggestion(app, monkeypatch, _patch_xfa_io):
|
||||
"""视觉建议已统一为 PDF automark;adapter 仅保留 datasets 拆分建议。"""
|
||||
with app.app_context():
|
||||
user = User(username='unified-suggest', email='unified-suggest@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
@@ -145,6 +149,7 @@ def test_unified_suggest_api_returns_visual_and_split(app, monkeypatch, _patch_x
|
||||
'display_name': 'Unified Suggest',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'main_table_id': paths['MAIN_TABLE'],
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'unified-tab',
|
||||
'operation_id': 'unified-wizard',
|
||||
@@ -153,20 +158,16 @@ def test_unified_suggest_api_returns_visual_and_split(app, monkeypatch, _patch_x
|
||||
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/unified-mapping/suggest',
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/value-adapter/split-rules/suggest',
|
||||
json={
|
||||
'document_id': document_id,
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
'path_id': paths['MATNR'],
|
||||
},
|
||||
headers=_admin_headers(app, 'unified-suggest'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = parse_api_data(response.get_json())
|
||||
assert data['suggestion_status'] == 'suggested'
|
||||
assert data['visual_suggestion']['diagnostics']['auto_confirm_blocked'] is True
|
||||
rule_set = data['split_rule_suggestion']['rule_set']
|
||||
rule_set = data['rule_set']
|
||||
assert rule_set['status'] == 'draft'
|
||||
assert rule_set['status'] != 'confirmed'
|
||||
assert rule_set['requires_confirmation'] is True
|
||||
@@ -187,6 +188,7 @@ def test_save_bindings_and_split_rules_creates_revision(app, monkeypatch, _patch
|
||||
'display_name': 'Unified Save',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'main_table_id': paths['MAIN_TABLE'],
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'save-tab',
|
||||
'operation_id': 'save-wizard',
|
||||
@@ -205,23 +207,26 @@ def test_save_bindings_and_split_rules_creates_revision(app, monkeypatch, _patch
|
||||
rule_set['requires_confirmation'] = True
|
||||
segment_id = new_segment_id()
|
||||
definition['split_rules'] = [rule_set]
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'line-quantity',
|
||||
'field_id': 'f-qty',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'page_scope': 'exact_page',
|
||||
'page_no': 1,
|
||||
'fallback_value_region': {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
}]
|
||||
definition['bindings'] = [{
|
||||
'binding_id': 'bind-save-test-001',
|
||||
'field_id': 'f-qty',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'line-quantity',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': paths['MENGE'],
|
||||
'data_path': '/data/ITEMS/DATA/MENGE',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
'source': 'manual_draw',
|
||||
'status': 'confirmed',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
}]
|
||||
saved = profile_service.save_draft(
|
||||
{
|
||||
@@ -252,6 +257,45 @@ def test_save_bindings_and_split_rules_creates_revision(app, monkeypatch, _patch
|
||||
assert 'split_rules' in snap
|
||||
|
||||
|
||||
def test_xfa_publish_gate_accepts_a_line_binding_with_its_shared_line_visual_layout():
|
||||
"""明细 datasets binding 必须复用共同 line field 框,而不是被错误要求抬头值框。"""
|
||||
definition = {
|
||||
'order_field_layouts': [],
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'line-binding-001',
|
||||
'field_id': 'field-quantity',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'line_1:quantity',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-quantity',
|
||||
'data_path': '/datasets/data/data/ITEMS/DATA/MENGE',
|
||||
},
|
||||
}],
|
||||
'table_regions': [{
|
||||
'line_layouts': [{
|
||||
'layout_id': 'line_1',
|
||||
'field_regions': [{
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'region': {'x0': .2, 'y0': .3, 'x1': .4, 'y1': .4},
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
|
||||
blocking = _blocking_shared_field_labels(
|
||||
definition=definition,
|
||||
schema_field_ids={'field-quantity'},
|
||||
)
|
||||
|
||||
# 关键断言:正式 line binding 的 layout 身份与共同明细框一致时,不应被发布门禁误阻断。
|
||||
assert not any(item['key'] == 'xfa_shared_field_label_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_suggest_split_rules_service_status_draft(app, monkeypatch, _patch_xfa_io):
|
||||
"""拆分建议 service 层 status 必须为 draft/suggested。"""
|
||||
with app.app_context():
|
||||
@@ -264,6 +308,7 @@ def test_suggest_split_rules_service_status_draft(app, monkeypatch, _patch_xfa_i
|
||||
'display_name': 'Split Svc',
|
||||
'schema_version_id': schema_id,
|
||||
'document_id': document_id,
|
||||
'main_table_id': paths['MAIN_TABLE'],
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'browser_session_id': 'svc-tab',
|
||||
'operation_id': 'svc-wizard',
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_migration.py
|
||||
|
||||
用途:验收统一 binding 一次性迁移(坐标 + XFA Dry Run;路径保留 100%;正式字段差异 0)。
|
||||
依赖:order_profile_unified_migration、pytest。
|
||||
逻辑:使用合成 definition,不接真实 PDF;断言报告指标与 convert 稳定性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
_clear_xfa_legacy_mappings,
|
||||
build_migration_report,
|
||||
convert_coordinate_definition_to_unified_bindings,
|
||||
convert_xfa_definition_to_unified_bindings,
|
||||
)
|
||||
|
||||
|
||||
def _coordinate_definition() -> dict:
|
||||
"""构造最小合法坐标 definition(含 order_field_layouts)。"""
|
||||
return {
|
||||
'template_mode': 'coordinate',
|
||||
'document_match': {
|
||||
'required_anchors': [],
|
||||
'optional_anchors': [],
|
||||
'negative_anchors': [],
|
||||
},
|
||||
'table_regions': [{
|
||||
'region_id': 'table_main',
|
||||
'page_scope': 'first_page',
|
||||
'region': {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.8},
|
||||
'header_layouts': [],
|
||||
'line_layouts': [{
|
||||
'layout_id': 'line_1',
|
||||
'field_regions': [{
|
||||
'region_id': 'line_part',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0.2, 'y0': 0.3, 'x1': 0.4, 'y1': 0.35},
|
||||
'allowed_sources': ['pdf_text'],
|
||||
'extractor_key': 'direct',
|
||||
}],
|
||||
}],
|
||||
'continuation_rule': {'required_anchor_ids': []},
|
||||
}],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'hdr_po',
|
||||
'field_id': 'fld-po',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'first_page',
|
||||
'absolute_value_region': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.14},
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
}
|
||||
|
||||
|
||||
def _xfa_definition() -> dict:
|
||||
"""构造最小合法 XFA definition(header + line mapping)。"""
|
||||
return {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': ['/data/ITEMS1/DATA'],
|
||||
},
|
||||
'header_mappings': [{
|
||||
'mapping_id': 'map-po',
|
||||
'field_id': 'fld-po',
|
||||
'field_code': 'customer_po_number',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
'path_id': 'path-ebeln',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
'line_mapping': {
|
||||
'row_path': '/data/ITEMS/DATA',
|
||||
'fields': [{
|
||||
'mapping_id': 'map-matnr',
|
||||
'field_id': 'fld-part',
|
||||
'field_code': 'part_number',
|
||||
'data_path': '/data/ITEMS/DATA/MATNR',
|
||||
'path_id': 'path-matnr',
|
||||
'value_type': 'string',
|
||||
}],
|
||||
},
|
||||
'bindings': [],
|
||||
'split_rules': [],
|
||||
}
|
||||
|
||||
|
||||
def test_coordinate_dry_run_path_preserve_and_zero_field_diff():
|
||||
"""坐标迁移:正式字段差异 0;bindings 覆盖 order + line 字段。"""
|
||||
before = _coordinate_definition()
|
||||
after, stats = convert_coordinate_definition_to_unified_bindings(before)
|
||||
report = build_migration_report(before=before, after=after, stats=stats)
|
||||
assert report['field_diff_count'] == 0
|
||||
assert report['path_preserve_rate'] == 100.0
|
||||
assert report['binding_count'] >= 2
|
||||
assert report['pending_visual_count'] == 0
|
||||
assert all(
|
||||
item['value_binding']['type'] in {'pdf_coordinate', 'ocr_coordinate'}
|
||||
for item in after['bindings']
|
||||
)
|
||||
assert all(item['visual_binding']['status'] == 'confirmed' for item in after['bindings'])
|
||||
# 原 coordinate 键保留
|
||||
assert after['order_field_layouts']
|
||||
assert after['table_regions']
|
||||
|
||||
|
||||
def test_xfa_dry_run_path_preserve_100_and_zero_field_diff():
|
||||
"""XFA 迁移:path_id 保留率 100%;正式字段差异 0;视觉框为 suggested。"""
|
||||
before = _xfa_definition()
|
||||
after, stats = convert_xfa_definition_to_unified_bindings(before, widgets=[])
|
||||
report = build_migration_report(before=before, after=after, stats=stats)
|
||||
assert report['path_preserve_rate'] == 100.0
|
||||
assert report['field_diff_count'] == 0
|
||||
assert report['binding_count'] == 2
|
||||
assert report['pending_visual_count'] == 2
|
||||
assert report['legacy_will_be_cleared'] is True
|
||||
assert report['legacy_mapping_counts'] == {'header': 1, 'line': 1}
|
||||
assert after['header_mappings'] == before['header_mappings']
|
||||
assert after['line_mapping'] == before['line_mapping']
|
||||
assert after['source_contract'] == before['source_contract']
|
||||
assert all(item['value_binding']['type'] == 'xfa_dataset' for item in after['bindings'])
|
||||
assert {item['value_binding']['path_id'] for item in after['bindings']} == {
|
||||
'path-ebeln', 'path-matnr',
|
||||
}
|
||||
assert all(item['visual_binding']['status'] == 'suggested' for item in after['bindings'])
|
||||
|
||||
|
||||
def test_xfa_execute_clears_legacy_mappings():
|
||||
"""Execute 后须清除 header_mappings / line_mapping.fields,仅保留 bindings。"""
|
||||
before = _xfa_definition()
|
||||
after, _stats = convert_xfa_definition_to_unified_bindings(before, widgets=[])
|
||||
cleared = _clear_xfa_legacy_mappings(after)
|
||||
assert cleared['bindings']
|
||||
assert cleared['header_mappings'] == []
|
||||
assert cleared['line_mapping']['fields'] == []
|
||||
assert cleared['line_mapping']['row_path'] == before['source_contract']['authoritative_line_collection_path']
|
||||
|
||||
|
||||
def test_xfa_migrated_pending_visual_blocks_publish_gate():
|
||||
"""关键断言:迁移 Execute 清除 legacy 后 suggested 视觉框仍阻断发布。"""
|
||||
from app.services.shipping_notice.order_document_profile_publish_check_service import (
|
||||
_blocking_xfa_visual_bindings,
|
||||
)
|
||||
|
||||
before = _xfa_definition()
|
||||
after, _stats = convert_xfa_definition_to_unified_bindings(before, widgets=[])
|
||||
migrated = _clear_xfa_legacy_mappings(after)
|
||||
schema_field_ids = {'fld-po', 'fld-part'}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=migrated,
|
||||
schema_field_ids=schema_field_ids,
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_binding_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_scan_unified_migration_profiles_synthetic():
|
||||
"""scan 返回逐族状态;无 DB 时用 summarize 逻辑(纯函数部分)。"""
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
scan_unified_migration_profiles,
|
||||
summarize_unified_migration_status,
|
||||
)
|
||||
|
||||
coord = summarize_unified_migration_status(_coordinate_definition(), template_mode='coordinate')
|
||||
assert coord['unified_binding_status'] == 'needs_migration'
|
||||
assert coord['field_diff_count'] == 0
|
||||
|
||||
xfa = summarize_unified_migration_status(_xfa_definition(), template_mode='xfa_dataset')
|
||||
assert xfa['unified_binding_status'] == 'needs_migration'
|
||||
assert xfa['pending_visual_count'] == 2
|
||||
assert xfa['path_preserve_rate'] == 100.0
|
||||
|
||||
# scan 需 DB;此处只验证函数可导入且 summarize 与 convert 一致
|
||||
assert callable(scan_unified_migration_profiles)
|
||||
@@ -16,7 +16,11 @@ import pytest
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import XfaAcroformField
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_datasets
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import extract_xfa_profile
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import validate_xfa_extraction
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import (
|
||||
_line_amount_failures,
|
||||
_normalize_comparable,
|
||||
validate_xfa_extraction,
|
||||
)
|
||||
from tests.test_shipping_xfa_helpers import load_datasets_fixture
|
||||
from tests.test_shipping_xfa_profile_extraction import _raw_profile, _schema_definition
|
||||
|
||||
@@ -103,6 +107,43 @@ def test_line_amount_formula_failure():
|
||||
assert 'xfa_business_validation_failed' in result.reason_codes
|
||||
|
||||
|
||||
def test_current_schema_amount_aliases_do_not_implicitly_split_composite_prices():
|
||||
"""交叉校验不得把未显式拆分的 NETPR 复合展示值当作单价。"""
|
||||
assert _normalize_comparable('898.72 / 1') == '898.72 / 1'
|
||||
assert _line_amount_failures([{
|
||||
'qty': '30',
|
||||
'unit_price': '898.72',
|
||||
'price_unit': '1',
|
||||
'line_amount_with_tax': '26,961.60',
|
||||
}]) == []
|
||||
|
||||
|
||||
def test_line_amount_formula_never_uses_price_unit_as_an_implicit_divisor():
|
||||
"""金额公式只使用数量、单价和金额;price_unit 不能成为后端特殊除数。"""
|
||||
assert _line_amount_failures([{
|
||||
'qty': '30',
|
||||
'unit_price': '898.72',
|
||||
'line_amount_with_tax': '26,961.60',
|
||||
}]) == []
|
||||
|
||||
# 即使原始行残留同名值,未注册字段也不能作为后台隐式除数。
|
||||
assert _line_amount_failures([{
|
||||
'qty': '30',
|
||||
'unit_price': '898.72',
|
||||
'price_unit': 'not-a-number',
|
||||
'line_amount_with_tax': '26,961.60',
|
||||
}]) == []
|
||||
|
||||
# 即使 Schema 中存在同名字段,通用金额公式也不得按字段名切换为除法。
|
||||
failures = _line_amount_failures([{
|
||||
'qty': '10',
|
||||
'unit_price': '20',
|
||||
'price_unit': '10',
|
||||
'line_amount_with_tax': '20',
|
||||
}])
|
||||
assert failures and failures[0]['reason'] == 'amount_mismatch'
|
||||
|
||||
|
||||
def test_header_total_vs_line_sum_failure():
|
||||
"""关键断言:Header 总金额与明细合计不一致 → business_validation_failed。"""
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
@@ -177,6 +218,61 @@ def test_acroform_display_format_difference_is_ok(monkeypatch):
|
||||
assert result.cross_check_summary['acroform_status'] == 'matched'
|
||||
|
||||
|
||||
def test_acroform_composite_value_requires_an_explicit_split_binding(monkeypatch):
|
||||
"""复合 Widget 只有明确 split_rule_ref 才可跳过原文对账。"""
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
raw_profile['definition']['split_rules'] = []
|
||||
price_binding = next(
|
||||
item for item in raw_profile['definition']['bindings']
|
||||
if item['field_code'] == 'unit_price'
|
||||
)
|
||||
price_binding.pop('split_rule_ref', None)
|
||||
# 运行期模型只信 binding 明确引用;清除引用后使用直取值以暴露不一致。
|
||||
for row in extraction.rows:
|
||||
for field in row.get('fields') or []:
|
||||
if field.get('field_code') == 'unit_price':
|
||||
field['value'] = '898.72'
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_validation.read_acroform_fields',
|
||||
lambda _pdf: [XfaAcroformField('NETPR', 'NETPR', '898.72 / 1', '898.72 / 1')],
|
||||
)
|
||||
result = validate_xfa_extraction(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=b'%PDF-fake',
|
||||
)
|
||||
|
||||
assert result.passed is False
|
||||
assert 'xfa_acroform_mismatch' in result.reason_codes
|
||||
|
||||
|
||||
def test_acroform_english_month_date_matches_normalized_dataset_date(monkeypatch):
|
||||
"""AcroForm 的英文月名日期与 datasets ISO 日期一致时不得误判为冲突。"""
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
|
||||
def _fake_acroform(_pdf_bytes):
|
||||
return [
|
||||
XfaAcroformField('EINDT', 'EINDT', '14-Jul-2026', '14***6'),
|
||||
]
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_validation.read_acroform_fields',
|
||||
_fake_acroform,
|
||||
)
|
||||
result = validate_xfa_extraction(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=b'%PDF-fake',
|
||||
)
|
||||
|
||||
# 关键断言:只覆盖一个字段应为 partial,而不是格式假冲突导致 mismatched。
|
||||
assert result.passed is True
|
||||
assert result.cross_check_summary['acroform_status'] == 'partial'
|
||||
|
||||
|
||||
def test_acroform_empty_fields_is_unavailable(monkeypatch):
|
||||
"""关键断言:PDF 有调用但无 AcroForm Fields → unavailable,不得记 matched。"""
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_visual_binding.py
|
||||
|
||||
用途:验收 XFA 视觉绑定候选评分、歧义诊断与审计 before/after。
|
||||
依赖:xfa_visual_binding、xfa_acroform、order_document_profile_visual_binding_service。
|
||||
逻辑:纯函数 + mock Widget/datasets;不接真实 PDFium/google-re2。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import XfaAcroformWidget
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis
|
||||
from app.services.shipping_notice.document_layout.xfa_visual_binding import (
|
||||
suggest_visual_binding_candidates,
|
||||
visual_binding_audit_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_audit_service import (
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENTS,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
|
||||
from app.services.shipping_notice.progress_audit_contract import XFA_PROGRESS_EVENT_CODES
|
||||
|
||||
|
||||
def _dataset_analysis() -> XfaDatasetAnalysis:
|
||||
"""构造最小 datasets 分析(双 MATNR 歧义路径)。"""
|
||||
return XfaDatasetAnalysis(
|
||||
nodes=[],
|
||||
dataset_root_path='/data',
|
||||
leaf_values_by_path={
|
||||
'/data/HEADER/EBELN': '4510039227',
|
||||
'/data/ITEMS/DATA/MATNR': 'TEMP-S000218922',
|
||||
'/data/ITEMS1/DATA/MATNR': 'TEMP-S000218922',
|
||||
},
|
||||
header_candidates=['/data/HEADER'],
|
||||
collection_candidates=[],
|
||||
known_path_ids=set(),
|
||||
stats={},
|
||||
)
|
||||
|
||||
|
||||
def _widget(
|
||||
*,
|
||||
short_name: str,
|
||||
value: str,
|
||||
page_no: int = 1,
|
||||
bbox: dict[str, float] | None = None,
|
||||
) -> XfaAcroformWidget:
|
||||
"""合成单个 Widget。"""
|
||||
region = bbox or {'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55}
|
||||
qname = f'form[0].{short_name}[0]'
|
||||
return XfaAcroformWidget(
|
||||
widget_id=f'wgt-{short_name}',
|
||||
qualified_name=qname,
|
||||
short_name=short_name,
|
||||
page_no=page_no,
|
||||
normalized_bbox=region,
|
||||
value=value,
|
||||
value_masked=value[:4] + '***' if value else '',
|
||||
)
|
||||
|
||||
|
||||
def test_visual_binding_candidates_never_auto_confirm():
|
||||
"""所有候选 status 必须为 suggested,diagnostics 阻断自动确认。"""
|
||||
widgets = [
|
||||
_widget(short_name='EBELN', value='4510039227', bbox={'x0': 0.1, 'y0': 0.1, 'x1': 0.4, 'y1': 0.2}),
|
||||
_widget(short_name='MATNR', value='TEMP-S000218922', bbox={'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55}),
|
||||
]
|
||||
result = suggest_visual_binding_candidates(
|
||||
page_no=1,
|
||||
normalized_bbox={'x0': 0.1, 'y0': 0.38, 'x1': 0.52, 'y1': 0.58},
|
||||
dataset_analysis=_dataset_analysis(),
|
||||
widgets=widgets,
|
||||
)
|
||||
assert result['candidates']
|
||||
assert all(item['status'] == 'suggested' for item in result['candidates'])
|
||||
assert result['diagnostics']['auto_confirm_blocked'] is True
|
||||
assert 'confirmed' not in str(result).lower() or all(
|
||||
item['status'] != 'confirmed' for item in result['candidates']
|
||||
)
|
||||
|
||||
|
||||
def test_ambiguous_path_candidates_flagged():
|
||||
"""同短名多 datasets 路径时必须标记 ambiguous。"""
|
||||
widgets = [_widget(short_name='MATNR', value='TEMP-S000218922')]
|
||||
result = suggest_visual_binding_candidates(
|
||||
page_no=1,
|
||||
normalized_bbox={'x0': 0.1, 'y0': 0.4, 'x1': 0.5, 'y1': 0.55},
|
||||
dataset_analysis=_dataset_analysis(),
|
||||
widgets=widgets,
|
||||
)
|
||||
top = result['candidates'][0]
|
||||
assert len(top['path_candidates']) >= 2
|
||||
assert result['diagnostics']['ambiguous'] is True
|
||||
|
||||
|
||||
def test_visual_binding_audit_events_registered():
|
||||
"""视觉绑定审计事件须注册于契约白名单。"""
|
||||
for event in XFA_VISUAL_BINDING_AUDIT_EVENTS:
|
||||
assert event in XFA_AUDIT_EVENT_TYPES, event
|
||||
assert event in XFA_PROGRESS_EVENT_CODES, event
|
||||
|
||||
|
||||
def test_confirm_visual_binding_writes_before_after_audit(app):
|
||||
"""确认视觉绑定必须写入 before/after 审计摘要,且须携带合成预览 checksum。"""
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as svc
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import RENDER_MODE
|
||||
|
||||
checksum = 'sha256:' + ('c' * 64)
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-test-001',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-ebeln',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.9,
|
||||
},
|
||||
}],
|
||||
}
|
||||
before_snap = visual_binding_audit_snapshot(definition['bindings'][0])
|
||||
assert before_snap['status'] == 'suggested'
|
||||
|
||||
with patch.object(lease_service, 'require_active_lease', return_value=object()):
|
||||
with patch.object(svc, '_profile') as profile_mock:
|
||||
profile = type('P', (), {'id': 1, 'status': 'draft', 'template_mode': 'xfa_dataset', 'definition_json': definition})()
|
||||
profile_mock.return_value = profile
|
||||
with patch.object(svc.db.session, 'flush', lambda: None):
|
||||
with patch.object(svc.db.session, 'commit', lambda: None):
|
||||
with patch.object(svc, 'record_visual_binding_audit') as audit_mock:
|
||||
result = svc.confirm_xfa_visual_binding(
|
||||
1,
|
||||
'bind-test-001',
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.11, 'y0': 0.11, 'x1': 0.31, 'y1': 0.21},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
path_id=None,
|
||||
actor_id=1,
|
||||
browser_session_id='tab',
|
||||
lease_token='lease',
|
||||
preview_render_checksum=checksum,
|
||||
render_mode=RENDER_MODE,
|
||||
)
|
||||
audit_mock.assert_called_once()
|
||||
kwargs = audit_mock.call_args.kwargs
|
||||
assert kwargs['event_type'] == 'xfa_visual_binding_confirmed'
|
||||
assert kwargs['before']['status'] == 'suggested'
|
||||
assert kwargs['after']['status'] == 'confirmed'
|
||||
assert kwargs['before']['normalized_bbox']['x0'] == 0.1
|
||||
assert kwargs['after']['normalized_bbox']['x0'] == 0.11
|
||||
assert result['visual_binding']['preview_render_checksum'] == checksum
|
||||
assert result['visual_binding']['render_mode'] == RENDER_MODE
|
||||
assert result['visual_binding']['confirmed_on'] == RENDER_MODE
|
||||
|
||||
|
||||
def test_confirm_visual_binding_requires_synthetic_preview_checksum(app):
|
||||
"""关键断言:缺 preview_render_checksum / render_mode 时确认 fail-closed。"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as svc
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'bind-test-002',
|
||||
'field_id': 'f-po',
|
||||
'field_code': 'customer_po_no',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-ebeln',
|
||||
'data_path': '/data/HEADER/EBELN',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.9,
|
||||
},
|
||||
}],
|
||||
}
|
||||
with patch.object(lease_service, 'require_active_lease', return_value=object()):
|
||||
with patch.object(svc, '_profile') as profile_mock:
|
||||
profile = type('P', (), {
|
||||
'id': 1,
|
||||
'status': 'draft',
|
||||
'template_mode': 'xfa_dataset',
|
||||
'definition_json': definition,
|
||||
})()
|
||||
profile_mock.return_value = profile
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
svc.confirm_xfa_visual_binding(
|
||||
1,
|
||||
'bind-test-002',
|
||||
visual_binding={
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.11, 'y0': 0.11, 'x1': 0.31, 'y1': 0.21},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
path_id=None,
|
||||
actor_id=1,
|
||||
browser_session_id='tab',
|
||||
lease_token='lease',
|
||||
)
|
||||
assert caught.value.code == (
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_CONFIRM_REQUIRES_SYNTHETIC_PREVIEW'
|
||||
)
|
||||
@@ -1,142 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_visual_binding_permissions.py
|
||||
|
||||
用途:验收 XFA 视觉绑定 API 的管理员鉴权与租约门禁。
|
||||
依赖:Flask test client、JWT、XFA phase2 样本夹具。
|
||||
逻辑:非 admin 403;suggest 可读;confirm/reject 无租约 409。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import User
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_visual_binding_service as vb_service
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
from tests.test_shipping_xfa_profile_phase2 import _patch_xfa_io, _schema_with_required, _seed_xfa_sample
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers_factory(app):
|
||||
"""生成 admin Bearer JWT。"""
|
||||
|
||||
def _build(username: str):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
return _build
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def user_headers_factory(app):
|
||||
"""生成普通用户 Bearer JWT。"""
|
||||
|
||||
def _build(username: str):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
return _build
|
||||
|
||||
|
||||
def _xfa_draft_profile(app, monkeypatch):
|
||||
"""创建含 binding 占位的最小 XFA 草稿 Profile。"""
|
||||
with app.app_context():
|
||||
admin = User(username='xfa-vb-admin', email='xfa-vb-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin)
|
||||
db.session.commit()
|
||||
schema = _schema_with_required()
|
||||
document, paths, _pdf = _seed_xfa_sample(user=admin)
|
||||
created = creation_service.complete_wizard({
|
||||
'display_name': 'XFA Visual Binding',
|
||||
'schema_version_id': schema.id,
|
||||
'document_id': document.id,
|
||||
'authoritative_collection_path_id': paths['ITEMS_DATA'],
|
||||
'mirror_collection_path_ids': [paths['ITEMS1_DATA']],
|
||||
'browser_session_id': 'vb-tab',
|
||||
'operation_id': 'vb-wizard-op',
|
||||
}, actor_id=admin.id)
|
||||
profile_id = int(created['id'])
|
||||
binding = vb_service.ensure_binding_stub(
|
||||
profile_id,
|
||||
field_id='f-po',
|
||||
field_code='customer_po_no',
|
||||
scope='header',
|
||||
path_id=paths['EBELN'],
|
||||
data_path='/data/HEADER/EBELN',
|
||||
actor_id=admin.id,
|
||||
browser_session_id='vb-tab',
|
||||
lease_token=created['edit_lease']['lease_token'],
|
||||
)
|
||||
return profile_id, document.id, binding['binding_id'], created['edit_lease']['lease_token']
|
||||
|
||||
|
||||
def test_visual_binding_suggest_requires_admin(app, monkeypatch, admin_headers_factory, user_headers_factory, _patch_xfa_io):
|
||||
"""非 admin 不得调用视觉建议 API。"""
|
||||
profile_id, document_id, _, _ = _xfa_draft_profile(app, monkeypatch)
|
||||
client = app.test_client()
|
||||
payload = {
|
||||
'document_id': document_id,
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
}
|
||||
forbidden = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/visual-bindings/suggest',
|
||||
json=payload,
|
||||
headers=user_headers_factory('vb-user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
ok = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/visual-bindings/suggest',
|
||||
json=payload,
|
||||
headers=admin_headers_factory('vb-admin2'),
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
data = parse_api_data(ok.get_json())
|
||||
assert data['diagnostics']['auto_confirm_blocked'] is True
|
||||
|
||||
|
||||
def test_visual_binding_confirm_requires_lease(app, monkeypatch, admin_headers_factory, _patch_xfa_io):
|
||||
"""确认视觉绑定必须持有有效租约。"""
|
||||
profile_id, _document_id, binding_id, _lease_token = _xfa_draft_profile(app, monkeypatch)
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa/visual-bindings/{binding_id}/confirm',
|
||||
json={
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||||
'source': 'manual_draw',
|
||||
'confidence': 1.0,
|
||||
},
|
||||
},
|
||||
headers=admin_headers_factory('vb-admin3'),
|
||||
)
|
||||
assert response.status_code == 409
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED'
|
||||
@@ -1,220 +0,0 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_visual_publish_gate.py
|
||||
|
||||
用途:阶段 5 视觉绑定发布门禁——缺 bindings / 双源 / 未确认框阻断发布。
|
||||
依赖:publish_check_service 内部 _blocking_xfa_visual_bindings、xfa_contract。
|
||||
逻辑:纯单元构造 definition;断言 xfa_visual_bindings_required / dual source / incomplete。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.order_document_profile_publish_check_service import (
|
||||
_blocking_xfa_validation_metrics,
|
||||
_blocking_xfa_visual_bindings,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _source_contract() -> dict:
|
||||
"""最小 XFA source_contract。"""
|
||||
return {
|
||||
'template_packet_checksum': 'sha256:' + ('a' * 64),
|
||||
'dataset_structure_fingerprint': 'sha256:' + ('b' * 64),
|
||||
'dataset_root_path': '/data',
|
||||
'authoritative_line_collection_path': '/data/ITEMS/DATA',
|
||||
}
|
||||
|
||||
|
||||
def _confirmed_binding(*, field_id: str, field_code: str, status: str = 'confirmed') -> dict:
|
||||
"""构造最小统一绑定(原生 PDF 画布确认证据)。"""
|
||||
return {
|
||||
'binding_id': f'bind-{field_id}-aaaa-bbbb',
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': 'header' if field_id.startswith('f-h') else 'line',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': f'path-{field_id}',
|
||||
'data_path': f'/data/HEADER/{field_code.upper()}' if field_id.startswith('f-h') else f'/data/ITEMS/DATA/{field_code.upper()}',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
|
||||
'source': 'manual_draw',
|
||||
'status': status,
|
||||
'confidence': 1.0,
|
||||
**({
|
||||
'render_mode': 'native_pdf',
|
||||
'confirmed_on': 'native_pdf',
|
||||
} if status == 'confirmed' else {}),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_missing_bindings_blocks_xfa_profile():
|
||||
"""关键断言:XFA 无 bindings → xfa_visual_bindings_required。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_bindings_required' for item in blocking)
|
||||
|
||||
|
||||
def test_dual_binding_source_blocks_publish():
|
||||
"""关键断言:bindings 与 legacy mappings 共存 → xfa_dual_binding_source。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [{
|
||||
'mapping_id': 'm-po', 'field_id': 'f-h-po', 'field_code': 'customer_po_no',
|
||||
'data_path': '/data/HEADER/EBELN', 'path_id': 'path-po',
|
||||
}],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_dual_binding_source' for item in blocking)
|
||||
|
||||
|
||||
def test_unconfirmed_visual_binding_blocks_publish():
|
||||
"""关键断言:坐标类字段未确认视觉框 → incomplete;datasets 仅 suggested 视觉不阻断。"""
|
||||
coord = _confirmed_binding(field_id='f-h-po', field_code='customer_po_no', status='suggested')
|
||||
coord['value_binding'] = {
|
||||
'type': 'pdf_coordinate',
|
||||
'region_id': 'region-po',
|
||||
'path_id': None,
|
||||
'data_path': None,
|
||||
}
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [coord],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_binding_incomplete' for item in blocking)
|
||||
|
||||
datasets_only = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no', status='suggested')],
|
||||
}
|
||||
assert _blocking_xfa_visual_bindings(
|
||||
definition=datasets_only,
|
||||
schema_field_ids={'f-h-po'},
|
||||
) == []
|
||||
|
||||
|
||||
def test_confirmed_bindings_pass_visual_gate():
|
||||
"""关键断言:datasets path 可发布(视觉可选);原生 PDF confirmed 不阻断。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert blocking == []
|
||||
|
||||
|
||||
def test_legacy_synthetic_confirmed_requires_reconfirm():
|
||||
"""关键断言:旧 xfa_dataset_preview 确认框视为未重确认。"""
|
||||
binding = _confirmed_binding(field_id='f-h-po', field_code='customer_po_no')
|
||||
binding['visual_binding']['confirmed_on'] = 'xfa_dataset_preview'
|
||||
binding['visual_binding']['render_mode'] = 'xfa_dataset_preview'
|
||||
# 仅视觉过期时 datasets path 仍可发布;若清掉 path 才 incomplete。
|
||||
binding['value_binding']['type'] = 'pdf_coordinate'
|
||||
binding['value_binding']['region_id'] = 'region-po'
|
||||
binding['value_binding']['path_id'] = None
|
||||
binding['value_binding']['data_path'] = None
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [binding],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert any(item.get('key') == 'xfa_visual_binding_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_confirmed_bindings_missing_renderer_version_no_longer_block():
|
||||
"""关键断言:本期不再要求 renderer_version / synthetic checksum。"""
|
||||
binding = _confirmed_binding(field_id='f-h-po', field_code='customer_po_no')
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [binding],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert blocking == []
|
||||
assert not any(item.get('key') == 'xfa_preview_renderer_version_mismatch' for item in blocking)
|
||||
|
||||
|
||||
def test_confirmed_bindings_missing_page_identity_no_longer_block():
|
||||
"""关键断言:本期不再要求 synthetic 页身份。"""
|
||||
definition = {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': _source_contract(),
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
|
||||
'bindings': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no')],
|
||||
}
|
||||
blocking = _blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids={'f-h-po'},
|
||||
)
|
||||
assert blocking == []
|
||||
assert not any(item.get('key') == 'xfa_preview_page_identity_missing' for item in blocking)
|
||||
|
||||
|
||||
def test_audit_compensation_health_fail_closed():
|
||||
"""关键断言:补偿骨架未完成真实重放 → healthy=False。"""
|
||||
from app.services.shipping_notice.audit_compensation_service import (
|
||||
is_audit_compensation_healthy,
|
||||
reset_compensation_store_for_tests,
|
||||
)
|
||||
|
||||
reset_compensation_store_for_tests()
|
||||
assert is_audit_compensation_healthy() is False
|
||||
|
||||
|
||||
def test_validation_metrics_threshold_blocks_below_100_percent():
|
||||
"""关键断言:摘要指标 < 1.0 时发布门禁阻断。"""
|
||||
blocking = _blocking_xfa_validation_metrics({
|
||||
'visual_coverage_rate': 0.5,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
})
|
||||
assert any(item.get('key') == 'xfa_visual_coverage_insufficient' for item in blocking)
|
||||
@@ -1,14 +1,16 @@
|
||||
"""
|
||||
tests/test_worker_shipping.py
|
||||
|
||||
用途:验证 Shipping Worker 在 Windows spawn 模式下使用启动它的虚拟环境解释器。
|
||||
用途:验证 Shipping Worker 在 Windows spawn 模式下使用启动它的虚拟环境解释器与统一自动标注队列。
|
||||
依赖:worker_shipping、pytest monkeypatch。
|
||||
逻辑:避免 multiprocessing 子进程回退到系统 Python,导致 OCR 等可选依赖从错误环境加载。
|
||||
逻辑:避免 multiprocessing 子进程回退到系统 Python;Worker 不再持有已删除的 XFA 专用 OCR 启动门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -31,19 +33,9 @@ def test_configure_shipping_worker_process_executable_uses_current_interpreter(m
|
||||
assert recorded == [sys.executable]
|
||||
|
||||
|
||||
def test_assert_shipping_worker_capabilities_rejects_missing_xfa_ocr(monkeypatch):
|
||||
"""关键断言:shipping Worker 在领取 Job 前必须拒绝缺少 XFA OCR 的运行环境。"""
|
||||
monkeypatch.setattr(worker_shipping, 'is_ocr_engine_available', lambda: False)
|
||||
|
||||
with pytest.raises(RuntimeError, match='XFA OCR dependency is unavailable'):
|
||||
worker_shipping.assert_shipping_worker_capabilities()
|
||||
|
||||
|
||||
def test_assert_shipping_worker_capabilities_accepts_complete_xfa_ocr(monkeypatch):
|
||||
"""关键断言:完整 OCR 环境允许 shipping Worker 启动并消费队列。"""
|
||||
monkeypatch.setattr(worker_shipping, 'is_ocr_engine_available', lambda: True)
|
||||
|
||||
worker_shipping.assert_shipping_worker_capabilities()
|
||||
def test_shipping_worker_does_not_depend_on_removed_xfa_ocr_startup_gate():
|
||||
"""统一 PDF 自动标注由 shipping 队列消费,Worker 导入时不得依赖已删除 XFA OCR 模块。"""
|
||||
assert not hasattr(worker_shipping, 'assert_shipping_worker_capabilities')
|
||||
|
||||
|
||||
def test_shipping_worker_claims_unified_pdf_automark_jobs(monkeypatch):
|
||||
@@ -59,3 +51,16 @@ def test_shipping_worker_claims_unified_pdf_automark_jobs(monkeypatch):
|
||||
queue_service.claim_next_shipping_notice_job()
|
||||
|
||||
assert JobType.SHIPPING_PDF_AUTOMARK in received['job_types']
|
||||
|
||||
|
||||
def test_route_runtime_diagnostic_identifies_loaded_workflow_without_document_content():
|
||||
"""路由审计必须可定位 Worker 代码身份,且不得采集文档或字段内容。"""
|
||||
from app.jobs.handlers import shipping_order_extraction as handler
|
||||
|
||||
diagnostic = handler._route_runtime_diagnostic()
|
||||
|
||||
source_path = Path(diagnostic['workflow_module_path'])
|
||||
assert diagnostic['interpreter'] == sys.executable
|
||||
assert source_path.name == 'order_extraction_workflow.py'
|
||||
assert diagnostic['workflow_source_sha256'] == hashlib.sha256(source_path.read_bytes()).hexdigest()
|
||||
assert {'pdf', 'dataset', 'value', 'text', 'glyph'}.isdisjoint(diagnostic)
|
||||
Reference in new issue
Block a user