feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:18:37 +08:00
1 parent 3a9fbac2fc
commit d2b3d74def
571 files changed
+78064 -24681

No files matched your search

@@ -1,371 +1,619 @@
"""
tests/test_shipping_process_gate_service.py
用途:验证统一门禁领域服务的创建、状态机、指纹跳过、下游失效与 19 Gate 接线矩阵。
用途:验证统一门禁领域服务的创建、状态机、指纹跳过、下游失效与全量 Gate 接线矩阵。
依赖:Flask testing app、process_gate_service、process_gate_bridge、process_gate_contract。
逻辑:最小 Workflow/Item/Version 夹具上创建 Execution;对每个 Gate 覆盖
passed / blocked_manual / failed_terminal;断言指纹未变不重跑。
逻辑:最小 User/Task 夹具上创建 Execution;对每个 Gate 覆盖
passed / blocked_manual / failed_terminal;断言指纹未变不重跑;Gate 数量由契约驱动。
"""
from __future__ import annotations
from typing import Any
import pytest
from app import db
from app.models import (
FileAsset,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingNoticeWorkflow,
ShippingNoticeWorkflowItem,
ShippingNoticeWorkflowItemVersion,
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingNotice,
User,
)
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES, PROCESS_GATE_DEFINITIONS
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
invalidate_downstream_gates,
queue_gate_attempt,
sync_gate_from_business_result,
)
def _seed_workflow_version(suffix: str = '001') -> tuple[Any, Any, Any]:
def _seed_workflow_version(
suffix: str = '001',
*,
owner: User | None = None,
) -> tuple[User, int | None, int | None]:
"""
创建最小 User → Workflow → Item → Version 链。
创建最小 User + ShippingNotice,供 Execution 绑定 review_case_id / task_id。
co8 后不再创建 Workflow 台账;保留函数名以兼容其它门禁测试模块 import。
Args:
suffix: 用于编号去重的后缀。
owner: 非空时 Task 归属该用户;否则新建 gate 测试用户。
Returns:
(user, item, version)
(user, review_case_id, task_id)
"""
tag = str(suffix or '001')[:40]
user = User(username=f'gate-svc-{tag}', email=f'gate-svc-{tag}@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no=f'FA-GATE-{tag}',
owner_user_id=int(user.id),
original_filename='gate.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{user.id}/gate-{tag}.pdf',
content_hash=(tag.ljust(64, '0'))[:64],
file_size=10,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no=f'SNI-GATE-{tag}',
asset_id=int(asset.id),
user = owner
if user is None:
user = User(username=f'gate-svc-{tag}', email=f'gate-svc-{tag}@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
task = ShippingNotice(
task_no=f'SN-GATE-{tag}',
user_id=int(user.id),
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
source_type='manual',
process_status='waiting_inventory',
)
db.session.add(intake)
db.session.add(task)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=int(intake.id),
document_type='attachment',
attachment_key='gate.pdf',
filename='gate.pdf',
classification='order_notice',
parse_status='parsed',
content_hash=(f'h{tag}'.ljust(64, '1'))[:64],
)
db.session.add(document)
db.session.flush()
workflow = ShippingNoticeWorkflow(
workflow_no=f'WF-GATE-{tag}',
conversation_id=f'conv-gate-{tag}',
owner_user_id=int(user.id),
status='open',
current_stage='extracting',
)
db.session.add(workflow)
db.session.flush()
item = ShippingNoticeWorkflowItem(
item_no=f'WFI-GATE-{tag}',
workflow_id=int(workflow.id),
workflow_no=workflow.workflow_no,
conversation_id=f'conv-gate-{tag}',
owner_user_id=int(user.id),
root_document_id=int(document.id),
current_document_id=int(document.id),
lifecycle_status='extracting',
current_stage='extracting',
current_version_no=1,
)
db.session.add(item)
db.session.flush()
version = ShippingNoticeWorkflowItemVersion(
workflow_item_id=int(item.id),
item_no=item.item_no,
workflow_id=int(workflow.id),
workflow_no=workflow.workflow_no,
document_id=int(document.id),
version_no=1,
status='active',
is_current=True,
)
db.session.add(version)
db.session.flush()
item.current_version_id = int(version.id)
db.session.flush()
return user, item, version
return user, None, int(task.id)
@pytest.fixture
def gate_execution(app):
"""提供已初始化 19 Gate 的 Execution。"""
"""提供已初始化全量 Gate 的 Execution(数量由 PROCESS_GATE_DEFINITIONS 驱动)。"""
with app.app_context():
_user, item, version = _seed_workflow_version()
_user, review_case_id, task_id = _seed_workflow_version()
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
review_case_id=review_case_id,
task_id=task_id,
actor_type='system',
actor_id='test',
)
db.session.commit()
yield execution
def test_ensure_execution_creates_nineteen_gates(gate_execution):
"""创建 Execution 时必须初始化全部 19 个 Gate 行。"""
def test_ensure_execution_creates_all_contract_gates(gate_execution):
"""创建 Execution 时必须初始化契约定义的全部 Gate 行(禁止硬编码 19/20)。"""
gates = ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all()
assert len(gates) == 19
assert len(gates) == len(PROCESS_GATE_CODES)
assert {g.gate_code for g in gates} == set(PROCESS_GATE_CODES)
assert gate_execution.current_gate_code == 'document_materialization'
def test_fingerprint_skip_does_not_rerun_passed_gate(gate_execution):
"""已通过且输入指纹未变的 Gate 不重跑。"""
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
first = apply_gate_outcome(
execution=gate_execution,
gate_code='document_materialization',
passed=True,
effective_result={'stage': 'ok'},
input_fingerprint='fp-doc-1',
idempotency_key='fp-skip-1',
)
attempts_before = ShippingProcessGateAttempt.query.filter_by(gate_id=int(first.id)).count()
second = apply_gate_outcome(
execution=gate_execution,
gate_code='document_materialization',
passed=True,
effective_result={'stage': 'ok'},
input_fingerprint='fp-doc-1',
idempotency_key='fp-skip-2',
)
attempts_after = ShippingProcessGateAttempt.query.filter_by(gate_id=int(second.id)).count()
assert second.status == 'passed'
assert attempts_after == attempts_before
def test_upstream_invalidation_only_targets_dependents(gate_execution):
"""库存源变化只失效依赖下游,不碰无关前置门禁。"""
apply_gate_outcome(
execution=gate_execution,
gate_code='inventory_matching',
passed=True,
effective_result={'matched': True},
force=True,
idempotency_key='inv-match-pass',
)
apply_gate_outcome(
execution=gate_execution,
gate_code='document_materialization',
passed=True,
effective_result={'ok': True},
force=True,
idempotency_key='doc-pass',
)
invalidated = invalidate_downstream_gates(
execution=gate_execution,
change_type='inventory_source_changed',
)
assert 'inventory_matching' in invalidated
assert 'document_materialization' not in invalidated
doc = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id),
gate_code='document_materialization',
).first()
assert doc.status == 'passed'
@pytest.mark.parametrize('gate_code', [str(item['gate_code']) for item in PROCESS_GATE_DEFINITIONS])
def test_each_gate_supports_passed_manual_blocked_and_technical_failed(app, gate_code):
"""
19 Gate 每个至少覆盖 passed、blocked_manual、failed_terminal 三类结果。
契约定义的每个 Gate 至少覆盖 passed、blocked_manual、failed_terminal 三类结果。
核心逻辑:同一 Execution 上对目标 Gate 依次同步三类 outcome。
"""
with app.app_context():
_user, item, version = _seed_workflow_version(suffix=gate_code.replace('_', '')[:32])
_user, review_case_id, task_id = _seed_workflow_version(suffix=gate_code.replace('_', '')[:32])
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
review_case_id=review_case_id,
task_id=task_id,
)
# [STEP 1] passed
passed = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code=gate_code,
passed=True,
effective_result_json={'findings': [], 'case': 'passed'},
idempotency_key=f'{gate_code}:passed',
invalidate_change_type=None,
)
assert passed.status == 'passed'
# [STEP 2] blocked_manual(允许 repass)
blocked = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code=gate_code,
passed=False,
blocking_reason_code='gate_invalidated',
effective_result_json={'findings': [], 'case': 'blocked_manual'},
idempotency_key=f'{gate_code}:blocked',
invalidate_change_type=None,
)
assert blocked.status == 'blocked_manual'
# [STEP 3] failed_terminal via complete path after queue
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code=gate_code,
trigger_type='system_requeue',
actor_type='system',
actor_id='test',
idempotency_key=f'{gate_code}:terminal',
)
from app.services.shipping_notice.process_gate_service import complete_gate_attempt, mark_attempt_running
mark_attempt_running(attempt_id=int(attempt.id), worker_id='test')
terminal = complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='failed_terminal',
error_code='TECH',
error_summary='technical failed',
effective_result_json={'case': 'failed_terminal'},
)
assert terminal.status == 'failed_terminal'
def test_idempotent_queue_replays_same_attempt(gate_execution):
"""相同幂等键只产生一个 Attempt。"""
first = queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='same-key-ten-times',
input_snapshot={'action_code': 'retry_with_latest_rules'},
)
for _ in range(9):
again = queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='same-key-ten-times',
input_snapshot={'action_code': 'retry_with_latest_rules'},
)
assert int(again.id) == int(first.id)
count = ShippingProcessGateAttempt.query.filter_by(idempotency_key='same-key-ten-times').count()
assert count == 1
def test_idempotent_key_conflicts_across_gate_and_action(gate_execution, app):
"""同幂等键跨 Gate / 跨 action 必须 409,禁止复用其他上下文 Attempt。"""
from app.core.errors import ConflictError
first = queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-context-key',
input_snapshot={'action_code': 'retry_with_latest_rules'},
)
with pytest.raises(ConflictError) as gate_exc:
queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='order_extraction',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-context-key',
input_snapshot={'action_code': 'retry_with_latest_rules'},
)
assert gate_exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
with pytest.raises(ConflictError) as action_exc:
queue_gate_attempt(
execution_no=gate_execution.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-context-key',
input_snapshot={'action_code': 'open_order_review'},
)
assert action_exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='cross-context-key').count() == 1
assert int(first.id) == int(
ShippingProcessGateAttempt.query.filter_by(idempotency_key='cross-context-key').first().id
)
def test_idempotent_key_conflicts_across_execution(app):
"""同幂等键跨 Execution 必须冲突。"""
from app.core.errors import ConflictError
with app.app_context():
_u1, item1, ver1 = _seed_workflow_version(suffix='idem-a')
_u2, item2, ver2 = _seed_workflow_version(suffix='idem-b')
_u1, rc1, task1 = _seed_workflow_version(suffix='idem-a')
_u2, rc2, task2 = _seed_workflow_version(suffix='idem-b')
exe1 = ensure_execution_for_workflow_version(
workflow_item_id=int(item1.id),
workflow_item_version_id=int(ver1.id),
review_case_id=rc1,
task_id=task1,
actor_type='system',
actor_id='test',
)
exe2 = ensure_execution_for_workflow_version(
workflow_item_id=int(item2.id),
workflow_item_version_id=int(ver2.id),
review_case_id=rc2,
task_id=task2,
actor_type='system',
actor_id='test',
)
db.session.commit()
queue_gate_attempt(
execution_no=exe1.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-execution-key',
input_snapshot={'action_code': 'retry_with_latest_rules'},
)
with pytest.raises(ConflictError) as exc:
queue_gate_attempt(
execution_no=exe2.execution_no,
gate_code='layout_parsing',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='cross-execution-key',
input_snapshot={'action_code': 'retry_with_latest_rules'},
)
assert exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'