feat(shipping-notice): 收敛复核状态隔离、STP 重试幂等与 XFA 合成预览标注

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-07 02:58:28 +08:00
1 parent 84a881b554
commit 74270adc22
149 files changed
+20111 -3871

No files matched your search

+4
View File
@@ -420,6 +420,10 @@ def pytest_configure(config):
"markers",
"inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
)
config.addinivalue_line(
"markers",
"postgres: requires PostgreSQL dialect (skip on SQLite/memory fixtures)",
)
# [STEP] Windows 质量门禁:basetemp 落仓内 + retention=0(见 pytest.ini)。
if not getattr(config.option, 'basetemp', None):
basetemp = Path(__file__).resolve().parents[1] / '.pytest_tmp' / 'run'
@@ -198,9 +198,18 @@ 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):
def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(app, monkeypatch):
"""相同 XFA 文件复用时,目标 Document 必须获得独立 Analysis 并重写快照身份。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
audit_events: list[str] = []
def _capture_audit(**kwargs):
audit_events.append(str(kwargs.get('event_type')))
monkeypatch.setattr(
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
_capture_audit,
)
with app.app_context():
original = _document()
source_analysis = ShippingXfaStructureAnalysis(
@@ -269,11 +278,21 @@ def test_xfa_layout_reuse_localizes_structure_analysis_for_duplicate_document(ap
assert target_analysis.dataset_structure_fingerprint == source_analysis.dataset_structure_fingerprint
assert target_capability['structure_analysis_id'] == target_analysis.id
assert localized.payload_json['capability']['structure_analysis_id'] == target_analysis.id
assert 'xfa_structure_analysis_reused' in audit_events
def test_xfa_layout_without_source_analysis_is_not_reused(app):
def test_xfa_layout_without_source_analysis_is_not_reused(app, monkeypatch):
"""XFA 快照声明 ready 但源 Analysis 缺失时必须重新排队,禁止复制伪 ready 状态。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
audit_events: list[str] = []
def _capture_audit(**kwargs):
audit_events.append(str(kwargs.get('event_type')))
monkeypatch.setattr(
'app.services.shipping_notice.audit_service.append_shipping_audit_event',
_capture_audit,
)
with app.app_context():
original = _document()
source_layout = record_inline_layout_snapshot(original, {
@@ -313,6 +332,8 @@ def test_xfa_layout_without_source_analysis_is_not_reused(app):
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
def test_layout_parser_fingerprint_change_creates_new_version_without_force(app, monkeypatch):
@@ -230,11 +230,11 @@ def test_should_attempt_generic_extraction_rejects_layout_drift():
) is False
def test_should_attempt_generic_extraction_allows_no_match_after_xfa_fallback():
"""XFA 失败回退后 match_status 来自坐标路径;no_match 允许进入通用/Dify。"""
def test_should_attempt_generic_extraction_allows_no_match_for_coordinate_path():
"""坐标路径 no_match 允许进入通用解析;structure_identity_changed 仍 fail-closed。"""
assert _should_attempt_generic_extraction(
match_status='no_match',
profile_result={'issues': ['xfa_mirror_collection_mismatch'], 'match': {'status': 'no_match'}},
profile_result={'issues': [], 'match': {'status': 'no_match'}},
) is True
# 坐标路径自身的 structure_identity_changed 仍 fail-closed。
assert _should_attempt_generic_extraction(
@@ -243,8 +243,8 @@ def test_should_attempt_generic_extraction_allows_no_match_after_xfa_fallback():
) is False
def test_route_deterministic_unit_xfa_failure_falls_back_to_generic(monkeypatch):
"""关键断言:XFA capability 文档失败后回退 generic_deterministic。"""
def test_route_deterministic_unit_xfa_failure_does_not_fallback_to_generic(monkeypatch):
"""关键断言:XFA capability 文档正式提取失败后不回退 generic/coordinate。"""
document = {
'document_id': 90,
'layout_snapshot': {
@@ -304,16 +304,24 @@ def test_route_deterministic_unit_xfa_failure_falls_back_to_generic(monkeypatch)
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
_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 True
assert route.decision.get('capability_kind') == 'xfa_fallback_coordinate'
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'
assert 'xfa_dataset_missing' in (
route.decision.get('fallback_reason_codes')
or route.decision.get('xfa_fallback_reason_codes')
or route.decision.get('reason_codes')
or []
)
@@ -0,0 +1,89 @@
"""
tests/test_shipping_processing_ownership.py
用途:验收投影不一致 fail-closed 与任务归属 ConflictError。
依赖:processing_ownership、processing_projection_invariants、pytest、unittest.mock。
逻辑:不要求完整履约 E2E;ownership 用 mock 链路;不一致用 reconcile 断言动作剥离。
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from app.core.errors import ConflictError
from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership
from app.services.shipping_notice.processing_projection_invariants import (
PROJECTION_INCONSISTENT_ERROR_CODE,
TASK_OWNERSHIP_MISMATCH_ERROR_CODE,
detect_notice_pre_create_inconsistency,
reconcile_processing_projection_facts,
)
def test_detect_notice_pre_create_inconsistency():
"""有正式号 + 建单前 stage → True;履约 stage → False。"""
assert detect_notice_pre_create_inconsistency(
stage='waiting_review',
shipping_notice_no='SN-1',
) is True
assert detect_notice_pre_create_inconsistency(
stage='inventory_matching',
shipping_notice_no='SN-1',
) is False
assert detect_notice_pre_create_inconsistency(
stage='waiting_review',
shipping_notice_no=None,
) is False
def test_reconcile_marks_inconsistency_and_strips_fulfillment():
"""服务级拆链:reconcile 后断言 stage/actions/inconsistency 码。"""
payload = reconcile_processing_projection_facts({
'status': 'blocked',
'stage': 'customer_resolving',
'source_type': 'eml',
'work_item_no': 'OT-9',
'shipping_notice_no': 'SN-LEFT',
'progress_version': 4,
'current_gate': {
'gate_code': 'customer',
'status': 'blocked',
'next_action_code': 'confirm_customer',
'blocking_reason_code': 'customer_unresolved',
'attempt_no': 1,
},
'available_actions': ['confirm_customer', 'match_inventory', 'download_excel'],
}, excel_ready=True)
assert payload['stage'] == 'customer_resolving'
assert payload['projection_inconsistency_code'] == PROJECTION_INCONSISTENT_ERROR_CODE
assert 'confirm_customer' in payload['available_actions']
assert 'open_inventory_match_review' not in payload['available_actions']
assert 'download_excel' not in payload['available_actions']
assert len(payload['stage_nodes']) == 15
def test_assert_ownership_noop_without_expected_context():
"""未传期望 OT/Case/Run 时不拦截(兼容旧客户端)。"""
task = SimpleNamespace(id=1, task_no='SN-1', order_task_id=None)
assert_notice_task_ownership(task)
def test_assert_ownership_mismatch_raises_conflict(app):
"""期望 OT 与 Notice 挂接 OT 不一致时抛出固定错误码。"""
task = SimpleNamespace(id=7, task_no='SN-7', order_task_id=99)
linked_ot = SimpleNamespace(task_no='OT-REAL', extraction_run_id=None, candidate_id=None)
with app.app_context():
with patch('app.services.shipping_notice.processing_ownership.db') as mock_db, \
patch('app.services.shipping_notice.processing_ownership.append_shipping_audit_event'):
mock_db.session.get.return_value = linked_ot
mock_db.session.flush = MagicMock()
with pytest.raises(ConflictError) as exc:
assert_notice_task_ownership(
task,
expected_order_task_no='OT-OTHER',
actor_id=1,
)
assert exc.value.code == TASK_OWNERSHIP_MISMATCH_ERROR_CODE
@@ -1,9 +1,9 @@
"""
backend/tests/test_shipping_processing_projection.py
用途:验收会话级 processing 投影分组、OT 去重与任务—PDF 两层标题规则。
依赖:Flask/SQLite、create_order_extraction_run、project_conversation_processing。
逻辑:构造 queued / frozen-failed / completed;断言多 PDF 不占用首文件名、hash 去重计数。
???????? processing ?????OT ??????PDF ???????
???Flask/SQLite?create_order_extraction_run?project_conversation_processing?
????? queued / frozen-failed / completed???? PDF ????????hash ?????
"""
from __future__ import annotations
@@ -29,11 +29,11 @@ from tests.test_shipping_order_extraction_runs import _seed_run_input
def _ensure_run_order_task(*, run, intake, document) -> None:
"""
为投影测试物化最小 Candidate + OT,并分配 Run.user_task_no。
????????? Candidate + OT???? Run.user_task_no?
核心逻辑:对齐 test_shipping_conversation_processing_api 模式;
Candidate 前 Run 无持久化 OT 时不应出现 order_task 卡;
重识别继承 OT 时走受控换绑。
??????? test_shipping_conversation_processing_api ???
Candidate ? Run ???? OT ????? order_task ??
????? OT ???????
"""
candidate = ShippingOrderCandidate.query.filter_by(
order_extraction_run_id=int(run.id),
@@ -63,7 +63,7 @@ def _ensure_run_order_task(*, run, intake, document) -> None:
def test_project_conversation_processing_groups_and_dedupes_user_tasks(app):
"""同会话多 Run 投影:按状态分组;同 OT 只保留最新。"""
"""???? Run ?????????? OT ??????"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-A')
run_processing, _ = create_order_extraction_run(
@@ -135,10 +135,10 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app):
completed_nos = {row['user_task_no'] for row in projection.get('completed') or []}
assert run_processing.user_task_no in processing_nos
assert run_failed.user_task_no in needs_nos
# 未查看的 completed 作为成功通知展示在 completed 分组。
# ???? completed ????????? completed ???
assert run_done.user_task_no in completed_nos
# 关键断言:每个活跃 OT 只出现一次。
# ????????? OT ??????
all_nos = list(processing_nos | needs_nos | completed_nos)
assert len(all_nos) == len(set(all_nos)) == 3
@@ -148,7 +148,10 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app):
)
assert failed_task.get('status_label') == 'failed'
assert 'view_details' in (failed_task.get('available_actions') or [])
assert failed_task.get('primary_action')
primary = failed_task.get('primary_action')
assert primary
# ???cancel / view_details ???? CTA?BE-01??
assert primary not in {'cancel_task', 'cancel_run', 'view_details'}
done_task = next(
row for row in projection['completed']
@@ -158,8 +161,12 @@ def test_project_conversation_processing_groups_and_dedupes_user_tasks(app):
assert done_task.get('group') == 'completed'
def test_fingerprint_merge_prefers_newer_processing_over_older_failed(app):
"""BE-02:同指纹旧失败 + 新处理中,必须展示新 Run。"""
def test_same_attachment_fingerprint_across_ots_keeps_two_cards(app):
"""
BE-02(产品选择 A):不同 user_task_no 即使附件指纹相同,也各出一张卡。
断言:failed OT + processing OT 同 content_hash → 两张卡;total_tasks == 2。
"""
with app.app_context():
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake
from datetime import timedelta
@@ -227,13 +234,17 @@ def test_fingerprint_merge_prefers_newer_processing_over_older_failed(app):
conversation_id=session.session_id,
)
shown = projection['processing'] + projection['needs_action']
assert len(shown) == 1
assert shown[0]['user_task_no'] == newer.user_task_no
assert shown[0]['run_no'] == newer.run_no
shown_nos = {row['user_task_no'] for row in shown}
# 跨 OT 同指纹不得折叠:两张独立卡。
assert len(shown) == 2
assert shown_nos == {'OT-OLD-FAIL', 'OT-NEW-PROC'}
assert projection['summary']['total_tasks'] == 2
assert projection['summary']['needs_action'] == 1
assert projection['summary']['processing'] == 1
def test_completed_current_run_hidden_after_viewed(app):
"""UI-04:当前 completed 查看后从右侧收起。"""
"""UI-04??? completed ?????????"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-DONE')
run, _ = create_order_extraction_run(
@@ -262,10 +273,14 @@ def test_completed_current_run_hidden_after_viewed(app):
)
shown = after['processing'] + after['needs_action'] + list(after.get('completed') or [])
assert all(row['user_task_no'] != run.user_task_no for row in shown)
# ?????? completed ?? history?????????
history_nos = {row['user_task_no'] for row in (after.get('history') or [])}
assert run.user_task_no in history_nos
assert after['summary']['history'] >= 1
def _set_run_documents(run, documents: list[dict]) -> None:
"""覆盖 Run 快照 documents,便于断言任务—PDF 两层投影。"""
"""?? Run ?? documents????????PDF ?????"""
snapshot = dict(run.input_snapshot_json or {})
intakes = list(snapshot.get('intakes') or [])
if not intakes:
@@ -277,8 +292,8 @@ def _set_run_documents(run, documents: list[dict]) -> None:
run.request_snapshot_json = snapshot
def test_single_pdf_task_uses_filename_title(app):
"""单 PDF 任务:title 为文件名,file_count=1,display_kind=single。"""
def test_single_pdf_task_title_is_none_for_frontend_unified_label(app):
"""BE-05?? PDF ?? title ?? None?????? document_names / objects?"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-1PDF')
run, _ = create_order_extraction_run(
@@ -306,16 +321,18 @@ def test_single_pdf_task_uses_filename_title(app):
row for row in projection['processing'] + projection['needs_action']
if row['user_task_no'] == run.user_task_no
)
assert task['title'] == 'only.pdf'
# ???????????????????????????? title?
assert task['title'] is None
assert task['file_count'] == 1
assert task['display_kind'] == 'single_document_task'
assert task.get('document_names') == ['only.pdf']
doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document']
assert len(doc_objects) == 1
assert doc_objects[0]['filename'] == 'only.pdf'
def test_multi_pdf_task_does_not_use_first_filename_as_title(app):
"""多 PDF 任务:title 为空,file_count=2,objects 含两个当前 PDF。"""
"""? PDF ???title ???file_count=2?objects ????? PDF?"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-2PDF')
run, _ = create_order_extraction_run(
@@ -362,7 +379,11 @@ def test_multi_pdf_task_does_not_use_first_filename_as_title(app):
def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app):
"""同 OT 局部重识别:新版 PDF 替换自身,旧 Run 中未重识别 PDF 继续有效。"""
"""
BE-03:同 OT 局部重识别——被替代 Run 不另开顶层卡;有效 PDF 仍折叠保留。
断言:同一 user_task_no 仅一张卡;total_tasks == 1;未重识别 PDF 来自源 Run。
"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-PARTIAL-REPARSE')
source, _ = create_order_extraction_run(
@@ -412,7 +433,7 @@ def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app):
)
replacement.reparse_of_run_id = source.id
replacement.reparse_reason = 'field_mapping_error'
# 投影用例无 Case 标记:用同 content_hash 满足严格文档谱系校验。
# 共享 content_hash,确保同 OT 谱系可交叉识别 PDF 身份。
shared_hash = str(document.content_hash or 'hash-partial-shared')
document.content_hash = shared_hash
replacement_document.content_hash = shared_hash
@@ -437,13 +458,21 @@ def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app):
user_id=user.id,
conversation_id=session.session_id,
)
task = next(
row for row in projection['processing'] + projection['needs_action']
if row['user_task_no'] == source.user_task_no
all_cards = (
projection['processing']
+ projection['needs_action']
+ list(projection.get('completed') or [])
+ list(projection.get('history') or [])
)
# BE-03:被替代 Run 不另开顶层卡;同 OT 仅一张。
matching = [row for row in all_cards if row['user_task_no'] == source.user_task_no]
assert len(matching) == 1
assert projection['summary']['total_tasks'] == 1
task = matching[0]
assert task['run_no'] == replacement.run_no
doc_objects = [obj for obj in task['objects'] if obj.get('kind') == 'document']
# 关键断言:任务仍是两份 PDF;每份 PDF 保留其当前生效版本所属 Run。
# 局部重识别后:有效 PDF 仍为 2;未触碰 PDF 保留源 Run 版本。
assert task['file_count'] == 2
assert task['title'] is None
assert task['display_kind'] == 'multi_document_task'
@@ -456,7 +485,7 @@ def test_partial_reparse_keeps_unaffected_pdf_from_source_run(app):
def test_same_filename_different_hash_counts_as_two_pdfs(app):
"""同名不同 hash:file_count=2,不得按文件名误合并。"""
"""???? hash?file_count=2???????????"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-NAME')
run, _ = create_order_extraction_run(
@@ -496,7 +525,7 @@ def test_same_filename_different_hash_counts_as_two_pdfs(app):
def test_same_hash_different_document_id_counts_as_one_pdf(app):
"""同 hash 不同 document_id(重传):file_count=1。"""
"""? hash ?? document_id?????file_count=1?"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SAME-HASH')
run, _ = create_order_extraction_run(
@@ -535,14 +564,15 @@ def test_same_hash_different_document_id_counts_as_one_pdf(app):
)
assert task['file_count'] == 1
assert task['display_kind'] == 'single_document_task'
assert task['title'] == 'order.pdf'
# BE-05: title ?? None?? hash ???????????
assert task['title'] is None
doc_objects = [obj for obj in (task.get('objects') or []) if obj.get('kind') == 'document']
assert len(doc_objects) == 1
assert doc_objects[0]['document_id'] == 22
def test_sparse_snapshot_enriched_by_extraction_units(app):
"""快照仅 1 PDF 但 Unit 已拆 2 份时,投影须 multi + file_count=2。"""
"""??? 1 PDF ? Unit ?? 2 ?????? multi + file_count=2?"""
from app.models import (
FileAsset,
ShippingOrderDocument,
@@ -589,7 +619,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app):
keep_input_open=True,
)
_ensure_run_order_task(run=run, intake=intake, document=document)
# 故意只写 1 份进快照,模拟生产侧栏仍显示单文件名的脏数据。
# ???? 1 ???????????????????????
_set_run_documents(run, [{
'document_id': int(document.id),
'root_document_id': int(document.id),
@@ -630,7 +660,7 @@ def test_sparse_snapshot_enriched_by_extraction_units(app):
@pytest.mark.skip(reason='workflow ledger removed')
def test_sparse_snapshot_enriched_by_workflow_items(app):
"""快照仅 1 PDF 但同 Run 已有 2 个 WorkflowItem 时,投影须 multi。"""
"""??? 1 PDF ?? Run ?? 2 ? WorkflowItem ????? multi?"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-SPARSE-W')
from app.models import FileAsset, ShippingOrderDocument
@@ -715,3 +745,95 @@ def test_sparse_snapshot_enriched_by_workflow_items(app):
assert task['display_kind'] == 'multi_document_task'
assert task['title'] is None
assert 'peer.pdf' in (task.get('document_names') or [])
def test_primary_action_falls_back_to_focus_task_never_cancel(app, monkeypatch):
"""BE-01: no business entry -> primary_action=focus_task; never cancel/view_details."""
with app.app_context():
from app.services.shipping_notice import conversation_processing_projection as proj_mod
from app.services.shipping_notice import order_extraction_workspace_projection as ws_mod
user, agent, session, intake, document = _seed_run_input(suffix='PROJ-FOCUS')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run, intake=intake, document=document)
db.session.commit()
monkeypatch.setattr(
ws_mod,
'_run_available_actions',
lambda _run, _units: ['cancel_run', 'view_details'],
)
primary, actions = proj_mod._resolve_task_actions(run)
assert primary == 'focus_task'
assert 'focus_task' in actions
assert 'view_details' in actions
assert 'cancel_task' in actions or 'cancel_run' in actions
assert primary not in {'cancel_task', 'cancel_run', 'view_details'}
def test_summary_has_more_and_returned_metadata_when_truncated(app):
"""BE-04: after list truncate, summary keeps full counts + has_more/returned."""
with app.app_context():
user, agent, session, intake_a, document_a = _seed_run_input(suffix='PROJ-T0')
run_a, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_a.intake_no],
keep_input_open=True,
)
_ensure_run_order_task(run=run_a, intake=intake_a, document=document_a)
run_a.status = 'processing'
run_a.phase = 'extracting'
db.session.commit()
for suffix, agent_code in (
('PROJ-T1', 'shipping_notice_proj_t1'),
('PROJ-T2', 'shipping_notice_proj_t2'),
('PROJ-T3', 'shipping_notice_proj_t3'),
):
_, _, _, intake_x, document_x = _seed_run_input(suffix=suffix, agent_code=agent_code)
intake_x.user_id = user.id
intake_x.conversation_id = session.session_id
db.session.commit()
run_x, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake_x.intake_no],
allow_parallel_conversation_runs=True,
keep_input_open=True,
)
_ensure_run_order_task(run=run_x, intake=intake_x, document=document_x)
run_x.status = 'processing'
run_x.phase = 'extracting'
db.session.commit()
projection = project_conversation_processing(
user_id=user.id,
conversation_id=session.session_id,
limit=2,
history_limit=1,
)
summary = projection['summary']
returned_active = (
len(projection['needs_action'])
+ len(projection['processing'])
+ len(projection.get('completed') or [])
)
# Assert: full counts stay ahead of returned lists; truncate flags match.
assert summary['total_tasks'] >= 4
assert summary['total_tasks'] >= returned_active
assert summary.get('returned', {}).get('needs_action') == len(projection['needs_action'])
assert summary.get('returned', {}).get('processing') == len(projection['processing'])
assert summary.get('returned', {}).get('completed') == len(projection.get('completed') or [])
assert summary.get('returned', {}).get('history') == len(projection.get('history') or [])
assert summary.get('has_more_active') is True
assert summary.get('truncated', {}).get('active') is True
assert returned_active == 2
@@ -0,0 +1,239 @@
"""
tests/test_shipping_review_workbench_state_isolation.py
用途:锁定复核工作台状态隔离契约——profile_match 管理员裁剪、automation 资格分层、
Validation Snapshot 身份字段、用户 Gate 不把客户确认/技术 pending 当优先处理。
依赖:pytest、order_review_projection、process_gate_projection、types.SimpleNamespace。
逻辑:纯单元/轻量投影测试;不启 Flask 全应用。
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
from app.services.shipping_notice.order_review_projection import (
_project_case_automation_status,
)
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
def test_automation_waiting_to_start_when_eligible_but_not_queued():
"""资格达标且未建单时只能是 waiting_to_start,不得伪装 running。"""
case = SimpleNamespace(
status='ready',
confirmed_task_id=None,
document_id=10,
current_draft=SimpleNamespace(draft_version=1, updated_at=None),
run=SimpleNamespace(run_no='RUN-1'),
updated_at=None,
)
with patch(
'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job',
return_value=None,
), patch(
'app.services.shipping_notice.order_review_projection._stp_waiting_timeout_seconds',
return_value=3600,
):
result = _project_case_automation_status(
case,
validation={'can_build': True, 'can_auto_create': True},
post_confirm=None,
)
assert result['status'] == 'waiting_to_start'
assert result['retryable'] is False
assert result['task_no'] is None
def test_automation_queued_when_stp_job_exists():
"""存在 queued STP Job 时投影 queued,不得停留在 waiting_to_start。"""
case = SimpleNamespace(
status='ready',
confirmed_task_id=None,
document_id=10,
current_draft=SimpleNamespace(draft_version=2, updated_at=None),
run=SimpleNamespace(run_no='RUN-1'),
updated_at=None,
)
job = SimpleNamespace(id=99, status='queued')
with patch(
'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job',
return_value=job,
):
result = _project_case_automation_status(
case,
validation={'can_build': True, 'can_auto_create': True},
post_confirm=None,
)
assert result['status'] == 'queued'
assert result['job_id'] == 99
assert result['retryable'] is False
def test_automation_failed_retryable_when_post_confirm_needs_retry():
"""确认后推进失败必须可重试,不能只显示已确认。"""
case = SimpleNamespace(status='confirmed', confirmed_task_id=12)
result = _project_case_automation_status(
case,
validation={'can_build': True, 'can_auto_create': True},
post_confirm={
'task_no': 'SN-1',
'needs_retry': True,
'status': 'needs_retry',
'task_process_status': 'created',
},
)
assert result['status'] == 'failed'
assert result['retryable'] is True
assert result['task_no'] == 'SN-1'
def test_serialize_review_case_hides_profile_match_for_non_admin():
"""普通用户不得收到模板 ID / 候选分;仅 admin_only 占位。"""
from app.services.shipping_notice.order_review_projection import serialize_review_case
case = SimpleNamespace(
id=1,
case_no='SORC-1',
run_id=1,
unit_id=None,
document_id=10,
candidate_id=None,
status='ready',
disposition=None,
confirmed_task_id=None,
current_draft=None,
run=SimpleNamespace(
run_no='RUN-1',
schema_version_id=1,
input_snapshot_json={'schema': {'definition': {'fields': []}}, 'documents': []},
),
)
with patch(
'app.services.shipping_notice.order_review_customer_service.project_review_case_customer_resolution',
return_value={'resolved': True},
), patch(
'app.services.shipping_notice.order_review_field_conflict_service.project_review_case_field_conflicts',
return_value=[],
), patch(
'app.services.shipping_notice.order_review_duplicate_service.project_review_case_duplicate',
return_value={'needs_adjudication': False},
), patch(
'app.services.shipping_notice.order_review_reservation_service.project_review_case_reservation',
return_value=None,
), patch(
'app.services.shipping_notice.order_review_fulfillment_decision_service.project_review_case_line_decisions',
return_value=None,
), patch(
'app.services.shipping_notice.order_task_service.resolve_order_task_for_candidate',
return_value=None,
), patch(
'app.services.shipping_notice.order_review_projection.db',
) as mock_db, patch(
'app.models.ShippingProcessExecution',
) as mock_exec:
mock_db.session.get.return_value = None
mock_exec.query.filter_by.return_value.order_by.return_value.first.return_value = None
payload = serialize_review_case(case, is_admin=False)
assert payload['profile_match']['available'] is False
assert payload['profile_match']['visibility'] == 'admin_only'
assert payload['profile_match'].get('candidates') == []
assert payload['automation']['status'] in {'idle', 'waiting_to_start'}
def test_serialize_review_case_exposes_profile_match_for_admin():
"""管理员 is_admin=True 时须拿到完整 profile_match(UI-04 API 契约)。"""
from app.services.shipping_notice.order_review_projection import serialize_review_case
case = SimpleNamespace(
id=2,
case_no='SORC-2',
run_id=2,
unit_id=None,
document_id=11,
candidate_id=None,
status='ready',
disposition=None,
confirmed_task_id=None,
current_draft=None,
run=SimpleNamespace(
run_no='RUN-2',
schema_version_id=1,
input_snapshot_json={'schema': {'definition': {'fields': []}}, 'documents': []},
),
)
admin_payload = {
'available': True,
'visibility': 'admin',
'status': 'matched',
'candidates': [{'profile_id': 9, 'score': 0.91}],
'selected_profile': {'profile_id': 9, 'profile_code': 'P9'},
}
with patch(
'app.services.shipping_notice.order_review_customer_service.project_review_case_customer_resolution',
return_value={'resolved': True},
), patch(
'app.services.shipping_notice.order_review_field_conflict_service.project_review_case_field_conflicts',
return_value=[],
), patch(
'app.services.shipping_notice.order_review_duplicate_service.project_review_case_duplicate',
return_value={'needs_adjudication': False},
), patch(
'app.services.shipping_notice.order_review_reservation_service.project_review_case_reservation',
return_value=None,
), patch(
'app.services.shipping_notice.order_review_fulfillment_decision_service.project_review_case_line_decisions',
return_value=None,
), patch(
'app.services.shipping_notice.order_task_service.resolve_order_task_for_candidate',
return_value=None,
), patch(
'app.services.shipping_notice.order_review_profile_match_service.project_review_case_profile_match',
return_value=admin_payload,
), patch(
'app.services.shipping_notice.order_review_projection.db',
) as mock_db, patch(
'app.models.ShippingProcessExecution',
) as mock_exec:
mock_db.session.get.return_value = None
mock_exec.query.filter_by.return_value.order_by.return_value.first.return_value = None
payload = serialize_review_case(case, is_admin=True)
assert payload['profile_match']['available'] is True
assert payload['profile_match']['visibility'] == 'admin'
assert payload['profile_match']['candidates'][0]['profile_id'] == 9
def test_project_user_gate_summary_clears_stale_confirm_customer(monkeypatch):
"""无阻断时不得残留 confirm_customer 下一步。"""
execution = SimpleNamespace(execution_no='EX-1', id=1)
def fake_serialize(_execution, include_diagnostics=False):
return {
'execution_no': 'EX-1',
'status': 'running',
'current_gate': {
'gate_code': 'document_materialization',
'status': 'pending',
'blocking_reason_code': None,
},
'primary_next_action_code': 'confirm_customer',
'responsible_party': 'system',
'gates': [],
}
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection.serialize_process_execution',
fake_serialize,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection._execution_navigation_refs',
lambda _e: {'case_no': 'SORC-1', 'review_case_no': 'SORC-1', 'review_run_no': 'RUN-1'},
)
summary = project_user_gate_summary(execution)
assert summary['current_blocking_gate'] is None
assert summary['next_action_code'] is None
@@ -0,0 +1,287 @@
"""
tests/test_shipping_stp_auto_create_api_integration.py
用途:STP 自动建单可重复集成验收——真实 ORM enqueue、Flask Client retry、
GET 无副作用、failed→retry_of、active 唯一语义。
依赖:pytest app fixture、Job 模型、order review 测试夹具、parse_api_*。
逻辑:资格校验可 stub(聚焦入队闭环);enqueue/Job/API 必须真实落库。
"""
from __future__ import annotations
from datetime import datetime, timezone
from unittest.mock import patch
import pytest
from app import db
from app.models import Job, User
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from app.services.shipping_notice.order_stp_auto_create_service import (
SHIPPING_STP_JOB_DOMAIN,
build_stp_idempotency_key,
)
from tests.conftest import parse_api_data, parse_api_error
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
def _eligible_validation() -> dict:
return {
'status': 'ready',
'can_build': True,
'can_auto_create': True,
'failed_gates': [],
'issues': [],
'validated_at': datetime.now(timezone.utc).isoformat(),
'validation_checksum': 'stp-api-itest-v1',
}
def _count_stp_jobs(business_ref: str) -> int:
return int(
Job.query.filter_by(
domain=SHIPPING_STP_JOB_DOMAIN,
job_type='shipping_stp_auto_create',
business_ref=business_ref,
).count()
)
def _active_stp_jobs(business_ref: str) -> list[Job]:
return (
Job.query.filter(
Job.domain == SHIPPING_STP_JOB_DOMAIN,
Job.job_type == 'shipping_stp_auto_create',
Job.business_ref == business_ref,
Job.status.in_(('queued', 'running')),
)
.order_by(Job.id.asc())
.all()
)
def _seed_eligible_case(app, *, suffix: str):
"""创建可登录 owner + eligible Case(资格由 _validation stub 保证)。"""
from app.services.shipping_notice.order_extraction_run_service import (
transition_order_extraction_run,
)
user, agent, session, intake, _document = _seed_run_input(suffix=suffix)
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
run.run_no = f'SNER-ITEST-{suffix}'
transition_order_extraction_run(run, target_status='processing')
transition_order_extraction_run(run, target_status='review_required', result={})
case = ensure_run_review_cases(run=run)[0]
draft = case.current_draft
assert draft is not None
draft.validation_result_json = _eligible_validation()
draft.issue_summary_json = []
case.status = 'ready'
db.session.commit()
return user, run, case, draft
@pytest.fixture
def stp_eligibility_stubs(monkeypatch):
"""真实 enqueue 前提下 stub 资格评估,避免耦合完整 Gate 链。"""
from app.services.shipping_notice import order_stp_auto_create_service as svc
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)
def test_stp_retry_api_enqueues_reuses_and_get_has_no_side_effect(app, stp_eligibility_stubs):
"""Flask Client POST retry:真实 Job、幂等复用、GET 不入队。"""
with app.app_context():
user, run, case, draft = _seed_eligible_case(app, suffix='STPAPI1')
business_ref = build_stp_idempotency_key(
run_no=str(run.run_no),
document_id=int(case.document_id),
draft_version=int(draft.draft_version),
)
before = _count_stp_jobs(business_ref)
from app.core.auth.jwt import issue_local_access_token
client = app.test_client()
headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'}
get_before = client.get(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}',
headers=headers,
)
assert get_before.status_code == 200
assert _count_stp_jobs(business_ref) == before
first = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry',
headers=headers,
)
assert first.status_code == 200
first_body = first.get_json()
first_data = parse_api_data(first_body)
assert first_body.get('success') is True
assert first_data['status'] in {'queued', 'reused'}
assert first_data['job_id']
assert first_data['business_ref'] == business_ref
assert _count_stp_jobs(business_ref) == before + 1
assert len(_active_stp_jobs(business_ref)) == 1
job_id = int(first_data['job_id'])
second = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry',
headers=headers,
)
assert second.status_code == 200
second_data = parse_api_data(second.get_json())
assert second_data['status'] == 'reused'
assert int(second_data['job_id']) == job_id
assert second_data['business_ref'] == business_ref
assert len(_active_stp_jobs(business_ref)) == 1
assert _count_stp_jobs(business_ref) == before + 1
get_after = client.get(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}',
headers=headers,
)
assert get_after.status_code == 200
assert _count_stp_jobs(business_ref) == before + 1
def test_stp_retry_api_failed_job_creates_retry_of_chain(app, stp_eligibility_stubs):
"""failed Job 后 retry 生成新 Job 并写入 retry_of_job_id,仅一个 active。"""
with app.app_context():
user, run, case, draft = _seed_eligible_case(app, suffix='STPAPI2')
business_ref = build_stp_idempotency_key(
run_no=str(run.run_no),
document_id=int(case.document_id),
draft_version=int(draft.draft_version),
)
from app.core.auth.jwt import issue_local_access_token
client = app.test_client()
headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'}
first = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry',
headers=headers,
)
first_data = parse_api_data(first.get_json())
old_id = int(first_data['job_id'])
old = db.session.get(Job, old_id)
assert old is not None
old.status = 'failed'
old.message = 'itest forced failed'
db.session.commit()
retry = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry',
headers=headers,
)
assert retry.status_code == 200
retry_data = parse_api_data(retry.get_json())
assert retry_data['status'] == 'queued'
new_id = int(retry_data['job_id'])
assert new_id != old_id
assert int(retry_data.get('retry_of_job_id') or 0) == old_id
assert retry_data['business_ref'] == business_ref
active = _active_stp_jobs(business_ref)
assert len(active) == 1
assert int(active[0].id) == new_id
retained = db.session.get(Job, old_id)
assert retained is not None
assert retained.status == 'failed'
def test_stp_retry_api_confirmed_returns_localized_code(app, stp_eligibility_stubs):
"""已 confirmed Case 的 retry 返回 SHIPPING.STP_RETRY_ALREADY_CONFIRMED envelope。"""
with app.app_context():
user, _run, case, _draft = _seed_eligible_case(app, suffix='STPAPI3')
case.status = 'confirmed'
case.confirmed_task_id = 1
db.session.commit()
from app.core.auth.jwt import issue_local_access_token
client = app.test_client()
headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'}
response = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry',
headers=headers,
)
assert response.status_code == 409
error = parse_api_error(response.get_json())
assert error.get('code') == 'SHIPPING.STP_RETRY_ALREADY_CONFIRMED'
def test_stp_retry_api_not_eligible_uses_shipping_stp_code(app, monkeypatch):
"""资格失败时顶层 code 必须为 SHIPPING.STP_NOT_ELIGIBLE,细粒度进 details。"""
from app.services.shipping_notice import order_stp_auto_create_service as svc
with app.app_context():
user, _run, case, _draft = _seed_eligible_case(app, suffix='STPAPI4')
monkeypatch.setattr(
svc,
'ensure_stp_auto_create_for_case',
lambda **_kwargs: {
'status': 'skipped_needs_review',
'error_code': 'xfa_shadow_mode',
'blocking_reason_codes': ['xfa_shadow_mode'],
'job_id': None,
},
)
from app.core.auth.jwt import issue_local_access_token
client = app.test_client()
headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'}
response = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/stp-auto-create/retry',
headers=headers,
)
assert response.status_code == 400
error = parse_api_error(response.get_json())
assert error.get('code') == 'SHIPPING.STP_NOT_ELIGIBLE'
details = error.get('details') or {}
assert 'xfa_shadow_mode' in list(details.get('blocking_reason_codes') or [])
@pytest.mark.postgres
def test_stp_active_partial_unique_on_postgres(app, stp_eligibility_stubs):
"""PostgreSQL 部分唯一索引:同 business_ref 第二次插入不得产生第二个 active Job。"""
with app.app_context():
if db.engine.dialect.name != 'postgresql':
pytest.skip('requires PostgreSQL')
user, run, case, draft = _seed_eligible_case(app, suffix='STPPG1')
business_ref = build_stp_idempotency_key(
run_no=str(run.run_no),
document_id=int(case.document_id),
draft_version=int(draft.draft_version),
)
from app.jobs.queue import enqueue
from app.jobs.types import JobType
first_id = enqueue(
JobType.SHIPPING_STP_AUTO_CREATE,
{'case_no': case.case_no},
domain=SHIPPING_STP_JOB_DOMAIN,
business_ref=business_ref,
created_by_id=int(user.id),
message='pg unique first',
commit=True,
)
# 关闭应用层 dedupe,仅依赖部分唯一索引 + IntegrityError 回落。
second_id = enqueue(
JobType.SHIPPING_STP_AUTO_CREATE,
{'case_no': case.case_no},
domain=SHIPPING_STP_JOB_DOMAIN,
business_ref=business_ref,
created_by_id=int(user.id),
message='pg unique second',
dedupe_statuses=(),
dedupe_active=False,
commit=True,
)
assert int(second_id) == int(first_id)
assert len(_active_stp_jobs(business_ref)) == 1
@@ -0,0 +1,172 @@
"""
tests/test_shipping_stp_auto_create_enqueue.py
用途:锁定 STP 自动建单入队 / 显式重试 / Projection / retry_of_job_id 契约。
依赖:pytest、order_stp_auto_create_service、Job 模型、unittest.mock。
逻辑:不依赖 Worker 消费;覆盖幂等复用、failed→retry 新 Job、GET 无入队副作用断言辅助。
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
def test_ensure_stp_reuses_active_job_without_duplicate(app):
"""queued/running 时复用同一 Job,不得再 enqueue。"""
from app.services.shipping_notice import order_stp_auto_create_service as svc
case = SimpleNamespace(
id=1,
case_no='SORC-STP-1',
status='ready',
confirmed_task_id=None,
document_id=10,
candidate_id=None,
disposition=None,
run_id=1,
run=SimpleNamespace(run_no='SNER-TEST-1', id=1),
owner_user_id=1,
current_draft=SimpleNamespace(
draft_version=2,
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
issue_summary_json=[],
),
)
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, '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,
), patch.object(svc, 'enqueue') as enqueue_mock, patch.object(svc, 'record_fulfillment_audit'), patch.object(
svc, 'db',
):
result = svc.ensure_stp_auto_create_for_case(case=case, commit=False)
assert result['status'] in {'reused', 'already_queued', 'queued'}
assert result['job_id'] == 77
enqueue_mock.assert_not_called()
def test_ensure_stp_force_retry_keeps_failed_and_sets_retry_of(app):
"""force_retry 时保留 failed Job,新建 Job 并挂 retry_of_job_id。"""
from app.services.shipping_notice import order_stp_auto_create_service as svc
case = SimpleNamespace(
id=2,
case_no='SORC-STP-2',
status='ready',
confirmed_task_id=None,
document_id=11,
candidate_id=None,
disposition=None,
run_id=2,
run=SimpleNamespace(run_no='SNER-TEST-2', id=2),
owner_user_id=1,
current_draft=SimpleNamespace(
draft_version=1,
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
issue_summary_json=[],
),
)
failed = SimpleNamespace(id=50, status='failed', retry_of_job_id=None)
new_job = SimpleNamespace(id=51, status='queued', retry_of_job_id=None)
def _enqueue(*args, **kwargs):
del args, kwargs
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, '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,
), patch.object(svc, 'enqueue', side_effect=_enqueue), patch.object(
svc, 'record_fulfillment_audit',
), patch.object(svc, 'db') as mock_db:
mock_db.session.get.return_value = new_job
mock_db.session.flush = MagicMock()
result = svc.ensure_stp_auto_create_for_case(case=case, commit=False, force_retry=True)
assert result['status'] == 'queued'
assert result['job_id'] == 51
assert result.get('retry_of_job_id') == 50
assert new_job.retry_of_job_id == 50
def test_retry_stp_auto_create_for_case_rejects_confirmed(app):
"""已 confirmed Case 不得走 STP retry,须走确认后推进重试。"""
from app.core.errors import ConflictError
from app.services.shipping_notice import order_stp_auto_create_service as svc
case = SimpleNamespace(
case_no='SORC-STP-3',
status='confirmed',
confirmed_task_id=9,
)
with patch(
'app.services.shipping_notice.order_review_service.get_review_case_visible_to_user',
return_value=case,
):
with pytest.raises(ConflictError) as exc:
svc.retry_stp_auto_create_for_case(user_id=1, case_no='SORC-STP-3')
assert exc.value.code == 'SHIPPING.STP_RETRY_ALREADY_CONFIRMED'
def test_retry_stp_raises_structured_error_when_enqueue_not_queued(app):
"""入队失败必须抛业务错误,禁止伪装成功。"""
from app.core.errors import ValidationError
from app.services.shipping_notice import order_stp_auto_create_service as svc
case = SimpleNamespace(
case_no='SORC-STP-4',
status='ready',
confirmed_task_id=None,
)
with patch(
'app.services.shipping_notice.order_review_service.get_review_case_visible_to_user',
return_value=case,
), patch.object(
svc,
'ensure_stp_auto_create_for_case',
return_value={'status': 'not_eligible', 'error_code': 'SHIPPING.STP_NOT_ELIGIBLE', 'job_id': None},
):
with pytest.raises(ValidationError) as exc:
svc.retry_stp_auto_create_for_case(user_id=1, case_no='SORC-STP-4')
assert 'SHIPPING.STP' in str(exc.value.code)
assert exc.value.code == 'SHIPPING.STP_NOT_ELIGIBLE'
def test_automation_projection_uses_active_job_over_failed_history(app):
"""Projection 只认当前有效 Job;failed 历史不得冒充 queued。"""
from app.services.shipping_notice.order_review_projection import _project_case_automation_status
case = SimpleNamespace(
status='ready',
confirmed_task_id=None,
document_id=10,
current_draft=SimpleNamespace(draft_version=2, updated_at=None),
run=SimpleNamespace(run_no='RUN-P'),
updated_at=None,
)
active = SimpleNamespace(id=88, status='queued', retry_of_job_id=50)
with patch(
'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job',
return_value=active,
), patch(
'app.services.shipping_notice.order_stp_auto_create_service.find_latest_stp_job',
return_value=SimpleNamespace(id=50, status='failed'),
):
result = _project_case_automation_status(
case,
validation={'can_build': True, 'can_auto_create': True},
post_confirm=None,
)
assert result['status'] == 'queued'
assert result['job_id'] == 88
@@ -0,0 +1,201 @@
"""
tests/test_shipping_workbench_action_contract.py
用途:订单处理工作台动作契约——表驱动全量码 + 关键写链阶段族约束。
依赖:processing_projection_invariants、progress_audit_contract、pytest。
逻辑:不连库;断言每个合法 action_code 可规范化到意图;建单前剔除履约动作;
关键写链在 post_create 投影中保留并可映射。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.processing_projection_invariants import (
derive_available_actions,
normalize_action_code,
reconcile_processing_projection_facts,
)
from app.services.shipping_notice.progress_audit_contract import (
SHIPPING_PROCESSING_ACTION_INTENTS,
)
# action_code → (intent, stage_family, review_behavior)
# stage_family: pre_create | post_create | any | terminal
# review_behavior: hidden | open_customer_dialog | focus_* | open_inventory_candidates |
# todo | download | retry | view_result | view_record | refresh_strip
_TABLE: list[tuple[str, str, str, str]] = [
('open_order_review', 'open_order_review', 'pre_create', 'hidden'),
('edit_formal_task', 'edit_formal_task', 'any', 'hidden'),
('open_profile_review', 'open_profile_review', 'pre_create', 'focus_profile_panel'),
('confirm_customer', 'confirm_customer', 'pre_create', 'open_customer_dialog'),
('resolve_field_conflicts', 'resolve_field_conflicts', 'pre_create', 'focus_field_conflicts'),
('adjudicate_duplicate', 'adjudicate_duplicate', 'pre_create', 'focus_duplicate_panel'),
('open_inventory_source_review', 'open_inventory_source_review', 'pre_create', 'open_inventory_candidates'),
('confirm_inventory_source', 'open_inventory_source_review', 'post_create', 'todo'),
('match_inventory', 'open_inventory_match_review', 'post_create', 'todo'),
('rematch', 'open_inventory_match_review', 'post_create', 'todo'),
('open_shortage_review', 'open_shortage_review', 'post_create', 'focus_inventory_issues'),
('upload_inventory_file', 'upload_inventory_file', 'post_create', 'todo'),
('generate_excel', 'regenerate_excel', 'post_create', 'todo'),
('regenerate_excel', 'regenerate_excel', 'post_create', 'todo'),
('download_excel', 'download_excel', 'post_create', 'download'),
('mark_manual_uploaded', 'open_manual_upload', 'post_create', 'todo'),
('open_manual_upload', 'open_manual_upload', 'post_create', 'todo'),
('retry', 'retry', 'any', 'retry'),
('retry_parse', 'retry', 'pre_create', 'retry'),
('refresh', 'refresh', 'any', 'refresh_strip'),
('view_result', 'view_result', 'terminal', 'view_result'),
('open_fulfillment', 'view_result', 'terminal', 'view_result'),
('view_record', 'view_record', 'any', 'view_record'),
]
@pytest.mark.parametrize('action_code,intent,_family,_behavior', _TABLE)
def test_action_code_normalizes_to_contract_intent(action_code, intent, _family, _behavior):
"""每个合法动作码必须映射到契约意图集合。"""
mapped = normalize_action_code(action_code)
assert mapped == intent
assert mapped in SHIPPING_PROCESSING_ACTION_INTENTS
def test_unknown_action_code_is_dropped():
"""未知码不得泄漏到 available_actions。"""
assert normalize_action_code('totally_unknown_action_xyz') is None
def test_pre_create_projection_strips_fulfillment_actions():
"""建单前禁止下发匹配/Excel/上传等履约动作。"""
payload = reconcile_processing_projection_facts({
'status': 'blocked',
'stage': 'waiting_review',
'source_type': 'direct_pdf',
'shipping_notice_no': None,
'current_gate': {
'gate_code': 'order_review',
'status': 'blocked',
'next_action_code': 'confirm_customer',
'blocking_reason_code': 'customer_unresolved',
'attempt_no': 1,
},
'available_actions': [
'confirm_customer',
'match_inventory',
'generate_excel',
'open_manual_upload',
'download_excel',
],
}, excel_ready=True)
actions = set(payload['available_actions'])
assert 'confirm_customer' in actions
assert 'match_inventory' not in actions
assert 'open_inventory_match_review' not in actions
assert 'regenerate_excel' not in actions
assert 'open_manual_upload' not in actions
assert 'download_excel' not in actions
def test_post_create_projection_keeps_fulfillment_write_chain():
"""正式 Notice 存在时保留关键履约写链动作。"""
actions = derive_available_actions(
status='blocked',
stage='inventory_matching',
gate={
'gate_code': 'inventory_match',
'status': 'blocked',
'next_action_code': 'match_inventory',
'blocking_reason_code': 'inventory_shortage',
'attempt_no': 1,
},
legacy_actions=['download_excel'],
excel_ready=True,
shipping_notice_no='SN-100',
)
assert actions[0] == 'open_inventory_match_review'
assert 'download_excel' in actions
def test_confirm_customer_is_not_aliased_to_open_order_review():
"""客户确认不得被折叠为 open_order_review(工作台需独立导航执行)。"""
assert normalize_action_code('confirm_customer') == 'confirm_customer'
def test_notice_no_with_pre_create_stage_strips_fulfillment_actions():
"""有正式号但 stage 仍在建单前:fail-closed 清空履约动作,保留建单前 Gate 动作。"""
from app.services.shipping_notice.processing_projection_invariants import (
PROJECTION_INCONSISTENT_ERROR_CODE,
)
payload = reconcile_processing_projection_facts({
'status': 'blocked',
'stage': 'waiting_review',
'source_type': 'direct_pdf',
'work_item_no': 'OT-1',
'shipping_notice_no': 'SN-STALE',
'current_gate': {
'gate_code': 'order_review',
'status': 'blocked',
'next_action_code': 'confirm_customer',
'blocking_reason_code': 'customer_unresolved',
'attempt_no': 1,
},
'available_actions': [
'confirm_customer',
'match_inventory',
'generate_excel',
'open_manual_upload',
'download_excel',
],
}, excel_ready=True)
actions = set(payload['available_actions'])
assert 'confirm_customer' in actions
assert 'match_inventory' not in actions
assert 'open_inventory_match_review' not in actions
assert 'regenerate_excel' not in actions
assert 'open_manual_upload' not in actions
assert 'download_excel' not in actions
assert payload.get('projection_inconsistency_code') == PROJECTION_INCONSISTENT_ERROR_CODE
def test_confirm_inventory_source_aliases_to_contract_intent():
"""建单后库存确认仍映射契约意图;前端按 postCreate 分叉执行器。"""
assert normalize_action_code('confirm_inventory_source') == 'open_inventory_source_review'
assert normalize_action_code('open_inventory_source_review') == 'open_inventory_source_review'
def test_pre_create_keeps_inventory_source_review_but_strips_match():
"""建单前可下发库存源复核,但禁止匹配等履约写动作。"""
actions = derive_available_actions(
status='blocked',
stage='waiting_review',
gate={
'gate_code': 'inventory_source_routing',
'status': 'blocked',
'next_action_code': 'open_inventory_source_review',
'blocking_reason_code': 'require_manual_review',
'attempt_no': 1,
},
legacy_actions=['match_inventory', 'generate_excel'],
excel_ready=False,
shipping_notice_no=None,
)
assert 'open_inventory_source_review' in actions
assert 'open_inventory_match_review' not in actions
assert 'regenerate_excel' not in actions
def test_post_create_inventory_source_gate_keeps_contract_intent():
"""正式 Notice 存在时库存源 Gate 仍投影为契约意图码。"""
actions = derive_available_actions(
status='blocked',
stage='inventory_fetching',
gate={
'gate_code': 'inventory_source_routing',
'status': 'blocked',
'next_action_code': 'confirm_inventory_source',
'blocking_reason_code': 'require_manual_review',
'attempt_no': 1,
},
shipping_notice_no='SN-200',
)
assert actions[0] == 'open_inventory_source_review'
@@ -0,0 +1,164 @@
"""
tests/test_shipping_workbench_service_chains.py
用途:订单处理工作台四条履约链的「服务级拆链验证」(非完整 HTTP E2E)。
依赖:pytest、app fixture、order_task_stage_machine.sync_order_task_stage_for_notice、
shipping_processing_projection._project_order_task_work_item、既有 seed helpers。
逻辑:模拟写服务成功后的 Notice/OT 状态 → sync → 投影组装;
断言 stage / current_gate / available_actions / progress_version。
测试名与文档明确标注为服务级拆链,不得表述为完整 E2E。
"""
from __future__ import annotations
import pytest
from app import db
@pytest.fixture
def workbench_chain_ids(app):
"""构造挂接 Notice 的 OT + Run,仅返回主键供测试内重新加载。"""
with app.app_context():
from app.models import ShippingNotice, ShippingOrderTask
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='WB-CHAIN')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
notice = ShippingNotice(
task_no='SN-WB-CHAIN-1',
user_id=user.id,
conversation_id=session.session_id,
source_type='manual',
process_status='draft',
current_step='step3_confirm_customer',
)
db.session.add(notice)
db.session.flush()
order_task = ShippingOrderTask(
task_no='OT-WB-CHAIN-1',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=int(run.id),
shipping_notice_id=int(notice.id),
status='processing',
stage='waiting_review',
progress_version=1,
)
db.session.add(order_task)
db.session.flush()
notice.order_task_id = int(order_task.id)
run.user_task_no = order_task.task_no
db.session.commit()
return {
'run_id': int(run.id),
'notice_id': int(notice.id),
'order_task_id': int(order_task.id),
}
def _load_chain(ids: dict[str, int]):
"""按主键加载 Run/Notice/OT,避免跨 app_context 会话脱离。"""
from app.models import ShippingNotice, ShippingOrderProcessingRun, ShippingOrderTask
run = db.session.get(ShippingOrderProcessingRun, ids['run_id'])
notice = db.session.get(ShippingNotice, ids['notice_id'])
order_task = db.session.get(ShippingOrderTask, ids['order_task_id'])
assert run is not None and notice is not None and order_task is not None
return run, notice, order_task
def _project_after_sync(notice, order_task, run):
"""写后同步 OT 阶段并返回投影(服务级拆链公共步骤)。"""
from app.services.shipping_notice.order_task_stage_machine import (
sync_order_task_stage_for_notice,
)
from app.services.shipping_notice.shipping_processing_projection import (
_project_order_task_work_item,
)
before_version = int(getattr(order_task, 'progress_version', None) or 1)
sync_order_task_stage_for_notice(notice, order_task=order_task)
db.session.commit()
db.session.refresh(order_task)
projection = _project_order_task_work_item(run)
return before_version, projection
def test_service_chain_customer_confirm_projection(app, workbench_chain_ids):
"""
服务级拆链:客户确认后(Notice 进入建单/履约准备)投影 stage/actions/version。
非完整 E2E:不调用 confirm_customer HTTP,直接写入确认后业务态再 sync+project。
"""
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.process_status = 'building_order'
notice.current_step = 'step4_match_inventory'
notice.customer_id = 1
db.session.commit()
before, projection = _project_after_sync(notice, order_task, run)
assert projection['shipping_notice_no'] == notice.task_no
assert projection['stage'] in {
'order_creating', 'inventory_fetching', 'inventory_matching', 'waiting_review',
}
assert isinstance(projection.get('available_actions'), list)
assert int(projection['progress_version']) >= before
def test_service_chain_inventory_match_projection(app, workbench_chain_ids):
"""
服务级拆链:库存匹配/重匹配后投影。
非完整 E2E:写入匹配中/匹配完成态后 sync+project。
"""
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.process_status = 'inventory_matching'
notice.current_step = 'step4_match_inventory'
db.session.commit()
before, projection = _project_after_sync(notice, order_task, run)
assert projection['stage'] in {'inventory_matching', 'inventory_fetching', 'excel_generating'}
assert projection['progress_version'] >= before
assert projection.get('current_gate') is None or isinstance(projection['current_gate'], dict)
assert isinstance(projection.get('available_actions'), list)
def test_service_chain_excel_generate_projection(app, workbench_chain_ids):
"""
服务级拆链:Excel 生成后投影。
非完整 E2E:写入 waiting_upload / export 就绪态后 sync+project。
"""
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.process_status = 'waiting_upload'
notice.current_step = 'step7_upload_freight'
notice.export_file_path = '/tmp/fake-shipping.xlsx'
db.session.commit()
before, projection = _project_after_sync(notice, order_task, run)
assert projection['stage'] == 'freight_uploading'
assert projection['status'] in {'automating', 'blocked', 'processing', 'needs_action'}
assert int(projection['progress_version']) >= before
assert isinstance(projection.get('available_actions'), list)
def test_service_chain_freight_upload_retry_projection(app, workbench_chain_ids):
"""
服务级拆链:货代上传重试后投影。
非完整 E2E:写入上传失败待重试态后 sync+project(不走真实 RPA)。
"""
with app.app_context():
run, notice, order_task = _load_chain(workbench_chain_ids)
notice.process_status = 'upload_failed'
notice.current_step = 'step7_upload_freight'
notice.upload_status = 'failed'
notice.export_file_path = '/tmp/fake-shipping.xlsx'
db.session.commit()
before, projection = _project_after_sync(notice, order_task, run)
assert projection['stage'] == 'freight_uploading'
assert int(projection['progress_version']) >= before
actions = projection.get('available_actions') or []
assert all(isinstance(code, str) for code in actions)
@@ -131,8 +131,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_falls_back_to_generic(monkeypatch, xfa_pdf_bytes):
"""关键断言:Profile 未命中 → 回退通用/OCR/Dify 路径,保留 XFA 失败原因。"""
def test_route_deterministic_unit_xfa_no_match_does_not_fallback_to_generic(monkeypatch, xfa_pdf_bytes):
"""关键断言:Profile 未命中 → review_required 失败关闭,禁止通用/坐标正式回退。"""
outcome = analyze_xfa_pdf(xfa_pdf_bytes)
capability = outcome.snapshot['xfa_capability']
document = {
@@ -182,7 +182,6 @@ def test_route_deterministic_unit_xfa_no_match_falls_back_to_generic(monkeypatch
**decision,
'route_type': 'generic_deterministic',
'route_decision': 'needs_review',
'capability_kind': decision.get('capability_kind') or 'xfa_fallback_coordinate',
},
orders=[],
)
@@ -191,12 +190,20 @@ def test_route_deterministic_unit_xfa_no_match_falls_back_to_generic(monkeypatch
'app.services.shipping_notice.order_extraction_workflow._route_generic_deterministic_unit',
_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 True
assert route.decision.get('capability_kind') == 'xfa_fallback_coordinate'
codes = route.decision.get('fallback_reason_codes') or route.decision.get('xfa_fallback_reason_codes') or []
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
@@ -0,0 +1,239 @@
"""
tests/test_shipping_xfa_frozen_analysis.py
用途:锁定 BE-2——XFA 结构读取必须绑定 Layout 冻结的 structure_analysis_id。
依赖:resolve_frozen_xfa_structure_analysis、Flask app、内存 SQLite 模型。
逻辑:构造 Layout/Analysis 身份;断言禁止回退最新 Analysis。
"""
from __future__ import annotations
import hashlib
import secrets
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_analysis import (
resolve_frozen_xfa_structure_analysis,
)
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-frozen-{token}',
email=f'xfa-frozen-{token}@example.com',
role='user',
status='active',
)
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no=f'FA-XFA-FROZEN-{token}',
owner_user_id=user.id,
original_filename=f'{seed}.pdf',
storage_provider='minio',
storage_bucket='test',
storage_key=f'frozen/{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-FROZEN-{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 test_resolve_frozen_analysis_uses_layout_bound_id_not_latest(app):
"""关键断言:即使存在更新的 Analysis,仍必须读取 Layout 冻结的主键。"""
with app.app_context():
document = _seed_document(seed='frozen-latest')
older = 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={},
stats_json={},
security_summary_json={},
tree_summary_json={'known_path_ids': ['p1']},
parser_identity='xfa-parser.v1',
contract_version='xfa-contract.v1',
)
newer = 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-new',
datasets_packet_checksum='sha256:datasets-new',
dataset_structure_fingerprint='sha256:structure-new',
packet_checksums_json={},
stats_json={},
security_summary_json={},
tree_summary_json={'known_path_ids': ['p2']},
parser_identity='xfa-parser.v1',
contract_version='xfa-contract.v1',
)
db.session.add_all([older, newer])
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': older.id,
'template_packet_checksum': older.template_packet_checksum,
'dataset_structure_fingerprint': older.dataset_structure_fingerprint,
},
},
issues_json=[],
attempt_count=1,
)
db.session.add(layout)
db.session.flush()
older.layout_version_id = layout.id
document.current_layout_version_id = layout.id
db.session.commit()
_version, analysis, capability = resolve_frozen_xfa_structure_analysis(document)
assert int(analysis.id) == int(older.id)
assert int(analysis.id) != int(newer.id)
assert int(capability['structure_analysis_id']) == int(older.id)
assert int(_version.id) == int(layout.id)
def test_resolve_frozen_analysis_missing_id_fail_closed(app):
"""关键断言:Layout 缺少 structure_analysis_id 时抛 XFA_ANALYSIS_MISSING。"""
with app.app_context():
document = _seed_document(seed='missing-id')
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},
},
issues_json=[],
attempt_count=1,
)
db.session.add(layout)
db.session.flush()
document.current_layout_version_id = layout.id
db.session.commit()
with pytest.raises(ValidationError) as caught:
resolve_frozen_xfa_structure_analysis(document)
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_MISSING'
def test_resolve_frozen_analysis_identity_mismatch(app):
"""关键断言:Analysis 绑定其他 Document 时抛 IDENTITY_MISMATCH。"""
with app.app_context():
document = _seed_document(seed='mismatch-a')
other = _seed_document(seed='mismatch-b')
foreign = ShippingXfaStructureAnalysis(
document_id=other.id,
layout_version_id=None,
source_content_hash=other.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={},
stats_json={},
security_summary_json={},
tree_summary_json={},
parser_identity='xfa-parser.v1',
contract_version='xfa-contract.v1',
)
db.session.add(foreign)
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': foreign.id,
},
},
issues_json=[],
attempt_count=1,
)
db.session.add(layout)
db.session.flush()
document.current_layout_version_id = layout.id
db.session.commit()
with pytest.raises(ValidationError) as caught:
resolve_frozen_xfa_structure_analysis(document)
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_ANALYSIS_IDENTITY_MISMATCH'
@@ -0,0 +1,337 @@
"""
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 全栈。
"""
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,
)
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',
'mirror_collection_paths': [],
}
def _definition_with_binding(*, visual_status: str = 'suggested', region_kind: str = 'field') -> dict:
"""构造含统一 binding 的草稿 definition。"""
checksum = 'sha256:' + ('c' * 64)
visual = {
'page_no': 1,
'normalized_bbox': {'x0': 0.1, 'y0': 0.4, 'x1': 0.4, 'y1': 0.5},
'source': 'suggested',
'status': visual_status,
'confidence': 0.95,
'region_kind': region_kind,
}
if visual_status == 'confirmed':
visual.update({
'preview_render_checksum': checksum,
'render_mode': 'xfa_dataset_preview',
'confirmed_on': 'xfa_dataset_preview',
'renderer_version': 'hxops.xfa_static_preview.v1',
})
return {
'template_mode': 'xfa_dataset',
'source_contract': _source_contract(),
'header_mappings': [],
'line_mapping': {'row_path': '/data/ITEMS/DATA', 'fields': []},
'bindings': [{
'binding_id': 'bind-po-001',
'field_id': 'f-h-po',
'field_code': 'customer_po_no',
'scope': 'header',
'value_binding': {
'type': 'xfa_dataset',
'path_id': 'path-po',
'data_path': '/data/HEADER/EBELN',
},
'visual_binding': visual,
}],
'xfa_preview': {
'status': 'ready',
'preview_render_checksum': checksum,
'render_mode': 'xfa_dataset_preview',
'renderer_version': 'hxops.xfa_static_preview.v1',
'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。"""
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',
}
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_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'
@@ -0,0 +1,277 @@
"""
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
@@ -0,0 +1,124 @@
"""
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()
@@ -0,0 +1,61 @@
"""
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 == []
@@ -0,0 +1,320 @@
"""
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
@@ -177,6 +177,63 @@ def test_preview_token_rejects_replay(app):
assert caught.value.details.get('reason') == 'token_replay'
def test_redis_unavailable_fail_closed_outside_memory_allowlist(app, monkeypatch):
"""关键断言:非允许环境 Redis 不可用时须 STORE_UNAVAILABLE,不得内存消费成功。"""
with app.app_context():
app.config['TESTING'] = False
app.config['ENV_NAME'] = 'prod'
app.config['XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI'] = False
def _boom():
raise RuntimeError('redis down')
monkeypatch.setattr(
'app.services.redis_client.get_redis_client',
_boom,
)
rule = _rule_set(status='confirmed')
token = _issue_token(app, rule)
with pytest.raises(ValidationError) as caught:
verify_and_consume_split_preview_token(
token,
actor_id=7,
profile_id=11,
document_id=22,
path_id='path-a',
rule_fingerprint=split_rule_preview_fingerprint(rule),
sample_checksum=SAMPLE_CHECKSUM,
analysis_id=99,
template_packet_checksum=FAKE_PATH_CONTEXT['template_packet_checksum'],
dataset_structure_fingerprint=FAKE_PATH_CONTEXT['dataset_structure_fingerprint'],
)
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_STORE_UNAVAILABLE'
def test_confirm_integrity_propagates_store_unavailable(app, monkeypatch):
"""关键断言:确认保存路径不得把 STORE_UNAVAILABLE 误映射为 CONFIRM_REJECTED。"""
with app.app_context():
app.config['TESTING'] = False
app.config['ENV_NAME'] = 'prod'
app.config['XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI'] = False
monkeypatch.setattr(
'app.services.redis_client.get_redis_client',
lambda: (_ for _ in ()).throw(RuntimeError('redis down')),
)
rule = _rule_set(status='confirmed')
token = _issue_token(app, rule)
with pytest.raises(ValidationError) as caught:
_enforce_split_rule_confirmation_integrity(
previous_definition={},
definition={'split_rules': [rule]},
confirmation_tokens={'path-a': token},
actor_id=7,
profile_id=11,
document_id=22,
path_context=FAKE_PATH_CONTEXT,
)
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_CONFIRM_STORE_UNAVAILABLE'
def test_preview_token_rejects_sample_checksum_mismatch(app):
"""关键断言:样本 checksum 不匹配时确认须被拒绝。"""
with app.app_context():
@@ -248,6 +248,8 @@ def test_confirm_service_calls_record_audit_when_definition_ready():
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
@@ -105,10 +105,12 @@ def test_visual_binding_audit_events_registered():
def test_confirm_visual_binding_writes_before_after_audit(app):
"""确认视觉绑定必须写入 before/after 审计摘要。"""
"""确认视觉绑定必须写入 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': {
@@ -149,7 +151,7 @@ def test_confirm_visual_binding_writes_before_after_audit(app):
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:
svc.confirm_xfa_visual_binding(
result = svc.confirm_xfa_visual_binding(
1,
'bind-test-001',
visual_binding={
@@ -162,6 +164,8 @@ def test_confirm_visual_binding_writes_before_after_audit(app):
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
@@ -170,3 +174,71 @@ def test_confirm_visual_binding_writes_before_after_audit(app):
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'
)
@@ -29,7 +29,7 @@ def _source_contract() -> dict:
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,
@@ -46,6 +46,10 @@ def _confirmed_binding(*, field_id: str, field_code: str, status: str = 'confirm
'source': 'manual_draw',
'status': status,
'confidence': 1.0,
**({
'render_mode': 'native_pdf',
'confirmed_on': 'native_pdf',
} if status == 'confirmed' else {}),
},
}
@@ -86,13 +90,20 @@ def test_dual_binding_source_blocks_publish():
def test_unconfirmed_visual_binding_blocks_publish():
"""关键断言:正式字段视觉状态非 confirmed → xfa_visual_binding_incomplete。"""
"""关键断言:坐标类字段未确认视觉框 → 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': [_confirmed_binding(field_id='f-h-po', field_code='customer_po_no', status='suggested')],
'bindings': [coord],
}
blocking = _blocking_xfa_visual_bindings(
definition=definition,
@@ -100,9 +111,21 @@ def test_unconfirmed_visual_binding_blocks_publish():
)
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():
"""关键断言:全部正式字段 confirmed → 无视觉阻断。"""
"""关键断言:datasets path 可发布(视觉可选);原生 PDF confirmed 不阻断。"""
definition = {
'template_mode': 'xfa_dataset',
'source_contract': _source_contract(),
@@ -117,6 +140,76 @@ def test_confirmed_bindings_pass_visual_gate():
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({