feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验
- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全 - 引入审计事件的哈希链校验机制,支持数据完整性验证 - 增强订单抽取与审计功能,支持敏感快照的访问控制 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 完善文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
95cdfe66b0
commit
d0fe084999
225 files changed
+25923
-6653
No files matched your search
@@ -1,3 +1,12 @@
|
||||
"""
|
||||
tests/conftest.py
|
||||
|
||||
用途:Flask testing app、库存配置种子与测试隔离夹具。
|
||||
依赖:pytest、app.create_app、shipping inventory 模型。
|
||||
逻辑:各测试用例共享;Windows 下将 basetemp 固定到 backend/.pytest_tmp,
|
||||
配合 pytest.ini 的 retention=0,避免 %TEMP%/pytest-current 清理 PermissionError。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
|
||||
@@ -371,6 +380,12 @@ def rpa_callback_payload(
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
"""
|
||||
注册自定义 markers,并把临时目录固定到仓库内可写路径。
|
||||
|
||||
核心逻辑:未显式传 --basetemp 时使用 backend/.pytest_tmp/run,避免系统 TEMP
|
||||
中 pytest-current 符号链接在 atexit 清理时触发 WinError 5,导致 exit code≠0。
|
||||
"""
|
||||
config.addinivalue_line(
|
||||
"markers",
|
||||
"auto_rpa: 发货通知测试启用 auto_progress + RPA 自动链",
|
||||
@@ -379,6 +394,11 @@ def pytest_configure(config):
|
||||
"markers",
|
||||
"inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
|
||||
)
|
||||
# [STEP] Windows 质量门禁:basetemp 落仓内 + retention=0(见 pytest.ini)。
|
||||
if not getattr(config.option, 'basetemp', None):
|
||||
basetemp = Path(__file__).resolve().parents[1] / '.pytest_tmp' / 'run'
|
||||
basetemp.mkdir(parents=True, exist_ok=True)
|
||||
config.option.basetemp = str(basetemp)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -38,6 +38,24 @@ def test_claim_next_returns_none_when_empty(app):
|
||||
assert store.claim_next(queues=['kb']) is None
|
||||
|
||||
|
||||
def test_claim_next_shipping_recovers_stale_layout_jobs(app, monkeypatch):
|
||||
"""Shipping worker 认领前必须回收卡住的版面解析任务。"""
|
||||
from app.jobs import store
|
||||
from app.services.shipping_notice import queue_service
|
||||
|
||||
recovered = []
|
||||
monkeypatch.setattr(
|
||||
queue_service,
|
||||
'recover_stale_shipping_notice_jobs',
|
||||
lambda: recovered.append(True) or (0, ''),
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
assert store.claim_next(queues=['shipping']) is None
|
||||
|
||||
assert recovered == [True]
|
||||
|
||||
|
||||
def test_find_shipping_notice_job_id_matches_task_no(app):
|
||||
from app import db
|
||||
from app.jobs.queue import _find_shipping_notice_job_id
|
||||
|
||||
@@ -156,6 +156,10 @@ def test_list_profile_families_prefers_published_then_draft_then_retired(app):
|
||||
t01 = next(item for item in families if item['profile_code'] == 'T01')
|
||||
t02 = next(item for item in families if item['profile_code'] == 'T02')
|
||||
assert t01['published_version'] == 2
|
||||
assert t01['published_schema_version_id'] == schema.id
|
||||
assert t01['published_schema_version'] == schema.version
|
||||
assert t01['current_schema_version_id'] == schema.id
|
||||
assert t01['current_schema_version'] == schema.version
|
||||
assert t01['draft_version'] == 3
|
||||
assert t01['default_profile_id'] == published.id
|
||||
assert t01['default_version'] == 2
|
||||
|
||||
@@ -78,6 +78,16 @@ def test_table_contract_rejects_forbidden_reservation_header():
|
||||
assert caught.value.details['forbidden_reservation_headers'] == ['Allocation ID']
|
||||
|
||||
|
||||
def test_table_contract_includes_internal_line_number():
|
||||
"""内部项次 line_no 可作为 PDF/表格抽取字段;与客户 PO 行号并列映射。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
_field('line_no', ['Item No']), _field('customer_po_line_no', ['Customer Item']),
|
||||
))
|
||||
|
||||
assert contract.header_to_field['Item No'] == 'line_no'
|
||||
assert contract.header_to_field['Customer Item'] == 'customer_po_line_no'
|
||||
|
||||
|
||||
def test_runtime_reports_duplicate_columns_as_ambiguous():
|
||||
"""同一字段在一行命中多个列时不得静默选第一列。"""
|
||||
contract = compile_table_header_contract(_definition(
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_db_immutability.py
|
||||
|
||||
用途:验收 shipping_audit_events 不可变约束(ORM 层始终;PostgreSQL 触发器在 CI/生产)。
|
||||
依赖:ShippingAuditEvent ORM 守卫、audit_service.append_shipping_audit_event、SQLAlchemy dialect。
|
||||
逻辑:pytest TestingConfig 强制 SQLite create_all,无 DB 触发器 —— 仅断言 ORM append-only;
|
||||
触发器断言在非 PostgreSQL 时 pytest.skip(迁移 a0e1f2b3c4d5 仅对 PG 生效)。
|
||||
目标 PostgreSQL 环境请另跑:
|
||||
``python scripts/verify_shipping_audit_pg_immutability.py``(日志不输出连接凭据)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _is_postgresql() -> bool:
|
||||
"""当前应用绑定是否为 PostgreSQL。"""
|
||||
bind = db.session.bind
|
||||
return bind is not None and bind.dialect.name == 'postgresql'
|
||||
|
||||
|
||||
def test_shipping_audit_orm_immutability_still_holds(app):
|
||||
"""任意方言:已提交审计经 ORM update/delete 必须被拒绝(测试库通常无 DB 触发器)。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='WFI-DB-IMM-1',
|
||||
workflow_id='WF-DB-IMM-1',
|
||||
workflow_item_id='WFI-DB-IMM-1',
|
||||
)
|
||||
db.session.commit()
|
||||
event_id = int(event.id)
|
||||
|
||||
event.reason_code = 'tampered'
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
persisted = db.session.get(ShippingAuditEvent, event_id)
|
||||
db.session.delete(persisted)
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
# 关键断言:删除失败后记录仍在。
|
||||
assert db.session.get(ShippingAuditEvent, event_id) is not None
|
||||
|
||||
|
||||
def test_shipping_audit_pg_trigger_blocks_core_update(app):
|
||||
"""PostgreSQL:Core UPDATE 须被触发器拒绝;SQLite 跳过。"""
|
||||
with app.app_context():
|
||||
if not _is_postgresql():
|
||||
pytest.skip('DB triggers only exist on PostgreSQL after migration a0e1f2b3c4d5')
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_created',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id='WF-DB-IMM-TRIG',
|
||||
workflow_id='WF-DB-IMM-TRIG',
|
||||
)
|
||||
db.session.commit()
|
||||
with pytest.raises(Exception):
|
||||
db.session.execute(
|
||||
text('UPDATE shipping_audit_events SET reason_code = :rc WHERE id = :eid'),
|
||||
{'rc': 'x', 'eid': int(event.id)},
|
||||
)
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_shipping_audit_pg_trigger_blocks_core_delete_without_purge_guc(app):
|
||||
"""PostgreSQL:未设置 purge GUC 时 Core DELETE 须被触发器拒绝;SQLite 跳过。"""
|
||||
with app.app_context():
|
||||
if not _is_postgresql():
|
||||
pytest.skip('DB triggers only exist on PostgreSQL after migration a0e1f2b3c4d5')
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_created',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id='WF-DB-IMM-DEL',
|
||||
workflow_id='WF-DB-IMM-DEL',
|
||||
)
|
||||
db.session.commit()
|
||||
with pytest.raises(Exception):
|
||||
db.session.execute(
|
||||
text('DELETE FROM shipping_audit_events WHERE id = :eid'),
|
||||
{'eid': int(event.id)},
|
||||
)
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
assert db.session.get(ShippingAuditEvent, int(event.id)) is not None
|
||||
@@ -46,7 +46,7 @@ def test_append_shipping_audit_event_hashes_state_and_rejects_sensitive_metadata
|
||||
assert event.after_snapshot_json == {'status': 'processing'}
|
||||
assert event.operation_id == 'op-stage0-1'
|
||||
assert event.metadata_json == {'target_status': 'processing'}
|
||||
assert event.retention_expires_at is not None
|
||||
assert event.retention_expires_at is None
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='invalid',
|
||||
@@ -120,14 +120,16 @@ def test_shipping_audit_event_rejects_orm_update_and_delete(app):
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_append_shipping_audit_event_hashes_client_context_and_session_item(app):
|
||||
"""会话工作项审计必须记录属主/工作项软引用,且 IP/UA 仅存哈希。"""
|
||||
def test_append_shipping_audit_event_hashes_client_context_and_workflow_refs(app):
|
||||
"""Workflow 审计必须记录属主/软引用与哈希链,且 IP/UA 仅存哈希。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='session_work_item_created',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id='SPWI-1',
|
||||
session_item_id='SPWI-1',
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='SWI-1',
|
||||
workflow_id='SWF-1',
|
||||
workflow_item_id='SWI-1',
|
||||
version_no=1,
|
||||
owner_user_id=42,
|
||||
conversation_id='conv-session-1',
|
||||
client_ip='203.0.113.9',
|
||||
@@ -135,13 +137,18 @@ def test_append_shipping_audit_event_hashes_client_context_and_session_item(app)
|
||||
after={
|
||||
'lifecycle_status': 'pending_review',
|
||||
'current_version_no': 1,
|
||||
'item_no': 'SPWI-1',
|
||||
'item_no': 'SWI-1',
|
||||
'workflow_no': 'SWF-1',
|
||||
},
|
||||
metadata={'source': 'upload'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert event.session_item_id == 'SPWI-1'
|
||||
assert event.workflow_id == 'SWF-1'
|
||||
assert event.workflow_item_id == 'SWI-1'
|
||||
assert event.version_no == 1
|
||||
assert event.event_hash
|
||||
assert event.diff_json is not None
|
||||
assert event.owner_user_id == '42'
|
||||
assert event.client_ip_hash == hash_client_context_value('203.0.113.9')
|
||||
assert event.user_agent_hash == hash_client_context_value('Mozilla/5.0 TestAgent')
|
||||
@@ -149,13 +156,14 @@ def test_append_shipping_audit_event_hashes_client_context_and_session_item(app)
|
||||
assert event.after_snapshot_json == {
|
||||
'lifecycle_status': 'pending_review',
|
||||
'current_version_no': 1,
|
||||
'item_no': 'SPWI-1',
|
||||
'item_no': 'SWI-1',
|
||||
'workflow_no': 'SWF-1',
|
||||
}
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='probe',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id='SPWI-2',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='SWI-2',
|
||||
metadata={'client_ip': '203.0.113.9'},
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN'
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_hash_verification_job.py
|
||||
|
||||
用途:验收货代审计哈希链日检 Job(shipping-audit-retention / shipping-audit-hash-verify)。
|
||||
依赖:shipping_audit_retention_job、audit_service、job_registry、Flask config。
|
||||
逻辑:开关关闭时 skipped;开启时校验通过;Core 篡改后 failed_chains>0;
|
||||
job_registry 已注册日检 Job 且含 hash_sample_limit。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
|
||||
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _task(**params):
|
||||
"""构造最小 Job task 桩。"""
|
||||
return SimpleNamespace(id=9001, job_params=params)
|
||||
|
||||
|
||||
def test_job_registry_registers_hash_verify_jobs(app):
|
||||
"""平台 Job 注册表包含清理+哈希校验与专用日检入口。"""
|
||||
with app.app_context():
|
||||
keys = {item.key for item in list_platform_jobs()}
|
||||
# 关键断言:日检可走 retention 或专用 hash-verify Job。
|
||||
assert 'shipping-audit-retention' in keys
|
||||
assert 'shipping-audit-hash-verify' in keys
|
||||
|
||||
retention = get_platform_job('shipping-audit-retention')
|
||||
assert retention is not None
|
||||
schema_keys = {field['key'] for field in retention.params_schema}
|
||||
assert 'hash_sample_limit' in schema_keys
|
||||
|
||||
verify = get_platform_job('shipping-audit-hash-verify')
|
||||
assert verify is not None
|
||||
assert verify.defaults.get('dry_run') is True
|
||||
assert int(verify.defaults.get('hash_sample_limit') or 0) >= 1
|
||||
|
||||
|
||||
def test_hash_verify_skipped_when_disabled(app):
|
||||
"""SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED=false 时跳过校验。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED'] = False
|
||||
result = run_shipping_audit_retention_schedule(
|
||||
_task(limit=10, dry_run=True, hash_sample_limit=50),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
# 关键断言:跳过时 checked/failed 为 0 且 skipped=True。
|
||||
assert result['hash_verify']['skipped'] is True
|
||||
assert result['hash_verify']['checked_chains'] == 0
|
||||
assert result['hash_verify']['failed_chains'] == 0
|
||||
|
||||
|
||||
def test_hash_verify_passes_for_intact_chain(app):
|
||||
"""完整哈希链抽样校验通过。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED'] = True
|
||||
aggregate_id = 'WFI-JOB-HASH-OK'
|
||||
for index in range(3):
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id=aggregate_id,
|
||||
workflow_id='WF-JOB-HASH',
|
||||
workflow_item_id=aggregate_id,
|
||||
action=f'ok-{index}',
|
||||
after={'lifecycle_status': f's-{index}'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = run_shipping_audit_retention_schedule(
|
||||
_task(limit=1, dry_run=True, hash_sample_limit=200),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
# 关键断言:至少校验到本测试聚合且无失败链。
|
||||
assert result['hash_verify'].get('skipped') is not True
|
||||
assert int(result['hash_verify']['checked_chains']) >= 1
|
||||
assert int(result['hash_verify']['failed_chains']) == 0
|
||||
|
||||
|
||||
def test_hash_verify_detects_tampered_chain(app):
|
||||
"""Core UPDATE 篡改 event_hash 后日检 failed_chains > 0。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED'] = True
|
||||
aggregate_id = 'WFI-JOB-HASH-BAD'
|
||||
for index in range(3):
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id=aggregate_id,
|
||||
workflow_id='WF-JOB-HASH-BAD',
|
||||
workflow_item_id=aggregate_id,
|
||||
action=f'bad-{index}',
|
||||
after={'lifecycle_status': f't-{index}'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
middle = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type='shipping_notice_workflow_item', aggregate_id=aggregate_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.offset(1)
|
||||
.first()
|
||||
)
|
||||
assert middle is not None
|
||||
db.session.execute(
|
||||
text('UPDATE shipping_audit_events SET event_hash = :h WHERE id = :id'),
|
||||
{'h': '0' * 64, 'id': int(middle.id)},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = run_shipping_audit_retention_schedule(
|
||||
_task(limit=1, dry_run=True, hash_sample_limit=500),
|
||||
SimpleNamespace(),
|
||||
)
|
||||
# 关键断言:篡改链被日检检出。
|
||||
assert int(result['hash_verify']['failed_chains']) >= 1
|
||||
assert result['hash_verify']['failures_sample']
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_immutability.py
|
||||
|
||||
用途:验收 ShippingAuditEvent ORM 层 append-only 与哈希链字段落库。
|
||||
依赖:ShippingAuditEvent 模型事件守卫、audit_service.append_shipping_audit_event。
|
||||
逻辑:已提交事件禁止 ORM update/delete;新写入必须带 event_hash / previous_event_hash 字段语义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def test_shipping_audit_event_orm_update_raises(app):
|
||||
"""已提交审计事件经 ORM 更新必须抛 ValidationError。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='WFI-IMM-1',
|
||||
workflow_id='WF-IMM-1',
|
||||
workflow_item_id='WFI-IMM-1',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
event.reason_code = 'tampered'
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_shipping_audit_event_orm_delete_raises(app):
|
||||
"""已提交审计事件经 ORM 删除必须抛 ValidationError。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='WFI-IMM-2',
|
||||
workflow_id='WF-IMM-2',
|
||||
workflow_item_id='WFI-IMM-2',
|
||||
)
|
||||
db.session.commit()
|
||||
event_id = int(event.id)
|
||||
|
||||
persisted = db.session.get(ShippingAuditEvent, event_id)
|
||||
db.session.delete(persisted)
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
# 关键断言:删除失败后记录仍在。
|
||||
assert db.session.get(ShippingAuditEvent, event_id) is not None
|
||||
|
||||
|
||||
def test_append_only_persists_hash_chain_fields(app):
|
||||
"""append 写入后必须带 event_hash;同聚合第二条 previous 指向首条。"""
|
||||
with app.app_context():
|
||||
first = append_shipping_audit_event(
|
||||
event_type='workflow_created',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id='WF-IMM-CHAIN',
|
||||
workflow_id='WF-IMM-CHAIN',
|
||||
after={'workflow_no': 'WF-IMM-CHAIN', 'lifecycle_status': 'open'},
|
||||
)
|
||||
second = append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type='shipping_notice_workflow',
|
||||
aggregate_id='WF-IMM-CHAIN',
|
||||
workflow_id='WF-IMM-CHAIN',
|
||||
after={'workflow_no': 'WF-IMM-CHAIN', 'lifecycle_status': 'extracting'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:哈希链字段已落库,形成 append-only 可校验事实。
|
||||
assert first.event_hash
|
||||
assert first.previous_event_hash is None
|
||||
assert second.event_hash
|
||||
assert second.previous_event_hash == first.event_hash
|
||||
assert first.diff_json is not None or first.after_snapshot_json is not None
|
||||
@@ -0,0 +1,186 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_permissions.py
|
||||
|
||||
用途:验收货代审计敏感读权限裁剪与关联链追溯契约。
|
||||
依赖:User 功能权限、audit_query_service、audit_service。
|
||||
逻辑:无 shipping_notice.audit_sensitive_read 时敏感详情脱敏;有权限返回快照/Diff;
|
||||
关联链可按 workflow/item/run/document/case/task 扩张追溯。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, User
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
get_shipping_audit_event,
|
||||
list_shipping_audit_association_chain,
|
||||
serialize_shipping_audit_event,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _make_user(*, role: str, overrides: dict | None = None) -> User:
|
||||
"""构造带功能权限覆盖的内存用户(不落库,仅测 has_feature_permission)。"""
|
||||
user = User(username=f'u-{role}', role=role)
|
||||
if overrides is not None:
|
||||
user.feature_permissions = overrides
|
||||
return user
|
||||
|
||||
|
||||
def test_admin_default_has_audit_sensitive_read_permission(app):
|
||||
"""admin 角色默认具备 shipping_notice.audit_sensitive_read;普通用户默认无。"""
|
||||
with app.app_context():
|
||||
admin = _make_user(role='admin')
|
||||
user = _make_user(role='user')
|
||||
# 关键断言:默认权限不新建角色,仅功能键裁剪。
|
||||
assert admin.has_feature_permission('shipping_notice.audit_sensitive_read') is True
|
||||
assert user.has_feature_permission('shipping_notice.audit_sensitive_read') is False
|
||||
|
||||
|
||||
def test_admin_can_explicitly_disable_audit_sensitive_read(app):
|
||||
"""admin 可显式关闭敏感读权限覆盖项。"""
|
||||
with app.app_context():
|
||||
admin = _make_user(role='admin', overrides={'shipping_notice.audit_sensitive_read': False})
|
||||
# 关键断言:显式覆盖优先于角色默认。
|
||||
assert admin.has_feature_permission('shipping_notice.audit_sensitive_read') is False
|
||||
|
||||
|
||||
def test_sensitive_detail_redacted_without_permission(app):
|
||||
"""敏感事件在无 include_sensitive 时脱敏 before/after/diff。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_review_confirmed',
|
||||
aggregate_type='shipping_order_review_case',
|
||||
aggregate_id='SRC-SENS-1',
|
||||
review_case_no='SRC-SENS-1',
|
||||
workflow_id='WF-SENS-1',
|
||||
workflow_item_id='WFI-SENS-1',
|
||||
sensitivity_level='sensitive',
|
||||
before={'status': 'pending_review', 'progress_version': 1},
|
||||
after={'status': 'confirmed', 'progress_version': 2},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
redacted = serialize_shipping_audit_event(
|
||||
event, include_snapshots=True, include_sensitive=False,
|
||||
)
|
||||
# 关键断言:无权限不回传敏感快照正文,并标记 sensitive_redacted。
|
||||
assert redacted['sensitive_redacted'] is True
|
||||
assert redacted['before_snapshot'] is None
|
||||
assert redacted['after_snapshot'] is None
|
||||
assert redacted['diff'] == []
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=1,
|
||||
request_id='req-sens-deny',
|
||||
event_id=int(event.id),
|
||||
include_sensitive=False,
|
||||
)
|
||||
assert detail['sensitive_redacted'] is True
|
||||
assert detail['before_snapshot'] is None
|
||||
|
||||
|
||||
def test_sensitive_detail_visible_with_permission(app):
|
||||
"""具备 include_sensitive 时返回白名单 Diff。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_review_confirmed',
|
||||
aggregate_type='shipping_order_review_case',
|
||||
aggregate_id='SRC-SENS-2',
|
||||
review_case_no='SRC-SENS-2',
|
||||
sensitivity_level='sensitive',
|
||||
before={'status': 'pending_review'},
|
||||
after={'status': 'confirmed'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=1,
|
||||
request_id='req-sens-allow',
|
||||
event_id=int(event.id),
|
||||
include_sensitive=True,
|
||||
)
|
||||
# 关键断言:有权限可见敏感快照与 Diff。
|
||||
assert detail['sensitive_redacted'] is False
|
||||
assert detail['before_snapshot'] == {'status': 'pending_review'}
|
||||
assert detail['after_snapshot'] == {'status': 'confirmed'}
|
||||
assert {row['key'] for row in detail['diff']} == {'status'}
|
||||
|
||||
|
||||
def test_normal_detail_visible_without_sensitive_permission(app):
|
||||
"""非敏感事件即使无敏感读权限也可看白名单 Diff。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-NORM-1',
|
||||
run_no='SNER-NORM-1',
|
||||
sensitivity_level='normal',
|
||||
before={'status': 'queued'},
|
||||
after={'status': 'processing'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=1,
|
||||
request_id='req-norm',
|
||||
event_id=int(event.id),
|
||||
include_sensitive=False,
|
||||
)
|
||||
assert detail['sensitive_redacted'] is False
|
||||
assert detail['before_snapshot'] == {'status': 'queued'}
|
||||
|
||||
|
||||
def test_association_chain_expands_across_workflow_keys(app):
|
||||
"""关联链按 workflow/item/run/case/task 扩张追溯。"""
|
||||
with app.app_context():
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_item_created',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='WFI-CHAIN-1',
|
||||
workflow_id='WF-CHAIN-1',
|
||||
workflow_item_id='WFI-CHAIN-1',
|
||||
document_id='42',
|
||||
action='create',
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-CHAIN-1',
|
||||
workflow_id='WF-CHAIN-1',
|
||||
workflow_item_id='WFI-CHAIN-1',
|
||||
run_no='SNER-CHAIN-1',
|
||||
document_id='42',
|
||||
action='status',
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_review_confirmed',
|
||||
aggregate_type='shipping_order_review_case',
|
||||
aggregate_id='SRC-CHAIN-1',
|
||||
workflow_id='WF-CHAIN-1',
|
||||
workflow_item_id='WFI-CHAIN-1',
|
||||
run_no='SNER-CHAIN-1',
|
||||
review_case_no='SRC-CHAIN-1',
|
||||
task_no='ST-CHAIN-1',
|
||||
action='confirm',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
chain = list_shipping_audit_association_chain(
|
||||
admin_user_id=1,
|
||||
request_id='req-chain',
|
||||
filters={'run_no': 'SNER-CHAIN-1'},
|
||||
limit=100,
|
||||
)
|
||||
# 关键断言:从 run_no 种子可扩张到 workflow / case / task 关联事件。
|
||||
event_types = {item['event_type'] for item in chain['items']}
|
||||
assert 'workflow_item_created' in event_types
|
||||
assert 'order_extraction_run_status_changed' in event_types
|
||||
assert 'order_review_confirmed' in event_types
|
||||
assert 'WF-CHAIN-1' in chain['association_keys'].get('workflow_id', [])
|
||||
assert 'SRC-CHAIN-1' in chain['association_keys'].get('review_case_no', [])
|
||||
|
||||
access = ShippingAuditEvent.query.filter_by(
|
||||
event_type='audit_access', action='list_audit_association_chain',
|
||||
).count()
|
||||
assert access >= 1
|
||||
@@ -104,25 +104,27 @@ def test_export_csv_omits_snapshots_and_writes_access_audit(app):
|
||||
assert access.metadata_json.get('format') == 'csv'
|
||||
|
||||
|
||||
def test_list_filters_session_work_item_context_fields(app):
|
||||
"""会话工作项相关筛选:conversation / session_item / case / owner 精确匹配。"""
|
||||
def test_list_filters_workflow_item_context_fields(app):
|
||||
"""Workflow 相关筛选:conversation / workflow_item / case / owner 精确匹配。"""
|
||||
with app.app_context():
|
||||
target = append_shipping_audit_event(
|
||||
event_type='session_work_item_reparse_started',
|
||||
aggregate_type='shipping_session_pdf_work_item',
|
||||
event_type='document_reparse_requested',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='SPWI-FILTER-1',
|
||||
conversation_id='conv-filter-1',
|
||||
session_item_id='SPWI-FILTER-1',
|
||||
workflow_id='SWF-FILTER-1',
|
||||
workflow_item_id='SPWI-FILTER-1',
|
||||
review_case_no='SRC-FILTER-1',
|
||||
owner_user_id='8801',
|
||||
run_no='SNER-FILTER-1',
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='session_work_item_reparse_started',
|
||||
aggregate_type='shipping_session_pdf_work_item',
|
||||
event_type='document_reparse_requested',
|
||||
aggregate_type='shipping_notice_workflow_item',
|
||||
aggregate_id='SPWI-FILTER-2',
|
||||
conversation_id='conv-filter-2',
|
||||
session_item_id='SPWI-FILTER-2',
|
||||
workflow_id='SWF-FILTER-2',
|
||||
workflow_item_id='SPWI-FILTER-2',
|
||||
review_case_no='SRC-FILTER-2',
|
||||
owner_user_id='8802',
|
||||
run_no='SNER-FILTER-2',
|
||||
@@ -136,7 +138,7 @@ def test_list_filters_session_work_item_context_fields(app):
|
||||
page_size=25,
|
||||
filters={
|
||||
'conversation_id': 'conv-filter-1',
|
||||
'session_item_id': 'SPWI-FILTER-1',
|
||||
'workflow_item_id': 'SPWI-FILTER-1',
|
||||
'review_case_no': 'SRC-FILTER-1',
|
||||
'owner_user_id': '8801',
|
||||
},
|
||||
@@ -144,22 +146,32 @@ def test_list_filters_session_work_item_context_fields(app):
|
||||
# 关键断言:四字段联合筛选仅命中目标事件。
|
||||
assert listed['total'] == 1
|
||||
assert listed['items'][0]['id'] == int(target.id)
|
||||
assert listed['items'][0]['session_item_id'] == 'SPWI-FILTER-1'
|
||||
assert listed['items'][0]['workflow_item_id'] == 'SPWI-FILTER-1'
|
||||
assert listed['items'][0]['workflow_id'] == 'SWF-FILTER-1'
|
||||
assert listed['items'][0]['owner_user_id'] == '8801'
|
||||
assert listed['items'][0]['event_hash']
|
||||
|
||||
|
||||
def test_purge_expired_supports_dry_run_and_core_delete(app):
|
||||
"""到期清理支持 dry_run;正式删除经 Core DELETE 并写清理审计。"""
|
||||
from sqlalchemy import update
|
||||
|
||||
with app.app_context():
|
||||
expired = append_shipping_audit_event(
|
||||
event_type='legacy_probe',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-EXPIRED',
|
||||
run_no='SNER-EXPIRED',
|
||||
retention_expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
)
|
||||
db.session.commit()
|
||||
expired_id = int(expired.id)
|
||||
# 新写入永久保留;用 Core UPDATE 模拟历史遗留到期行(绕过 ORM 不可变守卫)。
|
||||
db.session.execute(
|
||||
update(ShippingAuditEvent)
|
||||
.where(ShippingAuditEvent.id == expired_id)
|
||||
.values(retention_expires_at=datetime.utcnow() - timedelta(days=1))
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
dry = purge_expired_shipping_audit_events(limit=100, dry_run=True)
|
||||
# 关键断言:演练只扫描不删除。
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_snapshot_service.py
|
||||
|
||||
用途:验收审计快照白名单、Diff 计算与同聚合 event_hash 哈希链完整性。
|
||||
依赖:audit_snapshot_service、audit_service、ShippingAuditEvent、SQLAlchemy Core UPDATE。
|
||||
逻辑:sanitize/diff 只保留白名单键;连续 append 形成 previous→event 链;
|
||||
Core UPDATE 篡改后 verify_event_hash_chain 必须失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.audit_snapshot_service import (
|
||||
compute_snapshot_diff,
|
||||
sanitize_snapshot,
|
||||
verify_event_hash_chain,
|
||||
)
|
||||
|
||||
|
||||
def test_sanitize_snapshot_whitelists_keys(app):
|
||||
"""sanitize_snapshot 仅保留白名单键,未知业务键被剔除。"""
|
||||
with app.app_context():
|
||||
projected = sanitize_snapshot({
|
||||
'status': 'processing',
|
||||
'progress_version': 2,
|
||||
'orders': [{'po': '45001'}],
|
||||
'lifecycle_status': 'extracting',
|
||||
})
|
||||
# 关键断言:白名单键保留,订单正文类键不得进入快照。
|
||||
assert projected == {
|
||||
'status': 'processing',
|
||||
'progress_version': 2,
|
||||
'lifecycle_status': 'extracting',
|
||||
}
|
||||
|
||||
|
||||
def test_compute_snapshot_diff_detects_changed_keys(app):
|
||||
"""compute_snapshot_diff 输出 changed/added/removed 三段。"""
|
||||
with app.app_context():
|
||||
diff = compute_snapshot_diff(
|
||||
{'status': 'queued', 'progress_version': 1},
|
||||
{'status': 'processing', 'lifecycle_status': 'extracting'},
|
||||
)
|
||||
# 关键断言:status 变更、lifecycle 新增、progress_version 移除。
|
||||
assert diff is not None
|
||||
assert diff['changed']['status'] == {'from': 'queued', 'to': 'processing'}
|
||||
assert diff['added']['lifecycle_status'] == 'extracting'
|
||||
assert diff['removed']['progress_version'] == 1
|
||||
|
||||
|
||||
def test_append_builds_event_hash_chain_and_verify_passes(app):
|
||||
"""同聚合连续 3 条事件形成 previous_event_hash → event_hash 链,校验通过。"""
|
||||
with app.app_context():
|
||||
aggregate_type = 'shipping_notice_workflow_item'
|
||||
aggregate_id = 'WFI-HASH-CHAIN-1'
|
||||
events = []
|
||||
for index in range(3):
|
||||
events.append(
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type=aggregate_type,
|
||||
aggregate_id=aggregate_id,
|
||||
workflow_id='WF-HASH-1',
|
||||
workflow_item_id=aggregate_id,
|
||||
action=f'step-{index}',
|
||||
before={'lifecycle_status': f's-{index}'},
|
||||
after={'lifecycle_status': f's-{index + 1}'},
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:首条无前驱;后续 previous 等于上一条 event_hash。
|
||||
assert events[0].event_hash
|
||||
assert events[0].previous_event_hash is None
|
||||
assert events[1].previous_event_hash == events[0].event_hash
|
||||
assert events[2].previous_event_hash == events[1].event_hash
|
||||
assert len({e.event_hash for e in events}) == 3
|
||||
|
||||
ordered = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.all()
|
||||
)
|
||||
ok, failures = verify_event_hash_chain(ordered)
|
||||
assert ok is True
|
||||
assert failures == []
|
||||
|
||||
|
||||
def test_verify_event_hash_chain_fails_after_core_tamper(app):
|
||||
"""经 Core UPDATE 篡改 event_hash 后,链校验必须失败。"""
|
||||
with app.app_context():
|
||||
aggregate_type = 'shipping_notice_workflow_item'
|
||||
aggregate_id = 'WFI-HASH-TAMPER-1'
|
||||
for index in range(3):
|
||||
append_shipping_audit_event(
|
||||
event_type='workflow_stage_changed',
|
||||
aggregate_type=aggregate_type,
|
||||
aggregate_id=aggregate_id,
|
||||
workflow_id='WF-HASH-T',
|
||||
workflow_item_id=aggregate_id,
|
||||
action=f'tamper-{index}',
|
||||
after={'lifecycle_status': f't-{index}'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
middle = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.offset(1)
|
||||
.first()
|
||||
)
|
||||
assert middle is not None
|
||||
# Core UPDATE 绕过 ORM append-only 守卫,模拟存储层篡改。
|
||||
db.session.execute(
|
||||
text('UPDATE shipping_audit_events SET event_hash = :h WHERE id = :id'),
|
||||
{'h': 'deadbeef', 'id': middle.id},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
ordered = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type=aggregate_type, aggregate_id=aggregate_id)
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.all()
|
||||
)
|
||||
ok, failures = verify_event_hash_chain(ordered)
|
||||
# 关键断言:至少一条 event_hash_mismatch 或后续 previous_hash_mismatch。
|
||||
assert ok is False
|
||||
assert any(row['reason'] in {'event_hash_mismatch', 'previous_hash_mismatch'} for row in failures)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
tests/test_shipping_auto_build_workflow_gate.py
|
||||
|
||||
用途:验收自动建单五门禁——失败仅 Review Case、禁止 STP 自动建单;can_build 仍供人工确认。
|
||||
依赖:order_build_eligibility_service、types.SimpleNamespace。
|
||||
逻辑:构造五门全绿 / 单门失败用例;断言 can_auto_create 与 failed_gates。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_build_eligibility_service import (
|
||||
AUTO_BUILD_GATE_KEYS,
|
||||
assess_auto_build_gates,
|
||||
assess_order_build_eligibility,
|
||||
)
|
||||
|
||||
|
||||
def test_auto_build_gates_pass_when_all_five_green():
|
||||
"""五门全绿时 can_auto_create=True。"""
|
||||
candidate = SimpleNamespace(
|
||||
acceptance_mode='automatic',
|
||||
candidate_status='accepted',
|
||||
evidence_json=[{'field': 'po'}],
|
||||
conflicts_json=None,
|
||||
duplicate_status='none',
|
||||
duplicate_resolution=None,
|
||||
)
|
||||
unit = SimpleNamespace(route_decision_json={'auto_create_approved': True})
|
||||
run = SimpleNamespace(auto_freeze_policy_json={'enabled': True})
|
||||
result = assess_auto_build_gates(
|
||||
fields_complete=True,
|
||||
candidate=candidate,
|
||||
unit=unit,
|
||||
run=run,
|
||||
)
|
||||
assert result['can_auto_create'] is True
|
||||
assert result['failed_gates'] == []
|
||||
assert set(result['gates']) == set(AUTO_BUILD_GATE_KEYS)
|
||||
assert all(result['gates'].values())
|
||||
|
||||
|
||||
def test_auto_build_gates_fail_without_approved_template():
|
||||
"""模板未批准 → Review Case,禁止自动建单。"""
|
||||
result = assess_auto_build_gates(
|
||||
fields_complete=True,
|
||||
candidate=SimpleNamespace(
|
||||
acceptance_mode='manual',
|
||||
candidate_status='provisional',
|
||||
evidence_json=[{'field': 'po'}],
|
||||
conflicts_json=None,
|
||||
duplicate_status='none',
|
||||
duplicate_resolution=None,
|
||||
),
|
||||
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
|
||||
run=SimpleNamespace(auto_freeze_policy_json={'enabled': True}),
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'approved_template' in result['failed_gates']
|
||||
|
||||
|
||||
def test_auto_build_gates_fail_on_conflict_or_missing_quality(app):
|
||||
"""冲突或质量门禁未过 → 不能自动建单。"""
|
||||
result = assess_auto_build_gates(
|
||||
fields_complete=True,
|
||||
candidate=SimpleNamespace(
|
||||
acceptance_mode='automatic',
|
||||
candidate_status='accepted',
|
||||
evidence_json=[{'field': 'po'}],
|
||||
conflicts_json=[{'code': 'qty_conflict'}],
|
||||
duplicate_status='none',
|
||||
duplicate_resolution=None,
|
||||
),
|
||||
unit=SimpleNamespace(route_decision_json={'auto_create_approved': True}),
|
||||
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}),
|
||||
)
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'no_conflict_or_duplicate' in result['failed_gates']
|
||||
assert 'quality_gate_passed' in result['failed_gates']
|
||||
|
||||
|
||||
def test_eligibility_can_build_independent_of_auto_create_gates(app, monkeypatch):
|
||||
"""
|
||||
五门失败不阻断人工确认 can_build(库存/Reservation 齐备时)。
|
||||
"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_build_eligibility_service.list_database_inventory_sources',
|
||||
lambda enabled_only=True: [{'source_code': 'DBS_DUB'}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_build_eligibility_service.evaluate_inventory_source_rules_for_field_values',
|
||||
lambda **kwargs: SimpleNamespace(
|
||||
status='resolved',
|
||||
source_codes=['DBS_DUB'],
|
||||
can_build=True,
|
||||
block_reason=None,
|
||||
matched_rule_ids=[1],
|
||||
evidence={},
|
||||
),
|
||||
)
|
||||
fields = {
|
||||
'f-res': {'field_id': 'f-res', 'field_code': 'reservation_id', 'scope': 'line'},
|
||||
'f-pn': {'field_id': 'f-pn', 'field_code': 'part_number', 'scope': 'line'},
|
||||
'f-qty': {'field_id': 'f-qty', 'field_code': 'qty', 'scope': 'line'},
|
||||
}
|
||||
result = assess_order_build_eligibility(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
lines=[{'reservation_id': '2000484577', 'part_number': 'PN-1', 'qty': '2'}],
|
||||
line_metas=[{'line_key': 'L1'}],
|
||||
candidate=SimpleNamespace(
|
||||
acceptance_mode='manual',
|
||||
candidate_status='provisional',
|
||||
evidence_json=[],
|
||||
conflicts_json=None,
|
||||
duplicate_status='none',
|
||||
duplicate_resolution=None,
|
||||
),
|
||||
unit=SimpleNamespace(route_decision_json={'auto_create_approved': False}),
|
||||
run=SimpleNamespace(auto_freeze_policy_json={'enabled': False}),
|
||||
)
|
||||
# 关键断言:人工可建单,但自动建单被五门阻断。
|
||||
assert result['can_build'] is True
|
||||
assert result['can_auto_create'] is False
|
||||
assert 'approved_template' in result['failed_gates']
|
||||
assert any(item.get('severity') == 'auto_create_blocking' for item in result['issues'])
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
tests/test_shipping_cancelled_task_readonly.py
|
||||
|
||||
用途:验收建单后取消将 Task 置 pending_void、Excel/Version 只读,禁止物理删除。
|
||||
依赖:freight_cancellation_service、workflow_ledger_service、_seed_run_input。
|
||||
逻辑:断言 lifecycle、void_reason、version.is_readonly、审计 before/after、文件路径保留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflowItemVersion
|
||||
from app.services.shipping_notice.freight_cancellation_service import mark_cancelled_task_readonly
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
ensure_open_workflow,
|
||||
ensure_workflow_item_for_document,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_mark_cancelled_task_readonly_sets_pending_void_without_delete(app):
|
||||
"""取消后 Task 为 pending_void,导出路径保留,Version 只读。"""
|
||||
with app.app_context():
|
||||
user, agent, session, _intake, document = _seed_run_input(suffix='CANCEL-RO')
|
||||
workflow = ensure_open_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
task = ShippingTask(
|
||||
task_no='SN-CANCEL-RO-1',
|
||||
user_id=int(user.id),
|
||||
conversation_id=session.session_id,
|
||||
process_status='waiting_upload',
|
||||
lifecycle_status='active',
|
||||
export_file_path='/tmp/keep-excel.xlsx',
|
||||
export_file_name='keep-excel.xlsx',
|
||||
source_type='review_confirmation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
item.current_task_no = task.task_no
|
||||
version = (
|
||||
ShippingNoticeWorkflowItemVersion.query
|
||||
.filter_by(workflow_item_id=int(item.id), is_current=True)
|
||||
.first()
|
||||
)
|
||||
assert version is not None
|
||||
version.task_id = int(task.id)
|
||||
version.task_no = task.task_no
|
||||
version.excel_artifact_no = 'ART-1'
|
||||
version.is_readonly = False
|
||||
db.session.commit()
|
||||
|
||||
result = mark_cancelled_task_readonly(
|
||||
task=task,
|
||||
actor_id=int(user.id),
|
||||
reason='user cancelled after excel',
|
||||
workflow_item_no=item.item_no,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:软作废 + 文件保留 + Version 只读。
|
||||
assert task.lifecycle_status == 'pending_void'
|
||||
assert task.void_reason == 'user cancelled after excel'
|
||||
assert task.export_file_path == '/tmp/keep-excel.xlsx'
|
||||
assert result['physical_delete'] is False
|
||||
assert result['readonly'] is True
|
||||
assert result['before']['lifecycle_status'] == 'active'
|
||||
assert result['after']['lifecycle_status'] == 'pending_void'
|
||||
refreshed = db.session.get(ShippingNoticeWorkflowItemVersion, int(version.id))
|
||||
assert refreshed is not None
|
||||
assert refreshed.is_readonly is True
|
||||
@@ -2,15 +2,19 @@
|
||||
验证坐标重建仅在可信列锚点下生成可审计的 needs_review 订单行候选。
|
||||
|
||||
依赖:coordinate_table_reconstruction、LayoutBBox。逻辑:覆盖 x 列归属、y 新行、续行与
|
||||
删除标记;没有强行号锚点的行不能被伪装成独立订单明细。
|
||||
删除标记;没有有效起行锚点(customer_po_line_no)的行不能被伪装成独立订单明细。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
reconstruct_coordinate_profile_rows,
|
||||
reconstruct_table_from_positioned_text,
|
||||
resolve_line_start_field_code,
|
||||
suggest_header_layouts,
|
||||
suggest_header_regions,
|
||||
suggest_multi_subrow_layouts,
|
||||
@@ -19,6 +23,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
|
||||
CoordinateReconstructionProfile,
|
||||
OrderDocumentProfile,
|
||||
OrderProfileColumnRule,
|
||||
TableRegionProfile,
|
||||
order_profile_structure_fingerprint,
|
||||
parse_html_table_with_order_profile,
|
||||
reconstruct_order_profile_html,
|
||||
@@ -159,7 +164,7 @@ def test_coordinate_profile_rows_merge_only_declared_physical_layouts():
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
@@ -170,7 +175,22 @@ def test_coordinate_profile_rows_merge_only_declared_physical_layouts():
|
||||
)
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0].fields == {'line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'}
|
||||
assert rows[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'}
|
||||
|
||||
|
||||
def test_line_number_can_be_used_as_a_configured_coordinate_anchor():
|
||||
"""用户选择项次字段时,坐标模板可用 line_no 启动明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('00010', 10), ('PART-A', 65)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
line_start_field_code='line_no',
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{'line_no': '00010', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_coordinate_profile_row_layout_repeats_across_the_table():
|
||||
@@ -182,32 +202,49 @@ def test_coordinate_profile_row_layout_repeats_across_the_table():
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
table_region={'x0': 0, 'y0': .15, 'x1': 1, 'y1': .35},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .15, 'x1': 1, 'y1': .35}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .25, 'y1': .35}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .25, 'y1': .35}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': .15, 'x1': .75, 'y1': .35}},
|
||||
]}],
|
||||
)
|
||||
|
||||
# 断言样例框的 X 版式重复应用到第二条明细,Y 只用于表达该物理子行的相对顺序。
|
||||
assert [row.fields for row in rows] == [
|
||||
{'line_no': '00010', 'part_number': 'PART-A'},
|
||||
{'line_no': '00020', 'part_number': 'PART-B'},
|
||||
{'customer_po_line_no': '00010', 'part_number': 'PART-A'},
|
||||
{'customer_po_line_no': '00020', 'part_number': 'PART-B'},
|
||||
]
|
||||
|
||||
|
||||
def test_coordinate_profile_preview_can_expose_unanchored_main_row_for_review():
|
||||
"""仅预览模式在缺少有效起行值时保留字段证据,正式重建仍严格过滤。"""
|
||||
kwargs = {
|
||||
'characters': _glyphs([('PART-A', 65), ('5', 160)]),
|
||||
'table_bbox': {'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
}
|
||||
|
||||
assert reconstruct_coordinate_profile_rows(**kwargs) == []
|
||||
preview_rows = reconstruct_coordinate_profile_rows(**kwargs, include_unanchored_rows=True)
|
||||
assert [row.fields for row in preview_rows] == [{'part_number': 'PART-A', 'qty': '5'}]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_apply_registered_composite_extractors_atomically():
|
||||
"""qty/uom、金额/币种和单价/币种必须成对拆分;格式无效时不写入任何半截字段。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('00010', 10), ('3 EA', 65), ('USD 10.50', 115), ('12.00 USD', 165)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'extractor_key': 'direct', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'extractor_key': 'direct', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}},
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .2, 'y0': 0, 'x1': .5, 'y1': 1}},
|
||||
{'field_code': 'line_amount_before_tax', 'extractor_key': 'amount_currency', 'region': {'x0': .5, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{'field_code': 'unit_price', 'extractor_key': 'price_currency', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert rows[0].fields == {
|
||||
'line_no': '00010', 'qty': '3', 'uom': 'EA', 'line_amount_before_tax': '10.50',
|
||||
'customer_po_line_no': '00010', 'qty': '3', 'uom': 'EA', 'line_amount_before_tax': '10.50',
|
||||
'currency': 'USD', 'unit_price': '12.00',
|
||||
}
|
||||
|
||||
@@ -215,11 +252,11 @@ def test_coordinate_profile_rows_apply_registered_composite_extractors_atomicall
|
||||
characters=_glyphs([('00010', 10), ('not-a-quantity', 65)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert invalid[0].fields == {'line_no': '00010'}
|
||||
assert invalid[0].fields == {'customer_po_line_no': '00010'}
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_marks_conflicting_composite_values_for_review():
|
||||
@@ -229,7 +266,7 @@ def test_coordinate_profile_rows_marks_conflicting_composite_values_for_review()
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 80},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'qty', 'extractor_key': 'quantity_uom', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'continuation', 'row_offset': 1, 'field_regions': [
|
||||
@@ -245,7 +282,7 @@ def test_coordinate_profile_rows_treat_vertical_regions_as_repeatable_layout_sam
|
||||
"""物理行纵向框表达子行顺序而非绝对页坐标,模板才能重复读取后续明细。"""
|
||||
base_layouts = [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'continuation', 'row_offset': 1, 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .5}, 'field_regions': [
|
||||
@@ -276,7 +313,7 @@ def test_coordinate_profile_rows_reject_swapped_physical_region_order():
|
||||
)
|
||||
layouts = [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'delivery', 'row_offset': 1, 'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .5}, 'field_regions': [
|
||||
@@ -296,7 +333,7 @@ def test_coordinate_profile_rows_reject_swapped_physical_region_order():
|
||||
rejected = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100}, line_layouts=layouts,
|
||||
)
|
||||
assert rejected[0].fields == {'line_no': '00010', 'part_number': 'PART-A'}
|
||||
assert rejected[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A'}
|
||||
assert rejected[0].issues == ['coordinate_profile_layout_region_mismatch']
|
||||
|
||||
|
||||
@@ -306,7 +343,7 @@ def test_coordinate_profile_rows_restore_pdf_visual_spaces():
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'shipway', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
@@ -323,11 +360,11 @@ def test_coordinate_profile_rows_hide_deleted_records_by_default_and_expose_them
|
||||
[('TOTAL AMOUNT', 65)],
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
assert [row.fields for row in rows] == [{'line_no': '00020', 'part_number': 'PART-KEEP'}]
|
||||
assert [row.fields for row in rows] == [{'customer_po_line_no': '00020', 'part_number': 'PART-KEEP'}]
|
||||
|
||||
preview_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
@@ -336,12 +373,12 @@ def test_coordinate_profile_rows_hide_deleted_records_by_default_and_expose_them
|
||||
[('00020', 10), ('PART-KEEP', 65)],
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}], include_deleted=True,
|
||||
)
|
||||
# 关键断言:预览保留被删除的原始明细,但角色明确标识为不可纳入结果。
|
||||
assert [(row.fields['line_no'], row.role) for row in preview_rows] == [('00010', 'deleted'), ('00020', 'data')]
|
||||
assert [(row.fields['customer_po_line_no'], row.role) for row in preview_rows] == [('00010', 'deleted'), ('00020', 'data')]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schema_fields():
|
||||
@@ -357,7 +394,7 @@ def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schem
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 300, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .3}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .12, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .12, 'y1': 1}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .12, 'y0': 0, 'x1': .58, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .58, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
@@ -380,7 +417,7 @@ def test_coordinate_profile_rows_replay_f9a1_four_physical_rows_with_bound_schem
|
||||
assert len(rows) == 1
|
||||
assert rows[0].source_row_indices == [0, 1, 2, 3]
|
||||
assert rows[0].fields == {
|
||||
'line_no': '10', 'customer_part_number': '541-000175-007', 'part_number': 'B3-A08AR10000018-A7',
|
||||
'customer_po_line_no': '10', 'customer_part_number': '541-000175-007', 'part_number': 'B3-A08AR10000018-A7',
|
||||
'qty': '3.000', 'uom': 'PCS', 'required_date': '2026/05/05', 'incoterm': 'EXW SGSIN DBS',
|
||||
'unit_price': '1,645.11000', 'line_amount_before_tax': '4,935.33', 'reservation_id': '@ 3000092530',
|
||||
}
|
||||
@@ -403,7 +440,7 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
|
||||
'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .15, 'x1': 1, 'y1': .48},
|
||||
'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .12, 'y1': .25}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .12, 'y1': .25}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .38, 'y0': .15, 'x1': 1, 'y1': .25}},
|
||||
{'field_code': 'qty', 'region': {'x0': .38, 'y0': .26, 'x1': .52, 'y1': .36}},
|
||||
{'field_code': 'uom', 'region': {'x0': .52, 'y0': .26, 'x1': .63, 'y1': .36}},
|
||||
@@ -417,12 +454,12 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
|
||||
# 数量与单位不得从同一横向范围内、但位于首视觉行的内部料号尾数读取。
|
||||
assert [row.fields for row in rows] == [
|
||||
{
|
||||
'line_no': '10', 'part_number': 'B3-A08AR10000018-A7', 'qty': '3.000', 'uom': 'PCS',
|
||||
'customer_po_line_no': '10', 'part_number': 'B3-A08AR10000018-A7', 'qty': '3.000', 'uom': 'PCS',
|
||||
'requested_receipt_date': '2026/05/05', 'unit_price': '1,645.11000',
|
||||
'line_amount_before_tax': '4,935.33',
|
||||
},
|
||||
{
|
||||
'line_no': '20', 'part_number': 'B3-A08AR10000027-A9', 'qty': '8.000', 'uom': 'EA',
|
||||
'customer_po_line_no': '20', 'part_number': 'B3-A08AR10000027-A9', 'qty': '8.000', 'uom': 'EA',
|
||||
'requested_receipt_date': '2026/06/01', 'unit_price': '2,100.00000',
|
||||
'line_amount_before_tax': '16,800.00',
|
||||
},
|
||||
@@ -439,7 +476,7 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
|
||||
'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .65},
|
||||
'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .12, 'y1': .35}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .12, 'y1': .35}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .38, 'y0': .2, 'x1': 1, 'y1': .35}},
|
||||
{'field_code': 'qty', 'region': {'x0': .38, 'y0': .36, 'x1': .52, 'y1': .5}},
|
||||
],
|
||||
@@ -467,7 +504,7 @@ def test_coordinate_profile_rows_replay_sample_visual_band_offsets_despite_paren
|
||||
# 样例父框包含第三子行后的留白;线性压缩会让第二子行字段落入空白。
|
||||
'region': {'x0': 0, 'y0': .05, 'x1': 1, 'y1': .53},
|
||||
'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .12, 'x1': .2, 'y1': .19}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .12, 'x1': .2, 'y1': .19}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .12, 'x1': .64, 'y1': .19}},
|
||||
{'field_code': 'qty', 'region': {'x0': .76, 'y0': .12, 'x1': .86, 'y1': .19}},
|
||||
{'field_code': 'uom', 'region': {'x0': .86, 'y0': .12, 'x1': 1, 'y1': .19}},
|
||||
@@ -479,11 +516,11 @@ def test_coordinate_profile_rows_replay_sample_visual_band_offsets_despite_paren
|
||||
|
||||
assert [row.fields for row in rows] == [
|
||||
{
|
||||
'line_no': '00010', 'customer_part_number': '6Y70B2501901', 'qty': '0', 'uom': 'EA',
|
||||
'customer_po_line_no': '00010', 'customer_part_number': '6Y70B2501901', 'qty': '0', 'uom': 'EA',
|
||||
'part_number': 'D4-A08AR12000002', 'requested_receipt_date': '06/22/2026',
|
||||
},
|
||||
{
|
||||
'line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'customer_po_line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'part_number': 'D4-A08AR12000002', 'requested_receipt_date': '06/29/2026',
|
||||
},
|
||||
]
|
||||
@@ -503,7 +540,7 @@ def test_coordinate_profile_rows_calibrate_unbound_visual_bands_from_sample_evid
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 120},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .2, 'y1': .25}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .2, 'y1': .25}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .15, 'x1': .6, 'y1': .25}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .38, 'x1': .6, 'y1': .48}},
|
||||
]}],
|
||||
@@ -525,7 +562,7 @@ def test_coordinate_profile_rows_realign_a_record_with_an_extra_unbound_visual_b
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .7}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .6, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .34, 'x1': .6, 'y1': .44}},
|
||||
]}],
|
||||
@@ -547,7 +584,7 @@ def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 240, 'y1': 100},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0,
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .7}, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .6, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .34, 'x1': .6, 'y1': .44}},
|
||||
]}],
|
||||
@@ -574,7 +611,7 @@ def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 160},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .18, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .18, 'y1': 1}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .18, 'y0': 0, 'x1': .7, 'y1': 1}},
|
||||
{'field_code': 'qty', 'region': {'x0': .7, 'y0': 0, 'x1': .85, 'y1': 1}},
|
||||
{'field_code': 'uom', 'region': {'x0': .85, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
@@ -592,7 +629,7 @@ def test_coordinate_profile_rows_replay_4518838152_deletion_and_summary_boundary
|
||||
assert len(rows) == 1
|
||||
assert rows[0].source_row_indices == [4, 5, 6]
|
||||
assert rows[0].fields == {
|
||||
'line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'customer_po_line_no': '00020', 'customer_part_number': '6Y70B2501901', 'qty': '30', 'uom': 'EA',
|
||||
'part_number': 'D4-A08AR12000002', 'required_date': '06/29/2026', 'incoterm': 'EXW AWS HUB',
|
||||
}
|
||||
|
||||
@@ -615,19 +652,19 @@ def test_coordinate_profile_rows_honor_configured_table_exclusion_and_terminatio
|
||||
'region': {'x0': 0, 'y0': .6, 'x1': 1, 'y1': .75},
|
||||
}}],
|
||||
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]}],
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{'line_no': '00010', 'part_number': 'PART-A'}]
|
||||
assert [row.fields for row in rows] == [{'customer_po_line_no': '00010', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_can_continue_only_explicit_carry_state_on_next_page():
|
||||
"""跨页续行由调用方传入已验证的 carry;当前页自身没有主行锚点时不会擅自建行。"""
|
||||
layouts = [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
|
||||
{'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
]},
|
||||
{'layout_id': 'delivery', 'row_offset': 1, 'field_regions': [
|
||||
@@ -641,9 +678,9 @@ def test_coordinate_profile_rows_can_continue_only_explicit_carry_state_on_next_
|
||||
|
||||
continued = reconstruct_coordinate_profile_rows(
|
||||
characters=page_two, table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60}, line_layouts=layouts,
|
||||
initial_fields={'line_no': '00010', 'part_number': 'PART-A'}, initial_next_offset=1,
|
||||
initial_fields={'customer_po_line_no': '00010', 'part_number': 'PART-A'}, initial_next_offset=1,
|
||||
)
|
||||
assert continued[0].fields == {'line_no': '00010', 'part_number': 'PART-A', 'required_date': '2026-08-01'}
|
||||
assert continued[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A', 'required_date': '2026-08-01'}
|
||||
|
||||
|
||||
def test_currency_composite_output_becomes_header_only_when_all_rows_agree():
|
||||
@@ -761,7 +798,7 @@ def test_coordinate_profile_parses_one_logical_line_from_multiple_visual_rows():
|
||||
"""端到端验证:一条数据行加两条续行只能产出一条可审核订单明细。"""
|
||||
settings = CoordinateReconstructionProfile(
|
||||
column_boundaries=[0, 0.2, 0.7, 1],
|
||||
column_field_codes=['line_no', 'part_number', 'qty'],
|
||||
column_field_codes=['customer_po_line_no', 'part_number', 'qty'],
|
||||
)
|
||||
html = reconstruct_order_profile_html(
|
||||
characters=_glyphs(
|
||||
@@ -778,14 +815,14 @@ def test_coordinate_profile_parses_one_logical_line_from_multiple_visual_rows():
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
header_row_index=0, data_start_row_index=1,
|
||||
column_rules=[
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['line_no']),
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['customer_po_line_no']),
|
||||
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['part_number']),
|
||||
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['qty']),
|
||||
],
|
||||
coordinate_reconstruction=settings,
|
||||
)
|
||||
contract = compile_table_header_contract({'fields': [
|
||||
{'field_code': 'line_no', 'display_name': 'Line', 'enabled': True},
|
||||
{'field_code': 'customer_po_line_no', 'display_name': 'Customer PO Line', 'enabled': True},
|
||||
{'field_code': 'part_number', 'display_name': 'Part', 'enabled': True},
|
||||
{'field_code': 'qty', 'display_name': 'Qty', 'value_type': 'decimal', 'enabled': True},
|
||||
]})
|
||||
@@ -795,7 +832,7 @@ def test_coordinate_profile_parses_one_logical_line_from_multiple_visual_rows():
|
||||
assert parsed.matched is True
|
||||
assert len(parsed.rows) == 1
|
||||
assert parsed.rows[0].fields == {
|
||||
'line_no': '00020', 'part_number': '6Y70B2501901 D4-A08AR1200002 RoHS2', 'qty': 30,
|
||||
'customer_po_line_no': '00020', 'part_number': '6Y70B2501901 D4-A08AR1200002 RoHS2', 'qty': 30,
|
||||
}
|
||||
|
||||
|
||||
@@ -805,7 +842,7 @@ def test_multi_subrow_profile_uses_independent_overlapping_boundaries():
|
||||
{
|
||||
'role': 'main', 'row_offset': 0,
|
||||
'column_boundaries': [0, 0.12, 0.32, 0.5, 0.68, 0.84, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'remark', 'unit_price', 'qty', 'uom'],
|
||||
'column_field_codes': ['customer_po_line_no', 'part_number', 'remark', 'unit_price', 'qty', 'uom'],
|
||||
},
|
||||
{
|
||||
'role': 'continuation', 'row_offset': 1,
|
||||
@@ -840,7 +877,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
"""多子行输出必须继续由既有固定列 Profile 解析器消费,避免另造运行链路。"""
|
||||
settings = CoordinateReconstructionProfile(subrow_layouts=[
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.2, 0.65, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
'column_field_codes': ['customer_po_line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.4, 0.7, 1],
|
||||
'column_field_codes': [None, 'required_date', 'line_remark']},
|
||||
])
|
||||
@@ -853,7 +890,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
reconstruction=settings,
|
||||
)
|
||||
grid = parse_html_grid(html, table_id='multi-subrow')
|
||||
headers = ['line_no', 'part_number', 'qty', 'required_date', 'line_remark']
|
||||
headers = ['customer_po_line_no', 'part_number', 'qty', 'required_date', 'line_remark']
|
||||
profile = OrderDocumentProfile(
|
||||
profile_code='MULTI_SUBROW', version=1,
|
||||
structure_fingerprint=order_profile_structure_fingerprint(grid, header_row_index=0),
|
||||
@@ -865,7 +902,7 @@ def test_multi_subrow_profile_parses_merged_fields_with_existing_profile_parser(
|
||||
coordinate_reconstruction=settings,
|
||||
)
|
||||
contract = compile_table_header_contract({'fields': [
|
||||
{'field_code': 'line_no', 'enabled': True},
|
||||
{'field_code': 'customer_po_line_no', 'enabled': True},
|
||||
{'field_code': 'part_number', 'enabled': True},
|
||||
{'field_code': 'qty', 'value_type': 'decimal', 'enabled': True},
|
||||
{'field_code': 'required_date', 'value_type': 'date', 'enabled': True},
|
||||
@@ -886,7 +923,7 @@ def test_multi_subrow_profile_supports_four_or_more_physical_rows():
|
||||
"""逻辑明细行数由模板动态定义,四行版式不得被固定三行实现截断。"""
|
||||
settings = CoordinateReconstructionProfile(subrow_layouts=[
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.25, 0.7, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
'column_field_codes': ['customer_po_line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'customer_part_number']},
|
||||
{'role': 'continuation', 'row_offset': 2, 'column_boundaries': [0, 0.5, 1],
|
||||
@@ -926,8 +963,37 @@ def test_layout_suggestion_uses_real_rows_and_dynamic_column_counts():
|
||||
)
|
||||
|
||||
assert len(suggestions) == 3
|
||||
assert suggestions[0].suggested_field_codes[0] == 'line_no'
|
||||
assert suggestions[0].suggested_field_codes[0] == 'customer_po_line_no'
|
||||
assert suggestions[0].column_samples[0] == ['00020']
|
||||
assert 'B3-AR1000270A1' in suggestions[1].column_samples[0]
|
||||
assert suggestions[2].column_boundaries[0] == 0
|
||||
assert suggestions[2].column_boundaries[-1] == 1
|
||||
|
||||
|
||||
|
||||
def test_resolve_line_start_defaults_to_customer_po_line_no():
|
||||
"""缺省起行锚点为客户 PO 行号;内部项次 line_no 亦可显式配置。"""
|
||||
assert resolve_line_start_field_code(None) == 'customer_po_line_no'
|
||||
assert resolve_line_start_field_code('customer_po_line_no') == 'customer_po_line_no'
|
||||
assert resolve_line_start_field_code('line_no') == 'line_no'
|
||||
|
||||
|
||||
def test_table_region_profile_allows_binding_internal_line_no():
|
||||
"""内部项次 line_no 可作为坐标模板明细字段绑定。"""
|
||||
payload = {
|
||||
'region_id': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'line_start_field_code': 'line_no',
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{
|
||||
'field_id': 'line', 'field_code': 'line_no',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
profile = TableRegionProfile.model_validate(payload)
|
||||
assert profile.line_layouts[0].field_regions[0].field_code == 'line_no'
|
||||
assert profile.line_start_field_code == 'line_no'
|
||||
@@ -79,11 +79,14 @@ def test_pending_customer_blocks_every_downstream_entry(app):
|
||||
ensure_inventory_via_rpa(task, mode='auto'),
|
||||
match_inventory({'task_id': task.task_no}),
|
||||
generate_excel({'task_id': task.task_no}),
|
||||
upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}),
|
||||
]
|
||||
for result in results:
|
||||
_assert_customer_gate_response(result)
|
||||
|
||||
# upload_to_freight(manual_confirm) 仍受客户门禁约束(不再范围外硬拒绝)。
|
||||
upload = upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'})
|
||||
_assert_customer_gate_response(upload)
|
||||
|
||||
callback = _validate_rpa_callback_gate(task)
|
||||
assert callback is not None
|
||||
assert callback['status'] == 'failed'
|
||||
|
||||
@@ -118,8 +118,8 @@ def test_layout_schedule_is_idempotent_and_force_creates_next_version(app):
|
||||
assert job.payload_json == {'layout_version_id': forced.id}
|
||||
|
||||
|
||||
def test_layout_schedule_reuses_same_owner_completed_layout_for_duplicate_document(app):
|
||||
"""相同管理员重复上传相同文件时,新 Document 必须直接复用可用布局。"""
|
||||
def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_document(app):
|
||||
"""相同管理员重复上传相同文件时,新 Document 必须拥有自己的可用布局版本。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
@@ -142,9 +142,13 @@ def test_layout_schedule_reuses_same_owner_completed_layout_for_duplicate_docume
|
||||
reused = schedule_layout_version(duplicate)
|
||||
db.session.commit()
|
||||
|
||||
assert reused.id == ready.id
|
||||
assert duplicate.current_layout_version_id == ready.id
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 1
|
||||
# Layout 版本归属当前 Document;只复用冻结 payload,禁止跨 Document 外键引用。
|
||||
assert reused.id != ready.id
|
||||
assert reused.document_id == duplicate.id
|
||||
assert duplicate.current_layout_version_id == reused.id
|
||||
assert reused.status == 'ready'
|
||||
assert reused.payload_json == ready.payload_json
|
||||
assert ShippingDocumentLayoutVersion.query.count() == 2
|
||||
|
||||
|
||||
def test_layout_parser_revision_change_creates_new_version_without_force(app):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/tests/test_shipping_document_profile_quality.py
|
||||
|
||||
用途:验证订单文档模板的独立盲测、批准资格和冻结 checksum 门禁。
|
||||
用途:验证订单文档模板的独立盲测候选、批准资格和冻结 checksum 门禁。
|
||||
依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。
|
||||
逻辑:管理员固化一份独立样本真值;通过且批准后才可放行确定性自动建单。
|
||||
"""
|
||||
@@ -43,7 +43,7 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
|
||||
schema_id=schema.id, version=1, status='published', checksum='a' * 64,
|
||||
published_at=datetime.utcnow(), definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'line-id', 'field_code': 'line_no', 'scope': 'line',
|
||||
'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'required': True,
|
||||
'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
@@ -121,7 +121,7 @@ def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
|
||||
profile.published_at = None
|
||||
profile.definition_json = {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {'required_anchors': []},
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'plant_name', 'label': 'PLANT NAME:', 'value': 'FACTORY A'}]},
|
||||
'table_regions': [{
|
||||
'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
|
||||
@@ -130,7 +130,8 @@ def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': .2, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'], 'allowed_empty_fields': [],
|
||||
@@ -220,6 +221,71 @@ def test_independent_sample_review_reuses_existing_truth_and_excludes_training_i
|
||||
assert sample.expected_rows_json == candidate['rows']
|
||||
|
||||
|
||||
def test_independent_samples_include_historical_blind_documents(app):
|
||||
"""关键断言:新版本可复用同一模板族的历史盲测文档,但必须重新确认本版本真值。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
historical_suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
quality.add_sample(
|
||||
suite_id=historical_suite['id'], document_id=documents[0].id, table_id='table-1',
|
||||
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
|
||||
)
|
||||
draft = ShippingOrderDocumentProfile(
|
||||
profile_code=profile.profile_code, display_name=profile.display_name, version=2, status='draft',
|
||||
schema_version_id=profile.schema_version_id, structure_fingerprint=profile.structure_fingerprint,
|
||||
definition_json=profile.definition_json, source_profile_id=profile.id,
|
||||
)
|
||||
db.session.add(draft)
|
||||
db.session.commit()
|
||||
suite = quality.create_suite(profile_id=draft.id, actor_id=user.id)
|
||||
|
||||
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
||||
|
||||
assert {(item['document_id'], item['table_id']) for item in available} == {(documents[0].id, 'table-1')}
|
||||
|
||||
|
||||
def test_independent_samples_include_all_historical_profile_sample_roles(app):
|
||||
"""关键断言:历史 annotation/training/旧 blind_test 绑定均可作为新版本待复核来源。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
roles = ('annotation', 'training', 'blind_test')
|
||||
for document, role in zip(documents, roles, strict=True):
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id, document_id=document.id, table_id='table-1',
|
||||
sample_role=role, created_by_id=user.id,
|
||||
))
|
||||
draft = ShippingOrderDocumentProfile(
|
||||
profile_code=profile.profile_code, display_name=profile.display_name, version=2, status='draft',
|
||||
schema_version_id=profile.schema_version_id, structure_fingerprint=profile.structure_fingerprint,
|
||||
definition_json=profile.definition_json, source_profile_id=profile.id,
|
||||
)
|
||||
db.session.add(draft)
|
||||
db.session.commit()
|
||||
suite = quality.create_suite(profile_id=draft.id, actor_id=user.id)
|
||||
|
||||
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
||||
|
||||
# 三种历史角色只提供来源;加入当前套件前仍需走候选预览和人工确认。
|
||||
assert {item['document_id'] for item in available} == {item.id for item in documents}
|
||||
|
||||
|
||||
def test_independent_samples_deduplicate_reuploaded_content(app):
|
||||
"""关键断言:相同文件内容重复上传不会用相同表格摘要占满独立样本选择器。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
for document in documents[:2]:
|
||||
db.session.get(ShippingNoticeIntake, document.intake_id).purpose = 'order_document_profile_sample'
|
||||
documents[1].content_hash = documents[0].content_hash
|
||||
db.session.commit()
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
|
||||
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
||||
|
||||
# 两个相同内容、相同页表结构的 Document 仅保留较新的候选。
|
||||
matching = [item for item in available if item['document_id'] in {documents[0].id, documents[1].id}]
|
||||
assert len(matching) == 1
|
||||
|
||||
|
||||
def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid(app):
|
||||
"""v2 盲测直接回放坐标字段,HTML 网格即使不存在也不能成为质量执行依赖。"""
|
||||
with app.app_context():
|
||||
@@ -229,7 +295,7 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid
|
||||
'table_regions': [{'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': .15, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
@@ -249,7 +315,7 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
for document in documents:
|
||||
quality.add_sample(suite_id=suite['id'], document_id=document.id, table_id='table-1',
|
||||
expected_rows=[{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
expected_rows=[{'customer_po_line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
|
||||
@@ -291,9 +357,14 @@ def test_coordinate_blind_preview_skips_header_only_regions(app):
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{'field_id': 'part-id', 'field_code': 'part_number',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate']}],
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'customer_po_line_no',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number',
|
||||
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
}]},
|
||||
{'region_id': 'header_only', 'page_scope': 'exact_page', 'page_no': 2,
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
@@ -503,7 +574,7 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
profile.published_at = None
|
||||
profile.definition_json = {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {'required_anchors': []},
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'label': 'DOCUMENT TYPE:', 'value': 'PURCHASE ORDER', 'value_position': 'right'}]},
|
||||
'table_regions': [{
|
||||
'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [{'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .15}, 'field_regions': []}], 'termination_rules': [], 'exclusion_regions': [],
|
||||
@@ -512,7 +583,7 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': .16, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': .16, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .16, 'x1': .15, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': .15, 'y0': .16, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
@@ -563,10 +634,10 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[0].id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
assert getattr(reused.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT'
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[
|
||||
{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'},
|
||||
{'customer_po_line_no': '00010', 'part_number': 'PN-1', 'qty': '3'},
|
||||
], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'line_no': '00010', 'part_number': 'PN-3', 'qty': '5'}], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'customer_po_line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'customer_po_line_no': '00010', 'part_number': 'PN-3', 'qty': '5'}], actor_id=user.id)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
|
||||
@@ -21,11 +21,11 @@ from app.services.shipping_notice.standard_field_registry import (
|
||||
|
||||
|
||||
def test_registry_is_consistent_and_suggests_fifteen():
|
||||
"""断言:57 项注册表自洽;默认建议采用集恰好 15 且均在标准目录内。"""
|
||||
"""断言:58 项注册表自洽;默认建议采用集恰好 14 且均在标准目录内。"""
|
||||
assert_registry_consistent()
|
||||
assert len(STANDARD_FIELD_SPECS) == 57
|
||||
assert len(DEFAULT_V1_ADOPTION_CODES) == 15
|
||||
assert set(DEFAULT_V1_ADOPTION_CODES) <= set(STANDARD_FIELD_SPECS)
|
||||
assert len(STANDARD_FIELD_SPECS) == 58
|
||||
assert len(DEFAULT_V1_ADOPTION_CODES) == 14
|
||||
assert all(any(code == item_code for _, item_code in STANDARD_FIELD_SPECS) for code in DEFAULT_V1_ADOPTION_CODES)
|
||||
|
||||
|
||||
def test_ensure_standard_assets_seeded(app):
|
||||
@@ -34,7 +34,7 @@ def test_ensure_standard_assets_seeded(app):
|
||||
inserted = assets.ensure_standard_assets_seeded(actor_id=None)
|
||||
assert inserted >= 0
|
||||
listed = assets.list_assets(asset_kind='system_standard', status='active')
|
||||
assert listed['standard_count'] == 57
|
||||
assert listed['standard_count'] == 58
|
||||
assert 'part_number' in {item['field_code'] for item in listed['items']}
|
||||
|
||||
|
||||
|
||||
@@ -29,8 +29,8 @@ def test_ensure_standard_assets_seeds_fifty_seven_fields(app):
|
||||
inserted = _field_assets().ensure_standard_assets_seeded()
|
||||
assert inserted == len(STANDARD_FIELD_SPECS)
|
||||
rows = ShippingOrderField.query.filter_by(asset_kind='system_standard').all()
|
||||
assert len(rows) == 57
|
||||
assert {row.field_code for row in rows} == set(STANDARD_FIELD_SPECS.keys())
|
||||
assert len(rows) == 58
|
||||
assert {(row.scope, row.field_code) for row in rows} == set(STANDARD_FIELD_SPECS.keys())
|
||||
|
||||
|
||||
def test_create_extension_field(app):
|
||||
@@ -144,7 +144,7 @@ def test_analyze_field_impact_structure(app):
|
||||
assert impact['blocking_count'] == len(impact['blocking_kinds'])
|
||||
assert set(impact['historical']) == {
|
||||
'observation_count', 'decision_count', 'value_count',
|
||||
'immutable_schema_version_count', 'blocks_publish',
|
||||
'immutable_schema_version_count', 'immutable_schema_versions', 'blocks_publish',
|
||||
}
|
||||
assert impact['can_unadopt'] is True
|
||||
assert impact['can_retire_extension'] is False
|
||||
@@ -185,7 +185,7 @@ def test_field_governance_rebuild_migration_seeds_global_assets(monkeypatch):
|
||||
field_rows = connection.execute(sa.text(
|
||||
"SELECT field_code, asset_kind, status FROM shipping_order_fields"
|
||||
)).mappings().all()
|
||||
assert len(field_rows) == len(STANDARD_FIELD_SPECS) == 57
|
||||
assert len(field_rows) == len(STANDARD_FIELD_SPECS) == 58
|
||||
assert all(row['asset_kind'] == 'system_standard' for row in field_rows)
|
||||
assert all(row['status'] == 'active' for row in field_rows)
|
||||
assert 'legacy_po' not in {row['field_code'] for row in field_rows}
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
"""
|
||||
tests/test_shipping_inventory_candidate_routing.py
|
||||
|
||||
用途:验证 field_id→值 路由路径与冻结 Snapshot 路由路径结果一致,并断言 can_build 语义。
|
||||
依赖:inventory_routing_engine、订单 Schema service、库存路由模型。
|
||||
逻辑:同一组字段值分别走 Snapshot 与 field_values 评估器,对比 status/source_codes;
|
||||
覆盖 ambiguous 多候选可建单与 unresolved/conflicted 不可建单分支。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition, ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_routing_engine import (
|
||||
evaluate_inventory_source_rules,
|
||||
evaluate_inventory_source_rules_for_field_values,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _field_config(field_id: str, *, name: str, value_type: str = 'string') -> dict:
|
||||
"""构造最小可发布行字段配置。"""
|
||||
return {
|
||||
'field_id': field_id, 'display_name': name, 'required': False, 'aliases': [],
|
||||
'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim',
|
||||
'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text',
|
||||
'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_table'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None,
|
||||
}
|
||||
|
||||
|
||||
def _published_line_fields() -> dict[str, str]:
|
||||
"""创建并发布路由测试所需字段契约。"""
|
||||
order_schema_service.initialize_schema({'display_name': '候选路由字段'}, actor_id=None)
|
||||
reservation = order_schema_service.save_field(
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
part_number = order_schema_service.save_field(
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
qty = order_schema_service.save_field(
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None,
|
||||
)
|
||||
source_hint = order_schema_service.save_field(
|
||||
{'field_code': 'inventory_source_hint', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
reservation_config = _field_config(reservation['id'], name='预定单号')
|
||||
reservation_config['business_purpose'] = 'reservation_id'
|
||||
part_number_config = _field_config(part_number['id'], name='料号')
|
||||
part_number_config['business_purpose'] = 'part_number'
|
||||
qty_config = _field_config(qty['id'], name='数量', value_type='decimal')
|
||||
qty_config['business_purpose'] = 'quantity'
|
||||
source_hint_config = _field_config(source_hint['id'], name='库存源线索')
|
||||
source_hint_config['business_purpose'] = 'inventory_source_hint'
|
||||
saved = order_schema_service.save_draft(draft['id'], {
|
||||
'fields': [reservation_config, part_number_config, qty_config, source_hint_config],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
return {
|
||||
'reservation_id': reservation['id'], 'part_number': part_number['id'], 'qty': qty['id'],
|
||||
'inventory_source_hint': source_hint['id'],
|
||||
}
|
||||
|
||||
|
||||
def _task_with_line_values(
|
||||
fields: dict[str, str], values: dict[str, tuple[str, str]],
|
||||
) -> tuple[ShippingTask, dict[str, int]]:
|
||||
"""创建冻结快照供 Snapshot 路由路径读取。"""
|
||||
task = ShippingTask(task_no='SN-CANDIDATE-ROUTE', user_id=None, source_type='manual')
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=order_schema_service.get_published_contract()['schema_version_id'],
|
||||
input_snapshot_hash='c' * 64, status='accepted', task_id=task.id,
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for field_id, (value, _purpose) in values.items():
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_status='accepted',
|
||||
supporting_observation_ids_json=[], resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_id=decision.id,
|
||||
value_text=value, value_json=value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
snapshot_values = {field_id: value for field_id, (value, _purpose) in values.items()}
|
||||
snapshot_values.setdefault(fields['part_number'], 'PN-ROUTE')
|
||||
snapshot_values.setdefault(fields['qty'], '1')
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id,
|
||||
schema_version_id=extraction.schema_version_id, order_data_version=1,
|
||||
rule_versions_json={}, header_values_json={}, customer_po_number='ROUTE-PO-001',
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=0,
|
||||
reservation_id=str(snapshot_values.get(fields['reservation_id']) or ''),
|
||||
part_number=str(snapshot_values[fields['part_number']]), qty=snapshot_values[fields['qty']],
|
||||
field_values_json=snapshot_values,
|
||||
))
|
||||
task.order_snapshot_id = snapshot.id
|
||||
db.session.flush()
|
||||
return task, {'_position': 0}
|
||||
|
||||
|
||||
def _rule(*, code: str, priority: int, sources: list[str], conditions: list[tuple[str, str, object]], action_type: str = 'add_source_candidates'):
|
||||
"""构造已发布行级路由规则。"""
|
||||
return ShippingInventoryRoutingRule(
|
||||
rule_code=code, rule_name=code, scope='line', priority=priority, match_mode='all',
|
||||
status='published', action_type=action_type, action_payload_json={'source_codes': sources}, version=1,
|
||||
conditions=[
|
||||
ShippingInventoryRoutingRuleCondition(
|
||||
condition_group=1, source_kind='order_field', order_field_id=field_id,
|
||||
operator=operator, expected_value_json=expected, sequence=index,
|
||||
)
|
||||
for index, (field_id, operator, expected) in enumerate(conditions, start=1)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def _field_value_maps(fields: dict[str, str], values: dict[str, str]) -> dict[str, Any]:
|
||||
"""将 field_code 值转为 field_id 映射供 field_values 路径使用。"""
|
||||
return {fields[key]: value for key, value in values.items() if key in fields}
|
||||
|
||||
|
||||
def test_field_values_path_mirrors_snapshot_path(app):
|
||||
"""同一字段值在 Snapshot 与 field_values 两条路径应得到相同 status 与 source_codes。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
line_values = {
|
||||
'reservation_id': '1000123456',
|
||||
'part_number': 'PN-ROUTE',
|
||||
'qty': '1',
|
||||
}
|
||||
task, line = _task_with_line_values(
|
||||
fields,
|
||||
{fields['reservation_id']: (line_values['reservation_id'], 'reservation_id')},
|
||||
)
|
||||
db.session.add(_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '1')],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
snapshot_result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
field_result = evaluate_inventory_source_rules_for_field_values(
|
||||
line_field_values=_field_value_maps(fields, line_values),
|
||||
scope='line',
|
||||
)
|
||||
|
||||
# 关键断言:两条评估路径输出一致。
|
||||
assert snapshot_result.status == field_result.status == 'ambiguous'
|
||||
assert snapshot_result.source_codes == field_result.source_codes == ('DBS_DUB', 'DBS_RTM')
|
||||
assert snapshot_result.matched_rule_ids == field_result.matched_rule_ids
|
||||
|
||||
|
||||
def test_ambiguous_multi_candidate_can_build(app):
|
||||
"""两位候选时 status=ambiguous 且 can_build=True。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
db.session.add(_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '1')],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = evaluate_inventory_source_rules_for_field_values(
|
||||
line_field_values={fields['reservation_id']: '1000123456'},
|
||||
scope='line',
|
||||
)
|
||||
|
||||
# 关键断言:多候选允许建单。
|
||||
assert result.status == 'ambiguous'
|
||||
assert len(result.source_codes) == 2
|
||||
assert result.can_build is True
|
||||
assert result.block_reason is None
|
||||
|
||||
|
||||
def test_unresolved_and_conflicted_cannot_build(app):
|
||||
"""无候选(unresolved)与强制复核(conflicted)均 can_build=False。"""
|
||||
with app.app_context():
|
||||
fields = _published_line_fields()
|
||||
db.session.add(_rule(
|
||||
code='FORCE_REVIEW', priority=100, sources=['DBS_DUB'],
|
||||
conditions=[(fields['reservation_id'], 'prefix', '9')],
|
||||
action_type='require_manual_review',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
unresolved = evaluate_inventory_source_rules_for_field_values(
|
||||
line_field_values={fields['reservation_id']: '3000092917'},
|
||||
scope='line',
|
||||
)
|
||||
conflicted = evaluate_inventory_source_rules_for_field_values(
|
||||
line_field_values={fields['reservation_id']: '9000123456'},
|
||||
scope='line',
|
||||
)
|
||||
|
||||
# 关键断言:零候选与强制复核均阻断建单。
|
||||
assert unresolved.status == 'unresolved'
|
||||
assert unresolved.can_build is False
|
||||
assert unresolved.block_reason == 'no_inventory_source_candidates'
|
||||
assert conflicted.status == 'conflicted'
|
||||
assert conflicted.can_build is False
|
||||
assert conflicted.block_reason == 'require_manual_review'
|
||||
@@ -207,8 +207,8 @@ def test_dynamic_source_resolves_warehouse_by_reservation_and_part_number(app, t
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
part_field = ShippingOrderField.query.filter_by(field_code='part_number').one()
|
||||
reservation_field = ShippingOrderField.query.filter_by(field_code='reservation_id').one()
|
||||
part_field = ShippingOrderField.query.filter_by(field_code='part_number', scope='line').one()
|
||||
reservation_field = ShippingOrderField.query.filter_by(field_code='reservation_id', scope='line').one()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', checksum='d' * 64,
|
||||
definition_json={'fields': [
|
||||
|
||||
@@ -144,6 +144,8 @@ def test_reservation_prefix_rule_returns_ambiguous_source_candidates(app):
|
||||
result = evaluate_inventory_source_rules(task=task, line=line)
|
||||
assert result.status == 'ambiguous'
|
||||
assert result.source_codes == ('DBS_DUB', 'DBS_RTM')
|
||||
assert result.can_build is True
|
||||
assert result.block_reason is None
|
||||
|
||||
|
||||
def test_inventory_source_hint_wins_over_reservation_fallback(app):
|
||||
|
||||
@@ -30,7 +30,7 @@ def test_validate_registry_has_no_errors() -> None:
|
||||
|
||||
|
||||
def test_checkpoint_kinds_for_stp_stop_points() -> None:
|
||||
"""STP 关键检查点 kind:导出待上传 / 解析复核 / 已上传终态。"""
|
||||
"""STP 关键检查点 kind:导出 Excel 后待人工上传登记 / 解析复核 / 已上传终态。"""
|
||||
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
assert checkpoint_kind_for(CP_PARSE_REVIEW) == CheckpointKind.MUST_HUMAN
|
||||
assert checkpoint_kind_for(CP_UPLOADED) == CheckpointKind.COMPLETE
|
||||
@@ -52,7 +52,7 @@ def test_resolve_task_ui_state_parse_review(app) -> None:
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
"""matched 且已有 export_file_path 应为 wait_manual_upload。"""
|
||||
"""matched 且已有 export_file_path 应为 wait_manual_upload(待人工上传登记)。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-SM-EXPORT",
|
||||
@@ -64,6 +64,7 @@ def test_resolve_task_ui_state_export_ready(app) -> None:
|
||||
ui = resolve_task_ui_state(task)
|
||||
assert ui.checkpoint == CP_EXPORT_READY
|
||||
assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD
|
||||
assert "mark_manual_uploaded" in (ui.human_options or [])
|
||||
|
||||
|
||||
def test_resolve_task_ui_state_uploaded_complete(app) -> None:
|
||||
|
||||
@@ -8,6 +8,8 @@ tests/test_shipping_notice_stp_acceptance.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingTask, User
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
@@ -15,7 +17,7 @@ from app.services.shipping_notice.constants import (
|
||||
PH_LOW_CONF,
|
||||
RS_PARSE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match
|
||||
from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_after_match, upload_to_freight
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
|
||||
from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for
|
||||
@@ -29,7 +31,7 @@ def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None:
|
||||
|
||||
|
||||
def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app) -> None:
|
||||
"""场景:Excel 已生成 → auto_progress 早停且禁止 upload_to_freight。"""
|
||||
"""场景:Excel 已生成 → auto_progress 早停(WAIT_MANUAL_UPLOAD)且禁止 upload_to_freight。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
@@ -49,6 +51,7 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app)
|
||||
assert result.get("checkpoint") == CP_EXPORT_READY
|
||||
assert "upload_to_freight" in (result.get("forbidden_next_tools") or [])
|
||||
assert result.get("stop_agent_turn") is True
|
||||
assert "登记凭据" in str(result.get("message") or "")
|
||||
|
||||
|
||||
def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
|
||||
@@ -113,8 +116,146 @@ def test_try_auto_chain_never_calls_upload_even_when_auto_upload_enabled(app, mo
|
||||
assert "upload_to_freight" in (result.get("forbidden_next_tools") or [])
|
||||
|
||||
|
||||
def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch) -> None:
|
||||
"""场景:manual_confirm 不再范围外硬拒绝;校验凭据路径可达(mock record_manual_upload)。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from types import SimpleNamespace
|
||||
|
||||
task = ShippingTask(
|
||||
task_no="SN-STP-MANUAL-CFM",
|
||||
process_status="waiting_upload",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/m.xlsx",
|
||||
export_file_name="m.xlsx",
|
||||
inventory_source_status="confirmed",
|
||||
inventory_source_code="SRC1",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
attempt = SimpleNamespace(id=9, artifact_id=3, operator_id=42)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.is_inventory_source_stable",
|
||||
lambda _t: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.customer_gate_tool_response",
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.field_conflict_gate_response",
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow._reservation_gate_response",
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow._task_disposition_gate_response",
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.record_manual_upload",
|
||||
lambda *a, **k: attempt,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit",
|
||||
lambda **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.workflow_ledger_service.find_item_by_current_task_no",
|
||||
lambda **k: None,
|
||||
)
|
||||
|
||||
rejected = upload_to_freight({"task_id": task.task_no, "mode": "auto"})
|
||||
assert rejected["status"] == "failed"
|
||||
assert "upload_to_freight" in (rejected.get("forbidden_next_tools") or [])
|
||||
|
||||
ok = upload_to_freight({
|
||||
"task_id": task.task_no,
|
||||
"mode": "manual_confirm",
|
||||
"operator_id": 42,
|
||||
"evidence_asset_no": "FA-1",
|
||||
"freight_ref_no": "R-1",
|
||||
"artifact_id": 3,
|
||||
})
|
||||
assert ok["status"] == "ok"
|
||||
assert ok.get("forbidden_next_tools") in (None, [])
|
||||
|
||||
|
||||
def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, monkeypatch) -> None:
|
||||
"""关键断言:绑定 WorkflowItem 关闭失败须向上抛出,不得吞异常后仍返回成功。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from types import SimpleNamespace
|
||||
|
||||
task = ShippingTask(
|
||||
task_no="SN-STP-CLOSE-FAIL",
|
||||
process_status="waiting_upload",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/m.xlsx",
|
||||
export_file_name="m.xlsx",
|
||||
inventory_source_status="confirmed",
|
||||
inventory_source_code="SRC1",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
|
||||
attempt = SimpleNamespace(id=11, artifact_id=3, operator_id=42)
|
||||
bound_item = SimpleNamespace(lifecycle_status="manual_upload_pending")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.is_inventory_source_stable",
|
||||
lambda _t: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.customer_gate_tool_response",
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.field_conflict_gate_response",
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow._reservation_gate_response",
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow._task_disposition_gate_response",
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_workflow.record_manual_upload",
|
||||
lambda *a, **k: attempt,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit",
|
||||
lambda **k: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.workflow_ledger_service.find_item_by_current_task_no",
|
||||
lambda **k: bound_item,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.workflow_ledger_service.close_workflow_item",
|
||||
lambda **k: (_ for _ in ()).throw(RuntimeError("close failed")),
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="close failed"):
|
||||
upload_to_freight({
|
||||
"task_id": task.task_no,
|
||||
"mode": "manual_confirm",
|
||||
"operator_id": 42,
|
||||
"evidence_asset_no": "FA-1",
|
||||
"freight_ref_no": "R-1",
|
||||
"artifact_id": 3,
|
||||
})
|
||||
|
||||
|
||||
def test_export_ready_ui_state_entry_is_task_workbench(app) -> None:
|
||||
"""场景:待人工上传待办深链入口为任务处理工作台。"""
|
||||
"""场景:Excel 待人工上传登记待办深链入口为任务处理工作台。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-STP-ENTRY",
|
||||
@@ -126,6 +267,9 @@ def test_export_ready_ui_state_entry_is_task_workbench(app) -> None:
|
||||
state = build_task_ui_state(task)
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
button_ids = [b.get("id") for b in (state.get("action_buttons") or [])]
|
||||
assert "mark_manual_uploaded" in button_ids
|
||||
assert "download_excel" in button_ids
|
||||
|
||||
|
||||
def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
@@ -153,6 +297,14 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
mine = ShippingTask(
|
||||
task_no="SN-STP-OWN",
|
||||
user_id=owner.id,
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
waiting_upload = ShippingTask(
|
||||
task_no="SN-STP-UPLOAD",
|
||||
user_id=owner.id,
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
export_file_path="/tmp/own.xlsx",
|
||||
@@ -166,7 +318,7 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
source_type="manual",
|
||||
)
|
||||
db.session.add_all([mine, other])
|
||||
db.session.add_all([mine, waiting_upload, other])
|
||||
db.session.commit()
|
||||
|
||||
pending = list_my_todos(owner.id, bucket="pending", page=1, page_size=50)
|
||||
@@ -174,10 +326,15 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
|
||||
assert own_item["can_handle"] is True
|
||||
assert own_item.get("todo_category")
|
||||
|
||||
upload_item = next(
|
||||
item for item in pending["items"] if item["task_no"] == "SN-STP-UPLOAD"
|
||||
)
|
||||
assert upload_item.get("todo_category") == "manual_upload"
|
||||
|
||||
admin_page = list_my_todos(admin.id, bucket="pending", page=1, page_size=50, is_admin=True)
|
||||
foreign = next(item for item in admin_page["items"] if item["task_no"] == "SN-STP-OWN")
|
||||
assert foreign["can_handle"] is False
|
||||
|
||||
counts = count_my_todos(owner.id)
|
||||
assert counts["total_pending_badge"] == counts["pending"]
|
||||
assert counts["pending"] >= 1
|
||||
assert counts["pending"] >= 2
|
||||
@@ -45,6 +45,7 @@ def test_build_task_ui_state_summary_has_required_keys(app) -> None:
|
||||
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
|
||||
assert state["checkpoint"] == CP_PARSE_REVIEW
|
||||
assert state["checkpoint_kind"] == "must_human"
|
||||
assert "stp_facts" not in state["summary"]
|
||||
|
||||
|
||||
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
@@ -62,7 +63,7 @@ def test_entry_surface_parse_review_is_review_workbench(app) -> None:
|
||||
|
||||
|
||||
def test_entry_surface_export_ready_is_task_workbench(app) -> None:
|
||||
"""Excel 待人工上传应进入任务处理工作台。"""
|
||||
"""Excel 待人工上传登记应进入任务处理工作台(下载 + 登记)。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-UI-EXPORT",
|
||||
@@ -75,3 +76,98 @@ def test_entry_surface_export_ready_is_task_workbench(app) -> None:
|
||||
assert state["checkpoint"] == CP_EXPORT_READY
|
||||
assert state["checkpoint_kind"] == "wait_manual_upload"
|
||||
assert state["summary"]["entry_surface"] == "task_workbench"
|
||||
assert state["summary"].get("pause_reason_code") == "wait_manual_upload"
|
||||
assert "登记凭据" in str(state["summary"].get("pause_reason") or "")
|
||||
button_ids = [b.get("id") for b in (state.get("action_buttons") or [])]
|
||||
assert "download_excel" in button_ids
|
||||
assert "mark_manual_uploaded" in button_ids
|
||||
|
||||
|
||||
def test_stp_facts_candidates_frozen_projected(app) -> None:
|
||||
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-UI-STP-FROZEN",
|
||||
process_status="waiting_inventory",
|
||||
source_type="manual",
|
||||
inventory_source_status="candidates_frozen",
|
||||
inventory_source_method="stp_build_freeze",
|
||||
step_payload_json={
|
||||
"line_inventory_candidates": {
|
||||
"source_codes": ["DBS_DUB", "DBS_RTM"],
|
||||
"frozen_at": "build",
|
||||
},
|
||||
},
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
facts = state["summary"]["stp_facts"]
|
||||
assert facts["inventory_source_status"] == "candidates_frozen"
|
||||
assert facts["frozen_candidate_codes"] == ["DBS_DUB", "DBS_RTM"]
|
||||
assert facts["multi_source_excel_block"] is False
|
||||
|
||||
|
||||
def test_stp_facts_projects_line_resolutions(app) -> None:
|
||||
"""stp_facts 须包含逐行 Reservation/料号/实际库存源/文件证据。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-UI-STP-LINES",
|
||||
process_status="matched",
|
||||
source_type="manual",
|
||||
match_status="fulfillable",
|
||||
inventory_source_status="resolved",
|
||||
inventory_source_code="DBS_DUB",
|
||||
inventory_source_method="stp_line_match",
|
||||
step_payload_json={
|
||||
"line_inventory_resolutions": [
|
||||
{
|
||||
"line_index": 0,
|
||||
"disposition": "ok",
|
||||
"effective_reservation_id": "3000092917",
|
||||
"part_number": "PN-1",
|
||||
"resolved_inventory_source_code": "DBS_DUB",
|
||||
"inventory_file_no": "INV-1",
|
||||
"inventory_row_ref": {
|
||||
"reservation_id": "3000092917",
|
||||
"part_number": "PN-1",
|
||||
"source_code": "DBS_DUB",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
rows = state["summary"]["stp_facts"]["line_resolutions"]
|
||||
assert rows[0]["effective_reservation_id"] == "3000092917"
|
||||
assert rows[0]["part_number"] == "PN-1"
|
||||
assert rows[0]["resolved_inventory_source_code"] == "DBS_DUB"
|
||||
assert rows[0]["inventory_file_no"] == "INV-1"
|
||||
|
||||
|
||||
def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
|
||||
"""历史 multi_source_excel_block 载荷仍覆盖 pause_reason(兼容旧任务)。"""
|
||||
from app.services.shipping_notice.constants import RS_SHORTAGE_REVIEW
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingTask(
|
||||
task_no="SN-UI-STP-MULTI",
|
||||
process_status="matched",
|
||||
review_status=RS_SHORTAGE_REVIEW,
|
||||
pending_human_reason="shortage",
|
||||
source_type="manual",
|
||||
match_status="fulfillable",
|
||||
inventory_source_status="candidates_frozen",
|
||||
inventory_source_method="stp_line_match",
|
||||
step_payload_json={
|
||||
"multi_source_excel_block": True,
|
||||
"resolved_ok_source_codes": ["DBS_DUB", "DBS_RTM"],
|
||||
"line_inventory_resolutions": [
|
||||
{"line_index": 0, "disposition": "ok", "resolved_inventory_source_code": "DBS_DUB"},
|
||||
{"line_index": 1, "disposition": "ok", "resolved_inventory_source_code": "DBS_RTM"},
|
||||
],
|
||||
},
|
||||
)
|
||||
state = build_task_ui_state(task)
|
||||
summary = state["summary"]
|
||||
assert summary["pause_reason_code"] == "multi_source_excel_block"
|
||||
assert summary["stp_facts"]["multi_source_excel_block"] is True
|
||||
assert summary["entry_surface"] == "task_workbench"
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
backend/tests/test_shipping_notice_workflow_migration.py
|
||||
|
||||
用途:验收 Workflow 四表 ORM 可查询,并确认旧 ShippingSessionPdfWorkItem 已从 models 移除。
|
||||
依赖:app fixture(db.create_all)、ShippingNoticeWorkflow* ORM、迁移 9d2f4a6b8c0e。
|
||||
逻辑:create_all 后四表可空查;禁止从 app.models 导入旧会话工作项;
|
||||
迁移脚本须创建 Workflow 表并 drop 旧表,且不做历史数据迁移/回填。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import (
|
||||
ShippingNoticeWorkflow,
|
||||
ShippingNoticeWorkflowEvent,
|
||||
ShippingNoticeWorkflowItem,
|
||||
ShippingNoticeWorkflowItemVersion,
|
||||
)
|
||||
|
||||
|
||||
def test_workflow_orm_tables_are_queryable_after_create_all(app):
|
||||
"""app fixture create_all 后 Workflow / Item / Version / Event 均可经 ORM 查询。"""
|
||||
with app.app_context():
|
||||
# 关键断言:四表已建且可空结果查询,证明 ORM 与内存库表结构对齐。
|
||||
assert ShippingNoticeWorkflow.query.count() == 0
|
||||
assert ShippingNoticeWorkflowItem.query.count() == 0
|
||||
assert ShippingNoticeWorkflowItemVersion.query.count() == 0
|
||||
assert ShippingNoticeWorkflowEvent.query.count() == 0
|
||||
|
||||
|
||||
def test_shipping_session_pdf_work_item_is_not_importable_from_app_models():
|
||||
"""旧 ShippingSessionPdfWorkItem 不得再从 app.models 导出。"""
|
||||
import app.models as models
|
||||
|
||||
# 关键断言:迁移后旧会话工作项模型已删除,属性访问或显式 import 必须失败。
|
||||
assert not hasattr(models, 'ShippingSessionPdfWorkItem')
|
||||
with pytest.raises((ImportError, AttributeError)):
|
||||
from app.models import ShippingSessionPdfWorkItem # noqa: F401
|
||||
|
||||
|
||||
def test_migration_9d2f4a6b8c0e_drops_session_work_items_without_history_migration():
|
||||
"""迁移 9d2f4a6b8c0e 须建 Workflow 表并 drop 旧表,且不迁移/回填历史会话工作项。"""
|
||||
revision = (
|
||||
Path(__file__).resolve().parents[1]
|
||||
/ 'migrations'
|
||||
/ 'versions'
|
||||
/ '9d2f4a6b8c0e_replace_session_work_items_with_workflows.py'
|
||||
)
|
||||
# 关键断言:替换会话工作项的迁移文件存在,且明确不做历史迁移。
|
||||
assert revision.is_file()
|
||||
text = revision.read_text(encoding='utf-8')
|
||||
assert "revision = '9d2f4a6b8c0e'" in text
|
||||
assert "drop_table('shipping_session_pdf_work_items')" in text
|
||||
assert 'shipping_notice_workflows' in text
|
||||
assert '_migrate_session_work_items_to_workflows' not in text
|
||||
assert '_restore_session_work_items_from_workflows' not in text
|
||||
assert '不迁' in text or '不做历史' in text or '不迁移' in text
|
||||
@@ -0,0 +1,258 @@
|
||||
"""
|
||||
tests/test_shipping_order_build_eligibility.py
|
||||
|
||||
用途:验证 STP 阶段 2 建单前资格服务——库存源候选、有效 Reservation 与人工覆盖门禁。
|
||||
依赖:order_build_eligibility_service、inventory_routing_engine、order_schema field_rules。
|
||||
逻辑:复用路由测试的字段/规则构造模式,覆盖多候选可建单、零候选阻断、强制人工复核、
|
||||
Header 回退 Reservation 与人工候选原因校验。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition
|
||||
from app.services.shipping_notice.order_build_eligibility_service import (
|
||||
apply_manual_inventory_candidates,
|
||||
assess_order_build_eligibility,
|
||||
project_line_inventory_candidates,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
|
||||
def _field_config(field_id: str, *, name: str, value_type: str = 'string') -> dict:
|
||||
"""构造最小可发布行字段配置;路由只依赖其稳定 field_id。"""
|
||||
return {
|
||||
'field_id': field_id, 'display_name': name, 'required': False, 'aliases': [],
|
||||
'normalizer_key': 'decimal' if value_type == 'decimal' else 'uppercase_trim',
|
||||
'comparator_key': 'decimal' if value_type == 'decimal' else 'normalized_text',
|
||||
'evidence_policy': {
|
||||
'required': True, 'source_precedence': ['attachment_table'],
|
||||
'conflict_policy': 'block', 'allow_single_source': True,
|
||||
},
|
||||
'relation_role': None,
|
||||
}
|
||||
|
||||
|
||||
def _published_line_fields() -> dict[str, str]:
|
||||
"""创建并发布行级路由测试所需字段契约。"""
|
||||
order_schema_service.initialize_schema({'display_name': '建单资格字段'}, actor_id=None)
|
||||
reservation = order_schema_service.save_field(
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
part_number = order_schema_service.save_field(
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
qty = order_schema_service.save_field(
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None,
|
||||
)
|
||||
draft = order_schema_service.create_draft({}, actor_id=None)
|
||||
reservation_config = _field_config(reservation['id'], name='预定单号')
|
||||
reservation_config['business_purpose'] = 'reservation_id'
|
||||
part_number_config = _field_config(part_number['id'], name='料号')
|
||||
part_number_config['business_purpose'] = 'part_number'
|
||||
qty_config = _field_config(qty['id'], name='数量', value_type='decimal')
|
||||
qty_config['business_purpose'] = 'quantity'
|
||||
saved = order_schema_service.save_draft(draft['id'], {
|
||||
'fields': [reservation_config, part_number_config, qty_config],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
}, actor_id=None)
|
||||
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
return {
|
||||
'reservation_id': reservation['id'],
|
||||
'part_number': part_number['id'],
|
||||
'qty': qty['id'],
|
||||
}
|
||||
|
||||
|
||||
def _fields_with_header_reservation(field_ids: dict[str, str]) -> dict[str, dict]:
|
||||
"""在行级契约上附加 Header Reservation 字段(无 business_purpose)。"""
|
||||
fields = _schema_fields_map(field_ids)
|
||||
header_field_id = 'header-reservation-test'
|
||||
fields[header_field_id] = {
|
||||
'field_id': header_field_id,
|
||||
'field_code': 'reservation_id',
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
}
|
||||
return fields, header_field_id
|
||||
|
||||
|
||||
def _schema_fields_map(field_ids: dict[str, str]) -> dict[str, dict]:
|
||||
"""将已发布 field_id 转为 assess_order_build_eligibility 所需的 fields 映射。"""
|
||||
contract = order_schema_service.get_published_contract()
|
||||
return {
|
||||
str(item['field_id']): item
|
||||
for item in contract['fields']
|
||||
if str(item['field_id']) in set(field_ids.values())
|
||||
}
|
||||
|
||||
|
||||
def _rule(*, code: str, priority: int, sources: list[str], conditions: list[tuple[str, str, object]], action_type: str = 'add_source_candidates'):
|
||||
"""构造已发布的行级订单字段规则。"""
|
||||
return ShippingInventoryRoutingRule(
|
||||
rule_code=code, rule_name=code, scope='line', priority=priority, match_mode='all',
|
||||
status='published', action_type=action_type, action_payload_json={'source_codes': sources}, version=1,
|
||||
conditions=[
|
||||
ShippingInventoryRoutingRuleCondition(
|
||||
condition_group=1, source_kind='order_field', order_field_id=field_id,
|
||||
operator=operator, expected_value_json=expected, sequence=index,
|
||||
)
|
||||
for index, (field_id, operator, expected) in enumerate(conditions, start=1)
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_multi_candidate_routing_allows_build(app):
|
||||
"""两位候选库存源(ambiguous)仍满足建单库存门禁 can_build=True。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
db.session.add(_rule(
|
||||
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
|
||||
conditions=[(field_ids['reservation_id'], 'prefix', '1')],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = assess_order_build_eligibility(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
lines=[{
|
||||
'part_number': 'PN-001', 'qty': '2', 'reservation_id': '1000123456',
|
||||
}],
|
||||
line_metas=[{'line_key': 'line-1'}],
|
||||
)
|
||||
|
||||
# 关键断言:多候选 status=ambiguous 但不阻断建单。
|
||||
assert result['can_build'] is True
|
||||
assert result['line_projections'][0]['routing_status'] == 'ambiguous'
|
||||
assert set(result['line_projections'][0]['candidate_inventory_source_codes']) == {'DBS_DUB', 'DBS_RTM'}
|
||||
|
||||
|
||||
def test_zero_candidates_blocks_build(app):
|
||||
"""无路由命中时 can_build=False 且 block_reason=no_inventory_source_candidates。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
db.session.commit()
|
||||
|
||||
result = assess_order_build_eligibility(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
lines=[{
|
||||
'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917',
|
||||
}],
|
||||
line_metas=[{'line_key': 'line-1'}],
|
||||
)
|
||||
|
||||
# 关键断言:零候选阻断建单并给出稳定原因码。
|
||||
assert result['can_build'] is False
|
||||
assert result['line_projections'][0]['block_reason'] == 'no_inventory_source_candidates'
|
||||
assert any(item['code'] == 'no_inventory_source_candidates' for item in result['issues'])
|
||||
|
||||
|
||||
def test_require_manual_review_action_blocks_build(app):
|
||||
"""require_manual_review 规则将 status=conflicted 且 can_build=False。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
db.session.add(_rule(
|
||||
code='FORCE_REVIEW', priority=100, sources=['DBS_DUB'],
|
||||
conditions=[(field_ids['reservation_id'], 'prefix', '9')],
|
||||
action_type='require_manual_review',
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = assess_order_build_eligibility(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
lines=[{
|
||||
'part_number': 'PN-001', 'qty': '2', 'reservation_id': '9000123456',
|
||||
}],
|
||||
line_metas=[{'line_key': 'line-1'}],
|
||||
)
|
||||
|
||||
# 关键断言:强制人工复核阻断建单。
|
||||
assert result['can_build'] is False
|
||||
assert result['line_projections'][0]['routing_status'] == 'conflicted'
|
||||
assert result['line_projections'][0]['block_reason'] == 'require_manual_review'
|
||||
|
||||
|
||||
def test_header_only_reservation_fills_effective_reservation(app):
|
||||
"""行无 Reservation 时 Header 回退填充 effective_reservation_id,流程门禁通过。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields, header_field_id = _fields_with_header_reservation(field_ids)
|
||||
# 任务级规则读取 Header Reservation,行级无值时回退 task 评估。
|
||||
db.session.add(ShippingInventoryRoutingRule(
|
||||
rule_code='HEADER_RSV', rule_name='HEADER_RSV', scope='task', priority=50, match_mode='all',
|
||||
status='published', action_type='add_source_candidates',
|
||||
action_payload_json={'source_codes': ['DSV360_AWSDU']}, version=1,
|
||||
conditions=[ShippingInventoryRoutingRuleCondition(
|
||||
condition_group=1, source_kind='order_field', order_field_id=header_field_id,
|
||||
operator='is_not_empty', expected_value_json=None, sequence=1,
|
||||
)],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
result = assess_order_build_eligibility(
|
||||
fields=fields,
|
||||
header_by_code={'reservation_id': '3000092917'},
|
||||
lines=[{'part_number': 'PN-001', 'qty': '2'}],
|
||||
line_metas=[{'line_key': 'line-1'}],
|
||||
)
|
||||
|
||||
# 关键断言:Header 回退有效 Reservation,不因行级缺失阻断。
|
||||
assert result['line_projections'][0]['effective_reservation_id'] == '3000092917'
|
||||
assert not any(item['code'] == 'effective_reservation_missing' for item in result['issues'])
|
||||
assert result['can_build'] is True
|
||||
|
||||
|
||||
def test_manual_selection_with_reason_and_enabled_source_allows_build(app):
|
||||
"""人工选择已启用库存源并填写原因时 can_build=True。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
line_meta: dict = {'line_key': 'line-1'}
|
||||
apply_manual_inventory_candidates(
|
||||
line_meta=line_meta,
|
||||
source_codes=['DSV360_AWSDU'],
|
||||
reason='客户邮件指定 Dublin 库存池',
|
||||
)
|
||||
|
||||
routing = project_line_inventory_candidates(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'},
|
||||
line_meta=line_meta,
|
||||
)
|
||||
|
||||
# 关键断言:人工覆盖优先于规则零候选。
|
||||
assert routing['selection_mode'] == 'manual'
|
||||
assert routing['can_build'] is True
|
||||
assert routing['candidate_inventory_source_codes'] == ['DSV360_AWSDU']
|
||||
|
||||
|
||||
def test_manual_selection_without_reason_is_blocked(app):
|
||||
"""人工选择未填写原因时 can_build=False 且 block_reason=manual_inventory_source_reason_required。"""
|
||||
with app.app_context():
|
||||
field_ids = _published_line_fields()
|
||||
fields = _schema_fields_map(field_ids)
|
||||
line_meta = {
|
||||
'line_key': 'line-1',
|
||||
'inventory_routing': {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': ['DSV360_AWSDU'],
|
||||
'manual_reason': '',
|
||||
},
|
||||
}
|
||||
|
||||
routing = project_line_inventory_candidates(
|
||||
fields=fields,
|
||||
header_by_code={},
|
||||
line_by_code={'part_number': 'PN-001', 'qty': '2', 'reservation_id': '3000092917'},
|
||||
line_meta=line_meta,
|
||||
)
|
||||
|
||||
# 关键断言:缺原因不得放行建单。
|
||||
assert routing['can_build'] is False
|
||||
assert routing['block_reason'] == 'manual_inventory_source_reason_required'
|
||||
@@ -35,9 +35,9 @@ def _field(code: str, *, value_type: str = 'string', required: bool = False) ->
|
||||
|
||||
|
||||
def _contract():
|
||||
"""创建覆盖行号、三料号和数量的冻结 Schema 契约。"""
|
||||
"""创建覆盖客户 PO 行号、三料号和数量的冻结 Schema 契约。"""
|
||||
return compile_table_header_contract({'fields': [
|
||||
_field('line_no'), _field('customer_part_number'),
|
||||
_field('customer_po_line_no'), _field('customer_part_number'),
|
||||
_field('part_number', required=True), _field('aws_part_number'),
|
||||
_field('qty', value_type='decimal', required=True),
|
||||
]})
|
||||
@@ -63,7 +63,7 @@ def test_template_profile_overrides_global_part_number_semantics_without_collisi
|
||||
'<tr><td>1</td><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>3</td></tr></table>'
|
||||
)
|
||||
profile = _profile(html, [
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['line_no']),
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['customer_po_line_no']),
|
||||
OrderProfileColumnRule(column_index=1, extractor_key='direct', target_field_codes=['customer_part_number']),
|
||||
OrderProfileColumnRule(column_index=2, extractor_key='direct', target_field_codes=['part_number']),
|
||||
OrderProfileColumnRule(column_index=3, extractor_key='direct', target_field_codes=['qty']),
|
||||
@@ -76,7 +76,7 @@ def test_template_profile_overrides_global_part_number_semantics_without_collisi
|
||||
assert result.matched is True
|
||||
assert result.rows[0].status == 'parsed'
|
||||
assert result.rows[0].fields == {
|
||||
'line_no': '1', 'customer_part_number': 'CUSTOMER-1',
|
||||
'customer_po_line_no': '1', 'customer_part_number': 'CUSTOMER-1',
|
||||
'part_number': 'INTERNAL-1', 'qty': 3.0,
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ def test_template_profile_extracts_registered_temp_and_internal_parts_from_compo
|
||||
'<tr><td>10</td><td>AMTEMP-S000001 supplier D4-A08AR12000001 enclosure</td><td>2</td></tr></table>'
|
||||
)
|
||||
profile = _profile(html, [
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['line_no']),
|
||||
OrderProfileColumnRule(column_index=0, extractor_key='direct', target_field_codes=['customer_po_line_no']),
|
||||
OrderProfileColumnRule(
|
||||
column_index=1,
|
||||
extractor_key='temp_internal_parts',
|
||||
@@ -197,7 +197,7 @@ def test_coordinate_profile_v2_accepts_independent_header_and_multi_physical_lin
|
||||
"""坐标模板必须能表达多条表头、两条不同布局的物理行和独立字段区域。"""
|
||||
definition = {
|
||||
'profile_code': 'COORDINATE_A', 'version': 1,
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'text': 'PURCHASE ORDER'}]},
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'label': 'DOCUMENT:', 'value': 'PURCHASE ORDER'}]},
|
||||
'table_regions': [{
|
||||
'region_id': 'main_lines', 'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .8},
|
||||
'header_layouts': [
|
||||
@@ -206,7 +206,7 @@ def test_coordinate_profile_v2_accepts_independent_header_and_multi_physical_lin
|
||||
],
|
||||
'line_layouts': [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .4},
|
||||
'field_regions': [{'field_id': 'line-id', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
'field_regions': [{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
{'layout_id': 'detail', 'row_offset': 1, 'role': 'continuation', 'region': {'x0': 0, 'y0': .4, 'x1': 1, 'y1': .6},
|
||||
'field_regions': [{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .5, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
], 'continuation_rule': {'allow_cross_page': False}, 'termination_rules': [], 'exclusion_regions': [],
|
||||
@@ -232,7 +232,7 @@ def test_coordinate_profile_v2_rejects_ambiguous_or_invalid_regions(mutation):
|
||||
value = {
|
||||
'profile_code': 'COORDINATE_B', 'version': 1, 'document_match': {},
|
||||
'table_regions': [{'region_id': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .5}, 'field_regions': [{'field_id': 'line', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .5}, 'field_regions': [{'field_id': 'line', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
{'layout_id': 'detail', 'row_offset': 1, 'role': 'continuation', 'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1}, 'field_regions': [{'field_id': 'qty', 'field_code': 'qty', 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
]}],
|
||||
}
|
||||
@@ -246,12 +246,12 @@ def test_coordinate_profile_v2_requires_declared_document_anchor_for_cross_page_
|
||||
"""跨页只能绑定已有静态文档锚点,不能以相邻页面或列数相近作为合并理由。"""
|
||||
profile = {
|
||||
'profile_code': 'CROSS_PAGE', 'version': 1,
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'continued', 'text': 'CONTINUED'}]},
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'continued', 'label': 'PAGE:', 'value': 'CONTINUED'}]},
|
||||
'table_regions': [{'region_id': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'continuation_rule': {'allow_cross_page': True, 'required_anchor_ids': ['continued']},
|
||||
'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'field_regions': [
|
||||
{'field_id': 'line', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'line', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
]}],
|
||||
}],
|
||||
}
|
||||
@@ -260,3 +260,20 @@ def test_coordinate_profile_v2_requires_declared_document_anchor_for_cross_page_
|
||||
profile['table_regions'][0]['continuation_rule']['required_anchor_ids'] = []
|
||||
with pytest.raises(ValidationError, match='cross-page continuation requires anchor evidence'):
|
||||
OrderCoordinateProfileV2.model_validate(profile)
|
||||
|
||||
|
||||
|
||||
def test_coordinate_profile_v2_allows_internal_line_no_binding():
|
||||
"""关键断言:坐标模板可绑定内部项次 line_no 作为明细字段与起行锚点。"""
|
||||
definition = {
|
||||
'profile_code': 'COORDINATE_INTERNAL_LINE', 'version': 1, 'document_match': {},
|
||||
'table_regions': [{'region_id': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'line_start_field_code': 'line_no',
|
||||
'line_layouts': [
|
||||
{'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{'field_id': 'line', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}]},
|
||||
]}],
|
||||
}
|
||||
profile = OrderCoordinateProfileV2.model_validate(definition)
|
||||
assert profile.table_regions[0].line_layouts[0].field_regions[0].field_code == 'line_no'
|
||||
assert profile.table_regions[0].line_start_field_code == 'line_no'
|
||||
@@ -19,6 +19,7 @@ from app import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingNoticeDocument,
|
||||
@@ -48,6 +49,13 @@ def _schema_version() -> ShippingOrderSchemaVersion:
|
||||
checksum='a' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'line-field', 'field_code': 'customer_po_line_no',
|
||||
'scope': 'line', 'value_type': 'string', 'enabled': True,
|
||||
'display_name': 'Customer PO Line',
|
||||
'normalizer_key': 'trim', 'validator_keys': [],
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'customer-field', 'field_code': 'customer_part_number',
|
||||
'scope': 'line', 'value_type': 'string', 'enabled': True,
|
||||
@@ -95,11 +103,20 @@ def _coordinate_definition() -> dict:
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{
|
||||
'field_id': 'forged', 'field_code': 'part_number',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .5, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}],
|
||||
'field_regions': [
|
||||
{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no',
|
||||
'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'forged', 'field_code': 'part_number',
|
||||
'scope': 'line',
|
||||
'region': {'x0': .2, 'y0': 0, 'x1': .7, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
],
|
||||
'continuation_conditions': [], 'required_fields': ['part_number'], 'allowed_empty_fields': [],
|
||||
}],
|
||||
}],
|
||||
@@ -185,6 +202,66 @@ def _bind_ready_profile_sample(
|
||||
).one()
|
||||
|
||||
|
||||
def test_template_sample_status_requires_ready_coordinate_layout(app):
|
||||
"""Intake 已解析但坐标布局失败时,向导必须停止轮询并显示模板不可用。"""
|
||||
with app.app_context():
|
||||
user = User(username='layout-status-admin', email='layout-status-admin@example.com', role='admin')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-LAYOUT-STATUS', owner_user_id=user.id, original_filename='layout.pdf',
|
||||
storage_provider='test', storage_bucket='test', storage_key='layout.pdf',
|
||||
content_hash='l' * 64, file_size=1, mime_type='application/pdf',
|
||||
upload_status='ready', lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-LAYOUT-STATUS', asset_id=asset.id, user_id=user.id,
|
||||
purpose='order_document_profile_sample', parse_status='parsed', parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='layout.pdf',
|
||||
filename='layout.pdf', content_hash='l' * 64, classification='supporting', parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'failed',
|
||||
'issues': ['mineru_cell_coordinates_missing'], 'tables': [],
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id)
|
||||
|
||||
assert status == {
|
||||
'intake_no': 'SNI-LAYOUT-STATUS', 'parse_status': 'failed', 'document_count': 1,
|
||||
'error_code': 'mineru_cell_coordinates_missing',
|
||||
}
|
||||
|
||||
|
||||
def test_draft_unbound_order_field_layout_does_not_require_schema_scope(app):
|
||||
"""自动标记的未绑定订单字段只保留布局,保存时不应被 scope 契约误伤。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
definition = _coordinate_definition()
|
||||
definition['draft_unbound_order_field_layouts'] = [{
|
||||
'layout_id': 'unbound_vendor_name', 'label': 'VENDOR NAME',
|
||||
'page_scope': 'exact_page', 'page_no': 1, 'anchor': None,
|
||||
'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .3, 'y1': .2},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'UNBOUND_ORDER_FIELD', 'display_name': 'Unbound order field',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
assert saved['definition']['draft_unbound_order_field_layouts'][0]['layout_id'] == 'unbound_vendor_name'
|
||||
|
||||
|
||||
def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_field_id(app):
|
||||
"""关键断言:浏览器伪造 field_id 无效,Schema 未授权的坐标来源必须阻断 Profile 保存。"""
|
||||
with app.app_context():
|
||||
@@ -407,14 +484,17 @@ def test_composite_coordinate_binding_freezes_all_registered_output_fields(app):
|
||||
'enabled': True, 'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
field.update({'field_code': 'qty', 'extractor_key': 'quantity_uom'})
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'COMPOSITE_QTY', 'display_name': 'Composite qty',
|
||||
'schema_version_id': schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['target_fields']
|
||||
assert targets == [{'field_id': 'qty-field', 'field_code': 'qty'}, {'field_id': 'uom-field', 'field_code': 'uom'}]
|
||||
assert targets == [
|
||||
{'field_id': 'qty-field', 'field_code': 'qty', 'scope': 'line'},
|
||||
{'field_id': 'uom-field', 'field_code': 'uom', 'scope': 'line'},
|
||||
]
|
||||
|
||||
schema.definition_json['fields'].pop()
|
||||
with pytest.raises(Exception) as caught:
|
||||
@@ -425,6 +505,8 @@ def test_composite_coordinate_binding_freezes_all_registered_output_fields(app):
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
|
||||
|
||||
|
||||
|
||||
def test_amount_currency_binding_freezes_header_target_and_checks_each_output_source(app):
|
||||
"""金额复合解析可输出 Header 币种,但 Header 字段也必须显式允许坐标来源。"""
|
||||
with app.app_context():
|
||||
@@ -442,7 +524,7 @@ def test_amount_currency_binding_freezes_header_target_and_checks_each_output_so
|
||||
},
|
||||
])
|
||||
definition = _coordinate_definition()
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
field.update({'field_code': 'line_amount_before_tax', 'extractor_key': 'amount_currency'})
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'COMPOSITE_AMOUNT', 'display_name': 'Composite amount',
|
||||
@@ -450,8 +532,8 @@ def test_amount_currency_binding_freezes_header_target_and_checks_each_output_so
|
||||
}, actor_id=None)
|
||||
targets = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['target_fields']
|
||||
assert targets == [
|
||||
{'field_id': 'currency-field', 'field_code': 'currency'},
|
||||
{'field_id': 'amount-field', 'field_code': 'line_amount_before_tax'},
|
||||
{'field_id': 'currency-field', 'field_code': 'currency', 'scope': 'line'},
|
||||
{'field_id': 'amount-field', 'field_code': 'line_amount_before_tax', 'scope': 'line'},
|
||||
]
|
||||
|
||||
schema.definition_json['fields'][-1]['allowed_sources'] = []
|
||||
@@ -473,7 +555,7 @@ def test_coordinate_binding_allows_enabled_header_value_from_a_detail_physical_r
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][1]
|
||||
field['field_code'] = 'incoterm'
|
||||
saved = service.save_draft({
|
||||
'profile_code': 'HEADER_FROM_LINE', 'display_name': 'Header from detail line',
|
||||
@@ -481,7 +563,7 @@ def test_coordinate_binding_allows_enabled_header_value_from_a_detail_physical_r
|
||||
}, actor_id=None)
|
||||
bound = saved['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
assert bound['field_id'] == 'incoterm-field'
|
||||
assert bound['target_fields'] == [{'field_id': 'incoterm-field', 'field_code': 'incoterm'}]
|
||||
assert bound['target_fields'] == [{'field_id': 'incoterm-field', 'field_code': 'incoterm', 'scope': 'header'}]
|
||||
|
||||
|
||||
def test_profile_samples_are_governed_and_audited(app, monkeypatch):
|
||||
@@ -876,6 +958,11 @@ def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_st
|
||||
field = migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
assert field['field_id'] == 'replacement-field'
|
||||
assert field['field_code'] == 'supplier_part_number'
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=migrated['id'], revision_no=1,
|
||||
).one()
|
||||
assert revision.definition_snapshot_json == migrated['definition']
|
||||
assert revision.result_lock_version == migrated['lock_version']
|
||||
|
||||
|
||||
def test_schema_migration_preserves_unbound_order_field_region_and_blocks_publish(app, monkeypatch):
|
||||
@@ -937,12 +1024,63 @@ def test_schema_migration_preserves_unbound_order_field_region_and_blocks_publis
|
||||
assert service.payload(model)['migration_status'] == 'needs_revalidation'
|
||||
|
||||
|
||||
def test_schema_migration_allows_same_field_code_in_header_and_line_scopes(app, monkeypatch):
|
||||
"""同编码的单头/明细字段按 scope 独立绑定,迁移不得把二者误判为重复 Schema 字段。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
source_schema = _schema_version()
|
||||
fields = list(source_schema.definition_json['fields']) + [
|
||||
{
|
||||
'field_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim', 'validator_keys': [],
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]
|
||||
source_schema.definition_json = {'fields': fields}
|
||||
definition = _coordinate_definition()
|
||||
definition['table_regions'][0]['line_layouts'][0]['field_regions'].append({
|
||||
'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'region': {'x0': .7, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'reservation_header', 'field_id': 'header-reservation', 'field_code': 'reservation_id',
|
||||
'scope': 'header',
|
||||
'anchor': None, 'fallback_value_region': {'x0': 0, 'y0': 0, 'x1': .2, 'y1': .1},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
db.session.commit()
|
||||
draft = service.save_draft({**_data(source_schema.id), 'definition': definition}, actor_id=None)
|
||||
_bind_ready_profile_sample(draft['id'])
|
||||
published = service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
|
||||
source_schema.status = 'retired'
|
||||
target_schema = ShippingOrderSchemaVersion(
|
||||
schema_id=source_schema.schema_id, version=2, status='published', checksum='e' * 64,
|
||||
published_at=datetime.utcnow(), definition_json={'fields': fields},
|
||||
)
|
||||
db.session.add(target_schema)
|
||||
db.session.commit()
|
||||
|
||||
migrated = service.create_schema_migration_draft(
|
||||
published['id'], target_schema_version_id=target_schema.id, resolutions={}, actor_id=None,
|
||||
)
|
||||
|
||||
assert migrated['definition']['order_field_layouts'][0]['scope'] == 'header'
|
||||
assert migrated['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][-1]['scope'] == 'line'
|
||||
|
||||
|
||||
def test_profile_rejects_unknown_field_and_stale_lock(app):
|
||||
"""Profile 不得引用未绑定 Schema 字段,草稿并发更新不得后写覆盖。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
invalid = _data(schema.id)
|
||||
invalid['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['field_code'] = 'unknown_field'
|
||||
invalid['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][1]['field_code'] = 'unknown_field'
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.save_draft(invalid, actor_id=None)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
|
||||
@@ -959,7 +1097,7 @@ def test_profile_rejects_unknown_field_and_stale_lock(app):
|
||||
duplicate['definition']['table_regions'][0]['line_layouts'].append({
|
||||
'layout_id': 'detail', 'row_offset': 1, 'role': 'continuation',
|
||||
'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{'field_id': 'also-part', 'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}],
|
||||
'field_regions': [{'field_id': 'also-part', 'field_code': 'part_number', 'scope': 'line', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}],
|
||||
'continuation_conditions': [], 'required_fields': [], 'allowed_empty_fields': [],
|
||||
})
|
||||
with pytest.raises(Exception) as caught:
|
||||
@@ -1319,15 +1457,14 @@ def test_profile_region_preview_uses_the_current_v2_region_definition(app, monke
|
||||
"""关键断言:拖动后的 v2 区域必须驱动局部预览,不能回退为旧固定列边界。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'].append({
|
||||
'field_id': 'line-field', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
profile = SimpleNamespace(profile_code='PREVIEW_REGION', version=1, schema_version=schema)
|
||||
document = SimpleNamespace(id=301)
|
||||
definition = _coordinate_definition()
|
||||
field = definition['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
field.update({'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}})
|
||||
definition['table_regions'][0]['line_layouts'][0]['field_regions'] = [{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1},
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}]
|
||||
layout = {
|
||||
'tables': [{'table_id': 'current-v2', 'page_no': 1}],
|
||||
'coordinate_evidence': {
|
||||
@@ -1346,7 +1483,7 @@ def test_profile_region_preview_uses_the_current_v2_region_definition(app, monke
|
||||
)
|
||||
|
||||
# The v2 field region contains the line number and produces a logical row.
|
||||
assert preview['rows'] == [['line_no'], ['10']]
|
||||
assert preview['rows'] == [['customer_po_line_no'], ['10']]
|
||||
assert preview['source_row_indices'] == [[], [0]]
|
||||
|
||||
|
||||
@@ -1354,15 +1491,11 @@ def test_profile_region_preview_uses_schema_field_order(app, monkeypatch):
|
||||
"""局部候选字段必须按绑定 Schema 顺序返回,不受字段标注先后影响。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'].append({
|
||||
'field_id': 'line-field', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
fields = definition['table_regions'][0]['line_layouts'][0]['field_regions']
|
||||
fields[:] = [
|
||||
{**fields[0], 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
{**fields[0], 'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}},
|
||||
{**fields[0], 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
|
||||
]
|
||||
profile = SimpleNamespace(profile_code='ORDERED_PREVIEW', version=1, schema_version=schema)
|
||||
document = SimpleNamespace(id=306)
|
||||
@@ -1384,27 +1517,24 @@ def test_profile_region_preview_uses_schema_field_order(app, monkeypatch):
|
||||
20, data={'document_id': 306, 'table_id': 'ordered', 'definition': definition}, actor_id=1,
|
||||
)
|
||||
|
||||
# 断言先标注的 line_no 仍排在 Schema 中更靠前的 part_number 之后。
|
||||
assert preview['rows'][0] == ['part_number', 'line_no']
|
||||
# 断言先标注的 part_number 仍排在 Schema 中更靠前的 customer_po_line_no 之后。
|
||||
assert preview['rows'][0] == ['customer_po_line_no', 'part_number']
|
||||
|
||||
|
||||
def test_coordinate_profile_exact_pages_allow_same_geometry_and_preview_only_current_page(app, monkeypatch):
|
||||
"""不同页可复用同一坐标框,但局部候选只能使用当前页的表头和物理行定义。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'].append({
|
||||
'field_id': 'line-field', 'field_code': 'line_no', 'scope': 'line', 'value_type': 'string',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
definition = _coordinate_definition()
|
||||
page_one, page_two = definition['table_regions'][0], _coordinate_definition()['table_regions'][0]
|
||||
for page_no, table_region in ((1, page_one), (2, page_two)):
|
||||
table_region.update({'region_id': f'main_lines_page_{page_no}', 'page_scope': 'exact_page', 'page_no': page_no})
|
||||
table_region['line_layouts'][0]['layout_id'] = f'line_{page_no}_1'
|
||||
table_region['line_layouts'][0]['field_regions'][0].update({
|
||||
'field_code': 'line_no',
|
||||
table_region['line_layouts'][0]['field_regions'] = [{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no',
|
||||
'region': {'x0': 0 if page_no == 1 else .5, 'y0': 0, 'x1': .5 if page_no == 1 else 1, 'y1': 1},
|
||||
})
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
}]
|
||||
definition['table_regions'] = [page_one, page_two]
|
||||
profile = SimpleNamespace(profile_code='PAGE_SCOPED', version=1, schema_version=schema)
|
||||
document = SimpleNamespace(id=302)
|
||||
@@ -1424,7 +1554,7 @@ def test_coordinate_profile_exact_pages_allow_same_geometry_and_preview_only_cur
|
||||
18, data={'document_id': 302, 'table_id': 'second-page', 'definition': definition}, actor_id=1,
|
||||
)
|
||||
|
||||
assert preview['rows'] == [['line_no'], ['2']]
|
||||
assert preview['rows'] == [['customer_po_line_no'], ['2']]
|
||||
assert preview['source_row_indices'] == [[], [0]]
|
||||
|
||||
|
||||
@@ -1475,7 +1605,7 @@ def test_profile_header_suggestion_uses_current_definition_and_page_coordinates(
|
||||
"""表头建议必须读取当前未保存画布定义,并以整页坐标解释表头框。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
schema.definition_json['fields'][1]['aliases'] = ['MPN']
|
||||
next(field for field in schema.definition_json['fields'] if field['field_code'] == 'part_number')['aliases'] = ['MPN']
|
||||
definition = _coordinate_definition()
|
||||
definition['table_regions'][0]['line_layouts'] = []
|
||||
definition['table_regions'][0].update({
|
||||
@@ -1751,7 +1881,7 @@ def test_profile_sample_delete_only_allows_unreferenced_dedicated_samples(app, m
|
||||
|
||||
|
||||
def test_delete_draft_cascades_blind_test_suite(app):
|
||||
"""关键断言:删除草稿 Profile 时一并清理盲测套件,避免外键约束导致 500。"""
|
||||
"""关键断言:删除草稿 Profile 时清理全部盲测套件(含历史 checksum),避免外键 500。"""
|
||||
with app.app_context():
|
||||
user = User(username='draft-delete-admin', email='draft-delete@example.com', role='admin', status='active')
|
||||
schema = _schema_version()
|
||||
@@ -1765,19 +1895,25 @@ def test_delete_draft_cascades_blind_test_suite(app):
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
# checksum 版本化后同一 profile 可并存多条 suite;只删 .first() 会触发 FK 500
|
||||
current_suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=profile.checksum or profile.structure_fingerprint,
|
||||
created_by_id=user.id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
stale_suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum='4' * 64, status='superseded',
|
||||
created_by_id=user.id,
|
||||
)
|
||||
db.session.add_all([current_suite, stale_suite])
|
||||
db.session.commit()
|
||||
suite_id = suite.id
|
||||
suite_ids = [current_suite.id, stale_suite.id]
|
||||
profile_id = profile.id
|
||||
|
||||
service.delete_draft(profile_id)
|
||||
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile_id) is None
|
||||
assert db.session.get(ShippingDocumentProfileTestSuite, suite_id) is None
|
||||
for suite_id in suite_ids:
|
||||
assert db.session.get(ShippingDocumentProfileTestSuite, suite_id) is None
|
||||
|
||||
|
||||
def test_profile_rejects_legacy_grid_definition(app):
|
||||
@@ -1806,10 +1942,16 @@ def test_workbench_minimum_v2_definition_can_be_saved(app):
|
||||
'region': {'x0': .16, 'y0': .30, 'x1': .72, 'y1': .50}, 'header_layouts': [],
|
||||
'line_layouts': [{'layout_id': 'main_line', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': .16, 'y0': .30, 'x1': .72, 'y1': .50},
|
||||
'field_regions': [{'field_id': '', 'field_code': 'part_number',
|
||||
'region': {'x0': .16, 'y0': .36, 'x1': .44, 'y1': .42},
|
||||
'extractor_key': 'direct', 'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate'}],
|
||||
'field_regions': [
|
||||
{'field_id': '', 'field_code': 'customer_po_line_no',
|
||||
'region': {'x0': .16, 'y0': .36, 'x1': .28, 'y1': .42},
|
||||
'extractor_key': 'direct', 'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate'},
|
||||
{'field_id': '', 'field_code': 'part_number',
|
||||
'region': {'x0': .30, 'y0': .36, 'x1': .44, 'y1': .42},
|
||||
'extractor_key': 'direct', 'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate'},
|
||||
],
|
||||
'new_line_anchor': None, 'continuation_conditions': [], 'required_fields': ['part_number'], 'allowed_empty_fields': [],
|
||||
}], 'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
||||
'termination_rules': [], 'exclusion_regions': [],
|
||||
@@ -1968,7 +2110,7 @@ def test_coordinate_preview_reports_four_source_rows(app, monkeypatch):
|
||||
'table_id': 'four-row',
|
||||
'coordinate_reconstruction': {'subrow_layouts': [
|
||||
{'role': 'main', 'row_offset': 0, 'column_boundaries': [0, 0.25, 0.7, 1],
|
||||
'column_field_codes': ['line_no', 'part_number', 'qty']},
|
||||
'column_field_codes': ['customer_po_line_no', 'part_number', 'qty']},
|
||||
{'role': 'continuation', 'row_offset': 1, 'column_boundaries': [0, 0.5, 1],
|
||||
'column_field_codes': [None, 'customer_part_number']},
|
||||
{'role': 'continuation', 'row_offset': 2, 'column_boundaries': [0, 0.5, 1],
|
||||
@@ -1984,7 +2126,7 @@ def test_coordinate_preview_reports_four_source_rows(app, monkeypatch):
|
||||
|
||||
|
||||
def test_coordinate_suggestion_returns_reviewable_dynamic_rows(app, monkeypatch):
|
||||
"""建议接口只返回相对边界和示例,并自动标出首行 line_no。"""
|
||||
"""建议接口只返回相对边界和示例,并自动标出首行 customer_po_line_no。"""
|
||||
characters = []
|
||||
source_index = 0
|
||||
for row_index, row in enumerate([
|
||||
@@ -2016,7 +2158,7 @@ def test_coordinate_suggestion_returns_reviewable_dynamic_rows(app, monkeypatch)
|
||||
|
||||
assert result['status'] == 'needs_review'
|
||||
assert len(result['subrow_layouts']) == 2
|
||||
assert result['subrow_layouts'][0]['suggested_field_codes'][0] == 'line_no'
|
||||
assert result['subrow_layouts'][0]['suggested_field_codes'][0] == 'customer_po_line_no'
|
||||
# Canvas suggestions must carry normalized page regions, not raw PDF coordinates.
|
||||
assert result['subrow_layouts'][0]['region']['x0'] == 0
|
||||
assert 0 <= result['subrow_layouts'][0]['region']['y0'] < result['subrow_layouts'][0]['region']['y1'] <= 1
|
||||
@@ -2085,7 +2227,7 @@ def test_coordinate_suggestion_binds_line_columns_from_enabled_field_rules(app,
|
||||
'coordinate_evidence': {'tables': {'schema-suggest': characters}, 'pages': {'1': {'width': 320, 'height': 70}}},
|
||||
}
|
||||
version = SimpleNamespace(definition_json={'fields': [
|
||||
{'field_id': 'line', 'field_code': 'line_no', 'scope': 'line', 'enabled': True,
|
||||
{'field_id': 'line', 'field_code': 'customer_po_line_no', 'scope': 'line', 'enabled': True,
|
||||
'display_name': 'Item number', 'aliases': ['ITEM NO'], 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True,
|
||||
'display_name': 'Material number', 'aliases': ['MATERIAL NO'], 'allowed_sources': ['pdf_coordinate']},
|
||||
@@ -2103,9 +2245,9 @@ def test_coordinate_suggestion_binds_line_columns_from_enabled_field_rules(app,
|
||||
)
|
||||
|
||||
header_codes = [field['field_code'] for field in result['header_regions'][0]['fields']]
|
||||
assert header_codes == ['line_no', 'part_number', None]
|
||||
assert header_codes == ['customer_po_line_no', 'part_number', None]
|
||||
# The disabled automatic marker never produces a table-header or detail-column binding.
|
||||
assert result['subrow_layouts'][0]['suggested_field_codes'] == ['line_no', 'part_number', None]
|
||||
assert result['subrow_layouts'][0]['suggested_field_codes'] == ['customer_po_line_no', 'part_number', None]
|
||||
|
||||
|
||||
def test_coordinate_suggestion_binds_line_columns_from_normalized_field_codes(app, monkeypatch):
|
||||
@@ -2127,7 +2269,7 @@ def test_coordinate_suggestion_binds_line_columns_from_normalized_field_codes(ap
|
||||
'coordinate_evidence': {'tables': {'code-suggest': characters}, 'pages': {'1': {'width': 320, 'height': 70}}},
|
||||
}
|
||||
version = SimpleNamespace(definition_json={'fields': [
|
||||
{'field_id': 'line', 'field_code': 'line_no', 'scope': 'line', 'enabled': True,
|
||||
{'field_id': 'line', 'field_code': 'customer_po_line_no', 'scope': 'line', 'enabled': True,
|
||||
'display_name': '项次', 'aliases': ['ITEM NO'], 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'price', 'field_code': 'unit_price', 'scope': 'line', 'enabled': True,
|
||||
'display_name': '单价', 'aliases': [], 'allowed_sources': ['pdf_coordinate']},
|
||||
@@ -2144,7 +2286,7 @@ def test_coordinate_suggestion_binds_line_columns_from_normalized_field_codes(ap
|
||||
)
|
||||
|
||||
assert result['subrow_layouts'][0]['suggested_field_codes'] == [
|
||||
'line_no', 'unit_price', 'order_quantity',
|
||||
'customer_po_line_no', 'unit_price', 'order_quantity',
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -55,9 +55,15 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.jobs.queue import fail_job
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction import (
|
||||
submit_order_extraction_run_result,
|
||||
submit_order_extraction_unit_result,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan_batch
|
||||
from app.services.shipping_notice.order_extraction_plan import (
|
||||
ensure_order_extraction_plan,
|
||||
ensure_order_extraction_plan_batch,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_workflow import route_deterministic_unit
|
||||
from tests.test_shipping_notice_order_extraction import _ensure_order_schema, _order
|
||||
|
||||
@@ -797,6 +803,43 @@ def test_plan_unit_state_machine_is_local_and_rolls_up_partial_failure(app):
|
||||
assert units[0].status == 'candidate_ready'
|
||||
|
||||
|
||||
def test_second_pdf_unit_can_persist_after_first_unit_consumes_shared_intake(app):
|
||||
"""同一邮件的首个空结果消费 Intake 后,后续 PDF Unit 仍须在同一 Run 内完成落库。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _first_document = _seed_run_input(suffix='UNIT-CONSUMED')
|
||||
second_document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='attachment',
|
||||
attachment_key='second-pdf',
|
||||
filename='orders-second',
|
||||
content_hash='d' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='Second PDF order facts',
|
||||
)
|
||||
db.session.add(second_document)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
db.session.commit()
|
||||
first_unit, second_unit = sorted(run.extraction_plan.units, key=lambda item: int(item.document_id))
|
||||
|
||||
submit_order_extraction_unit_result(run=run, unit=first_unit, orders=[])
|
||||
db.session.refresh(intake)
|
||||
assert intake.parse_status == 'consumed'
|
||||
assert intake.consumed_task_id is None
|
||||
assert intake.consumed_batch_id is None
|
||||
|
||||
result = submit_order_extraction_unit_result(run=run, unit=second_unit, orders=[])
|
||||
|
||||
assert result['unit_id'] == second_unit.id
|
||||
db.session.refresh(intake)
|
||||
assert intake.parse_status == 'consumed'
|
||||
|
||||
|
||||
def test_plan_can_append_future_selection_batch_units_idempotently(app):
|
||||
"""未来批次附件完成物化后,可按冻结选择计划追加 unit,且重复追加不重复建单元。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -41,6 +41,7 @@ def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinate
|
||||
'table_regions': [{'region_id': 'lines', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .9}, 'line_layouts': [], 'header_layouts': [{'layout_id': 'headers', 'region': {'x0': .6, 'y0': .6, 'x1': .9, 'y1': .7}}]}],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'po_field', 'field_id': 'po-id', 'field_code': 'customer_po',
|
||||
'scope': 'header',
|
||||
'page_scope': page_scope, **layout,
|
||||
}],
|
||||
})
|
||||
@@ -80,6 +81,74 @@ def test_anchor_relative_value_is_confirmed_with_native_page_coordinates():
|
||||
assert result.source == 'pdf_coordinate'
|
||||
|
||||
|
||||
def test_unlocked_anchor_reads_same_field_after_horizontal_layout_shift():
|
||||
"""标签右侧字段不应被画布初始横坐标限制,才能覆盖同版式的左移变体。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {
|
||||
'anchor_id': 'reservation', 'text': 'reservation_id',
|
||||
'region': {'x0': .30, 'y0': .79, 'x1': .41, 'y1': .82},
|
||||
'position_locked': False,
|
||||
},
|
||||
'value_region': {'x0': 1.1, 'y0': 0, 'x1': 2.0, 'y1': 1}, 'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('reservation_id#3000099132', 12, 160))},
|
||||
))[0]
|
||||
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == '3000099132'
|
||||
|
||||
|
||||
def test_movable_right_of_anchor_starts_at_actual_anchor_end():
|
||||
"""不同 PDF 的标签字宽变化不能让相对值框跳过预约号的首位数字。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {'anchor_id': 'reservation', 'text': 'reservation_id', 'position_locked': False},
|
||||
'value_region': {'x0': 1.11, 'y0': 0, 'x1': 1.82, 'y1': 1}, 'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('reservation_id#3000099132', 12, 160))},
|
||||
))[0]
|
||||
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == '3000099132'
|
||||
|
||||
|
||||
def test_legacy_right_of_anchor_canvas_box_is_rebased_after_horizontal_shift():
|
||||
"""旧画布保存绝对框时,运行期仍须按右侧语义兼容左移同版式单据。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {
|
||||
'anchor_id': 'reservation', 'text': 'reservation_id',
|
||||
'region': {'x0': .30, 'y0': .79, 'x1': .41, 'y1': .82},
|
||||
},
|
||||
'absolute_value_region': {'x0': .424, 'y0': .79, 'x1': .50, 'y1': .82},
|
||||
'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('reservation_id#3000099132', 12, 160))},
|
||||
))[0]
|
||||
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == '3000099132'
|
||||
|
||||
|
||||
def test_legacy_cross_row_value_box_remains_absolute():
|
||||
"""旧版跨行地址框不得误转为锚点偏移,以免生成越界相对坐标。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {
|
||||
'anchor_id': 'bill_to', 'text': 'BILL TO',
|
||||
'region': {'x0': .02, 'y0': .10, 'x1': .15, 'y1': .12},
|
||||
},
|
||||
'absolute_value_region': {'x0': .33, 'y0': .58, 'x1': .72, 'y1': .60},
|
||||
'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('BILL TO', 4, 20), ('Taipei Taiwan', 70, 116))},
|
||||
))[0]
|
||||
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == 'Taipei Taiwan'
|
||||
|
||||
|
||||
def test_wide_address_value_region_is_valid_relative_to_short_anchor():
|
||||
"""地址值框可比短标签宽得多,自动标记后保存不得被相对区域上限拒绝。"""
|
||||
profile = _profile(layout={
|
||||
@@ -107,6 +176,25 @@ def test_duplicate_anchor_requires_review_instead_of_selecting_one():
|
||||
assert result.issues == ['order_field_anchor_ambiguous']
|
||||
|
||||
|
||||
def test_anchor_match_folds_case_and_uses_reference_region_to_resolve_duplicates():
|
||||
"""画布标签可省略 PDF 大小写与空格,重复文本则仍必须由保存位置唯一定位。"""
|
||||
profile = _profile(layout={
|
||||
'anchor': {
|
||||
'anchor_id': 'number', 'text': 'Number',
|
||||
'region': {'x0': .35, 'y0': .18, 'x1': .65, 'y1': .28},
|
||||
'position_locked': False,
|
||||
},
|
||||
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1}, 'value_mode': 'right_of_anchor',
|
||||
})
|
||||
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
|
||||
pages={'1': _glyphs(('NUMBER 999', 20, 20), ('number 45001', 80, 40))},
|
||||
))[0]
|
||||
|
||||
# 关键断言:位置框只在多处命中时消歧,不会将单一标签锁死在训练样本坐标。
|
||||
assert result.status == 'confirmed'
|
||||
assert result.value == '45001'
|
||||
|
||||
|
||||
def test_anchor_reference_region_and_exact_mode_reject_unrelated_label_occurrences():
|
||||
"""锚点参考区与精确匹配共同排除页眉重复标签和更长单词中的局部文本。"""
|
||||
profile = _profile(layout={
|
||||
@@ -435,7 +523,7 @@ def test_quality_gate_normalizes_order_field_truth_before_comparison():
|
||||
failures = _order_field_quality_failures(
|
||||
parser=profile, schema_fields=schema, sample_id=10,
|
||||
layout={'coordinate_evidence': _evidence(pages={'1': _glyphs(('DATE 2026-08-01', 20, 20))})},
|
||||
expected_values={'order_date': '2026-08-01'},
|
||||
expected_values={'header:order_date': '2026-08-01'},
|
||||
)
|
||||
|
||||
# 关键断言:同一日期的 JSON 字符串与运行时 date 对象不应产生伪 mismatch。
|
||||
|
||||
@@ -14,7 +14,7 @@ def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None
|
||||
},
|
||||
'table_regions': [{'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [{'field_id': 'line-id', 'field_code': 'line_no', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}],
|
||||
'field_regions': [{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']}],
|
||||
}]}],
|
||||
}}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ import pytest
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewCaseEvent,
|
||||
@@ -62,6 +64,24 @@ def _materialized_run(*, user, agent, session, intake):
|
||||
return run
|
||||
|
||||
|
||||
def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'reservation-id') -> None:
|
||||
"""
|
||||
为 Review 就绪路径测试注入行级 catch-all 库存源规则。
|
||||
|
||||
核心逻辑:行 Reservation 非空即产出已启用测试库存源 DSV360_AWSDU,满足阶段 2 建单门禁。
|
||||
"""
|
||||
db.session.add(ShippingInventoryRoutingRule(
|
||||
rule_code='REVIEW_CATCH_ALL', rule_name='Review Catch All', scope='line', priority=50,
|
||||
match_mode='all', status='published', action_type='add_source_candidates',
|
||||
action_payload_json={'source_codes': ['DSV360_AWSDU']}, version=1,
|
||||
conditions=[ShippingInventoryRoutingRuleCondition(
|
||||
condition_group=1, source_kind='order_field', order_field_id=reservation_field_id,
|
||||
operator='is_not_empty', expected_value_json=None, sequence=1,
|
||||
)],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candidate_readonly(app):
|
||||
"""同一 PDF 重入只保留一个 Case/Draft,草稿复制机器快照但不改写 Candidate。"""
|
||||
with app.app_context():
|
||||
@@ -287,6 +307,7 @@ def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(ap
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
_seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id')
|
||||
|
||||
first = patch_header_field(
|
||||
user_id=user.id, case_no=case.case_no, field_id='po-id', value='PO-MANUAL',
|
||||
@@ -639,6 +660,7 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
|
||||
validated = patch_header_field(
|
||||
user_id=user.id, case_no=case.case_no, field_id='po-id', value='PO-CONFIRMED', expected_draft_version=1,
|
||||
)
|
||||
_seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id')
|
||||
db.session.commit()
|
||||
|
||||
result = confirm_review_case(
|
||||
@@ -688,6 +710,7 @@ def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutati
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
_seed_review_inventory_routing_catch_all(reservation_field_id='reservation-id')
|
||||
try:
|
||||
confirm_review_case(user_id=user.id, case_no=case.case_no, expected_draft_version=99, idempotency_key='review-stale-1')
|
||||
except Exception as exc:
|
||||
|
||||
@@ -85,25 +85,30 @@ def _publish_draft(version_id: int) -> dict:
|
||||
|
||||
|
||||
def test_order_schema_initializes_standard_fields_and_allows_extension_fields(app):
|
||||
"""关键断言:57 个预置标准字段身份不可变;扩展字段仍允许按业务治理新增。"""
|
||||
"""关键断言:58 项标准资产(含 Header/Line 同名 Reservation)身份不可变;扩展字段仍可新增。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
|
||||
core_codes = set(service.STANDARD_ORDER_FIELD_SPECS)
|
||||
fields = ShippingOrderField.query.order_by(ShippingOrderField.display_sequence).all()
|
||||
assert len(core_codes) == 57
|
||||
assert len(fields) == 58
|
||||
assert len(core_codes) == 57 # reservation_id 在 Header/Line 共享同一业务编码
|
||||
assert {field.field_code for field in fields} == core_codes
|
||||
assert {(field.scope, field.field_code) for field in fields if field.field_code == 'reservation_id'} == {
|
||||
('header', 'reservation_id'), ('line', 'reservation_id'),
|
||||
}
|
||||
assert service.STANDARD_ORDER_FIELD_SPECS['bill_to_address'] == ('header', 'string')
|
||||
assert service.STANDARD_ORDER_FIELD_SPECS['product_revision'] == ('line', 'string')
|
||||
assert 'po_number' not in core_codes
|
||||
assert 'aws_part_number' not in core_codes
|
||||
|
||||
bill_to_address = next(field for field in fields if field.field_code == 'bill_to_address')
|
||||
with pytest.raises(Exception) as error:
|
||||
service.save_field({
|
||||
'field_code': 'bill_to_address', 'scope': 'line', 'value_type': 'string',
|
||||
}, actor_id=None, field_id=bill_to_address.id)
|
||||
assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_FIELD_IMMUTABLE'
|
||||
# 标准资产身份只读:带 field_id 的更新不会改 scope,也不会抛业务异常。
|
||||
unchanged = service.save_field({
|
||||
'field_code': 'bill_to_address', 'scope': 'line', 'value_type': 'string',
|
||||
}, actor_id=None, field_id=bill_to_address.id)
|
||||
assert unchanged['scope'] == 'header'
|
||||
assert db.session.get(ShippingOrderField, bill_to_address.id).scope == 'header'
|
||||
|
||||
extension = service.save_field({
|
||||
'field_code': 'business_extension', 'scope': 'header', 'value_type': 'string',
|
||||
@@ -111,12 +116,13 @@ def test_order_schema_initializes_standard_fields_and_allows_extension_fields(ap
|
||||
assert extension['field_code'] == 'business_extension'
|
||||
|
||||
|
||||
def test_order_schema_publish_keeps_history_when_field_code_changes(app):
|
||||
"""发布后可重命名系统标识,但旧契约快照保持原名称且位置/类型仍锁定。"""
|
||||
def test_order_schema_publish_keeps_history_when_display_name_changes(app):
|
||||
"""扩展字段可改显示名;已发布契约仍保留发布时的 field_code 与锁定身份。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
field = service.save_field({
|
||||
'field_code': 'request_qty', 'scope': 'line', 'value_type': 'decimal',
|
||||
'display_name': '请求数量',
|
||||
}, actor_id=None)
|
||||
draft = service.create_draft({'change_note': '初始字段'}, actor_id=None)
|
||||
_save_draft(draft['id'], [_field_config(field['id'])])
|
||||
@@ -128,17 +134,22 @@ def test_order_schema_publish_keeps_history_when_field_code_changes(app):
|
||||
assert contract['fields'][0]['field_code'] == 'request_qty'
|
||||
assert contract['fields'][0]['scope'] == 'line'
|
||||
|
||||
# 发布可能刷新资产 updated_at;改名前以当前库值为准。
|
||||
current = db.session.get(ShippingOrderField, field['id'])
|
||||
renamed = service.save_field({
|
||||
'field_code': 'renamed_qty', 'scope': 'line', 'value_type': 'decimal',
|
||||
'display_name': '重命名数量',
|
||||
'expected_updated_at': current.updated_at.isoformat() if current.updated_at else None,
|
||||
}, actor_id=None, field_id=field['id'])
|
||||
assert renamed['field_code'] == 'renamed_qty'
|
||||
assert renamed['field_code'] == 'request_qty'
|
||||
assert renamed['display_name_default'] == '重命名数量'
|
||||
assert service.get_published_contract()['fields'][0]['field_code'] == 'request_qty'
|
||||
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
service.save_field({
|
||||
'field_code': 'renamed_qty', 'scope': 'header', 'value_type': 'decimal',
|
||||
'scope': 'header',
|
||||
'expected_updated_at': renamed['updated_at'],
|
||||
}, actor_id=None, field_id=field['id'])
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_IMMUTABLE'
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.FIELD_ASSET_IMMUTABLE'
|
||||
|
||||
|
||||
def test_order_schema_business_purposes_bind_stable_line_field_ids(app):
|
||||
@@ -146,11 +157,11 @@ def test_order_schema_business_purposes_bind_stable_line_field_ids(app):
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
fields_by_code = {
|
||||
field.field_code: field
|
||||
(field.scope, field.field_code): field
|
||||
for field in ShippingOrderField.query.filter_by(status='active').all()
|
||||
}
|
||||
reservation = fields_by_code['reservation_id']
|
||||
source_hint = fields_by_code['inventory_source_hint']
|
||||
reservation = fields_by_code[('line', 'reservation_id')]
|
||||
source_hint = fields_by_code[('line', 'inventory_source_hint')]
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
reservation_config = _field_config(reservation.id, name='预定单号')
|
||||
reservation_config.update({
|
||||
@@ -204,6 +215,28 @@ def test_order_schema_rejects_duplicate_or_incompatible_business_purposes(app):
|
||||
assert getattr(scope_exc.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
|
||||
|
||||
def test_order_schema_allows_internal_line_number_extraction_bindings(app):
|
||||
"""内部项次 line_no 可作为可识别字段配置别名与坐标来源。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
line_no = ShippingOrderField.query.filter_by(field_code='line_no', scope='line').one()
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
config = _field_config(line_no.id, name='内部项次')
|
||||
config.update({
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': [],
|
||||
'comparator_key': 'normalized_text',
|
||||
'aliases': ['Item No'],
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
})
|
||||
saved = _save_draft(draft['id'], [config])
|
||||
adopted = next(item for item in saved['definition']['fields'] if item['field_id'] == line_no.id)
|
||||
assert adopted['aliases'] == ['Item No']
|
||||
assert adopted['allowed_sources'] == ['pdf_coordinate']
|
||||
assert saved['definition']['derivation_rules'][0]['target_field_code'] == 'line_no'
|
||||
assert saved['definition']['derivation_rules'][0]['enabled'] is False
|
||||
|
||||
|
||||
def test_order_schema_excluded_field_config_is_saved_but_not_published(app):
|
||||
"""未纳入字段仍保存版本显示名称和规则,但发布契约不得包含该字段。"""
|
||||
with app.app_context():
|
||||
@@ -281,7 +314,7 @@ def test_order_schema_admin_api_permissions_and_validation(app, client):
|
||||
json={'field_code': 'Bad Code', 'scope': 'line', 'value_type': 'string'},
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
assert parse_api_error(invalid.get_json())['code'] == 'SHIPPING.ORDER_FIELD_INVALID'
|
||||
assert parse_api_error(invalid.get_json())['code'] == 'SHIPPING.FIELD_ASSET_INVALID'
|
||||
|
||||
|
||||
def test_dynamic_header_field_value_is_unique(app):
|
||||
@@ -336,13 +369,13 @@ def test_order_schema_rejects_non_boolean_required_and_referenced_retire(app):
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
|
||||
_save_draft(draft['id'], [_field_config(field['id'])])
|
||||
with pytest.raises(Exception) as retire_exc:
|
||||
service.retire_field(field['id'])
|
||||
assert getattr(retire_exc.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
|
||||
# 草稿采用不阻断弃用;仅校验 required 布尔门禁后仍可退役扩展字段。
|
||||
retired = service.retire_field(field['id'], reason='draft-only reference')
|
||||
assert retired['status'] == 'retired'
|
||||
|
||||
|
||||
def test_delete_unused_order_field_removes_draft_config_and_catalog_row(app):
|
||||
"""未发布且无任何引用的字段应物理删除,并在同一事务移出当前草稿。"""
|
||||
def test_retire_unused_extension_field_hides_from_active_catalog(app):
|
||||
"""未发布扩展字段弃用后不再出现在活跃资产目录;禁止物理删除。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
field = service.save_field({
|
||||
@@ -353,16 +386,20 @@ def test_delete_unused_order_field_removes_draft_config_and_catalog_row(app):
|
||||
config.update({'normalizer_key': 'trim', 'validator_keys': [], 'comparator_key': 'normalized_text'})
|
||||
_save_draft(draft['id'], [config])
|
||||
|
||||
result = service.delete_field(field['id'])
|
||||
with pytest.raises(Exception) as delete_exc:
|
||||
service.delete_field(field['id'])
|
||||
assert getattr(delete_exc.value, 'code', None) == 'SHIPPING.FIELD_ASSET_DELETE_FORBIDDEN'
|
||||
|
||||
assert result == {'field_id': field['id'], 'action': 'deleted'}
|
||||
assert db.session.get(ShippingOrderField, field['id']) is None
|
||||
assert {item['field_code'] for item in service.get_state()['fields']} == set(service.STANDARD_ORDER_FIELD_SPECS)
|
||||
assert service.get_state()['versions'][0]['field_count'] == 0
|
||||
retired = service.retire_field(
|
||||
field['id'], reason='unused draft field', confirm_impact=True,
|
||||
)
|
||||
assert retired['status'] == 'retired'
|
||||
assert db.session.get(ShippingOrderField, field['id']).status == 'retired'
|
||||
assert field['id'] not in {item['id'] for item in service.get_state()['fields']}
|
||||
|
||||
|
||||
def test_delete_historical_order_field_archives_and_hides_current_catalog(app):
|
||||
"""已发布字段删除时须保留历史契约,但不再返回当前配置清单。"""
|
||||
def test_retire_published_extension_field_keeps_history(app):
|
||||
"""已发布扩展字段弃用后历史契约仍可读取,但活跃目录隐藏。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
|
||||
field = service.save_field({
|
||||
@@ -375,14 +412,17 @@ def test_delete_historical_order_field_archives_and_hides_current_catalog(app):
|
||||
_publish_draft(draft['id'])
|
||||
next_draft = service.create_draft({}, actor_id=None)
|
||||
|
||||
result = service.delete_field(field['id'])
|
||||
|
||||
assert result == {'field_id': field['id'], 'action': 'archived'}
|
||||
retired = service.retire_field(
|
||||
field['id'], reason='archived after publish', confirm_impact=True,
|
||||
)
|
||||
assert retired['status'] == 'retired'
|
||||
assert db.session.get(ShippingOrderField, field['id']).status == 'retired'
|
||||
assert {item['field_code'] for item in service.get_state()['fields']} == set(service.STANDARD_ORDER_FIELD_SPECS)
|
||||
assert field['id'] not in {item['id'] for item in service.get_state()['fields']}
|
||||
assert service.get_state()['versions'][0]['id'] == next_draft['id']
|
||||
assert service.get_state()['versions'][0]['field_count'] == 0
|
||||
|
||||
assert any(
|
||||
item['field_id'] == field['id']
|
||||
for item in service.get_published_contract()['fields']
|
||||
)
|
||||
|
||||
def test_order_field_retire_is_blocked_by_active_cross_domain_config(app):
|
||||
"""库存解析匹配键和 Excel 映射引用稳定字段时,字段不得退役。"""
|
||||
@@ -422,8 +462,8 @@ def test_order_field_retire_is_blocked_by_active_cross_domain_config(app):
|
||||
|
||||
for field_id in (match_field['id'], template_field['id']):
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
service.retire_field(field_id)
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
|
||||
service.retire_field(field_id, reason='cross-domain reference')
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.FIELD_ASSET_RETIRE_IMPACT_CONFIRM_REQUIRED'
|
||||
|
||||
|
||||
def test_order_field_retire_is_blocked_by_v2_coordinate_profile(app):
|
||||
@@ -443,8 +483,8 @@ def test_order_field_retire_is_blocked_by_v2_coordinate_profile(app):
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
service.retire_field(field['id'])
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_FIELD_RETIRE_BLOCKED'
|
||||
service.retire_field(field['id'], reason='coordinate profile reference')
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.FIELD_ASSET_RETIRE_IMPACT_CONFIRM_REQUIRED'
|
||||
|
||||
|
||||
def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app):
|
||||
@@ -460,10 +500,13 @@ def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app):
|
||||
first = service.create_draft({}, actor_id=None)
|
||||
referenced_config = _field_config(referenced['id'])
|
||||
referenced_config.update({'normalizer_key': 'trim', 'comparator_key': 'normalized_text', 'validator_keys': []})
|
||||
fields = {item.field_code: item for item in ShippingOrderField.query.filter_by(status='active').all()}
|
||||
fields = {
|
||||
(item.scope, item.field_code): item
|
||||
for item in ShippingOrderField.query.filter_by(status='active').all()
|
||||
}
|
||||
policy_configs = []
|
||||
for code in ('reservation_id', 'part_number', 'qty', 'inventory_source_hint'):
|
||||
config = _field_config(fields[code].id, name=code)
|
||||
config = _field_config(fields[('line', code)].id, name=code)
|
||||
config.update({
|
||||
'aliases': [], 'extraction_instruction': '',
|
||||
'normalizer_key': 'decimal' if code == 'qty' else 'uppercase_trim',
|
||||
@@ -487,7 +530,7 @@ def test_schema_publish_cannot_omit_field_referenced_by_downstream_config(app):
|
||||
_save_draft(second['id'], [replacement_config])
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
_publish_draft(second['id'])
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED'
|
||||
assert getattr(exc_info.value, 'code', None) == 'SHIPPING.FIELD_IMPACT_BLOCKED'
|
||||
assert referenced['id'] in {
|
||||
field['field_id'] for field in service.get_published_contract()['fields']
|
||||
}
|
||||
@@ -576,7 +619,9 @@ def test_order_field_global_order_persists_without_schema_draft(app):
|
||||
refreshed = service.get_state()
|
||||
|
||||
assert [item['id'] for item in refreshed['fields']][-2:] == [second['id'], first['id']]
|
||||
assert [item['display_sequence'] for item in refreshed['fields']][-2:] == [58, 59]
|
||||
# 序号随标准目录 + 上下文字段种子数量变化,断言相对末位而非写死 59/60。
|
||||
total = len(refreshed['fields'])
|
||||
assert [item['display_sequence'] for item in refreshed['fields']][-2:] == [total - 1, total]
|
||||
assert not any(item['status'] == 'draft' for item in refreshed['versions'])
|
||||
|
||||
|
||||
@@ -604,9 +649,13 @@ def test_order_schema_draft_uses_optimistic_lock_and_writes_audit(app):
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'], request_id='publish-request',
|
||||
)
|
||||
events = ShippingOrderSchemaAuditEvent.query.order_by(ShippingOrderSchemaAuditEvent.id).all()
|
||||
assert [event.event_type for event in events][-3:] == ['draft_created', 'draft_saved', 'published']
|
||||
assert events[-2].request_id == 'save-request'
|
||||
assert events[-2].before_snapshot_json != events[-2].after_snapshot_json
|
||||
event_types = [event.event_type for event in events]
|
||||
assert 'draft_created' in event_types
|
||||
assert 'draft_saved' in event_types
|
||||
assert 'published' in event_types
|
||||
saved_event = next(event for event in events if event.event_type == 'draft_saved')
|
||||
assert saved_event.request_id == 'save-request'
|
||||
assert saved_event.before_snapshot_json != saved_event.after_snapshot_json
|
||||
|
||||
|
||||
def test_order_schema_catalog_exposes_type_compatible_rules(app):
|
||||
|
||||
@@ -42,8 +42,8 @@ def _profile():
|
||||
'table_regions': [{
|
||||
'line_layouts': [{
|
||||
'field_regions': [{
|
||||
'field_id': 'f1', 'field_code': 'old_code',
|
||||
'target_fields': [{'field_id': 'f1', 'field_code': 'old_code'}],
|
||||
'field_id': 'f1', 'field_code': 'old_code', 'scope': 'line',
|
||||
'target_fields': [{'field_id': 'f1', 'field_code': 'old_code', 'scope': 'line'}],
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
@@ -82,7 +82,9 @@ def test_profile_field_codes_are_remapped_by_stable_identity():
|
||||
field = result['table_regions'][0]['line_layouts'][0]['field_regions'][0]
|
||||
assert field['field_id'] == 'f1'
|
||||
assert field['field_code'] == 'new_code'
|
||||
assert field['scope'] == 'line'
|
||||
assert field['target_fields'][0]['field_code'] == 'new_code'
|
||||
assert field['target_fields'][0]['scope'] == 'line'
|
||||
|
||||
|
||||
def test_migration_resolution_contract_requires_each_breaking_field():
|
||||
|
||||
@@ -3,7 +3,8 @@ backend/tests/test_shipping_order_schema_runtime.py
|
||||
|
||||
用途:验证已发布订单 Schema 编译、EML/PDF 动态字段交叉验证和类型化持久化。
|
||||
依赖:order_schema service/runtime、ShippingNoticeDocument、动态订单模型。
|
||||
逻辑:创建唯一 Schema 后提交稳定 field_id Observation,断言一致证据被接受、冲突被阻断且下游只得到 field_code 投影。
|
||||
逻辑:创建唯一 Schema 后提交稳定 field_id Observation,断言一致证据被接受、冲突被阻断且下游只得到 field_code 投影;
|
||||
覆盖启用派生后 line_no 补齐且不残留必填阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,7 +23,11 @@ from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice.order_schema.runtime import dify_contract, persist_dynamic_order, published_version
|
||||
from app.services.shipping_notice.notice_line_table import parse_notice_table_text
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
compute_effective_reservation_id,
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
|
||||
|
||||
def _config(field_id: str, name: str, *, value_type: str) -> dict:
|
||||
@@ -81,6 +86,20 @@ def test_text_normalizers_preserve_source_case_for_user_visible_values(normalize
|
||||
) == 'Inventec D4-A08AR12000002 USD'
|
||||
|
||||
|
||||
def test_field_rules_accept_line_number_and_compute_effective_reservation():
|
||||
"""用户配置的项次可从原文写入;有效 Reservation 按行优先回退头,二者均可空。"""
|
||||
assert normalize_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'}) == '00010'
|
||||
assert validate_order_field_value('00010', {'field_code': 'line_no', 'value_type': 'string'})
|
||||
|
||||
assert compute_effective_reservation_id(
|
||||
line_reservation_id='3000000002', header_reservation_id='3000000001',
|
||||
) == '3000000002'
|
||||
assert compute_effective_reservation_id(
|
||||
line_reservation_id=None, header_reservation_id='3000000001',
|
||||
) == '3000000001'
|
||||
assert compute_effective_reservation_id() is None
|
||||
|
||||
|
||||
def test_dynamic_schema_rejects_text_evidence_with_only_case_difference(app):
|
||||
"""Schema v1 不得让大小写不同的 PDF 引文证明文本字段值。"""
|
||||
with app.app_context():
|
||||
@@ -479,6 +498,267 @@ def test_email_supplement_table_evidence_is_accepted_for_reservation_id(app):
|
||||
assert observation.evidence_metadata_json['cell_id'] == 'email-supplement:test:1:r2:c1'
|
||||
|
||||
|
||||
def test_runtime_preserves_customer_po_line_number_without_system_line_projection(app):
|
||||
"""客户 PO 原始行号按字符串保留前导零;不再投影系统序号到 line_no。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer_line = service.save_field(
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [_config(customer_line['id'], '客户 PO 行号', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'Item 00010\nItem 00020'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [],
|
||||
'lines': [
|
||||
{'fields': [{'field_id': customer_line['id'], 'observations': [{
|
||||
'value': '00010', 'document_id': document.id, 'quote': '00010',
|
||||
}]}]},
|
||||
{'fields': [{'field_id': customer_line['id'], 'observations': [{
|
||||
'value': '00020', 'document_id': document.id, 'quote': '00020',
|
||||
}]}]},
|
||||
],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='l' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
assert result['lines'] == [
|
||||
{'customer_po_line_no': '00010'},
|
||||
{'customer_po_line_no': '00020'},
|
||||
]
|
||||
assert all('line_no' not in item for item in result['system_line_projections'])
|
||||
assert all(item['line_key'] for item in result['system_line_projections'])
|
||||
assert draft['definition']['derivation_rules'][0]['enabled'] is False
|
||||
assert draft['definition']['derivation_rules'][0]['target_field_code'] == 'line_no'
|
||||
|
||||
|
||||
def test_runtime_derives_missing_line_no_and_clears_required_block(app):
|
||||
"""启用派生后:line_no 缺失被 copy_if_empty 补齐,不得残留 blocked_fields / needs_review。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID
|
||||
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer_line = service.save_field(
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
line_no = service.save_field(
|
||||
{'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [
|
||||
_config(customer_line['id'], '客户 PO 行号', value_type='string'),
|
||||
_config(line_no['id'], '内部项次', value_type='string'),
|
||||
],
|
||||
'derivation_rules': [{
|
||||
'rule_id': DEFAULT_DERIVATION_RULE_ID,
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
published = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'Item 00010\nItem 00020'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [],
|
||||
'lines': [
|
||||
{'fields': [{'field_id': customer_line['id'], 'observations': [{
|
||||
'value': '00010', 'document_id': document.id, 'quote': '00010',
|
||||
}]}]},
|
||||
{'fields': [{'field_id': customer_line['id'], 'observations': [{
|
||||
'value': '00020', 'document_id': document.id, 'quote': '00020',
|
||||
}]}]},
|
||||
],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='d' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
# 派生成功后投影含 line_no,且不得因派生前缺失而残留阻断。
|
||||
assert result['lines'] == [
|
||||
{'customer_po_line_no': '00010', 'line_no': '00010'},
|
||||
{'customer_po_line_no': '00020', 'line_no': '00020'},
|
||||
]
|
||||
assert 'line_no' not in result['blocked_fields']
|
||||
assert result['extraction'].status == 'accepted'
|
||||
assert result['extraction'].validation_result_json['blocked_fields'] == []
|
||||
lineage = result['field_lineage']
|
||||
assert len(lineage) == 2
|
||||
assert all(item['value_source'] == 'derived' for item in lineage)
|
||||
assert all(item['rule_id'] == DEFAULT_DERIVATION_RULE_ID for item in lineage)
|
||||
|
||||
# 派生值必须落库 FieldValue,否则冻结/Excel 读不到 line_no。
|
||||
stored = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=int(result['extraction'].id),
|
||||
field_id=line_no['id'],
|
||||
).all()
|
||||
assert len(stored) == 2
|
||||
assert sorted(str(item.value_json) for item in stored) == ['00010', '00020']
|
||||
decisions = ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=int(result['extraction'].id),
|
||||
field_id=line_no['id'],
|
||||
).all()
|
||||
assert all(item.decision_status == 'accepted' for item in decisions)
|
||||
assert all(item.reason_code == 'derived' for item in decisions)
|
||||
|
||||
|
||||
def test_simulate_derivation_strips_existing_targets_from_history_sample(app):
|
||||
"""历史 Extraction 已含派生 line_no 时,模拟须剔除目标后重新评估,不得恒跳过。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID
|
||||
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer_line = service.save_field(
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
line_no = service.save_field(
|
||||
{'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [
|
||||
_config(customer_line['id'], '客户 PO 行号', value_type='string'),
|
||||
_config(line_no['id'], '内部项次', value_type='string'),
|
||||
],
|
||||
'derivation_rules': [{
|
||||
'rule_id': DEFAULT_DERIVATION_RULE_ID,
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
published = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'Item 00010'
|
||||
first = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [],
|
||||
'lines': [{'fields': [{'field_id': customer_line['id'], 'observations': [{
|
||||
'value': '00010', 'document_id': document.id, 'quote': '00010',
|
||||
}]}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='s' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
assert first['lines'][0].get('line_no') == '00010'
|
||||
|
||||
simulated = service.simulate_derivation(
|
||||
published['id'],
|
||||
{'sample_ref': f"extraction:{first['extraction'].id}"},
|
||||
actor_id=actor_id,
|
||||
)
|
||||
assert simulated['derived_count'] == 1
|
||||
assert simulated['results'][0]['status'] == 'derived'
|
||||
assert simulated['results'][0]['before_target'] in (None, '')
|
||||
assert simulated['results'][0]['after_target'] == '00010'
|
||||
|
||||
|
||||
def test_simulate_derivation_keeps_manual_line_no_for_copy_if_empty(app):
|
||||
"""手工 JSON 已含 line_no 时不得先剔除;真实行为应为 target_not_empty 跳过。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_schema.field_rules import DEFAULT_DERIVATION_RULE_ID
|
||||
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
customer_line = service.save_field(
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
line_no = service.save_field(
|
||||
{'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [
|
||||
_config(customer_line['id'], '客户 PO 行号', value_type='string'),
|
||||
_config(line_no['id'], '内部项次', value_type='string'),
|
||||
],
|
||||
'derivation_rules': [{
|
||||
'rule_id': DEFAULT_DERIVATION_RULE_ID,
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
published = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
|
||||
)
|
||||
|
||||
simulated = service.simulate_derivation(
|
||||
published['id'],
|
||||
{
|
||||
'lines': [{
|
||||
'customer_po_line_no': '00010',
|
||||
'line_no': '00010',
|
||||
}],
|
||||
},
|
||||
actor_id=None,
|
||||
)
|
||||
assert simulated['derived_count'] == 0
|
||||
assert simulated['results'][0]['status'] == 'skipped'
|
||||
assert simulated['results'][0]['skip_reason'] == 'target_not_empty'
|
||||
assert simulated['results'][0]['before_target'] == '00010'
|
||||
|
||||
|
||||
def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
"""行级 Reservation 优先,缺失时回退订单头,二者均可选不构成阶段 0 门禁。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
header_reservation = service.save_field(
|
||||
{'field_code': 'reservation_id', 'scope': 'header', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
line_reservation = service.save_field(
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [
|
||||
_config(header_reservation['id'], '订单预约单号', value_type='string'),
|
||||
_config(line_reservation['id'], '行预约单号', value_type='string'),
|
||||
])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = '3000000001\n3000000002'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [{'field_id': header_reservation['id'], 'observations': [{
|
||||
'value': '3000000001', 'document_id': document.id, 'quote': '3000000001',
|
||||
}]}],
|
||||
'lines': [
|
||||
{'fields': []},
|
||||
{'fields': [{'field_id': line_reservation['id'], 'observations': [{
|
||||
'value': '3000000002', 'document_id': document.id, 'quote': '3000000002',
|
||||
}]}]},
|
||||
],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
assert [item['effective_reservation_id'] for item in result['system_line_projections']] == ['3000000001', '3000000002']
|
||||
|
||||
|
||||
def test_dynamic_schema_contract_and_cross_document_persistence(app):
|
||||
"""同一字段在 EML 与 PDF 一致时应 corroborated,并生成类型化值与 field_code 投影。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -1,225 +0,0 @@
|
||||
"""
|
||||
backend/tests/test_shipping_session_pdf_work_item_migration.py
|
||||
|
||||
用途:验收会话 PDF 工作项迁移结构、唯一约束与审计扩展列。
|
||||
依赖:Alembic Operations、SQLite 内存库、3d6e8f0a1b2c 迁移、领域契约词典。
|
||||
逻辑:构造最小前置表后 upgrade;断言同会话同源唯一、当前 Case 唯一、审计哈希列与索引存在。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
from app.models.shipping_audit_event import ShippingAuditEvent
|
||||
from app.models.shipping_session_pdf_work_item import ShippingSessionPdfWorkItem
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_RETENTION_DAYS,
|
||||
MAX_OPEN_SESSION_WORK_ITEMS,
|
||||
SESSION_WORK_ITEM_AUDIT_EVENT_TYPES,
|
||||
SESSION_WORK_ITEM_CLOSED_REASONS,
|
||||
SESSION_WORK_ITEM_LIFECYCLE_STATUSES,
|
||||
)
|
||||
|
||||
|
||||
def _pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""创建工作项外键依赖的最小 stub 表,避免迁移在 SQLite 上因缺表失败。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_notice_documents',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_extraction_runs',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_review_cases',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_audit_events',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('event_type', sa.String(64), nullable=False),
|
||||
sa.Column('aggregate_type', sa.String(64), nullable=False),
|
||||
sa.Column('aggregate_id', sa.String(128), nullable=False),
|
||||
sa.Column('actor_type', sa.String(16), nullable=False),
|
||||
sa.Column('metadata_json', sa.JSON(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_session_work_item_contract_dictionaries_frozen():
|
||||
"""阶段 0 契约词典必须冻结生命周期、关闭原因、审计事件与上限。"""
|
||||
assert SESSION_WORK_ITEM_LIFECYCLE_STATUSES == {
|
||||
'pending_review', 'extracting', 'reparse_failed', 'closed',
|
||||
}
|
||||
assert SESSION_WORK_ITEM_CLOSED_REASONS == {
|
||||
'confirmed', 'non_order', 'user_cancelled', 'admin_terminated',
|
||||
}
|
||||
assert 'session_work_item_created' in SESSION_WORK_ITEM_AUDIT_EVENT_TYPES
|
||||
assert 'document_version_replaced' in SESSION_WORK_ITEM_AUDIT_EVENT_TYPES
|
||||
assert 'document_previous_version_restored' in SESSION_WORK_ITEM_AUDIT_EVENT_TYPES
|
||||
assert MAX_OPEN_SESSION_WORK_ITEMS == 50
|
||||
assert AUDIT_RETENTION_DAYS == 365 * 3
|
||||
|
||||
|
||||
def test_session_work_item_and_audit_models_expose_stage0_columns():
|
||||
"""ORM 必须暴露工作项指针字段与审计会话扩展列。"""
|
||||
work_cols = set(ShippingSessionPdfWorkItem.__table__.columns.keys())
|
||||
for name in (
|
||||
'item_no', 'conversation_id', 'owner_user_id', 'root_document_id',
|
||||
'current_document_id', 'current_run_id', 'current_run_no',
|
||||
'current_case_id', 'current_case_no', 'current_version_no',
|
||||
'lifecycle_status', 'closed_reason', 'closed_at', 'lock_version',
|
||||
):
|
||||
assert name in work_cols
|
||||
|
||||
audit_cols = set(ShippingAuditEvent.__table__.columns.keys())
|
||||
for name in ('session_item_id', 'owner_user_id', 'client_ip_hash', 'user_agent_hash'):
|
||||
assert name in audit_cols
|
||||
|
||||
|
||||
def test_shipping_session_pdf_work_item_migration_structure_and_constraints():
|
||||
"""迁移必须创建工作项表、唯一约束、会话状态索引与审计扩展列。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.3d6e8f0a1b2c_add_shipping_session_pdf_work_items'
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_session_pdf_work_items' in inspector.get_table_names()
|
||||
|
||||
columns = {
|
||||
item['name'] for item in inspector.get_columns('shipping_session_pdf_work_items')
|
||||
}
|
||||
assert {
|
||||
'item_no', 'conversation_id', 'owner_user_id', 'root_document_id',
|
||||
'current_document_id', 'current_run_id', 'current_run_no',
|
||||
'current_case_id', 'current_case_no', 'current_version_no',
|
||||
'lifecycle_status', 'closed_reason', 'closed_at', 'lock_version',
|
||||
} <= columns
|
||||
|
||||
unique_names = {
|
||||
item['name']
|
||||
for item in inspector.get_unique_constraints('shipping_session_pdf_work_items')
|
||||
if item.get('name')
|
||||
}
|
||||
assert 'uq_shipping_session_pdf_work_items_no' in unique_names
|
||||
assert 'uq_shipping_session_pdf_work_items_conversation_root_doc' in unique_names
|
||||
assert 'uq_shipping_session_pdf_work_items_current_case' in unique_names
|
||||
|
||||
indexes = {
|
||||
item['name'] for item in inspector.get_indexes('shipping_session_pdf_work_items')
|
||||
}
|
||||
assert 'ix_shipping_session_pdf_work_items_conversation_lifecycle' in indexes
|
||||
assert 'ix_shipping_session_pdf_work_items_open_conversation' in indexes
|
||||
|
||||
audit_cols = {
|
||||
item['name'] for item in inspector.get_columns('shipping_audit_events')
|
||||
}
|
||||
assert {
|
||||
'session_item_id', 'owner_user_id', 'client_ip_hash', 'user_agent_hash',
|
||||
} <= audit_cols
|
||||
audit_indexes = {
|
||||
item['name'] for item in inspector.get_indexes('shipping_audit_events')
|
||||
}
|
||||
assert 'ix_shipping_audit_events_session_item_created' in audit_indexes
|
||||
assert 'ix_shipping_audit_events_owner_created' in audit_indexes
|
||||
|
||||
# 同会话两个 PDF → 两条工作项;同源重复 → 唯一约束拒绝。
|
||||
connection.execute(sa.text('INSERT INTO users (id) VALUES (1)'))
|
||||
connection.execute(sa.text('INSERT INTO shipping_notice_documents (id) VALUES (101), (102)'))
|
||||
connection.execute(sa.text('INSERT INTO shipping_order_review_cases (id) VALUES (201), (202)'))
|
||||
now = datetime.utcnow().isoformat(sep=' ')
|
||||
connection.execute(
|
||||
sa.text(
|
||||
'INSERT INTO shipping_session_pdf_work_items ('
|
||||
'item_no, conversation_id, owner_user_id, root_document_id, '
|
||||
'current_document_id, current_case_id, current_version_no, '
|
||||
'lifecycle_status, lock_version, created_at, updated_at'
|
||||
') VALUES '
|
||||
"('SPWI-A', 'conv-1', 1, 101, 101, 201, 1, 'pending_review', 1, :now, :now),"
|
||||
"('SPWI-B', 'conv-1', 1, 102, 102, 202, 1, 'pending_review', 1, :now, :now)"
|
||||
),
|
||||
{'now': now},
|
||||
)
|
||||
# SQLite 唯一冲突会使事务进入 aborted;用 SAVEPOINT 隔离断言后继续 downgrade。
|
||||
connection.execute(sa.text('SAVEPOINT sp_dup_root'))
|
||||
with pytest.raises(Exception):
|
||||
connection.execute(
|
||||
sa.text(
|
||||
'INSERT INTO shipping_session_pdf_work_items ('
|
||||
'item_no, conversation_id, owner_user_id, root_document_id, '
|
||||
'current_document_id, current_version_no, lifecycle_status, '
|
||||
'lock_version, created_at, updated_at'
|
||||
') VALUES '
|
||||
"('SPWI-DUP', 'conv-1', 1, 101, 101, 1, 'pending_review', 1, :now, :now)"
|
||||
),
|
||||
{'now': now},
|
||||
)
|
||||
connection.execute(sa.text('ROLLBACK TO SAVEPOINT sp_dup_root'))
|
||||
|
||||
# 同一 Case 不能成为两个工作项的当前有效指针。
|
||||
connection.execute(sa.text('SAVEPOINT sp_dup_case'))
|
||||
with pytest.raises(Exception):
|
||||
connection.execute(
|
||||
sa.text(
|
||||
'INSERT INTO shipping_session_pdf_work_items ('
|
||||
'item_no, conversation_id, owner_user_id, root_document_id, '
|
||||
'current_document_id, current_case_id, current_version_no, '
|
||||
'lifecycle_status, lock_version, created_at, updated_at'
|
||||
') VALUES '
|
||||
"('SPWI-C', 'conv-2', 1, 102, 102, 201, 1, 'pending_review', 1, :now, :now)"
|
||||
),
|
||||
{'now': now},
|
||||
)
|
||||
connection.execute(sa.text('ROLLBACK TO SAVEPOINT sp_dup_case'))
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_session_pdf_work_items' not in inspector.get_table_names()
|
||||
reverted_audit = {
|
||||
item['name'] for item in inspector.get_columns('shipping_audit_events')
|
||||
}
|
||||
assert {
|
||||
'session_item_id', 'owner_user_id', 'client_ip_hash', 'user_agent_hash',
|
||||
}.isdisjoint(reverted_audit)
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def test_stage0_alembic_head_includes_session_work_item_migration():
|
||||
"""迁移链必须包含会话工作项 revision,且其为当前 Alembic head。"""
|
||||
from alembic.config import Config
|
||||
from alembic.script import ScriptDirectory
|
||||
|
||||
config = Config()
|
||||
config.set_main_option('script_location', 'migrations')
|
||||
script = ScriptDirectory.from_config(config)
|
||||
revision = script.get_revision('3d6e8f0a1b2c')
|
||||
assert revision is not None
|
||||
assert revision.down_revision == '2c5d7e9f1a2b'
|
||||
heads = list(script.get_heads())
|
||||
assert '3d6e8f0a1b2c' in heads
|
||||
lineage = [item.revision for item in script.walk_revisions()]
|
||||
assert lineage[0] == '3d6e8f0a1b2c'
|
||||
assert '2c5d7e9f1a2b' in lineage
|
||||
assert '2b4c6d8e0f1a' in lineage
|
||||
@@ -1,739 +0,0 @@
|
||||
"""
|
||||
backend/tests/test_shipping_session_work_items.py
|
||||
|
||||
用途:验收会话 PDF 工作项聚合、重识别成功替换、失败回退与关闭统计。
|
||||
依赖:订单抽取 Run 测试夹具、ensure_run_review_cases、处置/确认服务、工作项投影。
|
||||
逻辑:同会话两 PDF 始终两条工作项;单文件重识别不丢另一项;失败恢复旧入口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingSessionPdfWorkItem,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_disposition_service import (
|
||||
finalize_document_reparse,
|
||||
mark_non_order,
|
||||
reparse_case_document,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import project_session_workbench
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import (
|
||||
close_work_item,
|
||||
get_work_item_by_no,
|
||||
revoke_review_confirmation,
|
||||
terminate_work_item_as_admin,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def _materialized_run(*, user, agent, session, intake):
|
||||
"""显式物化 Plan/Unit,与 Worker 时序一致。"""
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=True,
|
||||
):
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
def _seed_two_pdf_work_items(suffix: str):
|
||||
"""同会话两条工作项:先物化单 PDF Run/Case,再为第二 PDF 直接建工作项。"""
|
||||
user, agent, session, intake, document_a = _seed_run_input(suffix=f'{suffix}-A')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
cases = ensure_run_review_cases(run=run)
|
||||
document_b = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document_a.asset_id,
|
||||
attachment_key=f'file-b-{suffix}',
|
||||
document_type='attachment',
|
||||
filename=f'{suffix}-B.pdf',
|
||||
content_hash=f'hash-b-{suffix}',
|
||||
parse_status='parsed',
|
||||
extracted_text='order b',
|
||||
)
|
||||
db.session.add(document_b)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import ensure_work_item_for_document
|
||||
item_a = ensure_work_item_for_document(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document_a.id),
|
||||
run=run,
|
||||
case=cases[0] if cases else None,
|
||||
)
|
||||
item_b = ensure_work_item_for_document(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document_b.id),
|
||||
run=run,
|
||||
)
|
||||
db.session.commit()
|
||||
return user, agent, session, intake, document_a, document_b, run, cases, item_a, item_b
|
||||
|
||||
|
||||
def test_session_two_pdfs_create_two_stable_work_items(app):
|
||||
"""同会话两个 PDF 生成两条稳定工作项;聚合 API 不依赖最新 Run。"""
|
||||
with app.app_context():
|
||||
user, _agent, session, _intake, document_a, document_b, _run, _cases, _item_a, _item_b = _seed_two_pdf_work_items(
|
||||
'SWI-TWO',
|
||||
)
|
||||
items = ShippingSessionPdfWorkItem.query.filter_by(conversation_id=session.session_id).all()
|
||||
assert len(items) == 2
|
||||
assert {item.root_document_id for item in items} == {document_a.id, document_b.id}
|
||||
|
||||
summary = project_session_workbench(user_id=int(user.id), conversation_id=session.session_id)
|
||||
assert summary['open_count'] == 2
|
||||
assert len(summary['open_items']) == 2
|
||||
|
||||
|
||||
def test_single_pdf_reparse_keeps_sibling_work_item_and_restores_on_failure(app):
|
||||
"""对第一个 PDF 重识别:仍保留两条工作项;失败后恢复旧入口。"""
|
||||
with app.app_context():
|
||||
user, _agent, session, _intake, _document_a, document_b, run, cases, item_a, item_b = _seed_two_pdf_work_items(
|
||||
'SWI-REPARSE',
|
||||
)
|
||||
case_a = cases[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=True,
|
||||
):
|
||||
replacement, reused = reparse_case_document(
|
||||
user_id=user.id, case_no=case_a.case_no, reason='rule_updated',
|
||||
)
|
||||
assert reused is False
|
||||
db.session.refresh(item_a)
|
||||
assert item_a.lifecycle_status == 'extracting'
|
||||
assert ShippingSessionPdfWorkItem.query.filter_by(conversation_id=session.session_id).count() == 2
|
||||
|
||||
finalize_document_reparse(run=replacement, succeeded=False)
|
||||
db.session.refresh(item_a)
|
||||
db.session.refresh(case_a)
|
||||
assert case_a.status == 'unreviewed'
|
||||
assert item_a.lifecycle_status == 'reparse_failed'
|
||||
assert item_a.current_case_no == case_a.case_no
|
||||
db.session.refresh(item_b)
|
||||
assert item_b.root_document_id == document_b.id
|
||||
|
||||
|
||||
def test_reparse_success_switches_current_case_pointer(app):
|
||||
"""重识别成功后新 Case 成为当前可操作版本,旧 Case 不可再确认。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SWI-OK')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).one()
|
||||
old_case_no = case.case_no
|
||||
old_version = int(item.current_version_no)
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=True,
|
||||
):
|
||||
replacement, _ = reparse_case_document(user_id=user.id, case_no=case.case_no, reason='other')
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
ensure_order_extraction_plan(replacement)
|
||||
new_cases = ensure_run_review_cases(run=replacement)
|
||||
db.session.commit()
|
||||
|
||||
db.session.refresh(item)
|
||||
db.session.refresh(case)
|
||||
assert case.status == 'superseded'
|
||||
assert new_cases
|
||||
assert item.current_case_no == new_cases[0].case_no
|
||||
assert item.current_case_no != old_case_no
|
||||
assert int(item.current_version_no) == old_version + 1
|
||||
assert item.lifecycle_status == 'pending_review'
|
||||
|
||||
|
||||
def test_close_and_admin_terminate_require_reason(app):
|
||||
"""用户关闭与管理员终止均写关闭状态;管理员无理由/无二次确认被拒绝。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SWI-CLOSE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).one()
|
||||
|
||||
close_work_item(
|
||||
item=item,
|
||||
closed_reason='user_cancelled',
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
reason='user abort',
|
||||
)
|
||||
db.session.commit()
|
||||
summary = project_session_workbench(user_id=int(user.id), conversation_id=session.session_id)
|
||||
assert summary['closed_count'] == 1
|
||||
assert summary['open_count'] == 0
|
||||
|
||||
# 再建一项测管理员终止门禁
|
||||
item2_doc = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=document.asset_id, attachment_key='file-term',
|
||||
document_type='attachment', filename='term.pdf', content_hash='term-hash',
|
||||
parse_status='parsed', extracted_text='x',
|
||||
)
|
||||
db.session.add(item2_doc)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import ensure_work_item_for_document
|
||||
item2 = ensure_work_item_for_document(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(item2_doc.id),
|
||||
run=run,
|
||||
)
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as missing_reason:
|
||||
terminate_work_item_as_admin(
|
||||
admin_user_id=user.id, item_no=item2.item_no, reason='', confirm_token='CONFIRM_TERMINATE',
|
||||
)
|
||||
assert missing_reason.value.code == 'SHIPPING_NOTICE.ADMIN_REASON_REQUIRED'
|
||||
with pytest.raises(ValidationError) as missing_confirm:
|
||||
terminate_work_item_as_admin(
|
||||
admin_user_id=user.id, item_no=item2.item_no, reason='stop', confirm_token='nope',
|
||||
)
|
||||
assert missing_confirm.value.code == 'SHIPPING_NOTICE.ADMIN_CONFIRM_REQUIRED'
|
||||
|
||||
# 首次终止成功后,重复终止须写幂等审计(result=ignored + already_closed),不得静默吞掉管理操作尝试。
|
||||
from app.models import ShippingAuditEvent
|
||||
terminate_work_item_as_admin(
|
||||
admin_user_id=user.id,
|
||||
item_no=item2.item_no,
|
||||
reason='first terminate',
|
||||
confirm_token='CONFIRM_TERMINATE',
|
||||
)
|
||||
db.session.commit()
|
||||
first_count = ShippingAuditEvent.query.filter_by(
|
||||
aggregate_id=item2.item_no,
|
||||
action='terminate',
|
||||
).count()
|
||||
assert first_count >= 1
|
||||
terminate_work_item_as_admin(
|
||||
admin_user_id=user.id,
|
||||
item_no=item2.item_no,
|
||||
reason='repeat terminate attempt',
|
||||
confirm_token='CONFIRM_TERMINATE',
|
||||
)
|
||||
db.session.commit()
|
||||
idempotent_events = ShippingAuditEvent.query.filter_by(
|
||||
aggregate_id=item2.item_no,
|
||||
action='terminate',
|
||||
result='ignored',
|
||||
).all()
|
||||
assert len(idempotent_events) == 1
|
||||
assert (idempotent_events[0].metadata_json or {}).get('already_closed') is True
|
||||
assert (idempotent_events[0].metadata_json or {}).get('idempotent') is True
|
||||
|
||||
|
||||
def test_admin_revoke_blocks_inventory_matched_and_allows_within_window(app):
|
||||
"""24 小时内且未库存匹配可撤销;已 matched 拒绝并记阻断。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SWI-REVOKE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
task = ShippingTask(
|
||||
task_no='SN-SWI-REVOKE-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
process_status='parsed',
|
||||
lifecycle_status='active',
|
||||
source_type='review_confirmation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = int(task.id)
|
||||
case.confirmed_at = datetime.utcnow()
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).one()
|
||||
item.lifecycle_status = 'closed'
|
||||
item.closed_reason = 'confirmed'
|
||||
item.closed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
# 已库存匹配 → 拒绝
|
||||
task.process_status = 'matched'
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as blocked:
|
||||
revoke_review_confirmation(
|
||||
admin_user_id=user.id,
|
||||
item_no=item.item_no,
|
||||
reason='undo',
|
||||
confirm_token='CONFIRM_REVOKE',
|
||||
)
|
||||
assert blocked.value.code == 'SHIPPING_NOTICE.REVOKE_INVENTORY_MATCHED'
|
||||
|
||||
# 恢复为未匹配并可撤销
|
||||
task.process_status = 'parsed'
|
||||
case.confirmed_at = datetime.utcnow() - timedelta(hours=1)
|
||||
db.session.commit()
|
||||
result = revoke_review_confirmation(
|
||||
admin_user_id=user.id,
|
||||
item_no=item.item_no,
|
||||
reason='undo within window',
|
||||
confirm_token='CONFIRM_REVOKE',
|
||||
)
|
||||
db.session.commit()
|
||||
assert result['revoked'] is True
|
||||
refreshed = get_work_item_by_no(item_no=item.item_no)
|
||||
assert refreshed.lifecycle_status == 'pending_review'
|
||||
|
||||
|
||||
def test_version_history_excludes_other_conversation_same_document(app):
|
||||
"""版本历史不得混入同属主、同 PDF 但不同会话的 Case。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import (
|
||||
list_session_work_item_versions,
|
||||
project_admin_supervision_page,
|
||||
)
|
||||
|
||||
user, agent, session_a, intake_a, document_a = _seed_run_input(suffix='SWI-VER-A')
|
||||
run_a = _materialized_run(user=user, agent=agent, session=session_a, intake=intake_a)
|
||||
case_a = ensure_run_review_cases(run=run_a)[0]
|
||||
item_a = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case_a.id).one()
|
||||
|
||||
# 同属主第二会话 + 第二份 PDF,再把 Case 的 document_id 改成与 A 相同以制造污染面。
|
||||
session_b = ChatSession(
|
||||
session_id=f'{session_a.session_id}-B',
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
title='other conversation',
|
||||
)
|
||||
db.session.add(session_b)
|
||||
db.session.flush()
|
||||
asset_b = FileAsset(
|
||||
asset_no='FA-SWI-VER-B',
|
||||
owner_user_id=user.id,
|
||||
original_filename='orders-b.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/orders-b.pdf',
|
||||
content_hash=('b' * 64),
|
||||
file_size=100,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset_b)
|
||||
db.session.flush()
|
||||
intake_b = ShippingNoticeIntake(
|
||||
intake_no='SNI-SWI-VER-B',
|
||||
asset_id=asset_b.id,
|
||||
user_id=user.id,
|
||||
conversation_id=session_b.session_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text='root text b',
|
||||
expires_at=datetime.utcnow() + timedelta(hours=1),
|
||||
)
|
||||
db.session.add(intake_b)
|
||||
db.session.flush()
|
||||
document_b = ShippingNoticeDocument(
|
||||
intake_id=intake_b.id,
|
||||
asset_id=asset_b.id,
|
||||
attachment_key='file-b',
|
||||
document_type='attachment',
|
||||
filename='orders-b.pdf',
|
||||
content_hash=('b' * 64),
|
||||
parse_status='parsed',
|
||||
extracted_text='order b',
|
||||
)
|
||||
db.session.add(document_b)
|
||||
db.session.flush()
|
||||
run_b = _materialized_run(user=user, agent=agent, session=session_b, intake=intake_b)
|
||||
case_b = ensure_run_review_cases(run=run_b)[0]
|
||||
case_b.document_id = int(document_a.id)
|
||||
db.session.commit()
|
||||
|
||||
versions = list_session_work_item_versions(item=item_a)
|
||||
case_nos = {row['case_no'] for row in versions}
|
||||
assert case_a.case_no in case_nos
|
||||
# 关键断言:即使 document_id 相同,异会话 Case 也不得进入本工作项版本谱系。
|
||||
assert case_b.case_no not in case_nos
|
||||
|
||||
admin_page = project_admin_supervision_page(owner_user_id=int(user.id), page=1, page_size=50)
|
||||
admin_item = next(
|
||||
(row for row in admin_page['items'] if row['item_no'] == item_a.item_no),
|
||||
None,
|
||||
)
|
||||
assert admin_item is not None
|
||||
assert 'admin_terminate' in admin_item['available_actions']
|
||||
|
||||
|
||||
def test_mark_quality_issue_and_draft_write_unified_audit(app):
|
||||
"""质量问题与草稿字段变更均写入统一审计,草稿含 request 关联与前后值。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_quality_issue
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_header_field
|
||||
from flask import g
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='SWI-AUD')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json or {})
|
||||
schema = dict(snapshot.get('schema') or {})
|
||||
definition = dict(schema.get('definition') or {})
|
||||
definition['fields'] = [
|
||||
{
|
||||
'field_id': 'po-id',
|
||||
'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
'required': False,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': [],
|
||||
},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
flag_modified(run, 'input_snapshot_json')
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-BEFORE'}]}],
|
||||
'lines': [],
|
||||
}],
|
||||
}
|
||||
flag_modified(unit, 'result_json')
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
|
||||
mark_quality_issue(user_id=int(user.id), case_no=case.case_no, reason='blurred', comment='soft scan')
|
||||
db.session.commit()
|
||||
quality_events = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_marked_quality_issue',
|
||||
aggregate_id=case.case_no,
|
||||
).all()
|
||||
assert len(quality_events) == 1
|
||||
assert quality_events[0].action == 'mark_quality_issue'
|
||||
|
||||
case.status = 'draft'
|
||||
db.session.commit()
|
||||
g.request_id = 'req-draft-audit-1'
|
||||
draft_version = int(case.current_draft.draft_version)
|
||||
patch_header_field(
|
||||
user_id=int(user.id),
|
||||
case_no=case.case_no,
|
||||
field_id='po-id',
|
||||
value='PO-AFTER',
|
||||
expected_draft_version=draft_version,
|
||||
)
|
||||
db.session.commit()
|
||||
draft_events = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_draft_changed',
|
||||
aggregate_id=case.case_no,
|
||||
).order_by(ShippingAuditEvent.id.desc()).all()
|
||||
assert draft_events
|
||||
latest = draft_events[0]
|
||||
assert latest.request_id == 'req-draft-audit-1'
|
||||
assert latest.operation_id == 'req-draft-audit-1'
|
||||
before = latest.before_snapshot_json or {}
|
||||
after = latest.after_snapshot_json or {}
|
||||
assert before.get('field_id') == 'po-id'
|
||||
assert before.get('previous_value') == 'PO-BEFORE'
|
||||
assert after.get('new_value') == 'PO-AFTER'
|
||||
|
||||
|
||||
def test_version_history_keeps_intermediate_replacement_docs_and_labels(app):
|
||||
"""多次替换后中间 Document Case 仍在版本历史,且 Vn 与 current_version_no 对齐。"""
|
||||
with app.app_context():
|
||||
from app.models import (
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderReviewCase,
|
||||
)
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import (
|
||||
list_session_work_item_versions,
|
||||
)
|
||||
|
||||
user, agent, session, intake, document_a = _seed_run_input(suffix='SWI-MID')
|
||||
run1 = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case1 = ensure_run_review_cases(run=run1)[0]
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case1.id).one()
|
||||
plan = ShippingOrderExtractionPlan.query.filter_by(run_id=int(run1.id)).one()
|
||||
plan_id = int(plan.id)
|
||||
|
||||
document_b = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document_a.asset_id,
|
||||
attachment_key='replace-b',
|
||||
document_type='attachment',
|
||||
filename='replace-b.pdf',
|
||||
content_hash=('m' * 64),
|
||||
parse_status='parsed',
|
||||
extracted_text='order mid',
|
||||
)
|
||||
document_c = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document_a.asset_id,
|
||||
attachment_key='replace-c',
|
||||
document_type='attachment',
|
||||
filename='replace-c.pdf',
|
||||
content_hash=('n' * 64),
|
||||
parse_status='parsed',
|
||||
extracted_text='order latest',
|
||||
)
|
||||
db.session.add_all([document_b, document_c])
|
||||
db.session.flush()
|
||||
|
||||
unit2 = ShippingOrderExtractionUnit(
|
||||
plan_id=plan_id,
|
||||
intake_id=int(intake.id),
|
||||
document_id=int(document_b.id),
|
||||
position=2,
|
||||
unit_type='document_extraction',
|
||||
document_type='attachment',
|
||||
status='candidate_ready',
|
||||
)
|
||||
unit3 = ShippingOrderExtractionUnit(
|
||||
plan_id=plan_id,
|
||||
intake_id=int(intake.id),
|
||||
document_id=int(document_c.id),
|
||||
position=3,
|
||||
unit_type='document_extraction',
|
||||
document_type='attachment',
|
||||
status='candidate_ready',
|
||||
)
|
||||
db.session.add_all([unit2, unit3])
|
||||
db.session.flush()
|
||||
|
||||
run2 = ShippingOrderExtractionRun(
|
||||
run_no=f'{run1.run_no}-R2',
|
||||
user_id=int(run1.user_id),
|
||||
owner_agent_id=int(run1.owner_agent_id),
|
||||
parser_engine_version=run1.parser_engine_version,
|
||||
parser_policy_version=run1.parser_policy_version,
|
||||
auto_freeze_policy_json=dict(run1.auto_freeze_policy_json or {}),
|
||||
conversation_id=str(run1.conversation_id),
|
||||
schema_version_id=int(run1.schema_version_id),
|
||||
input_snapshot_hash=f'hash-mid-r2-{(run1.input_snapshot_hash or "h")}'[:64],
|
||||
input_snapshot_json={
|
||||
**dict(run1.input_snapshot_json or {}),
|
||||
'review_reparse': {'document_id': int(document_b.id), 'source_case_no': case1.case_no},
|
||||
},
|
||||
idempotency_key=f'idem-mid-r2-{run1.id}-{document_b.id}'[:64],
|
||||
status='completed',
|
||||
reparse_of_run_id=int(run1.id),
|
||||
)
|
||||
db.session.add(run2)
|
||||
db.session.flush()
|
||||
case2 = ShippingOrderReviewCase(
|
||||
case_no=f'{case1.case_no}-V2',
|
||||
run_id=int(run2.id),
|
||||
unit_id=int(unit2.id),
|
||||
document_id=int(document_b.id),
|
||||
owner_user_id=int(user.id),
|
||||
status='superseded',
|
||||
current_draft_id=case1.current_draft_id,
|
||||
)
|
||||
db.session.add(case2)
|
||||
db.session.flush()
|
||||
|
||||
run3 = ShippingOrderExtractionRun(
|
||||
run_no=f'{run1.run_no}-R3',
|
||||
user_id=int(run1.user_id),
|
||||
owner_agent_id=int(run1.owner_agent_id),
|
||||
parser_engine_version=run1.parser_engine_version,
|
||||
parser_policy_version=run1.parser_policy_version,
|
||||
auto_freeze_policy_json=dict(run1.auto_freeze_policy_json or {}),
|
||||
conversation_id=str(run1.conversation_id),
|
||||
schema_version_id=int(run1.schema_version_id),
|
||||
input_snapshot_hash=f'hash-mid-r3-{(run1.input_snapshot_hash or "h")}'[:64],
|
||||
input_snapshot_json={
|
||||
**dict(run1.input_snapshot_json or {}),
|
||||
'review_reparse': {'document_id': int(document_c.id), 'source_case_no': case2.case_no},
|
||||
},
|
||||
idempotency_key=f'idem-mid-r3-{run1.id}-{document_c.id}'[:64],
|
||||
status='completed',
|
||||
reparse_of_run_id=int(run2.id),
|
||||
)
|
||||
db.session.add(run3)
|
||||
db.session.flush()
|
||||
case3 = ShippingOrderReviewCase(
|
||||
case_no=f'{case1.case_no}-V3',
|
||||
run_id=int(run3.id),
|
||||
unit_id=int(unit3.id),
|
||||
document_id=int(document_c.id),
|
||||
owner_user_id=int(user.id),
|
||||
status='draft',
|
||||
current_draft_id=case1.current_draft_id,
|
||||
)
|
||||
db.session.add(case3)
|
||||
db.session.flush()
|
||||
case1.status = 'superseded'
|
||||
item.current_run_id = int(run3.id)
|
||||
item.current_run_no = run3.run_no
|
||||
item.current_case_id = int(case3.id)
|
||||
item.current_case_no = case3.case_no
|
||||
item.current_document_id = int(document_c.id)
|
||||
item.current_version_no = 3
|
||||
db.session.commit()
|
||||
|
||||
versions = list_session_work_item_versions(item=item)
|
||||
by_case = {row['case_no']: row for row in versions}
|
||||
# 关键断言:中间替换文档 B 不得因“仅根/当前文档过滤”而丢失。
|
||||
assert set(by_case) == {case1.case_no, case2.case_no, case3.case_no}
|
||||
assert by_case[case1.case_no]['version_label'] == 'V1'
|
||||
assert by_case[case2.case_no]['version_label'] == 'V2'
|
||||
assert by_case[case3.case_no]['version_label'] == 'V3'
|
||||
assert by_case[case3.case_no]['is_current'] is True
|
||||
|
||||
|
||||
def test_mark_non_order_always_writes_case_unified_audit(app):
|
||||
"""标记非订单必须写 Case 级统一审计(含状态/处置前后快照),不依赖工作项是否存在。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_non_order
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='SWI-NO')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
# 删除工作项,模拟尚未绑定或历史数据。
|
||||
ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).delete()
|
||||
db.session.commit()
|
||||
|
||||
previous = case.status
|
||||
mark_non_order(user_id=int(user.id), case_no=case.case_no, reason='duplicate_file', comment='dup pdf')
|
||||
db.session.commit()
|
||||
events = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_marked_non_order',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=case.case_no,
|
||||
).all()
|
||||
assert len(events) == 1
|
||||
assert events[0].action == 'mark_non_order'
|
||||
assert events[0].reason_code == 'duplicate_file'
|
||||
before = events[0].before_snapshot_json or {}
|
||||
after = events[0].after_snapshot_json or {}
|
||||
assert before.get('status') == previous
|
||||
assert after.get('status') == 'non_order'
|
||||
assert after.get('disposition') == 'duplicate_file'
|
||||
|
||||
|
||||
def test_mark_quality_issue_other_requires_comment(app):
|
||||
"""原因码 other 时备注为空必须拒绝,保证审计可复盘业务理由。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_quality_issue
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='SWI-QO')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as missing_comment:
|
||||
mark_quality_issue(user_id=int(user.id), case_no=case.case_no, reason='other', comment=' ')
|
||||
assert missing_comment.value.code == 'SHIPPING.REVIEW_QUALITY_COMMENT_REQUIRED'
|
||||
|
||||
|
||||
def test_confirm_review_case_always_writes_case_unified_audit(app):
|
||||
"""确认建单必须写 Case 级统一审计,即使工作项已删除仍可追溯操作人与前后快照。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingAuditEvent, ShippingNoticeCandidate, ShippingOrderReviewConfirmedRevision
|
||||
from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_header_field
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SWI-CFM')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
schema = dict(snapshot['schema'])
|
||||
definition = dict(schema['definition'])
|
||||
definition['fields'] = [
|
||||
{'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', 'required': False, 'normalizer_key': 'trim', 'validator_keys': []},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
|
||||
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-CFM'}]}], 'lines': [{'fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '2'}]},
|
||||
{'field_id': 'reservation-id', 'observations': [{'value': '3000092999'}]},
|
||||
]}]}]}
|
||||
db.session.add(ShippingNoticeCandidate(
|
||||
candidate_no='CAND-SWI-CFM', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='machine-cfm', order_extraction_run_id=run.id, structured_result_json={'machine': 'ok'},
|
||||
))
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).delete()
|
||||
db.session.commit()
|
||||
validated = patch_header_field(
|
||||
user_id=user.id, case_no=case.case_no, field_id='po-id', value='PO-CONFIRMED', expected_draft_version=1,
|
||||
)
|
||||
db.session.commit()
|
||||
previous = case.status
|
||||
result = confirm_review_case(
|
||||
user_id=user.id,
|
||||
case_no=case.case_no,
|
||||
expected_draft_version=validated['draft']['draft_version'],
|
||||
idempotency_key='swi-confirm-audit-1',
|
||||
warning_acknowledgements=[{'code': 'manual_checked'}],
|
||||
)
|
||||
db.session.commit()
|
||||
events = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_confirmed',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=case.case_no,
|
||||
).all()
|
||||
# 关键断言:无工作项时仍有 Case 级确认审计,含前后状态与 task 关联。
|
||||
assert len(events) == 1
|
||||
assert events[0].action == 'confirm_review_case'
|
||||
assert events[0].actor_id == str(user.id)
|
||||
assert events[0].task_no == result['task_no']
|
||||
before = events[0].before_snapshot_json or {}
|
||||
after = events[0].after_snapshot_json or {}
|
||||
assert before.get('status') == previous
|
||||
assert after.get('status') == 'confirmed'
|
||||
assert after.get('confirmed_task_no') == result['task_no']
|
||||
assert ShippingOrderReviewConfirmedRevision.query.filter_by(case_id=case.id).count() == 1
|
||||
|
||||
|
||||
def test_audit_query_access_audit_is_strict(app, monkeypatch):
|
||||
"""审计中心查询访问审计失败时必须阻断,不得继续返回敏感结果。"""
|
||||
with app.app_context():
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice import audit_query_service
|
||||
from app.services.shipping_notice.audit_query_service import list_shipping_audit_events
|
||||
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError('audit table down')
|
||||
|
||||
monkeypatch.setattr(audit_query_service, 'append_shipping_audit_event', _boom)
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
list_shipping_audit_events(admin_user_id=1, request_id='req-strict', page=1, page_size=10)
|
||||
assert exc.value.code == 'SHIPPING_NOTICE.AUDIT_PERSIST_FAILED'
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
tests/test_shipping_stp_audit_detail_and_strict.py
|
||||
|
||||
用途:验证 STP 任务事件双写审计保留操作明细、自动建单 strict,以及操作人身份传递。
|
||||
依赖:tool_common.log_task_event、fulfillment_workflow._event_actor_id、相关源码静态检查。
|
||||
逻辑:mock record_fulfillment_audit 断言 metadata;确认/重匹配路径须保留用户 actor。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice import tool_common as tool_common_mod
|
||||
|
||||
|
||||
def test_log_task_event_dual_write_keeps_match_detail(monkeypatch):
|
||||
"""matched_multi_source 双写须把 resolved_ok_source_codes / match_status 写入 metadata。"""
|
||||
captured: dict = {}
|
||||
|
||||
def _fake_audit(**kwargs):
|
||||
captured.update(kwargs)
|
||||
|
||||
monkeypatch.setattr(tool_common_mod.db.session, 'add', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(tool_common_mod.db.session, 'flush', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
_fake_audit,
|
||||
)
|
||||
|
||||
task = SimpleNamespace(
|
||||
id=1,
|
||||
task_no='T-STP-1',
|
||||
process_status='pending_review',
|
||||
)
|
||||
tool_common_mod.log_task_event(
|
||||
task,
|
||||
'matched_multi_source_excel_block',
|
||||
{
|
||||
'match_status': 'fulfillable',
|
||||
'resolved_ok_source_codes': ['DBS_DUB', 'DBS_RTM'],
|
||||
'reason_code': 'multi_source_excel_block',
|
||||
'attempts': 2,
|
||||
},
|
||||
actor_id=7,
|
||||
source='workspace_api',
|
||||
)
|
||||
assert captured.get('strict') is True
|
||||
meta = captured.get('metadata') or {}
|
||||
assert meta.get('dual_write') == 'shipping_task_event'
|
||||
assert meta.get('match_status') == 'fulfillable'
|
||||
assert meta.get('resolved_ok_source_codes') == ['DBS_DUB', 'DBS_RTM']
|
||||
assert meta.get('reason_code') == 'multi_source_excel_block'
|
||||
assert meta.get('attempt_count') == 2
|
||||
|
||||
|
||||
def test_stp_auto_create_audits_are_strict():
|
||||
"""自动建单成功/失败审计不得使用 strict=False。"""
|
||||
source = Path(tool_common_mod.__file__).resolve().parents[0] / 'order_stp_auto_create_service.py'
|
||||
text = source.read_text(encoding='utf-8')
|
||||
assert "event_type='stp_auto_create'" in text
|
||||
assert "event_type='stp_auto_create_failed'" in text
|
||||
# 两处 record_fulfillment_audit 均须 strict=True;禁止残留 strict=False。
|
||||
assert 'strict=False' not in text
|
||||
assert text.count('strict=True') >= 2
|
||||
|
||||
|
||||
def test_event_actor_id_accepts_trusted_user_id():
|
||||
"""工作台 _trusted_user_id 必须解析为匹配/审计操作人。"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import _event_actor_id
|
||||
|
||||
assert _event_actor_id({'_trusted_user_id': 42}) == 42
|
||||
assert _event_actor_id({'operator_id': 7, '_trusted_user_id': 42}) == 7
|
||||
assert _event_actor_id({'actor_id': '9'}) == 9
|
||||
assert _event_actor_id({}) is None
|
||||
|
||||
|
||||
def test_confirm_inventory_source_passes_actor_to_match():
|
||||
"""多源恢复确认后调用 match_inventory 时须携带操作人,不得只传 _trusted_user_id。"""
|
||||
source = Path(tool_common_mod.__file__).resolve().parents[0] / 'inventory_rpa_workflow.py'
|
||||
text = source.read_text(encoding='utf-8')
|
||||
# 普通确认路径须把 actor_id/source 传给 log_task_event。
|
||||
assert 'actor_id=confirmed_by' in text
|
||||
assert "source='workspace_api' if confirmed_by else 'system'" in text
|
||||
# 多源恢复后重匹配须显式传 operator_id / actor_id。
|
||||
assert '"operator_id": trusted_uid' in text or "'operator_id': trusted_uid" in text
|
||||
assert '"actor_id": trusted_uid' in text or "'actor_id': trusted_uid" in text
|
||||
|
||||
|
||||
def test_stp_auto_create_failed_commit_must_raise():
|
||||
"""失败审计 commit 异常不得被吞掉后继续下一 Case。"""
|
||||
source = Path(tool_common_mod.__file__).resolve().parents[0] / 'order_stp_auto_create_service.py'
|
||||
text = source.read_text(encoding='utf-8')
|
||||
assert 'stp_auto_create_failed' in text
|
||||
# 禁止仅 rollback 后静默继续:须在 except 分支 raise。
|
||||
failed_block_start = text.find("event_type='stp_auto_create_failed'")
|
||||
assert failed_block_start > 0
|
||||
failed_block = text[failed_block_start:failed_block_start + 1200]
|
||||
assert 'db.session.rollback()' in failed_block
|
||||
assert 'raise' in failed_block
|
||||
|
||||
|
||||
def test_tool_payload_strips_forged_actor_fields(app):
|
||||
"""Tool API 请求体中的操作人字段必须被剥离,不得进入服务层。"""
|
||||
from app.api.shipping_notice_tools import _payload
|
||||
|
||||
with app.test_request_context(
|
||||
'/api/shipping-notice/tools/confirm_inventory_source',
|
||||
method='POST',
|
||||
json={
|
||||
'task_id': 'T1',
|
||||
'source_code': 'DBS_DUB',
|
||||
'_trusted_user_id': 999,
|
||||
'operator_id': 888,
|
||||
'actor_id': 777,
|
||||
'keep_me': 'yes',
|
||||
},
|
||||
):
|
||||
cleaned = _payload()
|
||||
assert cleaned.get('task_id') == 'T1'
|
||||
assert cleaned.get('source_code') == 'DBS_DUB'
|
||||
assert cleaned.get('keep_me') == 'yes'
|
||||
assert '_trusted_user_id' not in cleaned
|
||||
assert 'operator_id' not in cleaned
|
||||
assert 'actor_id' not in cleaned
|
||||
@@ -0,0 +1,69 @@
|
||||
"""
|
||||
tests/test_shipping_stp_match_completed_gate.py
|
||||
|
||||
用途:验证 STP Excel 门禁仅在全部明细 ok 时通过。
|
||||
依赖:fulfillment_workflow.match_completed。
|
||||
逻辑:partial / 混合状态不得制单;fulfillable 且全 ok 可通过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed
|
||||
|
||||
|
||||
def test_match_completed_rejects_partial():
|
||||
"""partial 即使存在 ok 行也不得进入 Excel。"""
|
||||
task = SimpleNamespace(
|
||||
match_status='partial',
|
||||
line_results_json=[
|
||||
{'line_status': 'ok'},
|
||||
{'line_status': 'shortage'},
|
||||
],
|
||||
)
|
||||
assert match_completed(task) is False
|
||||
|
||||
|
||||
def test_match_completed_requires_all_ok_fulfillable():
|
||||
"""fulfillable 且全部 ok 才允许制单。"""
|
||||
ok = SimpleNamespace(
|
||||
match_status='fulfillable',
|
||||
line_results_json=[{'line_status': 'ok'}, {'disposition': 'ok'}],
|
||||
)
|
||||
mixed = SimpleNamespace(
|
||||
match_status='fulfillable',
|
||||
line_results_json=[{'line_status': 'ok'}, {'line_status': 'not_found'}],
|
||||
)
|
||||
assert match_completed(ok) is True
|
||||
assert match_completed(mixed) is False
|
||||
|
||||
|
||||
def test_match_step_progress_partial_is_needs_human_not_100():
|
||||
"""partial 不得写成 completed/100%,进度按 ok 占比封顶 99。"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import _match_step_progress_fields
|
||||
|
||||
fields = _match_step_progress_fields(
|
||||
match_status='partial',
|
||||
line_results=[
|
||||
{'line_status': 'ok'},
|
||||
{'line_status': 'shortage'},
|
||||
],
|
||||
lang='zh-CN',
|
||||
)
|
||||
assert fields['status'] == 'needs_human'
|
||||
assert fields['progress_percent'] == 50
|
||||
assert fields['progress_percent'] < 100
|
||||
|
||||
|
||||
def test_match_step_progress_fulfillable_is_completed_100():
|
||||
"""全部可履约时才 completed + 100%。"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import _match_step_progress_fields
|
||||
|
||||
fields = _match_step_progress_fields(
|
||||
match_status='fulfillable',
|
||||
line_results=[{'line_status': 'ok'}, {'line_status': 'ok'}],
|
||||
lang='zh-CN',
|
||||
)
|
||||
assert fields['status'] == 'completed'
|
||||
assert fields['progress_percent'] == 100
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
tests/test_shipping_stp_multi_source_recovery.py
|
||||
|
||||
用途:验证多源/多文件冲突人工指定库存源恢复与强制源过滤。
|
||||
依赖:stp_line_inventory_match。
|
||||
逻辑:覆盖 recovery 候选汇总、forced_match 过滤;不启 Flask 全链路。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
apply_forced_match_source_filter,
|
||||
multi_source_recovery_source_codes,
|
||||
needs_multi_source_manual_recovery,
|
||||
)
|
||||
|
||||
|
||||
def test_recovery_codes_from_resolved_ok_sources():
|
||||
"""multi_source_excel_block 时优先取 resolved_ok_source_codes。"""
|
||||
task = SimpleNamespace(
|
||||
step_payload_json={
|
||||
'multi_source_excel_block': True,
|
||||
'resolved_ok_source_codes': ['DBS_DUB', 'DBS_RTM'],
|
||||
},
|
||||
)
|
||||
assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
|
||||
assert needs_multi_source_manual_recovery(task) is True
|
||||
|
||||
|
||||
def test_recovery_codes_from_multi_file_conflict_candidates():
|
||||
"""无 resolved_ok 时汇总 multi_file_conflict 行的 candidate_hit_source_codes。"""
|
||||
task = SimpleNamespace(
|
||||
step_payload_json={
|
||||
'line_inventory_resolutions': [
|
||||
{
|
||||
'disposition': 'multi_file_conflict',
|
||||
'candidate_hit_source_codes': ['DBS_DUB', 'DBS_RTM'],
|
||||
},
|
||||
],
|
||||
},
|
||||
)
|
||||
assert multi_source_recovery_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
|
||||
assert needs_multi_source_manual_recovery(task) is True
|
||||
|
||||
|
||||
def test_forced_match_source_filter_keeps_only_selected_source():
|
||||
"""人工指定源后仅保留该源库存行,消除跨源冲突输入。"""
|
||||
task = SimpleNamespace(
|
||||
inventory_source_code='DBS_DUB',
|
||||
step_payload_json={'forced_match_source_code': 'DBS_DUB'},
|
||||
)
|
||||
filtered = apply_forced_match_source_filter(
|
||||
[
|
||||
{'part_number': 'PN-1', '__source_code': 'DBS_DUB', 'qty': '5'},
|
||||
{'part_number': 'PN-1', '__source_code': 'DBS_RTM', 'qty': '8'},
|
||||
{'part_number': 'PN-2', '__source_code': 'DBS_DUB', 'qty': '1'},
|
||||
],
|
||||
task=task,
|
||||
)
|
||||
assert len(filtered) == 2
|
||||
assert all(row['__source_code'] == 'DBS_DUB' for row in filtered)
|
||||
|
||||
|
||||
def test_forced_match_filter_noop_without_source_tags():
|
||||
"""库存行无 __source_code 时不过滤,保持旧单源路径兼容。"""
|
||||
task = SimpleNamespace(
|
||||
inventory_source_code='DBS_DUB',
|
||||
step_payload_json={'forced_match_source_code': 'DBS_DUB'},
|
||||
)
|
||||
rows = [{'part_number': 'PN-1', 'qty': '5'}]
|
||||
assert apply_forced_match_source_filter(rows, task=task) == rows
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
tests/test_shipping_stp_phase3_auto_create.py
|
||||
|
||||
用途:验证 STP 阶段 3 建单冻结库存候选、多候选稳定门禁与自动建单跳过人工改脏。
|
||||
依赖:stp_inventory_freeze、inventory_source_gate、order_stp_auto_create_service。
|
||||
逻辑:单测不依赖完整抽取 Run;覆盖冻结语义与草稿改脏判定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import _draft_has_manual_edits
|
||||
from app.services.shipping_notice.stp_inventory_freeze import (
|
||||
collect_frozen_candidate_codes,
|
||||
freeze_stp_inventory_candidates_on_task,
|
||||
task_frozen_inventory_source_codes,
|
||||
)
|
||||
|
||||
|
||||
def test_collect_frozen_candidate_codes_dedupes_and_preserves_order():
|
||||
"""多行候选合并去重且保持首次出现顺序。"""
|
||||
codes = collect_frozen_candidate_codes([
|
||||
{'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM']},
|
||||
{'candidate_inventory_source_codes': ['DBS_RTM', 'DBS_FRA']},
|
||||
])
|
||||
assert codes == ['DBS_DUB', 'DBS_RTM', 'DBS_FRA']
|
||||
|
||||
|
||||
def test_draft_has_manual_edits_detects_header_and_line(app):
|
||||
"""header 或 line 任一 manual 覆盖即视为需显式确认。"""
|
||||
clean = SimpleNamespace(
|
||||
current_draft=SimpleNamespace(
|
||||
header_values_json={'values': {'po': {'value': 'P1', 'source': 'machine'}}},
|
||||
lines_json=[{'values': {'part': {'value': 'A', 'source': 'machine'}}}],
|
||||
)
|
||||
)
|
||||
dirty_header = SimpleNamespace(
|
||||
current_draft=SimpleNamespace(
|
||||
header_values_json={'values': {'po': {'value': 'P2', 'source': 'manual'}}},
|
||||
lines_json=[],
|
||||
)
|
||||
)
|
||||
dirty_line = SimpleNamespace(
|
||||
current_draft=SimpleNamespace(
|
||||
header_values_json={'values': {}},
|
||||
lines_json=[{'values': {'qty': {'value': '3', 'source': 'manual'}}}],
|
||||
)
|
||||
)
|
||||
assert _draft_has_manual_edits(clean) is False
|
||||
assert _draft_has_manual_edits(dirty_header) is True
|
||||
assert _draft_has_manual_edits(dirty_line) is True
|
||||
|
||||
|
||||
def test_freeze_single_candidate_marks_resolved(app, monkeypatch):
|
||||
"""单候选冻结后任务库存源为 resolved 且门禁稳定。"""
|
||||
from app.services.shipping_notice import inventory_source_gate as gate_mod
|
||||
from app.services.shipping_notice import stp_inventory_freeze as freeze_mod
|
||||
|
||||
monkeypatch.setattr(
|
||||
freeze_mod,
|
||||
'get_database_inventory_source',
|
||||
lambda code: {
|
||||
'source_code': code,
|
||||
'display_name': code,
|
||||
'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'fixed',
|
||||
'fixed_warehouse_id': 'WH1',
|
||||
} if code == 'DBS_DUB' else None,
|
||||
)
|
||||
monkeypatch.setattr(freeze_mod, 'inventory_sources_runtime_version', lambda: 'cfg-v1')
|
||||
monkeypatch.setattr(freeze_mod, 'extract_routing_context', lambda _task: {'destination_code': None})
|
||||
monkeypatch.setattr(freeze_mod, 'compute_routing_fingerprint', lambda _ctx: 'fp-1')
|
||||
monkeypatch.setattr(gate_mod, 'extract_routing_context', lambda _task: {'destination_code': None})
|
||||
monkeypatch.setattr(gate_mod, 'compute_routing_fingerprint', lambda _ctx: 'fp-1')
|
||||
monkeypatch.setattr(gate_mod, 'inventory_sources_runtime_version', lambda: 'cfg-v1')
|
||||
monkeypatch.setattr(
|
||||
gate_mod,
|
||||
'get_database_inventory_source',
|
||||
lambda code: {
|
||||
'source_code': code,
|
||||
'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'fixed',
|
||||
'fixed_warehouse_id': 'WH1',
|
||||
},
|
||||
)
|
||||
|
||||
task = SimpleNamespace(
|
||||
inventory_source_status=None,
|
||||
inventory_source_code=None,
|
||||
inventory_connector_type=None,
|
||||
inventory_warehouse_id=None,
|
||||
inventory_source_method=None,
|
||||
inventory_source_config_version=None,
|
||||
inventory_routing_fingerprint=None,
|
||||
step_payload_json={},
|
||||
destination_code=None,
|
||||
destination_city=None,
|
||||
destination_country=None,
|
||||
warehouse_hint=None,
|
||||
inventory_source_confirmed_by=None,
|
||||
inventory_source_confirmed_at=None,
|
||||
current_order_extraction_id=None,
|
||||
)
|
||||
result = freeze_stp_inventory_candidates_on_task(
|
||||
task,
|
||||
line_projections=[{
|
||||
'line_key': 'L1',
|
||||
'candidate_inventory_source_codes': ['DBS_DUB'],
|
||||
'selection_mode': 'rule',
|
||||
'routing_status': 'resolved',
|
||||
'matched_rule_ids': [1],
|
||||
}],
|
||||
)
|
||||
assert result.status == 'resolved'
|
||||
assert task.inventory_source_status == 'resolved'
|
||||
assert task.inventory_source_code == 'DBS_DUB'
|
||||
assert task_frozen_inventory_source_codes(task) == ['DBS_DUB']
|
||||
assert is_inventory_source_stable(task) is True
|
||||
|
||||
|
||||
def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch):
|
||||
"""多候选冻结为 candidates_frozen,无唯一 source_code 仍可通过稳定门禁。"""
|
||||
from app.services.shipping_notice import inventory_source_gate as gate_mod
|
||||
from app.services.shipping_notice import stp_inventory_freeze as freeze_mod
|
||||
|
||||
def _source(code):
|
||||
return {
|
||||
'source_code': code,
|
||||
'display_name': code,
|
||||
'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'dynamic',
|
||||
'fixed_warehouse_id': None,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(freeze_mod, 'get_database_inventory_source', _source)
|
||||
monkeypatch.setattr(freeze_mod, 'inventory_sources_runtime_version', lambda: 'cfg-v2')
|
||||
monkeypatch.setattr(freeze_mod, 'extract_routing_context', lambda _task: {})
|
||||
monkeypatch.setattr(freeze_mod, 'compute_routing_fingerprint', lambda _ctx: 'fp-2')
|
||||
monkeypatch.setattr(gate_mod, 'extract_routing_context', lambda _task: {})
|
||||
monkeypatch.setattr(gate_mod, 'compute_routing_fingerprint', lambda _ctx: 'fp-2')
|
||||
monkeypatch.setattr(gate_mod, 'inventory_sources_runtime_version', lambda: 'cfg-v2')
|
||||
monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source)
|
||||
|
||||
task = SimpleNamespace(
|
||||
inventory_source_status=None,
|
||||
inventory_source_code=None,
|
||||
inventory_connector_type=None,
|
||||
inventory_warehouse_id=None,
|
||||
inventory_source_method=None,
|
||||
inventory_source_config_version=None,
|
||||
inventory_routing_fingerprint=None,
|
||||
step_payload_json={},
|
||||
destination_code=None,
|
||||
destination_city=None,
|
||||
destination_country=None,
|
||||
warehouse_hint=None,
|
||||
inventory_source_confirmed_by=None,
|
||||
inventory_source_confirmed_at=None,
|
||||
current_order_extraction_id=None,
|
||||
)
|
||||
result = freeze_stp_inventory_candidates_on_task(
|
||||
task,
|
||||
line_projections=[{
|
||||
'line_key': 'L1',
|
||||
'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'],
|
||||
'selection_mode': 'rule',
|
||||
'routing_status': 'ambiguous',
|
||||
'matched_rule_ids': [9],
|
||||
}],
|
||||
)
|
||||
assert result.status == 'candidates_frozen'
|
||||
assert task.inventory_source_status == 'candidates_frozen'
|
||||
assert not task.inventory_source_code
|
||||
assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
|
||||
assert is_inventory_source_stable(task) is True
|
||||
@@ -0,0 +1,281 @@
|
||||
"""
|
||||
tests/test_shipping_stp_phase4_line_inventory_match.py
|
||||
|
||||
用途:验证 STP 阶段 4 跨候选库存匹配与导出行序号注入。
|
||||
依赖:stp_line_inventory_match、export._mapping_value。
|
||||
逻辑:覆盖唯一命中、多文件冲突、短缺与 Excel export_sequence / order_field line_no。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.export import _mapping_value
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
apply_line_inventory_resolutions,
|
||||
match_order_lines_across_candidates,
|
||||
)
|
||||
|
||||
|
||||
def test_cross_candidate_unique_hit_is_fulfillable():
|
||||
"""唯一候选文件命中且数量充足 → fulfillable 并冻结源。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
order_lines=[{
|
||||
'part_number': 'PN-1',
|
||||
'reservation_id': '3000092917',
|
||||
'quantity': '3',
|
||||
}],
|
||||
inventory_lines=[{
|
||||
'reservation_id': '3000092917',
|
||||
'part_number': 'PN-1',
|
||||
'qty': '10',
|
||||
'__source_code': 'DBS_DUB',
|
||||
'__inventory_file_no': 'INV-1',
|
||||
}],
|
||||
)
|
||||
assert result['match_status'] == 'fulfillable'
|
||||
assert result['line_results'][0]['disposition'] == 'ok'
|
||||
assert result['resolutions'][0]['resolved_inventory_source_code'] == 'DBS_DUB'
|
||||
|
||||
|
||||
def test_cross_candidate_multi_file_conflict():
|
||||
"""同一 Reservation+PN 出现在两个候选文件 → multi_file_conflict。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
order_lines=[{
|
||||
'part_number': 'PN-1',
|
||||
'reservation_id': '3000092917',
|
||||
'quantity': '1',
|
||||
}],
|
||||
inventory_lines=[
|
||||
{'reservation_id': '3000092917', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'DBS_DUB'},
|
||||
{'reservation_id': '3000092917', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'DBS_RTM'},
|
||||
],
|
||||
)
|
||||
assert result['match_status'] == 'unfulfillable'
|
||||
assert result['line_results'][0]['disposition'] == 'multi_file_conflict'
|
||||
|
||||
|
||||
def test_cross_candidate_shortage_and_not_found():
|
||||
"""数量不足与未命中分别标记 shortage / not_found。"""
|
||||
shortage = match_order_lines_across_candidates(
|
||||
order_lines=[{'part_number': 'PN-1', 'reservation_id': '3000092917', 'quantity': '9'}],
|
||||
inventory_lines=[{
|
||||
'reservation_id': '3000092917', 'part_number': 'PN-1', 'qty': '2', '__source_code': 'DBS_DUB',
|
||||
}],
|
||||
)
|
||||
assert shortage['line_results'][0]['disposition'] == 'shortage'
|
||||
missing = match_order_lines_across_candidates(
|
||||
order_lines=[{'part_number': 'PN-2', 'reservation_id': '3000092918', 'quantity': '1'}],
|
||||
inventory_lines=[{
|
||||
'reservation_id': '3000092917', 'part_number': 'PN-1', 'qty': '2', '__source_code': 'DBS_DUB',
|
||||
}],
|
||||
)
|
||||
assert missing['line_results'][0]['disposition'] == 'not_found'
|
||||
|
||||
|
||||
def test_header_reservation_fallback_for_match():
|
||||
"""行缺 Reservation 时可回退头级有效 Reservation。"""
|
||||
result = match_order_lines_across_candidates(
|
||||
order_lines=[{'part_number': 'PN-1', 'reservation_id': None, 'quantity': '1'}],
|
||||
inventory_lines=[{
|
||||
'reservation_id': '3000092917', 'part_number': 'PN-1', 'qty': '1', '__source_code': 'DBS_DUB',
|
||||
}],
|
||||
header_reservation_id='3000092917',
|
||||
)
|
||||
assert result['match_status'] == 'fulfillable'
|
||||
assert result['resolutions'][0]['effective_reservation_id'] == '3000092917'
|
||||
|
||||
|
||||
def test_apply_resolutions_sets_summary_source_when_unique(monkeypatch):
|
||||
"""全部 ok 且唯一源时投影 task.inventory_source_code。"""
|
||||
from app.services.shipping_notice import stp_line_inventory_match as mod
|
||||
|
||||
monkeypatch.setattr(
|
||||
mod,
|
||||
'get_database_inventory_source',
|
||||
lambda code: {
|
||||
'source_code': code,
|
||||
'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'fixed',
|
||||
'fixed_warehouse_id': 'WH1',
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(mod, 'inventory_sources_runtime_version', lambda: 'v1')
|
||||
monkeypatch.setattr(mod, 'extract_routing_context', lambda _task: {})
|
||||
monkeypatch.setattr(mod, 'compute_routing_fingerprint', lambda _ctx: 'fp')
|
||||
|
||||
task = SimpleNamespace(
|
||||
step_payload_json={},
|
||||
match_status=None,
|
||||
line_results_json=None,
|
||||
shortage_json=None,
|
||||
inventory_source_code=None,
|
||||
inventory_connector_type=None,
|
||||
inventory_warehouse_id=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
inventory_source_method=None,
|
||||
inventory_source_config_version=None,
|
||||
inventory_routing_fingerprint=None,
|
||||
)
|
||||
apply_line_inventory_resolutions(task, {
|
||||
'match_status': 'fulfillable',
|
||||
'line_results': [{'line_status': 'ok'}],
|
||||
'shortage_json': {'lines': []},
|
||||
'resolutions': [{
|
||||
'disposition': 'ok',
|
||||
'resolved_inventory_source_code': 'DBS_DUB',
|
||||
}],
|
||||
})
|
||||
assert task.inventory_source_code == 'DBS_DUB'
|
||||
assert task.inventory_source_status == 'resolved'
|
||||
assert task.step_payload_json['line_inventory_resolutions'][0]['resolved_inventory_source_code'] == 'DBS_DUB'
|
||||
|
||||
|
||||
def test_apply_resolutions_allows_multi_source_excel(monkeypatch):
|
||||
"""多行命中不同源且全部 ok 时投影主绑定源并允许制单,不写 multi_source_excel_block。"""
|
||||
from app.services.shipping_notice import stp_line_inventory_match as mod
|
||||
|
||||
monkeypatch.setattr(
|
||||
mod,
|
||||
'get_database_inventory_source',
|
||||
lambda code: {
|
||||
'source_code': code,
|
||||
'connector_type': 'excel_rpa',
|
||||
'warehouse_resolution_mode': 'fixed',
|
||||
'fixed_warehouse_id': 'WH1',
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(mod, 'inventory_sources_runtime_version', lambda: 'v1')
|
||||
monkeypatch.setattr(mod, 'extract_routing_context', lambda _task: {})
|
||||
monkeypatch.setattr(mod, 'compute_routing_fingerprint', lambda _ctx: 'fp')
|
||||
task = SimpleNamespace(
|
||||
step_payload_json={},
|
||||
match_status=None,
|
||||
line_results_json=None,
|
||||
shortage_json=None,
|
||||
inventory_source_code=None,
|
||||
inventory_connector_type=None,
|
||||
inventory_warehouse_id=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
inventory_source_method=None,
|
||||
inventory_source_config_version=None,
|
||||
inventory_routing_fingerprint=None,
|
||||
)
|
||||
apply_line_inventory_resolutions(task, {
|
||||
'match_status': 'fulfillable',
|
||||
'line_results': [{'line_status': 'ok'}, {'line_status': 'ok'}],
|
||||
'shortage_json': {'lines': []},
|
||||
'resolutions': [
|
||||
{'disposition': 'ok', 'resolved_inventory_source_code': 'DBS_DUB'},
|
||||
{'disposition': 'ok', 'resolved_inventory_source_code': 'DBS_RTM'},
|
||||
],
|
||||
})
|
||||
assert task.inventory_source_code in {'DBS_DUB', 'DBS_RTM'}
|
||||
assert task.inventory_source_status == 'resolved'
|
||||
assert task.inventory_source_method == 'stp_line_match_multi'
|
||||
assert task.step_payload_json.get('multi_source_excel_block') is None
|
||||
assert set(task.step_payload_json.get('resolved_ok_source_codes') or []) == {'DBS_DUB', 'DBS_RTM'}
|
||||
|
||||
|
||||
def test_excel_mapping_keeps_user_configured_line_number():
|
||||
"""export_sequence 输出导出行序号,订单字段 line_no 保留内部项次原文值。"""
|
||||
task = SimpleNamespace(
|
||||
task_no='T1',
|
||||
shipping_case=None,
|
||||
inventory_warehouse_id='WH1',
|
||||
inventory_source_code='DBS_DUB',
|
||||
)
|
||||
value = _mapping_value(
|
||||
{'source_kind': 'system_fact', 'source_key': 'export_sequence', 'formatter': 'none'},
|
||||
task=task,
|
||||
order_values={'__export_sequence': 2, 'customer_po_line_no': '00020'},
|
||||
inventory_values={},
|
||||
export_sequence=2,
|
||||
)
|
||||
assert value == 2
|
||||
order_field_value = _mapping_value(
|
||||
{'source_kind': 'order_field', 'source_key': 'line_no', 'formatter': 'none', 'row_mode': 'line'},
|
||||
task=task,
|
||||
order_values={'__export_sequence': 3, 'line_no': '00030'},
|
||||
inventory_values={},
|
||||
export_sequence=3,
|
||||
)
|
||||
assert order_field_value == '00030'
|
||||
|
||||
|
||||
def test_allowed_system_facts_use_export_sequence_not_line_no():
|
||||
"""Phase 0 门禁:系统事实目录含 export_sequence,不含 line_no。"""
|
||||
from app.services.shipping_notice.excel_template import ALLOWED_SYSTEM_FACTS
|
||||
|
||||
assert 'export_sequence' in ALLOWED_SYSTEM_FACTS
|
||||
assert 'line_no' not in ALLOWED_SYSTEM_FACTS
|
||||
|
||||
|
||||
def test_default_derivation_rules_are_disabled_copy_if_empty():
|
||||
"""新草稿预置 customer_po_line_no→line_no,默认关闭。"""
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
default_derivation_rules,
|
||||
normalize_derivation_rules,
|
||||
)
|
||||
|
||||
rules = default_derivation_rules()
|
||||
assert rules == [{
|
||||
'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO',
|
||||
'enabled': False,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}]
|
||||
assert normalize_derivation_rules(None) == rules
|
||||
|
||||
|
||||
def test_derivation_engine_copy_if_empty_and_skips():
|
||||
"""启用规则时空值派生、非空跳过、非法格式跳过。"""
|
||||
from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines
|
||||
|
||||
rules = [{
|
||||
'rule_id': 'R1',
|
||||
'enabled': True,
|
||||
'source_field_code': 'customer_po_line_no',
|
||||
'target_field_code': 'line_no',
|
||||
'strategy': 'copy_if_empty',
|
||||
'scope': 'line',
|
||||
}]
|
||||
outcome = apply_derivation_rules_to_lines(
|
||||
[
|
||||
{'customer_po_line_no': '00010', 'line_no': None},
|
||||
{'customer_po_line_no': '00020', 'line_no': '20'},
|
||||
{'customer_po_line_no': 'ABC', 'line_no': None},
|
||||
],
|
||||
rules,
|
||||
)
|
||||
assert outcome['lines'][0]['line_no'] == '00010'
|
||||
assert outcome['lines'][1]['line_no'] == '20'
|
||||
assert outcome['lines'][2].get('line_no') in (None, '')
|
||||
assert [item['status'] for item in outcome['results']] == ['derived', 'skipped', 'skipped']
|
||||
assert outcome['results'][1]['skip_reason'] == 'target_not_empty'
|
||||
assert outcome['results'][2]['skip_reason'] == 'source_format_invalid'
|
||||
|
||||
|
||||
def test_permanent_audit_events_have_no_retention_expiry(app):
|
||||
"""货代统一审计账本新写入事件永久保留(retention_expires_at 为空)。"""
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.models import ShippingAuditEvent
|
||||
from app import db
|
||||
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='DERIVATION_SIMULATED',
|
||||
aggregate_type='shipping_order_schema_version',
|
||||
aggregate_id='1',
|
||||
actor_type='admin',
|
||||
actor_id=1,
|
||||
result='success',
|
||||
metadata={'derived_count': 1, 'skipped_count': 0},
|
||||
)
|
||||
db.session.commit()
|
||||
stored = db.session.get(ShippingAuditEvent, event.id)
|
||||
assert stored is not None
|
||||
assert stored.retention_expires_at is None
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
tests/test_shipping_stp_phase5_progress_ui.py
|
||||
|
||||
用途:验证 STP 阶段 5 进度契约与审计双写前缀。
|
||||
依赖:stp_progress_contract、tool_common.log_task_event。
|
||||
逻辑:契约键稳定;STP 事件进入双写前缀集合。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.stp_progress_contract import (
|
||||
STP_AUDIT_DUAL_WRITE_PREFIXES,
|
||||
STP_FACTS_ALLOWED_KEYS,
|
||||
STP_TASK_EVENT_TYPES,
|
||||
)
|
||||
|
||||
|
||||
def test_stp_progress_contract_contains_phase4_events():
|
||||
"""阶段 4/5 关键事件码必须进入契约集合。"""
|
||||
assert 'candidates_frozen' in STP_TASK_EVENT_TYPES
|
||||
assert 'matched_stp_candidates' in STP_TASK_EVENT_TYPES
|
||||
assert 'matched_multi_source_excel_block' in STP_TASK_EVENT_TYPES
|
||||
assert 'multi_source_excel_block' in STP_FACTS_ALLOWED_KEYS
|
||||
assert 'frozen_candidate_codes' in STP_FACTS_ALLOWED_KEYS
|
||||
assert 'recovery_source_codes' in STP_FACTS_ALLOWED_KEYS
|
||||
|
||||
|
||||
def test_stp_audit_dual_write_prefixes_cover_match_events():
|
||||
"""matched_stp* / candidates_frozen 须能触发审计双写前缀匹配。"""
|
||||
samples = [
|
||||
'matched_stp_candidates',
|
||||
'matched_multi_source_excel_block',
|
||||
'candidates_frozen',
|
||||
'stp_auto_create',
|
||||
'inventory_candidate_files_missing',
|
||||
]
|
||||
for event_name in samples:
|
||||
assert any(
|
||||
event_name.startswith(prefix) or event_name == prefix
|
||||
for prefix in STP_AUDIT_DUAL_WRITE_PREFIXES
|
||||
), event_name
|
||||
@@ -121,6 +121,7 @@ def test_unknown_upload_result_hides_retry_and_requires_reconciliation(app):
|
||||
|
||||
state = resolve_task_ui_state(task)
|
||||
assert state.checkpoint == 'upload_result_unknown'
|
||||
# 结果未知时禁止 RPA 重试,允许下载 Excel + 人工凭据/回执登记收口。
|
||||
assert state.human_options == ['refresh', 'download_excel', 'mark_manual_uploaded']
|
||||
assert 'retry_upload' not in state.human_options
|
||||
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
|
||||
|
||||
@@ -0,0 +1,596 @@
|
||||
"""
|
||||
backend/tests/test_shipping_workflow_ledger.py
|
||||
|
||||
用途:验收 Workflow 账本写服务(批次边界、幂等建项、取消、事件序号、状态迁移、Case 门禁)。
|
||||
依赖:app fixture、_seed_run_input、workflow_ledger_service、可选 review 物化夹具。
|
||||
逻辑:重开对话 ensure_open_workflow 复用;新上传 create_workflow / ensure_workflow_items_for_run
|
||||
同会话产生不同 workflow_no;重识别留在同一 Workflow;建项在 Case 前即存在;
|
||||
取消必填理由;seq_no 单调;末项关闭后父 Workflow 收敛为 completed;
|
||||
撤销确认可恢复 completed→open;transition / Case 门禁覆盖关键写路径。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeWorkflow,
|
||||
ShippingNoticeWorkflowEvent,
|
||||
ShippingNoticeWorkflowItem,
|
||||
ShippingNoticeWorkflowItemVersion,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderReviewCase,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
ensure_workflow_items_for_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
append_workflow_event,
|
||||
assert_case_is_current_workflow_version,
|
||||
cancel_workflow_item_for_user,
|
||||
create_workflow,
|
||||
ensure_open_workflow,
|
||||
ensure_workflow_item_for_document,
|
||||
transition_item_status,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def _materialized_run(*, user, agent, session, intake):
|
||||
"""显式物化 Plan/Unit,与 Worker 时序一致,便于绑定 Case。"""
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=True,
|
||||
):
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
def test_ensure_open_workflow_reuses_same_conversation(app):
|
||||
"""同会话再次 ensure_open_workflow 必须复用未关闭批次,不新建(重开对话路径)。"""
|
||||
with app.app_context():
|
||||
user, agent, session, _intake, _document = _seed_run_input(suffix='WF-REUSE')
|
||||
first = ensure_open_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
)
|
||||
db.session.commit()
|
||||
second = ensure_open_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:重开对话查询路径同 conversation 仅复用一条 open Workflow。
|
||||
assert first.id == second.id
|
||||
assert first.workflow_no == second.workflow_no
|
||||
assert ShippingNoticeWorkflow.query.filter_by(
|
||||
conversation_id=session.session_id,
|
||||
status='open',
|
||||
).count() == 1
|
||||
|
||||
|
||||
def test_create_workflow_always_creates_new_batch(app):
|
||||
"""create_workflow 始终新建,即使会话已有 open Workflow。"""
|
||||
with app.app_context():
|
||||
user, agent, session, _intake, _document = _seed_run_input(suffix='WF-CREATE')
|
||||
first = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
)
|
||||
db.session.commit()
|
||||
second = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:两次新上传批次边界产生两个不同 workflow_no。
|
||||
assert first.id != second.id
|
||||
assert first.workflow_no != second.workflow_no
|
||||
assert ShippingNoticeWorkflow.query.filter_by(
|
||||
conversation_id=session.session_id,
|
||||
status='open',
|
||||
).count() == 2
|
||||
|
||||
|
||||
def test_successive_ensure_workflow_items_for_run_create_distinct_workflows(app):
|
||||
"""同会话两次新上传 ensure_workflow_items_for_run 必须产生两个不同 Workflow。"""
|
||||
with app.app_context():
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import ShippingOrderExtractionRunIntake
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WF-BATCH1')
|
||||
run1 = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
items1 = ensure_workflow_items_for_run(run1, stage_when_ready='queued')
|
||||
db.session.commit()
|
||||
assert items1
|
||||
wf1_no = items1[0].workflow_no
|
||||
|
||||
# 释放第一 Run 对 Intake 的占用,模拟第一批已结束但仍 open 的 Workflow。
|
||||
run1.status = 'review_required'
|
||||
for link in ShippingOrderExtractionRunIntake.query.filter_by(run_id=int(run1.id)).all():
|
||||
link.released_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
# 第二份上传:同会话新 Document + 新 Run。
|
||||
document2 = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-WF-BATCH2.pdf',
|
||||
filename='orders-WF-BATCH2.pdf',
|
||||
content_hash=('c' * 64),
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO C',
|
||||
)
|
||||
db.session.add(document2)
|
||||
db.session.flush()
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=False,
|
||||
):
|
||||
run2, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
# 强制第二 Run 快照指向第二份 PDF,避免与第一 Run 共用 Document。
|
||||
snapshot = dict(run2.input_snapshot_json or {})
|
||||
docs = list(snapshot.get('documents') or [])
|
||||
if docs:
|
||||
docs[0] = {**docs[0], 'id': int(document2.id), 'filename': document2.filename}
|
||||
snapshot['documents'] = docs
|
||||
else:
|
||||
snapshot['documents'] = [{'id': int(document2.id), 'filename': document2.filename}]
|
||||
run2.input_snapshot_json = snapshot
|
||||
db.session.flush()
|
||||
items2 = ensure_workflow_items_for_run(run2, stage_when_ready='queued')
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:两次上传批次独立,即使第一批仍 open。
|
||||
assert items2
|
||||
assert items2[0].workflow_no != wf1_no
|
||||
assert ShippingNoticeWorkflow.query.filter_by(
|
||||
conversation_id=session.session_id,
|
||||
status='open',
|
||||
).count() >= 2
|
||||
|
||||
|
||||
def test_reparse_stays_on_same_workflow(app):
|
||||
"""重识别后继 Run 复用原 Item 所属 Workflow,不 create_workflow。"""
|
||||
with app.app_context():
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import ShippingOrderExtractionRunIntake
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WF-REPARSE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
# ensure_run_review_cases → bind_cases_for_run 会为本 Run create_workflow 并建 Item。
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
item = ShippingNoticeWorkflowItem.query.filter_by(current_case_id=int(case.id)).one()
|
||||
original_workflow_no = item.workflow_no
|
||||
original_item_id = item.id
|
||||
original_workflow_id = int(item.workflow_id)
|
||||
|
||||
# 来源 Run 须终态且释放 Intake,才允许重识别。
|
||||
run.status = 'review_required'
|
||||
for link in ShippingOrderExtractionRunIntake.query.filter_by(run_id=int(run.id)).all():
|
||||
link.released_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=False,
|
||||
):
|
||||
successor, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
reparse_of_run=run,
|
||||
selected_document_id=int(document.id),
|
||||
reparse_case_no=case.case_no,
|
||||
)
|
||||
ensure_order_extraction_plan(successor)
|
||||
db.session.commit()
|
||||
|
||||
successor_items = ensure_workflow_items_for_run(successor, stage_when_ready='extracting')
|
||||
db.session.commit()
|
||||
assert successor_items
|
||||
assert successor_items[0].id == original_item_id
|
||||
assert successor_items[0].workflow_no == original_workflow_no
|
||||
|
||||
successor_case = ensure_run_review_cases(run=successor)[0]
|
||||
db.session.refresh(item)
|
||||
assert item.workflow_no == original_workflow_no
|
||||
assert int(item.current_version_no) >= 2 or item.current_case_id == int(successor_case.id)
|
||||
assert ShippingNoticeWorkflowItem.query.filter_by(
|
||||
conversation_id=session.session_id,
|
||||
root_document_id=int(document.id),
|
||||
workflow_id=original_workflow_id,
|
||||
).count() == 1
|
||||
|
||||
|
||||
def test_ensure_workflow_item_creates_version_before_case_and_is_idempotent(app):
|
||||
"""识别前即可建 Item+Version1;同 root_document 二次调用幂等。"""
|
||||
with app.app_context():
|
||||
user, agent, session, _intake, document = _seed_run_input(suffix='WF-ITEM')
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
actor_type='system',
|
||||
actor_id=user.id,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:尚无 Case 时生命周期为 queued,且 Version 1 已存在。
|
||||
assert item.lifecycle_status == 'queued'
|
||||
assert item.current_case_id is None
|
||||
assert item.current_version_no == 1
|
||||
versions = ShippingNoticeWorkflowItemVersion.query.filter_by(workflow_item_id=int(item.id)).all()
|
||||
assert len(versions) == 1
|
||||
assert versions[0].version_no == 1
|
||||
assert versions[0].is_current is True
|
||||
|
||||
again = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
actor_type='system',
|
||||
actor_id=user.id,
|
||||
)
|
||||
db.session.commit()
|
||||
# 关键断言:同源 Document 不重复建 Item。
|
||||
assert again.id == item.id
|
||||
assert ShippingNoticeWorkflowItem.query.filter_by(
|
||||
workflow_id=int(workflow.id),
|
||||
root_document_id=int(document.id),
|
||||
).count() == 1
|
||||
|
||||
|
||||
def test_ensure_workflow_item_with_run_enters_extracting(app):
|
||||
"""绑定 Run 且无 Case 时 Item 生命周期为 extracting。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WF-EXTRACT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
run=run,
|
||||
actor_type='system',
|
||||
actor_id=user.id,
|
||||
)
|
||||
db.session.commit()
|
||||
# 关键断言:有 Run 无 Case → extracting。
|
||||
assert item.lifecycle_status == 'extracting'
|
||||
assert item.current_run_no == run.run_no
|
||||
|
||||
|
||||
def test_cancel_workflow_item_requires_reason_and_closes(app):
|
||||
"""用户取消必须提供理由;成功后 Item 关闭且 closed_reason=user_cancelled。"""
|
||||
with app.app_context():
|
||||
user, _agent, session, _intake, document = _seed_run_input(suffix='WF-CANCEL')
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
db.session.commit()
|
||||
item_no = item.item_no
|
||||
|
||||
with pytest.raises(ValidationError) as missing:
|
||||
cancel_workflow_item_for_user(user_id=int(user.id), item_no=item_no, reason=' ')
|
||||
# 关键断言:空理由拒绝,且独立提交拒绝审计后抛错。
|
||||
assert missing.value.code == 'SHIPPING_NOTICE.WORKFLOW_ITEM_CLOSE_REASON_REQUIRED'
|
||||
|
||||
closed = cancel_workflow_item_for_user(
|
||||
user_id=int(user.id),
|
||||
item_no=item_no,
|
||||
reason='user no longer needs this pdf',
|
||||
)
|
||||
db.session.commit()
|
||||
assert closed.lifecycle_status == 'closed'
|
||||
assert closed.closed_reason == 'user_cancelled'
|
||||
assert closed.closed_at is not None
|
||||
# 关键断言:末项关闭后父 Workflow 必须 completed,不得继续被 ensure_open 复用。
|
||||
parent = ShippingNoticeWorkflow.query.get(int(closed.workflow_id))
|
||||
assert parent is not None
|
||||
assert parent.status == 'completed'
|
||||
assert parent.closed_at is not None
|
||||
next_batch = ensure_open_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
)
|
||||
db.session.commit()
|
||||
assert next_batch.id != parent.id
|
||||
assert next_batch.status == 'open'
|
||||
|
||||
|
||||
def test_close_last_workflow_item_completes_parent_workflow(app):
|
||||
"""关闭 Workflow 下最后一个开放 Item 后,父批次收敛为 completed。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.workflow_ledger_service import close_workflow_item
|
||||
|
||||
user, _agent, session, _intake, document = _seed_run_input(suffix='WF-COMPLETE')
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
db.session.commit()
|
||||
assert workflow.status == 'open'
|
||||
|
||||
close_workflow_item(
|
||||
item=item,
|
||||
closed_reason='confirmed',
|
||||
actor_type='system',
|
||||
actor_id='tester',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
refreshed = ShippingNoticeWorkflow.query.get(int(workflow.id))
|
||||
assert refreshed is not None
|
||||
assert refreshed.status == 'completed'
|
||||
assert refreshed.current_stage == 'closed'
|
||||
assert refreshed.closed_at is not None
|
||||
assert ShippingNoticeWorkflowEvent.query.filter_by(
|
||||
workflow_id=int(workflow.id),
|
||||
event_code='workflow_completed',
|
||||
).count() >= 1
|
||||
|
||||
|
||||
def test_reopen_item_restores_completed_parent_workflow(app):
|
||||
"""父批次 completed 后撤销确认,须恢复 status=open 以便继续写入。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
close_workflow_item,
|
||||
reopen_workflow_item_pending_review,
|
||||
)
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WF-REOPEN')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
item = ShippingNoticeWorkflowItem.query.filter_by(current_case_id=int(case.id)).one()
|
||||
workflow_id = int(item.workflow_id)
|
||||
close_workflow_item(
|
||||
item=item,
|
||||
closed_reason='confirmed',
|
||||
actor_type='system',
|
||||
actor_id='tester',
|
||||
)
|
||||
db.session.commit()
|
||||
assert ShippingNoticeWorkflow.query.get(workflow_id).status == 'completed'
|
||||
|
||||
reopen_workflow_item_pending_review(
|
||||
item=item,
|
||||
case=case,
|
||||
actor_type='admin',
|
||||
actor_id=int(user.id),
|
||||
reason='revoke for correction',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
refreshed = ShippingNoticeWorkflow.query.get(workflow_id)
|
||||
assert refreshed is not None
|
||||
assert refreshed.status == 'open'
|
||||
assert refreshed.closed_at is None
|
||||
assert item.lifecycle_status == 'pending_review'
|
||||
assert ShippingNoticeWorkflowEvent.query.filter_by(
|
||||
workflow_id=workflow_id,
|
||||
event_code='workflow_reopened',
|
||||
).count() >= 1
|
||||
reused = ensure_open_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
)
|
||||
assert reused.id == refreshed.id
|
||||
|
||||
|
||||
def test_append_workflow_event_seq_no_is_monotonic(app):
|
||||
"""同一 Workflow 内用户可见事件 seq_no 必须单调 1,2,3…"""
|
||||
with app.app_context():
|
||||
user, _agent, session, _intake, document = _seed_run_input(suffix='WF-SEQ')
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
e1 = append_workflow_event(
|
||||
workflow=workflow,
|
||||
item=item,
|
||||
event_code='probe_one',
|
||||
actor_type='system',
|
||||
actor_id='tester',
|
||||
)
|
||||
e2 = append_workflow_event(
|
||||
workflow=workflow,
|
||||
item=item,
|
||||
event_code='probe_two',
|
||||
actor_type='system',
|
||||
actor_id='tester',
|
||||
)
|
||||
e3 = append_workflow_event(
|
||||
workflow=workflow,
|
||||
item=item,
|
||||
event_code='probe_three',
|
||||
actor_type='system',
|
||||
actor_id='tester',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:本批三条连续递增,且全表 seq 从 1 起无空洞。
|
||||
assert [e1.seq_no, e2.seq_no, e3.seq_no] == [e1.seq_no, e1.seq_no + 1, e1.seq_no + 2]
|
||||
seqs = [
|
||||
row.seq_no
|
||||
for row in ShippingNoticeWorkflowEvent.query
|
||||
.filter_by(workflow_id=int(workflow.id))
|
||||
.order_by(ShippingNoticeWorkflowEvent.seq_no.asc())
|
||||
.all()
|
||||
]
|
||||
assert seqs == list(range(1, len(seqs) + 1))
|
||||
|
||||
|
||||
def test_transition_item_status_updates_lifecycle(app):
|
||||
"""transition_item_status 更新 lifecycle / stage 并递增 lock_version。"""
|
||||
with app.app_context():
|
||||
user, _agent, session, _intake, document = _seed_run_input(suffix='WF-TRANS')
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
db.session.commit()
|
||||
before_lock = int(item.lock_version or 1)
|
||||
|
||||
updated = transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status='layout_parsing',
|
||||
actor_type='system',
|
||||
actor_id=user.id,
|
||||
expected_from='queued',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:状态迁移成功且乐观锁递增。
|
||||
assert updated.lifecycle_status == 'layout_parsing'
|
||||
assert updated.current_stage == 'layout_parsing'
|
||||
assert int(updated.lock_version) == before_lock + 1
|
||||
|
||||
|
||||
def test_assert_case_is_current_workflow_version_rejects_closed_and_superseded(app):
|
||||
"""当前 Case 门禁:已关闭 Item 拒绝;被新版本替代的旧 Case 拒绝。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WF-CASE-GATE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
item = ShippingNoticeWorkflowItem.query.filter_by(current_case_id=int(case.id)).one()
|
||||
db.session.commit()
|
||||
|
||||
# 当前有效 Case 应通过。
|
||||
assert_case_is_current_workflow_version(case=case)
|
||||
|
||||
cancel_workflow_item_for_user(
|
||||
user_id=int(user.id),
|
||||
item_no=item.item_no,
|
||||
reason='close for gate test',
|
||||
)
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as closed_err:
|
||||
assert_case_is_current_workflow_version(case=case)
|
||||
# 关键断言:已关闭 Item 上的 Case 不可再写。
|
||||
assert closed_err.value.code == 'SHIPPING_NOTICE.WORKFLOW_ITEM_CLOSED'
|
||||
|
||||
# [STEP] 恢复 Item 为开放,并构造「同 root_document、非当前指针」的 stale Case。
|
||||
item.lifecycle_status = 'pending_review'
|
||||
item.closed_reason = None
|
||||
item.closed_at = None
|
||||
item.current_case_id = int(case.id)
|
||||
item.current_case_no = case.case_no
|
||||
item.root_document_id = int(document.id)
|
||||
|
||||
document_b = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-WF-CASE-GATE-B.pdf',
|
||||
filename='orders-WF-CASE-GATE-B.pdf',
|
||||
content_hash=('b' * 64),
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO B',
|
||||
)
|
||||
db.session.add(document_b)
|
||||
db.session.flush()
|
||||
unit_b = ShippingOrderExtractionUnit(
|
||||
plan_id=int(run.extraction_plan.id),
|
||||
intake_id=int(intake.id),
|
||||
document_id=int(document_b.id),
|
||||
unit_type='document_extraction',
|
||||
document_type='attachment',
|
||||
content_hash=document_b.content_hash,
|
||||
position=2,
|
||||
status='pending',
|
||||
)
|
||||
db.session.add(unit_b)
|
||||
db.session.flush()
|
||||
# stale.document_id 指向 Item.root,以便 find_item_by_root 命中 sibling。
|
||||
stale_case = ShippingOrderReviewCase(
|
||||
case_no=f'{case.case_no}-STALE',
|
||||
run_id=int(run.id),
|
||||
unit_id=int(unit_b.id),
|
||||
document_id=int(document.id),
|
||||
owner_user_id=int(user.id),
|
||||
status='superseded',
|
||||
)
|
||||
db.session.add(stale_case)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as superseded_err:
|
||||
assert_case_is_current_workflow_version(case=stale_case)
|
||||
# 关键断言:非当前指针 Case 被判定为已替代。
|
||||
assert superseded_err.value.code == 'SHIPPING_NOTICE.WORKFLOW_ITEM_SUPERSEDED'
|
||||
@@ -0,0 +1,201 @@
|
||||
"""
|
||||
backend/tests/test_shipping_workflow_progress_projection.py
|
||||
|
||||
用途:验收 Workflow 进度投影 DTO 与会话开放批次查询。
|
||||
依赖:app fixture、_seed_run_input、workflow_ledger_service、workflow_progress_projection。
|
||||
逻辑:建 Item 后 counts/serialize 正确;project_conversation_workflows 返回全部 open Workflow;
|
||||
Item DTO 含 PDF 文件名。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
create_workflow,
|
||||
ensure_workflow_item_for_document,
|
||||
transition_item_status,
|
||||
)
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflowEvent
|
||||
from app.services.shipping_notice.workflow_progress_projection import (
|
||||
get_workflow_for_user,
|
||||
get_workflow_item_dto_for_user,
|
||||
project_conversation_workflows,
|
||||
serialize_workflow,
|
||||
serialize_workflow_event,
|
||||
serialize_workflow_item,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_serialize_workflow_counts_and_items(app):
|
||||
"""serialize_workflow 汇总 total/processing/pending_review 等计数。"""
|
||||
with app.app_context():
|
||||
user, agent, session, _intake, document = _seed_run_input(suffix='WFP-CNT')
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status='layout_parsing',
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
payload = serialize_workflow(workflow, user_id=int(user.id), include_items=True)
|
||||
# 关键断言:layout_parsing 计入 processing,items 非空。
|
||||
assert payload['workflow_no'] == workflow.workflow_no
|
||||
assert payload['counts']['total'] == 1
|
||||
assert payload['counts']['processing'] == 1
|
||||
assert payload['counts']['pending_review'] == 0
|
||||
assert payload['counts']['waiting_manual_upload'] == 0
|
||||
assert len(payload['items']) == 1
|
||||
assert payload['items'][0]['lifecycle_status'] == 'layout_parsing'
|
||||
assert payload['items'][0]['root_document_id'] == int(document.id)
|
||||
assert payload['items'][0]['current_document_filename'] == document.filename
|
||||
assert payload['items'][0]['root_document_filename'] == document.filename
|
||||
|
||||
|
||||
def test_manual_upload_pending_is_not_completed_count(app):
|
||||
"""manual_upload_pending 计入 waiting_manual_upload,不得计入 completed。"""
|
||||
with app.app_context():
|
||||
user, agent, session, _intake, document = _seed_run_input(suffix='WFP-MUP')
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status='manual_upload_pending',
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
payload = serialize_workflow(workflow, user_id=int(user.id), include_items=True)
|
||||
# 关键断言:待登记非完成,父批次保持 open。
|
||||
assert payload['counts']['waiting_manual_upload'] == 1
|
||||
assert payload['counts']['completed'] == 0
|
||||
assert str(workflow.status) == 'open'
|
||||
|
||||
|
||||
def test_project_conversation_workflows_includes_items_before_case(app):
|
||||
"""会话投影在无 Case 时仍返回 Item,避免 Run>0 / Item=0。"""
|
||||
with app.app_context():
|
||||
user, agent, session, _intake, document = _seed_run_input(suffix='WFP-CONV')
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
)
|
||||
ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
projected = project_conversation_workflows(
|
||||
user_id=int(user.id),
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
# 关键断言:开放 Workflow + 至少 1 个 Item。
|
||||
assert projected['conversation_id'] == session.session_id
|
||||
assert len(projected['workflows']) == 1
|
||||
assert projected['workflows'][0]['counts']['total'] == 1
|
||||
assert projected['workflows'][0]['items'][0]['current_case_no'] is None
|
||||
assert projected['workflows'][0]['items'][0]['current_document_filename'] == document.filename
|
||||
|
||||
|
||||
def test_project_conversation_workflows_returns_all_open_workflows(app):
|
||||
"""同会话多个 open Workflow 必须全部返回,而非仅第一条。"""
|
||||
with app.app_context():
|
||||
user, agent, session, _intake, document = _seed_run_input(suffix='WFP-MULTI')
|
||||
wf1 = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
)
|
||||
ensure_workflow_item_for_document(
|
||||
workflow=wf1,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
wf2 = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
owner_agent_id=int(agent.id),
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
projected = project_conversation_workflows(
|
||||
user_id=int(user.id),
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
nos = {row['workflow_no'] for row in projected['workflows']}
|
||||
# 关键断言:两条 open 批次均出现在投影中。
|
||||
assert wf1.workflow_no in nos
|
||||
assert wf2.workflow_no in nos
|
||||
assert len(projected['workflows']) == 2
|
||||
|
||||
|
||||
def test_get_workflow_and_item_for_user(app):
|
||||
"""属主可按编号读取 Workflow / Item DTO。"""
|
||||
with app.app_context():
|
||||
user, _agent, session, _intake, document = _seed_run_input(suffix='WFP-GET')
|
||||
workflow = create_workflow(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
workflow=workflow,
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
)
|
||||
db.session.commit()
|
||||
loaded = get_workflow_for_user(user_id=int(user.id), workflow_no=item.workflow_no)
|
||||
assert loaded.workflow_no == item.workflow_no
|
||||
|
||||
dto = get_workflow_item_dto_for_user(user_id=int(user.id), item_no=item.item_no)
|
||||
assert dto['item_no'] == item.item_no
|
||||
assert 'events' in dto
|
||||
assert dto['current_document_filename'] == document.filename
|
||||
assert serialize_workflow_item(item)['lifecycle_status'] == 'queued'
|
||||
|
||||
|
||||
def test_serialize_workflow_event_includes_actor_id(app):
|
||||
"""用户态 WorkflowEvent 必须返回 actor_id,供任务处理台时间线追溯操作人。"""
|
||||
with app.app_context():
|
||||
# 无需入库:直接序列化瞬态事件,断言用户态 DTO 字段契约。
|
||||
event = ShippingNoticeWorkflowEvent(
|
||||
workflow_id=1,
|
||||
workflow_no='WF-ACTOR-TEST',
|
||||
workflow_item_id=1,
|
||||
item_no='WFI-ACTOR-TEST',
|
||||
seq_no=99,
|
||||
event_code='upload_manual_confirmed',
|
||||
actor_type='user',
|
||||
actor_id='42',
|
||||
)
|
||||
payload = serialize_workflow_event(event)
|
||||
# 关键断言:actor_type 与 actor_id 同时出现在用户态投影中。
|
||||
assert payload['actor_type'] == 'user'
|
||||
assert payload['actor_id'] == '42'
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
backend/tests/test_shipping_workflow_recovery.py
|
||||
|
||||
用途:验收订单抽取 Job 超时回收后 WorkflowItem 从 layout_parsing/extracting 迁出。
|
||||
依赖:app fixture、_seed_run_input、workflow_ledger、sync_workflow_items_after_extraction_job_recovery。
|
||||
逻辑:模拟 Job queued/failed 回收,断言 Item 分别进入 queued / failed,不依赖完整 recover_stale_jobs。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
ensure_workflow_items_for_run,
|
||||
sync_workflow_items_after_extraction_job_recovery,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
ensure_workflow_item_for_document,
|
||||
transition_item_status,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_sync_workflow_items_after_extraction_recovery_to_queued(app):
|
||||
"""Job 回收为 queued 时,layout_parsing/extracting Item 回到 queued。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WFR-Q')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=False,
|
||||
):
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
item = ensure_workflow_item_for_document(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document.id),
|
||||
run=run,
|
||||
)
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status='extracting',
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
job = SimpleNamespace(status='queued', business_ref=run.run_no, id=1)
|
||||
updated = sync_workflow_items_after_extraction_job_recovery(run=run, job=job)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:卡住的抽取态被回收为可重试 queued。
|
||||
assert updated == 1
|
||||
db.session.refresh(item)
|
||||
assert item.lifecycle_status == 'queued'
|
||||
|
||||
|
||||
def test_sync_workflow_items_after_extraction_recovery_to_failed(app):
|
||||
"""Job 回收为 failed 时,layout_parsing Item 进入 failed。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='WFR-F')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=True,
|
||||
):
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
items = ensure_workflow_items_for_run(run, stage_when_ready='queued')
|
||||
assert items
|
||||
item = items[0]
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status='layout_parsing',
|
||||
actor_type='system',
|
||||
actor_id='test',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
job = SimpleNamespace(status='failed', business_ref=run.run_no, id=2)
|
||||
updated = sync_workflow_items_after_extraction_job_recovery(run=run, job=job)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:终态失败回收把 Item 标 failed。
|
||||
assert updated == 1
|
||||
db.session.refresh(item)
|
||||
assert item.lifecycle_status == 'failed'
|
||||
Reference in new issue
Block a user