feat(shipping-notice): 增强订单抽取与审计功能,支持取消与保留策略
- 在环境配置中新增进度细化、订单提取取消与审计导出相关的开关 - 实现订单抽取运行的取消功能,允许管理员在运行中进行操作 - 引入审计事件的保留策略,支持三年保留期的自动清理 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 增强文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
c85997884b
commit
95cdfe66b0
158 files changed
+19005
-1201
No files matched your search
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/tests/performance/__init__.py
|
||||
|
||||
用途:货代进度/审计阶段 5 性能冒烟测试包标记。
|
||||
"""
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
backend/tests/performance/test_shipping_order_extraction_progress_load.py
|
||||
|
||||
用途:进度投影与审计查询的负载冒烟(阶段 5 压测门槛)。
|
||||
依赖:serialize_workspace_run、audit_query_service、create_order_extraction_run。
|
||||
逻辑:在同一 app context 内连续投影约 20 次(模拟前台轮询峰值);审计列表并发读用线程池,
|
||||
但业务事件计数必须稳定。SQLite 内存库不跨连接共享,故投影压测采用同会话快速重入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.audit_query_service import list_shipping_audit_events
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_rapid_workspace_projection_reads_are_stable(app):
|
||||
"""连续 20 次投影同一 Run(模拟轮询峰值)不得失败,且结果稳定、无写副作用。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LOAD-CONC')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
results = []
|
||||
for _ in range(20):
|
||||
payload = serialize_workspace_run(run)
|
||||
results.append({
|
||||
'stage': payload.get('user_visible_stage'),
|
||||
'actions': tuple(payload['available_actions']),
|
||||
'total': payload['summary']['total_documents'],
|
||||
'progress_version': payload.get('progress_version'),
|
||||
})
|
||||
|
||||
# 关键断言:只读投影可重入;阶段/动作/版本一致,不因轮询漂移。
|
||||
assert len(results) == 20
|
||||
assert len({item['stage'] for item in results}) == 1
|
||||
assert len({item['actions'] for item in results}) == 1
|
||||
assert len({item['progress_version'] for item in results}) == 1
|
||||
assert all('view_details' in item['actions'] or 'refresh_status' in item['actions'] for item in results)
|
||||
|
||||
|
||||
def test_concurrent_audit_list_reads_do_not_duplicate_business_events(app):
|
||||
"""并发审计列表只追加访问审计,不复制业务事件。"""
|
||||
with app.app_context():
|
||||
append_shipping_audit_event(
|
||||
event_type='load_probe',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-LOAD-AUDIT',
|
||||
run_no='SNER-LOAD-AUDIT',
|
||||
operation_id='op-load-1',
|
||||
)
|
||||
db.session.commit()
|
||||
before = list_shipping_audit_events(
|
||||
admin_user_id=1,
|
||||
request_id='req-load-baseline',
|
||||
filters={'event_type': 'load_probe', 'run_no': 'SNER-LOAD-AUDIT'},
|
||||
)['total']
|
||||
|
||||
def _list_once(idx: int) -> int:
|
||||
with app.app_context():
|
||||
payload = list_shipping_audit_events(
|
||||
admin_user_id=1,
|
||||
request_id=f'req-load-{idx}',
|
||||
filters={'event_type': 'load_probe', 'run_no': 'SNER-LOAD-AUDIT'},
|
||||
)
|
||||
return int(payload['total'])
|
||||
|
||||
totals = []
|
||||
# 审计列表在 testing 配置下可跨线程读同一库;若环境为纯内存 SQLite,退化为串行仍校验计数。
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
futures = [pool.submit(_list_once, i) for i in range(10)]
|
||||
for future in as_completed(futures):
|
||||
totals.append(future.result())
|
||||
except Exception:
|
||||
totals = [_list_once(i) for i in range(10)]
|
||||
|
||||
# 关键断言:业务事件计数稳定;访问审计不会伪装成 load_probe。
|
||||
assert before >= 1
|
||||
assert set(totals) == {before}
|
||||
@@ -14,12 +14,12 @@ from app.services.shipping_notice.order_supplement_merge import merge_email_supp
|
||||
|
||||
|
||||
SCHEMA = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number'},
|
||||
{'field_id': 'part', 'field_code': 'part_number'},
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']},
|
||||
{'field_id': 'qty', 'field_code': 'qty'},
|
||||
{'field_id': 'reservation', 'field_code': 'reservation_id'},
|
||||
{'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', 'aliases': ['Reservation ID']},
|
||||
{'field_id': 'allocation', 'field_code': 'allocation_id'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']},
|
||||
]}
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ def test_email_supplement_html_grid_merges_by_po_and_mpn_without_overwriting_pdf
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='a' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th><th>Source Type</th><th>Allocated Qty</th></tr><tr><td>4518738152</td><td>D4-A08AR12000002</td><td>2000484577</td><td>DSB CMH</td><td>99</td></tr></table>'''],
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
supplement['document_id'] = 44
|
||||
assert supplement['rows'][0]['evidence']['reservation_id'] == {
|
||||
@@ -74,10 +75,40 @@ def test_email_supplement_po_fallback_requires_one_reservation():
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in result['conflicts'])
|
||||
|
||||
|
||||
def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
"""邮件 PO 与 PDF 不一致时,唯一完全匹配 MPN 仍可保守补齐预约号。"""
|
||||
order = _order()
|
||||
order['header_fields'][0]['observations'][0]['value'] = '4518838152'
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{
|
||||
'po_number': '4518738152', 'mpn': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'po_number': '4518738152', 'mpn': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'po_number': '4518838154', 'mpn': 'B3-AR1000270A1',
|
||||
'reservation_id': '4000111701', 'evidence': {},
|
||||
},
|
||||
],
|
||||
}
|
||||
result = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '2000484577'
|
||||
assert result['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_body_text():
|
||||
"""Outlook 展平的纵向表头可恢复补充行,尾部邮件正文不会被误当数据。"""
|
||||
supplement = parse_email_allocation_text(
|
||||
content_hash='b' * 64,
|
||||
schema_definition=SCHEMA,
|
||||
body_text='''Hello\nallocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nThank you''',
|
||||
)
|
||||
assert supplement['rows'] == [{
|
||||
@@ -92,4 +123,14 @@ def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_b
|
||||
def test_email_supplement_plain_text_deduplicates_quoted_email_rows():
|
||||
"""转发邮件重复同一正文表时只保留一个事实行,避免制造补充关联冲突。"""
|
||||
body = '''allocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152'''
|
||||
assert len(parse_email_allocation_text(body_text=body, content_hash='c' * 64)['rows']) == 1
|
||||
assert len(parse_email_allocation_text(body_text=body, content_hash='c' * 64, schema_definition=SCHEMA)['rows']) == 1
|
||||
|
||||
|
||||
def test_email_supplement_requires_frozen_schema_alias_for_order_headers():
|
||||
"""正文 PO/MPN/预约号表头只接受冻结 Schema 明确维护的别名,不再使用代码白名单。"""
|
||||
result = parse_email_allocation_tables(
|
||||
content_hash='d' * 64,
|
||||
schema_definition={'fields': []},
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th></tr><tr><td>4518838154</td><td>B3-AR1000270A1</td><td>4000111701</td></tr></table>'''],
|
||||
)
|
||||
assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']}
|
||||
@@ -56,18 +56,18 @@ def test_table_contract_is_driven_only_by_explicit_schema_aliases():
|
||||
assert parse_notice_table_text(text, contract=None) == []
|
||||
|
||||
|
||||
def test_table_contract_rejects_normalized_alias_collision():
|
||||
"""大小写、全半角或标点差异归一后冲突时必须阻断 Schema 保存/发布。"""
|
||||
def test_table_contract_allows_case_distinct_aliases_and_matches_exact_case():
|
||||
"""Schema v1 的大小写不同别名独立存在,表头只能匹配完全相同的大小写。"""
|
||||
definition = _definition(
|
||||
_field('part_number', ['Customer P/N']),
|
||||
_field('customer_part_number', ['customer p n']),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
compile_table_header_contract(definition)
|
||||
contract = compile_table_header_contract(definition)
|
||||
|
||||
assert caught.value.code == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
assert caught.value.details['table_header_collisions']
|
||||
assert contract.header_to_field['Customer P N'] == 'part_number'
|
||||
assert contract.header_to_field['customer p n'] == 'customer_part_number'
|
||||
assert 'CUSTOMER PN' not in contract.header_to_field
|
||||
|
||||
|
||||
def test_table_contract_rejects_forbidden_reservation_header():
|
||||
@@ -101,9 +101,9 @@ def test_table_contract_excludes_disabled_and_unsupported_context_fields():
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
))
|
||||
|
||||
assert 'disabled sku' not in contract.header_to_field
|
||||
assert 'sender' not in contract.header_to_field
|
||||
assert contract.header_to_field['qty'] == 'qty'
|
||||
assert 'Disabled SKU' not in contract.header_to_field
|
||||
assert 'Sender' not in contract.header_to_field
|
||||
assert contract.header_to_field['Qty'] == 'qty'
|
||||
|
||||
|
||||
def test_flat_table_parser_drops_zero_quantity_row():
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
backend/tests/test_shipping_access_audit_strict.py
|
||||
|
||||
用途:验证敏感访问审计必须逐次留存,失败时阻断调用。
|
||||
依赖:fulfillment_audit.record_access_audit、ShippingAuditEvent、pytest app fixture。
|
||||
逻辑:成功写入可查询;同资源连续两次访问落两条;模拟写入失败时 strict 抛错。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice import fulfillment_audit
|
||||
|
||||
|
||||
def test_access_audit_persists_and_is_queryable(app):
|
||||
"""敏感访问审计写入后可按 action/aggregate 检索。"""
|
||||
with app.app_context():
|
||||
wrote = fulfillment_audit.record_access_audit(
|
||||
action='view_order_extraction_run',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-ACCESS-1',
|
||||
actor_id=42,
|
||||
run_no='SNER-ACCESS-1',
|
||||
metadata={'status': 'processing'},
|
||||
)
|
||||
assert wrote is True
|
||||
row = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_resource_accessed',
|
||||
action='view_order_extraction_run',
|
||||
aggregate_id='SNER-ACCESS-1',
|
||||
).one()
|
||||
assert row.actor_id == '42'
|
||||
assert row.run_no == 'SNER-ACCESS-1'
|
||||
|
||||
|
||||
def test_access_audit_records_every_call(app):
|
||||
"""每次访问操作都必须独立留痕,禁止按窗口合并。"""
|
||||
with app.app_context():
|
||||
first = fulfillment_audit.record_access_audit(
|
||||
action='view_order_extraction_documents',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-ACCESS-2',
|
||||
actor_id=7,
|
||||
run_no='SNER-ACCESS-2',
|
||||
)
|
||||
second = fulfillment_audit.record_access_audit(
|
||||
action='view_order_extraction_documents',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-ACCESS-2',
|
||||
actor_id=7,
|
||||
run_no='SNER-ACCESS-2',
|
||||
)
|
||||
assert first is True
|
||||
assert second is True
|
||||
assert ShippingAuditEvent.query.filter_by(
|
||||
action='view_order_extraction_documents',
|
||||
aggregate_id='SNER-ACCESS-2',
|
||||
).count() == 2
|
||||
|
||||
|
||||
def test_access_audit_strict_raises_when_append_fails(app, monkeypatch):
|
||||
"""审计写入失败时必须抛错,禁止业务侧静默成功。"""
|
||||
with app.app_context():
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError('audit table down')
|
||||
|
||||
monkeypatch.setattr(fulfillment_audit, 'append_shipping_audit_event', _boom)
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
fulfillment_audit.record_access_audit(
|
||||
action='preview_order_review_document',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id='CASE-1',
|
||||
actor_id=1,
|
||||
review_case_no='CASE-1',
|
||||
strict=True,
|
||||
)
|
||||
assert exc.value.code == 'SHIPPING_NOTICE.AUDIT_PERSIST_FAILED'
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_end_to_end.py
|
||||
|
||||
用途:全链路审计关联键覆盖冒烟(上传取消 → 履约关键节点 → 查询 Diff/导出)。
|
||||
依赖:audit_service、fulfillment_audit、audit_query_service。
|
||||
逻辑:用同一 run_no/task_no/operation_id 串联多事件,验证可检索、可 Diff、导出无快照正文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
export_shipping_audit_events,
|
||||
get_shipping_audit_event,
|
||||
list_shipping_audit_events,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
|
||||
def test_audit_chain_traceable_by_correlation_keys(app):
|
||||
"""关键节点审计均可通过 run_no/task_no/operation_id 追溯,导出不含快照。"""
|
||||
with app.app_context():
|
||||
run_no = 'SNER-E2E-1'
|
||||
task_no = 'ST-E2E-1'
|
||||
operation_id = 'op-e2e-chain-1'
|
||||
|
||||
cancel_event = append_shipping_audit_event(
|
||||
event_type='order_extraction_run_cancel_requested',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
operation_id=operation_id,
|
||||
request_id=operation_id,
|
||||
document_id='101',
|
||||
before={'status': 'processing'},
|
||||
after={'status': 'processing', 'cancellation_requested': True},
|
||||
action='cancel_run',
|
||||
)
|
||||
record_fulfillment_audit(
|
||||
event_type='candidate_promoted',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task_no,
|
||||
action='promote_candidate',
|
||||
run_no=run_no,
|
||||
task_no=task_no,
|
||||
document_id='101',
|
||||
before={'status': 'candidate'},
|
||||
after={'status': 'task_created'},
|
||||
metadata={'operation_id': operation_id},
|
||||
)
|
||||
# fulfillment_audit 不自动 commit;与取消事件同事务提交。
|
||||
db.session.commit()
|
||||
|
||||
listed = list_shipping_audit_events(
|
||||
admin_user_id=42,
|
||||
request_id='req-e2e-list',
|
||||
filters={'run_no': run_no},
|
||||
)
|
||||
event_types = {item['event_type'] for item in listed['items']}
|
||||
# 关键断言:取消与履约晋级都可按 run_no 检索。
|
||||
assert 'order_extraction_run_cancel_requested' in event_types
|
||||
assert 'candidate_promoted' in event_types
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=42,
|
||||
request_id='req-e2e-detail',
|
||||
event_id=int(cancel_event.id),
|
||||
)
|
||||
assert detail['operation_id'] == operation_id
|
||||
assert any(row['key'] == 'status' or row['key'] == 'cancellation_requested' for row in detail['diff'])
|
||||
|
||||
by_task = list_shipping_audit_events(
|
||||
admin_user_id=42,
|
||||
request_id='req-e2e-task',
|
||||
filters={'task_no': task_no},
|
||||
)
|
||||
assert by_task['total'] >= 1
|
||||
|
||||
exported = export_shipping_audit_events(
|
||||
admin_user_id=42,
|
||||
request_id='req-e2e-export',
|
||||
filters={'run_no': run_no},
|
||||
format='csv',
|
||||
)
|
||||
assert run_no in exported['content']
|
||||
assert operation_id in exported['content']
|
||||
assert 'before_snapshot' not in exported['content']
|
||||
assert 'email_body' not in exported['content']
|
||||
|
||||
access = ShippingAuditEvent.query.filter_by(event_type='audit_access').count()
|
||||
assert access >= 3
|
||||
@@ -1,7 +1,9 @@
|
||||
"""验证货代统一审计事件的脱敏和 append-only 契约。
|
||||
"""
|
||||
backend/tests/test_shipping_audit_event.py
|
||||
|
||||
依赖:ShippingAuditEvent、audit_service、SQLAlchemy 内存会话。
|
||||
逻辑:审计写入只保存状态哈希和受控元数据;更新、删除或敏感内容均必须被拒绝。
|
||||
用途:验证货代统一审计事件的脱敏、白名单快照和 append-only 契约。
|
||||
依赖:ShippingAuditEvent、audit_service、progress_audit_contract、SQLAlchemy 内存会话。
|
||||
逻辑:审计写入只保存白名单快照/哈希和受控元数据;更新、删除或敏感内容均必须被拒绝。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,26 +13,92 @@ 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
|
||||
from app.services.shipping_notice.audit_service import (
|
||||
append_shipping_audit_event,
|
||||
hash_client_context_value,
|
||||
project_audit_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_FORBIDDEN_KEYS,
|
||||
AUDIT_RETENTION_DAYS,
|
||||
I18N_KEY_INVENTORY,
|
||||
)
|
||||
|
||||
|
||||
def test_append_shipping_audit_event_hashes_state_and_rejects_sensitive_metadata(app):
|
||||
"""状态审计仅保存前后哈希,正文或凭据类元数据必须在入库前拒绝。"""
|
||||
"""状态审计保存白名单快照与哈希,正文或凭据类元数据必须在入库前拒绝。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed', aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-1', run_no='SNER-1', before={'status': 'queued'},
|
||||
after={'status': 'running'}, metadata={'target_status': 'running'},
|
||||
event_type='order_extraction_run_status_changed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-1',
|
||||
run_no='SNER-1',
|
||||
operation_id='op-stage0-1',
|
||||
before={'status': 'queued'},
|
||||
after={'status': 'processing'},
|
||||
metadata={'target_status': 'processing'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:可追溯性来自哈希而不是把订单、邮件正文写进审计表。
|
||||
# 关键断言:可追溯性来自哈希与白名单快照,而不是把订单、邮件正文写进审计表。
|
||||
assert event.before_hash and event.after_hash
|
||||
assert event.metadata_json == {'target_status': 'running'}
|
||||
with pytest.raises(ValidationError, match='forbidden'):
|
||||
assert event.before_snapshot_json == {'status': 'queued'}
|
||||
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
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='invalid', aggregate_type='run', aggregate_id='1', metadata={'email_body': 'secret'},
|
||||
event_type='invalid',
|
||||
aggregate_type='run',
|
||||
aggregate_id='1',
|
||||
metadata={'email_body': 'secret'},
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN'
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('forbidden_key', sorted(AUDIT_FORBIDDEN_KEYS))
|
||||
def test_audit_forbidden_keys_blacklist_rejects_metadata_and_snapshot(app, forbidden_key: str):
|
||||
"""阶段 0 冻结的敏感键黑名单必须对元数据与快照同时生效。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as meta_err:
|
||||
append_shipping_audit_event(
|
||||
event_type='probe',
|
||||
aggregate_type='run',
|
||||
aggregate_id='SNER-BL',
|
||||
metadata={forbidden_key: 'x'},
|
||||
)
|
||||
assert meta_err.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN'
|
||||
|
||||
with pytest.raises(ValidationError) as snap_err:
|
||||
project_audit_snapshot({'status': 'queued', forbidden_key: 'x'})
|
||||
assert snap_err.value.code == 'SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN'
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_audit_snapshot_whitelist_strips_unknown_business_keys(app):
|
||||
"""未授权业务键不得进入快照;敏感键仍被拒绝。"""
|
||||
with app.app_context():
|
||||
projected = project_audit_snapshot({
|
||||
'status': 'extracting',
|
||||
'progress_version': 3,
|
||||
'orders': [{'po': '45001'}],
|
||||
})
|
||||
assert projected == {'status': 'extracting', 'progress_version': 3}
|
||||
|
||||
|
||||
def test_audit_evidence_refs_reject_url_payload(app):
|
||||
"""证据引用禁止携带对象存储 URL 等敏感键。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='evidence_viewed',
|
||||
aggregate_type='document',
|
||||
aggregate_id='12',
|
||||
evidence_refs=[{'file_asset_id': 9, 'url': 'https://minio.example/x'}],
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN'
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
@@ -50,3 +118,55 @@ def test_shipping_audit_event_rejects_orm_update_and_delete(app):
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_append_shipping_audit_event_hashes_client_context_and_session_item(app):
|
||||
"""会话工作项审计必须记录属主/工作项软引用,且 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',
|
||||
owner_user_id=42,
|
||||
conversation_id='conv-session-1',
|
||||
client_ip='203.0.113.9',
|
||||
user_agent='Mozilla/5.0 TestAgent',
|
||||
after={
|
||||
'lifecycle_status': 'pending_review',
|
||||
'current_version_no': 1,
|
||||
'item_no': 'SPWI-1',
|
||||
},
|
||||
metadata={'source': 'upload'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert event.session_item_id == 'SPWI-1'
|
||||
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')
|
||||
assert event.client_ip_hash != '203.0.113.9'
|
||||
assert event.after_snapshot_json == {
|
||||
'lifecycle_status': 'pending_review',
|
||||
'current_version_no': 1,
|
||||
'item_no': 'SPWI-1',
|
||||
}
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='probe',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id='SPWI-2',
|
||||
metadata={'client_ip': '203.0.113.9'},
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN'
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_stage0_i18n_key_inventory_is_frozen():
|
||||
"""四语言所需 key 清单必须冻结且覆盖阶段/健康/取消/审计错误前缀。"""
|
||||
assert AUDIT_RETENTION_DAYS == 365 * 3
|
||||
joined = '\n'.join(I18N_KEY_INVENTORY)
|
||||
assert 'shippingOrderExtractionUserStage.cancellation_requested' in joined
|
||||
assert 'shippingOrderExtractionHealthTip.processing_attention' in joined
|
||||
assert 'SHIPPING_NOTICE.CANCEL_REASON_REQUIRED' in joined
|
||||
assert 'admin.shippingAudit.export' in joined
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_query_service.py
|
||||
|
||||
用途:验证货代审计查询、白名单 Diff、受控导出与到期清理契约。
|
||||
依赖:audit_query_service、audit_service、ShippingAuditEvent、进度审计契约。
|
||||
逻辑:列表/详情/导出必须写访问审计且不泄露快照正文;清理经 Core DELETE 绕过 append-only 守卫。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
export_shipping_audit_events,
|
||||
get_shipping_audit_event,
|
||||
list_shipping_audit_events,
|
||||
purge_expired_shipping_audit_events,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def test_list_and_detail_write_access_audit_and_whitelist_diff(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-AUDIT-Q1',
|
||||
run_no='SNER-AUDIT-Q1',
|
||||
operation_id='op-audit-q1',
|
||||
before={'status': 'queued', 'progress_version': 1},
|
||||
after={'status': 'processing', 'progress_version': 2},
|
||||
metadata={'target_status': 'processing'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
listed = list_shipping_audit_events(
|
||||
admin_user_id=9001,
|
||||
request_id='req-list-1',
|
||||
page=1,
|
||||
page_size=25,
|
||||
filters={'run_no': 'SNER-AUDIT-Q1'},
|
||||
)
|
||||
# 关键断言:列表可发现业务事件,但不回传 before/after 快照。
|
||||
assert listed['total'] >= 1
|
||||
summary = next(item for item in listed['items'] if item['id'] == event.id)
|
||||
assert summary['has_snapshots'] is True
|
||||
assert 'before_snapshot' not in summary
|
||||
assert 'diff' not in summary
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=9001,
|
||||
request_id='req-detail-1',
|
||||
event_id=int(event.id),
|
||||
)
|
||||
# 关键断言:Diff 仅覆盖白名单键变化,不夹带订单正文类字段。
|
||||
assert detail['before_snapshot'] == {'status': 'queued', 'progress_version': 1}
|
||||
assert detail['after_snapshot'] == {'status': 'processing', 'progress_version': 2}
|
||||
changed_keys = {row['key'] for row in detail['diff']}
|
||||
assert changed_keys == {'progress_version', 'status'}
|
||||
|
||||
access_events = ShippingAuditEvent.query.filter_by(event_type='audit_access').all()
|
||||
actions = {row.action for row in access_events}
|
||||
assert 'list_audit_events' in actions
|
||||
assert 'get_audit_event' in actions
|
||||
|
||||
|
||||
def test_export_csv_omits_snapshots_and_writes_access_audit(app):
|
||||
"""CSV 导出仅稳定列,禁止快照全文,并写导出访问审计。"""
|
||||
with app.app_context():
|
||||
append_shipping_audit_event(
|
||||
event_type='candidate_promoted',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id='ST-1',
|
||||
run_no='SNER-AUDIT-Q2',
|
||||
task_no='ST-1',
|
||||
before={'status': 'candidate'},
|
||||
after={'status': 'task_created'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
exported = export_shipping_audit_events(
|
||||
admin_user_id=9002,
|
||||
request_id='req-export-1',
|
||||
filters={'run_no': 'SNER-AUDIT-Q2'},
|
||||
limit=100,
|
||||
format='csv',
|
||||
)
|
||||
# 关键断言:导出正文不含 snapshot / email_body 等敏感字段名。
|
||||
content = exported['content']
|
||||
assert 'event_type' in content
|
||||
assert 'SNER-AUDIT-Q2' in content
|
||||
assert 'before_snapshot' not in content
|
||||
assert 'email_body' not in content
|
||||
assert exported['exported'] >= 1
|
||||
|
||||
access = ShippingAuditEvent.query.filter_by(
|
||||
event_type='audit_access',
|
||||
action='export_audit_events',
|
||||
).first()
|
||||
assert access is not None
|
||||
assert access.metadata_json.get('format') == 'csv'
|
||||
|
||||
|
||||
def test_list_filters_session_work_item_context_fields(app):
|
||||
"""会话工作项相关筛选:conversation / session_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',
|
||||
aggregate_id='SPWI-FILTER-1',
|
||||
conversation_id='conv-filter-1',
|
||||
session_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',
|
||||
aggregate_id='SPWI-FILTER-2',
|
||||
conversation_id='conv-filter-2',
|
||||
session_item_id='SPWI-FILTER-2',
|
||||
review_case_no='SRC-FILTER-2',
|
||||
owner_user_id='8802',
|
||||
run_no='SNER-FILTER-2',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
listed = list_shipping_audit_events(
|
||||
admin_user_id=9003,
|
||||
request_id='req-filter-1',
|
||||
page=1,
|
||||
page_size=25,
|
||||
filters={
|
||||
'conversation_id': 'conv-filter-1',
|
||||
'session_item_id': 'SPWI-FILTER-1',
|
||||
'review_case_no': 'SRC-FILTER-1',
|
||||
'owner_user_id': '8801',
|
||||
},
|
||||
)
|
||||
# 关键断言:四字段联合筛选仅命中目标事件。
|
||||
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]['owner_user_id'] == '8801'
|
||||
|
||||
|
||||
def test_purge_expired_supports_dry_run_and_core_delete(app):
|
||||
"""到期清理支持 dry_run;正式删除经 Core DELETE 并写清理审计。"""
|
||||
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)
|
||||
|
||||
dry = purge_expired_shipping_audit_events(limit=100, dry_run=True)
|
||||
# 关键断言:演练只扫描不删除。
|
||||
assert dry['dry_run'] is True
|
||||
assert dry['scanned'] >= 1
|
||||
assert dry['deleted'] == 0
|
||||
assert db.session.get(ShippingAuditEvent, expired_id) is not None
|
||||
|
||||
result = purge_expired_shipping_audit_events(limit=100, dry_run=False)
|
||||
assert result['dry_run'] is False
|
||||
assert result['deleted'] >= 1
|
||||
# SQLite 可能复用已删主键;以业务事件类型断言清理结果,不以旧 id 缺失为准。
|
||||
assert ShippingAuditEvent.query.filter_by(
|
||||
event_type='legacy_probe',
|
||||
aggregate_id='SNER-EXPIRED',
|
||||
).first() is None
|
||||
|
||||
purge_audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='audit_retention_purged',
|
||||
).order_by(ShippingAuditEvent.id.desc()).first()
|
||||
assert purge_audit is not None
|
||||
assert purge_audit.metadata_json.get('deleted') >= 1
|
||||
@@ -8,6 +8,8 @@ backend/tests/test_shipping_customer_shadow_resolution.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
@@ -165,6 +167,41 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app):
|
||||
assert case.customer_id is None and case.business_no is None
|
||||
|
||||
|
||||
def test_schema_uuid_drift_keeps_stable_customer_identity_rule_matching(app):
|
||||
"""新版 Schema 仅重建字段 UUID 时,规则按同 field_code 映射并保留实际取值字段证据。"""
|
||||
with app.app_context():
|
||||
field, original_version = _published_field(code='ship_to_customer')
|
||||
definition, _rule_set = _definition(field)
|
||||
customer = _customer('Inventech Corp Mexico', 'IVMX')
|
||||
identity_rules.create_evidence(
|
||||
target_type='customer', target_id=customer.id,
|
||||
data={'definition_id': definition['id'], 'raw_value': 'Inventec IEC Technologies c/o EP Logistics LLC', 'status': 'approved'},
|
||||
actor_id=1,
|
||||
)
|
||||
original_version.status = 'retired'
|
||||
replacement_field_id = str(uuid.uuid4())
|
||||
replacement_version = ShippingOrderSchemaVersion(
|
||||
schema_id=original_version.schema_id, version=original_version.version + 1, status='published',
|
||||
definition_json={'fields': [{
|
||||
'field_id': replacement_field_id, 'field_code': 'ship_to_customer', 'display_name': 'ship_to_customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True, 'available_for_customer_identity': True,
|
||||
'normalizer_key': 'lowercase_trim',
|
||||
}]},
|
||||
checksum='f' * 64, lock_version=1,
|
||||
)
|
||||
db.session.add(replacement_version)
|
||||
db.session.flush()
|
||||
_intake, candidate = _seed_candidate()
|
||||
replacement_field = type('ReplacementField', (), {'id': replacement_field_id})()
|
||||
_attach_value(candidate, replacement_version, replacement_field, 'Inventec IEC Technologies c/o EP Logistics LLC')
|
||||
|
||||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||||
|
||||
assert resolution.status == 'unique_candidate'
|
||||
assert resolution.top_customer_id == customer.id
|
||||
assert resolution.evidence_json[0]['context_field_id'] == replacement_field_id
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status', ['needs_review', 'blocked', 'missing'])
|
||||
def test_unaccepted_field_values_never_become_identity_evidence(app, status):
|
||||
"""非 accepted/corroborated 值及原始 LLM JSON 均不能进入客户识别。"""
|
||||
|
||||
@@ -194,6 +194,11 @@ def test_independent_sample_review_reuses_existing_truth_and_excludes_training_i
|
||||
|
||||
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
||||
assert {item['document_id'] for item in available} == {documents[1].id, documents[2].id}
|
||||
# 候选下拉必须能区分同页多表,且不回传 HTML、坐标或内部布局内容。
|
||||
assert available[0]['table_index'] == 1
|
||||
assert available[0]['row_count'] > 0 and available[0]['column_count'] > 0
|
||||
assert available[0]['header_preview']
|
||||
assert 'html' not in available[0] and 'bbox' not in available[0]
|
||||
candidate = quality.preview_independent_sample(
|
||||
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', actor_id=user.id,
|
||||
)
|
||||
@@ -472,6 +477,21 @@ def test_draft_publish_requires_current_approved_blind_test(app):
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST'
|
||||
|
||||
|
||||
def test_draft_publish_requires_static_document_anchor(app):
|
||||
"""关键断言:零必填锚点的模板不能发布,避免成为匹配所有 PDF 的通配模板。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
with app.app_context():
|
||||
profile, _user, _documents = _published_profile_with_samples()
|
||||
profile.status = 'draft'
|
||||
profile.definition_json = {'document_match': {'required_anchors': []}}
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
quality.assert_profile_publishable(profile)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_REQUIRED_ANCHOR'
|
||||
|
||||
|
||||
def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
"""关键断言:v2 草稿在训练、独立多明细盲测通过后可发布,并冻结正式 checksum 凭证。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
@@ -1065,6 +1065,52 @@ def test_selected_eml_attachments_use_bounded_parallel_deep_extraction(app, ship
|
||||
]
|
||||
|
||||
|
||||
def test_eml_materialization_rejects_missing_selected_document(app, shipping_user, monkeypatch):
|
||||
"""已选附件未落成 Document 时,必须停止在输入准备阶段而非误报版面服务故障。"""
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
import app.services.shipping_notice.order_extraction_materialization as materialization
|
||||
|
||||
with app.app_context():
|
||||
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-MISSING-SELECTED-DOCUMENT')
|
||||
asset.original_filename = 'orders.eml'
|
||||
asset.mime_type = 'message/rfc822'
|
||||
db.session.commit()
|
||||
|
||||
def _preview_result(_asset, **_kwargs):
|
||||
return NoticeIntakeResult(
|
||||
filename='orders.eml', source_type='email', source_file_type='message/rfc822',
|
||||
text='mail preview', warnings=[], meta={'attachments': [
|
||||
{
|
||||
'attachment_key': 'att-002', 'filename': 'order.pdf',
|
||||
'mime_type': 'application/pdf', '_payload_bytes': b'pdf',
|
||||
},
|
||||
]},
|
||||
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(materialization, 'extract_notice_from_asset', _preview_result)
|
||||
# 关键断言:即使持久化层异常静默返回,也不能让空输入进入后续版面调度。
|
||||
monkeypatch.setattr(materialization, 'persist_intake_documents', lambda **_kwargs: {'document_count': 0})
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
materialization.ensure_order_extraction_input_documents(
|
||||
intakes=[intake],
|
||||
attachment_selection={
|
||||
'items': [{
|
||||
'intake_no': intake.intake_no,
|
||||
'attachment_key': 'att-002',
|
||||
'selected': True,
|
||||
'selection_batch': 1,
|
||||
}],
|
||||
},
|
||||
schema_definition={'fields': []},
|
||||
)
|
||||
|
||||
assert exc_info.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE'
|
||||
assert exc_info.value.details['reason'] == 'selected_attachment_document_missing'
|
||||
assert exc_info.value.details['missing_attachment_keys'] == ['att-002']
|
||||
|
||||
|
||||
def test_selected_normal_files_use_global_bounded_parallel_extraction(app, shipping_user, monkeypatch):
|
||||
"""不同普通文件共享首轮并发预算,完成顺序不得改变主线程持久化顺序。"""
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
|
||||
@@ -87,7 +87,7 @@ def _coordinate_definition() -> dict:
|
||||
"""构造最小 v2 坐标模板,供来源授权和服务端 field_id 冻结断言使用。"""
|
||||
return {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'text': 'PURCHASE ORDER'}]},
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'label': 'DOCUMENT TYPE:', 'value': 'PURCHASE ORDER', 'value_position': 'right'}]},
|
||||
'table_regions': [{
|
||||
'region_id': 'main_lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
|
||||
@@ -614,6 +614,38 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon
|
||||
).one().id == replacement['id']
|
||||
|
||||
|
||||
def test_clone_draft_inherits_annotation_sample_but_not_training_sample(app, monkeypatch):
|
||||
"""从已发布模板新建草稿时,编辑器 PDF 画布可用且不会复用训练发布资格。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
schema = _schema_version()
|
||||
source = service.save_draft(_data(schema.id), actor_id=None)
|
||||
annotation = _bind_ready_profile_sample(
|
||||
source['id'], sample_role='annotation', table_id='annotation-table', filename='annotation.pdf',
|
||||
)
|
||||
_bind_ready_profile_sample(
|
||||
source['id'], sample_role='training', table_id='training-table', filename='training.pdf',
|
||||
)
|
||||
published = service.publish(
|
||||
source['id'], actor_id=None, expected_lock_version=source['lock_version'],
|
||||
)
|
||||
|
||||
clone = service.clone_draft(published['id'], actor_id=None)
|
||||
inherited = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=clone['id']).all()
|
||||
|
||||
assert [(sample.document_id, sample.table_id, sample.sample_role) for sample in inherited] == [
|
||||
(annotation.document_id, 'annotation-table', 'annotation'),
|
||||
]
|
||||
assert db.session.get(ShippingOrderDocumentProfile, clone['id']).training_sample_count == 0
|
||||
audit = ShippingOrderDocumentProfileAudit.query.filter_by(
|
||||
profile_id=clone['id'], event_type='draft_cloned',
|
||||
).one()
|
||||
assert audit.detail_json['inherited_annotation_sample_count'] == 1
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=published['id']).count() == 2
|
||||
|
||||
|
||||
def test_profile_publish_rolls_back_when_sample_layout_hash_drifts(app, monkeypatch):
|
||||
"""样本文件与 ready Layout hash 不一致时必须整体回滚,旧 published 不能被部分退役。"""
|
||||
with app.app_context():
|
||||
@@ -949,8 +981,8 @@ def test_profile_definition_validation_exposes_first_invalid_field_path(app):
|
||||
assert getattr(caught.value, 'details', {}).get('field_path') == 'table_regions.0.line_layouts.0.region'
|
||||
|
||||
|
||||
def test_profile_admin_api_requires_admin_and_uses_standard_errors(app):
|
||||
"""普通用户不能维护 Profile;管理员错误使用统一业务 envelope。"""
|
||||
def test_profile_admin_api_rejects_legacy_unbound_draft_creation(app):
|
||||
"""关键断言:旧创建入口不得绕过向导生成没有 annotation/training 样本的草稿。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
@@ -969,54 +1001,13 @@ def test_profile_admin_api_requires_admin_and_uses_standard_errors(app):
|
||||
)
|
||||
assert denied.status_code == 403
|
||||
|
||||
created = client.post(
|
||||
rejected = client.post(
|
||||
'/api/admin/shipping-notice/order-document-profiles',
|
||||
json=_data(schema_id),
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert created.status_code == 201
|
||||
payload = parse_api_data(created.get_json())
|
||||
assert payload['profile_code'] == 'PO_312207'
|
||||
|
||||
lease = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}/edit-lease",
|
||||
json={'browser_session_id': 'profile-admin-tab', 'operation_id': 'profile-admin-lease'},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert lease.status_code == 201
|
||||
lease_payload = parse_api_data(lease.get_json())
|
||||
|
||||
invalid_definition = _data(schema_id)
|
||||
invalid_definition['definition']['table_regions'][0]['line_layouts'][0]['region']['x1'] = 0
|
||||
invalid = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}",
|
||||
json={
|
||||
**invalid_definition,
|
||||
'expected_lock_version': payload['lock_version'],
|
||||
'browser_session_id': 'profile-admin-tab',
|
||||
'lease_token': lease_payload['lease_token'],
|
||||
'operation_id': 'profile-admin-invalid-definition',
|
||||
},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
invalid_error = parse_api_error(invalid.get_json())
|
||||
assert invalid_error['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
assert invalid_error['details']['field_path'] == 'table_regions.0.line_layouts.0.region'
|
||||
|
||||
conflict = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}",
|
||||
json={
|
||||
**_data(schema_id),
|
||||
'expected_lock_version': payload['lock_version'] + 1,
|
||||
'browser_session_id': 'profile-admin-tab',
|
||||
'lease_token': lease_payload['lease_token'],
|
||||
'operation_id': 'profile-admin-stale-save',
|
||||
},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert conflict.status_code == 409
|
||||
assert parse_api_error(conflict.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT'
|
||||
assert rejected.status_code == 400
|
||||
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_profile_sample_api_supports_secure_preview_create_and_version_update(app, monkeypatch):
|
||||
@@ -1281,6 +1272,38 @@ def test_profile_page_preview_uses_memory_fallback_in_development(app, monkeypat
|
||||
assert store.getdel('preview-token') is None
|
||||
|
||||
|
||||
def test_preview_page_region_text_reads_only_the_admin_selected_glyphs(app, monkeypatch):
|
||||
"""画布创建匹配锚点时必须只读取框选坐标内文字,备注中的同名文本不能混入。"""
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': [
|
||||
{'text': 'P', 'bbox': {'x0': 10, 'y0': 10, 'x1': 14, 'y1': 18}},
|
||||
{'text': 'O', 'bbox': {'x0': 15, 'y0': 10, 'x1': 19, 'y1': 18}},
|
||||
{'text': ':', 'bbox': {'x0': 20, 'y0': 10, 'x1': 24, 'y1': 18}},
|
||||
{'text': 'P', 'bbox': {'x0': 10, 'y0': 60, 'x1': 14, 'y1': 68}},
|
||||
{'text': 'O', 'bbox': {'x0': 15, 'y0': 60, 'x1': 19, 'y1': 68}},
|
||||
]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
document = type('Document', (), {'id': 108})()
|
||||
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout)
|
||||
with app.app_context():
|
||||
result = service.read_preview_page_region_text(
|
||||
1, data={'document_id': 108, 'region': {'x0': .05, 'y0': .05, 'x1': .3, 'y1': .3}}, page_no=1, actor_id=1,
|
||||
)
|
||||
assert result['text'] == 'PO:'
|
||||
assert result['source'] == 'pdf_coordinate'
|
||||
# Center selection excludes the preceding P instead of pulling a neighboring line.
|
||||
edge_result = service.read_preview_page_region_text(
|
||||
1, data={'document_id': 108, 'region': {'x0': .139, 'y0': .1, 'x1': .245, 'y1': .18}}, page_no=1, actor_id=1,
|
||||
)
|
||||
assert edge_result['text'] == 'O:'
|
||||
|
||||
|
||||
def test_profile_region_preview_requires_a_bound_document(app, monkeypatch):
|
||||
"""局部预览只能作用于当前模板样本,避免管理员接口被 document_id 枚举越权。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_cancel.py
|
||||
|
||||
用途:验收订单抽取 Run/Unit 取消请求、权限、已完成保留与审计原子性。
|
||||
依赖:order_extraction_cancel_service、Run/Unit/Plan ORM、ShippingAuditEvent、进度事件。
|
||||
逻辑:排队 Unit 立即取消;执行中写 cancellation_requested;管理员代取消必须写原因;
|
||||
业务与审计同事务,敏感快照不得含正文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionUnit,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
cancel_order_extraction_run,
|
||||
cancel_order_extraction_unit,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def _attach_units(run, *, statuses: list[str], document_ids: list[int] | None = None) -> list[ShippingOrderExtractionUnit]:
|
||||
"""为测试 Run 物化计划与给定状态的 Unit。"""
|
||||
plan = ShippingOrderExtractionPlan(
|
||||
run_id=run.id,
|
||||
plan_version='shipping_order_extraction.plan.v1',
|
||||
input_snapshot_hash=run.input_snapshot_hash,
|
||||
status='running',
|
||||
unit_count=len(statuses),
|
||||
)
|
||||
db.session.add(plan)
|
||||
db.session.flush()
|
||||
units: list[ShippingOrderExtractionUnit] = []
|
||||
intake_id = int(run.intakes[0].intake_id)
|
||||
for index, status in enumerate(statuses):
|
||||
document_id = int(document_ids[index]) if document_ids and index < len(document_ids) else index + 1
|
||||
unit = ShippingOrderExtractionUnit(
|
||||
plan_id=plan.id,
|
||||
intake_id=intake_id,
|
||||
document_id=document_id,
|
||||
position=index,
|
||||
unit_type='document_extraction',
|
||||
document_type='attachment',
|
||||
content_hash=f'hash-{index}',
|
||||
status=status,
|
||||
started_at=datetime.utcnow() if status != 'pending' else None,
|
||||
)
|
||||
db.session.add(unit)
|
||||
units.append(unit)
|
||||
db.session.flush()
|
||||
run.extraction_plan = plan
|
||||
return units
|
||||
|
||||
|
||||
def test_cancel_pending_run_completes_immediately_and_writes_audit(app):
|
||||
"""排队中整批取消应立即收口,并同事务写入进度与审计。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='CANCEL-PENDING')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
units = _attach_units(run, statuses=['pending'], document_ids=[document.id])
|
||||
db.session.commit()
|
||||
|
||||
cancel_order_extraction_run(actor=user, run_no=run.run_no, reason_code='user_cancelled')
|
||||
db.session.commit()
|
||||
|
||||
db.session.refresh(run)
|
||||
# 关键断言:排队取消立即终态,PDF 为 cancelled。
|
||||
assert run.status == 'cancelled'
|
||||
assert run.cancellation_requested_at is not None
|
||||
assert run.cancellation_completed_at is not None
|
||||
assert all(unit.status == 'cancelled' for unit in units)
|
||||
events = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).all()
|
||||
codes = {event.event_code for event in events}
|
||||
assert 'cancellation_completed' in codes or 'unit_cancelled' in codes
|
||||
audits = ShippingAuditEvent.query.filter(ShippingAuditEvent.run_no == run.run_no).all()
|
||||
assert any(event.action == 'cancel_run' for event in audits)
|
||||
assert all('email_body' not in (event.metadata_json or {}) for event in audits)
|
||||
|
||||
|
||||
def test_cancel_inflight_unit_requests_then_worker_checkpoint_completes(app):
|
||||
"""执行中取消先进入正在取消,Worker 检查点后才生效并保留已完成 PDF。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='CANCEL-INFLIGHT')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-2.pdf',
|
||||
filename='orders-2.pdf',
|
||||
content_hash='b' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 2 QTY 1',
|
||||
)
|
||||
third = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-3.pdf',
|
||||
filename='orders-3.pdf',
|
||||
content_hash='c' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 3 QTY 1',
|
||||
)
|
||||
db.session.add_all([second, third])
|
||||
db.session.flush()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ready, extracting, pending = _attach_units(
|
||||
run,
|
||||
statuses=['candidate_ready', 'extracting', 'pending'],
|
||||
document_ids=[document.id, second.id, third.id],
|
||||
)
|
||||
run.status = 'processing'
|
||||
run.phase = 'deterministic_parsing'
|
||||
db.session.commit()
|
||||
|
||||
cancel_order_extraction_run(actor=user, run_no=run.run_no)
|
||||
db.session.commit()
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(ready)
|
||||
db.session.refresh(extracting)
|
||||
db.session.refresh(pending)
|
||||
|
||||
# 关键断言:已完成保留;执行中为请求态;排队已取消;Run 尚未伪造为已取消。
|
||||
assert ready.status == 'candidate_ready'
|
||||
assert pending.status == 'cancelled'
|
||||
assert extracting.status == 'extracting'
|
||||
assert extracting.cancellation_requested_at is not None
|
||||
assert run.status == 'processing'
|
||||
projection = serialize_workspace_run(run)
|
||||
assert projection['user_visible_stage'] == 'cancellation_requested'
|
||||
assert projection['summary']['cancelled_documents'] == 1
|
||||
assert projection['summary']['completed_documents'] == 1
|
||||
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(extracting)
|
||||
assert extracting.status == 'cancelled'
|
||||
assert run.status == 'cancelled'
|
||||
assert run.cancellation_completed_at is not None
|
||||
|
||||
|
||||
def test_admin_cancel_other_user_run_requires_reason(app):
|
||||
"""管理员取消他人任务必须填写原因,否则校验失败。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='CANCEL-ADMIN')
|
||||
admin = User(username='cancel-admin', email='cancel-admin@example.com', password_hash='x', role='admin')
|
||||
db.session.add(admin)
|
||||
db.session.flush()
|
||||
from app.models import ShippingOrderExtractionRun, ShippingOrderExtractionRunIntake
|
||||
from app.models import ShippingOrderSchemaVersion
|
||||
|
||||
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
assert schema_version is not None
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-CANCEL-ADMIN-{user.id}',
|
||||
user_id=user.id,
|
||||
owner_agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
schema_version_id=int(schema_version.id),
|
||||
input_snapshot_hash='a' * 64,
|
||||
input_snapshot_json={'intakes': [], 'schema': {'version': 1, 'checksum': 'a' * 64}},
|
||||
idempotency_key=f'cancel-admin-{user.id}',
|
||||
status='queued',
|
||||
phase='queued',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderExtractionRunIntake(run_id=run.id, intake_id=intake.id, position=0))
|
||||
_attach_units(run, statuses=['pending'], document_ids=[document.id])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
cancel_order_extraction_run(actor=admin, run_no=run.run_no)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.CANCEL_REASON_REQUIRED'
|
||||
db.session.rollback()
|
||||
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
admin = db.session.get(User, admin.id)
|
||||
cancel_order_extraction_run(actor=admin, run_no=run.run_no, reason='积压清理')
|
||||
db.session.commit()
|
||||
db.session.refresh(run)
|
||||
assert run.status == 'cancelled'
|
||||
assert run.cancellation_actor_type == 'admin'
|
||||
assert run.cancellation_reason == '积压清理'
|
||||
|
||||
|
||||
def test_cancel_unit_rejects_completed_document(app):
|
||||
"""已完成 PDF 不可取消,避免回滚业务结果。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='CANCEL-READY')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ready, = _attach_units(run, statuses=['candidate_ready'], document_ids=[document.id])
|
||||
run.status = 'processing'
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
cancel_order_extraction_unit(actor=user, run_no=run.run_no, document_id=int(ready.document_id))
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.CANCEL_NOT_ACTIVE'
|
||||
@@ -54,6 +54,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
serialize_order_extraction_run,
|
||||
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_plan import transition_order_extraction_unit
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan_batch
|
||||
@@ -250,6 +251,41 @@ def test_create_run_freezes_lightweight_input_without_sync_materialization(app):
|
||||
}
|
||||
|
||||
|
||||
def test_create_run_reparses_empty_email_supplement_from_frozen_html_tables(app):
|
||||
"""历史正文补充为空时,Run 必须按冻结 Schema 从 Intake HTML 表恢复预约号。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='EMAIL-HTML')
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
schema.definition_json = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#']},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN']},
|
||||
{'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', 'aliases': ['Reservation ID']},
|
||||
]}
|
||||
intake.structured_result_json = {
|
||||
'email': {'body_html_tables': ['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th></tr><tr><td>4518838154</td><td>B3-AR1000270A1</td><td>4000111701</td></tr></table>''']},
|
||||
}
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='__email_body__',
|
||||
filename='email-body.html',
|
||||
content_hash='e' * 64,
|
||||
classification='email_context',
|
||||
parse_status='parsed',
|
||||
extracted_text='Outlook flattened text without table columns',
|
||||
order_extraction_result_json={'email_supplement': {'rows': [], 'issues': ['email_supplement_po_header_missing']}},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
body = next(item for item in run.input_snapshot_json['intakes'][0]['documents'] if item['document_type'] == 'email_body')
|
||||
assert body['email_supplement']['rows'][0]['po_number'] == '4518838154'
|
||||
assert body['email_supplement']['rows'][0]['reservation_id'] == '4000111701'
|
||||
|
||||
|
||||
def test_worker_materialization_preserves_request_snapshot_on_retry(app):
|
||||
"""Worker 重试可复用执行计划,但不得改写发送时的请求快照与幂等审计锚点。"""
|
||||
with app.app_context():
|
||||
@@ -274,6 +310,36 @@ def test_worker_materialization_preserves_request_snapshot_on_retry(app):
|
||||
assert run.request_snapshot_json == request_snapshot
|
||||
|
||||
|
||||
def test_worker_rematerializes_a_legacy_empty_plan(app):
|
||||
"""遗留的 0 Unit 空计划不得跳过附件物化,否则重试会永久得到空版面输入。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='EMPTY-PLAN')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
empty_plan = ShippingOrderExtractionPlan(
|
||||
run_id=run.id,
|
||||
plan_version='shipping_order_extraction.plan.v1',
|
||||
input_snapshot_hash=str(run.input_snapshot_hash),
|
||||
status='planned',
|
||||
unit_count=0,
|
||||
)
|
||||
db.session.add(empty_plan)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.order_extraction_run_service import materialize_order_extraction_run_inputs
|
||||
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents'):
|
||||
plan = materialize_order_extraction_run_inputs(run)
|
||||
|
||||
# 关键断言:空计划被替换,重新冻结的执行计划必须实际包含附件 Unit。
|
||||
assert plan.unit_count == 1
|
||||
assert ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).count() == 1
|
||||
|
||||
|
||||
def test_create_run_rejects_an_intake_from_another_upload_batch(app):
|
||||
"""服务端必须拒绝伪造的跨批次 Intake 清单,不能依赖前端筛选。"""
|
||||
with app.app_context():
|
||||
@@ -431,6 +497,50 @@ def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction
|
||||
assert ShippingOrderExtractionRun.query.count() == 1
|
||||
|
||||
|
||||
def test_create_run_accepts_a_reused_layout_from_an_identical_document(app):
|
||||
"""相同内容复用历史布局时,当前 Document 的版本绑定应视为排程成功。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, original = _seed_run_input(suffix='REUSE-LAYOUT')
|
||||
db.session.add(ShippingDocumentLayoutVersion(
|
||||
document_id=original.id,
|
||||
version=1,
|
||||
status='ready',
|
||||
source_content_hash=original.content_hash,
|
||||
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:v3',
|
||||
parser_name='mineru',
|
||||
contract_version='shipping_document_table_snapshot.v1',
|
||||
payload_json={},
|
||||
issues_json=[],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
duplicate = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=original.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-REUSE-LAYOUT-duplicate.pdf',
|
||||
filename='orders-REUSE-LAYOUT-duplicate.pdf',
|
||||
content_hash=original.content_hash,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO duplicate',
|
||||
)
|
||||
db.session.add(duplicate)
|
||||
db.session.commit()
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
# 关键断言:复用版本属于原始 Document 也不能造成当前 Run 的排程失败。
|
||||
assert reused is False
|
||||
assert run.status == 'queued'
|
||||
|
||||
|
||||
def test_last_layout_completion_enqueues_waiting_run_once(app):
|
||||
"""最后一份附件布局完成才唤醒 Run,提前完成其中一份不能启动订单提取。"""
|
||||
with app.app_context():
|
||||
@@ -1729,6 +1839,39 @@ def test_chat_sessions_aggregate_only_new_unseen_order_extraction_attention(app)
|
||||
assert aggregate == {session.session_id: (1, 'error')}
|
||||
|
||||
|
||||
def test_final_order_extraction_job_failure_marks_queued_run_failed(app):
|
||||
"""Job 重试耗尽时必须收口 Run,避免聊天页永久显示处理中。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='FINAL-JOB-FAILURE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
assert job is not None
|
||||
job.status = 'running'
|
||||
job.attempts = job.max_attempts
|
||||
job.error_message = None
|
||||
db.session.commit()
|
||||
|
||||
assert fail_job(job.id, error='layout scheduler unavailable', retryable=True, owned_attempt=job.attempts) is True
|
||||
|
||||
db.session.expire_all()
|
||||
failed_run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
failed_job = db.session.get(Job, job.id)
|
||||
event = ShippingOrderExtractionProgressEvent.query.filter_by(
|
||||
run_id=run.id,
|
||||
event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED',
|
||||
).one()
|
||||
# 关键断言:队列终态与用户可见 Run 必须同事务收口,前端才能停止轮询。
|
||||
assert failed_job is not None and failed_job.status == 'failed'
|
||||
assert failed_run is not None and failed_run.status == 'failed'
|
||||
assert failed_run.phase == 'job_failed'
|
||||
assert failed_run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED'
|
||||
assert event.job_id == job.id
|
||||
assert intake.order_extraction_status == 'failed'
|
||||
|
||||
|
||||
def test_failed_run_retry_reuses_snapshot_and_execution_result(app):
|
||||
"""手工重试复用同一 Run/快照/确定性结果,只创建新的执行 Job。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -21,7 +21,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
events: list[str] = []
|
||||
run = SimpleNamespace(
|
||||
id=1, user_id=9, run_no='SNER-WORKER-MATERIALIZE', status='queued', current_job_id=None,
|
||||
attempt_count=0, input_snapshot_json={'attachment_selection': {}},
|
||||
attempt_count=0, cancellation_requested_at=None, input_snapshot_json={'attachment_selection': {}},
|
||||
)
|
||||
job = SimpleNamespace(id=1, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
plan = SimpleNamespace(id=1, unit_count=0, units=[])
|
||||
@@ -41,12 +41,24 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
'ShippingOrderExtractionUnit',
|
||||
SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: []),
|
||||
)),
|
||||
status=SimpleNamespace(in_=lambda *_a, **_k: True),
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: []),
|
||||
),
|
||||
join=lambda *_a, **_k: SimpleNamespace(
|
||||
filter=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
class _Eq:
|
||||
def __eq__(self, _other):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(handler, 'ShippingOrderExtractionPlan', SimpleNamespace(run_id=_Eq()))
|
||||
monkeypatch.setattr(handler, 'transition_order_extraction_run', lambda target, **_kwargs: setattr(target, 'status', 'processing'))
|
||||
monkeypatch.setattr(handler, 'fail_job', lambda *_args, **_kwargs: events.append('failed'))
|
||||
def fake_materialize(_run, *, finalize_plan=True):
|
||||
events.append('finalize' if finalize_plan else 'materialize')
|
||||
return plan if finalize_plan else None
|
||||
@@ -65,6 +77,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
monkeypatch.setattr(handler, '_result_requires_review', lambda **_kwargs: False)
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished'))
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 1})
|
||||
@@ -109,6 +122,72 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
assert run.phase == 'waiting_layout'
|
||||
|
||||
|
||||
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
|
||||
"""版面 Job 创建失败(如 MinerU 关闭)时必须同步收口 Run,禁止仅失败 Job 而留下 queued。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
transitions: list[str] = []
|
||||
run = SimpleNamespace(
|
||||
id=3, user_id=9, run_no='SNER-WORKER-LAYOUT-FAIL', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, input_snapshot_json={'attachment_selection': {}},
|
||||
)
|
||||
job = SimpleNamespace(id=3, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
|
||||
def fake_transition(target, *, target_status, **_kwargs):
|
||||
transitions.append(target_status)
|
||||
target.status = target_status
|
||||
|
||||
class _Expr:
|
||||
def in_(self, *_args, **_kwargs):
|
||||
return self
|
||||
|
||||
def __eq__(self, _other):
|
||||
return self
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _id: job)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderExtractionRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderExtractionUnit',
|
||||
SimpleNamespace(
|
||||
status=_Expr(),
|
||||
query=SimpleNamespace(join=lambda *_a, **_k: SimpleNamespace(
|
||||
filter=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||||
)),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ShippingOrderExtractionPlan', SimpleNamespace(run_id=_Expr()))
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: events.append('materialize'),
|
||||
)
|
||||
|
||||
def _raise_layout_scheduling(_run, *, created_by_id):
|
||||
raise ValidationError(
|
||||
'Order PDF layout job was not created',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED',
|
||||
)
|
||||
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', _raise_layout_scheduling)
|
||||
monkeypatch.setattr(handler, 'transition_order_extraction_run', fake_transition)
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'fail_job', lambda *_args, **kwargs: events.append(f"fail:{kwargs.get('retryable')}"))
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished'))
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'rollback', lambda: None)
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 3})
|
||||
|
||||
assert events == ['materialize', 'fail:False']
|
||||
assert transitions == ['processing', 'failed']
|
||||
assert run.status == 'failed'
|
||||
|
||||
|
||||
def _patch_unit_transitions(monkeypatch):
|
||||
"""用轻量状态机替代 ORM transition,便于验证单元级自动重试行为。"""
|
||||
|
||||
@@ -139,6 +218,7 @@ def _patch_unit_transitions(monkeypatch):
|
||||
def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]):
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.commit', lambda: None)
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.rollback', lambda: None)
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.refresh', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction.record_unit_progress',
|
||||
lambda *, event_code, reason_code=None, **_kwargs: event_log.append((event_code, reason_code)),
|
||||
@@ -147,6 +227,14 @@ def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]):
|
||||
'app.jobs.handlers.shipping_order_extraction._append_route_decision',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_cancel_service.should_abort_unit_for_cancellation',
|
||||
lambda **_kwargs: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_cancel_service.apply_worker_cancellation_checkpoint',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
|
||||
def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders(monkeypatch):
|
||||
@@ -190,7 +278,7 @@ def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders
|
||||
|
||||
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
|
||||
|
||||
assert result is orders
|
||||
assert result == orders
|
||||
assert unit.status == 'merging_supplement'
|
||||
assert unit.attempt_count == 3
|
||||
assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2
|
||||
|
||||
@@ -1,19 +1,45 @@
|
||||
"""订单抽取工作台投影的纯单元测试。"""
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_workspace_projection_unit.py
|
||||
|
||||
用途:订单抽取工作台投影的纯单元测试(无 DB)。
|
||||
依赖:order_extraction_workspace_projection、pytest monkeypatch。
|
||||
逻辑:覆盖 Run 级 currentActivity、handling_items 拆分、布局等待期失败/排队投影。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_chat_state
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import (
|
||||
_planned_layout_documents,
|
||||
build_handling_items,
|
||||
serialize_workspace_run_chat_state,
|
||||
)
|
||||
|
||||
|
||||
def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
|
||||
"""Run 级事件也应进入聊天卡 currentActivity,而不是只支持单元级事件。"""
|
||||
run = SimpleNamespace(
|
||||
status='processing',
|
||||
phase='deterministic_parsing',
|
||||
extraction_plan=SimpleNamespace(units=[]),
|
||||
input_snapshot_json={},
|
||||
error_code=None,
|
||||
result_json=None,
|
||||
started_at=None,
|
||||
finished_at=None,
|
||||
created_at=None,
|
||||
updated_at=None,
|
||||
last_activity_at=None,
|
||||
progress_version=1,
|
||||
attempt_count=0,
|
||||
cancellation_requested_at=None,
|
||||
cancellation_completed_at=None,
|
||||
cancellation_actor_type=None,
|
||||
cancellation_actor_id=None,
|
||||
cancellation_reason=None,
|
||||
cancellation_reason_code=None,
|
||||
run_no='OER-TEST',
|
||||
auto_freeze_policy_json=None,
|
||||
review_cases=[],
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -29,14 +55,219 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
|
||||
),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.progress_ui_v3_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.order_extraction_cancel_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.progress_feature_flags_payload',
|
||||
lambda: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._open_existing_document_ids',
|
||||
lambda _run: set(),
|
||||
)
|
||||
|
||||
result = serialize_workspace_run_chat_state(run)
|
||||
|
||||
assert result['currentActivity'] == {
|
||||
'unitId': 0,
|
||||
'fileName': None,
|
||||
'eventCode': 'expansion_wave_started',
|
||||
'selectionBatch': 2,
|
||||
'reasonCodes': ['budget_initial_limit', 'required_field_missing'],
|
||||
}
|
||||
assert result['currentActivity']['unitId'] == 0
|
||||
assert result['currentActivity']['fileName'] is None
|
||||
assert result['currentActivity']['eventCode'] == 'expansion_wave_started'
|
||||
assert result['currentActivity']['selectionBatch'] == 2
|
||||
assert result['currentActivity']['reasonCodes'] == ['budget_initial_limit', 'required_field_missing']
|
||||
assert result['currentActivity']['userVisibleStage'] == 'extracting'
|
||||
assert result['status'] == 'processing'
|
||||
assert result['handlingItems'] == []
|
||||
assert result['primaryNotice'] is None
|
||||
|
||||
|
||||
def test_build_handling_items_splits_pending_freeze_review_and_failure():
|
||||
"""Run 级 handling_items 必须拆分待补、冲突、冻结、复核与技术失败,不得只给笼统复核态。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
result_json={
|
||||
'pending_count': 2,
|
||||
'created_count': 1,
|
||||
'budget_stopped': True,
|
||||
'pending_orders': [
|
||||
{
|
||||
'candidate_no': 'C-1',
|
||||
'po_number': 'PO-1',
|
||||
'reasons': ['required_field_missing'],
|
||||
'missing_fields': ['qty'],
|
||||
},
|
||||
{
|
||||
'candidate_no': 'C-2',
|
||||
'po_number': 'PO-2',
|
||||
'reasons': ['email_supplement_conflict'],
|
||||
'missing_fields': [],
|
||||
},
|
||||
],
|
||||
'auto_freeze': {
|
||||
'blocked_tasks': [
|
||||
{'candidate_no': 'C-3', 'task_no': 'ST-9', 'code': 'auto_freeze_blocked'},
|
||||
],
|
||||
},
|
||||
},
|
||||
auto_freeze_policy_json={
|
||||
'enabled': False,
|
||||
'evaluated_from_run': True,
|
||||
'blocking_reason_codes': ['profile_manual_confirmation_required'],
|
||||
},
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
units = [
|
||||
SimpleNamespace(
|
||||
id=1,
|
||||
document_id=11,
|
||||
status='review_required',
|
||||
reason_code='row_needs_review',
|
||||
technical_failure_reason_code=None,
|
||||
),
|
||||
SimpleNamespace(
|
||||
id=2,
|
||||
document_id=12,
|
||||
status='failed',
|
||||
reason_code=None,
|
||||
technical_failure_reason_code='document_unreadable',
|
||||
),
|
||||
]
|
||||
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
categories = [item['category'] for item in items]
|
||||
|
||||
# 关键断言:混合原因必须分别成项,且技术失败优先于文档复核。
|
||||
assert categories[0] == 'technical_failure'
|
||||
assert 'document_review' in categories
|
||||
assert 'candidate_missing_info' in categories
|
||||
assert 'candidate_conflict' in categories
|
||||
assert 'auto_freeze_blocked' in categories
|
||||
assert 'budget_stopped' in categories
|
||||
assert items[0]['primary_action'] == 'retry_failed_attachments'
|
||||
missing = next(item for item in items if item['category'] == 'candidate_missing_info')
|
||||
assert missing['primary_action'] == 'review_candidate'
|
||||
assert 'required_field_missing' in missing['reason_codes']
|
||||
freeze = next(item for item in items if item['category'] == 'auto_freeze_blocked')
|
||||
assert freeze['affected_refs'][0]['task_no'] == 'ST-9'
|
||||
|
||||
|
||||
def test_build_handling_items_budget_stopped_includes_attachment_refs():
|
||||
"""预算停扩必须带上受限附件引用,便于前端直达定位。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
result_json={'budget_stopped': True, 'pending_count': 0, 'created_count': 0},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [
|
||||
{
|
||||
'selected': False,
|
||||
'filename': 'skip-budget.pdf',
|
||||
'content_hash': 'hash-1',
|
||||
'document_id': 42,
|
||||
'skip_reason_codes': ['budget_initial_limit'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
|
||||
items = build_handling_items(run, [], open_existing_doc_ids=set())
|
||||
budget = next(item for item in items if item['category'] == 'budget_stopped')
|
||||
assert budget['count'] == 1
|
||||
assert budget['affected_refs'][0]['file_name'] == 'skip-budget.pdf'
|
||||
assert budget['affected_refs'][0]['document_id'] == 42
|
||||
|
||||
|
||||
def test_planned_documents_inherit_failed_run_status_before_units_exist():
|
||||
"""Job 在 Unit 物化前失败时,右侧每份 PDF 必须显示失败而非处理中。"""
|
||||
run = SimpleNamespace(
|
||||
status='failed',
|
||||
phase=None,
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED',
|
||||
finished_at=None,
|
||||
created_at=None,
|
||||
last_activity_at=None,
|
||||
cancellation_requested_at=None,
|
||||
cancellation_completed_at=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [
|
||||
{'selected': True, 'filename': 'first.pdf', 'content_hash': 'a'},
|
||||
{'selected': True, 'filename': 'second.pdf', 'content_hash': 'b'},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
rows = _planned_layout_documents(run, {}, {})
|
||||
|
||||
# 关键断言:没有 Unit 也不允许以 pending 投影掩盖最终 Run 失败。
|
||||
assert [row['status'] for row in rows] == ['failed', 'failed']
|
||||
assert [row['user_visible_stage'] for row in rows] == ['failed', 'failed']
|
||||
assert {row['reason_code'] for row in rows} == {'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED'}
|
||||
|
||||
|
||||
def test_planned_documents_expose_queue_stage_and_health_tips(monkeypatch):
|
||||
"""Unit 未物化时也应投影排队阶段,并在阈值到达后给出健康提示。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
now = datetime(2026, 7, 30, 12, 0, 0)
|
||||
run = SimpleNamespace(
|
||||
status='queued',
|
||||
phase='waiting_layout',
|
||||
error_code=None,
|
||||
finished_at=None,
|
||||
created_at=now - timedelta(minutes=10),
|
||||
last_activity_at=now - timedelta(minutes=10),
|
||||
cancellation_requested_at=None,
|
||||
cancellation_completed_at=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [
|
||||
{'selected': True, 'filename': 'po.pdf', 'content_hash': 'h1', 'selection_batch': 1},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.progress_ui_v3_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.order_extraction_cancel_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.datetime',
|
||||
SimpleNamespace(utcnow=lambda: now),
|
||||
)
|
||||
|
||||
rows = _planned_layout_documents(run, {}, {})
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0]['user_visible_stage'] == 'waiting_layout'
|
||||
assert rows[0]['status'] == 'pending'
|
||||
assert rows[0]['queue_position'] == 1
|
||||
assert any(tip['code'] == 'queue_backlog' for tip in rows[0]['health_tips'])
|
||||
assert 'cancel_unit' in rows[0]['available_actions']
|
||||
|
||||
|
||||
def test_progress_event_status_maps_process_states():
|
||||
"""进度事件 status 必须表达过程态,不得一律 completed。"""
|
||||
from app.services.shipping_notice.order_extraction_progress import _progress_event_status
|
||||
|
||||
assert _progress_event_status(event_code='document_queued') == 'queued'
|
||||
assert _progress_event_status(event_code='extracting', entity_status='extracting') == 'running'
|
||||
assert _progress_event_status(event_code='run_completed') == 'completed'
|
||||
assert _progress_event_status(event_code='technical_failed') == 'failed'
|
||||
@@ -3,13 +3,13 @@
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
|
||||
|
||||
|
||||
def _profile(code: str, *, required: str = 'PURCHASE ORDER', optional: list[str] | None = None, score: float = .9, margin: float = .15) -> dict:
|
||||
"""构造不包含订单号、料号、数量或金额的最小冻结 Profile。"""
|
||||
def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None = None, score: float = .9, margin: float = .15) -> dict:
|
||||
"""构造最小冻结 Profile;工厂值必须与 PLANT NAME 标签形成关系才可命中。"""
|
||||
return {'profile_code': code, 'version': 1, 'checksum': f'{code.lower():0<64}'[:64], 'definition': {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {
|
||||
'required_anchors': [{'anchor_id': 'title', 'text': required}],
|
||||
'optional_anchors': [{'anchor_id': f'optional_{index}', 'text': value} for index, value in enumerate(optional or [])],
|
||||
'required_anchors': [{'anchor_id': 'plant_name', 'label': 'PLANT NAME:', 'value': value, 'value_position': 'right'}],
|
||||
'optional_anchors': [{'anchor_id': f'optional_{index}', 'label': 'TYPE:', 'value': item, 'value_position': 'right'} for index, item in enumerate(optional or [])],
|
||||
'minimum_score': score, 'minimum_margin': margin,
|
||||
},
|
||||
'table_regions': [{'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
|
||||
@@ -19,7 +19,7 @@ def _profile(code: str, *, required: str = 'PURCHASE ORDER', optional: list[str]
|
||||
}}
|
||||
|
||||
|
||||
def _layout(text: str = 'PURCHASE ORDER') -> dict:
|
||||
def _layout(text: str = 'PLANT NAME: FACTORY A') -> dict:
|
||||
"""构造最小页面坐标证据,业务文本仅用于证明它没有参与匹配逻辑。"""
|
||||
return {'tables': [{'table_id': 'table-1', 'page_no': 1}], 'coordinate_evidence': {
|
||||
'tables': {'table-1': [
|
||||
@@ -29,13 +29,23 @@ def _layout(text: str = 'PURCHASE ORDER') -> dict:
|
||||
}}
|
||||
|
||||
|
||||
def test_profile_matcher_uniquely_matches_static_anchors_not_dynamic_order_values():
|
||||
"""同一静态版式在订单号、料号、数量变化后仍稳定命中同一 Profile。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'])], layout=_layout('PURCHASE ORDER SUPPLIER A PO-999 QTY 999 PART-X'))
|
||||
def test_profile_matcher_uniquely_matches_label_value_anchor_not_dynamic_order_values():
|
||||
"""工厂标签和值关系不受订单号、料号、数量变化影响。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['UM17'])], layout=_layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X'))
|
||||
assert result.status == 'unique_match'
|
||||
assert result.profile_code == 'PO_A'
|
||||
|
||||
|
||||
def test_profile_matcher_ignores_pdf_whitespace_when_matching_label_value_anchor():
|
||||
"""PDF 坐标字符逐字拼接时空白会丢失,标签和值关系仍必须可命中。"""
|
||||
result = match_frozen_coordinate_profiles(
|
||||
profiles=[_profile('PO_A', value='IEC Technologies, S. de R.L. de C.V')],
|
||||
layout=_layout('PLANT NAME: IEC Technologies, S. de R.L. de C.V'),
|
||||
)
|
||||
|
||||
assert result.status == 'unique_match'
|
||||
|
||||
|
||||
def test_profile_matcher_rejects_similar_profiles_when_margin_is_insufficient():
|
||||
"""相同静态锚点的两个 Profile 必须返回 ambiguous,禁止按版本或顺序选择。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A'), _profile('PO_B')], layout=_layout())
|
||||
@@ -44,7 +54,7 @@ def test_profile_matcher_rejects_similar_profiles_when_margin_is_insufficient():
|
||||
|
||||
def test_profile_matcher_enforces_required_anchor_and_evidence_availability():
|
||||
"""缺静态锚点为 layout_drift;没有坐标页证据则为 evidence_insufficient。"""
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout('DELIVERY NOTE')).status == 'layout_drift'
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout('REMARK: FACTORY A')).status == 'layout_drift'
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout={'tables': []}).status == 'evidence_insufficient'
|
||||
|
||||
|
||||
@@ -52,10 +62,10 @@ def test_profile_matcher_reports_only_missing_anchor_identifiers():
|
||||
"""缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。"""
|
||||
profile = _profile('PO_A')
|
||||
profile['definition']['document_match']['required_anchors'].append({
|
||||
'anchor_id': 'customer_logo', 'text': 'ACME LOGO',
|
||||
'anchor_id': 'customer_logo', 'label': 'CUSTOMER:', 'value': 'ACME LOGO', 'value_position': 'right',
|
||||
})
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=_layout('PURCHASE ORDER PO-12345'))
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=_layout('PLANT NAME: FACTORY A PO-12345'))
|
||||
|
||||
# 关键断言:管理员能定位配置缺项,而诊断不泄露订单业务值。
|
||||
assert result.status == 'layout_drift'
|
||||
@@ -67,7 +77,7 @@ def test_profile_matcher_reports_only_missing_anchor_identifiers():
|
||||
|
||||
def test_profile_matcher_requires_optional_score_threshold():
|
||||
"""可选锚点未命中导致得分低于模板阈值时不得自动匹配。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'], score=.95)], layout=_layout())
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['UM17'], score=.95)], layout=_layout())
|
||||
assert result.status == 'no_match'
|
||||
|
||||
|
||||
@@ -76,7 +86,7 @@ def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table():
|
||||
layout = _layout('LINE ITEMS')
|
||||
layout['coordinate_evidence']['page_glyphs'] = {'1': [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
|
||||
for index, char in enumerate('PURCHASE ORDER')
|
||||
for index, char in enumerate('PLANT NAME: FACTORY A')
|
||||
]}
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=layout)
|
||||
|
||||
@@ -35,6 +35,7 @@ from app.services.shipping_notice.order_review_draft_service import (
|
||||
delete_line,
|
||||
patch_header_field,
|
||||
patch_line_field,
|
||||
validate_draft,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_evidence, list_case_evidence
|
||||
from app.services.shipping_notice.order_review_disposition_service import (
|
||||
@@ -95,6 +96,47 @@ def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candida
|
||||
assert db.session.get(ShippingNoticeCandidate, candidate.id).structured_result_json == {'machine': 'unchanged'}
|
||||
|
||||
|
||||
def test_review_case_backfills_final_run_order_for_an_empty_legacy_draft(app):
|
||||
"""最终合并订单可回填旧空草稿,复核页不得把成功 PDF 显示为机器订单不可用。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-FINAL-ORDER')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
# 先模拟 Worker 在最终合并结果写入前创建的空白旧 Case。
|
||||
legacy_case = ensure_run_review_cases(run=run)[0]
|
||||
run.execution_result_json = {'orders': [{
|
||||
'primary_document_id': unit.document_id,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': 'PO-FINAL'}]}],
|
||||
'lines': [{'fields': [{'field_id': 'part', 'observations': [{'value': 'A001'}]}]}],
|
||||
}]}
|
||||
|
||||
refreshed = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
# 关键断言:按当前 PDF 的 primary_document_id 回填,不依赖旧 Unit 中间结果。
|
||||
assert refreshed.id == legacy_case.id
|
||||
assert refreshed.current_draft.header_values_json['machine_fields'][0]['observations'][0]['value'] == 'PO-FINAL'
|
||||
assert refreshed.current_draft.lines_json[0]['machine_fields'][0]['observations'][0]['value'] == 'A001'
|
||||
assert not any(item['code'] == 'machine_order_unavailable' for item in refreshed.current_draft.issue_summary_json)
|
||||
|
||||
|
||||
def test_review_case_restores_original_case_from_machine_coordinate_quote(app):
|
||||
"""历史坐标结果的小写机器值应以同源原文 quote 回填,人工层保持不变。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-SOURCE-CASE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{
|
||||
'header_fields': [{'field_id': 'part', 'observations': [{
|
||||
'value': 'd4-a08ar12000002', 'quote': 'D4-A08AR12000002',
|
||||
}]}],
|
||||
'lines': [],
|
||||
}]}
|
||||
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
assert case.current_draft.header_values_json['machine_fields'][0]['observations'][0]['value'] == 'D4-A08AR12000002'
|
||||
|
||||
|
||||
def test_review_case_without_or_with_multiple_candidates_never_picks_a_machine_source(app):
|
||||
"""无 Candidate 和旧多 Candidate 都必须创建 Case,但不得任意选择机器结果作为来源。"""
|
||||
with app.app_context():
|
||||
@@ -270,10 +312,13 @@ def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(ap
|
||||
user_id=user.id, case_no=case.case_no, line_key='machine-1', field_id='qty-id', value='3',
|
||||
expected_draft_version=2,
|
||||
)
|
||||
# 关键断言:单字段改动不会清除其他字段,校验结果仍保留到 Draft。
|
||||
# 关键断言:单字段改动不会触发整单必填校验,避免用户逐项编辑时被其他空字段阻断。
|
||||
assert updated['draft']['lines'][0]['values']['qty-id']['value'] == '3'
|
||||
assert updated['draft']['validation']['status'] == 'ready'
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id).count() == 3
|
||||
assert updated['draft']['validation']['status'] == 'not_validated'
|
||||
assert updated['draft']['issues'] == []
|
||||
validated = validate_draft(user_id=user.id, case_no=case.case_no, expected_draft_version=3)
|
||||
assert validated['draft']['validation']['status'] == 'ready'
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id).count() == 4
|
||||
|
||||
|
||||
def test_review_draft_empty_line_and_last_line_delete_remain_blocking(app):
|
||||
@@ -303,16 +348,19 @@ def test_review_draft_empty_line_and_last_line_delete_remain_blocking(app):
|
||||
db.session.commit()
|
||||
|
||||
added = add_line(user_id=user.id, case_no=case.case_no, expected_draft_version=1)
|
||||
assert added['draft']['validation']['status'] == 'needs_review'
|
||||
assert any(item['code'] == 'required_field_missing' for item in added['draft']['issues'])
|
||||
assert added['draft']['validation']['status'] == 'not_validated'
|
||||
assert added['draft']['issues'] == []
|
||||
validated = validate_draft(user_id=user.id, case_no=case.case_no, expected_draft_version=2)
|
||||
assert validated['draft']['validation']['status'] == 'needs_review'
|
||||
assert any(item['code'] == 'required_field_missing' for item in validated['draft']['issues'])
|
||||
|
||||
deleted_empty = delete_line(
|
||||
user_id=user.id, case_no=case.case_no, line_key=added['draft']['lines'][-1]['line_key'],
|
||||
expected_draft_version=2,
|
||||
expected_draft_version=3,
|
||||
)
|
||||
deleted = delete_line(user_id=user.id, case_no=case.case_no, line_key='machine-1', expected_draft_version=3)
|
||||
assert deleted_empty['draft']['validation']['status'] == 'ready'
|
||||
assert deleted['draft']['validation']['status'] == 'needs_review'
|
||||
deleted = delete_line(user_id=user.id, case_no=case.case_no, line_key='machine-1', expected_draft_version=4)
|
||||
assert deleted_empty['draft']['validation']['status'] == 'not_validated'
|
||||
assert deleted['draft']['validation']['status'] == 'not_validated'
|
||||
assert not deleted['draft']['lines']
|
||||
|
||||
|
||||
@@ -341,6 +389,79 @@ def test_review_evidence_is_case_scoped_and_omits_untrusted_bbox(app):
|
||||
assert 'storage_key' not in str(payload)
|
||||
|
||||
|
||||
def test_review_evidence_normalizes_frozen_layout_coordinates(app):
|
||||
"""坐标订单字段必须以冻结页尺寸换算为前端可绘制 bbox,并准确切换证据页。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-COORDINATE-EVIDENCE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
intake_snapshot = dict(snapshot['intakes'][0])
|
||||
document_snapshot = dict(intake_snapshot['documents'][0])
|
||||
document_snapshot['layout_snapshot'] = {
|
||||
'coordinate_evidence': {'pages': {'2': {'width': 800, 'height': 1000}}},
|
||||
}
|
||||
intake_snapshot['documents'] = [document_snapshot]
|
||||
snapshot['intakes'] = [intake_snapshot]
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [{
|
||||
'field_id': 'ship-to', 'observations': [{
|
||||
'value': 'Example', 'quote': 'Example',
|
||||
'layout_evidence': {
|
||||
'page_no': 2, 'source': 'pdf_coordinate',
|
||||
'value_bbox': {'x0': 80, 'y0': 200, 'x1': 400, 'y1': 300},
|
||||
},
|
||||
}],
|
||||
}], 'lines': []}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
item = list_case_evidence(user_id=user.id, case_no=case.case_no)['items'][0]
|
||||
|
||||
assert item['page_no'] == 2
|
||||
assert item['source'] == 'pdf_coordinate'
|
||||
assert item['bbox'] == {'x0': 0.1, 'y0': 0.2, 'x1': 0.5, 'y1': 0.3}
|
||||
|
||||
|
||||
def test_review_evidence_resolves_line_cell_bbox_from_frozen_layout(app):
|
||||
"""明细只可按冻结 table/cell 坐标高亮,不能根据行列或文本位置猜测。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-LINE-CELL-EVIDENCE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
intake_snapshot = dict(snapshot['intakes'][0])
|
||||
document_snapshot = dict(intake_snapshot['documents'][0])
|
||||
document_snapshot['layout_snapshot'] = {
|
||||
'layout_candidate': {
|
||||
'pages': [{
|
||||
'page_no': 1, 'width': 1000, 'height': 500,
|
||||
'tables': [{'table_id': 'table-lines', 'rows': [{'cells': [{
|
||||
'cell_id': 'line-0-part', 'bbox': {'x0': 100, 'y0': 200, 'x1': 350, 'y1': 250},
|
||||
}]}]}],
|
||||
}],
|
||||
},
|
||||
}
|
||||
intake_snapshot['documents'] = [document_snapshot]
|
||||
snapshot['intakes'] = [intake_snapshot]
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [{
|
||||
'field_id': 'part-number', 'observations': [{
|
||||
'value': 'PART-1', 'quote': 'PART-1', 'table_id': 'table-lines', 'cell_id': 'line-0-part',
|
||||
}],
|
||||
}]}]}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
item = list_case_evidence(user_id=user.id, case_no=case.case_no)['items'][0]
|
||||
|
||||
# 关键断言:明细精确按冻结单元格投影到第 1 页,归一化坐标可直接供 PDF canvas 绘制。
|
||||
assert item['line_index'] == 0
|
||||
assert item['page_no'] == 1
|
||||
assert item['source'] == 'frozen_layout_cell'
|
||||
assert item['bbox'] == {'x0': 0.1, 'y0': 0.4, 'x1': 0.35, 'y1': 0.5}
|
||||
|
||||
|
||||
def test_manual_draft_and_dispositions_are_case_scoped_and_preserve_machine_facts(app):
|
||||
"""无 Candidate 仅能启用唯一草稿;非订单和质量异常不删除当前 PDF 的机器历史。"""
|
||||
with app.app_context():
|
||||
@@ -425,6 +546,9 @@ def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(a
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
assert case.status == 'superseded'
|
||||
assert case.disposition == 'reparsed'
|
||||
# 关键断言:旧 Run 明确投影后继编号,前端可跳转而非把已替代 Case 渲染为空白。
|
||||
run.superseded_by_run_id = replacement.id
|
||||
assert serialize_review_run(run)['superseded_by_run_no'] == replacement.run_no
|
||||
try:
|
||||
reparse_case_document(user_id=user.id, case_no=case.case_no, reason='other')
|
||||
except Exception as exc:
|
||||
|
||||
@@ -22,6 +22,7 @@ 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
|
||||
|
||||
|
||||
def _config(field_id: str, name: str, *, value_type: str) -> dict:
|
||||
@@ -71,6 +72,40 @@ def _save_and_publish(draft: dict, fields: list[dict]) -> dict:
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('normalizer', ['lowercase_trim', 'uppercase_trim'])
|
||||
def test_text_normalizers_preserve_source_case_for_user_visible_values(normalizer):
|
||||
"""大小写规则只服务于匹配;PDF 提取后展示和保存的业务文本必须保持原文。"""
|
||||
assert normalize_order_field_value(
|
||||
'Inventec D4-A08AR12000002 USD',
|
||||
{'value_type': 'string', 'normalizer_key': normalizer},
|
||||
) == 'Inventec D4-A08AR12000002 USD'
|
||||
|
||||
|
||||
def test_dynamic_schema_rejects_text_evidence_with_only_case_difference(app):
|
||||
"""Schema v1 不得让大小写不同的 PDF 引文证明文本字段值。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [_config(part['id'], '内部料号', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'Part No: abc-123'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [], 'lines': [{'fields': [{'field_id': part['id'], 'observations': [{
|
||||
'value': 'ABC-123', 'document_id': document.id, 'quote': 'Part No: abc-123',
|
||||
}]}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='c' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
assert result['blocked_fields'] == ['part_number']
|
||||
assert result['lines'] == [{}]
|
||||
|
||||
|
||||
def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
"""自动建单开关写入草稿 definition;发布后才生效,并写入审计摘要。"""
|
||||
from app.core.errors import ConflictError
|
||||
@@ -124,8 +159,8 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
assert published_event.after_snapshot_json.get('auto_creation_policy') == {'enabled': True}
|
||||
|
||||
|
||||
def test_schema_save_rejects_normalized_table_alias_collision(app):
|
||||
"""草稿保存阶段即应拒绝不同字段占用同一标准化表头,避免歧义进入发布版本。"""
|
||||
def test_schema_save_allows_case_distinct_table_aliases(app):
|
||||
"""Schema v1 可保存仅大小写不同的别名,运行期按精确大小写匹配。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
@@ -136,13 +171,13 @@ def test_schema_save_rejects_normalized_table_alias_collision(app):
|
||||
second = _config(customer['id'], '客户料号', value_type='string')
|
||||
second['aliases'] = ['customer p n']
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
service.save_draft(draft['id'], {
|
||||
'fields': [first, second], 'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [first, second], 'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
assert caught.value.details['table_header_collisions']
|
||||
assert [item['aliases'] for item in saved['definition']['fields']] == [
|
||||
['Customer P/N'], ['customer p n'],
|
||||
]
|
||||
|
||||
|
||||
def test_retired_run_schema_keeps_its_frozen_table_aliases(app):
|
||||
@@ -171,7 +206,7 @@ def test_retired_run_schema_keeps_its_frozen_table_aliases(app):
|
||||
|
||||
frozen_version = db.session.get(ShippingOrderSchemaVersion, first['id'])
|
||||
frozen_contract = compile_table_header_contract(frozen_version.definition_json or {})
|
||||
assert frozen_contract.header_to_field['legacy sku'] == 'part_number'
|
||||
assert frozen_contract.header_to_field['Legacy SKU'] == 'part_number'
|
||||
assert parse_notice_table_text(documents[1].extracted_text, contract=frozen_contract) == [{
|
||||
'part_number': 'PART-FROZEN', 'qty': 4.0,
|
||||
}]
|
||||
@@ -407,6 +442,43 @@ def test_confirmed_order_field_coordinate_evidence_is_persisted_and_backend_mark
|
||||
assert observation.evidence_ref == f'document:{documents[1].id}:order-field:{po["id"]}:page:1'
|
||||
|
||||
|
||||
def test_email_supplement_table_evidence_is_accepted_for_reservation_id(app):
|
||||
"""邮件分配表按 PO+MPN 合并后,预约单号必须保留为已验证行字段。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
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(reservation['id'], '预约单号', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
body = documents[0]
|
||||
body.document_type = 'email_body'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [], 'lines': [{'fields': [{'field_id': reservation['id'], 'observations': [{
|
||||
'value': '4000111701', 'document_id': body.id, 'quote': '4000111701',
|
||||
'email_supplement_evidence': {
|
||||
'table_index': 1, 'row_index': 2, 'column_index': 1,
|
||||
'cell_id': 'email-supplement:test:1:r2:c1',
|
||||
},
|
||||
}]}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='s' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
observation = ShippingOrderFieldObservation.query.filter_by(
|
||||
extraction_id=result['extraction'].id, field_id=reservation['id'],
|
||||
).one()
|
||||
assert result['lines'] == [{'reservation_id': '4000111701'}]
|
||||
assert result['blocked_fields'] == []
|
||||
assert observation.source_type == 'email_body_table'
|
||||
assert observation.extractor == 'email_allocation_table'
|
||||
assert observation.evidence_metadata_json['cell_id'] == 'email-supplement:test:1:r2:c1'
|
||||
|
||||
|
||||
def test_dynamic_schema_contract_and_cross_document_persistence(app):
|
||||
"""同一字段在 EML 与 PDF 一致时应 corroborated,并生成类型化值与 field_code 投影。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
backend/tests/test_shipping_progress_audit_contract_stage0.py
|
||||
|
||||
用途:验收处理进度细化与全链路审计阶段 0 契约冻结。
|
||||
依赖:progress_audit_contract、order_extraction_progress、ShippingOrderExtractionRun/Unit ORM、Alembic head。
|
||||
逻辑:核对状态词典、取消事件码、模型取消字段与迁移 head,确保后续阶段不漂移契约。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic.config import Config
|
||||
from alembic.script import ScriptDirectory
|
||||
|
||||
from app.models.shipping_audit_event import ShippingAuditEvent
|
||||
from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_progress import (
|
||||
MAPPING_VERSION,
|
||||
WORKSPACE_EVENT_CODES,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
CANCEL_PROGRESS_EVENT_CODES,
|
||||
HEALTH_TIP_CODES,
|
||||
HEALTH_TIP_THRESHOLDS_SECONDS,
|
||||
PROGRESS_MAPPING_VERSION,
|
||||
RUN_STATUSES,
|
||||
UNIT_STATUSES,
|
||||
USER_VISIBLE_STAGES,
|
||||
WORKSPACE_AVAILABLE_ACTIONS,
|
||||
)
|
||||
|
||||
|
||||
def test_stage0_status_and_stage_dictionaries_are_unique_source():
|
||||
"""状态、用户可见阶段与健康提示必须形成唯一冻结词典。"""
|
||||
assert RUN_STATUSES == {
|
||||
'queued', 'processing', 'completed', 'partially_completed',
|
||||
'review_required', 'failed', 'cancelled',
|
||||
}
|
||||
assert UNIT_STATUSES == {
|
||||
'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement',
|
||||
'candidate_ready', 'review_required', 'failed', 'cancelled',
|
||||
}
|
||||
assert 'cancellation_requested' in USER_VISIBLE_STAGES
|
||||
assert HEALTH_TIP_CODES == {'processing_slow', 'queue_backlog', 'processing_attention'}
|
||||
assert HEALTH_TIP_THRESHOLDS_SECONDS['processing_slow'] == 60
|
||||
assert HEALTH_TIP_THRESHOLDS_SECONDS['queue_backlog'] == 300
|
||||
assert HEALTH_TIP_THRESHOLDS_SECONDS['processing_attention'] == 1800
|
||||
assert {'cancel_run', 'cancel_unit', 'refresh_status'} <= WORKSPACE_AVAILABLE_ACTIONS
|
||||
|
||||
|
||||
def test_stage0_progress_mapping_includes_cancel_events():
|
||||
"""进度映射 v3 必须允许取消相关事件码写入(阶段 1 才会真正产生事件)。"""
|
||||
assert MAPPING_VERSION == PROGRESS_MAPPING_VERSION == 'shipping-order-progress-v3'
|
||||
assert CANCEL_PROGRESS_EVENT_CODES <= WORKSPACE_EVENT_CODES
|
||||
|
||||
|
||||
def test_stage0_run_unit_models_expose_cancellation_contract():
|
||||
"""Run/Unit ORM 必须具备取消请求元数据与活动版本字段。"""
|
||||
run_cols = set(ShippingOrderExtractionRun.__table__.columns.keys())
|
||||
unit_cols = set(ShippingOrderExtractionUnit.__table__.columns.keys())
|
||||
for name in (
|
||||
'cancellation_requested_at', 'cancellation_actor_type', 'cancellation_actor_id',
|
||||
'cancellation_reason', 'cancellation_reason_code', 'cancellation_completed_at',
|
||||
'progress_version',
|
||||
):
|
||||
assert name in run_cols
|
||||
for name in (
|
||||
'activity_version', 'cancellation_requested_at', 'cancellation_actor_type',
|
||||
'cancellation_actor_id', 'cancellation_reason', 'cancellation_reason_code',
|
||||
'cancellation_completed_at',
|
||||
):
|
||||
assert name in unit_cols
|
||||
|
||||
|
||||
def test_stage0_audit_model_exposes_extended_contract_columns():
|
||||
"""审计模型必须具备 operation_id、快照、证据引用与保留到期字段。"""
|
||||
cols = set(ShippingAuditEvent.__table__.columns.keys())
|
||||
for name in (
|
||||
'operation_id', 'actor_role', 'source', 'result', 'error_code', 'conversation_id',
|
||||
'unit_id', 'document_id', 'review_case_no', 'attempt_no', 'action', 'reason',
|
||||
'before_snapshot_json', 'after_snapshot_json', 'evidence_refs_json',
|
||||
'artifact_refs_json', 'context_refs_json', 'retention_expires_at',
|
||||
):
|
||||
assert name in cols
|
||||
|
||||
|
||||
def test_stage0_alembic_head_includes_progress_audit_migration():
|
||||
"""迁移链必须包含阶段 0 契约 revision(可为祖先,不必是唯一 head)。"""
|
||||
config = Config()
|
||||
config.set_main_option('script_location', 'migrations')
|
||||
script = ScriptDirectory.from_config(config)
|
||||
revision = script.get_revision('2b4c6d8e0f1a')
|
||||
assert revision is not None
|
||||
assert revision.down_revision == '1a3b5c7d9e0f'
|
||||
# 后续迁移可能接在其后;只要各 head 从 base 升级路径包含该 revision 即可。
|
||||
heads = list(script.get_heads())
|
||||
assert heads, 'Alembic heads must not be empty'
|
||||
for head in heads:
|
||||
path = {rev.revision for rev in script.walk_revisions('base', head)}
|
||||
assert '2b4c6d8e0f1a' in path, f'head {head} missing progress/audit revision 2b4c6d8e0f1a'
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
backend/tests/test_shipping_progress_feature_flags.py
|
||||
|
||||
用途:验收进度 UI v3 / 取消 / 审计导出功能开关与回滚语义。
|
||||
依赖:progress_feature_flags、cancel_service、audit_query_service、Flask testing config。
|
||||
逻辑:关闭开关后 API 拒绝且投影不暴露取消动作;关闭导出不影响列表可读。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
export_shipping_audit_events,
|
||||
list_shipping_audit_events,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import cancel_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from app.services.shipping_notice.progress_feature_flags import progress_feature_flags_payload
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_feature_flags_payload_defaults_enabled(app):
|
||||
"""默认三开关均为开启,便于灰度前全量验证。"""
|
||||
with app.app_context():
|
||||
flags = progress_feature_flags_payload()
|
||||
assert flags == {
|
||||
'progress_ui_v3': True,
|
||||
'cancel_enabled': True,
|
||||
'audit_export_enabled': True,
|
||||
}
|
||||
|
||||
|
||||
def test_cancel_feature_flag_blocks_api_and_projection(app):
|
||||
"""关闭取消开关后投影无 cancel_run,直接调用取消 API 返回 FEATURE_DISABLED。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='FLAG-CANCEL')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
app.config['SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED'] = False
|
||||
projection = serialize_workspace_run(run)
|
||||
# 关键断言:回滚取消能力时前端拿不到取消按钮事实。
|
||||
assert 'cancel_run' not in projection['available_actions']
|
||||
assert projection['feature_flags']['cancel_enabled'] is False
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
cancel_order_extraction_run(actor=user, run_no=run.run_no)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.CANCEL_FEATURE_DISABLED'
|
||||
|
||||
|
||||
def test_progress_ui_v3_flag_suppresses_health_tips(app):
|
||||
"""关闭进度 UI v3 时不下发健康提示,但保留阶段事实字段。"""
|
||||
with app.app_context():
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='FLAG-UI')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
run.status = 'processing'
|
||||
run.phase = 'extracting'
|
||||
run.started_at = datetime.utcnow() - timedelta(minutes=40)
|
||||
run.last_activity_at = datetime.utcnow() - timedelta(minutes=5)
|
||||
db.session.commit()
|
||||
|
||||
app.config['SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED'] = False
|
||||
projection = serialize_workspace_run(run)
|
||||
assert projection['feature_flags']['progress_ui_v3'] is False
|
||||
assert projection['health_tips'] == []
|
||||
assert projection['user_visible_stage']
|
||||
|
||||
|
||||
def test_audit_export_flag_blocks_export_only(app):
|
||||
"""关闭导出开关后 list 仍可读,export 拒绝且不删除既有审计。"""
|
||||
with app.app_context():
|
||||
append_shipping_audit_event(
|
||||
event_type='flag_probe',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-FLAG-AUDIT',
|
||||
run_no='SNER-FLAG-AUDIT',
|
||||
)
|
||||
db.session.commit()
|
||||
app.config['SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED'] = False
|
||||
|
||||
listed = list_shipping_audit_events(
|
||||
admin_user_id=1,
|
||||
request_id='req-flag-list',
|
||||
filters={'run_no': 'SNER-FLAG-AUDIT'},
|
||||
)
|
||||
assert listed['total'] >= 1
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
export_shipping_audit_events(
|
||||
admin_user_id=1,
|
||||
request_id='req-flag-export',
|
||||
filters={'run_no': 'SNER-FLAG-AUDIT'},
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_EXPORT_FEATURE_DISABLED'
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
tests/test_shipping_progress_stage3_diagnostics.py
|
||||
|
||||
用途:覆盖阶段 3 任务中心分页与管理员诊断筛选(积压/取消中)及健康 P50。
|
||||
依赖:pytest、Flask app fixture、order_extraction_run_service。
|
||||
逻辑:断言用户仅看到自己的 Run;管理员列表可按取消中过滤;latency 含 p50_ms。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderExtractionRun
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
get_order_extraction_run_health,
|
||||
list_order_extraction_diagnostic_runs,
|
||||
list_order_extraction_runs,
|
||||
)
|
||||
|
||||
|
||||
def _seed(app, suffix: str):
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
return _seed_run_input(suffix=suffix)
|
||||
|
||||
|
||||
def test_list_order_extraction_runs_paginates_for_owner(app):
|
||||
"""任务中心分页只返回当前用户 Run,并支持状态过滤。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed(app, 'S3PAGE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
payload = list_order_extraction_runs(
|
||||
user_id=user.id,
|
||||
page=1,
|
||||
page_size=10,
|
||||
status='queued',
|
||||
)
|
||||
assert isinstance(payload, dict)
|
||||
assert payload['total'] >= 1
|
||||
assert any(item.run_no == run.run_no for item in payload['items'])
|
||||
empty = list_order_extraction_runs(user_id=user.id, page=1, page_size=10, status='failed')
|
||||
assert empty['total'] == 0 or all(item.status == 'failed' for item in empty['items'])
|
||||
|
||||
|
||||
def test_diagnostic_list_filters_cancellation_in_flight(app):
|
||||
"""管理员诊断列表可筛出取消中的 Run。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed(app, 'S3CANCEL')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
run.status = 'processing'
|
||||
run.phase = 'processing'
|
||||
run.cancellation_requested_at = datetime.utcnow()
|
||||
run.cancellation_actor_type = 'user'
|
||||
run.cancellation_actor_id = str(user.id)
|
||||
db.session.commit()
|
||||
|
||||
payload = list_order_extraction_diagnostic_runs(
|
||||
admin_user_id=user.id,
|
||||
request_id='stage3-test',
|
||||
page=1,
|
||||
page_size=25,
|
||||
cancellation_in_flight=True,
|
||||
)
|
||||
assert any(item['run_no'] == run.run_no for item in payload['items'])
|
||||
hit = next(item for item in payload['items'] if item['run_no'] == run.run_no)
|
||||
assert hit['cancellation']['in_flight'] is True
|
||||
assert 'error_message' not in hit
|
||||
|
||||
|
||||
def test_health_latency_includes_p50(app):
|
||||
"""健康汇总 latency 必须同时提供 P50 与 P95。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed(app, 'S3P50')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
base = datetime.utcnow() - timedelta(minutes=3)
|
||||
run.created_at = base
|
||||
run.started_at = base + timedelta(seconds=2)
|
||||
run.extraction_completed_at = base + timedelta(seconds=5)
|
||||
run.result_persisted_at = base + timedelta(seconds=6)
|
||||
run.finished_at = base + timedelta(seconds=8)
|
||||
run.status = 'completed'
|
||||
run.phase = 'completed'
|
||||
db.session.commit()
|
||||
|
||||
report = get_order_extraction_run_health(now=base + timedelta(seconds=10))
|
||||
assert report['latency']['total']['p50_ms'] is not None
|
||||
assert report['latency']['total']['p95_ms'] is not None
|
||||
@@ -0,0 +1,225 @@
|
||||
"""
|
||||
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
|
||||
@@ -0,0 +1,739 @@
|
||||
"""
|
||||
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'
|
||||
Reference in new issue
Block a user