!11 feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理

Merge pull request !11 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
sophie authored and Gitee committed 2026-08-26 00:25:10 +00:00
commit 2ff9fdafe4
402 files changed
+23045 -20484

No files matched your search

+1 -1
View File
@@ -251,7 +251,7 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction
db.session.flush()
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
customer = getattr(getattr(task, 'shipping_case', None), 'customer', None)
customer = getattr(task, 'customer', None)
if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by(
extraction_id=extraction.id, role='bill_to',
).one_or_none() is None:
+1 -1
View File
@@ -36,7 +36,7 @@ def test_handler_error_rolls_back_before_mark_failed(monkeypatch):
class _Db:
session = _Session()
job = {'id': 939, 'job_type': 'shipping_auto_progress', 'attempts': 1, 'payload': {}}
job = {'id': 939, 'job_type': 'shipping_process_gate', 'attempts': 1, 'payload': {}}
monkeypatch.setattr(runner.store, 'claim_next', lambda **_kwargs: job)
monkeypatch.setattr(runner, 'get_handler', lambda _job_type: lambda *_args: (_ for _ in ()).throw(RuntimeError('db failed')))
monkeypatch.setattr(runner.store, 'mark_failed', lambda *_args, **_kwargs: (events.append('mark_failed'), (_ for _ in ()).throw(StopIteration)))
@@ -16,7 +16,7 @@ from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCase,
ShippingNotice,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
@@ -74,14 +74,14 @@ def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
@pytest.mark.parametrize('reference_kind', [
'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
])
def test_business_and_audit_references_block_delete(app, reference_kind: str):
"""每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。"""
with app.app_context():
customer = _customer()
if reference_kind == 'case':
db.session.add(ShippingCase(case_no='CASE-LIFECYCLE', customer_id=customer.id))
if reference_kind == 'notice':
db.session.add(ShippingNotice(task_no='SN-LIFECYCLE', customer_id=customer.id))
elif reference_kind == 'sequence':
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
elif reference_kind == 'external_ref':
@@ -194,14 +194,14 @@ def test_delete_unused_customer_cascades_configurable_identity_evidence(app):
@pytest.mark.parametrize('reference_kind', [
'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
])
def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str):
"""永久删除必须复用完整生命周期统计,任一业务或审计引用均返回冲突。"""
with app.app_context():
customer = _customer('BLK')
if reference_kind == 'case':
db.session.add(ShippingCase(case_no='CASE-DELETE-BLOCK', customer_id=customer.id))
if reference_kind == 'notice':
db.session.add(ShippingNotice(task_no='SN-DELETE-BLOCK', customer_id=customer.id))
elif reference_kind == 'sequence':
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
elif reference_kind == 'external_ref':
@@ -267,13 +267,13 @@ def test_delete_blocks_reference_created_after_preview(app):
preview = get_customer_lifecycle_impact(customer.id)
assert preview['can_delete'] is True
db.session.add(ShippingCase(case_no='CASE-DELETE-RACE', customer_id=customer.id))
db.session.add(ShippingNotice(task_no='SN-DELETE-RACE', customer_id=customer.id))
db.session.commit()
with pytest.raises(ConflictError) as exc_info:
delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None)
assert exc_info.value.code == 'SHIPPING.CUSTOMER_DELETE_BLOCKED'
assert exc_info.value.details['blockers']['business_cases'] == 1
assert exc_info.value.details['blockers']['shipping_notices'] == 1
assert db.session.get(ShippingCustomer, customer.id) is not None
@@ -16,7 +16,7 @@ from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCase,
ShippingNotice,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
@@ -71,8 +71,8 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
normalized_value='same@example.com', status='approved', source='manual',
),
ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'),
ShippingCase(
case_no='CASE-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
ShippingNotice(
task_no='SN-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
),
ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1),
@@ -82,7 +82,7 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
target_id = target.id
preview = get_customer_merge_impact(source_id, target_id)
assert preview['historical_references']['business_cases'] == 1
assert preview['historical_references']['shipping_notices'] == 1
# 合并预检同时展示旧识别证据与阶段一可配置证据的迁移统计。
assert preview['migrate'] == {
'identifiers': 1, 'duplicate_identifiers': 1, 'identity_evidences': 0,
@@ -105,10 +105,10 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source_id).count() == 0
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2
assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1
historical_case = db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-HISTORY').one()
assert historical_case.customer_id == source_id
assert historical_case.business_no == 'SRC26071601'
assert historical_case.customer_short_code_snapshot == 'SRC'
historical_notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-HISTORY').one()
assert historical_notice.customer_id == source_id
assert historical_notice.business_no == 'SRC26071601'
assert historical_notice.customer_short_code_snapshot == 'SRC'
assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1
merge = db.session.get(ShippingCustomerMerge, result['merge_id'])
assert merge is not None and merge.source_customer_id_snapshot == source_id
@@ -13,7 +13,7 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent
from app.models import ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice
from app.services.admin.shipping_customer_service import (
create_customer,
create_identifier,
@@ -219,7 +219,7 @@ def test_customer_list_returns_preaggregated_reference_counts(app):
"""列表返回业务单和识别证据数量,避免管理端逐客户补查。"""
with app.app_context():
customer = _create_customer()
db.session.add(ShippingCase(case_no='CASE-COUNT-1', customer_id=customer['id']))
db.session.add(ShippingNotice(task_no='SN-COUNT-1', customer_id=customer['id']))
db.session.add(ShippingCustomerIdentifier(
customer_id=customer['id'],
identifier_type='name_alias',
@@ -231,5 +231,5 @@ def test_customer_list_returns_preaggregated_reference_counts(app):
db.session.commit()
result = list_customers({'page': 1, 'page_size': 20})
assert result['items'][0]['case_count'] == 1
assert result['items'][0]['notice_count'] == 1
assert result['items'][0]['identifier_count'] == 1
@@ -1,8 +1,8 @@
"""
tests/services/shipping_notice/test_reconciliation_phase34_contract.py
用途:Phase 3 统一 Projection 四事实 + Phase 4 管理端 replay 权限 +
BRANCH F ownership_anomaly rollback 的合同测试。
用途:Phase 3 统一 Projection 四事实 + Phase 4 BRANCH F
ownership_anomaly rollback 的合同测试。
依赖:recovery_contract、reconciliation_projector、
reconciliation_service.reconcile_and_progress(mock 掉 DB 层仅验证纯函数矩阵)。
逻辑:
@@ -14,9 +14,6 @@ tests/services/shipping_notice/test_reconciliation_phase34_contract.py
retryable/failed/running/idle)。
[P3 T4] project_case_primary_action 1a~1i CTA 分派矩阵。
[P3 T5] project_review_case_projection_bundle 六字段非空(Case + automation + actions)。
[P4 T6] reconcile_and_progress PRE-CHECK:
a) replay_mode=True + is_admin=False → SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED 422
b) legacy_job_id=999 + is_admin=False → 422
[P4 T7] ownership_anomaly BRANCH F:
断言触发路径最终 outcome=ownership_anomaly_rejected 且不会脏写
(这里只测 ValidationError 降级情形,Review Case 不含旧流程字段)。
@@ -287,7 +284,7 @@ def test_pending_order_freeze_readiness_waits_for_the_user_to_submit_validation(
# ============================================================
# [P4 T6] 管理员权限拦截(纯函数 PRE-CHECK,通过 monkeypatch 替换锁 DB 查询)
# [P4] BRANCH F 归属异常(通过 monkeypatch 替换锁 DB 查询)
# ============================================================
def _mock_case_for_p4(case_no='CASE-2608-0042'):
@@ -372,72 +369,6 @@ def _install_minimal_mocks(monkeypatch, case=None, app=None):
return case
@pytest.mark.pure_unit
def test_p4_t6a_replay_mode_without_admin_raises(monkeypatch):
"""[P4 T6a] replay_mode=True + is_admin=False → 422 SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
_install_minimal_mocks(monkeypatch)
with pytest.raises(ValidationError) as exc:
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='auto',
is_admin=False,
replay_mode=True,
)
assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED'
@pytest.mark.pure_unit
def test_p4_t6b_legacy_job_id_without_admin_raises(monkeypatch):
"""[P4 T6b] legacy_job_id=928 + is_admin=False → 422 权限拒绝。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
_install_minimal_mocks(monkeypatch)
with pytest.raises(ValidationError) as exc:
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='auto',
is_admin=False,
legacy_job_id=928,
)
assert exc.value.code == 'SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED'
@pytest.mark.pure_unit
def test_p4_t6c_legacy_job_requires_failed_or_dead(monkeypatch):
"""[P4 T6c] legacy_job 必须是 failed/dead,否则 422。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
_install_minimal_mocks(monkeypatch)
bad_job = _fake_job(job_id=991, status='running') # 不是失败态
from app.services.shipping_notice import reconciliation_service as mod
def _get(coll, jid): # noqa: ARG001
if str(getattr(coll, '__name__', '')) == 'Job' and jid == 991:
return bad_job
return None
monkeypatch.setattr(mod.db.session, 'get', _get)
with pytest.raises(ValidationError):
reconcile_and_progress(
user_id=1,
case_no='CASE-2608-0042',
operation_id=str(uuid.uuid4()),
user_action='auto',
is_admin=True,
legacy_job_id=991,
)
# ============================================================
# [P4 T7] BRANCH F ownership_anomaly 422 降级(Review Case 不含旧流程字段)
# ============================================================
+9 -11
View File
@@ -11,7 +11,6 @@ from __future__ import annotations
from app import db
from app.models import (
FileAsset,
ShippingCase,
ShippingCustomer,
ShippingCustomerIdentifier,
ShippingIdentityDefinition,
@@ -328,7 +327,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(
customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active')
db.session.add(customer)
db.session.flush()
db.session.add(ShippingCase(case_no='CASE-DELETE-API', customer_id=customer.id))
db.session.add(ShippingNotice(task_no='SN-DELETE-API', customer_id=customer.id))
db.session.commit()
customer_id = customer.id
@@ -364,7 +363,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias',
normalized_value='SOURCEALIAS', status='approved', source='manual',
),
ShippingCase(case_no='CASE-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
ShippingNotice(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
])
db.session.commit()
source_id = source.id
@@ -397,7 +396,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
with app.app_context():
assert db.session.get(ShippingCustomer, source_id).status == 'merged'
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1
assert db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-API').one().customer_id == source_id
assert db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one().customer_id == source_id
def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client):
@@ -517,11 +516,10 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
_create_users()
wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active')
correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active')
case = ShippingCase(case_no='CASE-CORRECTION-API', numbering_status='pending')
db.session.add_all([wrong, correct, case])
db.session.add_all([wrong, correct])
db.session.flush()
task = ShippingNotice(
task_no='SN-CORRECTION-API', shipping_case_id=case.id,
task_no='SN-CORRECTION-API',
source_type='manual', customer_resolution_status='pending',
)
db.session.add(task)
@@ -529,7 +527,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
old_business_no = task.shipping_case.business_no
old_business_no = task.business_no
correct_id = correct.id
forbidden = client.post(
@@ -549,7 +547,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
assert payload['old_business_no'] == old_business_no
assert payload['new_business_no'].startswith('NEW')
with app.app_context():
old_case = ShippingCase.query.filter_by(business_no=old_business_no).one()
replacement = ShippingCase.query.filter_by(replaces_case_id=old_case.id).one()
assert old_case.status == 'voided'
old_notice = ShippingNotice.query.filter_by(business_no=old_business_no).one()
replacement = ShippingNotice.query.filter_by(supersedes_task_id=old_notice.id).one()
assert old_notice.lifecycle_status == 'voided'
assert replacement.business_no == payload['new_business_no']
@@ -26,7 +26,6 @@ def test_shipping_handler_builds_ui_state_event(app):
external_conversation_id=None,
request_id='req-1',
shipping_task_id='SN-TEST-001',
shipping_batch_no='SB-TEST',
)
event = handler.build_ui_state_event(ctx)
assert event is None or event.get('event') == 'shipping_ui_state'
+7 -123
View File
@@ -63,21 +63,11 @@ def _create_task_for_user(user_id: int) -> str:
return task.task_no
def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch):
def test_chat_turn_rejects_legacy_fulfillment_action(app, client):
user = _create_user()
agent = _create_shipping_agent()
task_no = _create_task_for_user(user.id)
monkeypatch.setattr(
"app.services.shipping_notice.chat_action_handlers.submit_decision",
lambda payload: {
"status": "ok",
"message": "已确认,请继续下一步。",
"task_id": task_no,
"data": {},
},
)
res = client.post(
"/api/chat/turns/stream",
headers={
@@ -99,14 +89,8 @@ def test_chat_turn_submit_decision_emits_run_lifecycle(app, client, monkeypatch)
events = _parse_sse_events(res.get_data(as_text=True))
event_names = [item.get("event") for item in events]
assert "run.started" in event_names
assert "step.started" in event_names
assert "message.completed" in event_names or "message_end" in event_names
assert "run.completed" in event_names
logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
assert len(logs) == 1
assert logs[0].query == "确认"
assert "已确认" in logs[0].answer
assert "run.failed" in event_names
assert "run.completed" not in event_names
def test_chat_turn_unknown_action_returns_failed(app, client):
@@ -154,11 +138,11 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
assert any(item.get("event") == "run.failed" for item in events)
def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, tmp_path):
def test_chat_turn_multipart_upload_rejects_removed_batch_action(app, client, tmp_path):
"""
multipart 上传时 agent_id 应从 form 字段解析;create_batch_from_notices 已下线为 410。
multipart 上传时 agent_id 应从 form 字段解析;旧建批 action 不再注册。
关键断言:form 带 agent_id 时 run 能启动;建批动作固定 BATCHES_REMOVED(非 agent 解析失败)。
关键断言:form 带 agent_id 时 run 能启动;旧 action 作为未知 action 失败。
"""
from io import BytesIO
@@ -191,8 +175,7 @@ def test_chat_turn_multipart_upload_reads_agent_id_from_form(app, client, tmp_pa
assert "run.failed" in event_names
assert "run.completed" not in event_names
failed = next(item for item in events if item.get("event") == "run.failed")
# 关键断言:SSE run.failed 顶层带业务 code(非嵌套 data)。
assert failed.get("code") == "SHIPPING.BATCHES_REMOVED"
assert failed.get("code") == "RESOURCE.NOT_FOUND"
def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, client, monkeypatch):
@@ -239,102 +222,3 @@ def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, clie
assert all('schema_preview' not in payload for payload in assistant_payloads)
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_chat_turn_create_batch_forwards_idempotency_key(app, client, monkeypatch, tmp_path):
"""shipping.create_batch_from_notices 应透传 payload 中的建单幂等键。"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
captured: dict = {}
def fake_create(**kwargs):
captured.update(kwargs)
return {
"status": "ok",
"batch_no": "SB-CHAT-IDEM-001",
"data": {
"tasks": [{"task_id": "SN-CHAT-IDEM-001"}],
"focus_task": {"task_no": "SN-CHAT-IDEM-001"},
},
}
monkeypatch.setattr(
"app.services.shipping_notice.batch_from_notices.create_shipping_batch_from_notice_items",
fake_create,
)
res = client.post(
"/api/chat/turns/stream",
headers={"X-Username": user.username, "X-Role": user.role},
data={
"agent_id": str(agent.id),
"input": json.dumps(
{
"type": "upload_followup",
"display_text": "上传发货通知:notice.txt",
"action_type": "shipping.create_batch_from_notices",
"payload": {"idempotency_key": "chat-idem-001"},
},
ensure_ascii=False,
),
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice.txt"),
},
content_type="multipart/form-data",
)
assert res.status_code == 200
res.get_data(as_text=True)
assert captured.get("create_idempotency_key") == "chat-idem-001"
notice_items = captured.get("notice_items") or []
assert notice_items
assert notice_items[0].get("source_content_hash")
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_chat_turn_create_batch_idempotent_replay(app, client, monkeypatch, tmp_path):
"""相同幂等键重复 Chat Turn 不重复建批,并返回可恢复 UI state。"""
from io import BytesIO
user = _create_user()
agent = _create_shipping_agent()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path)
orchestrator_calls: list[str] = []
monkeypatch.setattr(
"app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator",
lambda batch_no: orchestrator_calls.append(batch_no) or True,
)
payload_input = {
"type": "upload_followup",
"display_text": "上传发货通知:notice.txt",
"action_type": "shipping.create_batch_from_notices",
"payload": {"idempotency_key": "chat-replay-integration-001"},
}
headers = {"X-Username": user.username, "X-Role": user.role}
raw = "客户:ACME\nA001 x 10".encode("utf-8")
def _post_turn():
return client.post(
"/api/chat/turns/stream",
headers=headers,
data={
"agent_id": str(agent.id),
"input": json.dumps(payload_input, ensure_ascii=False),
"files": (BytesIO(raw), "notice.txt"),
},
content_type="multipart/form-data",
)
first = _post_turn()
assert first.status_code == 200
first_events = _parse_sse_events(first.get_data(as_text=True))
assert "run.failed" not in [item.get("event") for item in first_events]
second = _post_turn()
assert second.status_code == 200
second_events = _parse_sse_events(second.get_data(as_text=True))
completed = [item for item in second_events if item.get("event") == "message.completed"]
assert completed
assert "已恢复此前创建的批次" in str(completed[-1].get("content", ""))
assert len(orchestrator_calls) == 1
+154 -1
View File
@@ -6,6 +6,8 @@
from __future__ import annotations
import pytest
from app.services.shipping_notice.email_allocation_table_parser import (
parse_email_allocation_tables,
parse_email_allocation_text,
@@ -87,6 +89,19 @@ def test_email_supplement_external_reservation_id_alias_merges_real_mail_header(
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
def test_email_supplement_uses_schema_alias_order_for_duplicate_source_headers():
"""同字段的两个邮件列按 Schema aliases 顺序取值,不能整表拒绝。"""
supplement = parse_email_allocation_tables(
content_hash='h' * 64,
schema_definition=SCHEMA,
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Source Type</th><th>hub code</th></tr><tr><td>4518738152</td><td>D4-A08AR12000002</td><td>FIRST-SOURCE</td><td>SECOND-HUB</td></tr></table>'''],
)
assert supplement['issues'] == []
assert supplement['rows'][0]['inventory_source_hint'] == 'FIRST-SOURCE'
assert supplement['rows'][0]['evidence']['inventory_source_hint']['column_index'] == 2
def test_email_supplement_ampn_alias_matches_customer_part_number():
"""邮件 AMPN 应能与订单客户料号交叉关联并补入预约号。"""
order = _order()
@@ -139,7 +154,41 @@ def test_email_supplement_conflicting_schema_field_does_not_overwrite_pdf_or_pic
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
)[0]
assert not any(item['field_id'] == 'reservation' for item in merged['lines'][0]['fields'])
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
finding = next(item for item in merged['conflicts'] if item.get('field') == 'reservation_id')
assert finding['resolution_status'] == 'unresolved'
assert finding['scope'] == 'line'
assert finding['line_index'] == 0
assert finding['conflict_key'] == '0:reservation_id'
assert finding['values'] == ['33874', '33875']
assert [source['source_type'] for source in finding['sources']] == ['email_body', 'email_body']
@pytest.mark.pure_unit
def test_email_supplement_does_not_cross_compare_values_from_different_part_lines():
"""同 PO 的不同料号可有不同单价,补充合并只能比较同一目标行的关联正文行。"""
schema = {
'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
],
}
order = _order()
order['lines'][0]['fields'].append({'field_id': 'unit-price', 'observations': [{'value': '10.00'}]})
order['lines'].append({'fields': [
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]},
{'field_id': 'qty', 'observations': [{'value': 1}]},
{'field_id': 'unit-price', 'observations': [{'value': '20.00'}]},
]})
result = merge_email_supplements(
orders=[order],
supplements_by_intake={1: {'document_id': 304, 'rows': [
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '10.00', 'evidence': {}},
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000003', 'unit_price': '20.00', 'evidence': {}},
]}},
schema_definition=schema,
)[0]
assert not any(item.get('field') == 'unit_price' for item in result['conflicts'])
def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review():
@@ -166,6 +215,110 @@ def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review():
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
@pytest.mark.pure_unit
def test_email_supplement_treats_decimal_format_variants_as_the_same_value():
"""PDF 与邮件的金额仅格式不同,必须按 Schema decimal 语义比较而非制造冲突。"""
schema = {
'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
],
}
order = _order()
order['lines'][0]['fields'].append({
'field_id': 'unit-price', 'observations': [{'value': '1731.6'}],
})
supplement = {
'document_id': 44,
'rows': [{
'customer_po_number': '4518738152',
'part_number': 'D4-A08AR12000002',
'unit_price': '1,731.60',
'evidence': {},
}],
}
merged = merge_email_supplements(
orders=[order], supplements_by_intake={1: supplement}, schema_definition=schema,
)[0]
assert _value(merged['lines'][0]['fields'], 'unit-price') == '1731.6'
assert not any(item.get('field') == 'unit_price' for item in merged['conflicts'])
@pytest.mark.pure_unit
def test_email_supplement_decimal_difference_creates_a_complete_unresolved_finding():
"""真实金额不一致必须保留双方原值、规范值和邮件单元格证据,供复核直接裁决。"""
schema = {
'version': 'shipping-order-schema.v9',
'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
],
}
order = _order()
order['lines'][0]['fields'].append({
'field_id': 'unit-price', 'observations': [{
'value': '1731.60', 'document_id': 305, 'evidence_ref': {'page_no': 1, 'cell_id': 'pdf-unit-price'},
}],
})
supplement = {
'document_id': 304,
'rows': [{
'customer_po_number': '4518738152',
'part_number': 'D4-A08AR12000002',
'unit_price': '1732.00',
'evidence': {'unit_price': {'table_index': 0, 'row_index': 5, 'column_index': 4, 'cell_id': 'email-unit-price'}},
}],
}
merged = merge_email_supplements(
orders=[order], supplements_by_intake={1: supplement}, schema_definition=schema,
)[0]
finding = next(item for item in merged['conflicts'] if item.get('field') == 'unit_price')
assert finding['conflict_key'] == '0:unit_price'
assert finding['severity'] == 'blocking'
assert finding['resolution_status'] == 'unresolved'
assert finding['scope'] == 'line'
assert finding['line_index'] == 0
assert finding['values'] == ['1731.60', '1732.00']
assert finding['sources'] == [
{
'source_type': 'pdf', 'raw_value': '1731.60', 'canonical_value': '1731.60',
'document_id': 305, 'evidence_ref': {'page_no': 1, 'cell_id': 'pdf-unit-price'},
},
{
'source_type': 'email_body', 'raw_value': '1732.00', 'canonical_value': '1732.00',
'document_id': 304,
'evidence_ref': {'table_index': 0, 'row_index': 5, 'column_index': 4, 'cell_id': 'email-unit-price'},
},
]
assert finding['rule_version'] == 'shipping-order-schema.v9'
@pytest.mark.pure_unit
def test_email_supplement_duplicate_email_decimal_formats_do_not_create_a_conflict():
"""同一邮件补充行的等价金额格式必须按 decimal 归并,不能产生正文内部冲突。"""
schema = {
'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
],
}
result = merge_email_supplements(
orders=[_order()],
supplements_by_intake={1: {'document_id': 304, 'rows': [
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '1731.6', 'evidence': {}},
{'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002', 'unit_price': '1,731.60', 'evidence': {}},
]}},
schema_definition=schema,
)[0]
assert _value(result['lines'][0]['fields'], 'unit-price') == '1731.6'
assert not any(item.get('field') == 'unit_price' for item in result['conflicts'])
def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_numbers():
"""邮件 PN/AMPN 均可与订单内部/客户料号交叉匹配,不依赖字段名称相同。"""
scenarios = [
@@ -0,0 +1,108 @@
"""
tests/test_legacy_supplement_conflict_reassessment.py
用途:验证旧补充冲突不会被静默放行,而会升级为有稳定键的证据不足 Finding。
依赖:legacy_supplement_conflict_reassessment_service、pytest。
逻辑:纯函数层覆盖旧结构升级、非旧 Finding 保留以及重复旧记录收敛。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.legacy_supplement_conflict_reassessment_service import (
reassess_legacy_supplement_conflicts_from_frozen_order,
upgrade_legacy_supplement_conflicts,
)
from tests.test_email_supplement_merge import SCHEMA, _order
@pytest.mark.pure_unit
def test_upgrade_legacy_supplement_conflict_keeps_blocking_but_makes_recovery_visible():
"""旧 `{field, reason}` 不能被直接清除,须变为可展示的证据不足 Finding。"""
upgraded, count = upgrade_legacy_supplement_conflicts([{
'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price',
}])
assert count == 1
assert upgraded == [{
'conflict_key': '-1:unit_price', 'severity': 'blocking',
'reason': 'supplement_conflict_evidence_insufficient', 'resolution_status': 'unresolved',
'field': 'unit_price', 'scope': 'unscoped', 'line_index': None,
'values': [], 'sources': [], 'rule_version': 'legacy-supplement-conflict.v1',
'legacy_reason': 'supplement_field_conflict', 'recovery_action': 'reparse_current_pdf',
}]
@pytest.mark.pure_unit
def test_upgrade_legacy_supplement_conflict_does_not_touch_complete_current_finding():
"""已有新 Finding 的证据与裁决状态不可被历史迁移覆盖。"""
current = {
'conflict_key': '0:unit_price', 'severity': 'blocking',
'reason': 'supplement_field_conflict', 'resolution_status': 'unresolved',
'field': 'unit_price', 'values': ['1', '2'], 'sources': [{'source_type': 'pdf'}],
}
upgraded, count = upgrade_legacy_supplement_conflicts([current])
assert count == 0
assert upgraded == [current]
@pytest.mark.pure_unit
def test_upgrade_legacy_supplement_conflict_collapses_duplicate_legacy_identity():
"""同字段重复旧阻断升级后只有一项,避免一次操作产生多个不可裁决卡片。"""
upgraded, count = upgrade_legacy_supplement_conflicts([
{'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price'},
{'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'unit_price'},
])
assert count == 2
assert len(upgraded) == 1
@pytest.mark.pure_unit
def test_reassess_legacy_conflict_from_frozen_order_clears_decimal_format_false_positive():
"""冻结证据可恢复时,1731.6 与 1,731.60 必须按当前 decimal 规则清除旧假冲突。"""
schema = {'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
]}
order = _order()
order['lines'][0]['fields'].append({
'field_id': 'unit-price', 'observations': [{'value': '1731.6'}],
})
conflicts, status, count = reassess_legacy_supplement_conflicts_from_frozen_order(
candidate_conflicts=[{'reason': 'supplement_field_conflict', 'field': 'unit_price'}],
frozen_order=order,
supplements_by_intake={1: {'document_id': 304, 'rows': [{
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
'unit_price': '1,731.60', 'evidence': {},
}]}},
schema_definition=schema,
)
assert status == 'rebuilt'
assert count == 1
assert conflicts == []
@pytest.mark.pure_unit
def test_reassess_legacy_conflict_from_frozen_order_rebuilds_real_conflict_with_evidence():
"""冻结证据可恢复时,真实金额差异必须变为当前完整 Finding,而不是笼统旧阻断。"""
schema = {'fields': [
*SCHEMA['fields'],
{'field_id': 'unit-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
]}
order = _order()
order['lines'][0]['fields'].append({'field_id': 'unit-price', 'observations': [{
'value': '10.00', 'document_id': 305, 'evidence_ref': {'page_no': 1},
}]})
conflicts, status, _ = reassess_legacy_supplement_conflicts_from_frozen_order(
candidate_conflicts=[{'reason': 'supplement_field_conflict', 'field': 'unit_price'}],
frozen_order=order,
supplements_by_intake={1: {'document_id': 304, 'rows': [{
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
'unit_price': '11.00', 'evidence': {'unit_price': {'row_index': 1}},
}]}},
schema_definition=schema,
)
assert status == 'rebuilt'
assert conflicts[0]['conflict_key'] == '0:unit_price'
assert [source['document_id'] for source in conflicts[0]['sources']] == [305, 304]
@@ -55,6 +55,8 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi
assert created['profile_code'] != 'CLIENT_SUPPLIED_CODE'
assert created['draft_revision']['revision_no'] == 1
assert created['edit_lease']['browser_session_id'] == 'wizard-tab-a'
# 主表身份必须同时冻结在 Profile 定义和两类共同视觉样本上。
assert created['definition']['main_table_id'] == 'sample-table'
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1
assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1
@@ -115,6 +117,27 @@ def test_public_identity_signature_owns_coordinate_run_lifecycle(app, monkeypatc
assert signature['run_type'] == 'layout_signature'
def test_runtime_adapter_does_not_route_plain_pdf_by_stale_xfa_capability(monkeypatch):
"""关键断言:普通 PDF 的残留 XFA capability 不得改变正式值源路由。"""
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
monkeypatch.setattr(xfa_dataset, 'xfa_enabled', lambda: True)
stale_plain_pdf_layout = {
'document_kind': 'plain_pdf',
'xfa_capability': {'structure_analysis_ready': True},
}
assert xfa_dataset.owns_layout(stale_plain_pdf_layout) is False
supported_xfa_layout = {
'document_kind': 'xfa_hybrid',
'xfa_capability': {
'document_kind': 'xfa_hybrid',
'structure_analysis_ready': True,
},
}
assert xfa_dataset.owns_layout(supported_xfa_layout) is True
def test_wizard_xfa_mode_creates_visual_main_table_draft_before_dataset_mapping(app, monkeypatch):
"""关键断言:XFA 向导只冻结视觉主表;datasets 选择留给编辑映射,发布仍 fail-closed。"""
from hashlib import sha256
@@ -46,7 +46,11 @@ def _signature_run(profile: dict) -> ShippingOrderDocumentProfileValidationRun:
profile_id=profile['id'], revision_no=profile['draft_revision']['revision_no'],
definition_checksum=profile['draft_revision']['definition_checksum'], schema_version_id=profile['schema_version_id'],
run_type='layout_signature', status='passed',
summary_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'},
summary_json={
'signature_checksum': 'sig-checksum',
'matcher_policy_version': 'profile-layout-matcher',
'evidence_contract_version': validation_service.LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION,
},
result_snapshot_json={'signature_checksum': 'sig-checksum', 'matcher_policy_version': 'profile-layout-matcher'},
operation_id='signature-validation',
)
@@ -160,6 +164,37 @@ def test_report_blocks_when_signature_missing(app, monkeypatch):
assert 'signature_required' in keys or 'overlap_validation_required' in keys
def test_report_ignores_submitted_pre_hydration_signature(app, monkeypatch):
"""页面提交旧签名 ID 时,发布检查必须忽略它并通过统一入口重建当前签名。"""
with app.app_context():
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-legacy-signature-create')
lease = _lease(draft['id']); run = _passing_run(draft)
legacy = _signature_run(draft)
legacy.summary_json = {
key: value for key, value in legacy.summary_json.items()
if key != 'evidence_contract_version'
}
db.session.commit()
fresh = _signature_run(draft)
overlap = _overlap_run(draft)
calls: list[int] = []
def _resolve(profile, _revision, **_kwargs):
calls.append(profile.id)
return fresh
monkeypatch.setattr(validation_service, 'resolve_profile_identity_signature', _resolve)
monkeypatch.setattr(validation_service, 'run_cross_template_overlap', lambda *args, **kwargs: {'id': overlap.id, 'status': 'passed', 'stored_status': 'passed'})
report = checks.create_report(
draft['id'], data={'validation_run_id': run.id, 'matching_signature_run_id': legacy.id, 'overlap_validation_run_id': overlap.id},
actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-legacy-signature-report',
)
assert calls == [draft['id']]
assert report['matching_signature_run_id'] == fresh.id
def test_report_blocks_when_overlap_failed(app, monkeypatch):
"""关键断言:重叠验证 failed 时报告写入 overlap 阻断项与 conflict 引用。"""
with app.app_context():
@@ -202,8 +237,8 @@ def test_report_invalidates_when_signature_cleared(app, monkeypatch):
assert refreshed['status'] == 'invalidated'
def test_consume_report_blocks_editor_self_approval(app, monkeypatch):
"""职责分离:最近映射编辑者不得消费自己的发布检查报告。"""
def test_consume_report_allows_editor_self_approval(app, monkeypatch):
"""业务规则:管理员可确认发布自己编辑的订单模板草稿。"""
with app.app_context():
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
monkeypatch.setattr(
@@ -244,15 +279,9 @@ def test_consume_report_blocks_editor_self_approval(app, monkeypatch):
operation_id='pc-sod-report',
)
keys = [str(item['key']) for item in report['warning_items']]
with pytest.raises(ValidationError) as error:
checks.consume_report(
draft['id'],
report['report_no'],
data={'confirmed_warning_keys': keys},
actor_id=editor.id,
browser_session_id='publish-check-tab',
lease_token=lease['lease_token'],
operation_id='pc-sod-consume',
)
assert error.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID'
assert (error.value.details or {}).get('key') == 'editor_cannot_approve_own_version'
published = checks.consume_report(
draft['id'], report['report_no'], data={'confirmed_warning_keys': keys},
actor_id=editor.id, browser_session_id='publish-check-tab',
lease_token=lease['lease_token'], operation_id='pc-sod-consume',
)
assert published['status'] == 'published'
@@ -85,6 +85,71 @@ def test_frozen_sample_layout_survives_source_document_retention_cleanup(monkeyp
assert validation_service._load_sample_layout(sample) == frozen_layout
def test_frozen_sample_layout_hydrates_coordinate_evidence_reference(monkeypatch):
"""压缩 Layout 仍须通过其 FileAsset 引用恢复坐标证据,供签名和发布校验使用。"""
sample = SimpleNamespace(document_id=992, layout_version_id=772)
frozen_layout = {'status': 'ready', 'coordinate_evidence_ref': {'asset_no': 'evidence-asset'}}
document = SimpleNamespace(id=992)
hydrated_layout = {
**frozen_layout,
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 100}}},
}
def _get(model, identity):
if model.__name__ == 'ShippingDocumentLayoutVersion' and identity == 772:
return SimpleNamespace(payload_json=frozen_layout)
if model.__name__ == 'ShippingOrderDocument' and identity == 992:
return document
return None
monkeypatch.setattr(validation_service.db.session, 'get', _get)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.lifecycle._hydrate_coordinate_evidence',
lambda *, payload, document: hydrated_layout,
)
assert validation_service._load_sample_layout(sample) == hydrated_layout
def test_profile_identity_signature_rejects_pre_hydration_signature(monkeypatch):
"""旧证据契约生成的签名不能在修复后继续参与发布唯一性校验。"""
profile = SimpleNamespace(
id=93,
matching_signature_run_id=94,
matching_signature_checksum='old-signature',
matching_signature_version='order-profile-layout-signature',
)
revision = SimpleNamespace(definition_checksum='definition-checksum')
legacy_run = SimpleNamespace(
profile_id=93,
run_type='layout_signature',
status='passed',
definition_checksum='definition-checksum',
summary_json={},
result_snapshot_json={'signature_checksum': 'old-signature'},
)
monkeypatch.setattr(validation_service.db.session, 'get', lambda *_args: legacy_run)
with pytest.raises(Exception) as error:
validation_service.resolve_profile_identity_signature(profile, revision, auto_run=False)
assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE'
def test_match_thresholds_preserve_explicit_zero_score_and_margin():
"""模板允许唯一命中不设分数/间距下限时,发布校验不得把 0 覆盖为默认门槛。"""
thresholds = validation_service._match_thresholds({
'document_match': {
'minimum_score': 0.0,
'minimum_margin': 0.0,
'scoring_thresholds': {'evidence_coverage_minimum': 0.7},
},
})
assert thresholds['minimum_score'] == 0.0
assert thresholds['minimum_margin'] == 0.0
def test_failed_current_sample_run_remains_queryable(app):
"""关键断言:运行时样本证据不可用也必须保存 failed 摘要,方便后续审计而非吞掉失败。"""
with app.app_context():
@@ -8,7 +8,10 @@ from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.order_extraction_workflow import _build_approved_profile_order_result
from app.services.shipping_notice.order_extraction_workflow import (
_build_approved_profile_order_result,
_reservation_region_candidates,
)
SCHEMA = {'schema_version_id': 1, 'checksum': 'schema'}
@@ -18,6 +21,14 @@ DEFINITION = {'fields': [
{'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'required': True},
]}
RESERVATION_DEFINITION = {
'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1},
'fields': DEFINITION['fields'] + [
{'field_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header'},
{'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line'},
],
}
def _row(po: str, part: str) -> dict:
return {'status': 'parsed', 'issues': [], 'fields': [
@@ -27,6 +38,32 @@ def _row(po: str, part: str) -> dict:
]}
def _page_glyphs(*lines: str) -> list[dict]:
"""构造跨页 Reservation 路由回归所需的最小坐标文字。"""
glyphs = []
for row_index, line in enumerate(lines):
for column_index, char in enumerate(line):
glyphs.append({
'text': char,
'bbox': {'x0': column_index * 8, 'x1': column_index * 8 + 6, 'y0': row_index * 16, 'y1': row_index * 16 + 12},
'source_index': len(glyphs),
'boundary_before': 'space' if char == ' ' else 'none',
})
return glyphs
def _two_page_layout() -> dict:
return {
'coordinate_evidence': {
'pages': {'1': {'width': 800, 'height': 600}, '2': {'width': 800, 'height': 600}},
'page_glyphs': {
'1': _page_glyphs('Vendor Comments:', 'Reservation#33008'),
'2': _page_glyphs('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999'),
},
},
}
def test_approved_pdf_rejects_multiple_pos_in_one_pdf():
"""同一 PDF 的两条明细各有 PO 时,必须整体拒识而不是拆成多单。"""
orders, reason = _build_approved_profile_order_result(
@@ -47,3 +84,75 @@ def test_approved_pdf_keeps_one_order_when_only_one_po_is_proven():
)
assert reason is None
assert len(orders or []) == 1
def test_approved_pdf_writes_unnumbered_reservation_to_header_and_line_value_to_its_row():
"""同一证据区可同时提供整单默认 Reservation 与指定行覆盖值。"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=RESERVATION_DEFINITION,
table={'rows': [_row('PO-1', 'P-1'), _row('PO-1', 'P-2')]},
reservation_region_candidates=[
{'value': '33008', 'scope': 'header', 'line_no': None, 'raw_text': 'Reservation#33008'},
{'value': '3000098851', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098851 for line#1'},
],
)
assert reason is None
order = (orders or [])[0]
assert any(
item['field_id'] == 'header-reservation' and item['observations'][0]['value'] == '33008'
for item in order['header_fields']
)
assert any(
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == '3000098851'
for item in order['lines'][0]['fields']
)
assert not any(item['field_id'] == 'line-reservation' for item in order['lines'][1]['fields'])
def test_approved_pdf_marks_conflicting_reservation_region_for_review():
"""同一逻辑行的不同 Reservation 不得被任意选择。"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]},
reservation_region_candidates=[
{'value': '3000098851', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098851 for line#1'},
{'value': '3000098852', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation#3000098852 for line#1'},
],
)
assert reason is None
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
def test_enabled_reservation_region_reads_vendor_comments_across_pages():
"""已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。"""
result = _reservation_region_candidates(
raw_profile={'definition': RESERVATION_DEFINITION}, layout=_two_page_layout(),
)
assert result['reason'] is None
assert [item['value'] for item in result['candidates']] == ['33008', '3000098851']
def test_profile_without_reservation_region_does_not_scan_vendor_comments():
"""未标注专区的模板必须保持既有行为,不得扫描正文中的 Reservation。"""
result = _reservation_region_candidates(
raw_profile={'definition': DEFINITION}, layout=_two_page_layout(),
)
assert result == {'candidates': [], 'reason': None}
def test_enabled_reservation_region_requires_review_when_terms_heading_is_missing():
"""专区缺少结束锚点时,不得把未封闭文本区的值当成可自动建单证据。"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]},
reservation_region_reason='terms_and_conditions_anchor_missing',
)
assert reason is None
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
assert (orders or [])[0]['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing']
@@ -8,6 +8,8 @@ tests/test_post_ot_fulfillment_wave_p0.py
from __future__ import annotations
import ast
import inspect
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -16,6 +18,99 @@ import pytest
from app.core.errors import ConflictError
def test_create_post_ot_wave_uses_standard_fulfillment_audit_snapshot_keywords():
"""履约波次审计必须使用统一的 before/after 状态摘要参数。"""
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
function_node = ast.parse(inspect.getsource(svc.create_post_ot_fulfillment_wave)).body[0]
audit_calls = [
node
for node in ast.walk(function_node)
if isinstance(node, ast.Call)
and isinstance(node.func, ast.Name)
and node.func.id == 'record_fulfillment_audit'
]
assert len(audit_calls) == 1
keyword_names = {keyword.arg for keyword in audit_calls[0].keywords}
assert {'before', 'after'} <= keyword_names
assert not {'before_json', 'after_json'} & keyword_names
def test_released_shortage_line_is_eligible_for_post_ot_wave():
"""短缺放行仅完成审批,后续必须允许该行进入独立发货通知波次。"""
from app.services.shipping_notice.post_ot_fulfillment_wave_service import _assert_fact_allows_fulfill
required, available = _assert_fact_allows_fulfill({
'line_key': 'L-RELEASED',
'inventory_status': 'ready',
'match_result': 'matched',
'is_shortage': True,
'required_qty': '3',
'available_qty': '0',
'decision': {'decision_code': 'release_inventory_shortage'},
})
assert str(required) == '3'
assert str(available) == '0'
def test_list_eligible_post_ot_lines_keeps_released_shortage_only():
"""库存不足明细必须先有放行审计决定,才能成为 wave 候选。"""
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
case = SimpleNamespace(id=1)
with patch.object(svc, 'project_review_case_line_decisions', return_value={'lines': [
{
'line_key': 'released', 'line_status': 'released_shortage',
'inventory_status': 'ready', 'match_result': 'matched', 'is_shortage': True,
'required_qty': '3', 'available_qty': '0',
'decision': {'decision_code': 'release_inventory_shortage'},
},
{
'line_key': 'unreleased', 'line_status': 'pending_decision',
'inventory_status': 'ready', 'match_result': 'matched', 'is_shortage': True,
'required_qty': '3', 'available_qty': '0',
'decision': None,
},
]}):
assert svc.list_eligible_post_ot_line_keys(case) == ['released']
def test_post_ot_wave_creates_a_distinct_notice_with_only_selected_lines(app):
"""波次必须产生独立 Notice,且其 NoticeLine 只能包含本次勾选项次。"""
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
selected = [SimpleNamespace(
id=101, position=0, line_no='10', part_number='PN-10',
reservation_id='RES-10', qty='2', field_values_json={},
)]
snapshot = SimpleNamespace(lines=[
*selected,
SimpleNamespace(
id=102, position=1, line_no='20', part_number='PN-20',
reservation_id='RES-20', qty='3', field_values_json={},
),
])
added: list = []
with app.app_context():
with (
patch('app.services.shipping_notice.notice_line_service.db.session.query') as query,
patch('app.services.shipping_notice.notice_line_service.db.session.add_all', side_effect=added.extend),
patch('app.services.shipping_notice.notice_line_service.db.session.flush'),
):
query.return_value.filter_by.return_value.delete.return_value = 0
count = replace_notice_lines_from_snapshot(
notice_id=9,
snapshot=snapshot,
snapshot_line_ids={101},
)
assert count == 1
assert [(row.notice_id, row.snapshot_line_id, row.line_key) for row in added] == [(9, 101, '10')]
def test_create_post_ot_wave_idempotent_replay_returns_original(app):
"""同 key 且参数一致必须返回原 wave,不二次建波。"""
from app.services.shipping_notice import post_ot_fulfillment_wave_service as svc
@@ -143,7 +238,12 @@ def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app):
with app.app_context():
with (
patch.object(coord, 'line_auto_fulfill_enabled', return_value=True),
patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']),
patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1']),
patch.object(
coord,
'project_review_case_line_decisions',
return_value={'lines': [{'line_key': 'L1', 'line_status': 'ready_to_fulfill'}]},
),
patch.object(coord, 'create_post_ot_fulfillment_wave', side_effect=_boom),
patch.object(coord.db.session, 'rollback', side_effect=lambda: calls.append('rollback')),
patch.object(coord.db.session, 'flush', side_effect=lambda: calls.append('flush')),
@@ -159,6 +259,32 @@ def test_coordinate_auto_fulfill_rolls_back_then_marks_failed(app):
schedule_mock.assert_not_called()
def test_coordinate_auto_fulfill_requires_manual_selection_for_multiple_lines(app):
"""多条开放明细不得由系统自动合并为同一张发货通知单。"""
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
case = SimpleNamespace(id=3, case_no='RC-MULTI', confirmed_task_id=8)
with app.app_context():
with (
patch.object(coord, 'line_auto_fulfill_enabled', return_value=True),
patch.object(coord, 'list_eligible_post_ot_line_keys', return_value=['L1', 'L2']),
patch.object(
coord,
'project_review_case_line_decisions',
return_value={'lines': [
{'line_key': 'L1', 'line_status': 'released_shortage'},
{'line_key': 'L2', 'line_status': 'ready_to_fulfill'},
]},
),
patch.object(coord, 'create_post_ot_fulfillment_wave') as create_mock,
):
out = coord.coordinate_post_ot_auto_fulfill(case=case, trigger='inventory_shortage_released')
assert out['status'] == 'idle'
assert out['reason'] == 'manual_wave_selection_required'
create_mock.assert_not_called()
def test_mark_auto_fulfill_failed_does_not_create_wait_inventory(app):
"""无活动决定时只写匹配事实 detail,不新建 wait_inventory 决定。"""
from app.services.shipping_notice import line_auto_fulfill_coordinator as coord
@@ -250,3 +376,30 @@ def test_post_ot_api_does_not_call_confirm_auto_progress(app, monkeypatch):
assert calls['confirm'] == 0
assert out['post_ot_wave'] is True
assert out['wave_progress']['wave_no'] == 3
def test_post_ot_api_rejects_pre_ot_wave_without_legacy_fallback(app, monkeypatch):
"""无正式 OT 时必须拒绝,不能回落到历史建波/自动推进链路。"""
from app.api.workspace import shipping_notice as api
from app.core.errors import ValidationError
with app.app_context():
with app.test_request_context(
'/api/workspace/shipping-notice/order-review-cases/RC-9/line-fulfillment/wave',
method='POST',
json={'line_keys': ['L1'], 'idempotency_key': 'k1'},
):
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=1))
monkeypatch.setattr(
'app.services.shipping_notice.order_review_draft_service.soft_load_review_case_for_audit',
lambda **_k: SimpleNamespace(id=1, case_no='RC-9'),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
lambda _c: {'has_formal_ot': False},
)
with pytest.raises(ValidationError, match='formal order task') as exc:
api.workspace_create_shipping_order_review_fulfillment_wave('RC-9')
assert exc.value.code == 'SHIPPING.FORMAL_OT_REQUIRED'
@@ -206,6 +206,62 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
ensure_mock.assert_called_once()
def test_unique_customer_candidate_can_be_confirmed_before_draft_validation(app):
"""保存校验前,唯一 Shadow 候选必须先落为 Bill-to 已确认事实。"""
from app.services.shipping_notice import order_review_auto_progress_coordinator as coord
case = SimpleNamespace(case_no='SORC-UNIQUE-CUSTOMER', candidate_id=31)
with patch.object(
coord,
'_customer_step_for_case',
return_value=('auto_confirmed', {'customer_id': 5555}),
) as step_mock:
result = coord.auto_confirm_unique_customer_for_review_case(
case=case,
trigger='draft_validated',
)
step_mock.assert_called_once_with(case=case, trigger='draft_validated')
assert result == {'status': 'auto_confirmed', 'customer_id': 5555}
def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(app):
"""唯一客户自动确认只 flush,不能在 Draft 校验前单独提交事务。"""
from app.services.shipping_notice import order_review_auto_progress_coordinator as coord
case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31)
candidate = SimpleNamespace(id=31)
shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555)
extraction = SimpleNamespace(id=101)
shadow_model = SimpleNamespace(
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)),
)
match_model = SimpleNamespace(
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))),
)
with patch.object(coord.db.session, 'get', return_value=candidate), patch.object(
coord,
'ShippingCustomerShadowResolution',
shadow_model,
), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object(
coord,
'_resolve_extraction_for_case',
return_value=extraction,
), patch.object(
coord,
'ShippingOrderCustomerMatch',
match_model,
), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object(
coord,
'record_fulfillment_audit',
):
status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated')
assert status == 'auto_confirmed'
assert metadata == {'customer_id': 5555, 'extraction_id': 101}
assert confirm_mock.call_args.kwargs['commit'] is False
def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app):
"""合同 4:恢复扫描只收敛超时事实,不能在失败后自动补建 STP Job。"""
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
@@ -21,9 +21,7 @@ from app.models import (
ShippingProcessGateAttempt,
)
from app.services.shipping_notice.auto_progress_controller import (
AUTO_PROGRESS_GATE_CODES,
determine_formal_start_gate,
run_auto_progress_job,
submit_auto_progress,
)
from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through
@@ -80,38 +78,21 @@ def test_submit_creates_formal_execution_for_task_without_case(app):
assert len(gate_codes) == 20
assert gate_codes[0] == 'document_materialization'
assert gate_codes[-1] == 'manual_upload_handoff'
assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0
assert Job.query.filter_by(id=first['job_id']).one().job_type == 'shipping_process_gate'
def test_submit_reuses_formal_case_execution_and_supersedes_duplicate_apx(app):
"""同一 Task 已有正式 Case Execution 时不得保留第二条 APX 活动链。"""
def test_submit_reuses_formal_case_execution(app):
"""同一 Task 已有正式 Case Execution 时必须复用该 20-Gate 链。"""
task = _task_with_candidate()
formal = ensure_execution_for_workflow_version(review_case_id=901, task_id=int(task.id))
duplicate = ShippingProcessExecution(
execution_no='APX-DUPLICATE', task_id=int(task.id),
candidate_set_id=task.active_inventory_candidate_set_id,
execution_revision=1, status='blocked', current_gate_code=AUTO_PROGRESS_GATE_CODES[0],
lock_version=1,
)
db.session.add(duplicate)
db.session.flush()
for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1):
db.session.add(ShippingProcessGate(
execution_id=int(duplicate.id), gate_code=gate_code, sequence_no=sequence_no,
status='pending', evaluation_version=1, lock_version=1,
))
task.active_process_execution_id = int(duplicate.id)
task.active_process_execution_id = int(formal.id)
db.session.commit()
result = submit_auto_progress(task=task, trigger='user_retry')
db.session.refresh(task)
db.session.refresh(duplicate)
assert result['execution_id'] == formal.id
assert task.active_process_execution_id == formal.id
assert duplicate.status == 'superseded'
assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0
def test_formal_execution_queues_one_gate_attempt_job(app):
@@ -202,66 +183,3 @@ def test_active_stp_job_without_retry_metadata_is_reused(app):
assert result['retry_of_job_id'] is None
def test_legacy_shipping_auto_progress_job_is_terminal_readonly(app):
"""历史 APX Job 被 Worker 领取时只能终止,不能再执行六 Gate 状态机。"""
task = _task_with_candidate()
legacy = ShippingProcessExecution(
execution_no='APX-READONLY', task_id=int(task.id), status='active',
candidate_set_id=int(task.active_inventory_candidate_set_id),
current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1,
)
db.session.add(legacy)
db.session.flush()
gate = ShippingProcessGate(
execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0],
sequence_no=1, status='running', evaluation_version=1, lock_version=1,
)
db.session.add(gate)
db.session.flush()
task.active_process_execution_id = int(legacy.id)
job = Job(
domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id),
execution_id=int(legacy.id), gate_id=int(gate.id), status='running',
candidate_set_id=int(task.active_inventory_candidate_set_id),
payload_json={'fencing_token': 'legacy-token'}, fencing_token='legacy-token', max_attempts=1,
)
db.session.add(job)
db.session.commit()
result = run_auto_progress_job(job_id=int(job.id), worker_id='test-worker')
db.session.refresh(job)
db.session.refresh(gate)
assert result['status'] == 'legacy_readonly'
assert job.status == 'cancelled'
assert gate.status == 'cancelled'
def test_active_legacy_apx_job_does_not_block_formal_submission(app):
"""历史 APX 活动 Job 不得被正式 20-Gate 提交入口复用或阻塞。"""
task = _task_with_candidate()
legacy = ShippingProcessExecution(
execution_no='APX-NONBLOCKING', task_id=int(task.id), status='active',
candidate_set_id=int(task.active_inventory_candidate_set_id),
current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1,
)
db.session.add(legacy)
db.session.flush()
gate = ShippingProcessGate(
execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0],
sequence_no=1, status='queued', evaluation_version=1, lock_version=1,
)
db.session.add(gate)
db.session.flush()
task.active_process_execution_id = int(legacy.id)
db.session.add(Job(
domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id),
execution_id=int(legacy.id), gate_id=int(gate.id), candidate_set_id=int(task.active_inventory_candidate_set_id),
status='queued', payload_json={}, fencing_token='legacy-token', max_attempts=1,
))
db.session.commit()
result = submit_auto_progress(task=task, trigger='review_confirmed')
assert result['status'] == 'queued'
assert db.session.get(Job, result['job_id']).job_type == 'shipping_process_gate'
@@ -1,9 +1,9 @@
"""
backend/tests/test_shipping_business_numbering.py
用途:验证货代业务编号格式、上海日期、两位流水上限及业务单版本继承。
依赖:ShippingCase/Customer/Sequence、business_numbering_service、customer_identity_gate。
逻辑:直接调用领域服务,覆盖幂等、01-99、修订共享与强制新建独立编号。
用途:验证货代业务编号格式、上海日期、两位流水上限及 Notice 独立编号。
依赖:ShippingNotice/Customer/Sequence、business_numbering_service、customer_identity_gate。
逻辑:直接调用领域服务,覆盖幂等、01-99 与替代 Notice 独立编号。
"""
from datetime import datetime, timezone
@@ -12,9 +12,9 @@ import pytest
from app import db
from app.core.errors import ConflictError
from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice.business_numbering_service import (
assign_business_number,
assign_notice_business_number,
format_business_no,
shanghai_business_date,
)
@@ -22,25 +22,23 @@ from app.services.shipping_notice.customer_identity_gate import confirm_task_cus
from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref
def _seed_case(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
"""创建待客户确认的业务单、任务和启用客户。"""
def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
"""创建待客户确认的 Notice 和启用客户。"""
customer = ShippingCustomer(
standard_name=f"编号测试客户 {short_code}",
short_code=short_code,
status="active",
)
case = ShippingCase(case_no=f"CASE-{task_no}", numbering_status="pending")
db.session.add_all([customer, case])
db.session.add(customer)
db.session.flush()
task = ShippingNotice(
task_no=task_no,
shipping_case_id=case.id,
customer_resolution_status="pending",
source_type="manual",
)
db.session.add(task)
db.session.commit()
return task, case, customer
return task, customer
def test_number_format_and_shanghai_date_boundary(app):
@@ -55,53 +53,89 @@ def test_number_format_and_shanghai_date_boundary(app):
def test_confirmation_assigns_idempotent_business_number(app):
"""重复确认同一客户不得重复占用流水,正式编号保持不变。"""
with app.app_context():
task, case, customer = _seed_case()
task, customer = _seed_notice()
first = confirm_task_customer(task, customer_id=customer.id, actor_id=None)
first_no = first.shipping_case.business_no
first_no = first.business_no
second = confirm_task_customer(first, customer_id=customer.id, actor_id=None)
assert first_no
assert second.shipping_case.business_no == first_no
assert second.business_no == first_no
assert ShippingBusinessSequence.query.one().current_value == 1
assert second.shipping_case.customer_short_code_snapshot == "WYC"
assert second.customer_short_code_snapshot == "WYC"
assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1
def test_revision_inherits_and_force_case_uses_next_sequence(app):
"""同一业务单修订继承编号,独立业务单确认同客户时占用下一流水。"""
def test_each_notice_gets_a_distinct_business_number_for_same_customer(app):
"""同一客户 PO 的不同发货通知必须各自占用独立业务流水。"""
with app.app_context():
task, case, customer = _seed_case()
customer = ShippingCustomer(
standard_name='通知单波次客户', short_code='WVC', status='active',
)
db.session.add(customer)
db.session.flush()
first = ShippingNotice(task_no='SN-NOTICE-NO-1', customer_resolution_status='confirmed')
second = ShippingNotice(task_no='SN-NOTICE-NO-2', customer_resolution_status='confirmed')
db.session.add_all([first, second])
db.session.flush()
first.customer_id = customer.id
second.customer_id = customer.id
db.session.flush()
first_no = assign_notice_business_number(first)
second_no = assign_notice_business_number(second)
assert first_no != second_no
assert first.business_no == first_no
assert second.business_no == second_no
def test_notice_confirms_customer_and_assigns_number_without_shipping_case(app):
"""新 Notice 必须自持客户快照与编号,不能要求 ShippingCase 作为前置容器。"""
with app.app_context():
customer = ShippingCustomer(
standard_name='Notice 自持客户', short_code='NHC', status='active',
)
task = ShippingNotice(
task_no='SN-NOTICE-SELF-CUSTOMER',
customer_resolution_status='pending',
source_type='manual',
)
db.session.add_all([customer, task])
db.session.commit()
confirmed = confirm_task_customer(task, customer_id=customer.id, actor_id=7)
assert confirmed.customer_id == customer.id
assert confirmed.customer_name_snapshot == 'Notice 自持客户'
assert confirmed.customer_short_code_snapshot == 'NHC'
assert confirmed.business_no
assert confirmed.customer_resolution_status == 'confirmed'
def test_replacement_notice_uses_next_sequence(app):
"""替代 Notice 保留原号审计并为新 Notice 分配下一业务号。"""
with app.app_context():
task, customer = _seed_notice()
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
revision = ShippingNotice(
task_no="SN-NUMBER-REV",
shipping_case_id=case.id,
supersedes_task_id=task.id,
customer_resolution_status="confirmed",
source_type="manual",
)
forced_case = ShippingCase(case_no="CASE-FORCE-NUMBER", numbering_status="pending")
db.session.add_all([revision, forced_case])
db.session.flush()
forced_task = ShippingNotice(
task_no="SN-NUMBER-FORCED",
shipping_case_id=forced_case.id,
customer_resolution_status="pending",
source_type="manual",
)
db.session.add(forced_task)
db.session.add(revision)
db.session.commit()
confirm_task_customer(forced_task, customer_id=customer.id, actor_id=None)
assert revision.shipping_case.business_no == case.business_no
assert forced_task.shipping_case.business_no[:-2] == case.business_no[:-2]
assert case.business_no.endswith("01")
assert forced_task.shipping_case.business_no.endswith("02")
confirm_task_customer(revision, customer_id=customer.id, actor_id=None)
assert revision.business_no[:-2] == task.business_no[:-2]
assert task.business_no.endswith("01")
assert revision.business_no.endswith("02")
def test_daily_sequence_blocks_one_hundredth_case(app):
"""客户当日已有 99 笔时,第 100 笔必须阻断且不写业务号。"""
with app.app_context():
task, case, customer = _seed_case()
task, customer = _seed_notice()
business_date = shanghai_business_date()
db.session.add(ShippingBusinessSequence(
business_type="shipping_notice",
@@ -110,19 +144,19 @@ def test_daily_sequence_blocks_one_hundredth_case(app):
current_value=99,
))
db.session.commit()
case.customer_id = customer.id
task.customer_id = customer.id
with pytest.raises(ConflictError) as exc_info:
assign_business_number(case)
assign_notice_business_number(task)
assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED"
assert case.business_no is None
assert task.business_no is None
assert ShippingBusinessSequence.query.one().current_value == 99
def test_numbering_failure_rolls_back_customer_confirmation(app):
"""流水耗尽导致确认失败时,业务单客户和任务确认状态不得半落库。"""
with app.app_context():
task, case, customer = _seed_case()
task, customer = _seed_notice()
db.session.add(ShippingBusinessSequence(
business_type="shipping_notice",
customer_id=customer.id,
@@ -135,43 +169,41 @@ def test_numbering_failure_rolls_back_customer_confirmation(app):
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
db.session.rollback()
db.session.expire_all()
persisted_case = db.session.get(ShippingCase, case.id)
persisted_task = db.session.get(ShippingNotice, task.id)
assert persisted_case.customer_id is None
assert persisted_case.business_no is None
assert persisted_task.customer_id is None
assert persisted_task.business_no is None
assert persisted_task.customer_resolution_status == "pending"
def test_business_number_query_returns_latest_revision(app):
"""使用正式业务号查询时应返回同业务单最新修订任务。"""
def test_business_number_query_returns_exact_notice(app):
"""使用正式业务号查询时必须返回该 Notice,不能跳到替代版本。"""
with app.app_context():
task, case, customer = _seed_case()
task, customer = _seed_notice()
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
revision = ShippingNotice(
task_no="SN-NUMBER-QUERY-REV",
shipping_case_id=case.id,
supersedes_task_id=task.id,
document_version=2,
customer_resolution_status="confirmed",
customer_resolution_status="pending",
source_type="manual",
)
db.session.add(revision)
db.session.commit()
resolved = get_task_by_ref(case.business_no)
assert resolved.id == revision.id
assert extract_task_no_from_text(f"请继续处理 {case.business_no}") == case.business_no
resolved = get_task_by_ref(task.business_no)
assert resolved.id == task.id
assert extract_task_no_from_text(f"请继续处理 {task.business_no}") == task.business_no
def test_numbering_rejects_invalid_short_code_even_if_data_bypasses_service(app):
"""客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。"""
with app.app_context():
task, case, customer = _seed_case()
case.customer_id = customer.id
task, customer = _seed_notice()
task.customer_id = customer.id
customer.short_code = "W1"
# 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。
with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info:
assign_business_number(case)
assign_notice_business_number(task)
assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID"
assert case.business_no is None
assert task.business_no is None
db.session.rollback()
@@ -10,6 +10,8 @@ from __future__ import annotations
from types import SimpleNamespace
import pytest
from app.services.shipping_notice.candidate_qualification_service import (
evaluate_candidate_qualification,
resolve_review_case_customer_resolved,
@@ -111,6 +113,104 @@ def test_layout_table_review_diagnostic_does_not_block_auto_create(monkeypatch):
assert 'blocking_conflict' not in reason_codes
@pytest.mark.pure_unit
def test_derived_field_evidence_gap_does_not_block_candidate_qualification(monkeypatch):
"""派生已解决的字段不能继续被历史 evidence_missing 阻断。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
candidate = _eligible_candidate(
conflicts_json=[{
'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing',
'owning_gate_code': 'field_completeness',
}],
structured_result_json={
'customer': {'resolution_status': 'user_confirmed'},
'extraction': {'field_adjudication': {
'blocked_fields': [],
'decisions': [{'field_code': 'line_no', 'status': 'derived', 'reason_code': 'derived'}],
}},
},
)
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['gates']['field_conflicts_resolved'] is True
assert result['can_auto_create'] is True
@pytest.mark.pure_unit
def test_resolved_blocking_finding_does_not_block_candidate_qualification(monkeypatch):
"""标准 Finding 已记录人工裁决时,资格 Gate 只能阻断 unresolved 项。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
candidate = _eligible_candidate(conflicts_json=[{
'conflict_key': '0:unit_price',
'field': 'unit_price',
'severity': 'blocking',
'reason': 'supplement_field_conflict',
'resolution_status': 'resolved',
'values': ['1731.60', '1732.00'],
}])
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['gates']['field_conflicts_resolved'] is True
assert result['can_auto_create'] is True
@pytest.mark.pure_unit
def test_non_blocking_standard_finding_does_not_block_candidate_qualification(monkeypatch):
"""统一 Finding 的 severity 不是 blocking 时不得被资格 Gate 误拦截。"""
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.extraction_emergency_stop_enabled',
lambda: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.candidate_qualification_service.order_schema_service.get_auto_creation_policy',
lambda: {'enabled': True},
)
candidate = _eligible_candidate(conflicts_json=[{
'conflict_key': '0:unit_price',
'field': 'unit_price',
'severity': 'review_required',
'reason': 'supplement_field_conflict',
'resolution_status': 'unresolved',
'values': ['1731.60', '1732.00'],
}])
result = evaluate_candidate_qualification(
candidate=candidate,
fields_complete=True,
customer_resolved=True,
schema_auto_create_enabled=True,
)
assert result['gates']['field_conflicts_resolved'] is True
assert result['can_auto_create'] is True
def test_llm_candidate_can_pass_unified_gates(monkeypatch):
"""LLM Candidate 具备分类/字段置信度与证据时可通过统一门禁 → eligible。"""
monkeypatch.setattr(
@@ -244,7 +344,9 @@ def test_generic_candidate_failure_has_concrete_reason_codes(monkeypatch):
assert result['can_auto_create'] is False
assert 'evidence_missing' in result['blocking_reason_codes']
assert 'field_conflict' in result['blocking_reason_codes']
assert 'required_field_missing' in result['blocking_reason_codes']
# Candidate Qualification 在字段合并后运行,必须使用最终字段完整性原因码;
# `required_field_missing` 仅保留给解析/复核草稿阶段。
assert 'final_required_field_missing' in result['blocking_reason_codes']
assert 'duplicate_unresolved' in result['blocking_reason_codes'] or 'duplicate_resolved' in result['failed_gates']
assert any(code.startswith('customer_') for code in result['blocking_reason_codes'])
@@ -15,6 +15,9 @@ def test_legacy_fulfillment_chat_actions_are_not_registered():
action_types = set(list_action_types())
assert {
"shipping.create_batch_from_notices",
"shipping.create_batch_from_intakes",
"shipping.switch_batch_focus",
"shipping.freeze_order",
"shipping.generate_excel",
"shipping.retry_upload",
@@ -36,4 +39,6 @@ def test_legacy_workspace_fulfillment_routes_are_not_registered(app):
'/api/workspace/shipping-tasks/<task_no>/match-inventory',
'/api/workspace/shipping-tasks/<task_no>/generate-excel',
'/api/workspace/shipping-tasks/<task_no>/retry-upload',
'/api/workspace/shipping-tasks/<task_no>/retry',
'/api/workspace/shipping-tasks/<task_no>/lines/<line_key>/retry',
}.isdisjoint(routes)
@@ -11,6 +11,7 @@ from __future__ import annotations
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun
from sqlalchemy import event
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
from app.services.shipping_notice.order_task_service import (
allocate_user_task_no_for_run,
@@ -99,6 +100,10 @@ def test_workspace_shipping_processing_and_focus_viewed_api(app, client):
)
assert focus.status_code == 200, focus.get_json()
assert focus.get_json()['data']['focused_task_no'] == user_task_no
assert 'work_items' not in focus.get_json()['data']
assert set(focus.get_json()['data']['processing']['status_groups']) == {
'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived',
}
viewed = client.post(
f'/api/workspace/shipping-notice/conversation-tasks/{user_task_no}/viewed',
@@ -106,3 +111,122 @@ def test_workspace_shipping_processing_and_focus_viewed_api(app, client):
headers=headers,
)
assert viewed.status_code == 200, viewed.get_json()
assert 'work_items' not in viewed.get_json()['data']
def test_workspace_shipping_processing_summary_omits_detail_and_legacy_mirrors(app, client):
"""首屏会话摘要只返回状态→EML→PDF权威分组,详情必须按需读取。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='API-SUMMARY')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
db.session.commit()
token = issue_local_access_token(user)
session_id = session.session_id
assert run.id is not None
response = client.get(
f'/api/workspace/shipping-processing/conversations/{session_id}?view=summary',
headers={'Authorization': f'Bearer {token}'},
)
assert response.status_code == 200, response.get_json()
data = response.get_json()['data']
assert data['conversation_id'] == session_id
assert data['projection_mode'] == 'summary'
assert 'work_items' not in data
projection = data['conversation_processing']
assert set(projection['status_groups']) == {
'failed', 'waiting_human', 'processing', 'completed', 'cancelled', 'archived',
}
assert 'needs_action' not in projection
assert 'history' not in projection
for tasks in projection['status_groups'].values():
for task in tasks:
assert 'process_gate' not in task
assert 'objects' not in task
# PDF 叶子是首屏“状态→EML→PDF”树的一部分;但叶子同样不携带详情 Gate。
for child in task.get('aggregate_children') or []:
assert 'process_gate' not in child
def test_workspace_shipping_processing_summary_does_not_read_run_snapshots(app, client):
"""首屏摘要不得查询 processing run,避免 JSON 快照解码重新进入轮询路径。"""
with app.app_context():
user, _agent, session, _intake, _document = _seed_run_input(suffix='API-SUMMARY-FAST')
token = issue_local_access_token(user)
session_id = session.session_id
run_selects: list[str] = []
def capture_run_selects(_conn, _cursor, statement, _parameters, _context, _executemany):
if 'shipping_order_processing_runs' in statement.lower():
run_selects.append(statement)
event.listen(db.engine, 'before_cursor_execute', capture_run_selects)
try:
response = client.get(
f'/api/workspace/shipping-processing/conversations/{session_id}?view=summary',
headers={'Authorization': f'Bearer {token}'},
)
finally:
event.remove(db.engine, 'before_cursor_execute', capture_run_selects)
assert response.status_code == 200, response.get_json()
assert run_selects == []
def test_workspace_shipping_processing_summary_keeps_lightweight_action_entries(app, client):
"""摘要不加载重型详情,但必须保留后端裁决的最小操作入口。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='API-SUMMARY-ACTIONS')
run, _ = create_order_extraction_run(
user=user,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
keep_input_open=True,
)
run_no = run.run_no
db.session.commit()
token = issue_local_access_token(user)
session_id = session.session_id
document.parse_status = 'parsed'
document.order_extraction_status = 'review_required'
candidate = ShippingOrderCandidate(
candidate_no=f'SNC-API-SUMMARY-ACTIONS-{run.id}',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key=f'key-api-summary-actions-{run.id}',
order_extraction_run_id=run.id,
is_current_version=True,
candidate_status='provisional',
structured_result_json={},
)
db.session.add(candidate)
db.session.flush()
db.session.commit()
response = client.get(
f'/api/workspace/shipping-processing/conversations/{session_id}?view=summary',
headers={'Authorization': f'Bearer {token}'},
)
assert response.status_code == 200, response.get_json()
projection = response.get_json()['data']['conversation_processing']
assert [node['code'] for node in projection['lifecycle_nodes']] == [
'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete',
]
tasks = projection['status_groups']['waiting_human']
assert len(tasks) == 1
leaf = tasks[0]['aggregate_children'][0]
assert leaf['run_no'] == run_no
assert leaf['source_summary']['po_number'] is None
assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
assert leaf['ui_state']['primary_action']['code'] == 'open_order_review'
assert leaf['ui_state']['primary_action']['target_surface'] == 'order_lifecycle_workbench'
assert leaf['ui_state']['primary_action']['target_lifecycle_stage'] == 'intake_parse'
@@ -12,13 +12,18 @@ from pydantic import ValidationError
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
coordinate_profile_character_candidates,
_text_in_region,
_text_in_horizontal_region,
reconstruction_exclusion_regions,
reconstruct_coordinate_profile_rows,
reconstruct_coordinate_profile_rows_with_strategy,
reconstruct_table_from_positioned_text,
resolve_line_start_field_code,
suggest_header_layouts,
suggest_header_regions,
suggest_multi_subrow_layouts,
derive_incomplete_table_bbox,
)
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
from app.services.shipping_notice.document_layout.order_profile import TableRegionProfile
@@ -64,6 +69,87 @@ def _adaptive_layouts() -> list[dict]:
]
def test_coordinate_profile_character_candidates_share_page_first_union_contract():
"""三条解析链路应得到同一套整页优先、纵向并集字符候选。"""
page_characters = [
{'text': 'H', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}},
{'text': 'D', 'bbox': {'x0': 10, 'y0': 160, 'x1': 20, 'y1': 170}},
{'text': 'X', 'bbox': {'x0': 300, 'y0': 160, 'x1': 310, 'y1': 170}},
]
table_characters = [{'text': 'legacy', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]
characters, page_bbox = coordinate_profile_character_candidates(
table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5},
page_size={'width': 400, 'height': 400}, page_characters=page_characters,
table_characters=table_characters,
raw_table_bbox={'x0': 0, 'y0': 120, 'x1': 200, 'y1': 180},
table_id='table-1', page_no=1,
)
assert page_bbox == {'x0': 0.0, 'y0': 0.0, 'x1': 400.0, 'y1': 400.0}
assert [item['text'] for item in characters or []] == ['H', 'D']
def test_coordinate_profile_character_candidates_use_annotation_page_frame_on_taller_runtime_page():
"""分页训练表区在未分页长页中必须保持原始 PDF 点坐标,不能按新页高拉伸。"""
characters, page_bbox = coordinate_profile_character_candidates(
table_region={'x0': .0, 'y0': .2, 'x1': 1.0, 'y1': .3},
reference_page_frame={'width': 200, 'height': 100},
page_size={'width': 200, 'height': 200},
page_characters=[
{'text': 'line', 'bbox': {'x0': 10, 'y0': 21, 'x1': 30, 'y1': 29}},
{'text': 'wrong', 'bbox': {'x0': 10, 'y0': 41, 'x1': 35, 'y1': 49}},
],
table_characters=None, table_id='page-1', page_no=1,
)
# 关键断言:训练页 .2-.3 对应 y=20..30,而不是长页 y=40..60。
assert page_bbox == {'x0': 0.0, 'y0': 0.0, 'x1': 200.0, 'y1': 200.0}
assert [item['text'] for item in characters or []] == ['line']
def test_coordinate_profile_character_candidates_fallback_when_page_crop_is_empty():
"""空的页级裁剪不能覆盖仍可用的当前表字符证据。"""
characters, _ = coordinate_profile_character_candidates(
table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5},
page_size={'width': 100, 'height': 100},
page_characters=[{'text': 'header', 'bbox': {'x0': 80, 'y0': 80, 'x1': 90, 'y1': 90}}],
table_characters=[{'text': '10', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}],
table_id='table-1', page_no=1,
)
assert [item['text'] for item in characters or []] == ['10']
def test_coordinate_profile_character_candidates_do_not_reuse_table_on_other_page():
"""续页没有自己的页级候选时,不能重复消费首页表字符。"""
characters, _ = coordinate_profile_character_candidates(
table_region={'x0': .0, 'y0': .0, 'x1': .5, 'y1': .5},
page_size={'width': 100, 'height': 100},
page_characters=[],
table_characters=[{'text': '10', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}],
table_id='table-1', page_no=2, allow_table_fallback=False,
)
assert characters is None
def test_reconstruction_exclusions_do_not_treat_header_layouts_as_deleted_text():
"""表头框是语义/预览证据,默认不得在明细起行前删除相交字符。"""
exclusions = reconstruction_exclusion_regions({
'exclusion_regions': [{'x0': .1, 'y0': .1, 'x1': .2, 'y1': .2}],
'header_layouts': [{'region': {'x0': .0, 'y0': .2, 'x1': 1, 'y1': .4}}],
})
assert exclusions == [{'x0': .1, 'y0': .1, 'x1': .2, 'y1': .2}]
def test_horizontal_region_keeps_a_character_that_intersects_its_right_edge():
"""字段边界切过字形时必须保留该字,避免料号末尾标点被静默截断。"""
glyphs = [
(0, PositionedCharacter(text='A', bbox=LayoutBBox(x0=80, y0=20, x1=84, y1=30))),
(1, PositionedCharacter(text='-', bbox=LayoutBBox(x0=99.9, y0=20, x1=103, y1=30))),
]
assert _text_in_horizontal_region(glyphs, LayoutBBox(x0=80, y0=10, x1=100, y1=40)) == 'A -'
def test_table_region_text_prefers_explicit_pdf_space_boundary():
"""明细自由文本列应恢复 PDF 原始词边界,同时不依赖降低全局几何阈值。"""
glyphs = [
@@ -217,6 +303,72 @@ def test_subrow_suggestion_uses_one_record_for_vertical_samples():
assert suggestions[0].y1 < suggestions[1].y0
def test_incomplete_table_bbox_expands_from_page_rows_until_summary():
"""表格框只覆盖表头时,页级坐标可恢复唯一明细区,但不包含合计行。"""
characters = _glyphs(
[('Item', 10), ('Material', 65), ('Quantity', 150)],
[('Description', 10), ('Delivery Date', 120)],
[('10', 10), ('PART-A', 65), ('3.000', 150)],
[('FRAME', 65), ('PCS', 150)],
[('898.72', 120), ('2,696.16', 165)],
[('TOTAL AMOUNT', 65)],
)
expanded = derive_incomplete_table_bbox(
characters=characters,
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 48},
)
assert expanded == {'x0': 0.0, 'y0': 0.0, 'x1': 200.0, 'y1': 90.0}
def test_incomplete_table_bbox_does_not_expand_without_line_anchor():
"""没有可靠明细起行锚点时,不能把页面下方普通文本扩大成表格。"""
characters = _glyphs(
[('Item', 10), ('Material', 65), ('Quantity', 150)],
[('Description', 10), ('Delivery Date', 120)],
[('notes', 10), ('ordinary text', 65)],
[('TOTAL AMOUNT', 65)],
)
assert derive_incomplete_table_bbox(
characters=characters,
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 48},
) is None
def test_profile_reconstruction_uses_page_evidence_when_table_glyphs_are_header_only(monkeypatch):
"""Profile 重建入口必须把页级派生框传给同一行重建器。"""
from app.services.shipping_notice import order_document_profile_service as service
page_glyphs = _glyphs(
[('Item', 10), ('Material', 65), ('Quantity', 150)],
[('Description', 10), ('Delivery Date', 120)],
[('10', 10), ('PART-A', 65), ('3.000', 150)],
[('FRAME', 65), ('PCS', 150)],
[('898.72', 120), ('2,696.16', 165)],
[('TOTAL', 65)],
)
layout = {
'status': 'ready',
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 200, 'y1': 48}}],
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 120}},
'page_glyphs': {'1': page_glyphs},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {'table-1': page_glyphs[:30]},
},
}
monkeypatch.setattr(service.db.session, 'get', lambda _model, _id: SimpleNamespace(id=77))
result = service.suggest_coordinate_reconstruction(
{'document_id': 77, 'table_id': 'table-1'}, actor_id=None, layout_snapshot=layout,
)
assert result['table_bbox_source'] == 'page_coordinate_derived'
assert len(result['subrow_layouts']) == 3
def test_coordinate_profile_rows_merge_only_declared_physical_layouts():
"""v2 主行必须有行号,续行按 row_offset 合并,合计或额外文本不得混入明细。"""
rows = reconstruct_coordinate_profile_rows(
@@ -241,6 +393,114 @@ def test_coordinate_profile_rows_merge_only_declared_physical_layouts():
assert rows[0].fields == {'customer_po_line_no': '00010', 'part_number': 'PART-A', 'qty': '5', 'required_date': '2026-08-01'}
def test_coordinate_profile_rows_require_multi_field_signature_for_new_records():
"""孤立数字不能启动明细;同一视觉行的业务字段组合才可启动。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('0', 10)],
[('20', 10), ('PART-A', 65), ('5', 160)],
), table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': .75, 'y1': 1}},
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
schema_field_metadata=[
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer', 'validator_keys': ['positive_integer']},
],
)
# 关键断言:表头/噪声中的孤立 0 不得成为第 1 条明细,真实组合只产生 1 条。
assert [row.fields for row in rows] == [{
'customer_po_line_no': '20', 'part_number': 'PART-A', 'qty': '5',
}]
def test_coordinate_profile_rows_can_start_without_line_number_when_business_fields_agree():
"""客户行号缺失时,料号与数量等独立业务字段可在任意列位置联合起行。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs([('PART-A', 10), ('5', 160)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .75, 'y1': 1}},
{'field_code': 'qty', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
line_start_field_code='customer_po_line_no',
schema_field_metadata=[
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer', 'validator_keys': ['positive_integer']},
],
)
# 关键断言:起行不依赖列序或必须存在的行号字段。
assert [row.fields for row in rows] == [{'part_number': 'PART-A', 'qty': '5'}]
def test_coordinate_profile_rows_ignore_non_line_schema_fields_for_record_start():
"""明细起行只消费 Schema scope=line,header 字段不能提供联合起行证据。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs([('Vendor', 10), ('PART-A', 65)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .75, 'y1': 1}},
{'field_code': 'vendor', 'region': {'x0': .75, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
line_start_field_code='customer_po_line_no',
schema_field_metadata=[
{'field_code': 'vendor', 'scope': 'header', 'value_type': 'string', 'validator_keys': ['non_empty']},
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
],
)
# 只有一个 line 字段有效;header 字段不能把该视觉行提升为明细。
assert rows == []
def test_adaptive_record_start_uses_only_schema_line_fields_without_business_name_whitelist():
"""自适应模式同样按 Schema line 字段联合起行,不能把表头文本当行号。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs([('0rd', 10), ('Shipping In', 65)], [('20', 10), ('PART-A', 65)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
line_start_field_code='customer_po_line_no',
row_reconstruction_mode='adaptive_record_columns',
schema_field_metadata=[
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
],
)
assert [row.fields for row in rows] == [{
'customer_po_line_no': '20', 'customer_part_number': 'PART-A',
}]
def test_schema_string_line_anchor_rejects_header_text():
"""string 类型起行字段仍须满足通用行号形态,不能接受表头文本。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs([('0rd', 10), ('PART-A', 65)], [('B', 10), ('PART-B', 65)], [('20', 10), ('PART-C', 65)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
]}],
line_start_field_code='customer_po_line_no',
schema_field_metadata=[
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'},
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
],
)
assert [row.fields for row in rows] == [{
'customer_po_line_no': '20', 'part_number': 'PART-C',
}]
def test_line_number_can_be_used_as_a_configured_coordinate_anchor():
"""用户选择项次字段时,坐标模板可用 line_no 启动明细。"""
rows = reconstruct_coordinate_profile_rows(
@@ -277,6 +537,73 @@ def test_coordinate_profile_row_layout_repeats_across_the_table():
]
def test_coordinate_profile_rows_apply_selected_anchor_frame_translation_to_all_regions():
"""锚点框架选中的平移必须同时投影主表、物理行和每个字段区。"""
baseline_layout = {
'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40},
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0,
'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': .35},
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .25, 'x1': .25, 'y1': .35}},
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .25, 'x1': .55, 'y1': .35}},
{'field_code': 'qty', 'region': {'x0': .55, 'y0': .25, 'x1': .75, 'y1': .35}},
{'field_code': 'unit_price', 'region': {'x0': .75, 'y0': .25, 'x1': 1, 'y1': .35}},
],
}],
}
shifted = reconstruct_coordinate_profile_rows(
characters=_glyphs([('00010', 10), ('PART-A', 65), ('2', 135), ('10.50', 175)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .20},
**baseline_layout,
)
# Without the selected transform these glyphs sit outside all baseline Y regions.
assert shifted[0].fields == {
'customer_po_line_no': '00010', 'customer_part_number': 'PART-A',
'qty': '2', 'unit_price': '10.50',
}
def test_coordinate_profile_rows_apply_shared_affine_matrix_to_all_regions():
"""订单行必须消费订单头相同的矩阵变换,禁止仅支持旧 translate 键。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs([('00010', 10), ('PART-A', 65)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
table_region={'x0': 0, 'y0': .10, 'x1': 1, 'y1': .20},
line_layouts=[{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .10, 'x1': 1, 'y1': .20}, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .10, 'x1': .25, 'y1': .20}},
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .10, 'x1': 1, 'y1': .20}},
]}],
coordinate_transform={
'status': 'applied', 'matrix': [1.0, 0.0, 0.0, 0.0, 1.0, .10],
'anchor_ids': ['title'], 'reason_codes': [],
},
)
# 关键断言:仅矩阵键存在时,行字段仍以同一运行时坐标系读取。
assert [row.fields for row in rows] == [{'customer_po_line_no': '00010', 'customer_part_number': 'PART-A'}]
def test_coordinate_profile_rows_reject_invalid_selected_anchor_frame_transform():
"""非 matcher 认可的变换不得悄悄回退为绝对坐标取值。"""
kwargs = {
'characters': _glyphs([('00010', 10), ('PART-A', 65)]),
'table_bbox': {'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
'table_region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40},
'line_layouts': [{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .20, 'x1': 1, 'y1': .40}, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .20, 'x1': .25, 'y1': .40}},
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .20, 'x1': 1, 'y1': .40}},
]}],
}
assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={'status': 'pending'}) == []
assert reconstruct_coordinate_profile_rows(**kwargs, coordinate_transform={
'status': 'applied', 'translate_x': 0, 'translate_y': .9,
}) == []
def test_coordinate_profile_preview_can_expose_unanchored_main_row_for_review():
"""仅预览模式在缺少有效起行值时保留字段证据,正式重建仍严格过滤。"""
kwargs = {
@@ -585,6 +912,133 @@ def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_l
},
]
def test_dynamic_x_columns_recovers_a_shifted_record_hidden_by_static_header_exclusion():
"""表头随单头高度移动时,动态候选须以起行/列校验恢复被旧表头框遮住的首条明细。"""
rows, strategy = reconstruct_coordinate_profile_rows_with_strategy(
characters=_glyphs(
[('LN', 10), ('Quantity', 50), ('Part Number', 120)],
[('1', 10), ('113', 50), ('PART-A', 120)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 60},
table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
line_layouts=[{
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': .5, 'x1': 1, 'y1': .9},
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .5, 'x1': .15, 'y1': .7}},
{'field_code': 'qty', 'region': {'x0': .15, 'y0': .5, 'x1': .4, 'y1': .7}},
{'field_code': 'part_number', 'region': {'x0': .4, 'y0': .5, 'x1': 1, 'y1': .7}},
],
}],
exclusion_regions=[{'x0': 0, 'y0': .2, 'x1': 1, 'y1': .75}],
dynamic_exclusion_regions=[],
line_start_field_code='customer_po_line_no',
)
assert strategy.status == 'selected'
assert strategy.row_mode == 'dynamic_x_columns'
assert [row.fields for row in rows] == [
{'customer_po_line_no': '1', 'qty': '113', 'part_number': 'PART-A'},
]
def test_dynamic_x_columns_translates_all_field_frames_from_the_record_anchor():
"""动态行整体上移时,跨视觉行字段须随同一锚点平移而非复用首行前缀。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('1', 10), ('113', 50), ('WTP-D4-', 120)],
[('A08AR12000001', 120)],
[('D4-A08AR12000001', 120)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 260, 'y1': 120},
table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
line_layouts=[{
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': .50, 'x1': 1, 'y1': .95},
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .70, 'x1': .15, 'y1': .80}},
{'field_code': 'qty', 'region': {'x0': .15, 'y0': .70, 'x1': .4, 'y1': .80}},
{'field_code': 'customer_part_number', 'region': {'x0': .4, 'y0': .70, 'x1': 1, 'y1': .90}},
{'field_code': 'part_number', 'region': {'x0': .4, 'y0': .92, 'x1': 1, 'y1': 1}},
],
}],
line_start_field_code='customer_po_line_no',
row_reconstruction_mode='dynamic_x_columns',
)
assert [row.fields for row in rows] == [{
'customer_po_line_no': '1', 'qty': '113',
'customer_part_number': 'WTP-D4-A08AR12000001',
'part_number': 'D4-A08AR12000001',
}]
def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor():
"""固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('1', 10), ('CUSTOMER-1', 60)], [('VENDOR-1', 60)],
[('2', 10), ('CUSTOMER-2', 60)], [('VENDOR-2', 60)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 140},
table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
line_layouts=[{
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': .50, 'x1': 1, 'y1': .95},
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .60, 'x1': .2, 'y1': .70}},
{'field_code': 'customer_part_number', 'region': {'x0': .25, 'y0': .60, 'x1': 1, 'y1': .68}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': .70, 'x1': 1, 'y1': .78}},
],
}],
line_start_field_code='customer_po_line_no',
schema_field_metadata=[
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
],
)
assert [row.fields for row in rows] == [
{'customer_po_line_no': '1', 'customer_part_number': 'CUSTOMER-1', 'part_number': 'VENDOR-1'},
{'customer_po_line_no': '2', 'customer_part_number': 'CUSTOMER-2', 'part_number': 'VENDOR-2'},
]
def test_coordinate_profile_strategy_prefers_fixed_for_wrapped_part_fields():
"""跨视觉行字段必须使用字段框完整值,不能被 adaptive 前缀覆盖。"""
schema = [
{'field_code': code, 'scope': 'line', 'enabled': True, 'data_type': 'string'}
for code in ('customer_po_line_no', 'customer_part_number', 'part_number')
]
rows, strategy = reconstruct_coordinate_profile_rows_with_strategy(
characters=_glyphs(
[('1', 10), ('WTP-B3-', 55)],
[('A08AR11000001', 55)],
[('B3-A08AR11000001', 55)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 70},
table_region={'x0': 0, 'y0': .1, 'x1': 1, 'y1': .95},
line_layouts=[{
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .95},
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .2, 'y1': .4}},
{'field_code': 'customer_part_number', 'region': {'x0': .2, 'y0': .2, 'x1': .7, 'y1': .65}},
{'field_code': 'part_number', 'region': {'x0': .2, 'y0': .65, 'x1': .7, 'y1': .9}},
],
}],
schema_field_metadata=schema,
line_start_field_code='customer_po_line_no',
)
assert strategy.status == 'selected'
assert strategy.row_mode == 'fixed_subrows'
assert rows[0].fields['customer_part_number'] == 'WTP-B3-A08AR11000001'
assert rows[0].fields['part_number'] == 'B3-A08AR11000001'
assert rows[0].issues == []
deleted = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 10), ('B3-A08AR10000018-A7', 120)],
@@ -850,6 +1304,7 @@ def test_profile_order_carries_coordinate_field_evidence_into_observation():
'page_no': 1, 'table_id': 'table-1',
'value_bbox': {'x0': 10, 'y0': 20, 'x1': 40, 'y1': 30},
'glyph_indices': [5, 6, 7], 'token_ids': ['g5', 'g6', 'g7'],
'evidence_ref': 'layout:9:p1:table-1:part-id',
'bbox_text': 'PART-A', 'quote_source': 'glyph_region',
'source': 'pdf_coordinate', 'has_value_coordinate': True,
'coordinate_status': 'candidate', 'highlight_quality': 'candidate',
@@ -860,13 +1315,51 @@ def test_profile_order_carries_coordinate_field_evidence_into_observation():
schema={'schema_version_id': 1, 'checksum': 'a' * 64}, definition=definition, table=table,
)
from app.services.shipping_notice.order_extraction_workflow import _normalize_profile_order_observations
_normalize_profile_order_observations(
[order], default_value_source='coordinate_ocr', coordinate_transform=None,
)
observation = order['lines'][0]['fields'][0]['observations'][0]
assert observation['value'] == 'PART-A'
# 统一 Observation 合同:坐标路径也必须显式声明最终值源,而不是只藏在 layout_evidence。
assert observation['value_source'] == 'native_pdf'
assert observation['evidence_ref'] == 'layout:9:p1:table-1:part-id'
assert observation['transform_ref'] == {'kind': 'legacy_absolute'}
assert observation['layout_evidence']['page_no'] == 1
assert observation['layout_evidence']['value_bbox'] == {'x0': 10, 'y0': 20, 'x1': 40, 'y1': 30}
assert observation['layout_evidence']['token_ids'] == ['g5', 'g6', 'g7']
def test_profile_observation_preserves_ocr_source_and_applied_transform():
"""OCR 证据与受限变换必须在统一 Observation 中可审计,不能伪装为原生 PDF。"""
from app.services.shipping_notice.order_extraction_workflow import _normalize_profile_order_observations
order = {
'header_fields': [],
'lines': [{'fields': [{'field_id': 'part-id', 'observations': [{
'value': 'PART-A', 'document_id': 9,
'layout_evidence': {'source': 'ocr_coordinate', 'evidence_ref': 'layout:9:p1:t1:c1'},
}]}]}],
}
transform = {
'status': 'applied', 'matrix': [1.01, 0, .02, 0, .99, .01],
'anchor_count': 3, 'residual': .002,
}
_normalize_profile_order_observations(
[order], default_value_source='coordinate_ocr', coordinate_transform=transform,
)
observation = order['lines'][0]['fields'][0]['observations'][0]
assert observation['value_source'] == 'ocr'
assert observation['evidence_ref'] == 'layout:9:p1:t1:c1'
assert observation['transform_ref'] == {
'kind': 'coordinate_transform', 'status': 'applied',
'matrix': [1.01, 0, .02, 0, .99, .01], 'anchor_count': 3, 'residual': .002,
}
def test_coordinate_reconstruction_uses_x_y_and_continuation_rules():
"""行号、料号、数量按 x/y 重建;无行号的下一视觉行只能是续行。"""
result = _reconstruct(_glyphs(
@@ -2,7 +2,7 @@
backend/tests/test_shipping_customer_auto_resolution.py
用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice/Case、customer_auto_resolution。
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
"""
@@ -14,7 +14,6 @@ from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
FileAsset,
ShippingCase,
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingIdentityDefinition,
@@ -122,11 +121,10 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
candidate_key="document:1", validation_status="ready", selected=True,
structured_result_json={"business_summary": {"customer_name": "unstable name"}},
)
case = ShippingCase(case_no=f"AUTO-CASE-{user.id}", numbering_status="pending")
db.session.add_all([candidate, case])
db.session.add(candidate)
db.session.flush()
task = ShippingNotice(
task_no=f"SN-AUTO-{user.id}", shipping_case_id=case.id, source_candidate_id=candidate.id,
task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id,
user_id=user.id, source_type="email_attachment",
customer_resolution_status="pending",
)
@@ -216,8 +214,8 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
assert result["rule_version"] == AUTO_RESOLUTION_VERSION
assert task.customer_resolution_status == "confirmed"
assert task.customer_resolution_method == "auto_rule"
assert task.shipping_case.customer_id == customer.id
assert task.shipping_case.business_no.startswith("WYC")
assert task.customer_id == customer.id
assert task.business_no.startswith("WYC")
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1
event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one()
assert event.detail_json['rule_set']['checksum']
@@ -240,13 +238,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False
disabled = try_auto_confirm_task_customer(task)
assert disabled["status"] == "disabled"
assert task.shipping_case.business_no is None
assert task.business_no is None
_allow_auto_confirmation(app)
unmatched = try_auto_confirm_task_customer(task)
assert unmatched["status"] == "unmatched"
assert task.customer_resolution_status == "pending"
assert task.shipping_case.business_no is None
assert task.business_no is None
def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
@@ -261,7 +259,7 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
assert result["status"] == "ambiguous"
assert len(result["candidate_customer_ids"]) == 2
assert task.customer_resolution_status == "pending"
assert task.shipping_case.business_no is None
assert task.business_no is None
def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
@@ -271,7 +269,6 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
task = _seed_candidate_task()
task_id = task.id
case_id = task.shipping_case_id
result = try_auto_confirm_task_customer(task)
assert result["status"] == "auto_confirmed"
@@ -279,10 +276,9 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
db.session.expire_all()
persisted_task = db.session.get(ShippingNotice, task_id)
persisted_case = db.session.get(ShippingCase, case_id)
assert persisted_task.customer_resolution_status == "pending"
assert persisted_case.customer_id is None
assert persisted_case.business_no is None
assert persisted_task.customer_id is None
assert persisted_task.business_no is None
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0
@@ -300,7 +296,7 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic
assert result["status"] == "insufficient_labeled_samples"
assert result["quality_gate"]["labeled_sample_count"] == 0
assert task.customer_resolution_status == "pending"
assert task.shipping_case.business_no is None
assert task.business_no is None
def test_business_evidence_never_auto_confirms(app):
@@ -405,61 +401,48 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
assert result["quality_gate"]["labeled_sample_count"] == 1
assert result["quality_gate"]["accuracy"] == 0
assert task.customer_resolution_status == "pending"
assert task.shipping_case.business_no is None
assert task.business_no is None
def test_numbered_customer_correction_voids_old_number_and_replaces_case(app):
"""客户误确认纠错必须保留原号作废,生成新客户编号并让原号查询跟随替代单。"""
def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app):
"""客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。"""
with app.app_context():
wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active")
correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active")
case = ShippingCase(case_no="CASE-CORRECTION", numbering_status="pending")
db.session.add_all([wrong, correct, case])
db.session.add_all([wrong, correct])
db.session.flush()
first = ShippingNotice(
task_no="SN-CORRECTION-V1", shipping_case_id=case.id, document_version=1,
source_type="manual", customer_resolution_status="pending",
)
db.session.add(first)
db.session.flush()
latest = ShippingNotice(
task_no="SN-CORRECTION-V2", shipping_case_id=case.id, document_version=2,
supersedes_task_id=first.id, source_type="manual", upload_status="pending",
customer_resolution_status="pending", inventory_source_code="DSV",
task_no="SN-CORRECTION-V1", document_version=1,
source_type="manual", upload_status="pending", customer_resolution_status="pending", inventory_source_code="DSV",
inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}],
match_status="fulfillable", line_results_json=[{"sku": "A"}],
export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx",
)
db.session.add(latest)
db.session.add(first)
db.session.commit()
confirm_task_customer(first, customer_id=wrong.id, actor_id=None)
old_case_id = case.id
old_business_no = case.business_no
old_business_no = first.business_no
result = correct_numbered_task_customer(
latest,
first,
customer_id=correct.id,
reason="自动识别客户错误",
actor_id=None,
)
old_case = db.session.get(ShippingCase, old_case_id)
replacement = db.session.get(ShippingCase, result["new_case_id"])
assert old_case.business_no == old_business_no
assert old_case.status == "voided"
assert old_case.numbering_status == "voided"
assert replacement.replaces_case_id == old_case.id
replacement = db.session.get(ShippingNotice, result["new_notice_id"])
assert first.business_no == old_business_no
assert first.lifecycle_status == "voided"
assert replacement.supersedes_task_id == first.id
assert replacement.business_no.startswith("NEW")
assert replacement.business_no != old_business_no
assert latest.shipping_case_id == replacement.id
assert first.shipping_case_id == replacement.id
assert latest.customer_resolution_method == "admin_correction"
assert latest.inventory_source_status is None
assert latest.inventory_lines_json is None
assert latest.export_file_path is None
assert latest.source_type == "manual"
assert get_task_by_ref(old_business_no).id == latest.id
assert get_task_by_ref(replacement.business_no).id == latest.id
assert replacement.customer_resolution_method == "admin_correction"
assert replacement.inventory_source_status is None
assert replacement.inventory_lines_json is None
assert replacement.export_file_path is None
assert replacement.source_type == "manual"
assert get_task_by_ref(old_business_no).id == first.id
assert get_task_by_ref(replacement.business_no).id == replacement.id
assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2
metrics = get_auto_resolution_metrics()
assert metrics["corrected_task_count"] == 2
@@ -471,11 +454,10 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
with app.app_context():
wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active")
correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active")
case = ShippingCase(case_no="CASE-CORRECTION-BLOCK", numbering_status="pending")
db.session.add_all([wrong, correct, case])
db.session.add_all([wrong, correct])
db.session.flush()
task = ShippingNotice(
task_no="SN-CORRECTION-BLOCK", shipping_case_id=case.id,
task_no="SN-CORRECTION-BLOCK",
source_type="manual", customer_resolution_status="pending",
)
db.session.add(task)
@@ -493,4 +475,4 @@ def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(a
correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None)
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED"
db.session.rollback()
assert db.session.query(ShippingCase).count() == 1
assert db.session.query(ShippingNotice).count() == 1
@@ -3,7 +3,7 @@ backend/tests/test_shipping_customer_identity_gate.py
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。
依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。
逻辑:构造 pending 或缺失业务单的任务逐入口断言无副作用;确认后验证业务单/修订同步。
逻辑:构造 pending 或未确认客户的 Notice 逐入口断言无副作用;确认后验证 Notice 客户和编号事实。
"""
from __future__ import annotations
@@ -15,7 +15,7 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError
from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent, User
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent, User
from app.services.shipping_notice.customer_identity_gate import (
assert_customer_identity_gate,
confirm_task_customer,
@@ -31,7 +31,7 @@ from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.task_workflow import retry_task
def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]:
def _seed_task(*, customer_pending: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]:
"""创建待确认任务、启用客户和任务用户。"""
sequence = db.session.query(User).count()
user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user')
@@ -39,14 +39,9 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingNotice, ShippingCusto
customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active')
db.session.add_all([user, customer])
db.session.flush()
case = ShippingCase(case_no=f'CASE-GATE-{user.id}') if with_case else None
if case:
db.session.add(case)
db.session.flush()
task = ShippingNotice(
task_no=f'SN-GATE-{user.id}', user_id=user.id,
shipping_case_id=case.id if case else None,
customer_resolution_status='pending' if case else None,
customer_resolution_status='pending' if customer_pending else None,
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}],
inventory_source_status='user_confirmed', inventory_source_code='DSV',
)
@@ -111,12 +106,12 @@ def test_pending_customer_blocks_retry_before_clearing_review_state(app):
assert task.error_message == '标准客户尚未确认'
def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
"""客户确认同步同业务单全部任务,并在同事务生成正式业务号。"""
def test_confirm_customer_does_not_assign_notice_number_before_excel(app):
"""客户确认只固化客户事实;正式单号只能在首个 Excel 生成时分配。"""
with app.app_context():
task, customer, user = _seed_task()
revision = ShippingNotice(
task_no='SN-GATE-REV', user_id=user.id, shipping_case_id=task.shipping_case_id,
task_no='SN-GATE-REV', user_id=user.id,
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
)
db.session.add(revision)
@@ -124,24 +119,60 @@ def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
db.session.refresh(revision)
case = db.session.get(ShippingCase, task.shipping_case_id)
assert updated.customer_resolution_status == 'confirmed'
assert revision.customer_resolution_status == 'confirmed'
assert revision.customer_resolution_status == 'pending'
assert updated.customer_resolution_method == 'manual'
assert case.customer_id == customer.id
assert case.customer_name_snapshot == customer.standard_name
assert case.customer_short_code_snapshot == customer.short_code
assert case.business_no.startswith(customer.short_code)
assert len(case.business_no) == len(customer.short_code) + 8
assert case.sequence_value == 1
assert case.numbering_status == 'assigned'
assert updated.customer_id == customer.id
assert updated.customer_name_snapshot == customer.standard_name
assert updated.customer_short_code_snapshot == customer.short_code
assert updated.business_no is None
assert updated.business_date is None
assert updated.business_sequence_value is None
assert customer_identity_is_confirmed(updated) is True
assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 2
assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 2
assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 1
assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 0
def test_inactive_customer_reblocks_and_missing_case_is_blocked(app):
"""已确认客户停用后重新阻断;缺少业务单的任务也必须阻断。"""
def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, monkeypatch):
"""PostgreSQL 行锁只覆盖 Notice,不能锁 joined customer 的外连接空侧。"""
with app.app_context():
task, customer, user = _seed_task()
original_query = db.session.query
lock_arguments: list[dict] = []
class NoticeQuerySpy:
"""保留真实 Query 行为,仅记录客户确认路径的行锁参数。"""
def __init__(self, query):
self._query = query
def filter(self, *criteria):
self._query = self._query.filter(*criteria)
return self
def with_for_update(self, **kwargs):
lock_arguments.append(kwargs)
self._query = self._query.with_for_update(**kwargs)
return self
def one(self):
return self._query.one()
def traced_query(*entities, **kwargs):
query = original_query(*entities, **kwargs)
if len(entities) == 1 and entities[0] is ShippingNotice:
return NoticeQuerySpy(query)
return query
monkeypatch.setattr(db.session, 'query', traced_query)
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
assert lock_arguments == [{'of': ShippingNotice}]
def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
"""已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。"""
with app.app_context():
task, customer, user = _seed_task()
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
@@ -151,11 +182,11 @@ def test_inactive_customer_reblocks_and_missing_case_is_blocked(app):
assert_customer_identity_gate(task, operation='match_inventory')
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
missing_case, _other_customer, _other_user = _seed_task(with_case=False)
with pytest.raises(AppError) as missing_case_error:
assert_customer_identity_gate(missing_case, operation='match_inventory')
assert missing_case_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
assert customer_identity_is_confirmed(missing_case) is False
unconfirmed, _other_customer, _other_user = _seed_task(customer_pending=False)
with pytest.raises(AppError) as unconfirmed_error:
assert_customer_identity_gate(unconfirmed, operation='match_inventory')
assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
assert customer_identity_is_confirmed(unconfirmed) is False
def test_workspace_customer_search_and_confirmation_api(app, client):
@@ -95,3 +95,113 @@ def test_shipping_customer_migrations_upgrade_and_downgrade():
finally:
for module, original_op in zip(modules, original_ops, strict=True):
module.op = original_op
def _shipping_case_removal_schema(engine: sa.Engine, *, migrated: bool) -> None:
"""构造最终删表迁移所需的最小 Notice/Case 历史结构。"""
metadata = sa.MetaData()
sa.Table('shipping_customers', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'shipping_cases', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('customer_id', sa.Integer(), nullable=True),
sa.Column('business_no', sa.String(32), nullable=True),
)
sa.Table(
'shipping_notices', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('task_no', sa.String(64), nullable=False),
sa.Column('shipping_case_id', sa.Integer(), sa.ForeignKey('shipping_cases.id'), nullable=True),
sa.Column('customer_id', sa.Integer(), nullable=True),
sa.Column('business_no', sa.String(32), nullable=True),
)
metadata.create_all(engine)
with engine.begin() as connection:
connection.execute(sa.text("INSERT INTO shipping_cases (id, customer_id, business_no) VALUES (1, 7, 'CUS26082301')"))
if migrated:
connection.execute(sa.text(
"INSERT INTO shipping_notices (id, task_no, shipping_case_id, customer_id, business_no) "
"VALUES (1, 'SN-MIGRATED', 1, 7, 'CUS26082301')"
))
else:
connection.execute(sa.text(
"INSERT INTO shipping_notices (id, task_no, shipping_case_id, customer_id, business_no) "
"VALUES (1, 'SN-UNMIGRATED', 1, NULL, NULL)"
))
def test_shipping_case_removal_migration_requires_notice_facts_and_drops_legacy_table():
"""最终迁移只能删除已回填 Notice 的 Case;未回填事实必须显式失败。"""
module = importlib.import_module('migrations.versions.hp9q0r1s2t3u_remove_shipping_case')
for migrated in (True, False):
engine = sa.create_engine('sqlite:///:memory:')
_shipping_case_removal_schema(engine, migrated=migrated)
with engine.begin() as connection:
original_op = module.op
module.op = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
try:
if migrated:
module.upgrade()
inspector = sa.inspect(connection)
assert 'shipping_cases' not in inspector.get_table_names()
assert 'shipping_case_id' not in {item['name'] for item in inspector.get_columns('shipping_notices')}
else:
with pytest.raises(RuntimeError, match='migration incomplete'):
module.upgrade()
finally:
module.op = original_op
def test_shipping_case_removal_repairs_fact_columns_skipped_by_inconsistent_revision():
"""版本表已越过前置迁移但 Notice 仍为旧结构时,最终迁移应先恢复事实列再删 Case。"""
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
sa.Table('shipping_customers', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'shipping_cases', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('customer_id', sa.Integer(), nullable=True),
sa.Column('business_no', sa.String(32), nullable=True),
sa.Column('business_date', sa.Date(), nullable=True),
sa.Column('sequence_value', sa.Integer(), nullable=True),
sa.Column('numbering_rule_version', sa.String(32), nullable=True),
sa.Column('customer_name_snapshot', sa.String(200), nullable=True),
sa.Column('customer_short_code_snapshot', sa.String(6), nullable=True),
)
sa.Table(
'shipping_notices', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('task_no', sa.String(64), nullable=False),
sa.Column('shipping_case_id', sa.Integer(), sa.ForeignKey('shipping_cases.id'), nullable=True),
)
metadata.create_all(engine)
with engine.begin() as connection:
connection.execute(sa.text("INSERT INTO shipping_customers (id) VALUES (7)"))
connection.execute(sa.text(
"INSERT INTO shipping_cases "
"(id, customer_id, business_no, business_date, sequence_value, numbering_rule_version, "
"customer_name_snapshot, customer_short_code_snapshot) "
"VALUES (1, 7, 'CUS26082301', '2026-08-23', 1, 'V1', 'Customer', 'CUS')"
))
connection.execute(sa.text(
"INSERT INTO shipping_notices (id, task_no, shipping_case_id) "
"VALUES (1, 'SN-LEGACY', 1)"
))
module = importlib.import_module('migrations.versions.hp9q0r1s2t3u_remove_shipping_case')
with engine.begin() as connection:
original_op = module.op
module.op = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
try:
module.upgrade()
inspector = sa.inspect(connection)
columns = {item['name'] for item in inspector.get_columns('shipping_notices')}
assert {'business_no', 'customer_id', 'business_date', 'business_sequence_value'} <= columns
row = connection.execute(sa.text(
"SELECT business_no, customer_id, business_sequence_value "
"FROM shipping_notices WHERE id = 1"
)).one()
assert row == ('CUS26082301', 7, 1)
assert 'shipping_cases' not in inspector.get_table_names()
finally:
module.op = original_op
@@ -14,7 +14,7 @@ import pytest
from app import db
from app.models import (
FileAsset, ShippingCase, ShippingCustomer, ShippingCustomerShadowMatch,
FileAsset, ShippingCustomer, ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution, ShippingCustomerSite, ShippingOrderCandidate,
ShippingOrderDocument, ShippingOrderIntake, ShippingOrderExtraction, ShippingOrderField,
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderSchema,
@@ -154,9 +154,6 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app):
)
_intake, candidate = _seed_candidate(sender='spoof@example.net')
_attach_value(candidate, version, field, 'buyer@wyc.example.com')
case = ShippingCase(case_no='CASE-SHADOW')
db.session.add(case)
resolution = refresh_candidate_shadow_resolution(candidate)
assert resolution.status == 'unique_candidate'
@@ -164,7 +161,6 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app):
assert resolution.identity_rule_set_id == rule_set['id']
assert resolution.evidence_json[0]['context_field_id'] == field.id
assert resolution.evidence_json[0]['source']['kind'] == 'field_value'
assert case.customer_id is None and case.business_no is None
def test_schema_uuid_drift_keeps_stable_customer_identity_rule_matching(app):
@@ -93,6 +93,25 @@ def test_layout_snapshot_checksum_and_idempotent_current_version(app):
assert current_layout_snapshot(document)['marker'] == 'v1'
def test_ready_pdf_layout_requires_coordinate_evidence_asset(app, monkeypatch):
"""关键断言:PDF 坐标证据资产保存失败时,布局不得伪装为 ready。"""
with app.app_context():
document = _document()
monkeypatch.setattr(layout_lifecycle, '_persist_coordinate_evidence_asset', lambda **_: None)
snapshot = {
**_snapshot(),
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><td>x</td></tr></table>'}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}},
'page_glyphs': {'1': [{'text': 'x'}]},
'tables': {'table-1': [{'text': 'x'}]},
},
}
version = record_inline_layout_snapshot(document, snapshot)
assert version.status == 'failed'
assert 'shipping_document_layout_coordinate_evidence_persist_failed' in version.issues_json
def test_inline_derived_xfa_layout_localizes_structure_analysis_identity(app):
"""坐标补证派生 Layout 必须克隆 XFA Analysis,样本可安全冻结到新版本。"""
with app.app_context():
@@ -504,6 +523,8 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab
assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate']
assert 'tables' not in pending.payload_json['coordinate_evidence']
assert 'page_glyphs' not in pending.payload_json['coordinate_evidence']
assert pending.payload_json['matching_features']['version'] == 'v1'
assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2]
assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json
assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json
assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json
@@ -569,6 +590,66 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map
assert 'tables' not in restored['coordinate_evidence']
def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app):
"""冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。"""
with app.app_context():
document = _document()
current = record_inline_layout_snapshot(document, {
**_snapshot(),
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'tables': {'table-1': [{'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
db.session.flush()
document.current_layout_version = current
frozen_layout = {
**_snapshot(),
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
}
restored = ensure_on_demand_coordinate_evidence(
document=document, layout=frozen_layout, page_nos={1},
)
# 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H'
assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H'
def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app):
"""同页同时存在时,当前 Layout 是最新事实,不能被旧 Run 快照坐标覆盖。"""
with app.app_context():
document = _document()
current = record_inline_layout_snapshot(document, {
**_snapshot(),
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
document.current_layout_version = current
stale_run_layout = {
**_snapshot(),
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'STALE', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'sources': {'pages': {'1': 'ocr_coordinate'}},
},
}
restored = ensure_on_demand_coordinate_evidence(
document=document, layout=stale_run_layout, page_nos={1},
)
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT'
assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate'
def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypatch):
"""同一页存在多张物理表时,每个 table_id 都必须获得独立坐标字符证据。"""
with app.app_context():
@@ -612,6 +693,35 @@ def test_on_demand_evidence_restores_every_table_on_the_same_page(app, monkeypat
}
def test_on_demand_evidence_leaves_coordinates_missing_when_native_and_ocr_fail(app, monkeypatch):
"""原 PDF 无字符且 OCR 不可用时不得伪造坐标,调用方必须转 Review。"""
with app.app_context():
document = _document()
layout = {
**_snapshot(),
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 80}}],
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
}
page = SimpleNamespace(page_no=1, width=100, height=200, image=None, characters=[])
monkeypatch.setattr(
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content: [page],
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.ocr_pdf.extract_ocr_lines',
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError('ocr unavailable')),
)
restored = ensure_on_demand_coordinate_evidence(
document=document, layout=layout, page_nos={1},
)
assert not restored['coordinate_evidence'].get('page_glyphs')
def test_layout_document_budget_creates_unsupported_audit_versions(app):
"""超过单 Intake 配额的支持附件必须有 unsupported 审计,不能静默跳过。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
@@ -115,6 +115,53 @@ def test_attach_native_pdf_page_images_renders_only_missing_pages():
assert attached[1].characters is chars_b
def test_extract_native_pdf_pages_closes_pdfium_handles_before_returning():
"""PDFium 句柄必须在数据复制后显式关闭,不能留给 weakref finalizer 在进程退出时回收。"""
closed: list[str] = []
class FakeTextPage:
def count_chars(self):
return 0
def close(self):
closed.append('text')
class FakePage:
def get_size(self):
return 200, 100
def get_textpage(self):
return FakeTextPage()
def get_rotation(self):
return 0
def close(self):
closed.append('page')
class FakeDocument:
def __init__(self, _content):
self.page = FakePage()
def __len__(self):
return 1
def __getitem__(self, _index):
return self.page
def close(self):
closed.append('document')
with patch(
'app.services.shipping_notice.document_layout.native_pdf.pdfium.PdfDocument',
FakeDocument,
):
pages = extract_native_pdf_pages(b'%PDF', render_images=False)
assert len(pages) == 1
assert closed == ['text', 'page', 'document']
def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
"""PDFium 空格即使没有 bbox,也必须成为下一可见字符的可靠边界并保留原始序号。"""
class FakeTextPage:
@@ -135,6 +182,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
assert loose is True
return (10 + index * 4, 80, 13 + index * 4, 88)
def close(self):
"""模拟 PDFium text page 的显式释放接口。"""
class FakePage:
"""模拟无需渲染的单页 PDF。"""
@@ -150,6 +200,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
"""样本不旋转。"""
return 0
def close(self):
"""模拟 PDFium page 的显式释放接口。"""
class FakeDocument:
"""模拟 PDFium 文档的页数和索引访问。"""
@@ -164,6 +217,9 @@ def test_native_pdf_preserves_original_space_boundary_without_zero_bbox_glyph():
"""返回唯一页面。"""
return FakePage()
def close(self):
"""模拟 PDFium document 的显式释放接口。"""
with patch(
'app.services.shipping_notice.document_layout.native_pdf.pdfium.PdfDocument',
FakeDocument,
@@ -242,6 +298,35 @@ def test_native_pdf_text_fallback_accepts_po_header_synonyms_without_false_page_
assert 'PURCHASE' not in tables[0]['html']
def test_native_pdf_text_fallback_skips_separator_between_header_and_first_data_row():
"""表头下的起始横线不能截断无框采购订单的首条明细。"""
characters = []
for y, entries in [
(10, [('Item', 10), ('Material', 55), ('Qty', 135)]),
(22, [('________________________________________', 10)]),
(34, [('00010', 10), ('PART-A', 55), ('2', 135)]),
(46, [('________________________________________', 10)]),
(58, [('Total:', 90), ('2', 135)]),
]:
for value, x0 in entries:
for index, char in enumerate(value):
characters.append(PositionedCharacter(
text=char, source_index=len(characters),
bbox=LayoutBBox(x0=x0 + index * 4, y0=y, x1=x0 + index * 4 + 3, y1=y + 8),
))
page = NativePdfPage(
page_no=1, width=180, height=100, rotation=0, characters=characters,
image=np.full((200, 360), 255, dtype=np.uint8),
)
tables = build_native_pdf_text_table_fallbacks(b'%PDF', native_pages=[page])
# 起始横线后仍须保留首条业务数据;合计行和表尾横线不属于候选表。
assert len(tables) == 1
assert '00010' in tables[0]['html']
assert 'Total:' not in tables[0]['html']
def test_native_pdf_unique_text_builds_traceable_needs_review_layout():
"""唯一文本可形成 cell/token 引用,但人工真值延期时整体仍必须 needs_review。"""
mineru = _candidate('<table><tr><th>Part</th><th>Qty</th></tr></table>')
@@ -65,6 +65,7 @@ def test_runtime_persists_compact_text_and_table_snapshot_without_raw_response(a
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False,
)
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
@@ -107,6 +108,7 @@ def test_runtime_reuses_native_pdf_pages_across_fallback_layout_and_evidence(app
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False,
)
native_pages = [object()]
timings: dict[str, int] = {}
@@ -157,6 +159,7 @@ def test_runtime_empty_mineru_tables_use_pdfium_provider_fallback(app):
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=False,
)
empty_candidate = _candidate().model_copy(update={'pages': [
_candidate().pages[0].model_copy(update={'tables': []}),
@@ -30,6 +30,16 @@ from app.models import (
)
from app.services.shipping_notice import document_profile_quality_service as quality
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.file_assets import storage as file_asset_storage_module
@pytest.fixture(autouse=True)
def _memory_file_asset_storage(monkeypatch):
"""测试外置坐标证据使用内存对象,保持 FileAsset/MinIO 契约而不依赖服务。"""
objects: dict[str, bytes] = {}
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'upload_bytes', lambda *, storage_key, data, content_type: objects.__setitem__(storage_key, bytes(data)))
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'get_bytes', lambda storage_key: objects[storage_key])
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'delete_object', lambda storage_key: objects.pop(storage_key, None))
@pytest.mark.parametrize(
@@ -52,8 +62,8 @@ def test_blind_test_order_field_comparison_rejects_different_values():
)
def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_source():
"""盲测仅在模板显式启用自适应模式时改用整页字符,默认表格模式必须保持不变。"""
def test_quality_region_uses_page_glyphs_for_every_reconstruction_mode():
"""盲测与预览/正式解析必须从当前页同一字符事实开始重建。"""
evidence = {
'tables': {'table-1': [{'text': 'TABLE'}]},
'page_glyphs': {'1': [{'text': 'PAGE'}]},
@@ -62,13 +72,36 @@ def test_adaptive_quality_region_uses_page_glyphs_without_changing_default_sourc
assert quality._region_characters_for_quality(
region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'),
evidence=evidence, raw_table=raw_table, table_id='table-1',
) == [{'text': 'TABLE'}]
) == [{'text': 'PAGE'}]
assert quality._region_characters_for_quality(
region=SimpleNamespace(row_reconstruction_mode='adaptive_record_columns'),
evidence=evidence, raw_table=raw_table, table_id='table-1',
) == [{'text': 'PAGE'}]
def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages():
"""关键断言:第二页只有合同正文时,不能重复重建第一页的订单明细。"""
evidence = {
'tables': {'table-1': [{'text': 'TABLE'}]},
'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'TERMS'}]},
}
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False))
raw_table = {'table_id': 'table-1', 'page_no': 1}
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}]
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None
def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region():
"""关键断言:显式跨页区域只能使用后续页自己的 page glyphs。"""
evidence = {
'tables': {'table-1': [{'text': 'PAGE-1'}]},
'page_glyphs': {'1': [{'text': 'PAGE-1'}], '2': [{'text': 'PAGE-2'}]},
}
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=True))
raw_table = {'table_id': 'table-1', 'page_no': 1}
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) == [{'text': 'PAGE-2'}]
def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingOrderDocument]]:
"""创建一份已发布 Profile 及三份不同文档盲测样本,真值不复用建模输入。"""
user = User(username='profile-quality-admin', email='profile-quality-admin@example.com', role='admin')
@@ -244,10 +277,8 @@ def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(a
)
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
assert executed['latest_run']['status'] == 'passed', executed['latest_run']
with pytest.raises(Exception) as self_approval:
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
assert getattr(self_approval.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
approved = quality.approve_suite(suite_id=suite['id'], actor_id=_independent_approver().id)
# 业务规则:具备管理员权限即可批准,不再要求必须由其他管理员批准。
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
assert approved['status'] == 'approved'
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
qualification = quality.qualification_summary(profile)
@@ -334,6 +365,7 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app):
layout_version = documents[1].current_layout_version
payload = dict(layout_version.payload_json)
payload.pop('coordinate_evidence_ref', None)
payload['coordinate_evidence'] = {'tables': {}, 'pages': {}, 'page_glyphs': {}}
layout_version.payload_json = payload
db.session.commit()
@@ -344,7 +376,6 @@ def test_independent_sample_without_coordinate_evidence_stays_preparing(app):
if item['document_id'] == documents[1].id
)
assert candidate['review_mode'] == 'preparing'
assert candidate['confirmable'] is False
assert candidate['layout_issue_codes'] == ['coordinate_evidence_missing']
@@ -365,27 +396,6 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
"""模拟从原始 PDF 恢复整页字符,验证盲测不依赖 MinerU table_id。"""
assert page_nos is None
recovered = dict(layout)
recovered['coordinate_evidence'] = {
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': [
{'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20,
'x1': x0 + char_index * 5 + 4, 'y1': 30,
}}
for text, x0 in [('PN-1', 30), ('3', 150)]
for char_index, char in enumerate(text)
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {},
}
return recovered
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
candidate_option = next(item for item in available if item['document_id'] == document.id)
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
@@ -393,11 +403,13 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
assert candidate_option['confirmable'] is False
assert candidate_option['layout_issue_codes'] == ['mineru_cell_coordinates_missing']
candidate = quality.preview_independent_sample(
suite_id=suite['id'], document_id=document.id,
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
)
assert candidate['rows'] == [{'part_number': 'PN-1', 'qty': '3'}]
with pytest.raises(Exception) as diagnostic_preview:
quality.preview_independent_sample(
suite_id=suite['id'], document_id=document.id,
table_id=quality.DOCUMENT_CANDIDATE_TABLE_ID, actor_id=user.id,
)
assert getattr(diagnostic_preview.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
candidate = {'rows': []}
with pytest.raises(Exception) as bypassed_review:
quality.add_sample(
suite_id=suite['id'], document_id=document.id,
@@ -405,7 +417,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
expected_rows=candidate['rows'], actor_id=user.id,
)
assert getattr(bypassed_review.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
assert candidate['confirmable'] is False
assert diagnostic_preview.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
with pytest.raises(Exception) as diagnostic_confirmation:
quality.confirm_sample_reviews(
suite_id=suite['id'], document_id=document.id,
@@ -414,7 +426,7 @@ def test_layout_failed_document_is_diagnostic_only(app, monkeypatch):
layout_version_id=current_version.id,
layout_payload_checksum=current_version.payload_checksum, actor_id=user.id,
)
assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE'
assert getattr(diagnostic_confirmation.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch):
@@ -431,29 +443,6 @@ def test_running_layout_without_payload_is_not_reviewable(app, monkeypatch):
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
"""模拟正在预热时直接从原 PDF 恢复整页坐标,空布局不得阻断复核。"""
assert layout == {'status': 'pending', 'tables': [], 'issues': []}
assert page_nos is None
return {
**layout,
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': [
{'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20,
'x1': x0 + char_index * 5 + 4, 'y1': 30,
}}
for text, x0 in [('PN-1', 30), ('3', 150)]
for char_index, char in enumerate(text)
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {},
},
}
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
candidate_option = next(item for item in available if item['document_id'] == document.id)
assert candidate_option['table_id'] == quality.DOCUMENT_CANDIDATE_TABLE_ID
@@ -484,26 +473,6 @@ def test_document_candidate_identity_expires_after_background_layout_completion(
for item in available
)
def recover_document_coordinates(*, document, layout, page_nos, table_by_page=None):
"""文档级复核使用整页证据,不依赖后台刚生成的表格身份。"""
assert page_nos is None
recovered = dict(layout)
recovered['coordinate_evidence'] = {
'pages': {'1': {'width': 200, 'height': 60}},
'page_glyphs': {'1': [
{'text': char, 'bbox': {
'x0': x0 + char_index * 5, 'y0': 20,
'x1': x0 + char_index * 5 + 4, 'y1': 30,
}}
for text, x0 in [('PN-1', 30), ('3', 150)]
for char_index, char in enumerate(text)
]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
'tables': {},
}
return recovered
monkeypatch.setattr(quality, 'ensure_on_demand_coordinate_evidence', recover_document_coordinates)
with pytest.raises(Exception) as stale_preview:
quality.preview_independent_sample(
suite_id=suite['id'], document_id=document.id,
@@ -600,8 +569,9 @@ def test_coordinate_v2_blind_suite_uses_frozen_coordinate_evidence_not_html_grid
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'table-1', 'page_no': 1}],
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}},
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
})
db.session.flush()
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
for document in documents:
@@ -671,7 +641,7 @@ def test_coordinate_blind_preview_skips_header_only_regions(app):
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'table-1', 'page_no': 1}],
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}},
'coordinate_evidence': {'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 60}}, 'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}}},
})
db.session.commit()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
@@ -680,6 +650,56 @@ def test_coordinate_blind_preview_skips_header_only_regions(app):
assert candidate['rows'] == []
def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app):
"""盲测候选必须和编辑器预览一样排除表头视觉区域。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
profile.definition_json = {
'document_match': {'required_anchors': []},
'table_regions': [{
'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
'header_layouts': [{
'layout_id': 'header', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .25},
'field_regions': [],
}],
'line_layouts': [{
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': .25, 'x1': 1, 'y1': 1},
'field_regions': [
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
],
}],
}], 'order_field_layouts': [],
}
glyphs = [
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 10, 'x1': 23 + index * 4, 'y1': 20}}
for index, char in enumerate('Item')
] + [
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}}
for index, char in enumerate('20')
] + [
{'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}}
for index, char in enumerate('PART-A')
]
record_inline_layout_snapshot(documents[1], {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
'tables': [{'table_id': 'table-1', 'page_no': 1}],
'coordinate_evidence': {
'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}},
},
})
db.session.commit()
candidate = quality._candidate_for_sample(
profile=profile, document_id=documents[1].id, table_id='table-1',
)
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
with app.app_context():
+22 -17
View File
@@ -19,7 +19,7 @@ from app import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingCase, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
)
from app.services.shipping_notice import excel_template
@@ -152,12 +152,10 @@ def _workbook_upload() -> FileStorage:
def test_filename_pattern_supports_business_number_and_split_business_variables():
"""业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。"""
shipping_case = ShippingCase(
case_no='CASE-FILENAME', business_no='WYC26060201', customer_short_code_snapshot='WYC',
business_date=date(2026, 6, 2), sequence_value=1,
task = ShippingNotice(
task_no='TASK-FILENAME', inventory_source_code='DBS', business_no='WYC26060201',
customer_short_code_snapshot='WYC', business_date=date(2026, 6, 2), business_sequence_value=1,
)
task = ShippingNotice(task_no='TASK-FILENAME', inventory_source_code='DBS')
task.shipping_case = shipping_case
template = ShippingExcelTemplate(
template_code='FILENAME', display_name='Filename',
definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'},
@@ -333,8 +331,15 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
ShippingOrderFieldValue(extraction_id=extraction.id, field_id=po_number.id, value_text='16754796', decision_id=po_decision.id),
ShippingOrderFieldValue(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, value_text='PN-1', decision_id=line_decision.id),
])
confirmed_customer = ShippingCustomer(
standard_name='Export ACME', short_code='EAC', status='active',
)
db.session.add(confirmed_customer)
db.session.flush()
task = ShippingNotice(
task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB',
customer_id=confirmed_customer.id,
customer_resolution_status='confirmed',
# 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。
inventory_warehouse_id=None, inventory_lines_json=[{
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
@@ -348,6 +353,7 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
lines=[(1, part.id, 'PN-1', 1, '1000000001')],
)
assert task.business_no is None
path, filename, artifact = generate_shipment_excel(task)
db.session.commit()
@@ -363,10 +369,13 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
assert artifact.order_schema_version_id == version.id
assert artifact.inventory_parsing_profile_id == parsing.id
assert artifact.file_checksum and artifact.input_checksum and artifact.file_size > 0
assert task.business_no is not None
assert task.business_no.startswith('EAC')
# 已存在待上传 Artifact 时仍保持原有幂等保护,和 Warehouse ID 无关。
with pytest.raises(ValueError, match='当前任务存在待上传的发货 Excel'):
# 一个 Notice 已有 Excel 后必须创建新 Notice,禁止同号追加第二个 Artifact。
with pytest.raises(ConflictError) as second_export:
generate_shipment_excel(task)
assert second_export.value.code == 'SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED'
def test_header_mapping_rejects_line_order_field(app):
@@ -401,17 +410,13 @@ def test_export_date_system_fact_uses_business_timezone(app):
assert isinstance(value, date)
def test_excel_pull_request_number_uses_export_date_without_changing_case_number(app):
"""Excel Pull Request Number 必须采用导出日期,且业务单主编号保持原值。"""
def test_excel_pull_request_number_uses_notice_business_number(app):
"""Excel Pull Request Number 直接使用 Notice business_no,不因导出日期重编号。"""
with app.app_context():
shipping_case = ShippingCase(
case_no='CASE-EXCEL-NO', business_no='IVMX26080801', sequence_value=1,
)
task = ShippingNotice(task_no='TASK-EXCEL-NO')
task.shipping_case = shipping_case
task = ShippingNotice(task_no='TASK-EXCEL-NO', business_no='IVMX26080801', business_sequence_value=1)
assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26081101'
assert shipping_case.business_no == 'IVMX26080801'
assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26080801'
assert task.business_no == 'IVMX26080801'
def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app):
+126 -11
View File
@@ -12,11 +12,15 @@ from decimal import Decimal
from types import SimpleNamespace
from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate
from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan
from app.services.shipping_notice.order_extraction_workflow import (
_apply_stp_route_adjudication,
_coordinate_profile_rows,
_physical_table_targets_profile_region,
_profile_table_candidates,
_route_reason_for_issue,
_selected_coordinate_transform,
_virtual_page_without_rows_is_nonblocking,
_should_attempt_generic_extraction,
route_deterministic_unit,
)
@@ -37,6 +41,37 @@ def _field(code: str, *, scope: str = 'line', required: bool = False, collection
}
def test_physical_table_outside_profile_region_is_not_a_parse_target():
"""页脚等非目标物理表不得进入模板明细重建并污染已成功的订单表。"""
regions = [{
'region_id': 'order-lines', 'page_scope': 'exact_page', 'page_no': 1,
'region': {'x0': .02, 'y0': .40, 'x1': .94, 'y1': .46},
'line_layouts': [{}],
}]
page = {'width': 612, 'height': 792}
assert _physical_table_targets_profile_region(
raw_table={'table_id': 'order-lines', 'page_no': 1, 'bbox': {'x0': 15, 'y0': 235, 'x1': 570, 'y1': 345}},
table_regions=regions, page_size=page,
) is True
assert _physical_table_targets_profile_region(
raw_table={'table_id': 'footer-summary', 'page_no': 1, 'bbox': {'x0': 16, 'y0': 659, 'x1': 569, 'y1': 721}},
table_regions=regions, page_size=page,
) is False
def test_empty_virtual_page_does_not_block_a_successful_target_table():
"""无物理表的续页仅用于补漏;没有行时不得覆盖已成功的目标表。"""
assert _virtual_page_without_rows_is_nonblocking(
raw_table={'table_id': 'page-2', 'page_no': 2},
fixed_rows=[], adaptive_rows=[],
) is True
assert _virtual_page_without_rows_is_nonblocking(
raw_table={'table_id': 'page-2', 'page_no': 2},
fixed_rows=[{'status': 'needs_review', 'issues': ['field_invalid']}], adaptive_rows=[],
) is False
def _good_candidate() -> dict:
return {
'page_no': 1,
@@ -66,6 +101,19 @@ def _good_candidate() -> dict:
}
def _frozen_generic_document(candidate: dict) -> dict:
"""构造与生产 Run 一致的冻结候选和 Parse Plan,禁止测试直接旁路生产边界。"""
layout = {'status': 'ready', 'tables': [], 'layout_candidate': {}}
return {
'document_id': 55,
'layout_snapshot': layout,
'layout_schema_candidates': [candidate],
'generic_parse_plan': compile_generic_parse_plan(
candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout,
),
}
def test_gate_passes_clean_candidate():
"""完整映射且无未解释行时 gate 通过。"""
definition = {'fields': [_field('part_number', required=True), _field('qty', required=True)]}
@@ -326,6 +374,43 @@ def test_should_attempt_generic_extraction_allows_no_special_profile_feature():
) is True
def test_legacy_profile_does_not_apply_matcher_inferred_coordinate_transform():
"""已发布 legacy 模板的正式字段解析必须沿用盲测验证过的绝对坐标。"""
inferred = {
'status': 'applied', 'translate_x': 0.0, 'translate_y': .03,
'anchor_ids': ['title'], 'reason_codes': [],
}
transform = _selected_coordinate_transform(
raw_profile={
'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
'definition': {'coordinate_model': {'type': 'legacy'}},
},
profile_match={
'status': 'unique_match', 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
'candidates': [{
'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
'coordinate_transform': inferred,
}],
},
)
# 关键断言:自动推断的位移只服务于匹配,不得改变 legacy 模板的正式字段坐标。
assert transform is None
assert _selected_coordinate_transform(
raw_profile={
'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
'definition': {'coordinate_model': {'type': 'anchor_frame'}},
},
profile_match={
'status': 'unique_match', 'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
'candidates': [{
'profile_code': 'ZT_US', 'version': 1, 'checksum': 'a' * 64,
'coordinate_transform': inferred,
}],
},
) == inferred
def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkeypatch):
"""自适应模板的完整业务行不得按子布局数量误判跨页,成功匹配必须上送路由审计。"""
profile = {
@@ -405,7 +490,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey
assert result['match']['status'] == 'unique_match'
assert result['match']['profile_code'] == 'ODP-PRODUCTION'
# 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。
assert seen_table_ids == ['native-text-table-p1-1']
assert seen_table_ids == ['native-text-table-p1-1', 'native-text-table-p1-1']
def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
@@ -415,6 +500,7 @@ def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
region=SimpleNamespace(model_dump=lambda: {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}),
termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False),
line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines',
model_dump=lambda: {'region_id': 'lines', 'page_scope': 'all_pages', 'line_layouts': [{}]},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
@@ -442,6 +528,43 @@ def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
assert seen['characters'][0]['text'] == 'Terms'
def test_coordinate_profile_rows_forward_selected_match_transform_without_recomputing(monkeypatch):
"""工作流只能转交共同 matcher 的已选变换,不能由表格或订单值重新推断。"""
region = SimpleNamespace(
page_scope='all_pages', page_no=None, line_layouts=[SimpleNamespace(model_dump=lambda: {})],
region=SimpleNamespace(model_dump=lambda: {'x0': 0.1, 'y0': 0.2, 'x1': 0.9, 'y1': 0.5}),
termination_rules=[], exclusion_regions=[], continuation_rule=SimpleNamespace(allow_cross_page=False),
line_start_field_code=None, row_reconstruction_mode='fixed_subrows', region_id='lines',
model_dump=lambda: {'region_id': 'lines', 'page_scope': 'all_pages'},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow._frozen_coordinate_profile',
lambda *_args, **_kwargs: SimpleNamespace(table_regions=[region]),
)
seen = {}
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workflow.reconstruct_coordinate_profile_rows',
lambda **kwargs: (seen.update(coordinate_transform=kwargs.get('coordinate_transform')) or []),
)
transform = {
'status': 'applied', 'translate_x': 0.0, 'translate_y': .03,
'anchor_ids': ['title'], 'reason_codes': [],
}
rows = _coordinate_profile_rows(
raw_profile={}, raw_table={'table_id': 'order-table', 'page_no': 1},
layout={'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': [{'text': 'x', 'bbox': {'x0': 30, 'y0': 30, 'x1': 31, 'y1': 31}}]},
'tables': {},
}},
contract=SimpleNamespace(fields_by_code={}), schema_fields={}, coordinate_transform=transform,
)
assert rows == []
assert seen['coordinate_transform'] == transform
def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkeypatch):
"""固定子行以模板表区为权威,须读取 MinerU 框外续行并跳过同页无关表。"""
region = SimpleNamespace(
@@ -559,11 +682,7 @@ def test_route_deterministic_unit_uses_generic_when_enabled(monkeypatch):
'order_document_profiles': [],
'intakes': [{
'intake_no': 'SNI-001',
'documents': [{
'document_id': 55,
'layout_snapshot': {'status': 'ready', 'tables': []},
'layout_schema_candidates': [candidate],
}],
'documents': [_frozen_generic_document(candidate)],
}],
},
)
@@ -609,11 +728,7 @@ def test_template_parse_failure_falls_back_to_generic(monkeypatch):
'order_document_profiles': [{'schema_version_id': 1}],
'intakes': [{
'intake_no': 'SNI-001',
'documents': [{
'document_id': 55,
'layout_snapshot': {'status': 'ready', 'tables': []},
'layout_schema_candidates': [candidate],
}],
'documents': [_frozen_generic_document(candidate)],
}],
},
)
@@ -0,0 +1,95 @@
"""
tests/test_shipping_generic_parse_plan.py
用途:验证自动标注候选必须先冻结为 Parse Plan,且 Plan 不能跨 Schema/Layout/候选复用。
依赖:generic_parse_plan、generic_order_gate。
逻辑:覆盖生产通用解析的身份门禁;任一输入漂移均 fail-closed 到 Review。
"""
from types import SimpleNamespace
from app.services.shipping_notice.generic_order_gate import evaluate_generic_extraction_gate
from app.services.shipping_notice.generic_parse_plan import (
compile_generic_parse_plan,
validate_generic_parse_plan,
)
def _candidate() -> dict:
return {
'page_no': 1, 'table_id': 'table-1', 'mapping_status': 'candidate',
'columns': [{'column_index': 0, 'field_id': 'part', 'field_code': 'part_number', 'status': 'mapped'}],
'rows': [{'row_index': 1, 'role': 'data', 'fields': [{
'field_id': 'part', 'field_code': 'part_number', 'value': 'ABC',
'cell_id': 'cell-1', 'evidence_ref': 'layout:1:cell-1',
}]}],
'row_role_summary': {'data': 1}, 'unmapped_nonempty_column_indices': [],
}
def _definition() -> dict:
return {'fields': [{
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True,
'required': True, 'value_type': 'string', 'aliases': ['Part'],
}]}
def _evaluate(*, plan, candidates, layout):
return evaluate_generic_extraction_gate(
candidates=candidates, parse_plan=plan, require_parse_plan=True, layout_snapshot=layout,
definition=_definition(), schema={'schema_version_id': 1, 'checksum': 'a' * 64},
intake={'intake_no': 'SNI-1'}, unit=SimpleNamespace(document_id=1),
)
def test_frozen_parse_plan_allows_clean_generic_deterministic_candidate():
"""自动标注经 Plan 冻结、证据绑定和 Gate 后才可进入确定性解析。"""
candidate = _candidate()
layout = {'layout_candidate': {'pages': [{'page_no': 1}]}}
plan = compile_generic_parse_plan(candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout)
result = _evaluate(plan=plan, candidates=[candidate], layout=layout)
assert result.passed is True
def test_missing_parse_plan_blocks_production_generic_route():
"""候选本身再完整,未冻结 Plan 也不得作为生产事实。"""
result = _evaluate(plan=None, candidates=[_candidate()], layout={'layout_candidate': {}})
assert result.passed is False
assert 'generic_parse_plan_missing' in result.gate_reason_codes
def test_parse_plan_blocks_runtime_candidate_drift():
"""冻结后运行时候选变化均不得以旧 Plan 自动建单。"""
candidate = _candidate()
layout = {'layout_candidate': {'pages': [{'page_no': 1}]}}
plan = compile_generic_parse_plan(candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout)
changed_candidate = _candidate()
changed_candidate['rows'][0]['fields'][0]['value'] = 'CHANGED'
result = _evaluate(plan=plan, candidates=[changed_candidate], layout=layout)
assert result.passed is False
assert 'generic_parse_plan_runtime_candidate_changed' in result.gate_reason_codes
def test_parse_plan_blocks_schema_or_layout_drift():
"""冻结 Plan 不能跨 Schema 或 Layout 复用,防止自动标注结果污染其他文档。"""
candidate = _candidate()
layout = {'layout_candidate': {'pages': [{'page_no': 1}]}}
plan = compile_generic_parse_plan(candidates=[candidate], schema_checksum='a' * 64, layout_snapshot=layout)
schema_changed = validate_generic_parse_plan(
plan=plan, schema_checksum='b' * 64, layout_snapshot=layout, runtime_candidates=[candidate],
)
layout_changed = validate_generic_parse_plan(
plan=plan, schema_checksum='a' * 64,
layout_snapshot={'layout_candidate': {'pages': [{'page_no': 2}]}}, runtime_candidates=[candidate],
)
assert schema_changed.passed is False
assert 'generic_parse_plan_schema_changed' in schema_changed.reason_codes
assert layout_changed.passed is False
assert 'generic_parse_plan_layout_changed' in layout_changed.reason_codes
@@ -1,25 +1,23 @@
"""
backend/tests/test_shipping_notice_business_case.py
用途:验证货代业务单聚合在普通建单、修订和强制新建场景下的归属规则。
依赖:app fixture、ShippingNotice/ShippingCase、business_case_service。
逻辑:直接调用领域服务并断言业务单关系,不触发解析和库存副作用。
用途:验证 Notice 建单和替代关系不依赖 ShippingCase。
依赖:app fixture、ShippingNotice、task_workflow。
逻辑:直接调用领域服务并断言 Notice 独立事实,不触发解析和库存副作用。
"""
from app import db
import pytest
from app import db
from app.core.errors import ConflictError
from app.models import ShippingCase, ShippingCustomer, ShippingNotice
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
from app.services.shipping_notice.task_workflow import create_batch_tasks, create_task
from app.models import ShippingCustomer, ShippingNotice
from app.services.shipping_notice.task_workflow import create_task
def _task(task_no: str, *, case_id: int | None = None, supersedes_task_id: int | None = None) -> ShippingNotice:
"""构造最小货代任务,供业务单关系断言使用。"""
def _task(task_no: str, *, supersedes_task_id: int | None = None) -> ShippingNotice:
"""构造最小 Notice,供替代关系断言使用。"""
return ShippingNotice(
task_no=task_no,
shipping_case_id=case_id,
supersedes_task_id=supersedes_task_id,
source_type='manual',
)
@@ -33,76 +31,32 @@ def _active_customer(*, short_code: str = 'CASE') -> ShippingCustomer:
return customer
def test_normal_and_force_create_use_different_cases(app):
"""普通建单和强制新建必须各自创建独立业务单。"""
def test_notices_are_independent_without_business_case(app):
"""不同 Notice 无需中间聚合实体,业务事实由自身保存。"""
with app.app_context():
normal = resolve_shipping_case_for_new_task(created_by_id=None)
forced = resolve_shipping_case_for_new_task(
duplicate_resolution_type='force_create',
created_by_id=None,
)
assert normal.id != forced.id
assert normal.business_no is None
assert forced.business_no is None
first = _task('SN-NOTICE-INDEPENDENT-1')
second = _task('SN-NOTICE-INDEPENDENT-2')
db.session.add_all([first, second])
db.session.commit()
assert first.id != second.id
assert first.business_no is None
assert second.business_no is None
def test_revision_inherits_existing_parent_case(app):
"""修订任务必须继承父任务已有业务单,不能创建新业务单。"""
def test_replacement_links_to_parent_notice(app):
"""替代 Notice 仅链接原 Notice,不继承或依赖 Case。"""
with app.app_context():
case = resolve_shipping_case_for_new_task(created_by_id=None)
parent = _task('SN-CASE-PARENT-1', case_id=case.id)
parent = _task('SN-NOTICE-PARENT-1')
db.session.add(parent)
db.session.flush()
resolved = resolve_shipping_case_for_new_task(
supersedes_task_id=parent.id,
duplicate_resolution_type='revision',
)
assert resolved.id == case.id
assert ShippingCase.query.count() == 1
replacement = _task('SN-NOTICE-REPLACEMENT-1', supersedes_task_id=parent.id)
db.session.add(replacement)
db.session.commit()
assert replacement.supersedes_task_id == parent.id
def test_revision_rejects_parent_without_business_case(app):
"""修订父任务缺少业务单时必须阻断,禁止隐式补建。"""
with app.app_context():
parent = _task('SN-CASE-LEGACY-1')
db.session.add(parent)
db.session.flush()
with pytest.raises(ConflictError) as exc_info:
resolve_shipping_case_for_new_task(
supersedes_task_id=parent.id,
duplicate_resolution_type='revision',
)
assert exc_info.value.code == 'SHIPPING_NOTICE.REVISION_CASE_MISSING'
assert ShippingCase.query.count() == 0
def test_revision_chain_reuses_root_case(app):
"""连续修订版本必须沿用同一业务单聚合。"""
with app.app_context():
case = resolve_shipping_case_for_new_task(created_by_id=None)
parent = _task('SN-CASE-CHAIN-1', case_id=case.id)
db.session.add(parent)
db.session.flush()
revision_case = resolve_shipping_case_for_new_task(
supersedes_task_id=parent.id,
duplicate_resolution_type='revision',
)
revision = _task('SN-CASE-CHAIN-2', case_id=revision_case.id, supersedes_task_id=parent.id)
db.session.add(revision)
db.session.flush()
next_case = resolve_shipping_case_for_new_task(
supersedes_task_id=revision.id,
duplicate_resolution_type='revision',
)
assert next_case.id == case.id
assert ShippingCase.query.count() == 1
def test_create_task_assigns_case_and_serializes_it(app):
"""真实单票建单路径必须创建业务单并在 Tool 投影中返回关联信息。"""
def test_create_task_assigns_notice_customer_and_serializes_it(app):
"""真实单票建单路径直接写 Notice 客户事实,不创建 ShippingCase。"""
with app.app_context():
customer = _active_customer(short_code='CRT')
result = create_task({
@@ -111,11 +65,9 @@ def test_create_task_assigns_case_and_serializes_it(app):
'customer_id': customer.id,
})
task = ShippingNotice.query.filter_by(task_no=result['task_id']).one()
assert task.shipping_case_id is not None
assert task.customer_resolution_status == 'confirmed'
assert result['data']['shipping_case_id'] == task.shipping_case_id
assert result['data']['case_no'] == task.shipping_case.case_no
assert task.shipping_case.customer_id == customer.id
assert task.customer_id == customer.id
assert result['data']['customer_id'] == customer.id
def test_create_task_rejects_without_customer(app):
@@ -126,59 +78,3 @@ def test_create_task_rejects_without_customer(app):
assert exc_info.value.code == 'SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK'
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_batch_revision_inherits_parent_case(app):
"""真实批量建单路径中的 revision 必须继承父任务业务单。"""
with app.app_context():
customer = _active_customer(short_code='REV')
case = resolve_shipping_case_for_new_task(created_by_id=None)
case.customer_id = customer.id
case.customer_name_snapshot = customer.standard_name
case.customer_short_code_snapshot = customer.short_code
parent = _task('SN-CASE-BATCH-PARENT', case_id=case.id)
parent.customer_resolution_status = 'confirmed'
db.session.add(parent)
db.session.commit()
result = create_batch_tasks({
'notice_items': [{
'source_type': 'manual',
'raw_text': 'revision notice',
'document_version': 2,
'supersedes_task_id': parent.id,
'duplicate_resolution_type': 'revision',
}],
'defer_parse': True,
})
task = ShippingNotice.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one()
assert task.shipping_case_id == case.id
assert task.supersedes_task_id == parent.id
assert task.customer_resolution_status == 'confirmed'
assert ShippingCase.query.count() == 1
@pytest.mark.skip(reason='legacy shipping_batches dropped in co8e9f0a1b2c')
def test_batch_force_create_uses_new_case(app):
"""真实批量建单路径中的 force_create 必须创建独立业务单。"""
with app.app_context():
customer = _active_customer(short_code='FRC')
original_case = resolve_shipping_case_for_new_task(created_by_id=None)
original = _task('SN-CASE-FORCE-SOURCE', case_id=original_case.id)
db.session.add(original)
db.session.commit()
result = create_batch_tasks({
'notice_items': [{
'source_type': 'manual',
'raw_text': 'forced notice',
'duplicate_source_task_id': original.id,
'duplicate_resolution_type': 'force_create',
'customer_id': customer.id,
}],
'defer_parse': True,
})
task = ShippingNotice.query.filter_by(task_no=result['data']['tasks'][0]['task_id']).one()
assert task.shipping_case_id != original_case.id
assert task.duplicate_source_task_id == original.id
assert task.customer_resolution_status == 'confirmed'
assert ShippingCase.query.count() == 2
@@ -101,6 +101,62 @@ def test_intake_status_exposes_layout_lifecycle_without_blocking_terminal_fallba
assert completed['layout_status'] == 'completed'
assert completed['layout_summary']['failed'] == 1
def test_active_intake_list_omits_heavy_candidate_review_details(app, shipping_user):
"""活跃列表保留恢复所需字段,但不得传输审核证据与裁决历史。"""
from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation
with app.app_context():
asset, intake = _seed_parsed_intake(
shipping_user.id,
intake_no='SNI-LIGHT-LIST-001',
hash_value='light-list-hash',
)
intake.conversation_id = 'conversation-light-list'
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
attachment_key='order.pdf',
filename='order.pdf',
content_hash='light-list-document-hash',
classification='order_notice',
parse_status='parsed',
)
db.session.add(document)
db.session.flush()
db.session.add(ShippingOrderCandidate(
candidate_no='SNC-LIGHT-LIST-001',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='light-list-candidate',
structured_result_json={
'business_summary': {'po_number': 'PO-LIGHT-001'},
'extraction': {
'field_adjudication': {'observation_history': ['large-history']},
'customer_matches': [{'customer': 'large-match'}],
},
},
evidence_json=[{'text': 'large-evidence'}],
selected=True,
validation_status='ready',
))
db.session.commit()
rows = list_active_intakes_for_conversation(
user_id=shipping_user.id,
conversation_id='conversation-light-list',
)
assert len(rows) == 1
candidate = rows[0]['candidates'][0]
assert candidate['candidate_no'] == 'SNC-LIGHT-LIST-001'
assert candidate['po_number'] == 'PO-LIGHT-001'
assert candidate['selected'] is True
assert 'evidence' not in candidate
assert 'field_adjudication' not in candidate
assert 'customer_matches' not in candidate
def test_candidate_review_duplicate_api_and_access_guards(app, client):
"""Candidate API 应支持修订、刷新和决策,并阻止越权或已消费候选修改。"""
from app.core.auth.jwt import issue_local_access_token
@@ -13,7 +13,7 @@ import pytest
from app import db
from app.models import (
ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink,
ShippingOrderCustomerMatch,
@@ -101,7 +101,7 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
"""为直接构造的 RPA 回调任务补齐已确认客户。
核心逻辑:测试不经建单工作流时,显式创建 business case 与激活客户,
核心逻辑:测试不经建单工作流时,显式绑定激活客户,
使回调测试只验证 RPA 契约,而不绕过客户身份门禁。
"""
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
@@ -111,47 +111,17 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
)
db.session.add(customer)
db.session.flush()
case = ShippingCase(
case_no=f'CASE-{task.task_no}', customer=customer,
customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code,
)
task.shipping_case = case
task.customer = customer
task.customer_name_snapshot = customer.standard_name
task.customer_short_code_snapshot = customer.short_code
task.customer_resolution_status = 'confirmed'
task.customer_resolution_method = 'test_fixture'
db.session.add_all([case, task])
db.session.add(task)
db.session.flush()
# 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。
task._test_customer_confirmed = True
@pytest.fixture(autouse=True)
def _confirmed_customer_for_rpa_flows(app, monkeypatch):
"""为本模块新建的业务单绑定测试客户,使用例聚焦客户门禁之后的 RPA 行为。"""
from app.services.shipping_notice import task_workflow
original = task_workflow.resolve_shipping_case_for_new_task
def _resolve_confirmed_case(**kwargs):
case = original(**kwargs)
if case.customer_id is not None:
return case
customer = db.session.query(ShippingCustomer).filter_by(short_code="RPA").one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name="RPA 流程测试客户",
short_code="RPA",
status="active",
)
db.session.add(customer)
db.session.flush()
case.customer_id = customer.id
case.customer_name_snapshot = customer.standard_name
case.customer_short_code_snapshot = customer.short_code
return case
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
@pytest.fixture(autouse=True)
def _freeze_test_rpa_batch_callback_contract(monkeypatch):
"""兼容旧测试调用:仅在测试边界补齐 v2 envelope,不改变生产回调校验。"""
@@ -41,7 +41,10 @@ from app.models import (
)
from app.services.chat.log_service import merge_chat_log_payload
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
from app.services.shipping_notice.order_extraction import persist_order_extraction_result
from app.services.shipping_notice.order_extraction import (
_discard_resolved_worker_field_conflicts,
persist_order_extraction_result,
)
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
from app.services.shipping_notice.open_existing_reservation_backfill import (
backfill_exact_file_open_existing_reservations,
@@ -84,6 +87,9 @@ def _ensure_order_schema() -> dict[str, str]:
configs.append({
'field_id': field['id'], 'display_name': code, 'required': required, 'aliases': [],
'business_purpose': business_purposes.get(code, 'general'),
# Reservation 是自动建单的流程匹配键;证据不足必须阻断 STP,不能仅作为诊断。
'auto_create_key_field': code == 'reservation_id',
'minimum_confidence': 0.85 if code == 'reservation_id' else None,
'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_text', 'backend_table', 'dify_llm'],
@@ -115,6 +121,111 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it()
assert assessment['missing_process_fields'] == ['reservation_id']
def test_candidate_discards_early_optional_line_evidence_conflict_after_derivation(app):
"""派生补齐可选 line_no 后,Candidate 不得保留 Worker 的早期 PDF 证据阻断。"""
with app.app_context():
order_schema_service.initialize_schema({'display_name': '派生字段测试'}, actor_id=None)
customer_line = order_schema_service.save_field(
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
line_no = order_schema_service.save_field(
{'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
part = order_schema_service.save_field(
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
qty = order_schema_service.save_field(
{'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None,
)
draft = order_schema_service.create_draft({}, actor_id=None)
def config(field: dict, *, required: bool, normalizer: str, validators: list[str], comparator: str) -> dict:
return {
'field_id': field['id'], 'display_name': field['field_code'], 'required': required,
'auto_create_key_field': False, 'aliases': [], 'business_purpose': 'general',
'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_text'],
'conflict_policy': 'block', 'allow_single_source': True,
},
'relation_role': None, 'comparator_key': comparator,
}
saved = order_schema_service.save_draft(draft['id'], {
'fields': [
config(customer_line, required=False, normalizer='trim', validators=[], comparator='normalized_text'),
config(line_no, required=False, normalizer='trim', validators=[], comparator='normalized_text'),
config(part, required=True, normalizer='uppercase_trim', validators=['non_empty'], comparator='normalized_text'),
config(qty, required=True, normalizer='decimal', validators=['positive_decimal'], comparator='decimal'),
],
'derivation_rules': [{
'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO', 'enabled': True,
'source_field_code': 'customer_po_line_no', 'target_field_code': 'line_no',
'strategy': 'copy_if_empty', 'scope': 'line',
}],
'expected_lock_version': draft['lock_version'],
})
published = order_schema_service.publish(
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
)
_user, _session, intake, document, _runtime_context = _seed_extraction_input()
document.extracted_text = 'Customer PO Line 00010 SKU SKU-A QTY 10'
db.session.commit()
result = _persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [{
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
'source_intake_no': intake.intake_no, 'primary_document_id': document.id,
'classification': 'shipping_request', 'classification_confidence': 0.99,
'header_fields': [],
'lines': [{'fields': [
{'field_id': customer_line['id'], 'observations': [{
'value': '00010', 'document_id': document.id, 'quote': 'Customer PO Line 00010', 'confidence': 0.99,
}]},
{'field_id': part['id'], 'observations': [{
'value': 'SKU-A', 'document_id': document.id, 'quote': 'SKU SKU-A', 'confidence': 0.99,
}]},
{'field_id': qty['id'], 'observations': [{
'value': 10, 'document_id': document.id, 'quote': 'QTY 10', 'confidence': 0.99,
}]},
]}],
'conflicts': [{
'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing',
'owning_gate_code': 'field_completeness',
}],
}]})
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
decisions = candidate.structured_result_json['extraction']['field_adjudication']['decisions']
assert any(
item.get('field_code') == 'line_no' and item.get('reason_code') == 'derived'
for item in decisions
)
assert not any(
item.get('field') == 'line_no' and item.get('reason') == 'evidence_missing'
for item in candidate.conflicts_json
)
assert 'blocking_conflict' not in result['pending_orders'][0]['reasons']
def test_candidate_keeps_early_field_conflict_when_final_schema_still_blocks_field():
"""最终 Schema 仍阻断的必填/关键字段,不得被已接受的旧 Decision 静默放行。"""
conflicts = _discard_resolved_worker_field_conflicts(
[{
'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing',
'owning_gate_code': 'field_completeness',
}],
decisions=[{
'field_code': 'line_no', 'status': 'derived', 'reason_code': 'derived',
}],
blocked_fields=['line_no'],
)
assert conflicts == [{
'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing',
'owning_gate_code': 'field_completeness',
}]
def test_candidate_validation_projects_customer_po_number_to_legacy_candidate_field():
"""当前动态 Schema 的客户 PO 必须投影到 Candidate 兼容字段,供履约链路读取。"""
assessment = assess_candidate_business_summary({
@@ -837,7 +948,7 @@ def test_persist_order_extraction_result_keeps_provider_orders_provisional_and_r
assert result['pending_count'] == 2
assert result['non_shipping_count'] == 0
assert result['created_with_missing_fields_count'] == 0
assert result['batch_no'] is None
assert 'batch_no' not in result
candidates = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).all()
assert len(candidates) == 2
assert len({item.candidate_key for item in candidates}) == 2
@@ -1032,10 +1143,6 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate',
lambda **_kwargs: dict(duplicate_result),
)
monkeypatch.setattr(
'app.services.shipping_notice.batch_from_intakes.detect_duplicates_for_candidate',
lambda **_kwargs: dict(duplicate_result),
)
context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context})
result = _persist_test_orders({
@@ -1133,8 +1240,8 @@ def test_persist_order_extraction_result_unassigned_pending_keeps_documents_part
assert document.order_extraction_status == 'partially_completed'
def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_review(app):
"""同文件最新 Candidate 按 PO/SKU/qty 唯一命中时,只补旧任务空 Reservation 并保留人工复核。"""
def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app):
"""同文件唯一命中补齐 Reservation 后,既有任务进入解析复核而非继续停在缺字段态。"""
with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input()
existing = ShippingNotice(
@@ -1195,7 +1302,8 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
assert values['part_number'] == 'P123456'
assert values['qty'] == 24
assert values['reservation_id'] == '1000140351'
assert existing.review_status == 'rsv_req'
# Reservation 已补齐,状态机必须退出 rsv_req;仍保留解析复核,禁止自动确认或推进。
assert existing.review_status == 'parse_review'
assert existing.pending_human_reason == 'low_confidence'
assert 'process_field_gate' not in (existing.step_payload_json or {})
assert existing.error_message is None
@@ -1281,7 +1389,11 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
assert result['pending_count'] == 1
assert 'blocking_conflict' in result['pending_orders'][0]['reasons']
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert any(item['reason'] == 'cross_source_conflict' for item in candidate.conflicts_json)
# 当前裁决以受信表格/PDF 值为准;仍必须作为关键字段冲突阻断 STP。
assert any(
item['field'] == 'reservation_id' and item['reason'] == 'pdf_preferred'
for item in candidate.conflicts_json
)
adjudication = candidate.structured_result_json['extraction']['field_adjudication']
reservation_observations = [
item for item in adjudication['observations']
@@ -19,37 +19,11 @@ from app.services.shipping_notice.query_service import (
resolve_task_from_payload,
serialize_task,
task_export_error_message,
task_sort_key,
list_freight_notice_groups_for_task,
)
from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
def test_chat_match_result_payload_uses_unified_actions_only():
"""Chat 匹配结果不得再把旧 action_buttons 作为按钮来源。"""
from app.services.shipping_notice.chat_action_handlers import _match_result_payload
payload = _match_result_payload(
"SN-ACTIONS-ONLY",
{
"data": {
"match_status": "shortage",
"line_results": [],
"shortage": {"lines": []},
},
"action_buttons": [{"id": "legacy_retry"}],
"ui_state": {
"actions": {
"primary": {"code": "open_shortage_review", "enabled": True},
"secondary": [],
},
},
},
)
assert payload["actions"]["primary"]["code"] == "open_shortage_review"
assert "action_buttons" not in payload
def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
"""task_no 与数字主键均应能解析到同一任务。"""
with app.app_context():
@@ -327,6 +301,116 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
assert "can_handle" not in no_viewer
def test_serialize_task_summary_projects_only_current_notice_line_facts(app):
"""同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。"""
with app.app_context():
from app import db
from app.models import ShippingNoticeLine, ShippingNoticeLineInventoryMatch
from app.services.shipping_notice.query_service import serialize_task_summary
first = ShippingNotice(task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11)
second = ShippingNotice(task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11)
db.session.add_all([first, second]); db.session.flush()
db.session.add_all([
ShippingNoticeLine(
notice_id=first.id, position=1, line_key='LINE-1', part_number='PART-FIRST',
reservation_id='RES-1', required_qty='12', field_values_json={'line_no': '00010'},
),
ShippingNoticeLine(
notice_id=second.id, position=1, line_key='LINE-2', part_number='PART-SECOND',
reservation_id='RES-2', required_qty='8', field_values_json={'line_no': '00020'},
),
ShippingNoticeLineInventoryMatch(
task_id=first.id, line_key='LINE-1', match_result='matched', inventory_status='ready',
available_qty='20', shortage_qty='0', is_current=True,
),
ShippingNoticeLineInventoryMatch(
task_id=second.id, line_key='LINE-2', match_result='matched', inventory_status='ready',
available_qty='9', shortage_qty='0', is_current=True,
),
])
db.session.commit()
data = serialize_task_summary(first, viewer_user_id=11)
assert data['business_no'] == 'WVC26082301'
assert data['notice_line_summary'] == [{
'line_no': '00010', 'part_number': 'PART-FIRST', 'customer_part_number': None,
'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20',
'shortage_qty': '0', 'inventory_status': 'ready',
}]
def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app):
"""货代上传聚合必须按同 PO 的 business_no 拆组,并排除无业务号及他人 Notice。"""
with app.app_context():
from app import db
from app.models import ShippingNoticeLine
from app.services.shipping_notice import query_service
def with_po(task_no, business_no, user_id):
return ShippingNotice(task_no=task_no, business_no=business_no, source_type='manual', user_id=user_id)
first = with_po('SN-GROUP-1', 'WYC26082401', 11)
second = with_po('SN-GROUP-2', 'WYC26082402', 11)
no_business = with_po('SN-GROUP-3', None, 11)
other = with_po('SN-GROUP-4', 'WYC26082499', 99)
db.session.add_all([first, second, no_business, other]); db.session.flush()
db.session.add_all([
ShippingNoticeLine(notice_id=first.id, position=1, line_key='G1', part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={'line_no': '00010'}),
ShippingNoticeLine(notice_id=second.id, position=1, line_key='G2', part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={'line_no': '00020'}),
])
db.session.commit()
original_header_reader = query_service.current_header_field_values_or_empty
# customer_po_number 是当前动态 Schema 的正式 PO 字段;聚合必须不依赖旧兼容投影。
query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-GROUP'}
try:
result = list_freight_notice_groups_for_task(first, user_id=11)
finally:
query_service.current_header_field_values_or_empty = original_header_reader
assert result['po_number'] == 'PO-GROUP'
assert [item['business_no'] for item in result['items']] == ['WYC26082401', 'WYC26082402']
# 单条菜单必须消费服务端授权投影,前端不得按上传状态自行猜测可执行动作。
assert 'available_actions' in result['items'][0]
assert result['items'][0]['lines'][0]['part_number'] == 'PART-A'
assert result['items'][1]['lines'][0]['part_number'] == 'PART-B'
def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app):
"""当前 Extraction 不可读时,货代上传聚合仍必须以冻结快照中的客户 PO 对齐同一发货批次。"""
with app.app_context():
from app import db
from app.models import ShippingOrderSnapshot
from app.services.shipping_notice import query_service
first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11)
second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11)
db.session.add_all([first, second]); db.session.flush()
for task in (first, second):
snapshot = ShippingOrderSnapshot(
task_id=task.id,
extraction_id=task.id,
schema_version_id=1,
order_data_version=1,
header_values_json={},
customer_po_number='ZNB-16754796',
)
db.session.add(snapshot); db.session.flush()
task.order_snapshot_id = snapshot.id
db.session.commit()
original_header_reader = query_service.current_header_field_values_or_empty
query_service.current_header_field_values_or_empty = lambda _task: {}
try:
result = list_freight_notice_groups_for_task(first, user_id=11)
finally:
query_service.current_header_field_values_or_empty = original_header_reader
assert result['po_number'] == '16754796'
assert [item['business_no'] for item in result['items']] == ['WYC26082411', 'WYC26082412']
def test_list_my_todos_and_count_buckets(app):
"""list_my_todos 按 bucket 分类;count 徽标与 pending 一致。"""
with app.app_context():
@@ -434,7 +518,7 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
assert hit['ui_state']['summary']['entry_surface'] == 'review_workbench'
assert hit['ui_state']['lifecycle_stage'] == 'order_review'
assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [
'available', 'current', 'unavailable', 'unavailable',
'available', 'current', 'unavailable', 'unavailable', 'unavailable',
]
counts = count_my_todos(user.id)
@@ -485,8 +569,8 @@ def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_stil
assert original.case_no not in review_case_nos
def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app):
"""历史空 Review Case 可以处置,但不能被待办页默认授权进入订单生命周期。"""
def test_open_review_case_without_current_candidate_enters_intake_parse(app):
"""无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。"""
with app.app_context():
from app import db
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
@@ -503,7 +587,8 @@ def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app):
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
hit = next(item for item in pending['items'] if item.get('review_case_no') == case.case_no)
assert hit['ui_state']['lifecycle_stage'] is None
assert hit['ui_state']['lifecycle_stage'] == 'intake_parse'
assert hit['ui_state']['intake_parse_authorized'] is True
assert hit['ui_state']['lifecycle_entries'] == []
@@ -708,7 +793,6 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
row = SimpleNamespace(
review_status=task.review_status,
pending_human_reason=task.pending_human_reason,
shipping_case_id=task.shipping_case_id,
customer_resolution_status=task.customer_resolution_status,
order_snapshot_id=task.order_snapshot_id,
current_order_extraction_id=task.current_order_extraction_id,
@@ -4,6 +4,25 @@ from app.services.shipping_notice.reservation_id import (
normalize_reservation_id,
validated_reservation_id,
)
from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
extract_reservation_from_region_text,
extract_reservation_from_vendor_comments_pages,
)
def _glyph_lines(*lines: str) -> list[dict]:
"""构造按视觉阅读顺序排列的最小页面文字证据。"""
glyphs = []
for row_index, line in enumerate(lines):
for column_index, char in enumerate(line):
glyphs.append({
'text': char,
'bbox': {'x0': column_index * 8, 'x1': column_index * 8 + 6, 'y0': row_index * 16, 'y1': row_index * 16 + 12},
'source_index': len(glyphs),
'boundary_before': 'space' if char == ' ' else 'none',
})
return glyphs
def test_match_numeric_reservation_id():
@@ -37,6 +56,91 @@ def test_reservation_contract_only_accepts_five_or_ten_digits():
assert not is_valid_reservation_id("12345678901", numeric_only=True)
def test_reservation_region_maps_line_when_reservation_label_and_line_number_are_present():
"""专用区域只在同一行有 Reservation 语义时提取,并将可靠行号交给正式解析链路。"""
assert extract_reservation_from_region_text("Reservation#3000098851 for line#1") == [{
'value': '3000098851', 'line_no': 1, 'scope': 'line',
'raw_text': 'Reservation#3000098851 for line#1', 'status': 'mapped',
}]
def test_reservation_region_assigns_reservation_without_line_to_header():
"""无行号 Reservation 是整单事实,写 Header 后由既有回退规则应用给全部明细。"""
assert extract_reservation_from_region_text("MDW hub order.Reservation#33008") == [{
'value': '33008', 'line_no': None, 'scope': 'header',
'raw_text': 'MDW hub order.Reservation#33008', 'status': 'header',
}]
def test_reservation_region_ignores_unrelated_numeric_noise():
"""备注区的普通客户号、数量等数字没有 Reservation 标签时不得被误写入订单。"""
assert extract_reservation_from_region_text("End Customer: D1\nQuantity: 1000143920") == []
def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading():
"""专区启用后跨页累计 Vendor Comments,首次 Terms 标题后的值必须被排除。"""
candidates, reason = extract_reservation_from_vendor_comments_pages([
(1, _glyph_lines('Vendor Comments:', 'Reservation#33008')),
(2, _glyph_lines('Reservation#3000098851 for line#1', 'Terms and Conditions:', 'Reservation#99999')),
])
assert reason is None
assert [item['value'] for item in candidates] == ['33008', '3000098851']
def test_vendor_comments_window_requires_start_and_end_headings():
"""缺少任一边界时不能把全文中的 Reservation 当作专区证据。"""
candidates, reason = extract_reservation_from_vendor_comments_pages([
(1, _glyph_lines('Reservation#33008')),
])
assert candidates == []
assert reason == 'vendor_comments_anchor_missing'
def test_reservation_region_applies_header_and_line_override_together():
"""整单值是默认值,指定行的 Reservation 仅覆盖对应明细。"""
applied = apply_reservation_region_candidates(
candidates=extract_reservation_from_region_text(
"MDW hub order.Reservation#33008\nReservation#3000098851 for line#1"
),
header_field_id='header-reservation',
line_field_id='line-reservation',
line_count=2,
)
assert applied.header_value == '33008'
assert applied.line_values == {1: '3000098851'}
assert applied.needs_review is False
def test_reservation_region_marks_only_conflicts_and_invalid_line_references_for_review():
"""重复同一值可去重;同一行冲突或越界才阻断自动建单。"""
applied = apply_reservation_region_candidates(
candidates=extract_reservation_from_region_text(
"Reservation#3000098851 for line#1\nReservation#3000098852 for line#1\n"
"Reservation#3000098853 for line#3"
),
header_field_id='header-reservation',
line_field_id='line-reservation',
line_count=2,
)
assert applied.needs_review is True
assert set(applied.review_reasons) == {'conflicting_line_value', 'line_out_of_range'}
def test_reservation_region_requires_review_when_numbered_value_has_no_line_target():
"""Schema 未启用行级字段时,不能静默丢弃带行号的覆盖值。"""
applied = apply_reservation_region_candidates(
candidates=extract_reservation_from_region_text("Reservation#3000098851 for line#1"),
header_field_id='header-reservation', line_field_id=None, line_count=1,
)
assert applied.needs_review is True
assert applied.review_reasons == ('line_field_unavailable',)
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
"""空订单或畸形行都不能被视为 Reservation 门禁通过。"""
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
@@ -79,7 +79,6 @@ def test_resolve_with_mocked_simple_namespace_attributes() -> None:
upload_status="uploaded",
review_status=None,
pending_human_reason=None,
shipping_case_id=None,
customer_resolution_status=None,
order_snapshot_id=None,
inventory_lines_json=None,
@@ -290,28 +290,6 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon
})
def test_export_ready_ui_state_entry_is_task_workbench(app) -> None:
"""场景:Excel 待人工上传登记待办深链入口为任务处理工作台。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-STP-ENTRY",
source_type="manual",
export_file_path="/tmp/x.xlsx",
export_file_name="x.xlsx",
)
state = build_task_ui_state(task)
assert state["checkpoint"]["kind"] == "wait_manual_upload"
assert state["summary"]["entry_surface"] == "task_workbench"
button_ids = [
item.get("code")
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
if item
]
assert "mark_manual_uploaded" in button_ids
assert "download_excel" in button_ids
assert "action_buttons" not in state
def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
"""场景:跨会话待办 + 权限 — 创建者 can_handle,管理员看他人任务只读。"""
with app.app_context():
+1 -102
View File
@@ -14,7 +14,7 @@ import pytest
from app import db
from app.models import (
ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule,
ShippingCase, ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice,
ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice,
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine,
@@ -107,34 +107,6 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
db.session.flush()
@pytest.fixture(autouse=True)
def _confirmed_customer_for_legacy_tool_flows(app, monkeypatch):
"""为本模块创建的业务单绑定测试客户,使既有用例继续聚焦客户 Gate 之后的流程。"""
from app.services.shipping_notice import task_workflow
original = task_workflow.resolve_shipping_case_for_new_task
def _resolve_confirmed_case(**kwargs):
case = original(**kwargs)
if case.customer_id is not None:
return case
customer = db.session.query(ShippingCustomer).filter_by(short_code="TST").one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name="Tool 流程测试客户",
short_code="TST",
status="active",
)
db.session.add(customer)
db.session.flush()
case.customer_id = customer.id
case.customer_name_snapshot = customer.standard_name
case.customer_short_code_snapshot = customer.short_code
return case
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client):
with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret"
@@ -703,79 +675,6 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
@pytest.mark.auto_rpa
def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client, tmp_path, monkeypatch):
from datetime import datetime, timedelta
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
trigger.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,
)
create_res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={"conversation_id": "conv-rpa-batch-retry"},
)
batch_no = create_res.get_json()["batch_no"]
task_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={
"batch_no": batch_no,
"conversation_id": "conv-rpa-batch-retry",
"source_type": "manual",
},
)
task_id = task_res.get_json()["task_id"]
with app.app_context():
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"connector_type": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_rpa_triggered",
detail_json={"attempt": 1},
created_at=datetime.utcnow() - timedelta(seconds=5),
)
)
db.session.commit()
with app.app_context():
result = retry_batch_pending_tasks(batch_no)
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert result["started"] == 1
assert result["skipped"] == 0
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert task.pending_human_reason == PH_RPA_EXHAUSTED
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_failed").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_exhausted").count() == 1
assert len(list(trigger.glob("inventory_export_*.json"))) == 0
def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client):
headers = _tool_headers(app)
+23 -28
View File
@@ -77,18 +77,18 @@ def test_unified_actions_preserve_backend_surface_without_action_code_fallback()
"primary_action": {
"code": "mark_manual_uploaded",
"label": "登记人工上传",
"target_surface": "upload_complete",
"target_surface": "freight_upload",
},
"action_presentation": [{
"code": "download_excel",
"label": "下载发货 Excel",
"target_surface": "upload_complete",
"target_surface": "freight_upload",
"target_anchor": "excel_artifact",
}],
},
)
assert state["primary"]["target_surface"] == "upload_complete"
assert state["secondary"][0]["target_surface"] == "upload_complete"
assert state["primary"]["target_surface"] == "freight_upload"
assert state["secondary"][0]["target_surface"] == "freight_upload"
assert state["secondary"][0]["target_anchor"] == "excel_artifact"
@@ -121,8 +121,8 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None:
assert "stage_context" in detailed_state
def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None:
"""没有 Gate 的旧 checkpoint 仅表达状态,不能再直接产生可写 UI 动作。"""
def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None:
"""旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STAGE-ACTIONS",
@@ -131,15 +131,15 @@ def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(ap
source_type="manual",
)
state = build_task_ui_state(task)
assert state["stage"]["code"] == "order_review"
assert state["stage"]["index"] == 2
assert state["stage"]["total"] == 4
assert state["stage"]["code"] == "unclassified"
assert state["stage"]["index"] == 0
assert state["stage"]["total"] == 5
assert state["actions"]["primary"] is None
assert state["actions"]["secondary"] == []
def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None:
"""正式工作台的四个入口必须由后端下发,页面不能按阶段顺序自行生成。"""
def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None:
"""正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-LIFECYCLE-ENTRIES",
@@ -148,13 +148,8 @@ def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> Non
source_type="manual",
)
state = build_task_ui_state(task)
assert state["lifecycle_stage"] == "order_review"
assert state["lifecycle_entries"] == [
{"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"},
{"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"},
{"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
{"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
]
assert state["lifecycle_stage"] == "unclassified"
assert state["lifecycle_entries"] == []
def test_task_ui_state_ignores_superseded_process_execution(app) -> None:
@@ -208,12 +203,12 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
assert state['stage']['code'] == 'fulfillment_prep'
assert state['current_step']['code'] == 'fulfillment_prep'
assert [entry['state'] for entry in state['lifecycle_entries']] == [
'available', 'available', 'current', 'unavailable',
'available', 'available', 'current', 'unavailable', 'unavailable',
]
def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None:
"""正式人工上传 Gate 必须裁决为通知完成,不受旧复核字段影响。"""
"""正式人工上传 Gate 必须停留货代上传,不受旧复核字段影响。"""
with app.app_context():
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
@@ -235,16 +230,16 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No
state = build_task_ui_state(task)
assert state['lifecycle_stage'] == 'upload_complete'
assert state['lifecycle_stage'] == 'freight_upload'
assert state['lifecycle_authority'] == 'process_gate'
assert state['stage']['code'] == 'upload_complete'
assert state['stage']['code'] == 'freight_upload'
assert [entry['state'] for entry in state['lifecycle_entries']] == [
'available', 'available', 'available', 'current',
'available', 'available', 'available', 'current', 'unavailable',
]
def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None:
"""库存匹配/上传结果只映射四个业务阶段。"""
def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> None:
"""库存和上传历史字段不能再替代正式 Gate 生成生命周期。"""
with app.app_context():
fulfillment = ShippingNotice(
task_no="SN-UI-FULFILLMENT",
@@ -257,11 +252,11 @@ def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(
source_type="manual",
upload_status="uploaded",
)
assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep"
assert build_task_ui_state(fulfillment)["stage"]["code"] == "unclassified"
upload_state = build_task_ui_state(upload, include_stage_context=True)
assert upload_state["stage"]["code"] == "upload_complete"
assert upload_state["stage"]["code"] == "unclassified"
# 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。
assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual"
assert upload_state["stage_context"]["upload"]["outcome"] == "not_started"
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
@@ -1,55 +0,0 @@
"""
tests/test_shipping_order_auto_freeze_execution.py
用途:锁定自动冻结候选范围不得扩大到 Run 内其它已消费任务。
依赖:order_auto_freeze_execution._freeze_created_tasks。
逻辑:未传入本轮 eligible candidate_nos 时不得扫描全 Run consumed 集合。
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
from app.services.shipping_notice.order_auto_freeze_execution import _freeze_created_tasks
def test_freeze_created_tasks_requires_eligible_candidate_nos():
"""空 eligible 集合必须直接返回,禁止扩大冻结范围。"""
run = SimpleNamespace(id=1)
with patch(
'app.services.shipping_notice.order_auto_freeze_execution.ShippingOrderCandidate'
) as candidate_model:
frozen, blocked = _freeze_created_tasks(run=run, policy={'enabled': True}, candidate_nos=[])
assert frozen == []
assert blocked == []
candidate_model.query.filter_by.assert_not_called()
def test_freeze_created_tasks_filters_accepted_selected_and_eligible_nos():
"""冻结查询必须约束 accepted + selected 且限定本轮 candidate_nos。"""
run = SimpleNamespace(id=42)
query = MagicMock()
query.filter_by.return_value = query
query.filter.return_value = query
query.order_by.return_value = query
query.all.return_value = []
with patch(
'app.services.shipping_notice.order_auto_freeze_execution.ShippingOrderCandidate'
) as candidate_model:
candidate_model.query = query
frozen, blocked = _freeze_created_tasks(
run=run,
policy={'enabled': True},
candidate_nos=['CAND-A', 'CAND-B'],
)
assert frozen == []
assert blocked == []
query.filter_by.assert_called_once_with(
order_extraction_run_id=42,
is_current_version=True,
candidate_status='accepted',
selected=True,
)
assert query.filter.call_count == 2
@@ -122,6 +122,85 @@ def _coordinate_definition() -> dict:
}
def test_reservation_region_requires_header_and_allows_optional_line_scope_schema():
"""无行号值必须有 Header 落点;启用 Line 后同一区域还可承载行级 Reservation。"""
schema = SimpleNamespace(definition_json={'fields': [{
'field_id': 'reservation-header', 'field_code': 'reservation_id', 'scope': 'header',
'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'],
}, {
'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'],
}, {
'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line',
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
}, {
'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line',
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
}]})
definition = _coordinate_definition()
definition['reservation_id_region'] = {
'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .3},
'page_scope': 'exact_page', 'page_no': 1,
}
normalized = service._normalize_definition(definition, schema_version=schema)
assert normalized['reservation_id_region']['page_no'] == 1
def test_reference_page_frames_are_preserved_by_coordinate_definition_normalization():
"""模板规范化必须保留标注页物理尺寸,不能只保存浏览器百分比坐标。"""
schema = SimpleNamespace(definition_json={'fields': [
{
'field_id': 'line-field', 'field_code': 'customer_po_line_no', 'scope': 'line',
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
},
{
'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line',
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
},
]})
definition = _coordinate_definition()
definition['reference_page_frames'] = {
'1': {'width': 609, 'height': 791, 'origin': 'pdf_top_left', 'box': 'cropbox'},
}
normalized = service._normalize_definition(definition, schema_version=schema)
assert normalized['reference_page_frames']['1']['width'] == 609.0
assert normalized['reference_page_frames']['1']['height'] == 791.0
assert normalized['coordinate_model']['type'] == 'legacy'
def test_reference_page_frames_read_annotation_coordinate_evidence():
"""参考页框必须来自冻结 Layout 的 PDF 坐标证据,而不是前端提交。"""
frames = service._reference_page_frames({
'coordinate_evidence': {'pages': {'1': {'width': 609, 'height': 791}}},
})
assert frames == {
'1': {'width': 609.0, 'height': 791.0, 'origin': 'pdf_top_left', 'box': 'cropbox'},
}
def test_reservation_region_rejects_schema_without_header_scope():
"""无行号 Reservation 需要稳定 Header 落点,只有 Line 字段时不得保存。"""
schema = SimpleNamespace(definition_json={'fields': [{
'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
'enabled': True, 'normalizer_key': 'reservation_id', 'allowed_sources': ['pdf_coordinate'],
}]})
definition = _coordinate_definition()
definition['reservation_id_region'] = {
'region': {'x0': .1, 'y0': .2, 'x1': .9, 'y1': .3},
'page_scope': 'exact_page', 'page_no': 1,
}
with pytest.raises(Exception) as caught:
service._normalize_definition(definition, schema_version=schema)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID'
def test_visual_sample_preview_reads_common_ocr_value_before_xfa_path_is_selected(app, monkeypatch):
"""XFA 草稿未选 datasets path 时,仍从共同 PDF 坐标证据显示 PO 样本值。"""
glyphs = [
@@ -365,6 +444,45 @@ def test_preview_page_region_text_uses_unique_xfa_widget_when_coordinate_text_is
assert result['status'] == 'needs_review'
def test_preview_page_region_text_does_not_use_partial_xfa_widget_value(app, monkeypatch):
"""局部框与大 Widget 仅相交时,不能把整段 /V 当作框内视觉样本。"""
document = SimpleNamespace(id=112, asset_id=501, filename='hybrid.pdf')
layout = {
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': []},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
}
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout)
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None, raising=False)
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [
SimpleNamespace(
page_no=1,
normalized_bbox={'x0': .40, 'y0': .10, 'x1': .80, 'y1': .60},
value='TEMP-S000218922 FRAME MPN:D4-A08AR12000001 Customer',
),
], raising=False)
monkeypatch.setattr(service, '_read_rendered_preview_crop_text', lambda _image: 'D4-A08AR12000001', raising=False)
with app.app_context():
result = service.read_preview_page_region_text(
1,
data={
'document_id': 112,
'region': {'x0': .50, 'y0': .30, 'x1': .70, 'y1': .40},
'rendered_image_base64': 'data:image/png;base64,iVBORw0KGgo=',
},
page_no=1,
actor_id=1,
)
assert result['text'] == 'D4-A08AR12000001'
assert result['source'] == 'xfa_rendered_ocr'
def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch):
"""任意视觉框命中多个带值 Widget 时不得将其中之一冒充样本值。"""
document = SimpleNamespace(id=110, asset_id=501, filename='hybrid.pdf')
@@ -392,6 +510,39 @@ def test_preview_page_region_text_rejects_ambiguous_xfa_widgets(app, monkeypatch
assert result['source'] == 'acroform_widget_ambiguous'
def test_preview_page_region_text_reads_xfa_canvas_crop_when_server_rendering_has_no_value(app, monkeypatch):
"""XFA 可见值必须从管理员当前 PDF.js 画布裁剪图回读,不能以服务端 PDFium 空结果丢弃标注。"""
document = SimpleNamespace(id=111, asset_id=501, filename='hybrid.pdf')
layout = {
'coordinate_evidence': {
'pages': {'1': {'width': 200, 'height': 100}},
'page_glyphs': {'1': []},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
}
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout)
monkeypatch.setattr(service, '_read_page_ocr_coordinate_evidence', lambda **_kwargs: None)
monkeypatch.setattr(service, '_read_acroform_widgets_for_preview', lambda **_kwargs: [])
monkeypatch.setattr(service, '_read_rendered_preview_crop_text', lambda _image: 'HC07', raising=False)
with app.app_context():
result = service.read_preview_page_region_text(
1,
data={
'document_id': 111,
'region': {'x0': .40, 'y0': .15, 'x1': .75, 'y1': .35},
'rendered_image_base64': 'data:image/png;base64,iVBORw0KGgo=',
},
page_no=1,
actor_id=1,
)
assert result['text'] == 'HC07'
assert result['source'] == 'xfa_rendered_ocr'
def test_visual_sample_preview_discards_duplicate_unbound_layout_for_bound_field(app, monkeypatch):
"""共同视觉预览忽略旧浏览器重复提交的已绑定未绑定布局,仍返回 PO 样本值。"""
glyphs = [
@@ -626,10 +777,16 @@ def test_template_sample_status_accepts_materialized_document_with_failed_layout
status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id)
# 上传成功只取决于样本文档已物化;失败 Layout 留到预览复核阶段按需恢复或报错。
assert status == {
'intake_no': 'SNI-LAYOUT-STATUS', 'parse_status': 'parsed', 'document_count': 1,
'document_ids': [document.id], 'error_code': None,
}
assert status['intake_no'] == 'SNI-LAYOUT-STATUS'
assert status['parse_status'] == 'parsed'
assert status['document_count'] == 1
assert status['document_ids'] == [document.id]
assert status['error_code'] is None
# 文档物化成功与 Layout 失败分开呈现,前端不可把上传成功误当成可自动标注。
assert status['layout_status'] == 'failed'
assert status['evidence_status'] == 'pending'
assert status['automark_ready'] is False
assert status['sample_readiness'] == []
def test_template_sample_status_accepts_materialized_document_without_modeling_table(app):
@@ -663,10 +820,15 @@ def test_template_sample_status_accepts_materialized_document_without_modeling_t
status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id)
# Layout 预热结果不是上传门禁,不能把可读 PDF 误报为上传失败。
assert status == {
'intake_no': 'SNI-EMPTY-TABLE-STATUS', 'parse_status': 'parsed', 'document_count': 1,
'document_ids': [document.id], 'error_code': None,
}
assert status['intake_no'] == 'SNI-EMPTY-TABLE-STATUS'
assert status['parse_status'] == 'parsed'
assert status['document_count'] == 1
assert status['document_ids'] == [document.id]
assert status['error_code'] is None
assert status['layout_status'] == 'ready'
assert status['evidence_status'] == 'pending'
assert status['automark_ready'] is False
assert status['sample_readiness'] == []
def test_template_sample_status_keeps_file_materialization_failure_fail_closed(app):
@@ -691,10 +853,91 @@ def test_template_sample_status_keeps_file_materialization_failure_fail_closed(a
status = service.get_sample_intake_status(intake.intake_no, actor_id=user.id)
# 文件本身未能物化时必须保持失败,不能借上传/Layout 解耦绕过。
assert status == {
'intake_no': 'SNI-MATERIALIZATION-FAILED', 'parse_status': 'failed', 'document_count': 0,
'document_ids': [], 'error_code': 'SHIPPING_NOTICE_INTAKE_PARSE_FAILED',
}
assert status['intake_no'] == 'SNI-MATERIALIZATION-FAILED'
assert status['parse_status'] == 'failed'
assert status['document_count'] == 0
assert status['document_ids'] == []
assert status['error_code'] == 'SHIPPING_NOTICE_INTAKE_PARSE_FAILED'
assert status['layout_status'] == 'pending'
assert status['evidence_status'] == 'pending'
assert status['automark_ready'] is False
assert status['sample_readiness'] == []
def test_refresh_profile_sample_readiness_freezes_ready_annotation_evidence(app):
"""ready Layout 与唯一主表齐备时,统一服务必须回填样本的完整冻结身份。"""
with app.app_context():
schema = _schema_version()
draft = service.save_draft(_data(schema.id), actor_id=None)
sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation')
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
state = service.refresh_profile_sample_readiness(profile=profile, sample=sample)
db.session.commit()
frozen = db.session.get(ShippingOrderDocumentProfileSample, sample.id)
# 同一服务既供轮询使用也供入队使用,冻结后的 Job 必须取得当前 Layout 的完整身份。
assert state['automark_ready'] is True
assert state['evidence_status'] == 'frozen'
assert frozen.layout_version_id is not None
assert frozen.layout_payload_checksum is not None
assert frozen.source_content_hash == 's' * 64
assert frozen.evidence_frozen_at is not None
def test_profile_sample_readiness_rejects_current_layout_content_identity_mismatch(app):
"""当前 Layout 的来源内容身份异常时不得冻结或入队,避免旧坐标混入新样本。"""
with app.app_context():
schema = _schema_version()
draft = service.save_draft(_data(schema.id), actor_id=None)
sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation')
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
document = db.session.get(ShippingOrderDocument, sample.document_id)
version = db.session.get(ShippingDocumentLayoutVersion, document.current_layout_version_id)
version.source_content_hash = 'x' * 64
db.session.flush()
state = service.refresh_profile_sample_readiness(profile=profile, sample=sample)
with pytest.raises(Exception) as caught:
service.require_profile_sample_automark_ready(profile=profile, sample=sample)
# 关键断言:Layout 可见并不足够,Document 与 Layout 的不可变内容身份不一致必须失败关闭。
assert state['automark_ready'] is False
assert state['evidence_status'] == 'stale'
assert state['reason_code'] == 'layout_content_hash_mismatch'
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE'
def test_profile_sample_readiness_requires_manual_main_table_selection_for_multiple_tables(app):
"""未绑定主表而 Layout 存在多个表时不得猜测第一张表,必须返回人工选择门禁。"""
with app.app_context():
from app.services.shipping_notice.document_layout.lifecycle import canonical_layout_payload
schema = _schema_version()
draft = service.save_draft(_data(schema.id), actor_id=None)
sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation')
profile = db.session.get(ShippingOrderDocumentProfile, draft['id'])
document = db.session.get(ShippingOrderDocument, sample.document_id)
version = db.session.get(ShippingDocumentLayoutVersion, document.current_layout_version_id)
payload = dict(version.payload_json)
tables = [dict(item) for item in payload['tables']]
tables.append({**tables[0], 'table_id': 'second-table'})
payload['tables'] = tables
checksum, _ = canonical_layout_payload(payload)
version.payload_json = payload
version.payload_checksum = checksum
sample.table_id = None
db.session.flush()
state = service.refresh_profile_sample_readiness(profile=profile, sample=sample)
with pytest.raises(Exception) as caught:
service.require_profile_sample_automark_ready(profile=profile, sample=sample)
# 关键断言:多表选择不是自动标注的可推断信息,禁止以位置或顺序猜测。
assert state['automark_ready'] is False
assert state['main_table_status'] == 'ambiguous'
assert state['reason_code'] == 'main_table_ambiguous'
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS'
def test_draft_unbound_order_field_layout_does_not_require_schema_scope(app):
@@ -860,6 +1103,36 @@ def test_order_field_layouts_can_share_one_anchor_with_distinct_layout_ids(app):
]
def test_order_field_layout_rejects_address_bound_to_number_anchor(app):
"""关键断言:地址字段不能保存为订单编号的 Number 标签,避免错误锚点进入运行时。"""
with app.app_context():
schema = _schema_version()
schema.definition_json['fields'].append({
'field_id': 'ship-to-address', 'field_code': 'ship_to_address', 'scope': 'header',
'value_type': 'string', 'enabled': True, 'normalizer_key': 'trim',
'validator_keys': [], 'allowed_sources': ['pdf_coordinate'],
})
definition = _coordinate_definition()
definition['order_field_layouts'] = [{
'layout_id': 'ship_to_address_layout', 'field_id': '', 'field_code': 'ship_to_address',
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
'anchor': {'anchor_id': 'order_field_1_1_anchor', 'text': 'Number'},
'value_region': {'x0': 1, 'y0': 0, 'x1': 5, 'y1': 1},
'value_mode': 'right_of_anchor', 'stop_anchors': [], 'required': False,
'minimum_evidence_level': 'coordinate',
}]
with pytest.raises(Exception) as caught:
service.save_draft({
'profile_code': 'SHIP_TO_NUMBER', 'display_name': 'Ship to number mismatch',
'schema_version_id': schema.id, 'definition': definition,
}, actor_id=None)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID'
assert getattr(caught.value, 'details', {}).get('reason') == 'order_field_anchor_semantic_mismatch'
assert getattr(caught.value, 'details', {}).get('field_code') == 'ship_to_address'
def test_order_field_layout_rejects_line_field_and_unbounded_value_only_mode(app):
"""订单字段不得借用明细字段;无锚点坐标回退必须限制在单页。"""
with app.app_context():
@@ -2027,6 +2300,86 @@ def test_profile_region_preview_uses_the_current_v2_region_definition(app, monke
assert preview['source_row_indices'] == [[], [0]]
def test_profile_region_preview_does_not_promote_unanchored_header_to_data(app, monkeypatch):
"""页级证据没有有效起行锚点时,预览必须保持无明细并进入 Review 语义。"""
with app.app_context():
schema = _schema_version()
profile = SimpleNamespace(profile_code='STRICT_PREVIEW', version=1, schema_version=schema)
document = SimpleNamespace(id=308)
definition = _coordinate_definition()
definition['table_regions'][0]['line_layouts'][0]['field_regions'] = [{
'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': 0, 'x1': .25, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
}]
layout = {
'tables': [{'table_id': 'header-only', 'page_no': 1}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}},
'tables': {'header-only': [
{'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}},
]},
'page_glyphs': {'1': [
{'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}},
]},
},
}
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
monkeypatch.setattr(
db.session, 'get',
lambda model, _identity: profile if model is ShippingOrderDocumentProfile else None,
)
preview = service.preview_profile_region(
22, data={'document_id': 308, 'table_id': 'header-only', 'definition': definition}, actor_id=1,
)
assert preview['rows'] == [['customer_po_line_no']]
assert preview['row_roles'] == ['header']
assert preview['status'] == 'needs_review'
def test_profile_region_preview_excludes_configured_header_regions_from_line_rows(app, monkeypatch):
"""已配置的表头区域不得作为坐标明细行;真实起行值仍必须保留。"""
with app.app_context():
schema = _schema_version()
profile = SimpleNamespace(profile_code='HEADER_BOUNDARY', version=1, schema_version=schema)
document = SimpleNamespace(id=309)
definition = _coordinate_definition()
table = definition['table_regions'][0]
table['header_layouts'] = [{
'layout_id': 'header_1',
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': .2},
'field_regions': [],
}]
table['line_layouts'][0]['field_regions'] = [{
'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line',
'region': {'x0': 0, 'y0': .21, 'x1': .3, 'y1': 1},
'allowed_sources': ['pdf_coordinate'],
}]
table['line_layouts'][0]['region'] = {'x0': 0, 'y0': .2, 'x1': 1, 'y1': 1}
layout = {
'tables': [{'table_id': 'header-and-data', 'page_no': 1}],
'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}},
'tables': {'header-and-data': [
{'text': 'Item', 'source_index': 0, 'bbox': {'x0': 5, 'y0': 5, 'x1': 20, 'y1': 10}},
{'text': 'Vendor', 'source_index': 1, 'bbox': {'x0': 30, 'y0': 5, 'x1': 45, 'y1': 10}},
{'text': '10', 'source_index': 2, 'bbox': {'x0': 5, 'y0': 30, 'x1': 15, 'y1': 40}},
]},
},
}
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
monkeypatch.setattr(db.session, 'get', lambda model, _identity: profile if model is ShippingOrderDocumentProfile else None)
preview = service.preview_profile_region(
23, data={'document_id': 309, 'table_id': 'header-and-data', 'definition': definition}, actor_id=1,
)
assert preview['rows'] == [['customer_po_line_no'], ['10']]
assert preview['source_row_indices'] == [[], [0]]
def test_profile_region_preview_uses_schema_field_order(app, monkeypatch):
"""局部候选字段必须按绑定 Schema 顺序返回,不受字段标注先后影响。"""
with app.app_context():
@@ -14,6 +14,7 @@ from decimal import Decimal
from unittest.mock import patch
import pytest
from sqlalchemy import event
from sqlalchemy.orm.attributes import flag_modified
from app import db
@@ -64,6 +65,7 @@ from app.jobs.queue import fail_job
from app.services.shipping_notice.order_extraction import (
submit_order_extraction_run_result,
submit_order_extraction_unit_result,
reconcile_review_case_after_unit,
)
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
from app.services.shipping_notice.order_extraction_plan import (
@@ -934,9 +936,13 @@ def test_run_v3_freezes_layout_schema_candidate_and_policy_versions(app):
)
frozen_document = run.input_snapshot_json['intakes'][0]['documents'][0]
candidates = frozen_document['layout_schema_candidates']
parse_plan = frozen_document['generic_parse_plan']
assert run.input_snapshot_json['snapshot_version'] == 3
assert candidates[0]['mapping_status'] == 'candidate'
assert candidates[0]['rows'][0]['fields'][0]['cell_id']
assert parse_plan['status'] == 'qualified'
assert parse_plan['schema_checksum'] == run.input_snapshot_json['schema']['checksum']
assert parse_plan['candidate_checksum']
assert 'layout_table_not_accepted' in candidates[0]['issues']
# 关键断言:策略版本写入快照,且不再暴露 Dify Workflow 清单。
assert run.input_snapshot_json['policy_versions']['route_strategy_version'] == ROUTE_STRATEGY_VERSION
@@ -1105,7 +1111,6 @@ def test_second_pdf_unit_can_persist_after_first_unit_consumes_shared_intake(app
db.session.refresh(intake)
assert intake.parse_status == 'consumed'
assert intake.consumed_task_id is None
assert intake.consumed_batch_id is None
result = submit_order_extraction_unit_result(run=run, unit=second_unit, orders=[])
@@ -1904,6 +1909,75 @@ def test_run_api_create_get_list_and_user_isolation(app, client):
assert hidden.get_json()['error']['code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND'
def test_run_list_returns_lightweight_summaries_without_full_workspace_projection(app, client, monkeypatch):
"""会话恢复列表不得为每个 Run 构建文档、Case、Gate 等完整工作台投影。"""
with app.app_context():
owner, agent, session, intake, _document = _seed_run_input(suffix='LIGHT-LIST')
run, _ = create_order_extraction_run(
user=owner,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
token = issue_local_access_token(owner)
run_no = run.run_no
conversation_id = session.session_id
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_workspace_projection.serialize_workspace_run',
lambda _run: (_ for _ in ()).throw(AssertionError('list must not build workspace projection')),
)
response = client.get(
f'/api/workspace/shipping-notice/order-extraction-runs?conversation_id={conversation_id}&limit=20',
headers={'Authorization': f'Bearer {token}'},
)
assert response.status_code == 200
item = next(row for row in response.get_json()['data']['items'] if row['run_no'] == run_no)
assert item['status'] == 'queued'
assert item['summary']['total_documents'] == 0
for forbidden in ('documents', 'handling_items', 'available_actions', 'result', 'selection_plan'):
assert forbidden not in item
def test_run_list_does_not_select_large_input_snapshots(app, client):
"""会话恢复列表只读摘要列,不能因 upload_batch_id 再取冻结输入快照。"""
with app.app_context():
owner, agent, session, intake, _document = _seed_run_input(suffix='LIST-SCALAR')
run, _ = create_order_extraction_run(
user=owner,
agent_id=agent.id,
conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
snapshot = dict(run.input_snapshot_json)
snapshot['large_regression_payload'] = 'x' * 1_000_000
run.input_snapshot_json = snapshot
db.session.commit()
token = issue_local_access_token(owner)
conversation_id = session.session_id
statements: list[str] = []
def capture_statement(_conn, _cursor, statement, _parameters, _context, _executemany):
if 'shipping_order_processing_runs' in statement:
statements.append(statement.lower())
with app.app_context():
event.listen(db.engine, 'before_cursor_execute', capture_statement)
try:
response = client.get(
f'/api/workspace/shipping-notice/order-extraction-runs?conversation_id={conversation_id}&limit=20',
headers={'Authorization': f'Bearer {token}'},
)
finally:
event.remove(db.engine, 'before_cursor_execute', capture_statement)
assert response.status_code == 200
assert statements
assert all('input_snapshot_json' not in statement for statement in statements)
def test_run_api_requires_upload_batch_id(app, client):
"""发送端缺少服务端上传批次时必须拒绝,不能回退为全会话 Intake 选择。"""
with app.app_context():
@@ -2170,6 +2244,9 @@ def test_run_documents_and_summary_keep_partial_success_isolated_per_pdf(app, cl
headers={'Authorization': f'Bearer {owner_token}'},
)
assert run_response.status_code == 200
# 关键断言:重型 Run 投影必须返回可与浏览器 HAR 对齐的分段耗时,便于定位慢查询。
assert 'run_lookup' in run_response.headers.get('Server-Timing', '')
assert 'workspace_projection' in run_response.headers.get('Server-Timing', '')
run_payload = run_response.get_json()['data']
assert run_payload['summary'] == {
'total_documents': 3,
@@ -2343,6 +2420,89 @@ def test_run_summary_omits_legacy_progress_projection(app):
assert 'progress' not in payload
def test_run_summary_exposes_user_lifecycle_progress_from_current_activity(app):
"""Run 摘要必须提供五阶段用户态进度与当前步骤,供复核台首屏直接展示。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='LIFECYCLE-PROGRESS')
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 = 'deterministic_parsing'
run.progress_version = 4
run.last_activity_at = datetime.utcnow()
db.session.commit()
payload = serialize_order_extraction_run(run)
progress = payload['lifecycle_progress']
assert progress['lifecycle_stage'] == 'intake_parse'
assert progress['lifecycle_status'] == 'running'
assert progress['current_step_code'] == 'document_queued'
assert progress['current_step_i18n_key'] == 'chat.shippingProcessing.progress.step.document_queued'
assert isinstance(progress['completed_step_codes'], list)
assert progress['last_activity_at']
assert progress['health_status'] == 'normal'
assert 'input_snapshot' not in str(progress)
assert 'provider' not in str(progress).lower()
def test_run_summary_lifecycle_progress_maps_completed_events_and_current_step(app):
"""事件事实映射为稳定用户步骤,并保留已完成步骤顺序。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='LIFECYCLE-EVENTS')
run, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
)
transition_order_extraction_run(run, target_status='processing')
ensure_order_extraction_plan(run)
unit = run.extraction_plan.units[0]
unit.status = 'extracting'
unit.started_at = datetime.utcnow()
unit.last_activity_at = datetime.utcnow()
latest_sequence = (
db.session.query(ShippingOrderExtractionProgressEvent.sequence_no)
.filter_by(run_id=run.id)
.order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc())
.first()
)
sequence_base = int(latest_sequence[0]) if latest_sequence else 0
for sequence, code in enumerate(('layout_parsing_completed', 'profile_matching'), start=1):
db.session.add(ShippingOrderExtractionProgressEvent(
run_id=run.id,
unit_id=unit.id,
document_id=document.id,
sequence_no=sequence_base + sequence,
event_code=code,
# 真实写入契约把该完成事实保留为 running,投影仍必须识别为已完成。
status='running',
visibility='workspace',
summary_json={},
idempotency_key=f'lifecycle-events-{sequence}',
))
db.session.commit()
progress = serialize_order_extraction_run(run)['lifecycle_progress']
assert progress['current_step_code'] == 'profile_matching'
assert progress['completed_step_codes'] == ['layout_parsing_completed']
def test_run_summary_lifecycle_progress_marks_failed_without_worker_details(app):
"""失败 Run 只显示稳定失败态和脱敏字段,不泄漏内部错误正文。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='LIFECYCLE-FAILED')
run, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
)
transition_order_extraction_run(run, target_status='processing')
transition_order_extraction_run(run, target_status='failed', error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED', error_message='secret worker trace')
payload = serialize_order_extraction_run(run)
progress = payload['lifecycle_progress']
assert progress['lifecycle_status'] == 'failed'
assert progress['health_status'] == 'failed'
assert 'secret worker trace' not in str(progress)
def test_user_run_summary_never_exposes_worker_error_text(app):
"""Workspace status cards expose a stable error code, never Provider or Worker details."""
with app.app_context():
@@ -2442,46 +2602,6 @@ def test_run_seen_api_keeps_cross_user_isolation(app, client):
assert hidden.status_code == 404
def test_chat_sessions_aggregate_only_new_unseen_order_extraction_attention(app):
"""侧栏只聚合同用户同Agent的新提醒,并把失败优先级提升到 error。"""
from app.api.chat import _order_extraction_attention_by_conversation
with app.app_context():
owner, agent, session, intake, _document = _seed_run_input(suffix='SESSION-ATTENTION')
ignored_agent = Agent(
name='Other owner', agent_code='generic', runtime_provider='dify', dify_app_id='other-owner',
dify_api_key='key', is_active=True,
)
db.session.add(ignored_agent)
db.session.flush()
run, _ = create_order_extraction_run(
user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
)
transition_order_extraction_run(run, target_status='processing')
transition_order_extraction_run(run, target_status='failed', error_message='provider unavailable')
historical = ShippingOrderProcessingRun(
run_no='SNER-HISTORICAL-SESSION', user_id=owner.id, owner_agent_id=agent.id,
conversation_id=session.session_id, schema_version_id=run.schema_version_id,
input_snapshot_hash='e' * 64, input_snapshot_json={}, idempotency_key='f' * 64,
status='completed', phase='completed', finished_at=datetime.utcnow(),
)
other_owner_run = ShippingOrderProcessingRun(
run_no='SNER-OTHER-OWNER', user_id=owner.id, owner_agent_id=ignored_agent.id,
conversation_id=session.session_id, schema_version_id=run.schema_version_id,
input_snapshot_hash='g' * 64, input_snapshot_json={}, idempotency_key='h' * 64,
status='completed', phase='completed', finished_at=datetime.utcnow(), attention_generated_at=datetime.utcnow(),
)
db.session.add_all([historical, other_owner_run])
db.session.commit()
aggregate = _order_extraction_attention_by_conversation(
user_id=owner.id,
agent_id=agent.id,
conversation_ids={session.session_id},
)
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():
@@ -2677,114 +2797,6 @@ def test_terminal_transition_updates_persisted_chat_state(app):
]
def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, client):
"""终态后晚到的旧卡必须在历史 GET 时按 Run 事实纠正,不能永久显示运行中。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='CHAT-HISTORY')
run, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
)
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
transition_order_extraction_run(
run,
target_status='failed',
error_code='TEST.FAILED',
error_message='failed before card persisted',
)
db.session.add(ChatLog(
user_id=user.id,
agent_id=agent.id,
session_id=session.session_id,
conversation_id=session.session_id,
query='',
answer='',
message_type='text',
payload={
'formId': f'shipping-order-extraction-run:{run.run_no}',
'order_extraction_run_no': run.run_no,
'shipping_order_extraction_state': {'status': 'extracting', 'terminal': False},
},
))
db.session.commit()
token = issue_local_access_token(user)
session_id = session.session_id
agent_id = agent.id
response = client.get(
f'/api/chat/messages?conversation_id={session_id}&agent_id={agent_id}',
headers={'Authorization': f'Bearer {token}'},
)
assert response.status_code == 200
state = response.get_json()[-1]['payload']['shipping_order_extraction_state']
assert state['status'] == 'failed'
assert state['terminal'] is True
assert state['availableActions'] == [
'view_details', 'refresh_status', 'retry_failed_attachments',
]
assert 'failed before card persisted' not in str(response.get_json())
def test_chat_history_does_not_project_user_run_anchor_as_duplicate_state_card(app, client):
"""同一 Run 的上传记录与状态记录共存时,历史回放只能出现一张助手状态卡。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='CHAT-DEDUPLICATE')
run, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
)
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
transition_order_extraction_run(run, target_status='failed', error_message='failed once')
db.session.add_all([
ChatLog(
user_id=user.id,
agent_id=agent.id,
session_id=session.session_id,
conversation_id=session.session_id,
query='上传附件',
answer='',
message_type='text',
payload={
'formId': f'shipping-order-extraction-user:{run.run_no}',
'order_extraction_run_no': run.run_no,
},
),
ChatLog(
user_id=user.id,
agent_id=agent.id,
session_id=session.session_id,
conversation_id=session.session_id,
query='',
answer='',
message_type='text',
payload={
'formId': f'shipping-order-extraction-run:{run.run_no}',
'order_extraction_run_no': run.run_no,
},
),
])
db.session.commit()
token = issue_local_access_token(user)
run_no = run.run_no
session_id = session.session_id
agent_id = agent.id
response = client.get(
f'/api/chat/messages?conversation_id={session_id}&agent_id={agent_id}',
headers={'Authorization': f'Bearer {token}'},
)
assert response.status_code == 200
messages = response.get_json()
state_cards = [
item for item in messages
if item['role'] == 'assistant'
and item.get('payload', {}).get('order_extraction_run_no') == run_no
]
assert len(state_cards) == 1
assert state_cards[0]['payload']['shipping_order_extraction_state']['status'] == 'failed'
assert [item['role'] for item in messages] == ['user', 'assistant']
def test_failed_run_retry_api_returns_queued_run(app, client):
"""用户点击重新识别后 API 返回 202,并原位恢复同一 Run。"""
with app.app_context():
@@ -2860,7 +2872,6 @@ def test_terminal_run_reparse_reuses_orphaned_consumed_intake(app, client):
transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1})
intake.parse_status = 'consumed'
intake.consumed_at = datetime.utcnow()
intake.consumed_batch_id = None
intake.consumed_task_id = None
db.session.commit()
token = issue_local_access_token(user)
@@ -2886,7 +2897,6 @@ def test_reparse_submission_accepts_orphaned_consumed_intake(app):
transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1})
intake.parse_status = 'consumed'
intake.consumed_at = datetime.utcnow()
intake.consumed_batch_id = None
intake.consumed_task_id = None
db.session.commit()
replacement, _ = reparse_order_extraction_run(
@@ -2909,7 +2919,6 @@ def test_reparse_unit_submission_accepts_orphaned_consumed_intake(app):
transition_order_extraction_run(source, target_status='review_required', result={'pending_count': 1})
intake.parse_status = 'consumed'
intake.consumed_at = datetime.utcnow()
intake.consumed_batch_id = None
intake.consumed_task_id = None
db.session.commit()
replacement, _ = reparse_order_extraction_run(
@@ -2925,6 +2934,23 @@ def test_reparse_unit_submission_accepts_orphaned_consumed_intake(app):
assert ShippingOrderCandidate.query.filter_by(order_extraction_run_id=replacement.id).count() == 0
def test_unit_replay_reconciles_review_case_after_ensure(monkeypatch):
"""Unit 幂等回放创建/恢复 Case 后必须进入统一自动校验协调器。"""
calls = []
monkeypatch.setattr(
'app.services.shipping_notice.order_review_service.ensure_review_case_for_unit',
lambda **kwargs: calls.append(('ensure', kwargs)) or object(),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_stp_auto_create_service.maybe_stp_auto_create_for_run',
lambda **kwargs: calls.append(('reconcile', kwargs)) or [{'validate_status': 'validated'}],
)
reconcile_review_case_after_unit(run='run', unit='unit')
assert [item[0] for item in calls] == ['ensure', 'reconcile']
def test_unit_submission_survives_deleted_chat_session(app):
"""后台 Run 不得因 UI 会话历史已清理而回滚 Candidate/Review Case 持久化。"""
with app.app_context():
@@ -3415,26 +3441,6 @@ def test_failed_reparse_restores_source_candidate_version(app):
assert source.superseded_by_run_id is None
def test_only_current_version_candidate_can_be_consumed(app):
"""旧版本 Candidate 即使被直接提交,也必须被建单入口拒绝。"""
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
with app.app_context():
user, _agent, _session, intake, document = _seed_run_input(suffix='SUPERSEDED')
candidate = ShippingOrderCandidate(
candidate_no='SNC-SUPERSEDED', intake_id=intake.id, primary_document_id=document.id,
candidate_key='old-version', selected=True, is_current_version=False, validation_status='ready',
)
db.session.add(candidate)
db.session.commit()
with pytest.raises(ValidationError) as caught:
create_shipping_batch_from_candidates(
user_id=user.id, intake_nos=[intake.intake_no], candidate_nos=[candidate.candidate_no],
create_idempotency_key='test-current-version-gate', conversation_id=None,
)
assert caught.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_FOUND'
def test_order_extraction_health_reports_backlog_latency_and_safe_errors(app):
"""管理员健康汇总应识别积压/失败并只返回安全运行元数据。"""
from app.services.shipping_notice.order_extraction_run_service import get_order_extraction_run_health
@@ -37,7 +37,9 @@ def _glyphs(*lines: tuple[str, float, float]) -> list[dict]:
return result
def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinateProfile:
def _profile(
*, layout: dict, page_scope: str = 'first_page', reference_page_frames: dict[str, dict] | None = None,
) -> OrderCoordinateProfile:
"""构造包含一个独立 header 字段的最小合法 v2 Profile。"""
return OrderCoordinateProfile.model_validate({
'profile_code': 'ORDER-FIELD-TEST', 'version': 1,
@@ -48,6 +50,7 @@ def _profile(*, layout: dict, page_scope: str = 'first_page') -> OrderCoordinate
'scope': 'header',
'page_scope': page_scope, **layout,
}],
'reference_page_frames': reference_page_frames or {},
})
@@ -60,15 +63,38 @@ def _schema(**overrides: object) -> dict[str, dict]:
}}
def _evidence(*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate') -> dict:
def _evidence(
*, pages: dict[str, list[dict]], source: str = 'pdf_coordinate', page_size: tuple[float, float] = (200, 200),
) -> dict:
"""构造冻结页级证据;故意不提供 tables,证明订单字段不依赖明细区。"""
return {
'pages': {page: {'width': 200, 'height': 200} for page in pages},
'pages': {page: {'width': page_size[0], 'height': page_size[1]} for page in pages},
'page_glyphs': pages,
'sources': {'pages': {page: source for page in pages}},
}
def test_fixed_order_field_uses_annotation_page_frame_when_runtime_page_is_taller():
"""同内容由分页页变为长页时,固定字段仍须读取标注页的 PDF 点坐标。"""
profile = _profile(
layout={'fallback_value_region': {'x0': .10, 'y0': .20, 'x1': .90, 'y1': .30}},
reference_page_frames={'1': {'width': 200, 'height': 100}},
)
result = extract_order_fields(
profile=profile,
schema_fields=_schema(),
coordinate_evidence=_evidence(
pages={'1': _glyphs(('45001', 40, 21))}, page_size=(200, 200),
),
allow_fixed_region_confirmation=True,
)[0]
# 关键断言:不能把训练页 y=20..30 重投影到长页 y=40..60。
assert result.status == 'confirmed'
assert result.value == '45001'
def test_visual_row_prefers_explicit_pdf_space_boundary_over_geometry_threshold():
"""真实词间距低于旧阈值时,PDF 文本流的明确空格仍应恢复,不能输出粘连地址。"""
row = [
@@ -140,6 +166,55 @@ def test_anchor_relative_value_is_confirmed_with_native_page_coordinates():
assert result.source == 'pdf_coordinate'
def test_anchor_frame_transform_moves_order_number_anchor_and_value_together():
"""共同 matcher 的纵向平移必须同时投影订单号标签和值框。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'po', 'text': 'PO NO',
'region': {'x0': .05, 'y0': .1, 'x1': .25, 'y1': .14},
'position_locked': True,
},
'absolute_value_region': {'x0': .2, 'y0': .1, 'x1': .9, 'y1': .14},
'value_mode': 'right_of_anchor',
})
result = extract_order_fields(
profile=profile,
schema_fields=_schema(),
coordinate_evidence=_evidence(pages={'1': _glyphs(('PO NO 45001', 20, 40))}),
coordinate_transform={'status': 'applied', 'translate_x': 0, 'translate_y': .1},
)[0]
assert result.status == 'confirmed'
assert result.value == '45001'
def test_coordinate_transform_applies_affine_matrix_to_order_header_regions():
"""订单头必须与订单行共享 matcher 已验证的仿射矩阵,而非只读取旧平移键。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'po', 'text': 'PO NO',
'region': {'x0': .10, 'y0': .10, 'x1': .30, 'y1': .14},
'position_locked': True,
},
'absolute_value_region': {'x0': .20, 'y0': .10, 'x1': .80, 'y1': .14},
'value_mode': 'right_of_anchor',
})
result = extract_order_fields(
profile=profile,
schema_fields=_schema(),
coordinate_evidence=_evidence(pages={'1': _glyphs(('PO NO 45001', 30, 40))}),
coordinate_transform={
'status': 'applied',
'matrix': [1.0, 0.0, .05, 0.0, 1.0, .10],
'anchor_ids': ['po'],
'reason_codes': [],
},
)[0]
# 关键断言:仅 matrix 存在时也必须与共同 matcher 的坐标系一致。
assert result.status == 'confirmed'
assert result.value == '45001'
def test_right_of_anchor_keeps_saved_value_width_when_actual_anchor_text_is_narrower():
"""值框只命中 USD 首字符时,应补齐同一连续词而非误报未读取到值。"""
profile = _profile(layout={
@@ -301,6 +376,25 @@ def test_anchor_reference_region_and_exact_mode_reject_unrelated_label_occurrenc
assert result.value == '45001'
def test_unique_anchor_outside_saved_reference_region_is_still_readable():
"""同版式样本唯一命中标签时,旧参考框不得阻断盲测/正式读取。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'ship_to', 'text': 'Ship to', 'match_mode': 'exact',
'region': {'x0': .55, 'y0': .10, 'x1': .63, 'y1': .12},
'position_locked': True,
},
'value_region': {'x0': .8, 'y0': 0, 'x1': 4.0, 'y1': 1.0},
'value_mode': 'right_of_anchor',
})
result = extract_order_fields(profile=profile, schema_fields=_schema(), coordinate_evidence=_evidence(
pages={'1': _glyphs(('Ship to:ACME', 20, 20))},
))[0]
assert result.status == 'confirmed'
assert result.value == 'ACME'
def test_legacy_placeholder_anchor_uses_its_reference_region_as_review_only_evidence():
"""历史手工默认标签不能丢值,但只能按原标注框降级为人工复核。"""
profile = _profile(layout={
@@ -390,6 +484,24 @@ def test_fallback_and_ocr_never_become_confirmed():
assert ocr_result.status == 'needs_review'
def test_profile_confirmed_fixed_region_is_confirmed_with_native_coordinates():
"""唯一确认模板中的无标签固定区域可作为原生 PDF 正式字段证据。"""
profile = _profile(layout={
'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .5, 'y1': .2},
})
result = extract_order_fields(
profile=profile,
schema_fields=_schema(),
coordinate_evidence=_evidence(pages={'1': _glyphs(('45001', 30, 20))}),
allow_fixed_region_confirmation=True,
)[0]
# 关键断言:此放宽仅由已确认的模板调用方显式开启,原生坐标和字段校验仍是必要条件。
assert result.status == 'confirmed'
assert result.issues == []
def test_multiline_stops_at_next_label_and_type_failure_requires_review():
"""地址值在下一个标签前截断;日期格式无效不能绕过 Schema validator。"""
address = _profile(layout={
@@ -429,6 +541,21 @@ def test_common_purchase_order_slash_date_is_normalized():
assert result.value.isoformat() == '2026-06-20'
def test_common_purchase_order_short_slash_date_is_normalized():
"""采购单常见两位年份日期应按冻结 date Schema 归一化。"""
profile = _profile(layout={
'anchor': {'anchor_id': 'date', 'text': 'DATE'},
'value_region': {'x0': 1.2, 'y0': 0, 'x1': 5, 'y1': 1},
})
result = extract_order_fields(profile=profile, schema_fields=_schema(
field_code='order_date', value_type='date', validator_keys=['iso_date'],
), coordinate_evidence=_evidence(pages={'1': _glyphs(('DATE 06/16/26', 20, 20))}))[0]
# 关键断言:视觉样本的两位年份转换为统一 ISO 日期,而不是未读取。
assert result.status == 'confirmed'
assert result.value.isoformat() == '2026-06-16'
def test_date_does_not_extend_beyond_value_frame():
"""值框边界是标注预览的唯一证据,日期也不得跨框补全。"""
profile = _profile(layout={
@@ -498,6 +625,27 @@ def test_absolute_value_region_uses_canvas_boundary_instead_of_anchor_projection
assert result.value == '66 Hou-Kang Street'
def test_absolute_single_line_value_region_moves_with_its_unique_anchor():
"""单头整体上移时,绝对客户值框必须跟随已唯一命中的自身标签。"""
profile = _profile(layout={
'anchor': {
'anchor_id': 'bill_to', 'text': 'BILL TO',
'region': {'x0': .10, 'y0': .30, 'x1': .30, 'y1': .35},
},
'absolute_value_region': {'x0': .10, 'y0': .38, 'x1': .90, 'y1': .44},
'value_mode': 'single_line',
})
result = extract_order_fields(
profile=profile, schema_fields=_schema(field_code='bill_to_customer'),
coordinate_evidence=_evidence(pages={'1': _glyphs(
('BILL TO', 20, 40), ('Hyve Solutions Corporation', 20, 56), ('44201 Nobel Drive', 20, 72),
)}),
)[0]
assert result.status == 'confirmed'
assert result.value == 'Hyve Solutions Corporation'
def test_tight_value_region_keeps_edge_glyphs_without_reading_adjacent_text():
"""紧贴 USD 字符盒的右侧值框应容忍渲染误差,但不能吞入相邻字段。"""
profile = _profile(layout={
@@ -1,6 +1,10 @@
"""验证订单坐标模板匹配:版面签名、七维评分与解析校验门禁。"""
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
from app.services.shipping_notice.document_layout.order_profile_matcher import (
_resolve_coordinate_transform,
match_frozen_coordinate_profiles,
)
from app.services.shipping_notice.document_layout.order_profile_signature import (
MATCHER_POLICY_ID,
build_layout_signature,
@@ -86,6 +90,210 @@ def _with_signature(profile: dict, layout: dict) -> dict:
return enriched
def _anchor_frame_profile(code: str = 'PO_ANCHOR_FRAME') -> dict:
"""构造声明锚点坐标框架的最小 Profile,供平移门禁回归使用。"""
profile = _profile(code)
profile['definition']['coordinate_model'] = {
'type': 'anchor_frame',
'anchors': [{
'anchor_id': 'title', 'text': 'PURCHASE ORDER', 'match_mode': 'exact',
'minimum_evidence_level': 'coordinate',
'region': {'x0': .185, 'y0': .05, 'x1': .26, 'y1': .0857142857},
}],
'max_translate_x': .02,
'max_translate_y': .05,
}
return profile
def _layout_with_frame_anchor(*, anchor_y: float = .05, table_y: float = .25) -> dict:
"""构造标题与主表同步平移的坐标 Layout,模拟正文高度改变而非结构变更。"""
layout = _layout(bbox={'x0': .05, 'y0': table_y, 'x1': .95, 'y1': .95})
text = 'PURCHASE ORDER'
anchor_glyphs = [
{
'text': char,
'bbox': {'x0': 10 + index * 5, 'y0': anchor_y * 280, 'x1': 14 + index * 5, 'y1': anchor_y * 280 + 10},
'boundary_before': 'space' if index and text[index - 1] == ' ' else 'none',
}
for index, char in enumerate(text)
if char != ' '
]
header = layout['coordinate_evidence']['tables']['table-1']
for glyph in header:
glyph['bbox']['y0'] += (table_y - .25) * 280
glyph['bbox']['y1'] += (table_y - .25) * 280
plant_text = 'PLANT NAME: FACTORY A'
plant_glyphs = [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
for index, char in enumerate(plant_text)
]
layout['coordinate_evidence']['page_glyphs']['1'] = [
*plant_glyphs,
*anchor_glyphs,
*header,
]
return layout
def test_anchor_frame_matches_bounded_vertical_translation_without_changing_legacy_profiles():
"""同一结构整体下移时仅启用锚点框架的 Profile 可命中,legacy 仍按原规则失败关闭。"""
baseline = _layout_with_frame_anchor()
shifted = _layout_with_frame_anchor(anchor_y=.095, table_y=.295)
framed = _with_signature(_anchor_frame_profile(), baseline)
legacy = _with_signature(_profile('PO_LEGACY'), baseline)
framed_result = match_frozen_coordinate_profiles(profiles=[framed], layout=shifted)
legacy_result = match_frozen_coordinate_profiles(profiles=[legacy], layout=shifted)
# 关键断言:变换来自唯一静态锚点,并且 legacy Profile 未因新能力改变行为。
assert framed_result.status == 'unique_match'
assert framed_result.candidates[0].coordinate_transform == {
'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.045,
'anchor_ids': ['title'], 'reason_codes': [],
}
assert legacy_result.candidates[0].coordinate_transform is None
def test_legacy_profile_automatically_uses_unique_document_match_label_for_bounded_translation():
"""新管理台不配置坐标模型时,唯一的模板身份标签仍可自动校正小幅整体平移。"""
definition = _profile('PO_AUTO_FRAME')['definition']
definition['document_match']['required_anchors'][0].update({
'label_region': {'x0': .05, 'y0': .02, 'x1': .265, 'y1': .10},
'value_region': {'x0': .42, 'y0': .02, 'x1': .85, 'y1': .10},
})
profile = OrderCoordinateProfile.model_validate(definition)
pages = {'1': {'width': 200, 'height': 280}}
glyphs = {'1': [
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 25.8, 'x1': 13 + index * 4, 'y1': 35.8}}
for index, char in enumerate('PLANT NAME:')
]}
transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs)
assert reasons == []
assert transform == {
'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.05,
'anchor_ids': ['plant_name'], 'reason_codes': [],
}
def test_affine_anchor_frame_requires_explicit_opt_in_and_three_stable_anchors():
"""仿射只允许显式治理的多锚点 Profile 使用,默认平移模板不改变行为。"""
definition = _anchor_frame_profile()['definition']
definition['coordinate_model'].update({
'transform_mode': 'affine',
'anchors': [
{'anchor_id': 'a', 'text': 'A', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .10, 'x1': .14, 'y1': .14}},
{'anchor_id': 'b', 'text': 'B', 'match_mode': 'exact', 'region': {'x0': .60, 'y0': .10, 'x1': .64, 'y1': .14}},
{'anchor_id': 'c', 'text': 'C', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .60, 'x1': .14, 'y1': .64}},
],
'max_scale_delta': .05,
'max_rotation_degrees': 3.0,
'max_residual': .005,
})
profile = OrderCoordinateProfile.model_validate(definition)
pages = {'1': {'width': 1000, 'height': 1000}}
# x 轴放大 2%,y 轴放大 1%,并整体右移 1%、下移 2%。
glyphs = {'1': [
{'text': 'A', 'bbox': {'x0': 122.4, 'y0': 131.2, 'x1': 142.4, 'y1': 151.2}},
{'text': 'B', 'bbox': {'x0': 632.4, 'y0': 131.2, 'x1': 652.4, 'y1': 151.2}},
{'text': 'C', 'bbox': {'x0': 122.4, 'y0': 636.2, 'x1': 142.4, 'y1': 656.2}},
]}
transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs)
# 关键断言:仿射矩阵仅由三个唯一锚点证明,且带可审计残差。
assert reasons == []
assert transform['matrix'] == [1.02, 0.0, .01, 0.0, 1.01, .02]
assert transform['anchor_ids'] == ['a', 'b', 'c']
assert transform['residual'] == 0.0
def test_affine_anchor_frame_rejects_degenerate_or_high_residual_evidence():
"""共线锚点和超残差锚点不允许形成看似可信的仿射坐标系。"""
definition = _anchor_frame_profile()['definition']
definition['coordinate_model'].update({
'transform_mode': 'affine',
'anchors': [
{'anchor_id': 'a', 'text': 'A', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .10, 'x1': .14, 'y1': .14}},
{'anchor_id': 'b', 'text': 'B', 'match_mode': 'exact', 'region': {'x0': .60, 'y0': .10, 'x1': .64, 'y1': .14}},
{'anchor_id': 'c', 'text': 'C', 'match_mode': 'exact', 'region': {'x0': .10, 'y0': .60, 'x1': .14, 'y1': .64}},
{'anchor_id': 'd', 'text': 'D', 'match_mode': 'exact', 'region': {'x0': .60, 'y0': .60, 'x1': .64, 'y1': .64}},
],
'max_scale_delta': .05,
'max_rotation_degrees': 3.0,
'max_residual': .003,
})
profile = OrderCoordinateProfile.model_validate(definition)
pages = {'1': {'width': 1000, 'height': 1000}}
# A/B/C 都符合平移;D 额外偏离 2%,残差必须阻断而不是被最小二乘掩盖。
glyphs = {'1': [
{'text': 'A', 'bbox': {'x0': 110, 'y0': 120, 'x1': 130, 'y1': 140}},
{'text': 'B', 'bbox': {'x0': 610, 'y0': 120, 'x1': 630, 'y1': 140}},
{'text': 'C', 'bbox': {'x0': 110, 'y0': 620, 'x1': 130, 'y1': 640}},
{'text': 'D', 'bbox': {'x0': 630, 'y0': 620, 'x1': 650, 'y1': 640}},
]}
transform, reasons = _resolve_coordinate_transform(profile=profile, pages=pages, page_glyphs=glyphs)
assert transform is None
assert reasons == ['profile_anchor_frame_affine_residual_out_of_range']
def test_anchor_frame_fails_closed_when_anchor_is_missing_ambiguous_or_out_of_range():
"""锚点框架不得因缺锚、重锚或超界平移降级猜测,均须成为模板硬失败。"""
baseline = _layout_with_frame_anchor()
profile = _with_signature(_anchor_frame_profile(), baseline)
missing = _layout()
ambiguous = _layout_with_frame_anchor(anchor_y=.08, table_y=.28)
ambiguous['coordinate_evidence']['page_glyphs']['1'].extend(
_layout_with_frame_anchor(anchor_y=.115)['coordinate_evidence']['page_glyphs']['1'][21:34],
)
out_of_range = _layout_with_frame_anchor(anchor_y=.14, table_y=.34)
for layout, reason in (
(missing, 'profile_anchor_frame_anchor_missing'),
(ambiguous, 'profile_anchor_frame_anchor_ambiguous'),
(out_of_range, 'profile_anchor_frame_transform_out_of_range'),
):
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.candidates[0].hard_match is False
assert reason in result.candidates[0].reason_codes
def test_anchor_frame_matches_static_anchor_embedded_in_a_pdf_line():
"""PDF 原生字符常把多个标签拼成一行;锚点应返回自身字符框而非整行框。"""
baseline = _layout_with_frame_anchor()
title = baseline['coordinate_evidence']['page_glyphs']['1'][21:34]
prefix = [{'text': 'X', 'bbox': {'x0': 0, 'y0': 14, 'x1': 5, 'y1': 24}}]
suffix = [{'text': 'X', 'bbox': {'x0': 80, 'y0': 14, 'x1': 85, 'y1': 24}}]
for glyph in title:
glyph['bbox']['y0'] += 10
glyph['bbox']['y1'] += 10
prefix[0]['bbox']['y0'] += 10
prefix[0]['bbox']['y1'] += 10
suffix[0]['bbox']['y0'] += 10
suffix[0]['bbox']['y1'] += 10
baseline['coordinate_evidence']['page_glyphs']['1'] = [
*baseline['coordinate_evidence']['page_glyphs']['1'][:21],
*prefix,
*title,
*suffix,
*baseline['coordinate_evidence']['page_glyphs']['1'][34:],
]
profile = _with_signature(_anchor_frame_profile(), baseline)
result = match_frozen_coordinate_profiles(profiles=[profile], layout=baseline)
# 关键断言:行内静态锚点仍唯一命中,且自身 bbox 不受前后文本扩大影响。
assert result.status == 'unique_match'
assert result.candidates[0].coordinate_transform == {
'status': 'applied', 'translate_x': 0.0, 'translate_y': 0.035714,
'anchor_ids': ['title'], 'reason_codes': [],
}
def test_profile_matcher_uniquely_matches_label_value_anchor_not_dynamic_order_values():
"""工厂标签和值关系不受订单号、料号、数量变化影响。"""
layout = _layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X')
@@ -120,6 +328,114 @@ def test_profile_matcher_enforces_required_anchor_and_evidence_availability():
assert match_frozen_coordinate_profiles(profiles=[profile], layout={'tables': []}).status == 'evidence_insufficient'
def test_profile_matcher_uses_persisted_lightweight_features_when_glyphs_are_compacted():
"""字符坐标被压缩后,模板匹配仍须使用压缩前持久化的结构特征。"""
complete_layout = _layout()
profile = _profile('PO_A')
profile['definition']['document_match']['required_anchors'] = []
profile = _with_signature(profile, complete_layout)
compacted_layout = {
'tables': complete_layout['tables'],
'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']},
'matching_features': {
'version': 'v1',
'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1},
'tables': [{
'table_id': 'table-1', 'page_no': 1,
'bbox': [0.05, 0.25, 0.95, 0.95],
'header_candidates': [{
'header_tokens': ['item', 'no', 'qty'],
'column_centers': [0.1225, 0.2825, 0.4225],
'column_width_ratios': [0.1611, 0.0722, 0.1167],
}],
}],
'static_text_centers': {},
},
}
result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout)
assert result.status == 'unique_match'
candidate = result.candidates[0]
assert candidate.dimension_states['header_semantic_position'] == 'matched'
assert candidate.dimension_states['column_topology'] == 'matched'
def test_profile_matcher_selects_semantic_header_candidate_not_data_row_from_compacted_projection():
"""压缩投影含数据行候选时,必须用语义与列几何选真实表头,不能只比列数。"""
complete_layout = _layout()
profile = _profile('PO_A')
profile['definition']['document_match']['required_anchors'] = []
profile = _with_signature(profile, complete_layout)
compacted_layout = {
'tables': complete_layout['tables'],
'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']},
'matching_features': {
'version': 'v1',
'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1},
'tables': [{
'bbox': [0.05, 0.25, 0.95, 0.95],
'header_candidates': [
{
'header_tokens': ['ab-100', 'ea', '10'],
'column_centers': [0.1225, 0.2825, 0.4225],
'column_width_ratios': [0.1611, 0.0722, 0.1167],
},
{
'header_tokens': ['item', 'no', 'qty'],
'column_centers': [0.1225, 0.2825, 0.4225],
'column_width_ratios': [0.1611, 0.0722, 0.1167],
},
],
}],
},
}
result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout)
assert result.status == 'unique_match'
assert result.candidates[0].dimension_states['header_semantic_position'] == 'matched'
def test_profile_matcher_rejects_incomplete_compacted_projection_as_evidence_insufficient():
"""没有候选表头事实的压缩投影不得仅凭页面和表框自动命中。"""
complete_layout = _layout()
profile = _profile('PO_A')
profile['definition']['document_match']['required_anchors'] = []
profile = _with_signature(profile, complete_layout)
compacted_layout = {
'tables': complete_layout['tables'],
'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']},
'matching_features': {
'version': 'v1',
'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1},
'tables': [{'bbox': [0.05, 0.25, 0.95, 0.95]}],
},
}
result = match_frozen_coordinate_profiles(profiles=[profile], layout=compacted_layout)
assert result.status == 'evidence_insufficient'
def test_profile_matcher_prefers_current_glyphs_to_persisted_projection():
"""当前 Layout 有完整 glyph 时,错误持久化投影不得覆盖实时证据。"""
layout = _layout()
profile = _with_signature(_profile('PO_A'), layout)
layout['matching_features'] = {
'version': 'v1',
'page_structure': {'aspect_ratio': 200 / 280, 'page_count': 1, 'table_count': 1},
'tables': [{'bbox': [0.05, 0.25, 0.95, 0.95], 'header_candidates': [{
'header_tokens': ['unrelated'], 'column_centers': [.8], 'column_width_ratios': [.1],
}]}],
}
result = match_frozen_coordinate_profiles(profiles=[profile], layout=layout)
assert result.status == 'unique_match'
assert result.candidates[0].dimension_states['column_topology'] == 'matched'
def test_profile_matcher_reports_only_missing_anchor_identifiers():
"""缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。"""
profile = _profile('PO_A')
@@ -11,6 +11,8 @@ from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from app.services.shipping_notice.order_review_field_conflict_service import (
project_review_case_evidence_issues,
project_review_case_field_conflicts,
@@ -94,6 +96,140 @@ def test_project_review_case_field_conflicts_empty_without_candidate():
assert project_review_case_field_conflicts(case) == []
def test_project_review_case_keeps_open_legacy_single_value_conflict_visible(monkeypatch):
"""资格层仍阻断的遗留单值 Finding 不得被投影静默丢弃。"""
candidate = SimpleNamespace(
conflicts_json=[{
'conflict_key': '0:unit_price',
'field': 'unit_price',
'line_index': 0,
'severity': 'blocking',
'reason': 'field_conflict',
'values': ['1731.60'],
}],
structured_result_json={},
)
case = SimpleNamespace(
candidate_id=1,
current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]),
)
from app.services.shipping_notice import order_review_field_conflict_service as svc
monkeypatch.setattr(svc, '_candidate_for_case', lambda _case: candidate)
monkeypatch.setattr(svc, 'current_open_candidate_conflicts', lambda _candidate: list(candidate.conflicts_json))
items = project_review_case_field_conflicts(case)
assert len(items) == 1
assert items[0]['field_code'] == 'unit_price'
assert items[0]['conflict_key'] == '0:unit_price'
@pytest.mark.pure_unit
def test_project_review_case_field_conflicts_uses_complete_finding_source_evidence():
"""正文补充真冲突必须直接展示 PDF/邮件值与来源,不能因缺 Observation 而消失。"""
candidate = SimpleNamespace(
conflicts_json=[{
'conflict_key': '0:unit_price',
'field': 'unit_price',
'line_index': 0,
'scope': 'line',
'severity': 'blocking',
'reason': 'supplement_field_conflict',
'resolution_status': 'unresolved',
'values': ['1731.60', '1732.00'],
'sources': [
{'source_type': 'pdf', 'raw_value': '1731.60', 'document_id': 305, 'evidence_ref': {'page_no': 1}},
{'source_type': 'email_body', 'raw_value': '1732.00', 'document_id': 304, 'evidence_ref': {'row_index': 5}},
],
}],
structured_result_json={},
)
case = SimpleNamespace(
candidate_id=1,
current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]),
)
from app.services.shipping_notice import order_review_field_conflict_service as svc
original = svc._candidate_for_case
svc._candidate_for_case = lambda _case: candidate
try:
items = project_review_case_field_conflicts(case)
finally:
svc._candidate_for_case = original
assert len(items) == 1
assert items[0]['conflict_key'] == '0:unit_price'
assert [option['display_value'] for option in items[0]['options']] == ['1731.60', '1732.00']
assert [option['evidence_role'] for option in items[0]['options']] == ['primary_pdf', 'context']
assert [option['document_id'] for option in items[0]['options']] == [305, 304]
@pytest.mark.pure_unit
def test_project_review_case_finding_with_pdf_source_is_marked_primary_pdf():
"""补充合并的 PDF 来源未附原始 source_type 时,面板仍须标识其为主 PDF。"""
candidate = SimpleNamespace(
conflicts_json=[{
'conflict_key': '0:unit_price', 'field': 'unit_price', 'line_index': 0,
'severity': 'blocking', 'reason': 'supplement_field_conflict',
'values': ['1', '2'],
'sources': [
{'source_type': 'pdf', 'raw_value': '1', 'document_id': 305, 'evidence_ref': {}},
{'source_type': 'email_body', 'raw_value': '2', 'document_id': 304, 'evidence_ref': {}},
],
}],
structured_result_json={},
)
case = SimpleNamespace(
candidate_id=1,
current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]),
)
from app.services.shipping_notice import order_review_field_conflict_service as svc
original = svc._candidate_for_case
svc._candidate_for_case = lambda _case: candidate
try:
items = project_review_case_field_conflicts(case)
finally:
svc._candidate_for_case = original
assert items[0]['options'][0]['evidence_role'] == 'primary_pdf'
@pytest.mark.pure_unit
def test_project_review_case_legacy_supplement_evidence_gap_is_visible_not_a_blank_panel():
"""历史补充冲突证据不足必须投影为可见证据问题,不能静默阻断资格。"""
candidate = SimpleNamespace(
conflicts_json=[{
'conflict_key': '-1:unit_price',
'field': 'unit_price',
'severity': 'blocking',
'reason': 'supplement_conflict_evidence_insufficient',
'resolution_status': 'unresolved',
'scope': 'unscoped',
'recovery_action': 'reparse_current_pdf',
}],
structured_result_json={},
)
case = SimpleNamespace(current_draft=None)
from app.services.shipping_notice import order_review_field_conflict_service as svc
original = svc._candidate_for_case
svc._candidate_for_case = lambda _case: candidate
try:
conflicts, evidence_issues = svc._project_review_case_candidate_findings(case)
finally:
svc._candidate_for_case = original
assert conflicts == []
assert evidence_issues == [{
'conflict_key': '-1:unit_price', 'field_code': 'unit_price', 'line_index': None,
'line_key': None, 'scope': 'unscoped', 'severity': 'blocking',
'reason': 'supplement_conflict_evidence_insufficient', 'options': [],
'observation_ids': [], 'recovery_action': 'reparse_current_pdf',
}]
def test_project_review_findings_deduplicate_evidence_gaps_and_keep_them_out_of_value_conflicts():
"""同键证据缺失只能保留一项,并与多值字段冲突分区展示。"""
candidate = SimpleNamespace(
@@ -155,6 +291,34 @@ def test_project_review_findings_deduplicate_evidence_gaps_and_keep_them_out_of_
assert [item['scope'] for item in evidence_issues] == ['unscoped', 'line']
def test_project_review_findings_omits_optional_line_no_evidence_gap():
"""line_no 非必填且可派生时,历史证据缺失不得继续显示为待确认。"""
candidate = SimpleNamespace(
conflicts_json=[{
'field': 'line_no',
'severity': 'blocking',
'reason': 'evidence_missing',
'owning_gate_code': 'field_completeness',
}],
structured_result_json={
'extraction': {'field_adjudication': {
'blocked_fields': [],
'decisions': [{'field_code': 'line_no', 'status': 'derived', 'reason_code': 'derived'}],
}},
},
)
case = SimpleNamespace(candidate_id=1, current_draft=SimpleNamespace(lines_json=[]))
from app.services.shipping_notice import order_review_field_conflict_service as svc
original = svc._candidate_for_case
svc._candidate_for_case = lambda _case: candidate
try:
assert project_review_case_evidence_issues(case) == []
finally:
svc._candidate_for_case = original
def test_sync_review_gates_replaces_stale_missing_field_gate_with_field_conflict():
"""草稿字段已齐全时,Gate 必须通过完整性并把最新证据冲突归属到字段冲突门禁。"""
case = SimpleNamespace(
@@ -101,3 +101,110 @@ def test_resume_waiting_manual_confirm_when_auto_gate_false(monkeypatch):
assert result['auto_gate_allowed'] is False
assert result['task_created'] is False
assert case.status == 'ready'
@pytest.mark.pure_unit
def test_resume_enqueues_auto_create_when_draft_validation_is_eligible(monkeypatch):
"""保存并校验在所有 Gate 通过时必须入队 STP,而非停在 ready。"""
case = _case(can_build=True, can_auto_create=True, validation_status='ready')
monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case)
monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None)
monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: [])
monkeypatch.setattr(svc, 'record_fulfillment_audit', lambda **_kw: None)
monkeypatch.setattr(svc.db.session, 'flush', lambda: None)
monkeypatch.setattr(svc.db.session, 'commit', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_projection.serialize_review_case',
lambda _c: {'case_no': case.case_no, 'status': case.status},
)
monkeypatch.setattr(
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
lambda **_kw: {'status': 'queued', 'job_id': 91, 'idempotency_key': 'stp-91'},
)
result = svc.resume_after_review_change(
user_id=7,
case_no=case.case_no,
trigger='draft_validated',
skip_validate=True,
allow_auto_create=True,
)
assert result['outcome'] == 'auto_create_enqueued'
assert result['auto_gate_allowed'] is True
assert result['stp_enqueue'] == {'status': 'queued', 'job_id': 91, 'idempotency_key': 'stp-91'}
def test_resume_auto_confirms_unique_customer_before_validating(monkeypatch):
"""保存校验时必须先确认唯一客户候选,再执行 Draft 校验。"""
case = _case(can_build=True, can_auto_create=False, validation_status='ready')
calls = []
monkeypatch.setattr(svc, '_reload_case', lambda **_kw: case)
monkeypatch.setattr(svc, '_persist_candidate_qualification', lambda _c: None)
monkeypatch.setattr(svc, '_invalidate_downstream_if_needed', lambda **_kw: [])
monkeypatch.setattr(
'app.services.shipping_notice.order_review_auto_progress_coordinator.auto_confirm_unique_customer_for_review_case',
lambda **_kw: calls.append('customer') or {'status': 'auto_confirmed', 'customer_id': 5555},
)
monkeypatch.setattr(
svc,
'validate_draft',
lambda **_kw: calls.append('validate') or {'status': 'ready'},
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
lambda **_kw: None,
)
monkeypatch.setattr(svc.db.session, 'flush', lambda: None)
monkeypatch.setattr(svc.db.session, 'commit', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.order_review_projection.serialize_review_case',
lambda _c: {'case_no': case.case_no},
)
svc.resume_after_review_change(
user_id=7,
case_no=case.case_no,
trigger='draft_validated',
skip_validate=False,
)
assert calls == ['customer', 'validate']
def test_validate_draft_api_delegates_versioned_validation_to_resume_coordinator(app, monkeypatch):
"""保存校验 API 不可绕过协调器,必须传递乐观锁版本。"""
from app.api.workspace import shipping_notice as api
from app.services.shipping_notice import order_review_resume_service
user = SimpleNamespace(id=7)
calls = []
def fake_resume(**kwargs):
calls.append(kwargs)
return {
'case': {'case_no': kwargs['case_no']},
'outcome': 'blocked',
'gate_recalculated': True,
}
monkeypatch.setattr(api, '_require_user', lambda: user)
monkeypatch.setattr(order_review_resume_service, 'resume_after_review_change', fake_resume)
with app.test_request_context(
'/shipping-notice/order-review-cases/CASE-API/draft/validate',
method='POST',
json={'expected_draft_version': 12},
):
response, status = api.workspace_validate_shipping_order_review_draft('CASE-API')
assert status == 200
assert response.get_json()['data']['case'] == {'case_no': 'CASE-API'}
assert calls == [{
'user_id': 7,
'case_no': 'CASE-API',
'trigger': 'draft_validated',
'change_type': None,
'skip_validate': False,
'allow_auto_create': True,
'expected_draft_version': 12,
}]
@@ -24,13 +24,17 @@ from app.models import (
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
ShippingOrderCandidate,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
ShippingOrderReviewStream,
ShippingOrderReviewCaseEvent,
ShippingOrderReviewConfirmedRevision,
ShippingOrderReviewWaveLine,
ShippingOrderSchemaVersion,
ShippingNotice,
ShippingCustomer,
User,
)
from app.services.shipping_notice.order_review_projection import (
@@ -294,7 +298,7 @@ def test_review_queue_projects_each_case_po_and_lifecycle_stage(app):
assert item['po_number'] == 'PO-QUEUE-001'
assert item['lifecycle_stage'] == 'order_review'
assert [entry['state'] for entry in item['lifecycle_entries']] == [
'available', 'current', 'unavailable', 'unavailable',
'available', 'current', 'unavailable', 'unavailable', 'unavailable',
]
@@ -334,7 +338,7 @@ def test_review_queue_uses_formal_task_lifecycle_stage(app):
assert item['po_number'] == 'PO-QUEUE-002'
assert item['lifecycle_stage'] == 'fulfillment_prep'
assert [entry['state'] for entry in item['lifecycle_entries']] == [
'available', 'available', 'current', 'unavailable',
'available', 'available', 'current', 'unavailable', 'unavailable',
]
@@ -401,6 +405,32 @@ def _materialized_run(*, user, agent, session, intake):
return run
def test_review_case_summary_exposes_only_failed_intake_retry_authorization(app):
"""当前阶段卡只消费服务端 parse_failed 的 SNI 编号与 retry_parse 授权。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-INTAKE-RETRY')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
case = ensure_run_review_cases(run=run)[0]
intake.parse_status = 'parse_failed'
db.session.commit()
failed = serialize_review_run(run)['items'][0]
# 关键断言:失败节点提供原 SNI 和 retry_parse;不需要重新上传或前端猜测。
assert failed['intake_no'] == intake.intake_no
assert failed['available_actions'] == ['retry_parse']
intake.parse_status = 'parsing'
db.session.commit()
parsing = serialize_review_run(run)['items'][0]
# 关键断言:运行中只能等待 Worker 超时回收,不能显示冲突重试动作。
assert parsing['available_actions'] == []
intake.parse_status = 'cancelled'
db.session.commit()
cancelled = serialize_review_run(run)['items'][0]
assert cancelled['available_actions'] == []
def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'reservation-id') -> None:
"""
为 Review 就绪路径测试注入行级 catch-all 库存源规则。
@@ -419,6 +449,51 @@ def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'res
db.session.commit()
def _seed_confirmed_bill_to_for_candidate(*, candidate, run, intake, user) -> None:
"""
为机器 Candidate 补齐可继承的 Bill-to 确认事实。
核心逻辑:确认服务只从 Candidate 关联的来源 Extraction 复制已确认客户;不能以
Candidate 摘要中的状态替代冻结所需的可审计客户事实。
"""
customer = ShippingCustomer(
standard_name='Review Test Customer',
short_code='REV',
)
db.session.add(customer)
db.session.flush()
extraction = ShippingOrderExtraction(
run_id=int(run.id),
intake_id=int(intake.id),
schema_version_id=int(run.schema_version_id),
input_snapshot_hash=str(run.input_snapshot_hash or ''),
input_snapshot_json={'source': 'review_test_customer_confirmation'},
status='accepted',
normalized_result_json={},
validation_result_json={},
created_by_id=int(user.id),
)
db.session.add(extraction)
db.session.flush()
candidate.order_extraction_id = int(extraction.id)
db.session.add(ShippingOrderCustomerMatch(
extraction_id=int(extraction.id),
role='bill_to',
raw_name=customer.standard_name,
normalized_name='REVIEW TEST CUSTOMER',
status='confirmed',
customer_id=int(customer.id),
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
identity_fingerprint='f' * 64,
identity_rule_version='order-customer-fingerprint.v1',
identity_components_json={'role': 'bill_to'},
resolution_method='manual',
confirmation_reason='测试确认',
confirmed_by_id=int(user.id),
))
def test_reservation_summary_reads_current_draft_value_before_async_validation():
"""合法预约号已保存但校验 Job 未落投影时,右栏不得误报缺失。"""
case = SimpleNamespace(
@@ -516,6 +591,42 @@ def test_reservation_summary_reads_machine_value_before_async_validation():
assert result['lines'][0]['effective_reservation_id'] == '33874'
def test_reservation_summary_does_not_leak_inventory_block_reason():
"""Reservation 面板不得展示同一明细的库存路由阻断原因。"""
case = SimpleNamespace(
run=SimpleNamespace(input_snapshot_json={
'schema': {'definition': {'fields': [{
'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line',
}]}}},
),
current_draft=SimpleNamespace(
validation_result_json={
'status': 'needs_review',
'line_projections': [{
'line_key': 'line-1',
'effective_reservation_id': None,
'can_build': False,
'block_reason': 'no_inventory_source_candidates',
}],
'issues': [{
'code': 'effective_reservation_missing',
'line_index': 0,
'owning_gate_code': 'reservation_validation',
'severity': 'blocking',
}],
},
lines_json=[],
),
)
result = project_review_case_reservation(case)
# 关键断言:库存路由码只能留在库存 Gate,Reservation 行应显示自身缺失原因。
assert result['lines'][0]['block_reason'] == 'effective_reservation_missing'
assert result['lines'][0]['block_reason'] != 'no_inventory_source_candidates'
assert result['lines'][0]['needs_attention'] is True
def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candidate_readonly(app):
"""同一 PDF 重入只保留一个 Case/Draft,草稿复制机器快照但不改写 Candidate。"""
with app.app_context():
@@ -634,7 +745,7 @@ def test_candidate_gate_reconciliation_supersedes_active_legacy_attempt(app):
gate_code='document_materialization',
trigger_type='system_requeue', actor_type='system', actor_id='test',
idempotency_key='candidate-supersedes-active-attempt',
input_snapshot={'action_code': 'retry_with_latest_rules'},
input_snapshot={'action_code': 'rematerialize_document'},
)
mark_attempt_running(attempt_id=attempt.id, worker_id='test')
from app.services.shipping_notice.process_gate_bridge import reconcile_extraction_gates_for_review_case
@@ -951,11 +1062,20 @@ def test_review_read_api_returns_safe_owner_scoped_projection(app):
token = issue_local_access_token(user)
headers = {'Authorization': f'Bearer {token}'}
run_response = client.get(f'/api/workspace/shipping-notice/order-extraction-runs/{run.run_no}/review', headers=headers)
queue_response = client.get(f'/api/workspace/shipping-notice/order-review-queue/{run.run_no}', headers=headers)
case_response = client.get(f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}', headers=headers)
# 关键断言:列表和详情仅给 owner 返回 Case/Draft 安全投影,不输出原始文本或对象存储信息。
assert run_response.status_code == 200
assert queue_response.status_code == 200
assert case_response.status_code == 200
# 关键断言:慢切换读取必须返回查找/投影边界,供浏览器 HAR 精确定位,不泄露业务内容。
assert 'review_lookup' in run_response.headers.get('Server-Timing', '')
assert 'review_projection' in run_response.headers.get('Server-Timing', '')
assert 'queue_lookup' in queue_response.headers.get('Server-Timing', '')
assert 'queue_projection' in queue_response.headers.get('Server-Timing', '')
assert 'case_lookup' in case_response.headers.get('Server-Timing', '')
assert 'case_projection' in case_response.headers.get('Server-Timing', '')
assert case.case_no in str(run_response.get_json())
body = case_response.get_json()
assert 'extracted_text' not in str(body)
@@ -1768,6 +1888,63 @@ def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(a
raise AssertionError('superseded case must not be reparsed')
def test_successful_document_reparse_reconciles_only_activated_replacement_case(app, monkeypatch):
"""PDF 重识别成功切换当前版本后,必须补触发新版 Case 的统一自动推进。"""
with app.app_context():
from app.services.shipping_notice import order_review_disposition_service as disposition
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-PROGRESS')
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
source_case = ensure_run_review_cases(run=source)[0]
transition_order_extraction_run(source, target_status='processing')
transition_order_extraction_run(source, target_status='review_required', result={})
replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other')
ensure_order_extraction_plan(replacement)
for unit in replacement.extraction_plan.units:
unit.status = 'candidate_ready'
replacement_case = ensure_run_review_cases(run=replacement)[0]
reconciled = []
monkeypatch.setattr(
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
'reconcile_single_case_for_auto_progress',
lambda **kwargs: reconciled.append(kwargs) or {'enqueue_status': 'queued'},
)
finalize_document_reparse(run=replacement, succeeded=True)
assert reconciled == [{
'case': replacement_case,
'trigger': 'document_reparse_succeeded',
'refresh_validation': True,
}]
def test_document_reparse_does_not_reconcile_when_stream_activation_is_rejected(app, monkeypatch):
"""Stream 冲突或已确认旧版本拒绝切换时,不得推进晚到的新版草稿。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REPARSE-AUTO-CONFLICT')
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
source_case = ensure_run_review_cases(run=source)[0]
mark_review_stream_confirmed(case=source_case)
transition_order_extraction_run(source, target_status='processing')
transition_order_extraction_run(source, target_status='review_required', result={})
replacement, _ = reparse_case_document(user_id=user.id, case_no=source_case.case_no, reason='other')
ensure_order_extraction_plan(replacement)
for unit in replacement.extraction_plan.units:
unit.status = 'candidate_ready'
ensure_run_review_cases(run=replacement)
reconciled = []
monkeypatch.setattr(
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
'reconcile_single_case_for_auto_progress',
lambda **kwargs: reconciled.append(kwargs),
)
finalize_document_reparse(run=replacement, succeeded=True)
assert reconciled == []
def test_run_auto_progress_ignores_legacy_open_case_that_is_not_stream_current(app):
"""Run 级协调只能处理文件 Stream 当前 Case,不能重启残留旧版本。"""
with app.app_context():
@@ -1925,6 +2102,8 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
schema['definition'] = definition
snapshot['schema'] = schema
run.input_snapshot_json = snapshot
# 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。
db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition
unit = run.extraction_plan.units[0]
unit.result_json = {'orders': [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-CONFIRM'}]}], 'lines': [{'fields': [
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
@@ -1941,6 +2120,12 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
},
)
db.session.add(machine)
_seed_confirmed_bill_to_for_candidate(
candidate=machine,
run=run,
intake=intake,
user=user,
)
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
# 确认建单要求 Candidate 已绑定 OT(BE-01);测试显式物化。
@@ -2016,17 +2201,26 @@ def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutati
schema['definition'] = definition
snapshot['schema'] = schema
run.input_snapshot_json = snapshot
# 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。
db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition
unit = run.extraction_plan.units[0]
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [
{'field_id': 'part-id', 'observations': [{'value': 'A002'}]},
{'field_id': 'qty-id', 'observations': [{'value': '3'}]},
{'field_id': 'reservation-id', 'observations': [{'value': '3000092918'}]},
]}]}]}
db.session.add(ShippingOrderCandidate(
machine = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-CONFIRM-REPLAY', intake_id=intake.id, primary_document_id=document.id,
candidate_key='machine-confirm-replay', order_extraction_run_id=run.id,
structured_result_json={'customer': {'resolution_status': 'confirmed'}},
))
)
db.session.add(machine)
_seed_confirmed_bill_to_for_candidate(
candidate=machine,
run=run,
intake=intake,
user=user,
)
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
@@ -2312,6 +2506,8 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app):
schema['definition'] = definition
snapshot['schema'] = schema
run.input_snapshot_json = snapshot
# 冻结建单以 SchemaVersion 为事实源;输入快照仅保留审计副本,测试必须同步两者。
db.session.get(ShippingOrderSchemaVersion, int(run.schema_version_id)).definition_json = definition
unit = run.extraction_plan.units[0]
# 行 A 完整;行 B 缺 qty → 整单 needs_review,但 A 应可先行。
unit.result_json = {'orders': [{'header_fields': [], 'lines': [
@@ -2325,11 +2521,18 @@ def test_partial_wave_ignores_incomplete_sibling_and_allows_second_wave(app):
{'field_id': 'reservation-id', 'observations': [{'value': '3000092902'}]},
]},
]}]}
db.session.add(ShippingOrderCandidate(
machine = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-MULTI-WAVE', intake_id=intake.id, primary_document_id=document.id,
candidate_key='machine-multi-wave', order_extraction_run_id=run.id,
structured_result_json={'customer': {'resolution_status': 'confirmed'}},
))
)
db.session.add(machine)
_seed_confirmed_bill_to_for_candidate(
candidate=machine,
run=run,
intake=intake,
user=user,
)
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
@@ -2456,3 +2659,17 @@ def test_assert_exact_duplicate_excludes_same_case_wave_tasks(app):
)
assert exc.value.code == 'SHIPPING.NOTICE_EXACT_DUPLICATE'
del agent, session, intake
def test_unvalidated_draft_is_not_projected_as_build_blocked(app):
"""未执行校验的 Draft 必须保持 not_validated,不能伪造成 can_build=false。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='UNVALIDATED-PROJECTION')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
case = ensure_review_case_for_unit(run=run, unit=unit)
db.session.flush()
detail = serialize_review_case(case)
eligibility = detail['draft']['build_eligibility']
assert eligibility['status'] == 'not_validated'
assert eligibility['can_build'] is None
@@ -1279,6 +1279,85 @@ def test_optional_non_key_field_evidence_missing_is_diagnostic_only(app):
assert diagnostic[0].get('user_visible') is False
def test_optional_table_coordinate_diagnostic_does_not_block_auto_create(app):
"""表格诊断命中可选列时,只能保留诊断,不能把它写入 blocked_fields。"""
with app.app_context():
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
line_no = service.save_field({'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, 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)
line_no_cfg = _config(line_no['id'], '行号', value_type='string')
line_no_cfg.update({'required': False, 'auto_create_key_field': False})
published = _save_and_publish(draft, [
line_no_cfg,
_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='q' * 64, documents=documents, actor_id=actor_id,
layout_candidates_by_document={
int(document.id): [{'reason': 'layout_table_needs_review', 'field_codes': ['line_no']}],
},
)
# 关键断言:可选行号的坐标问题不影响自动建单资格,但审计诊断必须保留。
assert 'line_no' not in (result.get('blocked_fields') or [])
finding = next(item for item in result['findings'] if item.get('field_code') == 'line_no')
assert finding['severity'] == 'diagnostic'
assert finding['blocks_current_action'] is False
def test_accepted_key_field_is_not_blocked_by_unaccepted_table_mapping(app):
"""关键字段已有当前可验证证据时,整表坐标诊断不能覆盖字段事实。"""
with app.app_context():
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
unit_price = service.save_field({'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
price_cfg = _config(unit_price['id'], '单价', value_type='decimal')
price_cfg.update({'auto_create_key_field': True, 'minimum_confidence': 0.9})
published = _save_and_publish(draft, [price_cfg])
intake_id, documents, actor_id = _seed_documents()
document = documents[1]
document.extracted_text = 'Unit Price 898.72'
result = persist_dynamic_order(
raw_order={
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
'header_fields': [],
'lines': [{'fields': [{'field_id': unit_price['id'], 'observations': [{
'value': '898.72', 'document_id': document.id,
'quote': 'Unit Price 898.72', 'confidence': 1.0,
}]}]}],
},
intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id,
layout_candidates_by_document={
int(document.id): [{
'mapping_status': 'candidate',
'rows': [{'role': 'data', 'fields': [{
'field_id': unit_price['id'], 'value': '898.72',
'cell_id': 'price-cell', 'evidence_ref': 'layout:price-cell',
}]}],
}],
},
)
# 关键断言:表格映射未被接受仍保留诊断,但已接受的单价证据不得被重新阻断。
assert 'unit_price' not in (result.get('blocked_fields') or [])
finding = next(item for item in result['findings'] if item.get('field_code') == 'unit_price')
assert finding['severity'] == 'diagnostic'
assert finding['blocks_current_action'] is False
def test_key_field_quality_issue_still_blocks(app):
"""auto_create_key_field 字段证据不足必须进入 blocked_fields(即使 required=false)。"""
with app.app_context():
@@ -19,11 +19,13 @@ from app.services.shipping_notice.progress_audit_contract import (
def test_order_task_progress_audit_event_types_frozen():
"""契约冻结:OT 进度三类事件码齐全。"""
"""契约冻结:OT 进度及投影一致性事件码齐全。"""
assert ORDER_TASK_PROGRESS_AUDIT_EVENT_TYPES == frozenset({
'order_task_created',
'order_task_updated',
'order_task_progress_changed',
'shipping_processing_projection_inconsistent',
'shipping_processing_task_ownership_mismatch',
})
@@ -114,3 +116,29 @@ def test_sync_order_task_processing_state_noop_skips_audit(app):
).count()
assert after_count == before_count
assert int(ot.progress_version or 1) == version
def test_sync_order_task_processing_state_can_bump_for_review_projection(app):
"""Review Gate 变化即使不改 stage/status,也必须推进 Projection 版本。"""
with app.app_context():
ot = _seed_user_and_task('OT-PROGRESS-AUDIT-3')
version = int(ot.progress_version or 1)
sync_order_task_processing_state(
ot,
force_progress_bump=True,
reason_code='review_gate_changed',
source='test_review_projection',
)
db.session.commit()
assert int(ot.progress_version or 1) == version + 1
event = (
ShippingAuditEvent.query.filter_by(
event_type='order_task_progress_changed',
aggregate_id=ot.task_no,
)
.order_by(ShippingAuditEvent.id.desc())
.first()
)
assert event is not None
assert event.reason_code == 'review_gate_changed'
@@ -186,7 +186,7 @@ def test_confirm_notice_create_failure_rolls_back_without_orphan_notice(app):
notice_before = ShippingNotice.query.count()
with patch(
'app.services.shipping_notice.order_review_confirmation_service.resolve_shipping_case_for_new_task',
'app.services.shipping_notice.order_task_service.link_notice_to_order_task',
side_effect=ConflictError('simulated notice create failure', code='SHIPPING.SIMULATED_NOTICE_FAIL'),
):
with pytest.raises(ConflictError) as exc_info:
+46 -3
View File
@@ -105,7 +105,7 @@ def test_enqueue_automark_rejects_annotation_when_current_layout_checksum_change
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
profile = SimpleNamespace(id=12, status='draft', definition_json={'main_table_id': 'table-1'})
annotation = SimpleNamespace(table_id='table-1', layout_version_id=88, layout_payload_checksum='a' * 64)
annotation = SimpleNamespace(id=71, document_id=77, table_id='table-1')
document = SimpleNamespace(
id=77,
current_layout_version_id=88,
@@ -125,12 +125,22 @@ def test_enqueue_automark_rejects_annotation_when_current_layout_checksum_change
'get',
lambda model, _ident: document if model is service.ShippingOrderDocument else None,
)
from app.services.shipping_notice import order_document_profile_service as profile_service
monkeypatch.setattr(
profile_service,
'require_profile_sample_automark_ready',
lambda **_kwargs: (_ for _ in ()).throw(ValidationError(
'Profile sample layout is stale',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE',
)),
)
monkeypatch.setattr(service, 'enqueue', lambda *_args, **_kwargs: 9001)
with pytest.raises(ValidationError) as caught:
enqueue_pdf_automark(12, document_id=77, table_id='table-1', schema_version_id=3, page_no=1, actor_id=1)
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
# Layout 身份不一致必须使用可操作的 stale 错误码,不能退化为泛化配置错误。
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE'
def test_execute_automark_rejects_job_after_document_layout_reparse(monkeypatch):
@@ -591,6 +601,33 @@ def test_automark_exposes_acroform_widget_as_independent_visual_candidate():
assert 'value_binding' not in widget_candidate['binding']
def test_automark_merges_same_field_same_geometry_sources():
"""关键断言:同字段同页同坐标的 PDF 与 Widget 候选只生成一个画布框。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
candidates = [
{
'candidate_id': 'pdf-1', 'candidate_kind': 'field_binding',
'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': {
'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}},
'evidence_sources': ['pdf_coordinate'], 'needs_review': True,
},
{
'candidate_id': 'widget-1', 'candidate_kind': 'field_binding',
'binding': {'field_id': 'f-po', 'field_code': 'customer_po_number', 'scope': 'header', 'visual_binding': {
'page_no': 1, 'normalized_bbox': {'x0': .1, 'y0': .2, 'x1': .3, 'y1': .4},
}},
'evidence_sources': ['acroform_widget'], 'needs_review': True,
},
]
merged = service._merge_duplicate_field_binding_candidates(candidates)
assert len(merged) == 1
assert merged[0]['evidence_sources'] == ['pdf_coordinate', 'acroform_widget']
def test_automark_keeps_unmatched_acroform_widget_as_unbound_visual_candidate(monkeypatch):
"""Widget 技术名未匹配 Schema 时仍可供人工框选,禁止自动猜业务字段。"""
from app.services.shipping_notice import order_document_profile_pdf_automark_service as service
@@ -717,7 +754,11 @@ def test_automark_enriches_widget_table_candidate_with_coordinate_header_text():
coordinate.suggest_order_field_layouts.return_value = {'order_field_candidates': []}
widget_geometry = {
'table_region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .8},
'subrow_layouts': [{'row_offset': 0, 'column_boundaries': [0, .25, 1]}],
# 动态 XFA 的表头控件有展示值时,Widget 聚类会把表头带误判为候选行。
'subrow_layouts': [{
'row_offset': 0, 'column_boundaries': [0, .25, 1],
'region': {'x0': .1, 'y0': .15, 'x1': .9, 'y1': .2},
}],
'header_regions': [], 'status': 'needs_review',
}
with patch('app.services.shipping_notice.order_document_profile_pdf_automark_service._profile', return_value=profile), patch(
@@ -741,6 +782,8 @@ def test_automark_enriches_widget_table_candidate_with_coordinate_header_text():
assert field['field_code'] == 'line_no'
assert field['region'] == {'x0': .1, 'y0': .15, 'x1': .3, 'y1': .2}
assert field['evidence_sources'] == ['acroform_widget_geometry', 'pdf_coordinate']
# 已确认的表头带不得同时作为可保存的 Widget 明细行。
assert widget_candidate['payload']['subrow_layouts'] == []
def test_automark_marks_opencv_and_native_structure_conflict_for_review():
@@ -82,6 +82,16 @@ def test_gate_action_contract_rejects_inventory_reroute_for_excel_gate():
) is True
def test_inventory_preparation_allows_reload_existing_result_without_rpa():
"""RPA 超时后可重读已有库存结果;该动作仅属于库存准备 Gate。"""
assert action_belongs_to_gate(
gate_code='inventory_preparation', action_code='reload_inventory_result',
) is True
assert action_belongs_to_gate(
gate_code='inventory_matching', action_code='reload_inventory_result',
) is False
def test_inventory_sufficiency_actions_keep_business_specific_labels():
"""库存缺口恢复必须保留精确业务动作,禁止客户端降级为统一“重试”。"""
assert action_presentation('open_shortage_review') == {
@@ -106,13 +116,13 @@ def test_fulfillment_action_presentation_declares_lifecycle_surface():
)['target_surface'] == 'fulfillment_prep'
assert action_presentation(
'retry_freight_upload_rpa', gate_code='freight_upload_rpa',
)['target_surface'] == 'upload_complete'
)['target_surface'] == 'freight_upload'
assert action_presentation(
'regenerate_manual_upload_todo', gate_code='manual_upload_handoff',
)['target_surface'] == 'upload_complete'
)['target_surface'] == 'freight_upload'
assert action_presentation(
'mark_manual_uploaded', gate_code='manual_upload_handoff',
)['target_surface'] == 'upload_complete'
)['target_surface'] == 'freight_upload'
def test_manual_upload_handoff_authorizes_excel_regeneration_at_artifact_anchor():
@@ -140,7 +150,7 @@ def test_gate_action_presentation_declares_ui_dispatch_without_frontend_action_c
'label_key': 'workspace.shippingNotice.processGate.actionCodes.mark_manual_uploaded',
'kind': 'current_gate',
'dispatch': 'dialog',
'ui_handler': 'manual_upload_evidence',
'ui_handler': 'manual_upload_confirmation',
}
assert action_presentation('confirm_customer') == {
'code': 'confirm_customer',
@@ -187,61 +197,6 @@ def test_field_quality_block_eligibility():
assert field_quality_may_block(required=False, auto_create_key_field=False) is False
def test_projection_marks_apx_gate_as_readonly_without_executable_actions(app, monkeypatch):
"""APX 历史 Gate 只可审计展示,不能再投影为可恢复业务 Gate。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
gate = SimpleNamespace(
id=1, gate_code='inventory_candidates_calculated', sequence_no=1,
status='pending', evaluation_version=1, input_fingerprint=None,
blocking_reason_code=None, blocking_reason_json=None,
recommendation_json=None, effective_result_json={}, findings_json=None,
next_action_code=None, passed_at=None, invalidated_at=None,
latest_attempt_id=None,
)
monkeypatch.setattr(
projection.ShippingProcessGateAttempt.query,
'get',
lambda _id: None,
raising=False,
)
payload = projection.serialize_process_gate(gate, include_diagnostics=False)
assert payload['gate_code'] == 'inventory_candidates_calculated'
assert payload['legacy_readonly'] is True
assert payload['allowed_actions'] == []
assert payload['recovery_targets'] == []
assert len(PROCESS_GATE_DEFINITIONS) == 20
def test_user_gate_summary_marks_apx_execution_readonly(app, monkeypatch):
"""APX Execution 不能向用户下发主动作或恢复目标。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='APX-1', status='blocked', current_gate_code='inventory_candidates_calculated',
last_passed_gate_code=None, primary_next_action_code=None, responsible_party='system',
lock_version=1, review_case_id=None, task_id=1, updated_at=None,
)
gate = SimpleNamespace(
id=1, gate_code='inventory_candidates_calculated', sequence_no=1, status='blocked_retryable',
evaluation_version=1, input_fingerprint=None, blocking_reason_code='inventory_candidates_required',
blocking_reason_json=None, recommendation_json=None, effective_result_json={},
next_action_code=None, passed_at=None, invalidated_at=None, latest_attempt_id=None,
)
query = projection.ShippingProcessGate.query
monkeypatch.setattr(query, 'filter_by', lambda **_kwargs: query)
monkeypatch.setattr(query, 'order_by', lambda *_args: query)
monkeypatch.setattr(query, 'all', lambda: [gate])
monkeypatch.setattr(projection.ShippingProcessGateAttempt.query, 'get', lambda _id: None, raising=False)
summary = projection.project_user_gate_summary(execution)
assert summary['status'] == 'legacy_readonly'
assert summary['legacy_readonly'] is True
assert summary['next_action_code'] is None
assert summary['allowed_actions'] == []
def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technical(app, monkeypatch):
"""库存匹配技术重试被隐藏时,跨阶段 RecoveryPlan 仍必须保留人工复核入口。"""
from types import SimpleNamespace
@@ -488,6 +443,43 @@ def test_inventory_preparation_exposes_only_rpa_retry(app, monkeypatch):
assert summary['allowed_actions'] == ['retry_inventory_preparation']
def test_inventory_rpa_timeout_prefers_reload_existing_result(app, monkeypatch):
"""RPA 超时先重读已落盘结果,不能把主按钮直接指向新的 RPA 请求。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-INVENTORY-TIMEOUT', status='blocked',
current_gate_code='inventory_preparation',
primary_next_action_code='retry_inventory_preparation',
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-INVENTORY-TIMEOUT', 'status': 'blocked',
'primary_next_action_code': 'retry_inventory_preparation',
'responsible_party': 'worker', 'recovery_targets': [],
'active_recovery_plans': [], 'gates': [],
'current_gate': {
'gate_code': 'inventory_preparation', 'status': 'blocked_retryable',
'blocking_reason_code': 'inventory_rpa_timeout',
'next_action_code': 'retry_inventory_preparation', 'evaluation_version': 3,
},
},
)
summary = projection.project_user_gate_summary(execution)
assert summary['next_action_code'] == 'reload_inventory_result'
assert summary['primary_action']['code'] == 'reload_inventory_result'
assert summary['allowed_actions'] == [
'reload_inventory_result',
'retry_inventory_preparation',
]
def test_user_gate_summary_exposes_manual_gate_evidence_and_rpa_retry(app, monkeypatch):
"""Gate 20 保持凭据登记主动作,并显式下发可选 RPA 重试。"""
from types import SimpleNamespace
@@ -558,12 +550,12 @@ def test_manual_upload_handoff_projects_evidence_confirmation_as_primary_action(
'mark_manual_uploaded',
'retry_freight_upload_rpa',
]
assert summary['primary_action']['target_surface'] == 'upload_complete'
assert summary['primary_action']['target_surface'] == 'freight_upload'
assert summary['primary_action']['target_anchor'] == 'manual_upload'
def test_manual_upload_handoff_projects_excel_recovery_at_artifact_anchor(app, monkeypatch):
"""跨 Gate Excel 恢复必须采用 RecoveryPlan 的位置,不能继承 Gate 20 的上传位置。"""
def test_manual_upload_handoff_hides_excel_regeneration_for_single_notice(app, monkeypatch):
"""同一 Notice 只能有一个 Excel,上传阶段不得投影重生入口。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
@@ -588,16 +580,10 @@ def test_manual_upload_handoff_projects_excel_recovery_at_artifact_anchor(app, m
},
},
)
monkeypatch.setattr(projection, '_excel_regeneration_allowed', lambda **_: True)
summary = projection.project_user_gate_summary(execution)
regeneration = next(
item for item in summary['action_presentation']
if item['code'] == 'regenerate_excel_artifact'
)
assert regeneration['target_surface'] == 'fulfillment_prep'
assert regeneration['target_anchor'] == 'excel_artifact'
assert 'regenerate_excel_artifact' not in summary['allowed_actions']
assert all(item['code'] != 'regenerate_excel_artifact' for item in summary['action_presentation'])
def test_inventory_source_gate_summary_exposes_no_manual_selection_action(app, monkeypatch):
@@ -1,10 +1,9 @@
"""
tests/test_shipping_process_gate_recovery_action_contract.py
用途:锁定 Gate 恢复动作投影「单一裁决」契约——库存 RPA 失败统一下发
「重新获取库存」(retry_inventory_preparation),不再因 inventory_preparation
Gate 的 responsible_party='worker' 被历史「worker/retry_ 技术动作屏蔽」规则
降级为人工上传入口 (upload_inventory_file)。
用途:锁定 Gate 恢复动作投影「单一裁决」契约——库存 RPA 超时/耗尽优先下发
「重新读取库存结果」(reload_inventory_result),其他失败下发「重新获取库存」
(retry_inventory_preparation),不再被历史 worker 技术动作屏蔽规则降级为人工上传入口。
依赖:process_gate_projection._resolve_recovery_next_action。
逻辑:pure_unit 纯单测(不建 Flask/DB);以阻断原因码 / Gate 状态为输入,
@@ -59,12 +58,10 @@ def test_inventory_file_empty_blocked_manual_resolves_to_retry():
@pytest.mark.parametrize('reason', [
'inventory_file_empty',
'inventory_preparation_failed',
'inventory_rpa_timeout',
'inventory_rpa_login_failed',
'inventory_rpa_export_failed',
'inventory_file_identity_mismatch',
'inventory_file_missing',
'inventory_rpa_exhausted',
])
def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason):
"""全部库存 RPA 失败原因(无论 blocked_manual / blocked_retryable)均下发「重新获取库存」。"""
@@ -79,14 +76,15 @@ def test_all_inventory_rpa_retry_reasons_expose_retry_action(reason):
@pytest.mark.pure_unit
def test_inventory_rpa_exhausted_falls_back_to_manual_upload():
"""历史耗尽码仍允许用户手动重新获取库存。"""
@pytest.mark.parametrize('reason', ['inventory_rpa_timeout', 'inventory_rpa_exhausted'])
def test_inventory_rpa_timeout_or_exhausted_prefers_reload_existing_result(reason):
"""超时或耗尽先重读已有结果,不能直接新开 RPA Attempt。"""
full, blocking = _mk(
{'gate_code': 'inventory_preparation', 'status': 'blocked_manual',
'blocking_reason_code': 'inventory_rpa_exhausted'},
'blocking_reason_code': reason},
)
action, _ = _resolve_recovery_next_action(blocking=blocking, full=full, execution=None)
assert action == 'retry_inventory_preparation'
assert action == 'reload_inventory_result'
@pytest.mark.pure_unit
@@ -225,6 +223,84 @@ def test_inventory_preparation_waiting_keeps_refresh_action():
assert action == 'poll_inventory_preparation'
def test_reload_inventory_result_reuses_snapshot_without_triggering_rpa(app, monkeypatch):
"""重新读取库存结果只复用快照,不能触发新的库存 RPA。"""
from app.models import ShippingNotice
from app.services.shipping_notice import process_gate_executor as executor
task = SimpleNamespace(task_no='SN-RELOAD-1')
execution = SimpleNamespace(task_id=7)
calls: list[tuple[str, object]] = []
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
lambda _task: {'source_code': 'DSV360_AWSDU'},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot',
lambda received_task, source, *, mode: calls.append((mode, (received_task, source))) or {'status': 'ok'},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa',
lambda *_args, **_kwargs: pytest.fail('reload must not trigger RPA'),
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
lambda _task: 'inventory_rpa_timeout',
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_kwargs: calls.append(('sync', _kwargs)),
)
with app.app_context():
outcome = executor._handle_reload_inventory_result(
execution=execution,
gate=SimpleNamespace(gate_code='inventory_preparation'),
payload={'actor_user_id': 3},
)
assert outcome['outcome'] == 'passed'
assert calls[0][0] == 'reload_result'
assert calls[1][0] == 'sync'
def test_reload_inventory_result_keeps_timeout_blocked_when_snapshot_missing(app, monkeypatch):
"""无可复用快照时保持超时阻断,不能隐式改为重新触发 RPA。"""
from app.models import ShippingNotice
from app.services.shipping_notice import process_gate_executor as executor
task = SimpleNamespace(task_no='SN-RELOAD-MISSING')
execution = SimpleNamespace(task_id=7)
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
lambda _task: {'source_code': 'DSV360_AWSDU'},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot',
lambda *_args, **_kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa',
lambda *_args, **_kwargs: pytest.fail('reload must not trigger RPA'),
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
lambda _task: 'inventory_rpa_timeout',
)
with app.app_context():
outcome = executor._handle_reload_inventory_result(
execution=execution,
gate=SimpleNamespace(gate_code='inventory_preparation'),
payload={},
)
assert outcome['outcome'] == 'blocked_retryable'
assert outcome['blocking_reason_code'] == 'inventory_rpa_timeout'
@pytest.mark.pure_unit
def test_no_blocking_returns_no_action():
"""无当前阻断时不下发给任何主恢复动作。"""
@@ -998,41 +998,6 @@ def test_legacy_workspace_forwarding_audit_is_structured(app):
}
def test_apx_runtime_audit_is_read_only_and_counts_active_states(app):
"""APX 清点只读统计运行中记录,不修改历史 Execution/Job。"""
from app import db
from app.models import Job, ShippingNotice, ShippingProcessExecution
from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state
task = ShippingNotice(task_no='SN-APX-AUDIT')
db.session.add(task)
db.session.flush()
active = ShippingProcessExecution(
execution_no='APX-20260811-ACTIVE', task_id=task.id, status='active',
current_gate_code='inventory_snapshots_ready',
)
historical = ShippingProcessExecution(
execution_no='APX-20260811-HIST', task_id=task.id, status='completed',
current_gate_code='inventory_matched',
)
db.session.add_all([active, historical])
db.session.flush()
job = Job(
domain='shipping_notice', job_type='shipping_auto_progress', task_id=task.id,
execution_id=active.id, status='queued', business_ref='APX-20260811-ACTIVE',
)
db.session.add(job)
db.session.commit()
result = audit_apx_runtime_state()
assert result['execution']['active_count'] == 1
assert result['execution']['historical_count'] == 1
assert result['job']['active_count'] == 1
assert ShippingProcessExecution.query.filter_by(id=active.id).one().status == 'active'
assert Job.query.filter_by(id=job.id).one().status == 'queued'
def test_inventory_mapping_is_versioned_and_immutable_by_shape():
"""Mapping 必须按文件+版本唯一,旧版本通过 superseded_by_id 留谱系。"""
assert 'uq_shipping_inventory_mapping_file_version' in _unique_names(ShippingInventoryMapping)
@@ -1117,71 +1082,48 @@ def test_current_inventory_rematch_shortage_completes_recovery_plan():
assert plan.completed_at is not None
def test_excel_regeneration_completion_preserves_manual_upload_gate():
"""跨 Gate Excel 重生完成后,当前 Gate 20 必须继续等待人工上传且计划可关闭。"""
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
class Plan:
status = 'queued'
action_code = 'regenerate_excel_artifact'
resume_after_gate = 'manual_upload_handoff'
started_at = None
completed_at = None
failure_code = None
failure_detail_json = None
plan = Plan()
complete_recovery_plan_for_attempt(
plan=plan,
outcome='blocked_manual',
business_result_code='manual_upload_pending',
)
assert plan.status == 'succeeded'
assert plan.completed_at is not None
def test_manual_upload_excel_regeneration_returns_to_manual_handoff(monkeypatch):
"""Gate 20 触发 Excel 重生后,执行器必须作废旧产物并保持人工上传阻断。"""
def test_excel_regeneration_rejects_existing_notice_artifact(monkeypatch):
"""已有 Excel 时不能在同一 Notice 重生,必须创建新的 Notice。"""
from types import SimpleNamespace
from app.models import ShippingExportArtifact, ShippingNotice
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
invalidated = {}
task = SimpleNamespace(id=1, task_no='SN-ONE-EXCEL')
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
monkeypatch.setattr(
'app.services.shipping_notice.recovery_invalidation_service.invalidate_excel_regeneration_only',
lambda **kwargs: invalidated.update(kwargs) or {'artifacts': [10], 'uploads': [11]},
ShippingExportArtifact,
'query',
SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=10))),
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
lambda _payload: {'status': 'ok'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._task_payload',
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
lambda _payload: pytest.fail('existing Artifact must not be regenerated'),
)
outcome = _handle_regenerate_excel(
execution=SimpleNamespace(execution_no='SPE-EXCEL-HANDOFF', task_id=1),
gate=SimpleNamespace(gate_code='manual_upload_handoff'),
payload={'attempt_id': 3, 'actor_user_id': 9},
payload={'actor_user_id': 9},
)
assert invalidated['attempt_id'] == 3
assert outcome['outcome'] == 'blocked_manual'
assert outcome['blocking_reason_code'] == 'manual_upload_pending'
assert outcome['output_snapshot']['invalidation']['artifacts'] == [10]
assert outcome['blocking_reason_code'] == 'notice_excel_already_generated'
def test_artifact_excel_regeneration_failure_resyncs_artifact_gate(monkeypatch):
"""Excel 生成失败后必须重投影 artifact Gate,不能沿用上传阶段。"""
from types import SimpleNamespace
from app.models import ShippingExportArtifact, ShippingNotice
from app.services.shipping_notice.process_gate_executor import _handle_regenerate_excel
synced = []
task = SimpleNamespace(id=1, task_no='SN-FIRST-EXCEL')
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
monkeypatch.setattr(
ShippingExportArtifact,
'query',
SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: None)),
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.generate_excel',
lambda _payload: {'status': 'failed', 'message': 'template unavailable'},
@@ -108,7 +108,7 @@ def test_inventory_shortage_gate_projects_a_user_visible_blocking_reason():
def test_normalize_unknown_action_codes():
"""未知 / 别名动作码映射到契约或丢弃。"""
assert normalize_action_code('retry_failed_documents') == 'retry'
assert normalize_action_code('retry_failed_documents') == 'retry_failed_documents'
assert normalize_action_code('open_fulfillment') == 'view_result'
assert normalize_action_code('not_a_real_action') is None
@@ -165,7 +165,10 @@ def test_download_excel_requires_excel_ready_fact():
with_ready = derive_available_actions(
status='blocked',
stage='freight_uploading',
gate={'next_action_code': 'wait_manual_upload'},
gate={
'gate_code': 'manual_upload_handoff',
'next_action_code': 'wait_manual_upload',
},
excel_ready=True,
)
assert 'download_excel' in with_ready
@@ -223,9 +226,11 @@ def test_map_notice_to_processing_status_stage_domain_mapping():
)
uploaded = SimpleNamespace(
id=None,
current_step='', upload_status='uploaded', export_file_path=None,
)
assert map_notice_to_processing_status_stage(uploaded) == ('completed', 'completed')
# 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。
assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading')
waiting = SimpleNamespace(
current_step='', upload_status='pending', export_file_path='/x.xlsx',
@@ -254,8 +259,8 @@ def test_map_notice_unknown_status_fail_closed():
assert map_notice_to_processing_status_stage(unknown) == ('blocked', 'waiting_review')
def test_derive_available_actions_blocked_without_retry_gate():
"""BE-04: business blocked without retry Gate must not append retry."""
def test_derive_available_actions_without_gate_fails_closed():
"""BE-04: no Gate and no object authorization must not invent an action."""
from app.services.shipping_notice.processing_projection_invariants import (
derive_available_actions,
)
@@ -270,12 +275,11 @@ def test_derive_available_actions_blocked_without_retry_gate():
},
excel_ready=False,
)
assert 'retry' not in actions
assert 'open_inventory_source_review' in actions
assert actions == []
def test_derive_available_actions_failed_adds_retry():
"""BE-04: technical failed should allow retry by default."""
def test_derive_available_actions_failed_without_gate_does_not_add_retry():
"""BE-04: failed status alone cannot authorize a generic retry."""
from app.services.shipping_notice.processing_projection_invariants import (
derive_available_actions,
)
@@ -286,7 +290,7 @@ def test_derive_available_actions_failed_adds_retry():
gate=None,
excel_ready=False,
)
assert 'retry' in actions
assert actions == ['view_result']
def test_retryable_projection_uses_technical_failure_reason_mapping():
@@ -475,8 +479,8 @@ def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action():
assert payload['available_actions'] == ['retry_inventory_preparation']
def test_waiting_human_reconcile_action_uses_projected_available_actions():
"""人工阻断存在统一对账动作时,主动作必须从当前投影动作列表中安全选取。"""
def test_waiting_human_reconcile_action_uses_gate_action():
"""人工阻断的统一对账动作必须由正式 Gate 明确下发。"""
payload = apply_user_projection_fields({
'status': 'waiting_review',
'stage': 'inventory_matching',
@@ -484,11 +488,12 @@ def test_waiting_human_reconcile_action_uses_projected_available_actions():
'gate_code': 'inventory_candidates_calculated',
'status': 'blocked',
'blocking_reason_code': 'inventory_candidates_required',
'next_action_code': 'reconcile_and_progress',
},
'available_actions': ['reconcile_and_progress', 'view_details'],
'available_actions': ['view_details'],
})
# 关键断言:该分支不得因未定义局部变量返回 500,且必须选中统一恢复入口。
# 关键断言:只能选中 Gate 明示的统一恢复入口。
assert payload['user_status'] == 'waiting_human'
assert payload['primary_action']['code'] == 'reconcile_and_progress'
@@ -27,6 +27,10 @@ from app.models import (
ShippingOrderCandidate,
ShippingOrderProcessingUnit,
ShippingOrderSubmission,
ShippingOrderTask,
ShippingNotice,
ShippingProcessExecution,
ShippingProcessGate,
User,
)
from app.services.file_assets.service import upload_file_asset
@@ -34,10 +38,13 @@ from app.services.shipping_notice.intake_service import create_shipping_notice_i
from app.services.shipping_notice.progress_audit_contract import (
DIRECT_PDF_ALLOWED_STAGES,
)
from app.services.shipping_notice.reconciliation_projector import (
project_case_primary_action,
)
from app.services.shipping_notice.shipping_processing_projection import (
_aggregate_eml_order_task_work_items,
_batch_file_counts,
_batch_four_stage_nodes,
_batch_lifecycle_nodes,
_batch_ui_state_from_items,
_conversation_processing_from_work_items,
_display_work_items_from_current_files,
@@ -45,6 +52,7 @@ from app.services.shipping_notice.shipping_processing_projection import (
_processing_ui_state_from_item,
_project_order_task_work_item,
map_run_status_to_processing_status,
project_conversation_processing_summary,
map_run_to_processing_stage,
project_conversation_processing_items,
project_intake_work_item,
@@ -94,28 +102,58 @@ def test_map_run_status_to_processing_status() -> None:
assert map_run_status_to_processing_status('unknown') == 'processing'
def test_waiting_human_case_promotes_authorized_create_draft_as_primary_action() -> None:
"""待人工的无草稿文件必须下发创建草稿,作为文件行唯一业务入口。"""
action = project_case_primary_action(
'waiting_human',
{'code': None, 'i18n_key': None, 'details': None},
['view', 'create_draft', 'validate'],
'order_review',
)
# 已授权的下一项业务操作不能被裁决为空,否则文件行没有可执行入口。
assert action == {
'code': 'create_draft',
'variant': 'primary',
'label_key': 'shipping.actions.create_draft',
}
def test_waiting_human_case_promotes_authorized_edit_draft_as_primary_action() -> None:
"""待人工的已有草稿文件必须下发编辑草稿,而不是重复阶段导航。"""
action = project_case_primary_action(
'waiting_human',
{'code': None, 'i18n_key': None, 'details': None},
['view', 'edit_draft', 'validate'],
'order_review',
)
# 编辑草稿是当前文件的业务入口,validate 仍留在工作台底栏执行。
assert action == {
'code': 'edit_draft',
'variant': 'primary',
'label_key': 'shipping.actions.edit_draft',
}
@pytest.mark.parametrize(
('stage', 'expected_lifecycle_stage'),
('gate_code', 'expected_lifecycle_stage'),
[
('inventory_preparation', 'fulfillment_prep'),
('inventory_candidates_calculated', 'fulfillment_prep'),
('inventory_candidates_frozen', 'fulfillment_prep'),
('inventory_snapshots_ready', 'fulfillment_prep'),
('inventory_matched', 'fulfillment_prep'),
('excel_generated', 'fulfillment_prep'),
('upload_receipt_recorded', 'upload_complete'),
('inventory_matching', 'fulfillment_prep'),
('artifact_generation', 'fulfillment_prep'),
('freight_upload_rpa', 'freight_upload'),
],
)
def test_batch_four_stage_nodes_maps_auto_progress_gate_stages(
stage: str,
def test_batch_lifecycle_nodes_maps_formal_gate_stages(
gate_code: str,
expected_lifecycle_stage: str,
) -> None:
"""自动推进 Gate 的真实阶段码必须归入对应四阶段,不能回退到接收解析。"""
nodes = _batch_four_stage_nodes([{
'stage': stage,
'user_stage': stage,
"""正式 Gate 必须归入对应五阶段,不能依赖历史技术阶段码。"""
nodes = _batch_lifecycle_nodes([{
'status': 'running',
'user_status': 'running',
'current_gate': {'gate_code': gate_code},
}])
summaries = {node['code']: node['summary']['total'] for node in nodes}
@@ -126,28 +164,19 @@ def test_batch_four_stage_nodes_maps_auto_progress_gate_stages(
@pytest.mark.parametrize(
('item', 'expected_lifecycle_stage'),
[
({'user_stage': 'inventory_match'}, 'fulfillment_prep'),
({'user_stage': 'freight_upload'}, 'upload_complete'),
({'user_stage': 'customer_resolving'}, 'order_review'),
({'user_stage': 'duplicate_checking'}, 'order_review'),
({'user_stage': 'waiting_human_review'}, 'order_review'),
# Case bundle 已归一化为业务阶段时,批次摘要与生命周期入口必须直接识别,
# 不能错误落入 unclassified 并禁用订单复核入口。
({'user_stage': 'order_review'}, 'order_review'),
# 正式 Gate 是当前业务位置,必须覆盖尚未同步的历史技术 stage。
({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'fulfillment_prep'),
({'stage': 'document_parsing', 'user_current_gate_code': 'inventory_matching'}, 'fulfillment_prep'),
# 无 Gate 时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段。
({'blocking_reason': {'code': 'inventory_file_missing'}}, 'fulfillment_prep'),
({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'),
],
)
def test_batch_four_stage_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases(
def test_batch_lifecycle_nodes_uses_formal_gate_or_owning_reason(
item: dict[str, object],
expected_lifecycle_stage: str,
) -> None:
"""批次四阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。"""
nodes = _batch_four_stage_nodes([{
"""批次五阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。"""
nodes = _batch_lifecycle_nodes([{
**item,
'status': 'waiting_human',
'user_status': 'waiting_human',
@@ -158,6 +187,42 @@ def test_batch_four_stage_nodes_prefers_formal_gate_and_maps_legacy_stage_aliase
assert summaries['intake_parse'] == (1 if expected_lifecycle_stage == 'intake_parse' else 0)
def test_batch_lifecycle_nodes_without_formal_fact_is_unclassified() -> None:
"""未知旧阶段保持未分类,不能凭空映射到某个业务工作面。"""
nodes = _batch_lifecycle_nodes([{
'status': 'waiting_human',
'user_status': 'waiting_human',
'user_stage': 'inventory_match',
}])
assert all(node['summary']['total'] == 0 for node in nodes)
@pytest.mark.parametrize(
('user_stage', 'expected_lifecycle_stage'),
[
('candidate_creating', 'intake_parse'),
('waiting_review', 'order_review'),
('inventory_preparation', 'fulfillment_prep'),
('manual_upload_handoff', 'freight_upload'),
],
)
def test_batch_lifecycle_nodes_maps_persisted_processing_stages(
user_stage: str,
expected_lifecycle_stage: str,
) -> None:
"""无 Gate 的当前文件仍须按已写入阶段完整归入五阶段,不能静默丢失。"""
nodes = _batch_lifecycle_nodes([{
'status': 'waiting_human',
'user_status': 'waiting_human',
'user_stage': user_stage,
}])
summaries = {node['code']: node['summary']['total'] for node in nodes}
assert summaries[expected_lifecycle_stage] == 1
assert sum(summaries.values()) == 1
def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> None:
"""通知准备未完成时通知完成必须由后端裁决为不可进入,不能由前端自行限制。"""
fulfillment_state = _processing_ui_state_from_item({
@@ -177,6 +242,7 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'order_review', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'fulfillment_prep', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
]
assert fulfillment_state['primary_action']['execution_mode'] == 'navigate'
@@ -201,40 +267,6 @@ def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> N
'target_lifecycle_stage': 'fulfillment_prep',
}]
legacy_view_state = _processing_ui_state_from_item({
'user_status': 'waiting_human',
'user_stage': 'waiting_review',
'source_summary': {'candidate_count': 1},
'run_no': 'SNER-LIFECYCLE-VIEW',
'case_no': 'SNRC-LIFECYCLE-VIEW',
'root_order_task_no': 'OT-LIFECYCLE-VIEW',
# 历史 Review 投影仍可能下发 view;它与 view_result 一样只是后端已授权的查看入口。
'available_actions': ['view'],
})
assert legacy_view_state['secondary_actions'] == [{
'code': 'view',
'enabled': True,
'execution_mode': 'navigate',
'target_surface': 'order_lifecycle_workbench',
'target_lifecycle_stage': 'order_review',
}]
review_state = _processing_ui_state_from_item({
'user_status': 'waiting_human',
'user_stage': 'waiting_review',
'source_summary': {'candidate_count': 1},
'run_no': 'SNER-REVIEW',
'case_no': 'SNRC-REVIEW',
'root_order_task_no': 'OT-REVIEW',
'available_actions': [],
})
assert review_state['lifecycle_entries'] == [
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'order_review', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
]
def test_processing_ui_state_exposes_shared_gate_authority() -> None:
"""批次投影须标明正式 Gate 裁决,不能让旧 technical stage 覆盖库存准备阶段。"""
@@ -358,6 +390,33 @@ def test_failed_run_overrides_stale_unit_review_stage_for_eml_leaf(app) -> None:
assert leaves[0]['primary_action'] is None
def test_eml_leaf_preserves_case_business_action_instead_of_replacing_it_with_navigation(app) -> None:
"""EML 文件行必须保留 Case 裁决的真实动作,五阶段入口已单独承担导航。"""
from tests.test_shipping_order_extraction_runs import _seed_run_input
with app.app_context():
_user, _agent, _session, intake, document = _seed_run_input(suffix='EML-KEEP-ACTION')
leaves = _eml_aggregate_document_children(
intake=intake,
order_task_children=[{
'work_item_type': 'order_task',
'work_item_no': 'DOCUMENT:KEEP-ACTION',
'case_no': 'SORC-KEEP-ACTION',
'current_gate': {'gate_code': 'order_review_build'},
'primary_action': {
'code': 'create_draft',
'variant': 'primary',
'label_key': 'shipping.actions.create_draft',
},
'available_actions': ['create_draft'],
'source_summary': {'document_id': document.id},
}],
)
assert leaves[0]['primary_action']['code'] == 'create_draft'
def test_intake_candidate_context_ignores_superseded_candidate(app) -> None:
"""历史 Candidate 只能审计,不能重新打开当前文件的生命周期入口。"""
with app.app_context():
@@ -478,42 +537,47 @@ def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(ap
def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_summary() -> None:
"""四阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。"""
"""五阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。"""
projection = _conversation_processing_from_work_items([
{
'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW',
'root_order_task_no': 'OT-REVIEW', 'source_type': 'direct_pdf',
'source_summary': {'document_id': 1, 'filename': 'review.pdf'},
'user_status': 'waiting_human', 'user_stage': 'waiting_review',
'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW',
'root_order_task_no': 'OT-REVIEW', 'source_type': 'direct_pdf',
'source_summary': {'document_id': 1, 'filename': 'review.pdf'},
'user_group': 'waiting_human',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'current_gate': {'gate_code': 'field_completeness', 'status': 'blocked'},
'blocking_reason': {'code': 'order_review_required'},
'available_actions': [],
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-UNKNOWN',
'root_order_task_no': 'OT-UNKNOWN', 'source_type': 'direct_pdf',
'source_summary': {'document_id': 2, 'filename': 'unknown.pdf'},
'user_status': 'running', 'user_stage': 'unmapped_legacy_stage',
'root_order_task_no': 'OT-UNKNOWN', 'source_type': 'direct_pdf',
'source_summary': {'document_id': 2, 'filename': 'unknown.pdf'},
'user_group': 'unclassified',
'user_status': 'running', 'user_stage': 'unmapped_legacy_stage',
'available_actions': [],
},
])
nodes = {node['code']: node for node in projection['four_stage_nodes']}
nodes = {node['code']: node for node in projection['lifecycle_nodes']}
assert nodes['order_review']['status'] == 'blocked'
assert nodes['intake_parse']['status'] == 'pending'
assert projection['unclassified_summary'] == {'count': 1}
def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None:
"""同一 EML 的两份订单 PDF 应在四阶段摘要中计为两项,而非一张父卡。"""
nodes = _batch_four_stage_nodes([{
def test_batch_lifecycle_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None:
"""同一 EML 的两份订单 PDF 应在五阶段摘要中计为两项,而非一张父卡。"""
nodes = _batch_lifecycle_nodes([{
'work_item_type': 'order_task',
'work_item_no': 'INTAKE:SNI-DOUBLE',
'source_type': 'eml',
'user_group': 'waiting_human',
'user_status': 'waiting_human',
'user_stage': 'order_review',
'aggregate_children': [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-1',
'user_group': 'waiting_human',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'current_gate': {'gate_code': 'field_completeness'},
'blocking_reason': {'code': 'required_field_missing'},
@@ -521,6 +585,7 @@ def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_roo
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-2',
'user_group': 'waiting_human',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'current_gate': {'gate_code': 'field_completeness'},
'blocking_reason': {'code': 'required_field_missing'},
@@ -535,19 +600,21 @@ def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_roo
assert order_review['summary']['needs_action'] == 2
def test_batch_four_stage_nodes_deduplicates_a_document_to_its_latest_projection() -> None:
def test_batch_lifecycle_nodes_deduplicates_a_document_to_its_latest_projection() -> None:
"""同一 PDF 的历史失败投影不能与当前通知准备投影重复计数或覆盖当前阶段。"""
nodes = _batch_four_stage_nodes([
{
'work_item_type': 'order_task', 'work_item_no': 'OT-OLD',
'user_status': 'failed', 'user_stage': 'document_parsing',
nodes = _batch_lifecycle_nodes([
{
'work_item_type': 'order_task', 'work_item_no': 'OT-OLD',
'user_group': 'failed',
'user_status': 'failed', 'user_stage': 'document_parsing',
'last_activity_at': '2026-08-15T09:00:00Z',
'blocking_reason': {'code': 'intake_parse_failed'},
'source_summary': {'document_id': 401, 'filename': 'same.pdf'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
{
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
'user_group': 'waiting_human',
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
'last_activity_at': '2026-08-15T10:00:00Z',
'blocking_reason': {'code': 'inventory_match_failed'},
'source_summary': {'document_id': 401, 'filename': 'same.pdf'},
@@ -565,15 +632,17 @@ def test_batch_four_stage_nodes_deduplicates_a_document_to_its_latest_projection
def test_batch_file_counts_uses_the_same_current_file_representative_as_stage_summary() -> None:
"""同一 PDF 的历史失败项不能同时计入失败和当前处理中的文件数量。"""
work_items = [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-OLD',
'user_status': 'failed', 'user_stage': 'document_parsing',
{
'work_item_type': 'order_task', 'work_item_no': 'OT-OLD',
'user_group': 'failed',
'user_status': 'failed', 'user_stage': 'document_parsing',
'last_activity_at': '2026-08-15T09:00:00Z',
'source_summary': {'document_id': 501, 'filename': 'same.pdf'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
{
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
'user_group': 'waiting_human',
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
'last_activity_at': '2026-08-15T10:00:00Z',
'source_summary': {'document_id': 501, 'filename': 'same.pdf'},
},
@@ -593,15 +662,16 @@ def test_batch_stage_summary_uses_the_same_user_group_as_file_counts() -> None:
work_items = [{
'work_item_type': 'order_task',
'work_item_no': 'OT-GROUP-OVERRIDES-STATUS',
'user_group': 'waiting_human',
'user_status': 'running',
'user_stage': 'inventory_matching',
'user_group': 'waiting_human',
'user_status': 'running',
'user_stage': 'inventory_matching',
'current_gate': {'gate_code': 'inventory_matching', 'status': 'blocked'},
'source_summary': {'document_id': 502, 'filename': 'waiting.pdf'},
}]
assert _batch_file_counts(work_items)['waiting_human_files'] == 1
fulfillment = next(
node for node in _batch_four_stage_nodes(work_items)
node for node in _batch_lifecycle_nodes(work_items)
if node['code'] == 'fulfillment_prep'
)
assert fulfillment['summary']['needs_action'] == 1
@@ -632,6 +702,35 @@ def test_conversation_status_groups_use_the_same_current_file_representative() -
]
@pytest.mark.parametrize('terminal_status', ['cancelled', 'archived'])
def test_cancelled_or_archived_file_stays_in_history_and_out_of_completion_metrics(
app,
terminal_status: str,
) -> None:
"""取消或归档仅保留历史,不得进入会话完成、文件完成或第五阶段统计。"""
with app.app_context():
work_items = [{
'work_item_type': 'order_task',
'work_item_no': f'OT-{terminal_status.upper()}',
'user_group': terminal_status,
'user_status': terminal_status,
'user_stage': 'freight_uploading',
'status': terminal_status,
'stage': terminal_status,
'source_summary': {'document_id': 570, 'filename': 'history.pdf'},
}]
projection = _conversation_processing_from_work_items(work_items)
assert projection['summary']['completed'] == 0
assert projection['summary']['history'] == 1
assert projection['summary']['total_files'] == 0
assert projection['summary']['completed_files'] == 0
assert projection['status_groups']['completed'] == []
assert [row['user_task_no'] for row in projection['status_groups'][terminal_status]] == [
f'OT-{terminal_status.upper()}',
]
assert all(node['summary']['total'] == 0 for node in projection['lifecycle_nodes'])
def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> None:
"""历史失败项不得在互斥统计后仍抢走批次当前按钮。"""
work_items = [
@@ -667,17 +766,19 @@ def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() ->
def test_batch_file_counts_deduplicates_reparse_versions_by_content_hash() -> None:
"""重解析产生新 document_id 时,内容哈希相同的 PDF 仍只计当前一项。"""
work_items = [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-V1',
'user_status': 'failed', 'user_stage': 'document_parsing',
{
'work_item_type': 'order_task', 'work_item_no': 'OT-V1',
'user_group': 'failed',
'user_status': 'failed', 'user_stage': 'document_parsing',
'last_activity_at': '2026-08-15T09:00:00Z',
'source_summary': {
'document_id': 601, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64,
},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-V2',
'user_status': 'waiting_human', 'user_stage': 'order_review',
{
'work_item_type': 'order_task', 'work_item_no': 'OT-V2',
'user_group': 'waiting_human',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'last_activity_at': '2026-08-15T10:00:00Z',
'source_summary': {
'document_id': 602, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64,
@@ -694,6 +795,7 @@ def test_batch_file_counts_prefers_content_hash_over_different_root_document_ids
work_items = [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V1',
'user_group': 'failed',
'user_status': 'failed', 'user_stage': 'document_parsing',
'last_activity_at': '2026-08-15T09:00:00Z',
'source_summary': {
@@ -703,6 +805,7 @@ def test_batch_file_counts_prefers_content_hash_over_different_root_document_ids
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V2',
'user_group': 'waiting_human',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'last_activity_at': '2026-08-15T10:00:00Z',
'source_summary': {
@@ -997,8 +1100,139 @@ def test_eml_order_intake_uses_latest_run_unit_review_outcome_without_order_task
assert all(child['user_status'] == 'waiting_human' for child in item['aggregate_children'])
def test_summary_excludes_unqualified_supporting_attachment_from_lifecycle_counts(app) -> None:
"""未知支撑附件没有 Candidate、Case、OT 时不得进入五阶段或业务文件统计。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, intake, primary_document = _seed_run_input(
suffix='SUMMARY-SUPPORTING-ATTACHMENT',
)
intake.source_type = 'eml'
supporting_document = ShippingOrderDocument(
intake_id=intake.id,
document_type='attachment',
attachment_key='po-info.xlsx',
filename='PO_INFO.xlsx',
content_hash='s' * 64,
classification='unknown',
parse_status='empty',
order_extraction_status='completed',
)
db.session.add(supporting_document)
db.session.commit()
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
leaves = [
child
for rows in payload['conversation_processing']['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
]
# 关键断言:仅验证支撑附件已被排除;主业务文档的当前阶段可随解析状态演进。
assert int(primary_document.id) in {
int(child['source_summary']['document_id']) for child in leaves
}
assert int(supporting_document.id) not in {
int(child['source_summary']['document_id']) for child in leaves
}
def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app) -> None:
"""首屏摘要必须下发四个文件状态数,避免概览总数与状态数来自不同合同。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, intake, document = _seed_run_input(
suffix='SUMMARY-FILE-STATUS-COUNTS',
)
intake.source_type = 'eml'
document.order_extraction_status = 'failed'
document.order_extraction_error_code = 'processing_failed'
db.session.commit()
summary = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)['conversation_processing']['summary']
# 关键断言:总文件与四个互斥状态数同源,批次概览不能因缺字段降为全 0。
assert summary['total_files'] == 1
assert summary['failed_files'] == 1
assert summary['waiting_human_files'] == 0
assert summary['processing_files'] == 0
assert summary['completed_files'] == 0
def test_summary_formal_gate_overrides_stale_completed_order_task(app) -> None:
"""摘要必须以正式库存 Gate 覆盖旧 OT completed,不能误显示为货代上传。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, intake, document = _seed_run_input(
suffix='SUMMARY-FORMAL-GATE-OVERRIDE',
)
candidate = ShippingOrderCandidate(
candidate_no='CAND-SUMMARY-GATE', intake_id=intake.id,
primary_document_id=document.id, candidate_key='summary-gate',
candidate_status='accepted', po_number='PO-SUMMARY-GATE',
)
db.session.add(candidate)
db.session.flush()
order_task = ShippingOrderTask(
task_no='OT-SUMMARY-GATE', user_id=user.id, conversation_id=session.session_id,
intake_id=intake.id, candidate_id=candidate.id, status='completed', stage='completed',
)
db.session.add(order_task)
db.session.flush()
notice = ShippingNotice(
task_no='SN-SUMMARY-GATE', user_id=user.id, conversation_id=session.session_id,
order_task_id=order_task.id,
)
db.session.add(notice)
db.session.flush()
order_task.shipping_notice_id = notice.id
execution = ShippingProcessExecution(
execution_no='SPE-SUMMARY-GATE', task_id=notice.id, status='blocked',
current_gate_code='inventory_preparation', lock_version=1,
)
db.session.add(execution)
db.session.flush()
notice.active_process_execution_id = execution.id
db.session.add(ShippingProcessGate(
execution_id=execution.id, gate_code='inventory_preparation', sequence_no=11,
status='blocked_manual', evaluation_version=1, lock_version=1,
blocking_reason_code='inventory_rpa_timeout',
next_action_code='retry_inventory_preparation',
))
db.session.commit()
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
leaves = [
child
for rows in payload['conversation_processing']['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
]
leaf = next(child for child in leaves if child['source_summary']['document_id'] == document.id)
# 关键断言:正式 Gate 是阶段与用户状态真相,旧 OT completed 只能作为兼容字段。
assert leaf['ui_state']['lifecycle_stage'] == 'fulfillment_prep'
assert leaf['user_status'] == 'waiting_human'
assert leaf['blocking_reason']['code'] == 'inventory_rpa_timeout'
# 摘要批次状态必须复用同一待人工叶子裁决,聊天卡不得显示成系统处理中。
assert payload['conversation_processing']['ui_state']['status'] == 'waiting_human'
def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -> None:
"""待人工附件已有 Review Case 时,叶子 ui_state 必须给出进入订单处理动作。"""
"""接收解析 Case 在详情与首屏摘要中均以重解析作为文件主动作。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
@@ -1031,10 +1265,113 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -
{'code': 'intake_parse', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'order_review', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'freight_upload', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
]
assert leaf['intake_parse_authorized'] is True
summary_payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
summary_leaf = next(
child
for rows in summary_payload['conversation_processing']['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
if child['source_summary']['document_id'] == unit.document_id
)
# 首屏摘要不得把阶段导航 open_order_review 冒充为业务主动作;
# 否则前端隐藏导航后,用户将失去真实的重解析入口。
assert summary_leaf['ui_state']['primary_action']['code'] == 'reparse'
def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> None:
"""首屏摘要有有效 Candidate 的当前 Case 必须保留复核业务动作。"""
with app.app_context():
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, document = _seed_run_input(
suffix='SUMMARY-CANDIDATE-EDIT-DRAFT',
)
intake.source_type = 'eml'
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-SUMMARY-EDIT-DRAFT', intake_id=intake.id,
primary_document_id=document.id, candidate_key='summary-edit-draft',
order_extraction_run_id=run.id, is_current_version=True,
candidate_status='accepted', po_number='PO-SUMMARY-EDIT-DRAFT',
)
db.session.add(candidate)
db.session.flush()
review_case = ensure_run_review_cases(run=run)[0]
db.session.commit()
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
summary_leaf = next(
child
for rows in payload['conversation_processing']['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
if child['source_summary']['document_id'] == document.id
)
assert summary_leaf['case_no'] == review_case.case_no
# Draft 已存在时,文件行只能暴露当前订单复核的业务动作,不能回退成接收解析重试。
assert summary_leaf['ui_state']['primary_action']['code'] == 'edit_draft'
assert 'edit_draft' in summary_leaf['available_actions']
assert 'reparse' not in summary_leaf['available_actions']
def test_summary_leaf_uses_current_review_case_run_for_intake_parse_navigation(app) -> None:
"""摘要投影的接收解析深链必须把同一 Case 的 Run 一并下发。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
user, agent, session, intake, document = _seed_run_input(
suffix='SUMMARY-CASE-RUN-ANCHOR',
)
intake.source_type = 'eml'
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
unit.status = 'review_required'
unit.reason_code = 'coordinate_evidence_unavailable'
run.status = 'review_required'
run.phase = 'review_required'
review_case = ensure_review_case_for_unit(run=run, unit=unit)
db.session.commit()
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
rows = [
row
for group in payload['conversation_processing']['status_groups'].values()
for row in group
]
task = next(row for row in rows if row['user_task_no'] == f'INTAKE:{intake.intake_no}')
leaf = next(
child for child in task['aggregate_children']
if child['source_summary']['document_id'] == document.id
)
assert leaf['case_no'] == review_case.case_no
assert leaf['run_no'] == run.run_no
assert leaf['ui_state']['lifecycle_entries'][0] == {
'code': 'intake_parse',
'state': 'current',
'target_surface': 'order_lifecycle_workbench',
}
def test_eml_sibling_unit_failure_does_not_revoke_review_actions(app) -> None:
"""同一 Run 的失败 PDF 只能影响自身;两个待复核 PDF 仍必须保留后端裁决的入口。"""
@@ -1172,7 +1509,7 @@ def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document
def test_conversation_projection_is_the_complete_batch_display_source(app) -> None:
"""会话投影一次下发分组、EML 子文件、四阶段及 UI 动作,前端无需二次裁决。"""
"""会话投影一次下发分组、EML 子文件、五阶段及 UI 动作,前端无需二次裁决。"""
with app.app_context():
items = _aggregate_eml_order_task_work_items([
{
@@ -1183,10 +1520,12 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No
'source_summary': {
'document_id': 101, 'document_count': 1, 'filename': 'a.pdf',
'email_subject': 'FWD: Shanghai shipping notice',
},
'status': 'failed', 'stage': 'waiting_review',
'user_status': 'failed', 'user_stage': 'waiting_review',
'available_actions': ['retry_parse'],
},
'status': 'failed', 'stage': 'waiting_review',
'user_group': 'failed',
'user_status': 'failed', 'user_stage': 'waiting_review',
'current_gate': {'gate_code': 'field_completeness'},
'available_actions': ['retry_parse'],
'primary_action': {'code': 'retry_parse'},
'blocking_reason': {'code': 'intake_parse_failed'},
'facts': {'upload_state': 'not_created'},
@@ -1199,10 +1538,12 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No
'source_summary': {
'document_id': 102, 'document_count': 1, 'filename': 'b.pdf',
'email_subject': 'FWD: Shanghai shipping notice',
},
'status': 'processing', 'stage': 'document_parsing',
'user_status': 'running', 'user_stage': 'document_parsing',
'available_actions': [], 'facts': {'upload_state': 'not_created'},
},
'status': 'processing', 'stage': 'document_parsing',
'user_group': 'processing',
'user_status': 'running', 'user_stage': 'document_parsing',
'current_gate': {'gate_code': 'document_parsing'},
'available_actions': [], 'facts': {'upload_state': 'not_created'},
},
])
@@ -1216,7 +1557,7 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No
assert failed[0]['ui_state']['primary_action'] == {'code': 'retry_parse'}
assert projection['ui_state']['primary_action'] == {'code': 'retry_parse'}
assert projection['summary']['total_files'] == 2
assert projection['four_stage_nodes'][1] == {
assert projection['lifecycle_nodes'][1] == {
'code': 'order_review', 'label_key': 'order_review', 'status': 'blocked',
'summary': {
'total': 1,
@@ -1260,7 +1601,8 @@ def test_eml_aggregate_action_uses_the_same_priority_as_its_status(app) -> None:
'last_activity_at': '2026-08-14T00:00:00Z',
'source_summary': {'document_id': 201, 'document_count': 1, 'filename': 'waiting.pdf'},
'status': 'waiting_human', 'stage': 'waiting_review',
'user_status': 'waiting_human', 'user_stage': 'waiting_review',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'current_gate': {'gate_code': 'order_review', 'status': 'blocked'},
'blocking_reason': {'code': 'customer_confirmation_required'},
'primary_action': {'code': 'confirm_customer'},
'available_actions': ['confirm_customer'], 'facts': {'upload_state': 'not_created'},
@@ -1597,6 +1939,66 @@ def test_consumed_eml_stays_visible_until_an_eml_order_task_represents_it(app, s
)
def test_conversation_projection_prefetches_eml_attachments_once(app, shipping_user):
"""同一会话多个 EML 应一次加载附件集合,避免按邮件重复查询 Document。"""
with app.app_context():
conversation_id = f'conv-stage4-eml-prefetch-{uuid.uuid4().hex[:8]}'
intakes = []
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=9404):
for index in range(2):
created = create_shipping_notice_intake(
user_id=shipping_user.id,
asset_no=_upload_ready_asset(
shipping_user.id,
filename=f'mail-{index}.eml',
content=b'From: a@b.c\nSubject: PO\n\nbody',
),
upload_batch_id=str(uuid.uuid4()),
conversation_id=conversation_id,
)
intake = ShippingOrderIntake.query.filter_by(
intake_no=created['intake_no'],
).one()
intake.source_type = 'eml'
intake.parse_status = 'consumed'
intake.order_extraction_status = 'partially_completed'
intakes.append(intake)
for index, intake in enumerate(intakes):
db.session.add_all([
ShippingOrderDocument(
intake_id=int(intake.id), document_type='email_body',
attachment_key='__email_body__', filename=f'mail-{index}.eml',
content_hash=f'body-{index}', classification='email_context',
parse_status='parsed',
),
ShippingOrderDocument(
intake_id=int(intake.id), document_type='attachment',
attachment_key=f'po-{index}.pdf', filename=f'po-{index}.pdf',
content_hash=f'attachment-{index}', classification='order',
parse_status='parsed', order_extraction_status='not_started',
),
])
db.session.commit()
document_selects: list[str] = []
def _capture_document_selects(_conn, _cursor, statement, _parameters, _context, _executemany):
if re.search(r'\bfrom\s+shipping_order_documents\b', statement, re.IGNORECASE):
document_selects.append(statement)
event.listen(db.engine, 'before_cursor_execute', _capture_document_selects)
try:
payload = project_conversation_processing_items(
user_id=shipping_user.id,
conversation_id=conversation_id,
)
finally:
event.remove(db.engine, 'before_cursor_execute', _capture_document_selects)
assert payload['conversation_processing']['summary']['total_files'] == 2
assert len(document_selects) <= 1
def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, shipping_user):
"""
order_task 投影须填充 current_gate / candidate_count / po_number,禁止全空摘要。
@@ -1682,6 +2084,7 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship
assert item['source_summary']['filename'] == document.filename
def test_order_task_projection_uses_stream_current_case_for_gate_and_deep_link(app, shipping_user):
"""同一文件旧开放 Case 残留时,OT Gate 与深链只能取 Stream 当前 Case。"""
del shipping_user
@@ -1816,6 +2219,47 @@ def test_eml_aggregate_keeps_run_authorized_batch_reparse_action(app, shipping_u
assert 'reparse_batch' in displayed[0]['available_actions']
def test_conversation_projection_reparseability_read_path_does_not_lock(app, shipping_user):
"""会话 GET 判断批次动作时只能读,不得发出 FOR UPDATE。"""
del shipping_user
with app.app_context():
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, _agent, session, intake, _document = _seed_run_input(suffix='EML-BATCH-READ-ONLY')
run = _materialized_run(user=user, agent=_agent, session=session, intake=intake)
ensure_run_review_cases(run=run)
transition_order_extraction_run(run, target_status='processing')
transition_order_extraction_run(run, target_status='review_required', result={})
db.session.commit()
statements: list[str] = []
def _capture(_conn, _cursor, statement, _parameters, _context, _executemany):
statements.append(statement)
event.listen(db.engine, 'before_cursor_execute', _capture)
try:
with patch(
'app.services.shipping_notice.order_review_disposition_service.select_current_batch_reparse_cases',
side_effect=AssertionError('GET projection must not enter the locked write selector'),
):
_aggregate_eml_order_task_work_items([{
'work_item_type': 'order_task', 'work_item_no': 'OT-EML-READ-ONLY',
'source_type': 'eml', 'intake_no': intake.intake_no, 'run_no': run.run_no,
'status': 'review_required', 'stage': 'order_review', 'user_status': 'waiting_human',
'user_stage': 'order_review', 'user_group': 'waiting_human', 'last_activity_at': '',
'available_actions': ['open_order_review'], 'facts': {'upload_state': 'not_created'},
'source_summary': {'document_id': None, 'filename': 'mail.eml'},
}])
finally:
event.remove(db.engine, 'before_cursor_execute', _capture)
assert not any('FOR UPDATE' in statement.upper() for statement in statements)
def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_user):
"""
BE-07:投影 stage/status 以 OT 已写入值为准,禁止读路径用 Notice 覆盖。
@@ -1868,16 +2312,16 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
assert synced['status'] == 'automating'
assert synced['stage'] == 'freight_uploading'
# 人工上传回执已落库时,Notice 终态必须覆盖尚未来得及同步的 OT 旧状态。
# 历史 Notice.upload_status 不构成成功证据;未补齐 Attempt/预约单时仍须停在货代上传。
notice.upload_status = 'uploaded'
order_task.status = 'automating'
order_task.stage = 'freight_uploading'
db.session.commit()
completed = _project_order_task_work_item(run)
assert completed['status'] == 'completed'
assert completed['stage'] == 'completed'
assert completed['user_status'] == 'completed'
assert all(node['status'] == 'passed' for node in completed['stage_nodes'])
unverified = _project_order_task_work_item(run)
assert unverified['status'] == 'waiting_human'
assert unverified['stage'] == 'freight_uploading'
assert unverified['user_status'] == 'waiting_human'
assert unverified['verified_upload_success'] is False
def test_conversation_processing_rebuild_prefers_work_item_user_status(app):
@@ -71,11 +71,12 @@ def test_project_post_confirm_auto_progress_marks_stuck_task_for_retry(app, monk
summary = projection._project_post_confirm_auto_progress(case)
# 关键断言:刷新后可据此恢复琥珀色重试入口,且保留成功 Job 身份。
# 关键断言:刷新后保留失败事实,但不恢复已下线的泛化 retry 入口;
# 用户必须回到当前 Gate 选择具体业务动作。
assert summary is not None
assert summary['task_no'] == 'SN-STUCK-1'
assert summary['needs_retry'] is True
assert summary['status'] == 'needs_retry'
assert summary['needs_retry'] is False
assert summary['status'] == 'failed'
assert summary['job_id'] == 55
assert summary['reason_code'] == 'auto_progress_job_succeeded_but_task_not_advanced'
@@ -202,17 +202,18 @@ def test_shortage_release_keeps_first_export_line_override():
) == {0: {'6': 'ODM-001'}}
def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_inventory_fact(app, monkeypatch):
"""短缺放行重投影后必须入队 Excel 产物 Gate,且不得改写库存缺口事实。"""
def test_shortage_release_syncs_gate_and_enqueues_auto_fulfill_without_mutating_inventory_fact(app, monkeypatch):
"""短缺放行只同步 Gate,并由 Worker 决定是否创建单条 Notice/Excel。"""
from types import SimpleNamespace
from app.services.shipping_notice import order_review_fulfillment_decision_service as svc
task = SimpleNamespace(id=12, active_process_execution_id=34)
task = SimpleNamespace(id=12, task_no='SN-12', active_process_execution_id=34)
case = SimpleNamespace(confirmed_task_id=12)
execution = SimpleNamespace(id=34, task_id=12)
synced = []
queued = []
auto_fulfill_jobs = []
monkeypatch.setattr(svc.db.session, 'get', lambda model, key: task if key == 12 else execution)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
@@ -222,6 +223,10 @@ def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_
'app.services.shipping_notice.auto_progress_controller.submit_auto_progress',
lambda **kwargs: queued.append(kwargs),
)
monkeypatch.setattr(
'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job',
lambda **kwargs: auto_fulfill_jobs.append(kwargs),
)
with app.app_context():
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=7)
@@ -233,6 +238,11 @@ def test_shortage_release_syncs_and_queues_confirmed_task_gate_without_mutating_
'operator_id': 7,
'commit': False,
}]
assert auto_fulfill_jobs == [{
'task_no': 'SN-12',
'trigger': 'inventory_shortage_released',
'commit': False,
}]
def test_shortage_release_rejects_missing_template_inventory_override():
@@ -554,70 +564,6 @@ def test_decide_flushes_new_decision_before_serializing_audit(app, monkeypatch):
assert result['decision']['id'] == 42
def test_create_wave_revalidates_inventory(app, monkeypatch):
"""建波次前 validate_draft 后仍库存不足则拒绝。"""
from types import SimpleNamespace
from app.services.shipping_notice import order_review_fulfillment_decision_service as svc
draft = SimpleNamespace(
draft_version=2,
lines_json=[{
'line_key': 'L1',
'qty': '10',
'reservation_id': 'R1',
'part_number': 'PN1',
}],
validation_result_json={
'line_projections': [{
'line_key': 'L1',
'available_qty': '1',
'effective_reservation_id': 'R1',
}],
},
)
case = SimpleNamespace(
id=1,
case_no='CASE-1',
status='ready',
current_draft=draft,
run=SimpleNamespace(run_no='RUN-1'),
)
decision = SimpleNamespace(
decision_code=DECISION_FULFILL,
line_status='ready_to_fulfill',
required_qty='10',
is_active=True,
)
monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case)
monkeypatch.setattr(svc, '_get_soft_loader', lambda: lambda **kwargs: case)
monkeypatch.setattr(svc, '_active_decision', lambda *a, **k: decision)
called = {'validate': False}
def _fake_validate(**kwargs):
called['validate'] = True
return {'status': 'ready'}
monkeypatch.setattr(
'app.services.shipping_notice.order_review_draft_service.validate_draft',
_fake_validate,
)
with app.app_context():
with pytest.raises(ConflictError) as exc:
svc.create_fulfillment_wave(
user_id=1,
case_no='CASE-1',
line_keys=['L1'],
expected_draft_version=2,
idempotency_key='wave-1',
)
assert called['validate'] is True
assert exc.value.code == 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY'
def test_project_empty_case_without_draft(app):
"""无草稿行时投影应返回空列表。"""
from types import SimpleNamespace
@@ -36,7 +36,6 @@ def test_wave_line_unique_constraint_blocks_second_insert(app):
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
from app.services.shipping_notice.tool_common import generate_task_no
user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-UQ')
@@ -46,19 +45,19 @@ def test_wave_line_unique_constraint_blocks_second_insert(app):
ensure_order_extraction_plan(run)
db.session.commit()
unit = run.extraction_plan.units[0]
unit.status = 'candidate_ready'
unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]}
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id))
task1 = ShippingNotice(
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
task_no=generate_task_no(),
user_id=int(user.id), source_type='review_confirmation',
source_file_name=document.filename, source_content_hash=document.content_hash,
)
task2 = ShippingNotice(
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
task_no=generate_task_no(),
user_id=int(user.id), source_type='review_confirmation',
source_file_name=document.filename, source_content_hash=document.content_hash,
)
@@ -93,7 +92,6 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
from app.services.shipping_notice.tool_common import generate_task_no
user, agent, session, intake, document = _seed_run_input(suffix='WAVE-CONC-RACE')
@@ -103,17 +101,17 @@ def test_wave_line_concurrent_inserts_only_one_wins(app):
ensure_order_extraction_plan(run)
db.session.commit()
unit = run.extraction_plan.units[0]
unit.status = 'candidate_ready'
unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]}
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
case_id = int(case.id)
shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user.id))
tasks = []
for _ in range(2):
task = ShippingNotice(
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id),
task_no=generate_task_no(),
user_id=int(user.id), source_type='review_confirmation',
source_file_name=document.filename, source_content_hash=document.content_hash,
)
@@ -106,6 +106,30 @@ def test_completed_checks_include_formal_ot_milestone():
assert 'order_review_completed' in codes
def test_completed_checks_do_not_mark_open_legacy_conflict_as_resolved():
"""遗留阻断 Finding 已投影为开放冲突时,不得再显示冲突已解决。"""
checks = project_completed_checks(
case=SimpleNamespace(updated_at=None),
process_gate={
'gates_track': [
{'gate_code': 'field_conflict_resolution', 'status': 'passed'},
],
},
customer_resolution=None,
duplicate=None,
field_conflicts=[{
'conflict_key': '0:unit_price',
'field_code': 'unit_price',
'status': 'open',
}],
field_completeness=None,
profile_match=None,
formal_ot={'has_formal_ot': False},
)
assert 'field_conflicts_resolved' not in {item['code'] for item in checks}
def test_post_ot_clears_pre_ot_blocking_gate():
"""正式 OT 后建单前 Gate 不得成为当前阻断。"""
summary = apply_post_ot_gate_rules(
@@ -235,6 +259,7 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating():
current_step=None,
stage_nodes_json=None,
step_payload_json=None,
upload_status=None,
)
stage = project_stage_for_task(task)
assert stage['code'] == 'order_creating'
@@ -242,8 +267,8 @@ def test_project_stage_for_task_without_domain_facts_is_order_creating():
assert stage['source'] == 'domain_facts'
def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
"""人工上传已完成时,旧 OT freight_uploading 阶段不能覆盖 Notice 终态。"""
def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload():
"""历史 Notice.upload_status 无成功 Attempt 时不得绕过货代上传核对。"""
task = SimpleNamespace(
id=1,
order_task_id=9,
@@ -253,8 +278,8 @@ def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
step_payload_json=None,
)
stage = project_stage_for_task(task)
assert stage['code'] == 'completed'
assert stage['source'] == 'notice_terminal'
assert stage['code'] == 'freight_uploading'
assert stage['source'] == 'upload_success_unverified'
def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch):
@@ -26,6 +26,7 @@ from app.services.shipping_notice.reservation_service import (
ensure_task_reservations,
record_inventory_verification,
)
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error
from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
@@ -77,6 +78,53 @@ def test_shortage_release_makes_only_its_snapshot_line_exportable(app):
assert line_ids == {released_line.id}
def test_partial_inventory_allows_excel_for_the_available_lines(app):
"""关键断言:部分短缺不阻断已完整满足行的滚动 Excel 导出资格。"""
with app.app_context():
task, user = _build_accepted_order(suffix='partial-excel-gate')
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
available_line = snapshot.lines[0]
shortage_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
qty=Decimal('3'), field_values_json={},
)
snapshot.lines.append(shortage_line)
db.session.flush()
record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[
{'reservation_id': available_line.reservation_id, 'part_number': available_line.part_number, 'required_qty': available_line.qty, 'available_qty': available_line.qty, 'line_status': 'ok'},
{'reservation_id': shortage_line.reservation_id, 'part_number': shortage_line.part_number, 'required_qty': shortage_line.qty, 'available_qty': '0', 'line_status': 'shortage'},
])
assert excel_gate_error(task) is None
def test_selected_notice_only_returns_its_frozen_lines(app):
"""独立发货通知只能取得用户选择的满足行,不能捎带同 PO 其他可用行。"""
with app.app_context():
task, user = _build_accepted_order(suffix='selected-notice-lines')
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
first_line = snapshot.lines[0]
second_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=1, part_number='000126', reservation_id='0012345681',
qty=Decimal('3'), field_values_json={},
)
snapshot.lines.append(second_line)
db.session.flush()
record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[
{'reservation_id': first_line.reservation_id, 'part_number': first_line.part_number, 'required_qty': first_line.qty, 'available_qty': first_line.qty, 'line_status': 'ok'},
{'reservation_id': second_line.reservation_id, 'part_number': second_line.part_number, 'required_qty': second_line.qty, 'available_qty': second_line.qty, 'line_status': 'ok'},
])
_verification, line_ids = current_available_snapshot_line_ids(
task,
selected_snapshot_line_ids={first_line.id},
)
assert line_ids == {first_line.id}
def test_inventory_verification_uses_frozen_quantity_and_rejects_duplicate_result(app):
"""关键断言:库存侧不得缩小需求数量或用重复结果覆盖同一冻结预约单。"""
with app.app_context():
@@ -0,0 +1,165 @@
"""验证订单模板运行时策略仅基于当前文档证据作出可审计的受控选择。"""
from app.services.shipping_notice.document_layout.runtime_parse_strategy import (
resolve_runtime_parse_strategy,
select_runtime_region_ids,
)
def _row(*, line_no: str, part_no: str, issues: list[str] | None = None) -> dict:
"""构造最小重建行,关键料号与项次用于验证策略不得静默改写业务结果。"""
return {
'status': 'parsed' if not issues else 'needs_review',
'issues': issues or [],
'fields': [
{'field_code': 'customer_po_line_no', 'value': line_no},
{'field_code': 'part_number', 'value': part_no},
],
}
def test_runtime_strategy_uses_every_page_with_coordinate_evidence():
"""模板画在首页时,运行时仍须计划检查所有有页级坐标的页面以避免静默漏续页。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}], '2': [{}], '3': []},
fixed_rows=[], adaptive_rows=[],
)
# 页面计划仍完整保留;没有任何可用明细行时整体必须 Review,不能伪造成功。
assert result.status == 'needs_review'
assert result.page_nos == (1, 2)
def test_runtime_strategy_selects_adaptive_only_when_fixed_has_no_valid_rows():
"""固定子行无有效行而自适应能完整重建时,系统才自动切换而非要求人工猜策略。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[_row(line_no='10', part_no='PART-A', issues=['row_incomplete'])],
adaptive_rows=[_row(line_no='10', part_no='PART-A')],
)
assert result.status == 'selected'
assert result.row_mode == 'adaptive_record_columns'
assert result.reason_codes == ('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',)
def test_runtime_strategy_selects_dynamic_x_columns_when_existing_modes_have_no_valid_rows():
"""固定与自适应均无行时,才允许使用同一 Schema 校验过的动态 Y 候选。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[], adaptive_rows=[],
dynamic_rows=[_row(line_no='10', part_no='PART-A')],
)
assert result.status == 'selected'
assert result.row_mode == 'dynamic_x_columns'
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
def test_runtime_strategy_requires_review_when_dynamic_conflicts_with_existing_valid_row():
"""动态结果与既有有效行冲突时不得静默保留旧模式,必须进入 Review。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[_row(line_no='10', part_no='PART-A')], adaptive_rows=[],
dynamic_rows=[_row(line_no='10', part_no='PART-B')],
)
assert result.status == 'needs_review'
assert result.row_mode is None
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
def test_runtime_strategy_selects_dynamic_when_it_safely_covers_more_valid_records():
"""动态候选完整覆盖旧模式且额外恢复有效起行记录时,才能取代不完整结果。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[_row(line_no='20', part_no='PART-B')], adaptive_rows=[],
dynamic_rows=[
_row(line_no='10', part_no='PART-A'),
_row(line_no='20', part_no='PART-B'),
],
)
assert result.status == 'selected'
assert result.row_mode == 'dynamic_x_columns'
assert result.reason_codes == ('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',)
def test_runtime_strategy_requires_review_when_two_valid_modes_disagree_on_business_rows():
"""两种有效重建结果的关键项次或料号不一致时不得按分数强选,必须转既有 Review。"""
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]},
fixed_rows=[_row(line_no='10', part_no='PART-A')],
adaptive_rows=[_row(line_no='10', part_no='PART-B')],
)
assert result.status == 'needs_review'
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
def test_runtime_strategy_requires_review_when_two_modes_disagree_on_non_key_business_value():
"""同项次料号但数量不同仍是业务冲突,不能因主键一致而静默采用固定子行。"""
fixed = _row(line_no='10', part_no='PART-A')
fixed['fields'].append({'field_code': 'quantity', 'value': '12'})
adaptive = _row(line_no='10', part_no='PART-A')
adaptive['fields'].append({'field_code': 'quantity', 'value': '10'})
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive],
)
assert result.status == 'needs_review'
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
def test_runtime_strategy_prefers_complete_fixed_rows_when_overlap_matches():
"""固定模式多识别一个字段时不得把同一条明细误判为策略冲突。"""
fixed = _row(line_no='10', part_no='PART-A')
fixed['fields'].append({'field_code': 'uom', 'value': 'EA'})
adaptive = _row(line_no='10', part_no='PART-A')
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive],
)
assert result.status == 'selected'
assert result.row_mode == 'fixed_subrows'
def test_runtime_strategy_still_reviews_when_field_values_conflict():
"""字段值冲突仍必须进入 Review,不能用字段数量掩盖识别差异。"""
fixed = _row(line_no='10', part_no='PART-A')
fixed['fields'].append({'field_code': 'uom', 'value': 'EA'})
adaptive = _row(line_no='10', part_no='PART-A')
adaptive['fields'].append({'field_code': 'uom', 'value': 'PCS'})
result = resolve_runtime_parse_strategy(
page_glyphs={'1': [{}]}, fixed_rows=[fixed], adaptive_rows=[adaptive],
)
assert result.status == 'needs_review'
assert result.reason_codes == ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',)
def test_runtime_strategy_reuses_base_region_on_continuation_page_without_duplicate_page_regions():
"""标注页只用于定位同页表区;没有专属标注的续页复用基础表区,不能重复消费其他页布局。"""
regions = [
{'region_id': 'page_one', 'page_scope': 'exact_page', 'page_no': 1},
{'region_id': 'page_two', 'page_scope': 'exact_page', 'page_no': 2},
]
assert select_runtime_region_ids(table_regions=regions, page_no=1) == ('page_one',)
assert select_runtime_region_ids(table_regions=regions, page_no=2) == ('page_two',)
assert select_runtime_region_ids(table_regions=regions, page_no=3) == ('page_one',)
def test_runtime_region_selection_prefers_legacy_continuation_region_before_base_region():
"""已发布模板的续页专属框仍优先于首页基准框,避免升级后错用另一种行布局。"""
regions = [
{'region_id': 'page_one', 'page_scope': 'first_page'},
{'region_id': 'continuation', 'page_scope': 'continuation_pages'},
{'region_id': 'all_pages', 'page_scope': 'all_pages'},
]
assert select_runtime_region_ids(table_regions=regions, page_no=1) == ('page_one',)
assert select_runtime_region_ids(table_regions=regions, page_no=2) == ('continuation',)
@@ -244,17 +244,23 @@ def test_stp_handler_accepts_worker_contract_and_finishes_owned_attempt(app):
payload={'case_no': 'SORC-STP-HANDLER', 'draft_version': 3, 'job_id': 906},
job_id=906,
)
finish_mock.assert_called_once_with(
906,
result={'ok': True, 'message': 'done', 'task_no': 'SN-1'},
message='done',
owned_attempt=2,
)
finish_mock.assert_called_once()
args, kwargs = finish_mock.call_args
assert args == (906,)
assert kwargs['message'] == 'done'
assert kwargs['owned_attempt'] == 2
assert kwargs['result'] == {
'ok': True,
'message': 'done',
'task_no': 'SN-1',
'contract_version': 'shipping-recovery-v1-phase1',
'status': 'ok',
}
fail_mock.assert_not_called()
def test_stp_handler_uses_fail_job_contract_for_business_failure(app):
"""业务失败必须使用 fail_job(error/result/retryable/owned_attempt),不得传旧参数名。"""
def test_stp_handler_marks_business_failure_blocked_manual(app):
"""业务失败必须停止自动重试并提供人工复核入口。"""
from app.jobs.context import JobContext
from app.jobs.handlers import shipping_stp_auto_create as handler
@@ -279,13 +285,15 @@ def test_stp_handler_uses_fail_job_contract_for_business_failure(app):
) as fail_mock:
handler.handle_shipping_stp_auto_create(ctx, {'job_id': 907})
fail_mock.assert_called_once_with(
907,
error='not eligible',
result=result,
retryable=True,
owned_attempt=1,
)
fail_mock.assert_called_once()
args, kwargs = fail_mock.call_args
assert args == (907,)
assert kwargs['error'] == 'not eligible'
assert kwargs['retryable'] is False
assert kwargs['owned_attempt'] == 1
assert kwargs['result']['blocking_reason'] == 'SHIPPING.STP_NOT_ELIGIBLE'
assert kwargs['result']['next_action'] == 'open_order_review'
assert kwargs['result']['contract_version'] == 'shipping-recovery-v1-phase1'
finish_mock.assert_not_called()
@@ -8,35 +8,54 @@ tests/test_shipping_stp_match_completed_gate.py
from __future__ import annotations
from types import SimpleNamespace
from app import db
from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch
from app.services.shipping_notice.fulfillment_workflow import match_completed
def test_match_completed_rejects_partial():
def _task_with_current_matches(*, task_no: str, rows: list[dict]) -> ShippingNotice:
"""写入正式行匹配事实,供 Excel 门禁读取。"""
task = ShippingNotice(task_no=task_no, source_type='manual')
db.session.add(task)
db.session.flush()
db.session.add_all([
ShippingNoticeLineInventoryMatch(
task_id=task.id,
line_key=f'L{index}',
match_result=row['match_result'],
inventory_status='ready',
shortage_qty=row.get('shortage_qty', '0'),
is_current=True,
)
for index, row in enumerate(rows, start=1)
])
db.session.flush()
return task
def test_match_completed_rejects_partial(app):
"""partial 即使存在 ok 行也不得进入 Excel。"""
task = SimpleNamespace(
match_status='partial',
line_results_json=[
{'line_status': 'ok'},
{'line_status': 'shortage'},
],
)
assert match_completed(task) is False
with app.app_context():
task = _task_with_current_matches(
task_no='SN-MATCH-PARTIAL',
rows=[{'match_result': 'matched'}, {'match_result': 'not_found', 'shortage_qty': '1'}],
)
assert match_completed(task) is False
def test_match_completed_requires_all_ok_fulfillable():
def test_match_completed_requires_all_ok_fulfillable(app):
"""fulfillable 且全部 ok 才允许制单。"""
ok = SimpleNamespace(
match_status='fulfillable',
line_results_json=[{'line_status': 'ok'}, {'disposition': 'ok'}],
)
mixed = SimpleNamespace(
match_status='fulfillable',
line_results_json=[{'line_status': 'ok'}, {'line_status': 'not_found'}],
)
assert match_completed(ok) is True
assert match_completed(mixed) is False
with app.app_context():
ok = _task_with_current_matches(
task_no='SN-MATCH-OK',
rows=[{'match_result': 'matched'}, {'match_result': 'matched'}],
)
mixed = _task_with_current_matches(
task_no='SN-MATCH-MIXED',
rows=[{'match_result': 'matched'}, {'match_result': 'not_found'}],
)
assert match_completed(ok) is True
assert match_completed(mixed) is False
def test_match_step_progress_partial_is_needs_human_not_100():
@@ -10,6 +10,8 @@ from __future__ import annotations
from types import SimpleNamespace
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
from app.services.shipping_notice.order_stp_auto_create_service import _draft_has_manual_edits
from app.services.shipping_notice.stp_inventory_freeze import (
@@ -86,38 +88,25 @@ def test_freeze_single_candidate_marks_resolved(app, monkeypatch):
},
)
task = SimpleNamespace(
inventory_source_status=None,
inventory_source_code=None,
inventory_connector_type=None,
inventory_warehouse_id=None,
inventory_source_method=None,
inventory_source_config_version=None,
inventory_routing_fingerprint=None,
step_payload_json={},
destination_code=None,
destination_city=None,
destination_country=None,
warehouse_hint=None,
inventory_source_confirmed_by=None,
inventory_source_confirmed_at=None,
current_order_extraction_id=None,
)
result = freeze_stp_inventory_candidates_on_task(
task,
line_projections=[{
'line_key': 'L1',
'candidate_inventory_source_codes': ['DBS_DUB'],
'selection_mode': 'rule',
'routing_status': 'resolved',
'matched_rule_ids': [1],
}],
)
assert result.status == 'resolved'
assert task.inventory_source_status == 'resolved'
assert task.inventory_source_code == 'DBS_DUB'
assert task_frozen_inventory_source_codes(task) == ['DBS_DUB']
assert is_inventory_source_stable(task) is True
with app.app_context():
task = ShippingNotice(task_no='SN-STP-FREEZE-ONE', source_type='manual')
db.session.add(task)
db.session.flush()
result = freeze_stp_inventory_candidates_on_task(
task,
line_projections=[{
'line_key': 'L1',
'candidate_inventory_source_codes': ['DBS_DUB'],
'selection_mode': 'rule',
'routing_status': 'resolved',
'matched_rule_ids': [1],
}],
)
assert result.status == 'resolved'
assert task.inventory_source_status == 'resolved'
assert task.inventory_source_code == 'DBS_DUB'
assert task_frozen_inventory_source_codes(task) == ['DBS_DUB']
assert is_inventory_source_stable(task) is True
def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch):
@@ -143,35 +132,22 @@ def test_freeze_multi_candidate_is_stable_without_unique_source(app, monkeypatch
monkeypatch.setattr(gate_mod, 'inventory_sources_runtime_version', lambda: 'cfg-v2')
monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source)
task = SimpleNamespace(
inventory_source_status=None,
inventory_source_code=None,
inventory_connector_type=None,
inventory_warehouse_id=None,
inventory_source_method=None,
inventory_source_config_version=None,
inventory_routing_fingerprint=None,
step_payload_json={},
destination_code=None,
destination_city=None,
destination_country=None,
warehouse_hint=None,
inventory_source_confirmed_by=None,
inventory_source_confirmed_at=None,
current_order_extraction_id=None,
)
result = freeze_stp_inventory_candidates_on_task(
task,
line_projections=[{
'line_key': 'L1',
'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'],
'selection_mode': 'rule',
'routing_status': 'ambiguous',
'matched_rule_ids': [9],
}],
)
assert result.status == 'candidates_frozen'
assert task.inventory_source_status == 'candidates_frozen'
assert not task.inventory_source_code
assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
assert is_inventory_source_stable(task) is True
with app.app_context():
task = ShippingNotice(task_no='SN-STP-FREEZE-MANY', source_type='manual')
db.session.add(task)
db.session.flush()
result = freeze_stp_inventory_candidates_on_task(
task,
line_projections=[{
'line_key': 'L1',
'candidate_inventory_source_codes': ['DBS_DUB', 'DBS_RTM'],
'selection_mode': 'rule',
'routing_status': 'ambiguous',
'matched_rule_ids': [9],
}],
)
assert result.status == 'candidates_frozen'
assert task.inventory_source_status == 'candidates_frozen'
assert not task.inventory_source_code
assert task_frozen_inventory_source_codes(task) == ['DBS_DUB', 'DBS_RTM']
assert is_inventory_source_stable(task) is True
@@ -4,7 +4,6 @@ from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingAuditEvent,
ShippingCase,
ShippingNotice,
ShippingTaskEvent,
ShippingTaskPurgeAudit,
@@ -62,11 +61,8 @@ def test_plain_created_task_can_be_deleted_and_restored(app):
def test_internal_business_task_is_voided_before_recycle_bin(app):
"""已有业务单的任务不能伪装为纯删除,必须留下作废事实和原因。"""
with app.app_context():
case = ShippingCase(case_no='SC-DISPOSITION-001')
task = _task('SN-DISPOSITION-VOID-001')
db.session.add_all([case, task])
db.session.flush()
task.shipping_case_id = case.id
task = _task('SN-DISPOSITION-VOID-001', business_no='SN260823001')
db.session.add(task)
db.session.commit()
outcome = move_task_to_recycle_bin(task, actor_id=1, reason='重复建单')
@@ -210,11 +206,9 @@ def test_workspace_voided_filter_includes_voided_recycle_bin_task(app, client):
"""已作废视图必须可审计“作废并删除”的任务,不能被 deleted_at 条件意外排除。"""
headers, user_id = _headers_for_user(app, 'disposition-voided-list')
with app.app_context():
case = ShippingCase(case_no='SC-DISPOSITION-LIST-VOIDED')
task = _task('SN-DISPOSITION-LIST-VOIDED', user_id=user_id)
db.session.add_all([case, task])
task = _task('SN-DISPOSITION-LIST-VOIDED', user_id=user_id, business_no='SN260823002')
db.session.add(task)
db.session.flush()
task.shipping_case_id = case.id
move_task_to_recycle_bin(task, actor_id=user_id, reason='测试作废')
db.session.commit()
@@ -254,11 +248,8 @@ def test_admin_can_purge_only_pure_deleted_task_and_audit_is_retained(app, clien
def test_purge_blocks_task_with_business_reference(app):
"""已有业务单的回收站任务即使被手工篡改为 active,也必须阻断永久删除。"""
with app.app_context():
case = ShippingCase(case_no='SC-DISPOSITION-PURGE-BLOCK')
task = _task('SN-DISPOSITION-PURGE-BLOCK')
db.session.add_all([case, task])
db.session.flush()
task.shipping_case_id = case.id
task = _task('SN-DISPOSITION-PURGE-BLOCK', business_no='SN260823003')
db.session.add(task)
task.deleted_at = __import__('datetime').datetime.utcnow()
db.session.commit()
@@ -30,8 +30,8 @@ def test_unuploaded_resend_voids_old_task_and_keeps_new_active(app):
assert new.lifecycle_status == 'active'
def test_uploaded_resend_requires_cancellation_receipt_before_new_can_continue(app):
"""关键断言:已上传旧版必须先有撤销回执,后继版才恢复活动状态。"""
def test_uploaded_resend_requires_external_cancellation_confirmation_before_new_can_continue(app):
"""关键断言:已上传旧版须登记外部撤销确认;不要求回执号或文件。"""
with app.app_context():
old, new, user = _tasks(uploaded=True)
establish_task_supersession(old_task=old, new_task=new, actor_id=user.id, reason='customer resend')
@@ -39,7 +39,11 @@ def test_uploaded_resend_requires_cancellation_receipt_before_new_can_continue(a
assert new.lifecycle_status == 'blocked'
with pytest.raises(ConflictError):
assert_task_not_supersession_blocked(new)
complete_freight_cancellation(cancellation_id=row.id, actor_id=user.id, freight_receipt_no='CANCEL-1', receipt_asset_id=1)
complete_freight_cancellation(
cancellation_id=row.id,
actor_id=user.id,
note='已在货代平台确认撤销',
)
assert row.status == 'cancelled'
assert old.lifecycle_status == 'voided'
assert new.lifecycle_status == 'active'
+177 -47
View File
@@ -18,7 +18,11 @@ from app.models import (
ShippingUploadAttempt,
)
from app.services.shipping_notice.fulfillment_workflow import _rpa_callback_success
from app.services.shipping_notice.upload_attempt_service import complete_attempt, mark_attempt_result_unknown, start_rpa_attempt, void_rejected_artifact
from app.services.shipping_notice.export import assert_notice_has_no_export_artifact
from app.services.shipping_notice.upload_attempt_service import (
complete_attempt, has_verified_upload_success, mark_attempt_result_unknown,
record_manual_upload, start_rpa_attempt, void_rejected_artifact,
)
from app.services.shipping_notice.state_machine import resolve_task_ui_state
@@ -64,10 +68,136 @@ def test_upload_callback_is_idempotent_and_locks_reservation(app):
assert ShippingUploadAttempt.query.count() == 1
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
# 三层成功事实齐全后,才允许任务进入业务「通知完成」。
assert has_verified_upload_success(db.session.get(ShippingNotice, task.id)) is True
with pytest.raises(ConflictError):
start_rpa_attempt(task, artifact_id=artifact.id)
def test_notice_with_existing_excel_cannot_generate_another_artifact(app):
"""一个发货通知单已有 Excel 后必须创建新 Notice,不能追加第二个 Artifact。"""
with app.app_context():
task, _artifact, _reservation = _ready_artifact()
with pytest.raises(ConflictError) as exc_info:
assert_notice_has_no_export_artifact(task)
assert exc_info.value.code == 'SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED'
def test_batch_notice_confirmation_isolates_each_business_number(app, monkeypatch):
"""批量通知单确认中一张被阻断时,其他通知单仍独立提交成功。"""
from types import SimpleNamespace
from app.api.workspace import shipping_notice as api
with app.app_context(), app.test_request_context(
'/api/workspace/shipping-notices/batch/confirm-uploaded',
method='POST',
json={'business_nos': ['WVC26082301', 'WVC26082302']},
):
commits: list[str] = []
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=7))
monkeypatch.setattr(
api,
'_confirm_notice_uploaded',
lambda *, business_no, user_id: (
{'status': 'ok'} if business_no.endswith('01')
else (_ for _ in ()).throw(ConflictError('already uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED'))
),
)
monkeypatch.setattr(api.db.session, 'commit', lambda: commits.append('commit'))
monkeypatch.setattr(api.db.session, 'rollback', lambda: commits.append('rollback'))
response = api.workspace_batch_confirm_shipping_notices_uploaded()
body = response[0].get_json()['data']
assert [item['status'] for item in body['results']] == ['confirmed', 'blocked']
assert commits == ['commit', 'rollback']
def test_business_no_rpa_batch_isolates_each_notice(app, monkeypatch):
"""批量 RPA 必须只接受 business_no,并让已受理通知独立提交。"""
from types import SimpleNamespace
from app.api.workspace import shipping_notice as api
with app.app_context(), app.test_request_context(
'/api/workspace/shipping-notices/batch/rpa-upload',
method='POST',
json={'business_nos': ['WVC26082301', 'WVC26082302']},
):
commits: list[str] = []
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=7))
monkeypatch.setattr(
api,
'_start_notice_rpa_upload',
lambda *, business_no, user_id: (
{'status': 'running'} if business_no.endswith('01')
else (_ for _ in ()).throw(ConflictError('unknown result', code='SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN'))
),
)
monkeypatch.setattr(api.db.session, 'commit', lambda: commits.append('commit'))
monkeypatch.setattr(api.db.session, 'rollback', lambda: commits.append('rollback'))
response = api.workspace_batch_start_shipping_notice_rpa_upload()
body = response[0].get_json()['data']
assert [item['status'] for item in body['results']] == ['accepted', 'blocked']
assert [item['business_no'] for item in body['results']] == ['WVC26082301', 'WVC26082302']
assert commits == ['commit', 'rollback']
def test_business_no_loader_rejects_task_no_alias(app, monkeypatch):
"""新货代入口不得把内部 task_no 或旧 Case 编号当作 business_no 接收。"""
from app.api.workspace import shipping_notice as api
with app.app_context(), app.test_request_context('/api/workspace/shipping-notices/SN-1/export'):
task = ShippingNotice(task_no='SN-1', business_no='WVC26082301', user_id=7)
monkeypatch.setattr(api, 'get_task_for_user', lambda reference, user_id: task)
with pytest.raises(Exception) as exc_info:
api._load_business_notice_for_user(business_no='SN-1', user_id=7)
assert getattr(exc_info.value, 'code', None) == 'RESOURCE.NOT_FOUND'
def test_upload_success_updates_only_its_notice(app):
"""一张独立 Notice 上传成功只终态化其自身,不影响同 PO 的其他 Notice。"""
with app.app_context():
task, artifact, _reservation = _ready_artifact()
other = ShippingNotice(task_no='TASK-UPLOAD-OTHER', order_task_id=task.order_task_id)
db.session.add(other); db.session.flush()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
complete_attempt(attempt, success=True, callback_id='callback-notice', freight_ref_no='F-2')
assert db.session.get(ShippingNotice, task.id).upload_status == 'uploaded'
assert db.session.get(ShippingNotice, other.id).upload_status is None
def test_legacy_uploaded_field_without_attempt_is_not_verified_success(app):
"""历史 upload_status=uploaded 缺少成功 Attempt 时必须留在货代上传核对。"""
with app.app_context():
task, _artifact, _reservation = _ready_artifact()
task.upload_status = 'uploaded'
db.session.flush()
assert has_verified_upload_success(task) is False
def test_archived_upload_success_is_not_counted_as_completed(app):
"""归档任务保留上传审计,但不能再计入当前通知完成统计。"""
with app.app_context():
task, artifact, _reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
complete_attempt(attempt, success=True, callback_id='callback-archived', freight_ref_no='REF-ARCHIVED')
task.lifecycle_status = 'archived'
db.session.flush()
assert has_verified_upload_success(task) is False
def test_failed_attempt_does_not_complete_reservation(app):
"""RPA 失败仅释放 Artifact 重试状态,不能把预约单错误标记为上传完成。"""
with app.app_context():
@@ -78,6 +208,24 @@ def test_failed_attempt_does_not_complete_reservation(app):
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'ready'
def test_manual_upload_confirmation_requires_no_receipt_or_file_evidence(app):
"""人工确认只记录操作者和目标 Excel,不要求货代回执或截图/PDF。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
attempt = record_manual_upload(
task,
artifact_id=artifact.id,
operator_id=7,
)
assert attempt.mode == 'manual'
assert attempt.evidence_asset_id is None
assert attempt.freight_ref_no is None
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
def test_trigger_delivery_failure_releases_artifact_for_a_later_retry(app):
"""共享目录投递失败要落为失败 Attempt,不能遗留 uploading Artifact 阻断下一轮。"""
with app.app_context():
@@ -173,7 +321,7 @@ def test_upload_callback_success_parsing_does_not_treat_false_text_as_success():
def test_rpa_report_upload_success_without_evidence_rejected(app):
"""success=True 但缺少 success_evidence 时必须 fail-closed 拒绝。"""
"""RPA success=True 但缺少受信 Worker 证据时必须 fail-closed 拒绝。"""
with app.app_context():
from unittest.mock import patch
@@ -197,7 +345,7 @@ def test_rpa_report_upload_success_without_evidence_rejected(app):
def test_rpa_report_upload_success_without_reference_allowed(app):
"""DSV 绿 DOM 成功时 reference 可为空;须带 success_evidence.kind 且证据资产落库。"""
"""DSV 受信成功证据可不带 reference,并持久化内部审计资产。"""
with app.app_context():
from unittest.mock import patch
@@ -232,13 +380,9 @@ def test_rpa_report_upload_success_without_reference_allowed(app):
'observed_at': '2026-08-05T03:00:00Z',
'page_url': 'https://dsv.example/history',
'dom_snippet': '<em class="fa fa-circle success-color status-icon"></em>',
'dom_sha256': (
__import__('hashlib')
.sha256(
b'<em class="fa fa-circle success-color status-icon"></em>'
)
.hexdigest()
),
'dom_sha256': __import__('hashlib').sha256(
b'<em class="fa fa-circle success-color status-icon"></em>'
).hexdigest(),
},
})
assert result['status'] == 'ok'
@@ -246,13 +390,12 @@ def test_rpa_report_upload_success_without_reference_allowed(app):
refreshed = db.session.get(ShippingUploadAttempt, attempt.id)
assert refreshed is not None
evidence = refreshed.success_evidence_json or {}
assert evidence.get('dom_sha256')
assert evidence.get('page_url')
assert refreshed.evidence_asset_id == 4242
def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app):
"""DOM 校验通过但证据资产落库失败时,不得标记上传成功。"""
def test_rpa_report_upload_success_requires_internal_audit_asset(app):
"""自动 RPA 成功仍保存内部审计资产;人工确认路径不受此规则影响。"""
with app.app_context():
from unittest.mock import patch
@@ -261,12 +404,16 @@ def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app):
task, artifact, reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
db.session.commit()
def _persist(*, task, attempt, success_evidence):
attempt.evidence_asset_id = 4242
return 4242
with patch(
'app.services.shipping_notice.fulfillment_workflow.customer_gate_tool_response',
return_value=None,
), patch(
'app.services.shipping_notice.fulfillment_workflow._persist_rpa_success_evidence_asset',
return_value=None,
side_effect=_persist,
):
result = rpa_report_upload({
'task_id': task.task_no,
@@ -283,60 +430,43 @@ def test_rpa_report_upload_rejects_when_evidence_asset_persist_fails(app):
'dom_sha256': __import__('hashlib').sha256(b'<div id="ok"/>').hexdigest(),
},
})
assert result['status'] == 'failed'
assert result.get('data', {}).get('upload_evidence_persist_failed') is True
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
assert db.session.get(ShippingUploadAttempt, attempt.id).status != 'succeeded'
assert result['status'] == 'ok'
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
assert db.session.get(ShippingUploadAttempt, attempt.id).evidence_asset_id == 4242
def test_normalize_rpa_success_evidence_rejects_missing_dom_or_bad_hash():
"""缺少 page_url/dom 或哈希不匹配时必须拒绝。"""
def test_normalize_rpa_success_evidence_requires_minimal_status_summary():
"""受信 RPA 成功证据必须具备可核验的站点、时间、文件和页面定位。"""
from app.services.shipping_notice.fulfillment_workflow import _normalize_rpa_success_evidence
import hashlib
snippet = '<div id="ok"/>'
digest = hashlib.sha256(snippet.encode('utf-8')).hexdigest()
base = {
'kind': 'green_success_dom',
'selector': '#ok',
'filename': 'test.xlsx',
'observed_at': '2026-08-05T03:00:00Z',
'page_url': 'https://example.test/upload',
'dom_snippet': snippet,
'dom_sha256': digest,
}
base.update({'dom_snippet': '<div id="ok"/>', 'dom_sha256': __import__('hashlib').sha256(b'<div id="ok"/>').hexdigest()})
assert _normalize_rpa_success_evidence({'success_evidence': base}) is not None
# 关键断言:缺 page_url / 缺 snippet / 哈希错误一律 None。
# 关键断言:缺页面定位、选择器、时间或文件名一律拒绝。
bad_url = dict(base, page_url='')
assert _normalize_rpa_success_evidence({'success_evidence': bad_url}) is None
bad_snip = dict(base, dom_snippet='')
assert _normalize_rpa_success_evidence({'success_evidence': bad_snip}) is None
bad_hash = dict(base, dom_sha256='0' * 64)
assert _normalize_rpa_success_evidence({'success_evidence': bad_hash}) is None
assert _normalize_rpa_success_evidence({'success_evidence': dict(base, selector='')}) is None
assert _normalize_rpa_success_evidence({'success_evidence': dict(base, observed_at='')}) is None
assert _normalize_rpa_success_evidence({'success_evidence': dict(base, filename='')}) is None
def test_normalize_rpa_success_evidence_requires_dom_contract():
"""缺 page_url / dom_snippet / 哈希不一致时必须拒绝成功证据。"""
import hashlib
def test_normalize_rpa_success_evidence_rejects_bad_dom_contract():
"""RPA 内部回调仍需 DOM 哈希自洽;这不适用于人工上传确认。"""
from app.services.shipping_notice.fulfillment_workflow import _normalize_rpa_success_evidence
snippet = '<em class="ok"></em>'
digest = hashlib.sha256(snippet.encode('utf-8')).hexdigest()
base = {
'kind': 'dsv_history_green_dom',
'selector': 'em.ok',
'filename': 'test.xlsx',
'observed_at': '2026-08-05T03:00:00Z',
'page_url': 'https://dsv.example/history',
'dom_snippet': snippet,
'dom_sha256': digest,
'dom_snippet': '<em class="ok"></em>',
'dom_sha256': '0' * 64,
'screenshot_base64': 'legacy-only',
}
assert _normalize_rpa_success_evidence({'success_evidence': base}) is not None
# 关键断言:缺 page_url / 缺 snippet / 哈希不匹配均 fail-closed。
missing_url = dict(base, page_url='')
assert _normalize_rpa_success_evidence({'success_evidence': missing_url}) is None
missing_dom = dict(base, dom_snippet='')
assert _normalize_rpa_success_evidence({'success_evidence': missing_dom}) is None
bad_hash = dict(base, dom_sha256='0' * 64)
assert _normalize_rpa_success_evidence({'success_evidence': bad_hash}) is None
assert _normalize_rpa_success_evidence({'success_evidence': base}) is None
@@ -1,444 +0,0 @@
"""
tests/test_shipping_vendor_comments_phase2.py
用途:阶段 2 集成回归——契约、关系投影、三来源裁决(Header/Table/Vendor Comments)、
回 Draft 门禁、格式策略服务 5 大主题全量覆盖。
依赖:6 个新服务(profile_vendor_comments_contract、coordinate_region_source_adapter、
reservation_relation_projection、profile_field_source_mapping_service、
source_merge_service、reservation_format_policy_service)。
逻辑:纯内存单测——读真实 PDF/数据库的用例放在阶段 4;
覆盖 Q13/Q14/Q15/Q16/Q18 全部冻结决策矩阵。
"""
from __future__ import annotations
import pytest
from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import (
CoordinateRegionSourceAdapter,
)
from app.services.shipping_notice.document_layout.field_split_core import (
BaseSplitMatcher,
BaseSplitNormalization,
BaseSplitRule,
BaseSplitRuleSet,
BaseSplitSegment,
RelationCaptureDef,
new_segment_id,
)
from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import (
FieldSourceCandidate,
ProfileFieldSourceMappingService,
)
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
NamedRegion,
ProfileFieldSourceMapping,
ReservationFormatPolicy,
field_source_mappings_checksum,
field_source_mappings_require_draft,
named_regions_checksum,
parse_field_source_mappings,
parse_named_regions,
profile_regions_require_draft,
)
from app.services.shipping_notice.document_layout.reservation_format_policy_service import (
ReservationFormatPolicyService,
)
from app.services.shipping_notice.document_layout.reservation_relation_projection import (
ReservationRelationProjection,
)
from app.services.shipping_notice.document_layout.source_merge_service import (
SourceMergeService,
)
from app.services.shipping_notice.document_layout.order_profile import RelativeRegion
# =========================================================================
# [TEST GROUP 1] profile_vendor_comments_contract(Q14/Q15)
# =========================================================================
def test_parse_named_regions_empty_is_allowed():
"""当前客户没配 Vendor Comments 区域 → 返回空,不报错。"""
assert parse_named_regions(None) == {}
assert parse_named_regions({}) == {}
def test_named_region_last_page_vendor_comments_parses():
"""Q14 冻结结构:region_id/label/region/page_scope/selection_mode 全齐。"""
raw = {
'vendor_comments': {
'region_id': 'vendor-comments-v1',
'label': 'Vendor Comments',
'region': {'x0': 0.03, 'y0': 0.62, 'x1': 0.42, 'y1': 0.78},
'page_scope': 'last_page',
'selection_mode': 'fixed_region',
},
}
regions = parse_named_regions(raw)
assert 'vendor_comments' in regions
r = regions['vendor_comments']
assert r.page_scope == 'last_page'
assert r.region.y1 > r.region.y0
def test_named_region_rejects_key_region_id_mismatch():
"""外键 key 与 region_id 不一致:拒绝。"""
raw = {'vc': {'region_id': 'other-name',
'label': 'L', 'region': {'x0':0,'y0':0,'x1':1,'y1':1},
'page_scope': 'last_page', 'selection_mode': 'fixed_region'}}
from app.core.errors import ValidationError
with pytest.raises(ValidationError):
parse_named_regions(raw)
def test_profile_regions_require_draft_matrix():
"""Q14:增删改 region/坐标/page_scope/selection_mode → 回 Draft;仅 label 不回。"""
old = {
'vc': {
'region_id': 'vc', 'label': 'Old Label',
'region': {'x0':0,'y0':0,'x1':1,'y1':1},
'page_scope': 'last_page', 'selection_mode': 'fixed_region',
},
}
# 仅改 label → 不回 Draft
new_same_label_only = {k: {**v, 'label': 'New Label'} for k, v in old.items()}
assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_same_label_only) is False
# 改 x0 → 回 Draft
new_coord = {k: {**v} for k, v in old.items()}
new_coord['vc']['region'] = {'x0':0.01,'y0':0,'x1':1,'y1':1}
assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_coord) is True
# 新增 region → 回 Draft
new_extra = {
**old,
'other': {
'region_id': 'other', 'label': 'O',
'region': {'x0':0,'y0':0,'x1':0.1,'y1':0.1},
'page_scope': 'first_page', 'selection_mode': 'fixed_region',
},
}
assert profile_regions_require_draft(old_named_regions=old, new_named_regions=new_extra) is True
def test_field_source_mappings_require_draft_any_change_triggers():
"""Q9:field_source_mappings 任何改 → 回 Draft(首期全量 fail-close)。"""
old = [{
'mapping_id': 'm1', 'target_scope': 'line', 'target_field_code': 'reservation_id',
'target_field_id': 'f-r1', 'vendor_comments_enabled': False,
}]
new = [{
'mapping_id': 'm1', 'target_scope': 'line', 'target_field_code': 'reservation_id',
'target_field_id': 'f-r1', 'vendor_comments_enabled': True,
'vendor_comments_region_ref': 'vc',
'vendor_comments_split_rule_set': {
'rule_set_id': 'rs1', 'rule_version': 1,
'normalization': {}, 'rules': [],
'unmatched_line_policy': 'evidence_only', 'source': 'user',
'status': 'confirmed', 'requires_confirmation': False,
},
}]
assert field_source_mappings_require_draft(old_mappings=old, new_mappings=new) is True
def test_reservation_format_policy_rejects_dangerous_regex():
"""Q15:(a+)+$ 被 Pydantic validator 拦截在构造阶段。"""
from pydantic import ValidationError as PydanticValErr
with pytest.raises(PydanticValErr):
ReservationFormatPolicy(
mode='custom_safe_regex',
pattern=r'(a+)+$',
)
# =========================================================================
# [TEST GROUP 2] reservation_relation_projection(Q2/Q7/Q12)
# =========================================================================
def test_relation_projection_bind_target_line_via_profile_business_line_no():
"""Q2:captured_relation.line_no=2 命中 profile_business_line_no{2:1} → 逻辑行号1。"""
from app.services.shipping_notice.document_layout.field_split_core import CoreCapturedRelation
proj = ReservationRelationProjection(
relation_policy='bind_target_line',
line_reference_basis='profile_business_line_no',
)
result = proj.project(
captured_relation=CoreCapturedRelation(type='line_reference', line_no=2, raw_text='for line#2'),
profile_business_line_numbers={1: '1', 2: '2', 3: '3'},
)
assert result.resolution == 'bound_to_line'
assert result.resolved_logical_line_no == 2 # 逻辑行号=1-based mapping key
def test_relation_projection_invalid_line_reference_emits_independent_reason():
"""Q12:引用不存在的行 99 → invalid_line_reference 独立原因码。"""
from app.services.shipping_notice.document_layout.field_split_core import CoreCapturedRelation
proj = ReservationRelationProjection(relation_policy='bind_target_line')
result = proj.project(
captured_relation=CoreCapturedRelation(type='line_reference', line_no=99, raw_text='line#99'),
profile_business_line_numbers={1: '1', 2: '2'},
)
assert result.resolution == 'invalid_line_reference'
assert result.invalid_reference_line_no == 99
assert result.audit_chain is not None
assert result.should_generate_header_observation is True # invalid 保留为头证据
def test_relation_projection_annotation_only_writes_metadata():
"""annotation_only:不绑定行,不生成行 Observation,生成头元数据。"""
proj = ReservationRelationProjection(relation_policy='annotation_only')
result = proj.project(
captured_relation=None,
annotation_reason_override='customer_commentary_reservation',
)
assert result.resolution == 'annotation_only'
assert result.annotation_reason == 'customer_commentary_reservation'
assert result.should_generate_line_observation is False
assert result.should_generate_header_observation is True
def test_relation_missing_policy_default_all_lines_flags_every_line():
"""missing_relation_policy=default_all_lines:每行都生成 Observation。"""
proj = ReservationRelationProjection(
relation_policy='bind_target_line',
missing_relation_policy='default_all_lines',
)
result = proj.project(captured_relation=None)
assert result.resolution == 'default_all_lines'
assert result.should_generate_line_observation is True
# =========================================================================
# [TEST GROUP 3] SourceMergeService(Q18 三来源裁决)
# =========================================================================
def _make_cand(source, scope, code, line_no, value, *,
fv=True, frc=None, mapping_id='m1', target_field_id='f-r1',
hint='provisional') -> FieldSourceCandidate:
c = FieldSourceCandidate(
source=source, target_scope=scope, target_field_code=code,
target_field_id=target_field_id, value=value, normalized_value=value,
format_valid=fv, format_reason_code=frc, effective_line_no=line_no,
resolution_hint=hint,
evidence_quote=value, evidence_ref=f'{source}-ref',
evidence_metadata={'mapping_id': mapping_id},
)
c.conflict_group_key = (scope, code, line_no)
return c
def test_source_merge_same_value_merged_marks_metadata():
"""Q18 same_value_merge:三来源同值 3000098851 → resolution=same_value_merged。"""
candidates = [
_make_cand('header_region', 'line', 'reservation_id', 1, '3000098851'),
_make_cand('table_column', 'line', 'reservation_id', 1, '3000098851'),
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851'),
]
svc = SourceMergeService(candidates)
merged = svc.merge_and_decide()
assert len(merged) == 1
m = merged[0]
assert m.accepted_value == '3000098851'
assert m.resolution == 'same_value_merged'
assert m.decision_status == 'accepted'
assert m.should_persist_observation is True
md = m.evidence_metadata
assert md['resolution'] == 'same_value_merged'
assert len(md['source_observations']) == 3
assert 'vendor_comments' in md['resolution_meta'].get('merged_from_sources', [])
def test_source_merge_conflict_triggers_needs_review_no_accepted_value():
"""Q18 冲突:Header=3000098851, VC=3000098899 → accepted_value=None, needs_review。"""
candidates = [
_make_cand('header_region', 'line', 'reservation_id', 1, '3000098851'),
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098899'),
]
svc = SourceMergeService(candidates)
merged = svc.merge_and_decide()
assert len(merged) == 1
m = merged[0]
assert m.accepted_value is None
assert m.resolution == 'needs_review'
assert m.decision_status == 'needs_review'
assert m.should_persist_observation is False
assert len(m.evidence_metadata['source_observations']) == 2
assert len(m.conflicts) == 2 # 双冲突
def test_source_merge_fill_missing_table_empty_filled_from_vc():
"""Q4 fill_missing:表列空,VC 提供值 → fill_missing 自动填补。"""
candidates = [
_make_cand('table_column', 'line', 'reservation_id', 1, ''),
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851'),
]
svc = SourceMergeService(candidates)
merged = svc.merge_and_decide()
m = merged[0]
assert m.accepted_value == '3000098851'
assert m.resolution == 'fill_missing'
md = m.evidence_metadata
assert md['resolution_meta']['accepted_source'] == 'vendor_comments'
def test_source_merge_annotation_only_never_becomes_accepted():
"""annotation_only / invalid_line_reference:永不升 accepted,永不生成有效 Observation。"""
candidates = [
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '3000098851', hint='annotation_only'),
_make_cand('vendor_comments', 'line', 'reservation_id', 1, '123', hint='invalid_line_reference'),
]
svc = SourceMergeService(candidates)
merged = svc.merge_and_decide()
assert len(merged) == 1
m = merged[0]
assert m.should_persist_observation is False
assert m.decision_status == 'blocked'
assert len(m.evidence_metadata['source_observations']) == 2
# =========================================================================
# [TEST GROUP 4] 三来源候选收集(ProfileFieldSourceMappingService)
# =========================================================================
def test_collect_candidates_table_and_header_scopes_are_independent():
"""Q4:不同 scope 独立保留,互不冲突。Header=300001, Line=300002 都被收集。"""
definition_json = {
'field_source_mappings': [
{'mapping_id': 'mh', 'target_scope': 'header',
'target_field_code': 'reservation_id', 'target_field_id': 'f-hr',
'header_source_enabled': True, 'header_source_ref': 'header-rid'},
{'mapping_id': 'ml', 'target_scope': 'line',
'target_field_code': 'reservation_id', 'target_field_id': 'f-lr',
'table_source_enabled': True, 'table_column_code': 'reservation_id'},
],
}
svc = ProfileFieldSourceMappingService(
definition_json=definition_json,
header_observations_by_source_ref={
'header-rid': [{'value': '300001', 'evidence_ref': 'h-ref-1'}],
},
table_column_values={
'reservation_id': [
{'line_index': 0, 'value': '300002', 'evidence_ref': 'l1'},
{'line_index': 1, 'value': '300003', 'evidence_ref': 'l2'},
],
},
)
cands = svc.collect_candidates()
header_cands = [c for c in cands if c.target_scope == 'header']
line_cands = [c for c in cands if c.target_scope == 'line']
assert len(header_cands) == 1
assert header_cands[0].value == '300001'
assert len(line_cands) == 2
line_values = sorted([c.value for c in line_cands])
assert line_values == ['300002', '300003']
# Header 与 Line 不同冲突组
groups = {c.conflict_group_key for c in cands}
assert len(groups) == 3 # header+None / line+1 / line+2
# =========================================================================
# [TEST GROUP 5] FormatPolicyService(Q15)
# =========================================================================
def test_format_policy_inherit_global_accepts_5_and_10_numeric():
svc = ReservationFormatPolicyService()
r5 = svc.check(ReservationFormatPolicy(mode='inherit_global'), '12345')
r10 = svc.check(ReservationFormatPolicy(mode='inherit_global'), '1234567890')
r_alpha = svc.check(ReservationFormatPolicy(mode='inherit_global'), 'ABC12')
assert r5.valid is True and r5.normalized_value == '12345'
assert r10.valid is True and r10.normalized_value == '1234567890'
assert r_alpha.valid is False and r_alpha.reason_code == 'reservation_format_invalid'
assert r_alpha.should_block_auto_create is True
def test_format_policy_custom_safe_regex_uses_first_capture_group():
"""字母型 Reservation 预留(例如 R-12345)通过第 1 捕获组提取。"""
svc = ReservationFormatPolicyService()
policy = ReservationFormatPolicy(
mode='custom_safe_regex',
pattern=r'R[ -](\d{5,10})\b',
case_sensitive=False,
)
r = svc.check(policy, 'please use R-3000098851 thanks')
assert r.valid is True
assert r.normalized_value == '3000098851'
# =========================================================================
# [TEST GROUP 6] CoordinateRegionSourceAdapter smoke(小字典 bbox)
# =========================================================================
def test_coordinate_region_adapter_last_page_reads_text():
"""last_page → page_no=2,返回可用原文 + bbox 证据。"""
def glyph(ch, x, y, page_w=800, page_h=1100, *,
prev_space=False, src_idx=0):
w = 10
b = 'space' if prev_space else 'none'
return {
'text': ch,
'bbox': {'x0': x*page_w, 'y0': y*page_h,
'x1': (x+0.01)*page_w, 'y1': (y+0.02)*page_h},
'boundary_before': b,
'source_index': src_idx,
}
page1_glyphs = [glyph('A', 0.05, 0.1, src_idx=i) for i, A in enumerate('PageOne')]
page2_glyphs = [
*(glyph(ch, 0.04 + i*0.015, 0.65, src_idx=100+i, prev_space=(ch == ' '))
for i, ch in enumerate('Reservation 3000098851 for line#2')),
]
page_bundle = {
1: {'glyphs': page1_glyphs, 'page': {'width': 800, 'height': 1100}},
2: {'glyphs': page2_glyphs, 'page': {'width': 800, 'height': 1100}},
}
region = NamedRegion(
region_id='vc', label='VC',
region=RelativeRegion(x0=0.01, y0=0.60, x1=0.80, y1=0.80),
page_scope='last_page',
selection_mode='fixed_region',
)
adapter = CoordinateRegionSourceAdapter(region, page_bundle)
result = adapter.extract()
assert result.status == 'available'
assert result.page_no == 2
assert '3000098851' in result.raw_text
assert 'line' in result.raw_text.lower()
# =========================================================================
# [TEST GROUP 7] checksums 稳定性(防篡改)
# =========================================================================
def test_checksums_deterministic_and_sensitive_to_content():
regions = {'vc': NamedRegion(
region_id='vc', label='L', selection_mode='fixed_region',
region=RelativeRegion(x0=0, y0=0, x1=1, y1=1),
page_scope='last_page',
)}
h1 = named_regions_checksum(regions)
assert len(h1) == 64
regions2 = dict(regions)
regions2['vc'].model_copy() # 内容相同 → hash 相同(copy 保持引用,直接 mutate 不行,因此换 label)
regions_diff = {'vc': NamedRegion(
region_id='vc', label='Changed Label But Still Same Content?',
selection_mode='fixed_region',
region=RelativeRegion(x0=0, y0=0, x1=1, y1=1),
page_scope='last_page',
)}
# Label 变化 → 不同 hash(label 进入 checksum,因为管理员 label 变更不触发回 Draft,但需要留痕)
h_diff = named_regions_checksum(regions_diff)
assert h1 != h_diff
mappings = [ProfileFieldSourceMapping(
mapping_id='m1', target_scope='line', target_field_code='reservation_id',
target_field_id='f-r1', vendor_comments_enabled=False,
)]
mh1 = field_source_mappings_checksum(mappings)
assert len(mh1) == 64
@@ -31,7 +31,6 @@ _TABLE: list[tuple[str, str, str, str]] = [
('confirm_customer', 'confirm_customer', 'pre_create', 'open_customer_dialog'),
('resolve_field_conflicts', 'resolve_field_conflicts', 'pre_create', 'focus_field_conflicts'),
('adjudicate_duplicate', 'adjudicate_duplicate', 'pre_create', 'focus_duplicate_panel'),
('open_inventory_source_review', 'open_inventory_source_review', 'pre_create', 'open_inventory_candidates'),
('confirm_inventory_source', 'open_inventory_source_review', 'post_create', 'todo'),
('match_inventory', 'open_inventory_match_review', 'post_create', 'todo'),
('rematch', 'open_inventory_match_review', 'post_create', 'todo'),
@@ -42,8 +41,7 @@ _TABLE: list[tuple[str, str, str, str]] = [
('download_excel', 'download_excel', 'post_create', 'download'),
('mark_manual_uploaded', 'open_manual_upload', 'post_create', 'todo'),
('open_manual_upload', 'open_manual_upload', 'post_create', 'todo'),
('retry', 'retry', 'any', 'retry'),
('retry_parse', 'retry', 'pre_create', 'retry'),
('retry_parse', 'retry_parse', 'pre_create', 'retry'),
('refresh', 'refresh', 'any', 'refresh_strip'),
('view_result', 'view_result', 'terminal', 'view_result'),
('open_fulfillment', 'view_result', 'terminal', 'view_result'),
@@ -101,13 +99,13 @@ def test_post_create_projection_keeps_fulfillment_write_chain():
status='blocked',
stage='inventory_matching',
gate={
'gate_code': 'inventory_match',
'gate_code': 'inventory_matching',
'status': 'blocked',
'next_action_code': 'match_inventory',
'blocking_reason_code': 'inventory_shortage',
'attempt_no': 1,
},
legacy_actions=['download_excel'],
authorized_actions=['download_excel'],
excel_ready=True,
shipping_notice_no='SN-100',
)
@@ -175,7 +173,7 @@ def test_pre_create_keeps_inventory_source_review_but_strips_match():
'blocking_reason_code': 'require_manual_review',
'attempt_no': 1,
},
legacy_actions=['match_inventory', 'generate_excel'],
authorized_actions=['match_inventory', 'generate_excel'],
excel_ready=False,
shipping_notice_no=None,
)
@@ -1,92 +0,0 @@
"""
tests/test_shipping_workspace_legacy_audit.py
用途:证明旧工作台写入口(retry / confirm-inventory-source)具备审计四要素。
依赖:Flask app/client fixture、ShippingTaskEvent、ShippingAuditEvent。
逻辑:模拟工作台 JWT 用户调用旧路由,断言操作人、时间、内容与前后快照均落库。
"""
from __future__ import annotations
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import (
ShippingAuditEvent,
ShippingCase,
ShippingCustomer,
ShippingNotice,
ShippingTaskEvent,
User,
)
def _workspace_headers(app, username: str = 'legacy-audit-user') -> tuple[dict[str, str], int]:
"""签发工作台用户头,并返回 headers 与 user_id。"""
with app.app_context():
user = User.query.filter_by(username=username).first()
if user is None:
user = User(username=username, email=f'{username}@example.com', role='user')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}, int(user.id)
def test_workspace_retry_records_actor_and_snapshots(app, client):
"""retry 须写入 TaskEvent + ShippingAuditEvent,含操作人与前后快照。"""
headers, user_id = _workspace_headers(app, 'legacy-audit-retry')
with app.app_context():
customer = ShippingCustomer(standard_name='Legacy Audit Co', short_code='LGA', status='active')
case = ShippingCase(case_no='SC-LEGACY-AUDIT-RETRY', customer=customer)
task = ShippingNotice(
task_no='SN-LEGACY-AUDIT-RETRY',
user_id=user_id,
shipping_case=case,
source_type='manual',
review_status='parse_review',
pending_human_reason='low_confidence',
error_message='timeout',
customer_resolution_status='confirmed',
raw_content='客户:ACME\nA001 x 1',
)
db.session.add_all([customer, case, task])
db.session.commit()
res = client.post(
'/api/workspace/shipping-tasks/SN-LEGACY-AUDIT-RETRY/retry',
headers=headers,
json={'comment': '人工重试'},
)
assert res.status_code == 200
envelope = res.get_json()
assert envelope['success'] is True
with app.app_context():
task = ShippingNotice.query.filter_by(task_no='SN-LEGACY-AUDIT-RETRY').one()
event = (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type='task_retry_requested')
.order_by(ShippingTaskEvent.id.desc())
.first()
)
# 关键断言:旧 retry 入口不再匿名,且前后状态可对比。
assert event is not None
assert event.actor_id == user_id
assert event.created_at is not None
assert event.before_json.get('status') == 'failed'
assert event.after_json.get('status') in {'created', 'parsed'}
audit = (
ShippingAuditEvent.query.filter_by(
aggregate_type='shipping_task',
aggregate_id='SN-LEGACY-AUDIT-RETRY',
action='retry_task',
)
.order_by(ShippingAuditEvent.id.desc())
.first()
)
assert audit is not None
assert int(audit.actor_id or 0) == user_id
assert audit.before_snapshot_json is not None
assert audit.after_snapshot_json is not None
assert audit.created_at is not None
@@ -553,6 +553,12 @@ def test_route_deterministic_unit_xfa_golden_ab(monkeypatch, xfa_pdf_bytes):
assert str(values['price_unit']) == expected['lines'][0]['price_unit']
assert Decimal(str(values['amount'])) == Decimal(expected['lines'][0]['amount'])
assert str(values['delivery_date']) == expected['lines'][0]['delivery_date']
# XFA 仍以 datasets 为正式值源,并把冻结字段 evidence 暴露为统一 Observation 引用。
material_observation = route.orders[0]['lines'][0]['fields'][0]['observations'][0]
assert material_observation['value_source'] == 'xfa_dataset'
assert isinstance(material_observation['evidence_ref'], dict)
assert material_observation['evidence_ref']['source'] == 'xfa_dataset'
assert 'transform_ref' not in material_observation
blob = json.dumps(route.decision, ensure_ascii=False, default=str)
assert '<data>' not in blob
assert 'datasets_xml' not in blob
@@ -1,7 +1,7 @@
"""
tests/test_shipping_xfa_publish_separation_of_duties.py
用途:阶段 6 发布职责分离契约——编辑人不得批准自己的 Revision。
用途:验证发布确认不再额外限制草稿创建人。
依赖:publish_check_service 已有 consume 阻断键;本文件固化原因码与审计事件集合。
逻辑:纯单元断言职责分离键与编辑审计事件白名单稳定。
"""
@@ -17,19 +17,13 @@ from app.services.shipping_notice import order_document_profile_publish_check_se
pytestmark = pytest.mark.pure_unit
def test_editor_self_approval_reason_key_is_stable():
"""关键断言:职责分离失败键稳定为 editor_cannot_approve_own_version。"""
def test_editor_self_approval_gate_is_removed():
"""关键断言:消费流程不再包含自己编辑不得发布的门禁。"""
source = inspect.getsource(checks.consume_report)
assert 'editor_cannot_approve_own_version' in source
assert '_find_last_profile_editor_id' in source
assert 'editor_cannot_approve_own_version' not in source
assert '_find_last_profile_editor_id' not in source
def test_editor_audit_events_cover_mapping_and_split():
"""关键断言:查找最近编辑者覆盖末端映射与拆分编辑审计事件。"""
source = inspect.getsource(checks._find_last_profile_editor_id)
for event in (
'xfa_mapping_saved',
'xfa_split_rule_suggested',
'xfa_segment_mapping_updated',
):
assert event in source
def test_publish_check_service_has_no_editor_separation_helper():
"""关键断言:发布检查服务不再保留历史编辑者查询辅助函数。"""
assert not hasattr(checks, '_find_last_profile_editor_id')
@@ -97,6 +97,18 @@ def test_matcher_whitelist_and_regex_limits():
XfaSplitMatcher(type='regex', pattern=r'(a+)+$')
def test_position_matcher_accepts_restricted_prefix_post_processor():
"""位置选行后可正式执行标签后取值,不能依赖 UI stages[]。"""
matcher = XfaSplitMatcher(
type='position',
line_index=3,
post_processors=[{'type': 'prefix', 'value': 'MPN', 'separators': [':', ':']}],
)
assert matcher.post_processors[0].type == 'prefix'
assert matcher.post_processors[0].value == 'MPN'
def test_rule_set_accepts_rule_id_alias():
"""历史 rule_id 字段可解析为 rule_set_id。"""
rule_set = XfaSplitRuleSet(
@@ -254,3 +254,32 @@ def test_line_breaks_config_is_honored():
assert 'A' in claimeds
unmatched = {item.normalized_text for item in result.evidence_only_segments if item.rule_id == 'unmatched'}
assert unmatched == {'B', 'C'}
def test_position_rule_applies_prefix_post_processor_to_selected_line():
"""先按行定位,再取标签后内容,保证 XFA 正式规则与预览一致。"""
rule_set = XfaSplitRuleSet(
rule_set_id='mpn-v1',
rule_version=1,
source_path_id='path-x',
source_scope='line',
rules=[
XfaSplitRule(
rule_id='r-mpn',
matcher=XfaSplitMatcher(
type='position', line_index=3,
post_processors=[{'type': 'prefix', 'value': 'MPN', 'separators': [':', ':']}],
),
segment=XfaSplitSegment(
segment_id=new_segment_id(), segment_code='part_number', display_name='MPN',
handling='mapped', target_field_id='f-part', target_field_code='part_number',
),
),
],
)
result = execute_split_rule_set(raw_value='TEMP-S000218922\nFRAME\nMPN:D4-A08AR12000001', rule_set=rule_set)
assert result.mapped_fields == {'part_number': 'D4-A08AR12000001'}
assert result.segments[0].raw_text == 'MPN:D4-A08AR12000001'
assert result.segments[0].normalized_text == 'D4-A08AR12000001'
@@ -1,292 +0,0 @@
"""
tests/test_task_retry_decision_service.py
用途:锁定统一重试决策树的只读分支(noop / fetch)与行级 retryable。
依赖:task_retry_decision_service、line_inventory_match_projection。
逻辑:不启全量 Flask;验证决策优先级。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.line_inventory_match_projection import project_line_retryable
from app.services.shipping_notice.task_retry_decision_service import (
ACTION_FETCH_INVENTORY,
ACTION_NOOP,
ACTION_REMATCH,
ACTION_AUTO_PROGRESS,
ACTION_FAILED,
_execute,
decide_retry_action_only,
_is_inventory_rpa_active,
)
def _task(**kwargs):
defaults = {
'task_no': 'OT-1',
'id': 1,
'upload_status': None,
'pending_human_reason': None,
'inventory_lines_json': None,
'inventory_snapshot_id': None,
'inventory_source_status': 'resolved',
'inventory_source_code': 'DSB_SLC',
'inventory_source_confirmed_by': None,
'order_data_version': 3,
}
defaults.update(kwargs)
return SimpleNamespace(**defaults)
def test_project_line_retryable_hides_shortage_and_running():
assert project_line_retryable(
inventory_allowed_actions=['retry_inventory_preparation'],
user_line_status='shortage',
) is False
assert project_line_retryable(
inventory_allowed_actions=['retry_inventory_preparation'],
user_line_status='inventory_file_missing',
inventory_rpa_running=True,
) is False
assert project_line_retryable(
inventory_allowed_actions=['retry_inventory_preparation'],
user_line_status='inventory_file_missing',
) is True
def test_decide_completed_is_noop():
task = _task(upload_status='uploaded')
decided = decide_retry_action_only(task, scope='task')
assert decided['action'] == ACTION_NOOP
assert decided['reason_code'] == 'already_completed'
def test_decide_missing_snapshot_fetch(monkeypatch):
task = _task(inventory_snapshot_id=None, inventory_lines_json=None)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_gate.is_inventory_source_stable',
lambda _t: True,
)
decided = decide_retry_action_only(task, scope='task')
assert decided['action'] == ACTION_FETCH_INVENTORY
def test_decide_rpa_pending_already_running():
task = _task(pending_human_reason='rpa_pending')
decided = decide_retry_action_only(task, scope='task')
assert decided['action'] == ACTION_NOOP
assert decided['reason_code'] == 'already_running'
def test_fulfillable_task_without_excel_continues_auto_progress(monkeypatch):
"""库存已完全匹配但 Excel 尚未生成时,任务级重试必须推进后续 Gate。"""
task = _task(
inventory_snapshot_id=7,
inventory_lines_json=[{'part_number': 'PN-1'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_gate.is_inventory_source_stable',
lambda _t: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.task_retry_decision_service._task_match_hint',
lambda _t: {},
)
decided = decide_retry_action_only(task, scope='task')
assert decided['action'] == ACTION_AUTO_PROGRESS
def test_structured_failed_attempt_overrides_stale_rpa_pending(monkeypatch):
"""逐源 Attempt 已失败时,旧 rpa_pending 摘要不得阻止用户手动重试。"""
task = _task(task_no='OT-FAILED', pending_human_reason='rpa_pending')
class _Query:
calls = 0
def filter(self, *_args):
return self
def order_by(self, *_args):
return self
def first(self):
self.calls += 1
if self.calls == 1:
return None
return SimpleNamespace(status='failed')
monkeypatch.setattr(
'app.models.ShippingTaskInventoryRpaAttempt.query',
_Query(),
raising=False,
)
assert _is_inventory_rpa_active(task) is False
def test_structured_running_attempt_blocks_duplicate_retry(monkeypatch):
"""逐源 Attempt 仍在运行时,必须拦截重复派发。"""
task = _task(task_no='OT-RUNNING', pending_human_reason=None)
class _Query:
def filter(self, *_args):
return self
def order_by(self, *_args):
return self
def first(self):
return SimpleNamespace(status='running')
monkeypatch.setattr(
'app.models.ShippingTaskInventoryRpaAttempt.query',
_Query(),
raising=False,
)
assert _is_inventory_rpa_active(task) is True
def test_execute_rolls_back_before_returning_unexpected_failure(monkeypatch):
"""下游数据库失败后,返回失败结果前必须清理 Session,供审计链继续写入。"""
task = _task(task_no='OT-ROLLBACK')
rollback_calls = []
monkeypatch.setattr(
'app.services.shipping_notice.task_retry_decision_service.db.session.rollback',
lambda: rollback_calls.append(True),
)
monkeypatch.setattr(
'app.services.shipping_notice.tools.auto_progress',
lambda _payload: (_ for _ in ()).throw(RuntimeError('database write failed')),
)
result = _execute(
task=task,
user_id=7,
decided={'action': ACTION_AUTO_PROGRESS},
continue_auto_progress=False,
decision_version=3,
idempotency_key='auto-progress:OT-ROLLBACK:v3',
line_key=None,
)
# 关键断言:审计在 _execute 返回后才写,故必须已恢复可用事务。
assert rollback_calls == [True]
assert result['action'] == ACTION_FAILED
assert result['status'] == 'failed'
def test_execute_fetch_retry_rpa_submits_formal_gate_action(monkeypatch):
"""正式 retry_rpa 必须提交正式 Gate Action。"""
task = _task(task_no='OT-TRIGGER-DIRECT', inventory_snapshot_id=None, inventory_lines_json=None)
captured: dict[str, object] = {}
monkeypatch.setattr(
'app.services.shipping_notice.task_retry_decision_service._request_formal_gate_action',
lambda **kwargs: captured.update(kwargs) or {'status': 'running'},
)
result = _execute(
task=task,
user_id=7,
decided={'action': ACTION_FETCH_INVENTORY},
continue_auto_progress=False,
decision_version=3,
idempotency_key='inventory-fetch:OT-TRIGGER-DIRECT:DSB_SLC:v3',
line_key=None,
trigger='conversation_retry',
)
assert result['status'] == 'running'
assert captured['action_code'] == 'retry_inventory_preparation'
def test_execute_rematch_submits_formal_gate_action(monkeypatch):
"""库存匹配节点重试必须提交正式 Gate Action。"""
task = _task(task_no='OT-REMATCH', inventory_snapshot_id=9, inventory_lines_json=[])
captured: dict[str, object] = {}
monkeypatch.setattr(
'app.services.shipping_notice.task_retry_decision_service._request_formal_gate_action',
lambda **kwargs: captured.update(kwargs) or {'status': 'running'},
)
result = _execute(
task=task,
user_id=7,
decided={'action': ACTION_REMATCH},
continue_auto_progress=False,
decision_version=3,
idempotency_key='inventory-rematch:OT-REMATCH:v3',
line_key=None,
trigger='user_retry',
)
assert result['status'] == 'running'
assert captured['action_code'] == 'retry_inventory_from_matching'
def test_execute_fetch_uses_formal_gate_action_instead_of_legacy_inventory(monkeypatch):
"""外部 retry_rpa 必须提交正式 Gate Action,不能直接执行旧库存函数。"""
task = _task(task_no='OT-FORMAL-RETRY', inventory_snapshot_id=None, inventory_lines_json=None)
captured: dict[str, object] = {}
import app.services.shipping_notice.task_retry_decision_service as service
import app.services.shipping_notice.inventory_workflow as inventory_workflow
monkeypatch.setattr(inventory_workflow, 'ensure_inventory', lambda _payload: (_ for _ in ()).throw(
AssertionError('legacy inventory workflow must not be called by external retry')
))
monkeypatch.setattr(
service,
'_request_formal_gate_action',
lambda **kwargs: captured.update(kwargs) or {'status': 'running', 'action': 'fetch_inventory'},
raising=False,
)
result = service._execute(
task=task,
user_id=7,
decided={'action': ACTION_FETCH_INVENTORY},
continue_auto_progress=False,
decision_version=3,
idempotency_key='formal-retry:OT-FORMAL-RETRY:v3',
line_key=None,
trigger='user_retry',
)
assert result['status'] == 'running'
assert captured['action_code'] == 'retry_inventory_preparation'
def test_execute_rematch_uses_formal_gate_action_instead_of_legacy_match(monkeypatch):
"""外部 rematch 必须提交正式 Gate Action,不能直接执行旧匹配函数。"""
task = _task(task_no='OT-FORMAL-REMATCH', inventory_snapshot_id=9, inventory_lines_json=[])
captured: dict[str, object] = {}
import app.services.shipping_notice.task_retry_decision_service as service
import app.services.shipping_notice.tools as shipping_tools
monkeypatch.setattr(shipping_tools, 'match_inventory', lambda _payload: (_ for _ in ()).throw(
AssertionError('legacy match workflow must not be called by external retry')
))
monkeypatch.setattr(
service,
'_request_formal_gate_action',
lambda **kwargs: captured.update(kwargs) or {'status': 'running', 'action': 'rematch'},
raising=False,
)
result = service._execute(
task=task,
user_id=7,
decided={'action': ACTION_REMATCH},
continue_auto_progress=False,
decision_version=3,
idempotency_key='formal-rematch:OT-FORMAL-REMATCH:v3',
line_key=None,
trigger='user_retry',
)
assert result['status'] == 'running'
assert captured['action_code'] == 'retry_inventory_from_matching'
+59 -1
View File
@@ -1,6 +1,7 @@
import pytest
from flask import g
from app import create_app, db
from app.models import Agent, User
from app.models import Agent, ChatSession, User
@pytest.fixture
def client():
@@ -97,3 +98,60 @@ def test_chat_url_logic(client):
res = client.get('/api/chat/sessions', headers=headers, json={'agent_id': agent_id})
assert res.status_code == 403
assert res.get_json()['error'] == 'Permission denied for this agent'
def test_chat_completions_stream_reads_session_snapshot_after_commit(client, monkeypatch):
"""
提交会话后消费 SSE 时使用标量快照,避免已脱离 Session 的 ORM 实例被延迟刷新。
关键断言:生成器在请求返回后仍能产出 session_created 事件,而不会抛出
DetachedInstanceError。
"""
with client.application.app_context():
user = User(username='stream-user', role='admin', email='stream-user@example.com')
agent = Agent(name='Stream Agent', dify_api_key='test-key', api_base_url='http://dify.invalid')
db.session.add_all([user, agent])
db.session.commit()
user_id = user.id
agent_id = agent.id
monkeypatch.setattr(
'app.services.chat.executors.stream_chat_via_executor',
lambda _context: iter(['data: {"event": "message_end"}\n\n']),
)
from app.api.chat import completions
captured_session = None
original_ensure_chat_session = completions._ensure_chat_session
def capture_ensured_session(*args, **kwargs):
nonlocal captured_session
captured_session = original_ensure_chat_session(*args, **kwargs)
return captured_session
monkeypatch.setattr(completions, '_ensure_chat_session', capture_ensured_session)
def get_current_user():
current_user = db.session.get(User, user_id)
g.current_user = current_user
return current_user
monkeypatch.setattr('app.core.decorators._get_current_user', get_current_user)
with client.application.test_request_context(
'/api/chat/completions',
method='POST',
json={'agent_id': agent_id, 'query': '测试流式会话'},
):
response = client.application.view_functions['chat.chat_completions']()
# 模拟生产环境:流式处理中的事务令 ORM 属性过期,随后请求 scoped Session 被清理。
assert captured_session is not None
db.session.expire(captured_session)
db.session.remove()
body = ''.join(response.response).encode()
assert response.status_code == 200
assert b'"event": "session_created"' in body
assert b'DetachedInstanceError' not in body
with client.application.app_context():
assert ChatSession.query.filter_by(user_id=user_id, agent_id=agent_id).count() == 1
+16
View File
@@ -53,6 +53,22 @@ def test_shipping_worker_claims_unified_pdf_automark_jobs(monkeypatch):
assert JobType.SHIPPING_PDF_AUTOMARK in received['job_types']
def test_shipping_worker_claims_review_revalidate_jobs(monkeypatch):
"""Review Revalidate Job 必须进入 shipping worker 领取白名单,不能永久 queued。"""
received: dict[str, object] = {}
def claim_next_job(**kwargs):
received.update(kwargs)
return None
monkeypatch.setattr('app.jobs.queue.claim_next_job', claim_next_job)
queue_service.claim_next_shipping_notice_job()
# 关键断言:字段变更后的异步校验任务必须由 shipping worker 领取。
assert JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS in received['job_types']
def test_route_runtime_diagnostic_identifies_loaded_workflow_without_document_content():
"""路由审计必须可定位 Worker 代码身份,且不得采集文档或字段内容。"""
from app.jobs.handlers import shipping_order_extraction as handler