feat(shipping-notice): 新增通用解析能力,优化性能并清理遗留废弃代码
This commit is contained in:
1 parent
935bf26fa6
commit
7cfd5d167e
230 files changed
+9337
-10989
No files matched your search
@@ -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)))
|
||||
|
||||
@@ -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 不含旧流程字段)
|
||||
# ============================================================
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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
|
||||
@@ -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]
|
||||
@@ -250,3 +250,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'
|
||||
@@ -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'
|
||||
@@ -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'
|
||||
@@ -19,6 +19,7 @@ from app.services.shipping_notice.document_layout.coordinate_table_reconstructio
|
||||
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
|
||||
@@ -217,6 +218,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(
|
||||
@@ -306,6 +373,26 @@ def test_coordinate_profile_rows_apply_selected_anchor_frame_translation_to_all_
|
||||
}
|
||||
|
||||
|
||||
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 = {
|
||||
@@ -897,6 +984,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',
|
||||
@@ -907,13 +995,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(
|
||||
|
||||
@@ -601,6 +601,36 @@ def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app):
|
||||
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():
|
||||
@@ -644,6 +674,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
|
||||
|
||||
@@ -12,6 +12,7 @@ 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,
|
||||
@@ -66,6 +67,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)]}
|
||||
@@ -595,11 +609,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)],
|
||||
}],
|
||||
},
|
||||
)
|
||||
@@ -645,11 +655,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
|
||||
@@ -12,7 +12,7 @@ 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.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:
|
||||
@@ -126,59 +126,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
|
||||
|
||||
@@ -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,10 @@ from app.services.shipping_notice.query_service import (
|
||||
resolve_task_from_payload,
|
||||
serialize_task,
|
||||
task_export_error_message,
|
||||
task_sort_key,
|
||||
)
|
||||
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():
|
||||
@@ -434,7 +407,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)
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -703,79 +703,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)
|
||||
|
||||
|
||||
@@ -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_five_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_five_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"]["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,14 +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": "freight_upload", "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:
|
||||
@@ -209,7 +203,7 @@ 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',
|
||||
]
|
||||
|
||||
|
||||
@@ -244,8 +238,8 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No
|
||||
]
|
||||
|
||||
|
||||
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",
|
||||
@@ -258,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"] == "freight_upload"
|
||||
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
|
||||
@@ -626,10 +626,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 +669,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 +702,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):
|
||||
|
||||
@@ -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
|
||||
@@ -935,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
|
||||
@@ -1106,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=[])
|
||||
|
||||
@@ -1905,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():
|
||||
@@ -2171,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,
|
||||
@@ -2443,46 +2519,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():
|
||||
@@ -2678,114 +2714,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():
|
||||
@@ -2861,7 +2789,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)
|
||||
@@ -2887,7 +2814,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(
|
||||
@@ -2910,7 +2836,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(
|
||||
@@ -3433,26 +3358,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
|
||||
|
||||
@@ -161,6 +161,34 @@ def test_anchor_frame_transform_moves_order_number_anchor_and_value_together():
|
||||
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={
|
||||
|
||||
@@ -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,
|
||||
@@ -151,6 +155,69 @@ def test_anchor_frame_matches_bounded_vertical_translation_without_changing_lega
|
||||
assert legacy_result.candidates[0].coordinate_transform is None
|
||||
|
||||
|
||||
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()
|
||||
@@ -248,14 +315,16 @@ def test_profile_matcher_uses_persisted_lightweight_features_when_glyphs_are_com
|
||||
'tables': complete_layout['tables'],
|
||||
'coordinate_evidence': {'pages': complete_layout['coordinate_evidence']['pages']},
|
||||
'matching_features': {
|
||||
'version': 'shipping-layout-matching-features.v1',
|
||||
'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_tokens': ['item', 'no', 'qty'],
|
||||
'column_centers': [0.1225, 0.2825, 0.4225],
|
||||
'column_width_ratios': [0.1611, 0.0722, 0.1167],
|
||||
'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': {},
|
||||
},
|
||||
@@ -269,6 +338,81 @@ def test_profile_matcher_uses_persisted_lightweight_features_when_glyphs_are_com
|
||||
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,111 @@ def test_project_review_case_field_conflicts_empty_without_candidate():
|
||||
assert project_review_case_field_conflicts(case) == []
|
||||
|
||||
|
||||
@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 +262,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(
|
||||
|
||||
@@ -103,6 +103,38 @@ def test_resume_waiting_manual_confirm_when_auto_gate_false(monkeypatch):
|
||||
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')
|
||||
|
||||
@@ -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',
|
||||
]
|
||||
|
||||
|
||||
@@ -445,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(
|
||||
@@ -660,7 +709,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
|
||||
@@ -2008,6 +2057,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'}]},
|
||||
@@ -2024,6 +2075,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);测试显式物化。
|
||||
@@ -2099,17 +2156,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()
|
||||
@@ -2395,6 +2461,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': [
|
||||
@@ -2408,11 +2476,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()
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -187,61 +187,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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -256,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,
|
||||
)
|
||||
@@ -272,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,
|
||||
)
|
||||
@@ -288,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():
|
||||
@@ -477,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',
|
||||
@@ -486,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', 'freight_upload'),
|
||||
('inventory_matching', 'fulfillment_prep'),
|
||||
('artifact_generation', 'fulfillment_prep'),
|
||||
('freight_upload_rpa', 'freight_upload'),
|
||||
],
|
||||
)
|
||||
def test_batch_lifecycle_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_lifecycle_nodes_maps_auto_progress_gate_stages(
|
||||
@pytest.mark.parametrize(
|
||||
('item', 'expected_lifecycle_stage'),
|
||||
[
|
||||
({'user_stage': 'inventory_match'}, 'fulfillment_prep'),
|
||||
({'user_stage': 'freight_upload'}, 'freight_upload'),
|
||||
({'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_lifecycle_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([{
|
||||
nodes = _batch_lifecycle_nodes([{
|
||||
**item,
|
||||
'status': 'waiting_human',
|
||||
'user_status': 'waiting_human',
|
||||
@@ -158,6 +187,42 @@ def test_batch_lifecycle_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases
|
||||
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({
|
||||
@@ -202,41 +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': 'freight_upload', '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 覆盖库存准备阶段。"""
|
||||
@@ -360,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():
|
||||
@@ -483,67 +540,44 @@ def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_s
|
||||
"""五阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。"""
|
||||
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_payload_exposes_five_nodes_and_unverified_legacy_completion_stays_freight_upload(app) -> None:
|
||||
"""新字段固定五节点,兼容字段同值,旧 technical completed 不得计作通知完成。"""
|
||||
with app.app_context():
|
||||
projection = _conversation_processing_from_work_items([{
|
||||
'work_item_type': 'order_task', 'work_item_no': 'OT-LEGACY-UPLOADED',
|
||||
'root_order_task_no': 'OT-LEGACY-UPLOADED', 'source_type': 'direct_pdf',
|
||||
'shipping_notice_no': 'SN-LEGACY-UPLOADED', 'has_formal_ot': True,
|
||||
'source_summary': {'document_id': 601, 'filename': 'legacy.pdf'},
|
||||
'status': 'completed', 'stage': 'completed',
|
||||
'user_status': 'completed', 'user_stage': 'completed',
|
||||
'verified_upload_success': False,
|
||||
'available_actions': [], 'facts': {'upload_state': 'succeeded'},
|
||||
}])
|
||||
|
||||
assert [node['code'] for node in projection['lifecycle_nodes']] == [
|
||||
'intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete',
|
||||
]
|
||||
assert projection['four_stage_nodes'] == projection['lifecycle_nodes']
|
||||
freight = next(node for node in projection['lifecycle_nodes'] if node['code'] == 'freight_upload')
|
||||
assert freight['summary']['needs_action'] == 1
|
||||
assert freight['summary']['completed'] == 0
|
||||
assert projection['summary']['completed'] == 0
|
||||
assert projection['status_groups']['completed'] == []
|
||||
assert [row['user_task_no'] for row in projection['status_groups']['waiting_human']] == [
|
||||
'OT-LEGACY-UPLOADED',
|
||||
]
|
||||
|
||||
|
||||
def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None:
|
||||
def test_batch_lifecycle_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None:
|
||||
"""同一 EML 的两份订单 PDF 应在五阶段摘要中计为两项,而非一张父卡。"""
|
||||
nodes = _batch_four_stage_nodes([{
|
||||
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'},
|
||||
@@ -551,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'},
|
||||
@@ -565,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'},
|
||||
@@ -595,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'},
|
||||
},
|
||||
@@ -623,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
|
||||
@@ -671,10 +711,10 @@ def test_cancelled_or_archived_file_stays_in_history_and_out_of_completion_metri
|
||||
with app.app_context():
|
||||
work_items = [{
|
||||
'work_item_type': 'order_task',
|
||||
'work_item_no': f'OT-{terminal_status.upper()}',
|
||||
'user_status': terminal_status,
|
||||
'work_item_no': f'OT-{terminal_status.upper()}',
|
||||
'user_group': terminal_status,
|
||||
'user_status': terminal_status,
|
||||
'user_stage': 'freight_uploading',
|
||||
# 覆盖历史兼容载荷尚未写入 user_group 的回退路径。
|
||||
'status': terminal_status,
|
||||
'stage': terminal_status,
|
||||
'source_summary': {'document_id': 570, 'filename': 'history.pdf'},
|
||||
@@ -684,10 +724,7 @@ def test_cancelled_or_archived_file_stays_in_history_and_out_of_completion_metri
|
||||
assert projection['summary']['history'] == 1
|
||||
assert projection['summary']['total_files'] == 0
|
||||
assert projection['summary']['completed_files'] == 0
|
||||
assert projection['completed'] == []
|
||||
assert [row['user_task_no'] for row in projection['history']] == [
|
||||
f'OT-{terminal_status.upper()}',
|
||||
]
|
||||
assert projection['status_groups']['completed'] == []
|
||||
assert [row['user_task_no'] for row in projection['status_groups'][terminal_status]] == [
|
||||
f'OT-{terminal_status.upper()}',
|
||||
]
|
||||
@@ -729,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,
|
||||
@@ -756,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': {
|
||||
@@ -765,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': {
|
||||
@@ -1059,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
|
||||
@@ -1098,6 +1270,108 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -
|
||||
]
|
||||
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 仍必须保留后端裁决的入口。"""
|
||||
@@ -1246,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'},
|
||||
@@ -1262,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'},
|
||||
},
|
||||
])
|
||||
|
||||
@@ -1279,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,
|
||||
@@ -1323,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'},
|
||||
@@ -1660,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,禁止全空摘要。
|
||||
@@ -1745,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
|
||||
@@ -1879,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 覆盖。
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -554,70 +554,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
|
||||
|
||||
@@ -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
|
||||
@@ -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,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'
|
||||
Reference in new issue
Block a user