feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口

完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
This commit is contained in:
hugo committed 2026-08-11 14:04:39 +08:00
1 parent 8e0bbf7a81
commit c94d173f92
181 files changed
+12947 -1724

No files matched your search

+79 -2
View File
@@ -223,6 +223,65 @@ def seed_task_inventory_source(
task.inventory_source_method = "rule_exact"
task.inventory_source_config_version = inventory_sources_runtime_version()
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
if getattr(task, '_test_customer_confirmed', False) and not task.order_snapshot_id:
freeze_test_task_order_snapshot(task)
def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
"""将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。"""
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
if task.order_snapshot_id:
return
rows = list(getattr(task, '_test_order_rows', []) or [])
if not rows:
lines = task.lines_json if isinstance(task.lines_json, list) else []
rows = [
{
'part_number': row.get('part_number'),
'reservation_id': row.get('reservation_id'),
'qty': row.get('qty'),
}
for row in lines if isinstance(row, dict)
]
task._test_order_rows = rows
_ensure_test_task_dynamic_order(task)
task.order_data_version = int(task.order_data_version or 1)
from app import db
from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction
db.session.flush()
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
customer = getattr(getattr(task, 'shipping_case', None), 'customer', None)
if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by(
extraction_id=extraction.id, role='bill_to',
).one_or_none() is None:
db.session.add(ShippingOrderCustomerMatch(
extraction_id=extraction.id, role='bill_to',
raw_name=customer.standard_name,
normalized_name=str(customer.standard_name or '').upper(), status='confirmed',
customer_id=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
identity_fingerprint='r' * 64,
identity_rule_version='test.v1', resolution_method='manual',
confirmation_reason='测试确认', confirmed_by_id=None,
))
db.session.flush()
freeze_order_snapshot(
task,
actor_id=None,
expected_order_data_version=int(task.order_data_version),
freeze_mode='auto',
auto_freeze_policy={
'test_fixture': True,
'enabled': True,
'mode': 'qualified',
'qualification_status': 'qualified',
'customer_scope_status': 'allowed',
'blocking_reason_codes': [],
},
)
db.session.flush()
def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
@@ -328,7 +387,7 @@ def inventory_xlsx_with_warehouse(
warehouse_id: str,
*,
sku: str = "A001",
reservation_id: str = "R-1",
reservation_id: str = "00001",
qty: int = 1,
) -> "BytesIO":
"""生成符合发布解析方案的库存 Excel,供身份、结构和库存解析测试使用。"""
@@ -387,6 +446,16 @@ def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
return item
def v2_inventory_batch_payload(payload: dict) -> dict:
"""测试构造器:补齐冻结 shipping_inventory_rpa.v2 回调 envelope。"""
body = dict(payload or {})
run_no = str(body.get('batch_run_no') or body.get('run_no') or '').strip()
body.setdefault('schema_version', 'shipping_inventory_rpa.v2')
body.setdefault('callback_id', f'test-callback:{run_no or "unknown"}')
body.setdefault('batch_run_no', run_no)
return body
def rpa_callback_payload(
task: "ShippingNotice",
file_path: str | Path,
@@ -394,14 +463,22 @@ def rpa_callback_payload(
run_no: str = "RUN-TEST-001",
status: str = "success",
) -> dict:
"""构造通过单任务 RPA 回调身份/run_no 校验的最小 payload。"""
"""构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。"""
return {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"test-callback:{run_no}",
"task_id": task.task_no,
"status": status,
"file_path": str(file_path),
"run_no": run_no,
"source_run_no": run_no,
"source_code": task.inventory_source_code,
"warehouse_id": task.inventory_warehouse_id,
"attempt_no": 1,
"lease_token": "test-lease-token",
"candidate_set_id": 1,
"execution_id": 1,
"gate_id": 1,
}
+48
View File
@@ -0,0 +1,48 @@
"""
tests/jobs/test_runner.py
用途:验证 Worker Handler 异常后的事务清理与 Job 失败收口顺序。
依赖:app.jobs.runner、可替换的 queue/handler/store/db session。
逻辑:模拟 Handler 抛出数据库异常,确认 runner 先 rollback,再调用 mark_failed。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
def test_handler_error_rolls_back_before_mark_failed(monkeypatch):
"""Handler 失败后必须先清理 aborted Session,避免失败收口再次查询失败。"""
from app.jobs import runner
events: list[str] = []
class _Logger:
def info(self, *_args, **_kwargs):
pass
def exception(self, *_args, **_kwargs):
pass
def error(self, *_args, **_kwargs):
pass
class _Session:
def rollback(self):
events.append('rollback')
class _Db:
session = _Session()
job = {'id': 939, 'job_type': 'shipping_auto_progress', '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)))
monkeypatch.setattr('app.db', _Db(), raising=False)
with pytest.raises(StopIteration):
runner.run_forever(SimpleNamespace(extras={'queues': ['shipping']}, config={}, logger=_Logger()), poll_interval_seconds=0)
assert events == ['rollback', 'mark_failed']
@@ -75,3 +75,5 @@ def test_permission_request_approve(app, monkeypatch):
def test_permission_request_not_found(app):
with app.app_context():
with pytest.raises(NotFoundError):
permission_service.approve_permission_request(999999)
@@ -41,6 +41,8 @@ def test_soft_delete_document_cancels_active_jobs(app):
source_file_name='doc.pdf',
source_file_path='data/kb/doc.pdf',
)
db.session.add_all([group, document, version])
db.session.flush()
queued = KbJob(
job_type='clean',
status='queued',
@@ -49,7 +51,7 @@ def test_soft_delete_document_cancels_active_jobs(app):
document_version_id=version.id,
progress=0,
)
db.session.add_all([group, document, version, queued])
db.session.add(queued)
db.session.commit()
assert document_service.soft_delete_document(document.id, user_id=1) is True
@@ -15,6 +15,7 @@ from app.models import (
ShippingInventoryCandidateSource,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingInventoryFile,
)
from app.services.shipping_notice.inventory_candidate_projection import (
project_inventory_candidate_facts,
@@ -141,3 +142,32 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
assert facts['blocking_reason']['code'] == 'inventory_candidate_version_stale'
assert facts['candidate_set_id'] == new_set.id
assert facts['line_resolutions'][0]['candidate_set_id'] == old_set.id
def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app):
"""行级证据 SHA 必须从正式库存快照读取,不能依赖可选 detail_json。"""
with app.app_context():
task = _task('SN-CAND-EVIDENCE')
candidate_set = _candidate_set(task)
db.session.add(ShippingInventoryCandidateLine(
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
))
db.session.flush()
snapshot = ShippingInventoryFile(
inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64,
)
db.session.add(snapshot)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=int(task.id), line_key='line-1', candidate_set_id=int(candidate_set.id),
candidate_set_version=1, inventory_snapshot_id=int(snapshot.id), match_result='matched',
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=snapshot.inventory_file_no,
matched_row_index=9, is_current=True, detail_json={},
))
db.session.commit()
facts = project_inventory_candidate_facts(task)
assert facts['line_resolutions'][0]['inventory_file_sha256'] == 'b' * 64
assert facts['line_resolutions'][0]['inventory_row_index'] == 9
@@ -202,7 +202,7 @@ def _mock_case_for_p4(case_no='CASE-2608-0042'):
return case
def _install_minimal_mocks(monkeypatch, case=None):
def _install_minimal_mocks(monkeypatch, case=None, app=None):
if case is None:
case = _mock_case_for_p4()
@@ -242,19 +242,20 @@ def _install_minimal_mocks(monkeypatch, case=None):
def _fake_visible(case_no, user_id, is_admin): # noqa: ARG001
return case
monkeypatch.setattr(mod.ShippingOrderReviewCase, 'query', _CaseQuery())
monkeypatch.setattr(mod, 'get_review_case_visible_to_user', _fake_visible)
# SQLAlchemy 的 Model.query 是 Flask app-context scoped descriptor;给测试替换
# 类属性前先进入 fixture 提供的 app context,避免纯合同测试被上下文机制阻断。
monkeypatch.setattr(
mod,
'ShippingOrderReviewCase',
SimpleNamespace(query=_CaseQuery(), id=SimpleNamespace(desc=lambda: None)),
)
monkeypatch.setattr(mod, 'get_review_case_visible_to_user', _fake_visible, raising=False)
# 避免 Job.query / db.session.get / CaseEvent 等深层调用触发
monkeypatch.setattr(mod.db.session, 'get', _fake_get)
monkeypatch.setattr(mod.db, 'session', MagicMock(
commit=lambda: None,
rollback=lambda: None,
flush=lambda: None,
add=lambda _x: None,
))
monkeypatch.setattr(mod.db, 'session', MagicMock())
# L1-L3 对账直接返回 NONE(避免 hit 真 DB)
mod.query_case_task_ownership = lambda *_a, **_kw: { # type: ignore[method-assign]
'match_level': 'NONE',
'match_level': 'none',
'confidence': 'LOW',
'task_no': None,
'candidate_matches': [],
@@ -55,6 +55,8 @@ T1_MATRIX = [
(None, None, False, 'None 码 → fail-closed 不可重试'),
# category_hint 与前缀冲突:前缀优先(空码除外)
('SHIPPING.TRANSIENT_NETWORK', 'worker_timeout', True, '前缀命中即使 hint 不同也可重试'),
('trigger_not_claimed_missing', None, True, '库存 Trigger 缺失 → 技术重试'),
('trigger_not_claimed_timeout', None, True, '库存 Trigger 超时 → 技术重试'),
]
@@ -66,8 +66,11 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
if code == 'packing_reference':
field = extension
else:
field = ShippingOrderField.query.filter_by(field_code=code).one()
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
field = ShippingOrderField.query.filter_by(
field_code=code,
scope=scope,
).one()
value_type = field.value_type
fields[code] = field
definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': value_type, 'enabled': True})
@@ -287,8 +290,16 @@ def test_auto_freeze_readiness_fails_closed_with_run_policy_blockers(app):
assert blocked_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
issues = blocked_error.value.details['issues']
assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_scope_not_configured'} in issues
assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_confirmation_required'} in issues
assert any(
item.get('reason') == 'auto_freeze_blocked'
and item.get('blocking_reason_code') == 'customer_scope_not_configured'
for item in issues
)
assert any(
item.get('reason') == 'auto_freeze_blocked'
and item.get('blocking_reason_code') == 'customer_confirmation_required'
for item in issues
)
assert any(item['reason'] == 'auto_freeze_not_enabled' for item in issues)
+12 -13
View File
@@ -4,9 +4,9 @@ from app.models import User, Agent, Department, PermissionRequest
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
# 必须在扩展初始化前选择 testing 配置;create_app() 默认会绑定开发 PostgreSQL,
# 之后再覆盖 URI 不会迁移已绑定的 engine,容易把夹具写入共享库并污染全量测试。
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
@@ -24,9 +24,8 @@ def get_headers(client, username='admin', password='admin'):
res = client.post('/api/user/login', json={'username': username, 'password': password})
data = res.get_json()
return {
'X-User-Id': str(data['id']),
'X-Username': data['username'],
'X-Role': data['role']
'Authorization': f"Bearer {data['access_token']}",
'Content-Type': 'application/json',
}
def test_department_crud(client):
@@ -114,6 +113,7 @@ def test_permission_flow(client):
client.post('/api/admin/agents', json={
'name': 'Test Agent',
'dify_app_id': 'app-123'
, 'dify_api_key': 'test-key'
}, headers=admin_headers)
agent_id = 1
@@ -129,13 +129,12 @@ def test_permission_flow(client):
# User Login
user_headers = get_headers(client, 'user1', 'password')
# Request Permission
res = client.post('/api/user/permission-requests', json={
'agent_id': agent_id,
'reason': 'I need it'
}, headers=user_headers)
assert res.status_code == 201
req_id = res.get_json()['id']
# 当前后端只保留管理员审批 API;测试直接创建待审事实,避免依赖已移除的用户申请路由。
with client.application.app_context():
request_row = PermissionRequest(user_id=2, agent_id=agent_id, reason='I need it', status='pending')
db.session.add(request_row)
db.session.commit()
req_id = request_row.id
# Admin List Requests
res = client.get('/api/admin/permission-requests', headers=admin_headers)
@@ -446,7 +446,8 @@ def test_shipping_customer_shadow_report_and_label_api(app, client):
report = parse_api_data(report_response.get_json())
assert report['total'] == 1
assert report['items'][0]['candidate_no'] == 'SNC-SHADOW-API'
assert report['auto_resolution']['enabled'] is False
# 当前安全默认是开启受控自动客户确认;质量门禁仍决定是否允许实际自动确认。
assert report['auto_resolution']['enabled'] is True
assert report['auto_resolution']['recent_events'] == []
label_response = client.put(
@@ -68,8 +68,12 @@ def test_admin_can_list_and_view_immutable_schema_history(app, client):
}, actor_id=1)
first = _publish_version(field['id'], display_name='采购订单号')
second = _publish_version(field['id'], display_name='客户订单号', source_version_id=first['id'])
current_field = next(
item for item in service.get_state()['fields'] if item['id'] == field['id']
)
service.save_field({
'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string',
'display_name': '采购订单号(更新)',
'expected_updated_at': current_field['updated_at'],
}, actor_id=1, field_id=field['id'])
forbidden = client.get('/api/admin/shipping-order-schema/versions', headers=_headers('schema-history-user', 'user'))
@@ -84,7 +88,10 @@ def test_admin_can_list_and_view_immutable_schema_history(app, client):
assert 'definition' not in page['items'][0]
assert page['items'][0]['published_by']['display_name'] == '版本管理员'
exact = client.get('/api/admin/shipping-order-schema/versions?version_number=1', headers=_headers('schema-history-admin', 'admin'))
exact = client.get(
f"/api/admin/shipping-order-schema/versions?version={first['version']}",
headers=_headers('schema-history-admin', 'admin'),
)
assert exact.status_code == 200
assert parse_api_data(exact.get_json())['items'][0]['id'] == first['id']
@@ -16,6 +16,54 @@ from app.services.shipping_notice.conversation_retry_auto_progress_service impor
)
def test_formal_trigger_failure_overrides_stale_automation(monkeypatch):
"""最新 Attempt 的 Trigger 缺失事实优先于历史 Job 的 needs_human 投影。"""
from app.services.shipping_notice import conversation_retry_auto_progress_service as service
task = type('Task', (), {'task_no': 'OT-TRIGGER', 'id': 1})()
class _Query:
def filter_by(self, **_kwargs):
return self
def first(self):
return task
monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False)
monkeypatch.setattr(
'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts',
lambda *_args, **_kwargs: {
'latest_attempts': {
'DSV360_AWSSL': {
'status': 'failed',
'error_code': 'trigger_not_claimed_missing',
},
},
},
)
assert service._formal_task_has_retryable_inventory_trigger_failure('OT-TRIGGER') is True
def test_failed_gate_job_does_not_count_as_active_attempt(monkeypatch):
"""Attempt 残留 queued 但正式 Job 已失败时,不得继续投影 already_running。"""
from app.services.shipping_notice import conversation_retry_auto_progress_service as service
task = type('Task', (), {'task_no': 'OT-STALE', 'id': 1})()
class _Query:
def filter_by(self, **_kwargs):
return self
def first(self):
return task
monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False)
monkeypatch.setattr(
'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts',
lambda *_args, **_kwargs: {'active_attempt_count': 0},
)
assert service._formal_task_has_active_attempt('OT-STALE') is False
def test_skip_reason_maps_queued_and_not_retryable():
"""queued → already_running;retryable=false → not_retryable。"""
assert _skip_reason_from_automation(
@@ -40,6 +88,42 @@ def test_manual_fallback_human_owner_still_retryable():
) is None
def test_inventory_needs_human_remains_retryable():
"""库存快照/RPA 暂态 needs_human 必须继续进入库存重试决策器。"""
assert _skip_reason_from_automation(
{
'status': 'needs_human',
'retryable': True,
'reason_code': 'inventory_snapshot_prepare_failed',
},
task_missing=False,
) is None
def test_missing_inventory_trigger_needs_human_remains_retryable():
"""Trigger 未被领取的技术失败必须继续触发正式 OT 库存重试。"""
assert _skip_reason_from_automation(
{
'status': 'needs_human',
'retryable': True,
'error_code': 'trigger_not_claimed_missing',
},
task_missing=False,
) is None
def test_business_needs_human_stays_skipped():
"""重复/短缺等业务裁决的 needs_human 不得触发库存 RPA。"""
assert _skip_reason_from_automation(
{
'status': 'needs_human',
'retryable': True,
'reason_code': 'inventory_shortage',
},
task_missing=False,
) == 'human_blocking'
def test_task_missing_always_skipped():
assert _skip_reason_from_automation(
{'status': 'failed', 'retryable': True},
@@ -54,7 +138,7 @@ def test_summarize_items_counts_outcomes():
{'outcome': 'skipped', 'reason_code': 'already_running'},
{'outcome': 'failed'},
])
assert summary == {'total': 4, 'retried': 2, 'skipped': 1, 'failed': 1}
assert summary == {'total': 4, 'retried': 2, 'skipped': 1, 'failed': 1, 'blocked': 0}
def test_project_conversation_allowed_actions_empty_without_conversation():
+150 -2
View File
@@ -9,6 +9,7 @@
from __future__ import annotations
import importlib.util
import hashlib
import json
import os
import re
@@ -42,6 +43,16 @@ def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
"requested_at": "2026-07-01T03:23:25.114522",
"mode": "auto",
"attempt": 3,
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": f"SRC-{task_no}:C1",
"source_code": "DSV360_AWSDU",
"source_run_no": f"SRC-{task_no}",
"attempt_no": 3,
"lease_token": "lease-test",
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
"expected_warehouse_id": "AWSDU",
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"connector_type": "dsv360",
@@ -59,6 +70,121 @@ def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
}
def test_single_inventory_trigger_missing_source_run_is_rejected_before_rpa(monkeypatch, tmp_path):
"""缺少 source_run_no 时不生成 None:C1、不启动浏览器,并移入 failed。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
failed_dir = trigger_dir / "failed"
trigger_dir.mkdir()
drop_dir.mkdir()
trigger_path = trigger_dir / "inventory_export_invalid.json"
payload = _build_inventory_export_trigger("SN-IDENTITY-INVALID")
payload.pop("source_run_no")
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
assert callbacks == [
(
"/api/shipping-notice/rpa/inventory-ready",
{
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": None,
"task_no": "SN-IDENTITY-INVALID",
"business_status": "rejected",
"status": "rejected",
"error_code": "trigger_identity_invalid",
"identity_errors": ["source_run_no"],
},
),
]
assert (failed_dir / trigger_path.name).is_file()
def test_single_inventory_trigger_missing_callback_id_is_rejected(monkeypatch, tmp_path):
"""v2 不允许 Worker 推导 callback_id,缺失时必须拒绝。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
trigger_dir.mkdir()
drop_dir.mkdir()
trigger_path = trigger_dir / "inventory_export_missing_callback.json"
payload = _build_inventory_export_trigger("SN-IDENTITY-CALLBACK-INVALID")
payload.pop("callback_id", None)
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
assert callbacks[0][1]["callback_id"] is None
assert callbacks[0][1]["error_code"] == "trigger_identity_invalid"
assert "callback_id" in callbacks[0][1]["identity_errors"]
assert (trigger_dir / "failed" / trigger_path.name).is_file()
def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch, tmp_path):
"""批量成功结果必须原样回传逐源 v2 身份,供后端绑定 SourceAttempt。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
trigger_dir.mkdir()
drop_dir.mkdir()
trigger_path = trigger_dir / "inventory_export_batch_identity.json"
source = {
"source_code": "DBS",
"warehouse_id": "WH-01",
"task_no": "SN-BATCH-IDENTITY",
"callback_id": "SRC-BATCH-001:C1",
"source_run_no": "SRC-BATCH-001",
"attempt_no": 2,
"lease_token": "lease-batch",
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
"expected_warehouse_id": "WH-01",
}
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "BATCH-001:batch:C1",
"batch_run_no": "BATCH-001",
"task_no": "SN-BATCH-IDENTITY",
"inventory_sources": [source],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
result = completed["results"][0]
assert {key: result[key] for key in (
"callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
"lease_token", "candidate_set_id", "execution_id", "gate_id", "expected_warehouse_id",
)} == {
"callback_id": "SRC-BATCH-001:C1",
"task_no": "SN-BATCH-IDENTITY",
"source_code": "DBS",
"source_run_no": "SRC-BATCH-001",
"attempt_no": 2,
"lease_token": "lease-batch",
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
"expected_warehouse_id": "WH-01",
}
def test_env_strips_wrapping_quotes(monkeypatch):
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
worker = _load_freight_rpa_worker()
@@ -443,12 +569,23 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
callback_path, callback_payload = callbacks[0]
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
assert callback_payload == {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
"task_no": "SN-20260629-2EDADC77",
"source_code": "DSV360_AWSDU",
"source_run_no": "SRC-SN-20260629-2EDADC77",
"run_no": "SRC-SN-20260629-2EDADC77",
"attempt_no": 3,
"lease_token": "lease-test",
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
"expected_warehouse_id": "AWSDU",
"status": "success",
"success": True,
"file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
"file_sha256": hashlib.sha256(b"fake inventory content").hexdigest(),
"rpa_mode": "browser",
"source_code": "DSV360_AWSDU",
}
assert not trigger_path.exists()
assert (processed_dir / trigger_path.name).is_file()
@@ -494,12 +631,23 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
callback_path, callback_payload = callbacks[0]
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
assert callback_payload == {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
"task_no": "SN-20260629-2EDADC77",
"source_code": "DSV360_AWSDU",
"source_run_no": "SRC-SN-20260629-2EDADC77",
"run_no": "SRC-SN-20260629-2EDADC77",
"attempt_no": 3,
"lease_token": "lease-test",
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
"expected_warehouse_id": "AWSDU",
"status": "success",
"success": True,
"file_path": str(exported),
"file_sha256": hashlib.sha256(exported.read_bytes()).hexdigest(),
"rpa_mode": "mock",
"source_code": "DSV360_AWSDU",
}
assert not trigger_path.exists()
assert (processed_dir / trigger_path.name).is_file()
@@ -161,6 +161,34 @@ def test_result_missing_projects_file_missing_and_retry_prep():
assert ACTION_CLOSE in view['line_allowed_actions']
def test_line_inventory_view_preserves_evidence_identity_fields():
"""行投影必须保留文件 SHA、文件行号与匹配 Attempt,供证据审计展示。"""
view = project_line_inventory_view(
has_formal_ot=True,
fact={
'match_result': 'matched',
'inventory_status': 'ready',
'available_qty': '8',
'inventory_snapshot_id': 9,
'matched_at': '2026-08-07T00:00:00',
'inventory_file_no': 'INV-001',
'file_sha256': 'a' * 64,
'matched_row_index': 17,
'match_attempt_id': 301,
'inventory_source_code': 'DBS_DUB',
},
required_qty='3',
stored_line_status='ready_to_fulfill',
decision_source='system',
can_fulfill_complete_line=True,
)
assert view['inventory_file_no'] == 'INV-001'
assert view['inventory_file_sha256'] == 'a' * 64
assert view['inventory_row_index'] == 17
assert view['match_attempt_id'] == 301
def test_user_status_maps_closed_and_system_ready():
"""存储态关闭与系统 ready 投影为用户态。"""
assert project_user_line_status(
@@ -56,6 +56,49 @@ def test_persist_without_snapshot_forbids_ready_not_found(app):
assert added[0].available_qty is None
def test_persist_prefers_formal_draft_line_key_over_matcher_temporary_key(app):
"""匹配器 line-1 不得覆盖 Case 草稿 machine-1 的正式明细身份。"""
from app.services.shipping_notice import line_inventory_match_persistence as svc
task = SimpleNamespace(id=1, inventory_snapshot_id=7)
added = []
with app.app_context():
with (
patch.object(svc, 'resolve_review_case_for_task', return_value=SimpleNamespace(id=3)),
patch.object(svc, '_draft_line_keys_by_index', return_value={0: 'machine-1'}),
patch.object(svc, 'get_active_candidate_set', return_value=None),
patch.object(svc, 'get_active_candidate_lines', return_value=[]),
patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q,
patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)),
patch.object(svc.db.session, 'flush'),
):
match_q.filter_by.return_value.first.return_value = None
match_q.filter_by.return_value.update.return_value = None
svc.persist_line_inventory_match_facts(
task=task,
inventory_snapshot_id=7,
match_payload={
'line_results': [{
'line_index': 0,
'disposition': 'shortage',
'part_number': 'PN1',
'reservation_id': 'R1',
'required_qty': 30,
'available_qty': 14,
'shortage_qty': 16,
}],
'resolutions': [{'line_index': 0, 'line_key': 'line-1'}],
},
)
assert len(added) == 1
assert added[0].line_key == 'machine-1'
assert added[0].available_qty == '14'
assert added[0].shortage_qty == '16'
def test_unit_participates_in_match_key():
"""BE-6:同料号预约单但单位不同不得命中。"""
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
@@ -98,6 +141,67 @@ def test_unit_participates_in_match_key():
assert out_ok['line_results'][0].get('unit') == 'PCS'
def test_reservation_part_match_without_unit_aggregates_fourteen_rows():
"""库存 Profile 未配置单位时,Reservation+料号命中 14 行并汇总为 14。"""
from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates
inventory = [
{
'part_number': 'D4-A08AR12000002',
'reservation_id': '2000484577',
'available_qty': 1,
'__source_code': 'DSV360_AWSBI_BYAWSCMH01',
}
for _ in range(14)
]
out = match_order_lines_across_candidates(
order_lines=[{
'part_number': 'D4-A08AR12000002',
'reservation_id': '2000484577',
'quantity': 30,
}],
inventory_lines=inventory,
)
line = out['line_results'][0]
assert out['match_status'] == 'partial'
assert line['available_qty'] == 14.0
assert line['shortage_qty'] == 16.0
def test_profile_match_shortage_payload_keeps_line_index_and_quantities():
"""单源短缺结果必须携带行序,才能写回 machine line 的 current 事实。"""
from app.services.shipping_notice.fulfillment_workflow import (
_profile_match_persistence_payload,
)
payload = _profile_match_persistence_payload(
[{
'part_number': 'D4-A08AR12000002',
'reservation_id': '2000484577',
'required_qty': 30.0,
'available_qty': 14.0,
'shortage_qty': 16.0,
'line_status': 'partial',
}],
inventory_source_code='DSV360_AWSBI_BYAWSCMH01',
)
# 关键断言:持久化层依赖 line_index 关联 Case 草稿的 machine-1;数量不得丢失。
assert payload['line_results'] == [{
'part_number': 'D4-A08AR12000002',
'reservation_id': '2000484577',
'required_qty': 30.0,
'available_qty': 14.0,
'shortage_qty': 16.0,
'line_status': 'partial',
'line_index': 0,
'disposition': 'shortage',
}]
assert payload['resolutions'][0]['line_index'] == 0
assert payload['resolutions'][0]['line_key'] is None
assert payload['resolutions'][0]['resolved_inventory_source_code'] == 'DSV360_AWSBI_BYAWSCMH01'
def test_compensation_runner_noops_when_flag_disabled(app, monkeypatch):
"""BE-4:flag 关闭时补偿扫描空跑。"""
from app.services.schedule import shipping_post_ot_auto_fulfill_compensation_job as job
@@ -474,6 +474,7 @@ def test_transition_order_extraction_unit_tracks_retry_and_technical_failure(mon
plan = SimpleNamespace(units=[], run=SimpleNamespace(run_no='SNER-PLAN'))
unit = SimpleNamespace(
id=1,
document_id=101,
status='pending',
attempt_count=0,
reason_code=None,
@@ -517,7 +518,11 @@ def test_runtime_snapshot_keeps_frozen_ready_layout_without_db_lookup(monkeypatc
'intake_id': 11,
'documents': [{
'document_id': 101,
'layout_snapshot': {'status': 'ready', 'layout_candidate': {'pages': []}},
'layout_snapshot': {
'status': 'ready',
'layout_candidate': {'pages': []},
'coordinate_evidence': {'pages': {}, 'page_glyphs': {}},
},
'layout_schema_candidates': [{'mapping_status': 'accepted'}],
}],
}],
@@ -551,7 +556,12 @@ def test_runtime_snapshot_hydrates_current_ready_layout_when_snapshot_is_stale(m
unit = SimpleNamespace(intake_id=11, document_id=101)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get',
lambda model, document_id: SimpleNamespace(id=document_id),
lambda model, document_id: SimpleNamespace(
id=document_id,
asset_id=301,
filename='po-1.pdf',
current_layout_version=None,
),
)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction_runtime_snapshot.current_layout_snapshot',
@@ -572,6 +582,8 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
"""工作台文档详情应直接暴露单元选择、预算和失败事实。"""
run = SimpleNamespace(
id=1,
status='processing',
auto_freeze_policy_json=None,
input_snapshot_json={
'schema': {'definition': {'fields': []}},
'intakes': [{
@@ -586,6 +598,7 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
extraction_plan=SimpleNamespace(units=[SimpleNamespace(
id=7,
document_id=101,
created_at=None,
status='failed',
reason_code=None,
selection_batch=1,
@@ -598,6 +611,8 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
'selected_in_batch': 1,
},
result_json={},
cancellation_requested_at=None,
cancellation_completed_at=None,
)]),
)
monkeypatch.setattr(
@@ -615,44 +630,39 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
items = serialize_workspace_run_documents(run)
assert items == [{
'unit_id': 7,
'document_id': 101,
'file_name': 'po-1.pdf',
'status': 'failed',
'selection_batch': 1,
'group_key': '451883815A',
'retry_status': 'failed',
'technical_failure_reason_code': 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
'budget_cost': {
'initial_attachment_budget': 2,
'initial_concurrency_budget': 2,
'selected_in_batch': 1,
},
'po_number': None,
'line_count': 0,
'profile': None,
'email_supplement': {
'status': 'none',
'relation_codes': [],
'conflict_count': 0,
'reservation_id_status': 'unavailable',
'source_type_status': 'unavailable',
},
'reason_code': 'technical_failure',
'review_details': [],
'available_actions': [],
'activity_event_code': None,
'started_at': None,
'last_activity_at': None,
'finished_at': None,
}]
item = items[0]
assert item['unit_id'] == 7
assert item['document_id'] == 101
assert item['file_name'] == 'po-1.pdf'
assert item['status'] == 'failed'
assert item['selection_batch'] == 1
assert item['group_key'] == '451883815A'
assert item['retry_status'] == 'failed'
assert item['technical_failure_reason_code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT'
assert item['budget_cost'] == {
'initial_attachment_budget': 2,
'initial_concurrency_budget': 2,
'selected_in_batch': 1,
}
assert item['reason_code'] == 'technical_failure'
assert item['review_details'] == []
assert item['available_actions'] == ['view_details']
assert item['activity_event_code'] is None
assert item['started_at'] is None
assert item['last_activity_at'] is None
assert item['finished_at'] is None
def test_workspace_documents_show_selected_pdfs_while_layout_is_pending(monkeypatch):
"""等待版面解析时仍返回已选 PDF,避免处理详情误报“暂无结果”。"""
run = SimpleNamespace(
id=1,
status='processing',
error_code=None,
created_at=None,
finished_at=None,
last_activity_at=None,
phase='waiting_layout',
input_snapshot_json={
'attachment_selection': {
'items': [{
@@ -63,11 +63,12 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app):
) as RC_Mock, patch(
'app.services.shipping_notice.order_review_auto_progress_coordinator.db',
), patch.object(
coord, '_customer_step_for_case', return_value={'status': 'skipped_no_shadow'},
), patch.object(
coord, 'validate_draft', return_value={'status': 'ready'},
), patch.object(
coord, 'ensure_stp_auto_create_for_case',
coord, '_customer_step_for_case', return_value=('skipped', {'reason': 'shadow_missing'}),
), patch(
'app.services.shipping_notice.order_review_draft_service.validate_draft',
return_value={'status': 'ready'},
), patch(
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
return_value={'status': 'queued', 'job_id': 1201,
'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'},
) as ensure_mock:
@@ -115,11 +116,12 @@ def test_contract_02_draft_validated_ready_triggers_single_case_coordinator(app)
with patch(
'app.services.shipping_notice.order_review_auto_progress_coordinator.db',
), patch.object(
coord, '_customer_step_for_case', return_value={'status': 'skipped'},
), patch.object(
coord, 'validate_draft', return_value={'status': 'ready'},
), patch.object(
coord, 'ensure_stp_auto_create_for_case',
coord, '_customer_step_for_case', return_value=('skipped', {'reason': 'shadow_missing'}),
), patch(
'app.services.shipping_notice.order_review_draft_service.validate_draft',
return_value={'status': 'ready'},
), patch(
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
return_value={'status': 'queued', 'job_id': 2202, 'idempotency_key': 'k-02'},
) as ensure_mock:
result = coord.reconcile_single_case_for_auto_progress(
@@ -146,21 +148,22 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
),
)
def _customer_step(c, actor_type_hint=None):
del c, actor_type_hint
def _customer_step(*, case, trigger):
del trigger
case.current_draft.validation_result_json = {
'can_build': True, 'can_auto_create': True, 'status': 'ready',
}
return {'status': 'auto_confirmed', 'customer_id': 5555}
return 'auto_confirmed', {'customer_id': 5555}
with patch(
'app.services.shipping_notice.order_review_auto_progress_coordinator.db',
), patch.object(
coord, '_customer_step_for_case', side_effect=_customer_step,
), patch.object(
coord, 'validate_draft', return_value={'status': 'ready'},
), patch.object(
coord, 'ensure_stp_auto_create_for_case',
), patch(
'app.services.shipping_notice.order_review_draft_service.validate_draft',
return_value={'status': 'ready'},
), patch(
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
return_value={'status': 'queued', 'job_id': 3303, 'idempotency_key': 'k-03'},
) as ensure_mock:
result = coord.reconcile_single_case_for_auto_progress(
@@ -180,10 +183,12 @@ def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(a
id=4, case_no='SORC-P1-04', status='ready', confirmed_task_id=None,
document_id=400, updated_at=None,
)
with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[4]), patch(
with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[4]), patch.object(
sw, '_scan_stale_inventory_attempts', return_value=0,
), patch.object(sw, '_recover_auto_progress_jobs', return_value=0), patch(
'app.services.shipping_notice.shipping_recovery_sweeper_service.db',
) as mock_db, patch(
'app.services.shipping_notice.shipping_recovery_sweeper_service.'
) as mock_db, patch.object(sw, 'ShippingOrderReviewCase') as ReviewCase, patch(
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
'reconcile_single_case_for_auto_progress',
return_value={'case_no': 'SORC-P1-04', 'enqueue_status': 'queued',
'job_id': 4404},
@@ -191,10 +196,9 @@ def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(a
mock_session = MagicMock()
loaded = SimpleNamespace(id=4, status='ready', confirmed_task_id=None)
mock_session.execute.return_value.scalar.return_value = None
mock_session.get.return_value = loaded
mock_session.begin_nested.return_value.__enter__ = MagicMock(return_value=None)
mock_session.begin_nested.return_value.__exit__ = MagicMock(return_value=None)
mock_session.begin_nested.return_value = MagicMock()
type(mock_db).session = mock_session
ReviewCase.query.filter_by.return_value.with_for_update.return_value.first.return_value = loaded
count = sw.shipping_recovery_tick()
assert coord_mock.call_count == 1
@@ -265,17 +269,18 @@ def test_contract_06_duplicate_blocked_case_rejects_general_retry(app):
from app.services.shipping_notice import reconciliation_service as rs
from app.services.shipping_notice.recovery_contract import should_general_retry_be_removed
case = SimpleNamespace(case_no='SORC-P1-06', status='ready', confirmed_task_id=None)
case = SimpleNamespace(
case_no='SORC-P1-06', status='ready', confirmed_task_id=None,
document_id=600, run=SimpleNamespace(run_no='SNER-P1-06'),
)
# 6A:assert_case_not_blocked_manual 前置拦截 → 409
with patch(
'app.services.shipping_notice.reconciliation_service.find_latest_stp_job',
return_value=SimpleNamespace(
with patch.object(rs, 'Job') as Job:
Job.query.filter.return_value.filter.return_value.order_by.return_value.first.return_value = SimpleNamespace(
id=60, status='failed',
result_json={'retryable': False,
'blocking_reason': 'SHIPPING.NOTICE_EXACT_DUPLICATE'},
),
):
)
with pytest.raises(ConflictError):
rs.assert_case_not_blocked_manual(case_no='SORC-P1-06', case=case)
@@ -309,9 +314,7 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
'app.services.shipping_notice.order_review_customer_service.refresh_order_customer_matches',
) as refresh_mock, patch(
'app.services.shipping_notice.order_review_customer_service.confirm_order_customer_match',
) as confirm_mock, patch(
'app.services.shipping_notice.order_review_customer_service.validate_draft',
) as validate_mock:
) as confirm_mock:
# Shadow = unique_candidate 但是 resolved=false。
with patch(
'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution',
@@ -330,16 +333,14 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
) as CM, patch(
'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction',
) as EX:
Cand.query.get.return_value = SimpleNamespace(id=70)
sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700)
CM.query.filter_by.return_value.first.return_value = None
EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700)
sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700)
# 执行投影(纯读)
out = project_review_case_customer_resolution(case)
# 7A:GET 路径不允许 confirm / validate / commit
confirm_mock.assert_not_called()
validate_mock.assert_not_called()
refresh_mock.assert_not_called()
sess_mock.commit.assert_not_called()
# 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认)
@@ -389,7 +390,7 @@ def test_contract_09_late_callback_does_not_resurrect_terminal_case(app):
)
with patch.object(h.db.session, 'get', return_value=job), patch(
'app.jobs.handlers.shipping_review_revalidate_progress.ShippingOrderReviewCase',
'app.models.shipping_order_review.ShippingOrderReviewCase',
) as RC, patch.object(h, 'finish_job') as finish_mock, patch.object(
h, 'fail_job',
) as fail_mock:
@@ -400,7 +401,7 @@ def test_contract_09_late_callback_does_not_resurrect_terminal_case(app):
finish_mock.assert_called_once()
args, _ = finish_mock.call_args
result = args[1] if len(args) > 1 else {}
result = finish_mock.call_args.kwargs.get('result') or {}
assert result.get('status') in {'skipped', 'superseded', 'case_terminal'}
fail_mock.assert_not_called()
@@ -427,14 +428,11 @@ def test_fe_01_stp_enqueue_missing_injects_blocking_reason(app):
lines_json=[],
),
)
with patch(
'app.services.shipping_notice.reconciliation_projector.db.session',
MagicMock(),
), patch(
'app.services.shipping_notice.reconciliation_projector.Job',
) as J:
J.query.filter.return_value.first.return_value = None
bundle = _project_fine_grained_pre_stp_blocking(case)
with patch('app.extensions.db.session', MagicMock()) as session_mock:
session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None
bundle = _project_fine_grained_pre_stp_blocking(
case, validation=case.current_draft.validation_result_json,
)
assert bundle is not None
assert bundle['blocking_reason']['code'] == 'stp_enqueue_missing'
@@ -459,13 +457,11 @@ def test_fe_02_retryable_shows_single_primary_action_only(app):
header_values_json={}, lines_json=[],
),
)
with patch(
'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(),
), patch(
'app.services.shipping_notice.reconciliation_projector.Job',
) as J:
J.query.filter.return_value.first.return_value = None
bundle = _project_fine_grained_pre_stp_blocking(case)
with patch('app.extensions.db.session', MagicMock()) as session_mock:
session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None
bundle = _project_fine_grained_pre_stp_blocking(
case, validation=case.current_draft.validation_result_json,
)
assert bundle['user_status'] == 'retryable'
primary = bundle.get('primary_action') or {}
@@ -477,15 +473,12 @@ def test_fe_02_retryable_shows_single_primary_action_only(app):
def test_fe_03_duplicate_only_allows_reconcile_and_progress(app):
"""FE 合同 3:duplicate → projection 剔除 retry,只保留 reconcile_and_progress。"""
from app.services.shipping_notice.processing_projection_invariants import (
_DUPLICATE_BLOCKING_CODES,
)
from app.services.shipping_notice.recovery_contract import (
BLOCKING_REASON_TO_ACTION_CODES,
should_general_retry_be_removed,
)
for bcode in _DUPLICATE_BLOCKING_CODES:
for bcode in ('duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'):
assert should_general_retry_be_removed(
retryable_flag=False, blocking_reason=bcode,
) is True, f'{bcode} 必须移除通用重试'
@@ -510,14 +503,14 @@ def test_fe_04_refresh_and_re_login_projection_consistent(app):
header_values_json={}, lines_json=[],
),
)
with patch(
'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(),
), patch(
'app.services.shipping_notice.reconciliation_projector.Job',
) as J:
J.query.filter.return_value.first.return_value = None
r1 = _project_fine_grained_pre_stp_blocking(case)
r2 = _project_fine_grained_pre_stp_blocking(case)
with patch('app.extensions.db.session', MagicMock()) as session_mock:
session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None
r1 = _project_fine_grained_pre_stp_blocking(
case, validation=case.current_draft.validation_result_json,
)
r2 = _project_fine_grained_pre_stp_blocking(
case, validation=case.current_draft.validation_result_json,
)
assert r1 is not None and r2 is not None
assert r1['blocking_reason']['code'] == r2['blocking_reason']['code']
@@ -541,13 +534,11 @@ def test_fe_05_no_contradictory_waiting_manual_and_waiting_auto_together(app):
header_values_json={}, lines_json=[],
),
)
with patch(
'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(),
), patch(
'app.services.shipping_notice.reconciliation_projector.Job',
) as J:
J.query.filter.return_value.first.return_value = None
bundle = _project_fine_grained_pre_stp_blocking(case)
with patch('app.extensions.db.session', MagicMock()) as session_mock:
session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None
bundle = _project_fine_grained_pre_stp_blocking(
case, validation=case.current_draft.validation_result_json,
)
status = bundle.get('user_status')
# retryable 与 waiting_human 互斥:命中短路 stp_enqueue_missing 时,只能二选一
+185 -86
View File
@@ -10,17 +10,26 @@ tests/test_shipping_auto_progress_p0_3.py
from __future__ import annotations
from app import db
from app.jobs.queue import claim_next_job
from app.models import Job, ShippingInventoryCandidateSet, ShippingNotice, ShippingProcessExecution, ShippingProcessGate
from app.models import (
Job,
ShippingInventoryCandidateSet,
ShippingNotice,
ShippingProcessExecution,
ShippingProcessGate,
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
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
def _task_with_candidate() -> ShippingNotice:
"""创建拥有 frozen CandidateSet 的最小正式 Task。"""
def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice:
"""创建正式 Task;可选择是否补齐订单解析与冻结快照事实。"""
task = ShippingNotice(task_no='APX-P0-3-001', process_status='created')
db.session.add(task)
db.session.flush()
@@ -30,12 +39,33 @@ def _task_with_candidate() -> ShippingNotice:
db.session.add(candidate)
db.session.flush()
task.active_inventory_candidate_set_id = candidate.id
if complete_order:
task.current_order_extraction_id = 101
task.order_snapshot_id = 201
db.session.commit()
return task
def test_submit_reuses_one_active_task_job(app):
"""同一 Task 多次触发只保留一个 queued/running AutoProgress Job。"""
def test_formal_start_gate_is_derived_from_persisted_task_facts(app):
"""无解析、未冻结、候选未冻结与候选冻结必须分别停在对应正式 Gate。"""
task = _task_with_candidate(complete_order=False)
candidate = ShippingInventoryCandidateSet.query.filter_by(task_id=task.id).one()
assert determine_formal_start_gate(task, candidate_set=candidate) == 'document_materialization'
task.current_order_extraction_id = 101
assert determine_formal_start_gate(task, candidate_set=candidate) == 'order_freeze_readiness'
task.order_snapshot_id = 201
candidate.lifecycle_status = 'draft'
assert determine_formal_start_gate(task, candidate_set=candidate) == 'inventory_source_routing'
candidate.lifecycle_status = 'frozen'
assert determine_formal_start_gate(task, candidate_set=candidate) == 'inventory_preparation'
def test_submit_creates_formal_execution_for_task_without_case(app):
"""无 Case 的新 Task 也必须创建正式 20-Gate,不得创建 APX 六 Gate。"""
task = _task_with_candidate()
first = submit_auto_progress(task=task, trigger='review_confirmed')
second = submit_auto_progress(task=task, trigger='user_retry')
@@ -43,96 +73,165 @@ def test_submit_reuses_one_active_task_job(app):
assert first['status'] == 'queued'
assert second['job_id'] == first['job_id']
assert second['reused'] is True
assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 1
execution = db.session.get(ShippingProcessExecution, first['execution_id'])
gate_codes = [row.gate_code for row in execution.gates]
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_worker_passes_only_one_gate_and_queues_successor(app, monkeypatch):
"""一个 Worker Job 只处理首个 Gate,passed 与第二个 Gate Job 同事务产生。"""
def test_submit_reuses_formal_case_execution_and_supersedes_duplicate_apx(app):
"""同一 Task 已有正式 Case Execution 时不得保留第二条 APX 活动链。"""
task = _task_with_candidate()
submitted = submit_auto_progress(task=task, trigger='review_confirmed')
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
assert claimed is not None and claimed.id == submitted['job_id']
monkeypatch.setattr(
'app.services.shipping_notice.auto_progress_controller._gate_outcome',
lambda task, gate: ('passed', None, {'test': True}),
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,
)
result = run_auto_progress_job(job_id=submitted['job_id'], worker_id='test-worker')
execution = db.session.get(ShippingProcessExecution, result['execution_id'] if 'execution_id' in result else Job.query.get(submitted['job_id']).execution_id)
gates = ShippingProcessGate.query.filter_by(execution_id=execution.id).order_by(ShippingProcessGate.sequence_no).all()
jobs = Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').order_by(Job.id).all()
assert result['gate_code'] == AUTO_PROGRESS_GATE_CODES[0]
assert gates[0].status == 'passed'
assert gates[1].status == 'pending'
assert len(jobs) == 2
assert jobs[0].status == 'success' and jobs[1].status == 'queued'
assert jobs[1].gate_id == gates[1].id
def test_stale_job_is_cancelled_without_touching_current_execution(app):
"""候选/Execution 指针已切换时,迟到 Job 只能 cancelled,不能改写当前链。"""
task = _task_with_candidate()
submitted = submit_auto_progress(task=task, trigger='review_confirmed')
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
assert claimed is not None
old_execution = db.session.get(ShippingProcessExecution, Job.query.get(submitted['job_id']).execution_id)
replacement = ShippingProcessExecution(
execution_no='APX-REPLACEMENT', task_id=task.id,
candidate_set_id=task.active_inventory_candidate_set_id, execution_revision=2,
status='active', lock_version=1,
)
db.session.add(replacement)
db.session.add(duplicate)
db.session.flush()
task.active_process_execution_id = replacement.id
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)
db.session.commit()
result = run_auto_progress_job(job_id=submitted['job_id'], worker_id='late-worker')
assert result['status'] == 'cancelled'
assert Job.query.get(submitted['job_id']).status == 'cancelled'
assert old_execution.status == 'active'
assert db.session.get(ShippingProcessExecution, replacement.id).status == 'active'
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_excel_gate_waits_for_human_receipt(app, monkeypatch):
"""Excel Gate 成功后不 completed;自动上传关闭时必须停在 receipt Gate 的人工阻断。"""
def test_formal_execution_queues_one_gate_attempt_job(app):
"""正式 20-Gate 链必须落 Attempt 并入队 ProcessGate Job,不能同步早退。"""
task = _task_with_candidate()
submitted = submit_auto_progress(task=task, trigger='review_confirmed')
monkeypatch.setattr(
'app.services.shipping_notice.auto_progress_controller._gate_outcome',
lambda task, gate: ('passed', None, {}),
formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id))
mark_gates_passed_through(
execution=formal,
through_gate_code='task_creation',
reason='test_review_confirmed',
)
for _ in range(5):
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
assert claimed is not None
run_auto_progress_job(job_id=claimed.id, worker_id='test-worker')
execution = db.session.get(ShippingProcessExecution, Job.query.get(submitted['job_id']).execution_id)
receipt_gate = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='upload_receipt_recorded',
).one()
assert execution.status == 'blocked'
assert receipt_gate.status == 'blocked_manual'
assert receipt_gate.blocking_reason_code == 'manual_upload_receipt_required'
def test_recorded_receipt_reopens_only_final_gate(app, monkeypatch):
"""人工登记回执后,服务端只重新执行最后一个 receipt Gate 并完成 Execution。"""
task = _task_with_candidate()
submitted = submit_auto_progress(task=task, trigger='review_confirmed')
monkeypatch.setattr(
'app.services.shipping_notice.auto_progress_controller._gate_outcome',
lambda task, gate: ('passed', None, {}),
)
for _ in range(5):
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
run_auto_progress_job(job_id=claimed.id, worker_id='test-worker')
task.upload_receipt_json = {'receipt_no': 'R-1'}
task.active_process_execution_id = formal.id
db.session.commit()
resume = submit_auto_progress(task=task, trigger='manual_upload_receipt_recorded')
claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress'])
result = run_auto_progress_job(job_id=claimed.id, worker_id='test-worker')
assert resume['gate_code'] == 'upload_receipt_recorded'
assert result['gate_code'] == 'upload_receipt_recorded'
assert db.session.get(ShippingProcessExecution, result['execution_id']).status == 'completed'
first = submit_auto_progress(task=task, trigger='review_confirmed')
second = submit_auto_progress(task=task, trigger='duplicate_confirm')
assert first['status'] == 'queued'
assert first['job_id'] == second['job_id']
attempt = db.session.get(ShippingProcessGateAttempt, first['attempt_id'])
job = db.session.get(Job, first['job_id'])
assert attempt is not None and attempt.job_id == job.id
assert attempt.status == 'queued'
assert job.job_type == 'shipping_process_gate'
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 1
def test_active_stp_job_without_retry_metadata_is_reused(app):
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
from types import SimpleNamespace
from unittest.mock import patch
from app.services.shipping_notice.order_stp_auto_create_service import (
ensure_stp_auto_create_for_case,
)
case = SimpleNamespace(
case_no='SORC-REUSE-MISSING-RETRY', status='ready', confirmed_task_id=None,
document_id=9001, candidate_id=None, run_id=1,
run=SimpleNamespace(id=1, run_no='SNER-REUSE-MISSING-RETRY'),
owner_user_id=1,
current_draft=SimpleNamespace(
draft_version=1,
validation_result_json={'status': 'ready', 'can_build': True, 'can_auto_create': True},
issue_summary_json=[], header_values_json={}, lines_json=[],
),
)
active = SimpleNamespace(id=901, status='queued')
with patch(
'app.services.shipping_notice.order_stp_auto_create_service._persist_case_candidate_qualification',
return_value=None,
), patch(
'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job',
return_value=active,
), patch('app.services.shipping_notice.order_stp_auto_create_service.db'):
result = ensure_stp_auto_create_for_case(case=case, commit=False)
assert result['status'] == 'already_queued'
assert result['job_id'] == 901
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'
@@ -83,6 +83,13 @@ def test_message_zh_for_reason_and_rpa_meta():
assert message_zh_for_reason('totally_unknown_xyz') is None
def test_rpa_upload_failures_keep_manual_retry_action():
"""RPA 失败仍属于 Gate 19,不能被覆盖成 Gate 20 的人工待办重生。"""
for reason_code in ('upload_rpa_login_failed', 'upload_platform_rejected'):
projected = build_explainability_reason(reason_code=reason_code)
assert projected['next_action'] == 'retry_freight_upload_rpa'
def test_inventory_preparation_reason_code_from_pending():
"""履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。"""
from types import SimpleNamespace
+155 -6
View File
@@ -19,12 +19,17 @@ from app import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
ShippingCase, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
)
from app.services.shipping_notice import excel_template
from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel
from app.services.shipping_notice.export import _excel_business_no, _filename, _mapping_value, _system_fact, generate_shipment_excel
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
from app.services.shipping_notice.inventory_file_store import (
active_inventory_lines_for_task,
replace_task_inventory_link,
resolve_inventory_lines_for_execution,
)
from app.services.shipping_notice.reservation_service import record_inventory_verification
from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE
from app.core.errors import ConflictError, ValidationError
@@ -132,6 +137,76 @@ def test_filename_pattern_supports_business_number_and_split_business_variables(
assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx'
def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cache(app, tmp_path):
"""业务执行必须使用活动库存 Link,忽略请求库存和旧任务缓存。"""
with app.app_context():
task = ShippingNotice(
task_no='TASK-INVENTORY-SOURCE', inventory_lines_json=[{'part_number': 'STALE'}],
)
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'),
inventory_lines_json=[{'part_number': 'ACTIVE'}], line_count=1,
share_mode='task_only', snapshot_status='ready',
)
db.session.add_all([task, inventory_file])
db.session.flush()
replace_task_inventory_link(task, inventory_file, role='owner')
db.session.flush()
resolved = resolve_inventory_lines_for_execution(
task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}],
)
assert resolved == [{'part_number': 'ACTIVE'}]
assert task.inventory_lines_json == [{'part_number': 'STALE'}]
def test_inventory_execution_keeps_legacy_fallback_without_active_link(app):
"""无活动 Link 的历史任务仍可读取请求库存或旧缓存,避免升级后无法恢复。"""
with app.app_context():
task = ShippingNotice(
task_no='TASK-INVENTORY-LEGACY', inventory_lines_json=[{'part_number': 'CACHE'}],
)
db.session.add(task)
db.session.flush()
assert resolve_inventory_lines_for_execution(
task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}],
) == [{'part_number': 'PAYLOAD'}]
assert resolve_inventory_lines_for_execution(task) == [{'part_number': 'CACHE'}]
def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp_path, monkeypatch):
"""已有正式快照 JSON 时读取动作不得重新解析物理文件并覆盖已修复数据。"""
with app.app_context():
storage_path = tmp_path / 'stale.xlsx'
storage_path.write_bytes(b'stale-source')
task = ShippingNotice(task_no='TASK-INVENTORY-NO-REPARSE')
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path),
inventory_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}],
line_count=1, share_mode='task_only', snapshot_status='ready',
)
db.session.add_all([task, inventory_file])
db.session.flush()
replace_task_inventory_link(task, inventory_file, role='owner')
db.session.flush()
reparse_calls: list[int] = []
def stale_reparse(_inventory_file):
reparse_calls.append(int(_inventory_file.id))
return ([{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-STALE'}], {})
monkeypatch.setattr(
'app.services.shipping_notice.inventory_file_store.parse_inventory_snapshot_file', stale_reparse,
)
assert active_inventory_lines_for_task(task) == [
{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'},
]
assert reparse_calls == []
def test_filename_pattern_falls_back_to_controlled_environment_configuration(app):
"""模板未提供规则时可使用受控环境变量,调用方仍不能提交任意文件名。"""
with app.app_context():
@@ -299,6 +374,54 @@ def test_export_date_system_fact_uses_business_timezone(app):
assert isinstance(value, date)
def test_excel_pull_request_number_uses_export_date_without_changing_case_number(app):
"""Excel Pull Request Number 必须采用导出日期,且业务单主编号保持原值。"""
with app.app_context():
shipping_case = ShippingCase(
case_no='CASE-EXCEL-NO', business_no='IVMX26080801', sequence_value=1,
)
task = ShippingNotice(task_no='TASK-EXCEL-NO')
task.shipping_case = shipping_case
assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26081101'
assert shipping_case.business_no == 'IVMX26080801'
def test_export_mapping_falls_back_to_export_sequence_and_derived_line_amount(app):
"""LineNumber 缺失时用导出行序号,Shipment Value 缺失时用数量乘单价。"""
with app.app_context():
fields = _lookup_standard_fields('line_no', 'line_amount_with_tax')
task = ShippingNotice(task_no='TASK-MAPPING')
assert _mapping_value(
{'source_kind': 'order_field', 'source_key': fields['line_no'].id, 'formatter': 'integer', 'row_mode': 'line'},
task=task, order_values={}, inventory_values={}, export_sequence=1,
) == 1
assert _mapping_value(
{'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'},
task=task, order_values={'__qty': Decimal('14'), '__unit_price': Decimal('941.76')}, inventory_values={},
) == 13184.64
def test_clear_template_data_rows_keeps_headers_and_removes_residual_values():
"""模板数据区从起始行起清空,表头不受影响。"""
from app.services.shipping_notice.export import _clear_template_data_rows
workbook = Workbook()
sheet = workbook.active
sheet['A3'] = 'header'
sheet['A4'] = 'current'
sheet['A5'] = 'residual-5'
sheet['B6'] = 'residual-6'
_clear_template_data_rows(sheet, 4)
assert sheet['A3'].value == 'header'
assert sheet['A4'].value is None
assert sheet['A5'].value is None
assert sheet['B6'].value is None
def test_two_sources_can_share_one_published_excel_template(app, tmp_path):
"""同结构库存源绑定同一 published 模板,避免复制维护映射规则。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
@@ -541,8 +664,8 @@ def test_template_publish_rejects_order_field_removed_from_current_schema(app):
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID'
def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app, tmp_path):
"""同一匹配键对应多个不同 ODM 时必须阻断,且不得留下半成品 Excel。"""
def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_path):
"""导出应读取活动库存 Link;无 Link 时旧缓存冲突仍须阻断且不留半成品。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
@@ -597,11 +720,37 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app,
lines=[(1, part.id, 'PN-A', 1, '1000000004')],
)
with pytest.raises(ValueError, match='值不一致'):
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
generate_shipment_excel(task)
export_root = tmp_path / 'shipping' / 'exports'
assert not export_root.exists() or not list(export_root.rglob('*.xlsx'))
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-ACTIVE-FIXED', user_id=None,
source_file_name='fixed.xlsx', storage_path=str(tmp_path / 'fixed.xlsx'),
inventory_lines_json=[
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'},
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'},
],
line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='AMBIGUOUS',
snapshot_status='ready',
)
db.session.add(inventory_file)
db.session.flush()
replace_task_inventory_link(task, inventory_file, role='owner')
task.inventory_snapshot_id = inventory_file.id
db.session.flush()
path, _filename_value, artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-FIXED'
finally:
workbook.close()
assert artifact.inventory_snapshot_id == inventory_file.id
assert task.inventory_lines_json[0][_inventory_field_id('odm_id')] == 'ODM-1'
def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch):
"""Artifact/任务事务提交失败时必须删除已生成文件,避免孤立 ready-looking 产物。"""
@@ -0,0 +1,71 @@
"""用途:验证库存恢复只失效当前任务关联的 Mapping/下游事实。
依赖:recovery_invalidation_service 与库存谱系模型。
逻辑:通过最小模型级约束检查和服务分支合同,禁止跨任务失效。
"""
from app.models import ShippingInventoryMapping
def test_mapping_status_contract_allows_invalidation_without_delete():
"""Mapping 失效必须保留记录,状态使用正式 invalidated 枚举。"""
allowed = next(
constraint.sqltext.text
for constraint in ShippingInventoryMapping.__table__.constraints
if getattr(constraint, 'name', '') == 'ck_shipping_inventory_mapping_status'
)
assert 'invalidated' in allowed
def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app):
"""候选版本切换后,旧 Artifact 不可下载,未终态上传 Attempt 不得继续使用。"""
from app import db
from app.models import (
ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile,
ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingUploadAttempt,
)
from app.services.shipping_notice.inventory_candidate_freeze_service import _invalidate_task_candidate_outputs
task = ShippingNotice(task_no='SN-CANDIDATE-INVALIDATE-1')
template = ShippingExcelTemplate(
template_code='CANDIDATE-INVALIDATE', display_name='Candidate invalidate', version=1,
status='published', storage_bucket='test', storage_key='template.xlsx',
original_filename='template.xlsx', file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='CANDIDATE-INVALIDATE', display_name='Candidate invalidate', version=1,
status='published', file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='CANDIDATE_INVALIDATE', display_name='Candidate invalidate')
db.session.add_all([task, template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted')
db.session.add(extraction)
db.session.flush()
artifact = ShippingExportArtifact(
artifact_no='EXP-CANDIDATE-INVALIDATE', task_id=task.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path='artifact.xlsx', file_name='artifact.xlsx', file_checksum='d' * 64,
file_size=1, status='ready',
)
db.session.add(artifact)
db.session.flush()
attempt = ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=1, mode='manual', idempotency_key='candidate-invalidate-1',
status='running',
)
db.session.add(attempt)
db.session.flush()
_invalidate_task_candidate_outputs(task, old_candidate_set_id=1, session=db.session)
db.session.refresh(artifact)
db.session.refresh(attempt)
assert artifact.status == 'superseded'
assert attempt.status == 'failed'
assert attempt.invalidated_at is not None
assert attempt.invalidation_reason == 'candidate_set_refrozen'
@@ -0,0 +1,51 @@
"""
用途:验证库存快照复用策略和多源组合指纹的 fail-closed 合同。
依赖:纯函数服务。
逻辑:覆盖身份、状态、过期与指纹变化;不触发外部 RPA。
"""
from datetime import datetime, timedelta
from types import SimpleNamespace
from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
def test_snapshot_reuse_requires_ready_identity_and_versions():
snap = SimpleNamespace(
snapshot_status='ready', expires_at=datetime.utcnow() + timedelta(hours=1),
source_code='A', warehouse_id='W1', source_config_version='v1',
input_fingerprint='cand-1', file_sha256='sha-1', parser_version='p1', mapping_version='m1', invalidated_at=None,
)
ok, reasons = check_inventory_snapshot_reusable(
snapshot=snap, source_code='A', warehouse_id='W1',
source_config_version='v1', candidate_input_fingerprint='cand-1',
parser_version='p1', mapping_version='m1',
expected_file_sha256='sha-1',
)
assert ok is True and reasons == []
ok, reasons = check_inventory_snapshot_reusable(snapshot=snap, source_code='B', warehouse_id='W1')
assert ok is False and 'source_code_mismatch' in reasons
ok, reasons = check_inventory_snapshot_reusable(snapshot=snap, source_code='A', parser_version='p2')
assert ok is False and 'parser_version_mismatch' in reasons
def test_combination_fingerprint_is_order_independent_but_input_sensitive():
a = build_inventory_combination_fingerprint(
task_snapshot_fingerprint='task', candidate_freeze_fingerprint='cand',
sources=[{'source_code': 'B', 'snapshot_id': 2}, {'source_code': 'A', 'snapshot_id': 1}],
reservation_version='r1', matching_rule_version='m1',
)
b = build_inventory_combination_fingerprint(
task_snapshot_fingerprint='task', candidate_freeze_fingerprint='cand',
sources=[{'source_code': 'A', 'snapshot_id': 1}, {'source_code': 'B', 'snapshot_id': 2}],
reservation_version='r1', matching_rule_version='m1',
)
c = build_inventory_combination_fingerprint(
task_snapshot_fingerprint='task', candidate_freeze_fingerprint='cand',
sources=[{'source_code': 'A', 'snapshot_id': 1}, {'source_code': 'B', 'snapshot_id': 3}],
reservation_version='r1', matching_rule_version='m1',
)
assert a == b
assert a != c
@@ -11,9 +11,25 @@ from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_text,
read_inventory_schema_preview,
)
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
from app.services.shipping_notice.match import match_notice_lines
def test_explicit_mapping_matches_excel_header_line_breaks(app):
"""发布映射的 Qty\nAvailable 表头必须解析到可用数量列。"""
with app.app_context():
columns = resolve_columns_from_field_mapping(
["Supplier Sku", "Resevation Order", "Qty\nAvailable", "AWS Sku"],
{
"1": "Supplier Sku",
"2": "Resevation Order",
"3": "Qty Available",
"5": "AWS Sku",
},
)
assert columns["3"] == 2
def _write_title_row_inventory_xlsx(path: Path) -> None:
wb = Workbook()
ws = wb.active
@@ -15,9 +15,22 @@ from app.models import (
ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink,
ShippingOrderCustomerMatch,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source
from tests.conftest import (
inventory_xlsx_with_warehouse,
scheduled_rpa_batch_item,
seed_rpa_inventory_trigger,
seed_task_inventory_source,
freeze_test_task_order_snapshot,
v2_inventory_batch_payload,
)
def _with_v2_batch_envelope(payload: dict) -> dict:
"""旧测试场景统一补齐冻结 v2 callback envelope,生产入口仍严格校验。"""
return v2_inventory_batch_payload(payload)
def _tool_headers():
@@ -99,6 +112,8 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
task.customer_resolution_method = 'test_fixture'
db.session.add_all([case, task])
db.session.flush()
# 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。
task._test_customer_confirmed = True
@pytest.fixture(autouse=True)
@@ -129,6 +144,26 @@ def _confirmed_customer_for_rpa_flows(app, monkeypatch):
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
@pytest.fixture(autouse=True)
def _freeze_test_rpa_batch_callback_contract(monkeypatch):
"""兼容旧测试调用:仅在测试边界补齐 v2 envelope,不改变生产回调校验。"""
from app.services.shipping_notice import inventory_rpa_workflow
import sys
original = inventory_rpa_workflow.rpa_report_inventory_batch
callback_seq = {'value': 0}
def _wrapped(payload):
body = _with_v2_batch_envelope(payload)
if not payload.get('callback_id'):
callback_seq['value'] += 1
body['callback_id'] = f"test-callback:{body.get('batch_run_no') or 'unknown'}:{callback_seq['value']}"
return original(body)
monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped)
monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped)
def test_inventory_rpa_single_attempt_messages_hide_fraction():
"""单次自动尝试模式不应再产出 1/1 计数,避免 Dify 误判仍会继续自动重试。"""
from app.services.shipping_notice.inventory_rpa_workflow import (
@@ -203,6 +238,8 @@ def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantit
db.session.add_all([profile, rtm_source, task, source_snapshot, other_snapshot])
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='1000123456', quantity=1)
_confirm_direct_rpa_task_customer(task)
freeze_test_task_order_snapshot(task)
db.session.commit()
result = resolve_ambiguous_source_from_ready_snapshots(
@@ -239,7 +276,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
with app.app_context():
task = ShippingNotice(
task_no='SN-MANUAL-PROFILE-001', source_type='manual', process_status='waiting_inventory',
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
@@ -247,7 +284,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
db.session.commit()
upload = FileStorage(
stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', qty=8).getvalue()),
stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', reservation_id='00001', qty=8).getvalue()),
filename='manual-stock.xlsx',
)
result = upload_inventory_file(task.task_no, upload)
@@ -264,7 +301,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
assert snapshot.mapping_confirmed is True
fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
assert snapshot.inventory_lines_json[0][fields['part_number']] == 'A001'
assert snapshot.inventory_lines_json[0][fields['reservation_id']] == 'R-1'
assert snapshot.inventory_lines_json[0][fields['reservation_id']] == '00001'
assert snapshot.inventory_lines_json[0][fields['available_qty']] == 8
@@ -282,7 +319,7 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
workbook = Workbook()
sheet = workbook.active
sheet.append(['Warehouse ID', 'Unexpected Part', 'Reservation ID', 'Qty'])
sheet.append(['AWSDU', 'A001', 'R-1', 8])
sheet.append(['AWSDU', 'A001', '00001', 8])
workbook.save(stream)
workbook.close()
stream.seek(0)
@@ -290,7 +327,7 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
with app.app_context():
task = ShippingNotice(
task_no='SN-MANUAL-DRIFT-001', source_type='manual', process_status='waiting_inventory',
lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}],
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
@@ -336,14 +373,16 @@ def test_rpa_report_inventory_batch_empty_item_treated_as_failed(app, tmp_path):
"""batch results 中空 dict 应直接 failed,不走 success→file_missing 绕路。"""
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
drop_dir = tmp_path / "drop"
drop_dir.mkdir(parents=True, exist_ok=True)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
with app.app_context():
result = rpa_report_inventory_batch({
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
"run_no": "RUN-EMPTY-ITEM",
"trigger_type": "scheduled",
"results": [{}],
})
}))
assert result["status"] == "ok"
assert result["result_status"] == "failed"
assert result["data"]["result_status"] == "failed"
@@ -365,7 +404,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
result = rpa_report_inventory_batch({
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
"run_no": "RUN-MIXED",
"trigger_type": "scheduled",
"results": [
@@ -383,7 +422,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
"error_message": "timeout",
},
],
})
}))
assert result["status"] == "ok"
assert result["result_status"] == "partial_failed"
assert result["data"]["result_status"] == "partial_failed"
@@ -398,7 +437,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
with app.app_context():
result = rpa_report_inventory_batch({
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
"run_no": "RUN-ALL-FAIL",
"trigger_type": "scheduled",
"results": [{
@@ -408,7 +447,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
"success": False,
"error_message": "timeout",
}],
})
}))
assert result["status"] == "ok"
assert result["result_status"] == "failed"
assert result["failed_count"] == 1
@@ -474,7 +513,7 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon
],
}
},
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -512,7 +551,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -546,7 +585,10 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
from app import db
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
with app.app_context():
task = ShippingNotice(
@@ -554,7 +596,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -598,7 +640,7 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -709,7 +751,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT")
@@ -777,7 +819,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no=run_no)
@@ -866,8 +908,9 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
drop_dir.mkdir(parents=True, exist_ok=True)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
sample_a = drop_dir / "task_a.xlsx"
sample_b = drop_dir / "task_b.xlsx"
sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
@@ -892,14 +935,14 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
task_b = ShippingNotice(
task_no="SN-BATCH-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task_a)
_confirm_direct_rpa_task_customer(task_b)
@@ -947,6 +990,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
drop_dir = tmp_path / "drop"
drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
sample = drop_dir / "shared.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
run_no = "RUN-SHARED-LINK"
@@ -957,14 +1001,14 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
task_fail = ShippingNotice(
task_no="SN-SHARED-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task_ok)
_confirm_direct_rpa_task_customer(task_fail)
@@ -1046,7 +1090,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -1091,7 +1135,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -1128,7 +1172,7 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
task_no="SN-REPAIR-ATTACH",
source_type="manual",
process_status="inventory_ready",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1286,7 +1330,7 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
task_no="SN-REPAIR-REJECT",
source_type="manual",
process_status="inventory_ready",
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -9,6 +9,8 @@ backend/tests/test_shipping_notice_inventory_schedule.py
from datetime import datetime, timedelta
from pathlib import Path
import pytest
from app import db
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig, User
from app.services.schedule.scheduler_service import run_task_now
@@ -24,6 +26,22 @@ from app.services.schedule.shipping_inventory_rpa_job import (
_filter_sources,
run_shipping_inventory_rpa_schedule,
)
from tests.conftest import v2_inventory_batch_payload
@pytest.fixture(autouse=True)
def _freeze_schedule_batch_callback_contract(monkeypatch):
"""旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。"""
from app.services.shipping_notice import inventory_rpa_workflow
import sys
original = inventory_rpa_workflow.rpa_report_inventory_batch
def _wrapped(payload):
return original(v2_inventory_batch_payload(payload))
monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped)
monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped)
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item
@@ -1,11 +1,13 @@
"""
backend/tests/test_shipping_notice_rpa_trigger_for_task.py
用途:验证按需库存导出在 batch 与 legacy 模式下生成正确 trigger。
用途:验证按需库存导出仅生成 v2 batch trigger,并携带完整冻结身份。
依赖:shipping_notice.rpa、pytest app/tmp_path 夹具。
逻辑:构造 connector_type 库存连接器载荷,检查 trigger 文件分支与关键字段。
"""
import pytest
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
@@ -27,28 +29,39 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path):
path = write_inventory_export_trigger_for_task(
"SN-ON-DEMAND-1",
source,
payload={"mode": "auto", "attempt": 1},
payload={
"mode": "auto", "attempt": 1, "source_run_no": "SRC-1",
"lease_token": "lease-1", "candidate_set_id": 12,
"execution_id": 88, "gate_id": 901,
"expected_warehouse_id": "AWSDU",
},
)
assert path
trigger_files = list(trigger_dir.glob("inventory_export_batch_*.json"))
assert trigger_files
text = trigger_files[0].read_text(encoding="utf-8")
assert "inventory_export_batch" in text
assert "SN-ON-DEMAND-1" in text
assert "DSV360_AWSDU" in text
payload = __import__("json").loads(trigger_files[0].read_text(encoding="utf-8"))
assert payload["action"] == "inventory_export_batch"
item = payload["inventory_sources"][0]
assert item["task_no"] == "SN-ON-DEMAND-1"
assert item["source_code"] == "DSV360_AWSDU"
assert item["source_run_no"] == "SRC-1"
assert item["execution_id"] == 88
assert item["gate_id"] == 901
def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path):
"""batch 关闭时仍写 legacy inventory_export trigger。"""
def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path):
"""v2 batch 关闭时 fail-closed,禁止生成 legacy inventory_export trigger。"""
from app.core.errors import ValidationError
trigger_dir = tmp_path / "triggers"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
with app.app_context():
path = write_inventory_export_trigger_for_task("SN-LEGACY-1", source)
assert path
assert list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json"))
with app.app_context(), pytest.raises(ValidationError, match="v2") as exc_info:
write_inventory_export_trigger_for_task("SN-LEGACY-1", source)
assert exc_info.value.code == "SHIPPING.INVENTORY_RPA_V2_REQUIRED"
assert not list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json"))
def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_path):
@@ -70,3 +83,30 @@ def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_p
assert item["entry_url"] == "https://example.invalid/dbs"
assert "username" not in item
assert "password" not in item
def test_batch_trigger_writes_explicit_v2_callback_identity(app, tmp_path):
"""新 batch Trigger 必须显式写入顶层和逐源 callback_id,Worker 不得推导。"""
import json
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
trigger_dir = tmp_path / "triggers"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
source = {
"source_code": "DBS",
"connector_type": "dbs",
"warehouse_id": "WH-1",
"source_run_no": "SRC-1",
"attempt_no": 2,
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
"expected_warehouse_id": "WH-1",
"lease_token": "lease-1",
}
with app.app_context():
path = write_inventory_export_batch_trigger("BATCH-1", [source])
body = json.loads((path and __import__('pathlib').Path(path)).read_text(encoding="utf-8"))
assert body["callback_id"] == "BATCH-1:batch:C1"
assert body["inventory_sources"][0]["callback_id"] == "SRC-1:C1"
+41 -12
View File
@@ -190,6 +190,39 @@ def test_parse_notice_tool_is_removed(app, client):
assert response.status_code == 404
def test_direct_excel_tool_dispatches_to_formal_auto_progress(monkeypatch):
"""旧 Tool 入口不能绕过 GateAttempt 直接生成 Excel。"""
from app.services.shipping_notice import fulfillment_workflow
submitted: dict[str, object] = {}
def _submit(task_no, **kwargs):
submitted['task_no'] = task_no
submitted.update(kwargs)
return {'status': 'running', 'data': {}}
monkeypatch.setattr(
'app.services.shipping_notice.progress_workflow.run_task_auto_progress',
_submit,
)
result = fulfillment_workflow.generate_excel({
'task_id': 'SN-FORMAL-EXCEL-ONLY',
'operator_id': 7,
'idempotency_key': 'formal-excel-only',
})
assert result['status'] == 'running'
assert submitted == {
'task_no': 'SN-FORMAL-EXCEL-ONLY',
'trigger': 'tool_api_generate_excel',
'expected_version': None,
'idempotency_key': 'formal-excel-only',
'resume_gate_code': 'artifact_generation',
'operator_id': 7,
}
def test_match_notice_lines_reports_progress():
seen: list[tuple[int, int]] = []
@@ -806,7 +839,7 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
assert rows["SN-MULTI-CONV-002"].process_status == "pending_review"
def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, monkeypatch):
def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch):
headers = _tool_headers(app)
create_res = client.post(
@@ -820,15 +853,11 @@ def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, mon
captured: dict[str, object] = {}
def fake_ensure_inventory(payload):
captured.update(payload)
return {
"status": "running",
"task_id": payload["task_id"],
"message": "已触发库存获取(测试桩)",
}
def fake_request_formal_gate_action(**kwargs):
captured.update(kwargs)
return {"status": "running", "task_id": task_id, "message": "已提交正式 20-Gate 恢复动作"}
monkeypatch.setattr(decision_workflow, "ensure_inventory", fake_ensure_inventory)
monkeypatch.setattr(decision_workflow, "_request_formal_gate_action", fake_request_formal_gate_action)
res = client.post(
"/api/shipping-notice/tools/submit_decision",
@@ -838,9 +867,9 @@ def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, mon
data = res.get_json()
assert data["status"] == "running"
assert data["task_id"] == task_id
assert data["message"] == "已触发库存获取(测试桩)"
assert captured["task_id"] == task_id
assert captured["mode"] == "retry_rpa"
assert data["message"] == "已提交正式 20-Gate 恢复动作"
assert captured["task"].task_no == task_id
assert captured["action_code"] == "retry_inventory_preparation"
def test_parse_inventory_oversized_text_route_is_removed(app, client):
@@ -59,6 +59,10 @@ def _seed_blocked_execution(owner: User | None = None):
execution_id=int(execution.id),
gate_code='order_freeze_readiness',
).first()
# 夹具显式将阻断 Gate 设为 Execution.current_gate,覆盖前置 Gate 默认初始状态,
# 以便 API 测试验证当前 Gate 的统一写校验。
execution.current_gate_code = gate.gate_code
execution.primary_next_action_code = gate.next_action_code
db.session.commit()
return user, execution, gate
@@ -86,6 +90,19 @@ def _seed_blocked_execution_for_agent_readonly():
)
ensure_order_extraction_plan(run)
cases = ensure_run_review_cases(run=run)
if not cases:
# 当前最小 API 夹具可能没有完整 Worker Candidate;仍创建只读授权所需的
# 正式 Case 绑定,测试只验证权限边界,不把缺失 Candidate 伪装成业务成功。
from app.models import ShippingOrderReviewCase
unit = run.extraction_plan.units[0] if run.extraction_plan and run.extraction_plan.units else None
if unit is not None and unit.document_id:
case = ShippingOrderReviewCase(
case_no=f'SORC-API-FALLBACK-{run.id}', run_id=int(run.id), unit_id=int(unit.id),
document_id=int(unit.document_id), owner_user_id=int(user.id), status='draft',
)
db.session.add(case)
db.session.flush()
cases = [case]
assert cases, 'review case required for agent authorization path'
case = cases[0]
execution = ensure_execution_for_workflow_version(
@@ -224,6 +241,51 @@ def test_workspace_post_action_idempotent(app, client):
assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='api-idempotent-1').count() == 1
def test_workspace_post_action_rejects_non_current_gate_for_all_gate_actions(app, client):
"""所有阶段统一禁止绕过 current_gate 写入其他 Gate。"""
with app.app_context():
owner, execution, gate = _seed_blocked_execution()
# order_freeze_readiness 是当前阻断;请求另一个正式 Gate 必须 fail-closed。
other_gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code='inventory_matching',
).first()
assert other_gate is not None
resp = client.post(
f'/api/workspace/shipping-notice/process-executions/{execution.execution_no}'
'/gates/inventory_matching/actions',
headers=_auth_headers(owner),
json={
'action_code': 'open_inventory_match_review',
'expected_gate_version': int(other_gate.evaluation_version),
'idempotency_key': 'api-non-current-gate-1',
},
)
assert resp.status_code == 400
assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_NOT_CURRENT'
def test_workspace_post_action_rejects_terminal_execution_for_all_gate_actions(app, client):
"""所有阶段统一禁止 completed/cancelled Execution 写动作。"""
with app.app_context():
owner, execution, gate = _seed_blocked_execution()
execution.status = 'completed'
db.session.commit()
resp = client.post(
f'/api/workspace/shipping-notice/process-executions/{execution.execution_no}'
f'/gates/{gate.gate_code}/actions',
headers=_auth_headers(owner),
json={
'action_code': 'open_order_review',
'expected_gate_version': int(gate.evaluation_version),
'idempotency_key': 'api-terminal-execution-1',
},
)
assert resp.status_code == 400
assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_EXECUTION_TERMINAL'
def test_workspace_get_missing_execution_404(app, client):
"""不存在的 execution_no 返回 404。"""
with app.app_context():
@@ -16,6 +16,7 @@ from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_DEFINITIONS,
PROCESS_GATE_REASON_OWNING_GATE,
assert_process_gate_contract_integrity,
action_presentation,
field_quality_may_block,
owning_gate_for_reason,
primary_next_action_for_gate,
@@ -59,6 +60,22 @@ def test_inventory_source_routing_primary_retry_action():
assert action == 'retry_with_latest_rules'
def test_inventory_sufficiency_actions_keep_business_specific_labels():
"""库存缺口恢复必须保留精确业务动作,禁止客户端降级为统一“重试”。"""
assert action_presentation('open_shortage_review') == {
'code': 'open_shortage_review',
'label_key': 'workspace.shippingNotice.processGate.actionCodes.open_shortage_review',
'kind': 'current_gate',
'dispatch': 'navigation',
}
assert action_presentation('retry_inventory_from_matching') == {
'code': 'retry_inventory_from_matching',
'label_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_from_matching',
'kind': 'recovery',
'dispatch': 'mutation',
}
def test_process_gate_reason_ownership_is_unique():
"""
每个阻断原因码恰好映射一个 owning_gate,覆盖率 100%。
@@ -83,6 +100,205 @@ 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
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-INV-1', status='blocked',
current_gate_code='inventory_matching', primary_next_action_code='retry_inventory_matching',
responsible_party='worker', lock_version=1, review_case_id=None, task_id=None,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-INV-1', 'status': 'blocked',
'primary_next_action_code': 'retry_inventory_matching',
'responsible_party': 'worker',
'current_gate': {
'gate_code': 'inventory_matching',
'status': 'blocked_manual',
'blocking_reason_code': 'inventory_match_incomplete',
'next_action_code': 'retry_inventory_matching',
},
'recovery_targets': [
{'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'},
],
'gates': [], 'active_recovery_plans': [],
},
)
summary = projection.project_user_gate_summary(execution)
assert summary['current_blocking_gate']['gate_code'] == 'inventory_matching'
assert summary['next_action_code'] == 'open_inventory_match_review'
assert summary['owner_type'] == 'human'
assert summary['technical_auto_only'] is False
assert summary['allowed_actions'] == [
'open_inventory_match_review',
'retry_inventory_from_preparation',
]
def test_user_gate_summary_exposes_sanitized_failure_detail_for_any_gate(app, monkeypatch):
"""所有 Gate 均应把当前 Attempt 的脱敏失败详情投影给用户,而非只显示泛化原因。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-FAIL-1', status='blocked',
current_gate_code='artifact_generation', primary_next_action_code='regenerate_excel_artifact',
responsible_party='system', lock_version=1, review_case_id=None, task_id=None,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-FAIL-1', 'status': 'blocked',
'primary_next_action_code': 'regenerate_excel_artifact',
'responsible_party': 'system', 'recovery_targets': [], 'gates': [],
'active_recovery_plans': [],
'current_gate': {
'gate_code': 'artifact_generation', 'status': 'blocked_retryable',
'blocking_reason_code': 'artifact_generation_failed',
'next_action_code': 'regenerate_excel_artifact',
'latest_attempt': {
'attempt_no': 7,
'status': 'failed',
'error_code': 'SHIPPING.EXCEL_ARTIFACT_WRITE_FAILED',
'error_summary': r'Excel 写入失败 at C:\worker\output.xlsx password=secret',
},
},
},
)
summary = projection.project_user_gate_summary(execution)
assert summary['failure_detail'] is not None
assert 'Excel 写入失败' in summary['failure_detail']
assert '[path]' in summary['failure_detail']
assert 'secret' not in summary['failure_detail']
def test_user_gate_summary_repairs_stale_rpa_action_for_gate19(app, monkeypatch):
"""历史 Gate 19 即使持久化了人工待办动作,也必须投影为 RPA 重试。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-RPA-STALE', status='blocked',
current_gate_code='freight_upload_rpa',
primary_next_action_code='regenerate_manual_upload_todo',
responsible_party='worker', lock_version=1, review_case_id=None, task_id=None,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-RPA-STALE', 'status': 'blocked',
'primary_next_action_code': 'regenerate_manual_upload_todo',
'responsible_party': 'worker', 'recovery_targets': [],
'active_recovery_plans': [], 'gates': [],
'current_gate': {
'gate_code': 'freight_upload_rpa', 'status': 'blocked_manual',
'blocking_reason_code': 'upload_platform_rejected',
'next_action_code': 'regenerate_manual_upload_todo',
},
},
)
summary = projection.project_user_gate_summary(execution)
assert summary['next_action_code'] == 'retry_freight_upload_rpa'
assert summary['owner_type'] == 'human'
def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch):
"""Gate 20 人工交接也可显式重试 RPA,且不依赖 AUTO_UPLOAD 配置。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-MANUAL-RPA', status='blocked',
current_gate_code='manual_upload_handoff',
primary_next_action_code='regenerate_manual_upload_todo',
responsible_party='owner', lock_version=1, review_case_id=None, task_id=None,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-MANUAL-RPA', 'status': 'blocked',
'primary_next_action_code': 'regenerate_manual_upload_todo',
'responsible_party': 'owner', 'recovery_targets': [],
'active_recovery_plans': [], 'gates': [],
'current_gate': {
'gate_code': 'manual_upload_handoff', 'status': 'blocked_manual',
'blocking_reason_code': 'manual_upload_pending',
'next_action_code': 'regenerate_manual_upload_todo',
},
},
)
summary = projection.project_user_gate_summary(execution)
assert summary['next_action_code'] == 'retry_freight_upload_rpa'
assert summary['owner_type'] == 'human'
def test_process_gate_dependency_integrity_and_excel_only_scope():
"""
校验依赖图完整性,并锁定「仅重生 Excel」不得失效库存匹配。
@@ -0,0 +1,109 @@
"""
tests/test_shipping_process_gate_contract_v2.py
用途:冻结 Gate v2 的 20 Gate 实施状态、恢复目标与 API 边界合同。
依赖:process_gate_contract、recovery_plan_contract、process_gate_projection。
逻辑:只验证服务端合同输出;客户端不得自行推导目标 Gate 或实现状态。
"""
from __future__ import annotations
from app.services.shipping_notice.process_gate_contract import (
PROCESS_GATE_DEFINITIONS,
PROCESS_GATE_IMPLEMENTATION_STATUSES,
assert_process_gate_contract_integrity,
)
from app.services.shipping_notice.process_gate_projection import serialize_process_gate
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
def test_gate_v2_freezes_implementation_status_for_all_twenty_gates():
"""20 个 Gate 必须都有实现状态;Gate 1–9 为 supported,Gate 10–20 为 implemented。"""
assert_process_gate_contract_integrity()
assert len(PROCESS_GATE_DEFINITIONS) == 20
assert all(item.get('implementation_status') in PROCESS_GATE_IMPLEMENTATION_STATUSES for item in PROCESS_GATE_DEFINITIONS)
assert all(item['implementation_status'] == 'supported' for item in PROCESS_GATE_DEFINITIONS[:9])
assert all(item['implementation_status'] == 'implemented' for item in PROCESS_GATE_DEFINITIONS[9:])
def test_gate_v2_cross_stage_recovery_contract_is_server_owned():
"""库存跨阶段恢复目标、继续点和失效范围必须由服务端合同固定。"""
preparation = recovery_plan_for_action(
current_gate='inventory_matching',
action_code='retry_inventory_from_preparation',
)
mapping = recovery_plan_for_action(
current_gate='inventory_matching',
action_code='retry_inventory_from_field_mapping',
)
assert preparation == {
'target_gate': 'inventory_preparation',
'resume_after_gate': 'inventory_matching',
'allowed_intermediate_gates': ('inventory_field_mapping',),
'invalidate_change_type': 'inventory_file_changed',
'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'),
'permission': 'owner_or_admin',
}
assert mapping['target_gate'] == 'inventory_field_mapping'
assert mapping['resume_after_gate'] == 'inventory_matching'
assert 'inventory_mapping' in mapping['invalidates']
def test_unknown_recovery_action_is_not_a_contract_target():
"""未注册动作不得被 Projection 或执行器当作跨阶段恢复目标。"""
assert recovery_plan_for_action(
current_gate='inventory_matching',
action_code='retry_inventory_from_excel',
) is None
def test_cross_stage_recovery_action_is_invalid_outside_inventory_matching(app):
"""跨阶段库存恢复动作在错误 Gate 上必须返回稳定 RecoveryPlan 错误码。"""
from app.core.errors import ValidationError
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
from app.services.shipping_notice.process_gate_recovery_service import request_gate_action
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
from tests.test_shipping_process_gate_service import _seed_workflow_version
from app import db
from app.models import ShippingProcessGate
with app.app_context():
user, _review_case_id, task_id = _seed_workflow_version(suffix='v2-cross-stage-invalid')
execution = ensure_execution_for_workflow_version(
task_id=int(task_id),
)
apply_gate_outcome(
execution=execution, gate_code='inventory_preparation', passed=False,
blocking_reason_code='inventory_snapshot_prepare_failed', effective_result={},
force=True, idempotency_key='v2-cross-stage-seed',
)
gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code='inventory_preparation',
).first()
assert gate is not None
with __import__('pytest').raises(ValidationError) as exc:
request_gate_action(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
action_code='retry_inventory_from_preparation',
expected_gate_version=int(gate.evaluation_version),
idempotency_key='v2-cross-stage-invalid-action',
actor_type='user', actor_id=int(user.id), payload={},
)
assert exc.value.code == 'SHIPPING.RECOVERY_TARGET_INVALID'
def test_gate_projection_exposes_implementation_status(app, monkeypatch):
"""单 Gate Projection 必须透传服务端实现状态,避免前端猜测。"""
from types import SimpleNamespace
gate = SimpleNamespace(
id=1, gate_code='layout_parsing', sequence_no=2, status='blocked_retryable',
evaluation_version=1, input_fingerprint=None, blocking_reason_code='layout_parse_failed',
blocking_reason_json=None, recommendation_json=None, effective_result_json={},
findings_json=None, next_action_code='retry_layout_parsing', passed_at=None,
invalidated_at=None, latest_attempt_id=None,
)
monkeypatch.setattr('app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get', lambda _id: None, raising=False)
projected = serialize_process_gate(gate, include_diagnostics=False)
assert projected['implementation_status'] == 'supported'
@@ -25,10 +25,9 @@ from tests.test_shipping_process_gate_service import _seed_workflow_version
def test_ten_identical_recovery_clicks_create_one_attempt(app):
"""同一幂等键连点十次只产生一个 Attempt。"""
with app.app_context():
_user, item, version = _seed_workflow_version(suffix='fault1')
_user, _case_id, task_id = _seed_workflow_version(suffix='fault1')
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
task_id=int(task_id),
)
apply_gate_outcome(
execution=execution,
@@ -71,10 +70,9 @@ def test_ten_identical_recovery_clicks_create_one_attempt(app):
def test_active_attempt_blocks_second_queue(app):
"""已有活动 Attempt 时第二次不同幂等键必须 Conflict。"""
with app.app_context():
_user, item, version = _seed_workflow_version(suffix='fault2')
_user, _case_id, task_id = _seed_workflow_version(suffix='fault2')
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
task_id=int(task_id),
)
apply_gate_outcome(
execution=execution,
@@ -120,10 +118,9 @@ def test_audit_failure_rolls_back_gate_queue(app, monkeypatch):
核心逻辑:monkeypatch record_fulfillment_audit 抛错,断言 queue 抛出且无 Attempt 行。
"""
with app.app_context():
_user, item, version = _seed_workflow_version(suffix='fault3')
_user, _case_id, task_id = _seed_workflow_version(suffix='fault3')
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
task_id=int(task_id),
)
apply_gate_outcome(
execution=execution,
@@ -167,10 +164,9 @@ def test_request_gate_action_rejects_forbidden_controls(app):
from app.core.errors import ValidationError
with app.app_context():
_user, item, version = _seed_workflow_version(suffix='fault4')
_user, _case_id, task_id = _seed_workflow_version(suffix='fault4')
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
task_id=int(task_id),
)
apply_gate_outcome(
execution=execution,
@@ -36,10 +36,12 @@ def test_lease_takeover_after_stale_heartbeat(app, monkeypatch):
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
lambda **kwargs: 0,
)
_user, item, version = _seed_workflow_version(suffix='lease1')
_user, review_case_id, task_id = _seed_workflow_version(suffix='lease1')
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
review_case_id=review_case_id,
task_id=task_id,
actor_type='system',
actor_id='lease-test',
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
@@ -72,10 +74,12 @@ def test_heartbeat_rejects_foreign_lease(app):
from app.core.errors import ConflictError
with app.app_context():
_user, item, version = _seed_workflow_version(suffix='lease2')
_user, review_case_id, task_id = _seed_workflow_version(suffix='lease2')
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
review_case_id=review_case_id,
task_id=task_id,
actor_type='system',
actor_id='lease-test',
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
@@ -110,10 +114,12 @@ def test_sync_manual_open_via_claim_and_run(app, monkeypatch):
'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job',
lambda **kwargs: 0,
)
_user, item, version = _seed_workflow_version(suffix='lease3')
_user, review_case_id, task_id = _seed_workflow_version(suffix='lease3')
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
review_case_id=review_case_id,
task_id=task_id,
actor_type='system',
actor_id='lease-test',
)
# 先阻断冻结门禁,再排队人工打开动作。
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
@@ -1,10 +1,10 @@
"""
tests/test_shipping_process_gate_retry_cap.py
用途:验证门禁技术失败跨 force_new Job 累计重试上限,并在耗尽后收口 Attempt/Gate。
用途:验证门禁技术失败只执行一次,并在失败后收口 Attempt/Gate,等待人工重试。
依赖:Flask testing app、run_shipping_process_gate handler、process_gate_service。
逻辑:mock claim_and_run 持续抛错;按 failed Job 累计;断言 TECHNICAL_RETRIES 次后
Attempt/Gate 进入 failed_terminal、input_snapshot Hash 一致、且不再入队重试 Job。
逻辑:mock claim_and_run 抛错;断言只产生一个失败 Job,Attempt 失败、Gate 进入 blocked_retryable,
并保留人工恢复入口。
"""
from __future__ import annotations
@@ -26,14 +26,13 @@ from app.services.shipping_notice.process_gate_service import (
from tests.test_shipping_process_gate_service import _seed_workflow_version
def test_technical_retries_cap_across_force_new_jobs(app):
"""跨 Job 累计失败达到上限后必须 failed_terminal,且不再新建 queued Job。"""
def test_gate_failure_does_not_auto_retry(app):
"""门禁失败只产生一个失败 Job,并保留原 Gate 的人工恢复入口。"""
with app.app_context():
app.config['SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES'] = 3
_user, item, version = _seed_workflow_version(suffix='retrycap')
_user, review_case_id, task_id = _seed_workflow_version(suffix='retrycap')
execution = ensure_execution_for_workflow_version(
workflow_item_id=int(item.id),
workflow_item_version_id=int(version.id),
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
@@ -47,49 +46,53 @@ def test_technical_retries_cap_across_force_new_jobs(app):
first_job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id))
db.session.commit()
attempt_id = int(attempt.id)
rollback_seen = {'value': False}
real_get = db.session.get
def _get_after_rollback(model, ident):
"""模拟 PostgreSQL aborted transaction:Attempt 只能在 rollback 后重读。"""
if model is ShippingProcessGateAttempt and not rollback_seen['value']:
raise AssertionError('attempt reloaded before rollback')
return real_get(model, ident)
real_rollback = db.session.rollback
def _record_rollback():
rollback_seen['value'] = True
return real_rollback()
with patch(
'app.jobs.handlers.shipping_process_gate.claim_and_run_gate_attempt',
side_effect=RuntimeError('boom https://erp.example.com/x?token=abc'),
), patch.object(db.session, 'get', side_effect=_get_after_rollback), patch.object(
db.session, 'rollback', side_effect=_record_rollback,
):
for round_idx in range(5):
attempt_row = db.session.get(ShippingProcessGateAttempt, attempt_id)
assert attempt_row is not None
if attempt_row.status in {'failed', 'succeeded', 'cancelled'}:
break
job_id = int(attempt_row.job_id or 0)
if job_id <= 0:
job_id = enqueue_gate_attempt_job(attempt_id=attempt_id, force_new=True)
db.session.commit()
job = db.session.get(Job, job_id)
assert job is not None
job.status = 'running'
job.attempts = 1
attempt_row.status = 'running'
gate = db.session.get(ShippingProcessGate, int(attempt_row.gate_id))
if gate is not None:
gate.status = 'running'
db.session.commit()
job = db.session.get(Job, int(first_job_id))
assert job is not None
job.status = 'running'
job.attempts = 1
attempt.status = 'running'
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
if gate is not None:
gate.status = 'running'
db.session.commit()
ctx = MagicMock()
ctx.extras = {'worker_label': f'retry-cap-worker-{round_idx}'}
run_shipping_process_gate(ctx, {'attempt_id': attempt_id, 'job_id': job_id})
ctx = MagicMock()
ctx.extras = {'worker_label': 'retry-cap-worker'}
run_shipping_process_gate(ctx, {'attempt_id': attempt_id, 'job_id': int(first_job_id)})
assert rollback_seen['value'] is True
attempt_final = db.session.get(ShippingProcessGateAttempt, attempt_id)
gate_final = db.session.get(ShippingProcessGate, int(attempt_final.gate_id))
assert attempt_final is not None
assert attempt_final.status == 'failed'
assert gate_final is not None
assert gate_final.status == 'failed_terminal'
assert attempt_final.error_code == 'TECHNICAL_RETRY_EXHAUSTED'
assert gate_final.status == 'blocked_retryable'
assert gate_final.next_action_code == 'retry_layout_parsing'
assert attempt_final.error_code == 'TECHNICAL_FAILURE'
# 敏感 URL 不得原样落库
assert 'erp.example.com' not in str(attempt_final.error_summary or '')
# [ASSERT] 技术重试不得污染业务输入快照,Hash 须与正文一致
snap = attempt_final.input_snapshot_json if isinstance(attempt_final.input_snapshot_json, dict) else {}
assert 'technical_retry_count' not in snap
from app.services.shipping_notice.process_gate_service import _stable_hash
assert attempt_final.input_snapshot_hash == _stable_hash(snap)
failed_jobs = (
Job.query
.filter_by(
@@ -99,7 +102,7 @@ def test_technical_retries_cap_across_force_new_jobs(app):
)
.count()
)
assert failed_jobs == 3
assert failed_jobs == 1
queued_jobs = (
Job.query
.filter_by(
@@ -399,7 +399,75 @@ def test_each_gate_supports_passed_manual_blocked_and_technical_failed(app, gate
assert terminal.status == 'failed_terminal'
def test_business_sync_reuses_same_gate_active_attempt(app):
"""Gate 执行器同步同门业务事实时不得递归创建第二个 Attempt。"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='activefactsync')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='active-fact-sync',
input_snapshot={
'action_code': 'retry_inventory_preparation',
'payload': {'actor_user_id': 1},
},
)
from app.services.shipping_notice.process_gate_service import mark_attempt_running
mark_attempt_running(attempt_id=int(attempt.id), worker_id='active-fact-sync')
gate = sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=False,
blocking_reason_code='inventory_file_missing',
effective_result_json={'findings': [], 'has_inventory_lines': False},
idempotency_key='nested-fact-sync-must-not-queue',
)
assert gate.status == 'running'
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
def test_force_business_sync_uses_current_gate_version(app):
"""强制重评不得回放失效前的固定幂等 Attempt。"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='forceversion')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
first = apply_gate_outcome(
execution=execution,
gate_code='task_creation',
passed=True,
effective_result={'findings': [], 'task_no': 'T-1'},
idempotency_key='fixed-task-sync',
force=True,
)
assert first is not None and first.status == 'passed'
first.status = 'invalidated'
first.blocking_reason_code = 'gate_invalidated'
first.evaluation_version = int(first.evaluation_version) + 1
db.session.flush()
second = apply_gate_outcome(
execution=execution,
gate_code='task_creation',
passed=True,
effective_result={'findings': [], 'task_no': 'T-1'},
idempotency_key='fixed-task-sync',
force=True,
)
assert second is not None and second.status == 'passed'
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(second.id)).count() == 2
def test_idempotent_queue_replays_same_attempt(gate_execution):
@@ -0,0 +1,795 @@
"""
用途:验证 RecoveryPlan 与库存准备谱系的结构化合同。
依赖:SQLAlchemy metadata、ShippingProcessRecoveryPlan、库存准备/Mapping 模型。
逻辑:只验证模型约束和关键状态字段,不触发外部 RPA 或业务恢复副作用。
"""
from __future__ import annotations
from sqlalchemy import UniqueConstraint
from app.models import (
ShippingInventoryMapping,
ShippingInventoryPreparationAttempt,
ShippingInventoryPreparationSourceAttempt,
ShippingProcessRecoveryPlan,
)
def _unique_names(model) -> set[str]:
return {
str(item.name)
for item in model.__table__.constraints
if isinstance(item, UniqueConstraint) and item.name
}
def test_recovery_plan_has_idempotent_business_identity():
"""RecoveryPlan 必须以 plan_no 和 execution+idempotency_key 形成业务幂等边界。"""
names = _unique_names(ShippingProcessRecoveryPlan)
assert 'uq_shipping_process_recovery_plans_no' in names
assert 'uq_shipping_process_recovery_plans_execution_idempotency' in names
assert 'status' in ShippingProcessRecoveryPlan.__table__.c
assert 'invalidation_plan_json' in ShippingProcessRecoveryPlan.__table__.c
def test_inventory_preparation_is_task_round_with_per_source_uniqueness():
"""准备轮次和逐源 Attempt 均必须保留不可混淆的唯一范围。"""
assert 'uq_shipping_inventory_preparation_task_attempt' in _unique_names(ShippingInventoryPreparationAttempt)
assert 'uq_shipping_inventory_preparation_source_attempt' in _unique_names(ShippingInventoryPreparationSourceAttempt)
assert {'source_code', 'status', 'inventory_file_id', 'rpa_attempt_id'} <= set(
ShippingInventoryPreparationSourceAttempt.__table__.c.keys()
)
def test_rpa_attempt_status_updates_its_bound_preparation_source(app):
"""RPA 回调必须更新既有 SourceAttempt,并聚合 PreparationAttempt 状态。"""
from app import db
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
from app.services.shipping_notice.inventory_recovery_service import (
create_inventory_preparation_round,
sync_inventory_preparation_round,
sync_preparation_source_from_rpa_attempt,
)
task = ShippingNotice(task_no='SN-PREP-LINEAGE-1', process_status='waiting_inventory')
db.session.add(task)
db.session.flush()
preparation = create_inventory_preparation_round(
task=task, execution_id=88, recovery_plan_id=None,
action_code='retry_inventory_preparation', source_codes=['DBS'], gate_attempt_id=301,
)
rpa = ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='DBS', attempt_no=1, source_run_no='PSR-LINEAGE-1',
status='queued', lease_token='lease-lineage', extra_json={}, callback_payload_json={},
)
db.session.add(rpa)
db.session.flush()
sync_inventory_preparation_round(
preparation_attempt=preparation,
result={'pending_source_codes': ['DBS'], 'source_attempts': {'DBS': {'attempt_id': rpa.id}}},
)
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=rpa.id, rpa_status='succeeded')
source = preparation.source_attempts[0]
assert preparation.input_snapshot_json['gate_attempt_id'] == 301
assert preparation.gate_attempt_id == 301
assert source.rpa_attempt_id == rpa.id
assert source.status == 'ready'
assert preparation.status == 'succeeded'
def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, app):
"""库存准备 Trigger 必须把 GateAttempt 身份原样带到 RPA。"""
from app import db
from app.models import ShippingNotice, ShippingProcessGate
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
from app.services.shipping_notice import per_source_rpa_service
task = ShippingNotice(task_no='SN-PREP-TRIGGER-IDENTITY', process_status='waiting_inventory')
db.session.add(task)
db.session.flush()
execution = ensure_execution_for_workflow_version(task_id=int(task.id), actor_type='system')
execution.current_gate_code = 'inventory_preparation'
task.active_process_execution_id = int(execution.id)
db.session.flush()
gate = ShippingProcessGate.query.filter_by(execution_id=int(execution.id), gate_code='inventory_preparation').first()
assert gate is not None
db.session.commit()
captured = {}
monkeypatch.setattr(
per_source_rpa_service,
'write_inventory_export_trigger_for_task',
lambda task_no, source, payload=None: captured.update(payload or {}) or 'trigger.json',
)
monkeypatch.setattr('app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', lambda task: {'source_code': 'DBS', 'warehouse_id': 'WH-1'})
monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS'])
monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False)
monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None)
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='auto')
assert result.pending_source_codes == ['DBS']
assert captured['execution_id'] == task.active_process_execution_id
assert captured['gate_id'] == gate.id
assert captured['callback_id'].endswith(':C1')
def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
"""旧 CandidateSet 回调必须在写入库存事实前被拒绝。"""
from app import db
from app.models import (
ShippingInventoryCandidateSet,
ShippingNotice,
ShippingTaskInventoryRpaAttempt,
)
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
task = ShippingNotice(task_no='SN-PREP-CALLBACK-IDENTITY', process_status='waiting_inventory')
db.session.add(task)
db.session.flush()
current = ShippingInventoryCandidateSet(
task_id=task.id, set_version=2, lifecycle_status='frozen', input_fingerprint='b' * 64,
)
db.session.add(current)
db.session.flush()
task.active_inventory_candidate_set_id = current.id
attempt = ShippingTaskInventoryRpaAttempt(
task_no=task.task_no,
source_code='DBS',
attempt_no=1,
source_run_no='PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X',
status='running',
callback_id='PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X:C1',
lease_token='lease-1',
extra_json={
'candidate_set_id': 999,
'execution_id': 88,
'gate_id': 901,
'expected_warehouse_id': 'WH-1',
},
)
db.session.add(attempt)
db.session.commit()
result, handled = per_source_callback_handler(
task,
source_code='DBS',
run_no=attempt.source_run_no,
callback_payload={
'schema_version': 'shipping_inventory_rpa.v2',
'callback_id': 'PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X:C2',
'task_no': task.task_no,
'source_code': 'DBS',
'source_run_no': attempt.source_run_no,
'attempt_no': 1,
'lease_token': 'lease-1',
'candidate_set_id': current.id,
'execution_id': 88,
'gate_id': 901,
'expected_warehouse_id': 'WH-1',
'status': 'success',
},
)
assert result == 'identity_mismatch'
assert handled is attempt
db.session.refresh(attempt)
assert attempt.status == 'running'
def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app, monkeypatch):
"""统一单源回调入口遇到身份错配时必须拒绝且不得落入旧库存写入路径。"""
from app import db
from app.models import ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice import inventory_rpa_workflow
task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY', process_status='waiting_inventory')
db.session.add(task)
db.session.commit()
monkeypatch.setattr(
inventory_rpa_workflow,
'_validate_single_source_v2_contract',
lambda task, payload: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler',
lambda task, source_code, run_no, callback_payload: ('identity_mismatch', object()),
)
legacy_called = {'value': False}
monkeypatch.setattr(
inventory_rpa_workflow,
'_lock_task_for_rpa_callback',
lambda task: legacy_called.__setitem__('value', True) or task,
)
response = inventory_rpa_workflow.rpa_report_inventory({
'schema_version': 'shipping_inventory_rpa.v2',
'callback_id': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X:C1',
'task_no': task.task_no,
'task_id': task.task_no,
'source_code': 'DBS',
'source_run_no': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X',
'run_no': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X',
'attempt_no': 1,
'lease_token': 'lease-invalid',
'candidate_set_id': 999,
'execution_id': 88,
'gate_id': 901,
'status': 'success',
})
assert response['status'] == 'failed'
assert response['data']['error_code'] == 'callback_identity_mismatch'
assert legacy_called['value'] is False
assert db.session.query(ShippingTaskEvent).filter_by(
task_id=task.id,
event_type='rpa_callback_rejected',
).count() == 1
def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app, monkeypatch):
"""PSR run_no 中 task_no 可含连字符,入口仍必须解析出真实 source_code。"""
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice import inventory_rpa_workflow
task = ShippingNotice(task_no='SN-2026-001', process_status='waiting_inventory')
db.session.add(task)
db.session.commit()
captured = {}
monkeypatch.setattr(inventory_rpa_workflow, '_validate_single_source_v2_contract', lambda task, payload: None)
monkeypatch.setattr(
'app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler',
lambda task, source_code, run_no, callback_payload: captured.update(source_code=source_code, run_no=run_no) or ('identity_mismatch', object()),
)
inventory_rpa_workflow.rpa_report_inventory({
'schema_version': 'shipping_inventory_rpa.v2',
'callback_id': 'PSR-SN-2026-001-DBS-A1-X:C1',
'task_no': task.task_no,
'task_id': task.task_no,
'source_code': 'DBS',
'source_run_no': 'PSR-SN-2026-001-DBS-A1-X',
'run_no': 'PSR-SN-2026-001-DBS-A1-X',
'attempt_no': 1,
'lease_token': 'lease-invalid',
'candidate_set_id': 999,
'execution_id': 88,
'gate_id': 901,
'status': 'success',
})
assert captured == {'source_code': 'DBS', 'run_no': 'PSR-SN-2026-001-DBS-A1-X'}
def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch(app, monkeypatch):
"""批量成功项也必须先通过逐源身份校验,不能先入库再拒绝。"""
from app import db
from app.models import ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice import inventory_rpa_workflow
task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY', process_status='waiting_inventory')
db.session.add(task)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler',
lambda task, source_code, run_no, callback_payload: ('identity_mismatch', object()),
)
legacy_called = {'value': False}
monkeypatch.setattr(
inventory_rpa_workflow,
'_lock_task_for_rpa_callback',
lambda task: legacy_called.__setitem__('value', True) or task,
)
response = inventory_rpa_workflow.rpa_report_inventory_batch({
'schema_version': 'shipping_inventory_rpa.v2',
'callback_id': 'batch-callback-identity',
'batch_run_no': 'BATCH-CALLBACK-IDENTITY',
'results': [{
'task_no': task.task_no,
'source_code': 'DBS',
'source_run_no': 'PSR-SNCALLBACKBATCHIDENTITY-DBS-A1-X',
'callback_id': 'PSR-SNCALLBACKBATCHIDENTITY-DBS-A1-X:C1',
'status': 'success',
'warehouse_id': 'WH-1',
}],
})
assert response['failed_count'] == 1
assert response['data']['failed'][0]['error_code'] == 'callback_identity_mismatch'
assert legacy_called['value'] is False
assert db.session.query(ShippingTaskEvent).filter_by(
task_id=task.id,
event_type='rpa_callback_rejected',
).count() == 1
def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch):
"""正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。"""
from app import db
from app.models import (
ShippingInventoryCandidateSet,
ShippingInventoryPreparationAttempt,
ShippingNotice,
ShippingProcessGate,
ShippingProcessGateAttempt,
)
from app.services.shipping_notice.process_gate_job_service import claim_and_run_gate_attempt
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
queue_gate_attempt,
)
task = ShippingNotice(
task_no='SNFORMALPREPLINEAGE',
process_status='waiting_inventory',
inventory_source_code='DBS',
)
db.session.add(task)
db.session.flush()
candidate = ShippingInventoryCandidateSet(
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='c' * 64,
)
db.session.add(candidate)
db.session.flush()
task.active_inventory_candidate_set_id = candidate.id
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
execution.candidate_set_id = candidate.id
execution.current_gate_code = 'inventory_preparation'
task.active_process_execution_id = execution.id
gate = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='inventory_preparation',
).one()
gate.status = 'pending'
gate.next_action_code = 'retry_inventory_preparation'
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
lambda payload: {
'status': 'success',
'data': {
'rpa': {
'all_prepared': True,
'prepared_source_codes': ['DBS'],
'pending_source_codes': [],
'failed_source_codes': [],
'source_attempts': {},
},
},
},
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='auto',
actor_type='system',
actor_id='test',
idempotency_key='formal-prep-lineage-1',
input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}},
)
result = claim_and_run_gate_attempt(attempt_id=attempt.id, worker_id='lineage-worker')
db.session.refresh(attempt)
db.session.refresh(gate)
preparation = ShippingInventoryPreparationAttempt.query.filter_by(
task_id=task.id, execution_id=execution.id, gate_attempt_id=attempt.id,
).one()
assert result.get('skipped') is False
assert attempt.status == 'succeeded'
assert gate.status == 'passed'
assert preparation.status == 'succeeded'
assert len(preparation.source_attempts) == 1
assert preparation.source_attempts[0].source_code == 'DBS'
assert preparation.source_attempts[0].status == 'ready'
assert preparation.source_attempts[0].rpa_attempt_id is None
db.session.refresh(execution)
assert execution.current_gate_code != 'inventory_preparation'
def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app):
"""正式起始 Gate 必须优先反映未完成的客户确认事实。"""
from app import db
from app.models import ShippingInventoryCandidateSet, ShippingNotice
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
task = ShippingNotice(
task_no='SNSTARTCUSTOMERPENDING',
process_status='created',
current_order_extraction_id=101,
order_snapshot_id=201,
customer_resolution_status='pending',
)
db.session.add(task)
db.session.flush()
candidate = ShippingInventoryCandidateSet(
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='d' * 64,
)
db.session.add(candidate)
db.session.flush()
assert determine_formal_start_gate(task, candidate_set=candidate) == 'customer_resolution'
def test_formal_start_gate_stops_at_field_conflict_before_inventory(app):
"""正式起始 Gate 必须优先反映尚未解决的订单字段冲突。"""
from app import db
from app.models import ShippingInventoryCandidateSet, ShippingNotice, ShippingTaskFieldConflict
from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate
task = ShippingNotice(
task_no='SNSTARTFIELDCONFLICT',
process_status='created',
current_order_extraction_id=101,
order_snapshot_id=201,
customer_resolution_status='confirmed',
)
db.session.add(task)
db.session.flush()
db.session.add(ShippingTaskFieldConflict(
task_id=task.id, field_name='part_number', status='open',
))
candidate = ShippingInventoryCandidateSet(
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='e' * 64,
)
db.session.add(candidate)
db.session.flush()
assert determine_formal_start_gate(task, candidate_set=candidate) == 'field_conflict_resolution'
def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app):
"""候选重冻结必须同时终止旧正式 GateAttempt 与其 Job。"""
from app import db
from app.models import Job, ShippingInventoryCandidateSet, ShippingNotice, ShippingProcessGateAttempt
from app.services.shipping_notice.auto_progress_controller import supersede_auto_progress_for_candidate_refreeze
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version, queue_gate_attempt
task = ShippingNotice(task_no='SNCANDIDATEREFREEZEATTEMPT', process_status='waiting_inventory')
db.session.add(task)
db.session.flush()
old_candidate = ShippingInventoryCandidateSet(
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='f' * 64,
)
db.session.add(old_candidate)
db.session.flush()
task.active_inventory_candidate_set_id = old_candidate.id
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
execution.candidate_set_id = old_candidate.id
task.active_process_execution_id = execution.id
db.session.flush()
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='auto', actor_type='system', actor_id='test',
idempotency_key='candidate-refreeze-attempt-1',
input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}},
)
job = Job.query.filter_by(id=attempt.job_id).one_or_none()
if job is None:
job = Job(
domain='shipping_notice', job_type='shipping_process_gate', task_id=task.id,
execution_id=execution.id, gate_id=attempt.gate_id, candidate_set_id=old_candidate.id,
status='queued', payload_json={'attempt_id': attempt.id}, business_ref='candidate-refreeze-job',
)
db.session.add(job)
db.session.flush()
attempt.job_id = job.id
db.session.commit()
supersede_auto_progress_for_candidate_refreeze(task)
db.session.commit()
db.session.refresh(attempt)
db.session.refresh(job)
assert attempt.status in {'superseded', 'cancelled'}
assert job.status == 'cancelled'
def test_legacy_workspace_forwarding_audit_is_structured(app):
"""旧工作台动作转发必须留下 legacy_forwarded 入口审计。"""
from app import db
from app.models import ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint
task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT', process_status='waiting_inventory')
db.session.add(task)
db.session.flush()
audit_legacy_forwarded_entrypoint(
task=task,
action_code='match_inventory',
actor_id=42,
request_id='req-legacy-forward',
)
row = ShippingTaskEvent.query.filter_by(
task_id=task.id,
event_type='shipping_legacy_entrypoint_forwarded',
).one()
assert row.source == 'workspace_api'
assert row.actor_id == 42
assert row.request_id == 'req-legacy-forward'
assert row.detail_json == {
'entrypoint': 'legacy_forwarded',
'action_code': 'match_inventory',
}
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', process_status='waiting_inventory')
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)
assert {'version', 'status', 'mapping_json', 'input_fingerprint', 'superseded_by_id'} <= set(
ShippingInventoryMapping.__table__.c.keys()
)
def test_process_execution_projection_exposes_server_owned_recovery_targets(app):
"""Projection 必须只读暴露服务端 RecoveryPlan 目标,不让客户端自行推导 target Gate。"""
from app import db
from app.models import ShippingProcessExecution, ShippingProcessGate
from app.services.shipping_notice.process_gate_projection import serialize_process_execution
with app.app_context():
execution = ShippingProcessExecution(
execution_no='EXE-PROJECTION-RECOVERY', status='blocked',
current_gate_code='inventory_matching', lock_version=1,
)
db.session.add(execution)
db.session.flush()
db.session.add(ShippingProcessGate(
execution_id=execution.id, gate_code='inventory_matching', sequence_no=15,
status='blocked_manual', evaluation_version=2,
))
db.session.flush()
projection = serialize_process_execution(execution)
targets = {item['action_code']: item for item in projection['recovery_targets']}
gate_targets = {item['action_code']: item for item in projection['current_gate']['recovery_targets']}
assert targets['retry_inventory_from_preparation']['target_gate'] == 'inventory_preparation'
assert gate_targets['retry_inventory_from_preparation']['target_gate'] == 'inventory_preparation'
assert targets['retry_inventory_from_field_mapping']['resume_after_gate'] == 'inventory_matching'
assert projection['active_recovery_plans'] == []
def test_recovery_plan_outcome_mapping_is_terminal_or_waiting():
"""RecoveryPlan 必须将 Attempt 结果映射到可审计的计划状态。"""
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
class Plan:
status = 'queued'
action_code = 'retry_inventory_from_preparation'
resume_after_gate = 'inventory_sufficiency'
started_at = None
completed_at = None
failure_code = None
failure_detail_json = None
plan = Plan()
complete_recovery_plan_for_attempt(plan=plan, outcome='passed')
assert plan.status == 'succeeded'
assert plan.completed_at is not None
plan = Plan()
complete_recovery_plan_for_attempt(plan=plan, outcome='waiting_external')
assert plan.status == 'waiting_external'
assert plan.completed_at is None
def test_current_inventory_rematch_shortage_completes_recovery_plan():
"""当前库存重匹配已完成但仍有缺口时,计划必须完成而非永久占用活动恢复位。"""
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
class Plan:
status = 'queued'
action_code = 'retry_inventory_from_matching'
resume_after_gate = 'inventory_sufficiency'
started_at = None
completed_at = None
failure_code = None
failure_detail_json = None
plan = Plan()
complete_recovery_plan_for_attempt(
plan=plan,
outcome='blocked_manual',
business_result_code='inventory_shortage_review_required',
)
# 关键断言:重新匹配动作已完成;正式流程仍可由 Gate 16 表达缺口人工复核。
assert plan.status == 'succeeded'
assert plan.completed_at is not None
def test_inventory_rematch_shortage_is_business_result_not_technical_failure(monkeypatch):
"""库存 14、缺口 16 时,匹配 Attempt 成功收口到缺口复核。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching
task = SimpleNamespace(
match_status='partial',
shortage_json={'lines': [{'available_qty': 14, 'shortage_qty': 16}]},
)
monkeypatch.setattr(
'app.models.ShippingNotice.query',
SimpleNamespace(get=lambda _task_id: task),
)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
lambda _payload: {'status': 'needs_human', 'message': '当前 Gate 需要人工处理。'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._task_payload',
lambda _execution, _payload: {'_orchestrator_internal_dispatch': True},
)
result = _handle_retry_inventory_matching(
execution=SimpleNamespace(task_id=13),
gate=SimpleNamespace(gate_code='inventory_sufficiency'),
payload={'actor_user_id': 1},
)
assert result['outcome'] == 'blocked_manual'
assert result['blocking_reason_code'] == 'inventory_shortage_review_required'
assert result['effective_result_json']['shortage']['lines'][0] == {
'available_qty': 14,
'shortage_qty': 16,
}
def test_field_mapping_recovery_does_not_create_preparation_round(monkeypatch):
"""字段映射恢复必须停留在 mapping handler,不得误建库存准备轮次。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _dispatch_action
called = {'preparation': 0, 'matching': 0}
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_preparation',
lambda **_: called.__setitem__('preparation', called['preparation'] + 1) or {'outcome': 'passed'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_from_field_mapping',
lambda **_: {'outcome': 'blocked_manual'},
)
result = _dispatch_action(
execution=object(), gate=SimpleNamespace(gate_code='inventory_matching'),
action_code='retry_inventory_from_field_mapping', payload={},
)
assert result['outcome'] == 'blocked_manual'
assert called['preparation'] == 0
def test_field_mapping_recovery_resumes_matching_after_mapping_passes(monkeypatch):
"""字段映射完成后必须重跑匹配,不能把 mapping 成功误作 matching 成功。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_from_field_mapping
called = {'matching': 0}
monkeypatch.setattr(
'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
lambda **_: {},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_field_mapping',
lambda **_: {'outcome': 'passed'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_matching',
lambda **_: called.__setitem__('matching', called['matching'] + 1) or {'outcome': 'passed'},
)
result = _handle_retry_inventory_from_field_mapping(
execution=object(), gate=SimpleNamespace(gate_code='inventory_matching'), payload={},
)
assert result['outcome'] == 'passed'
assert called['matching'] == 1
def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypatch):
"""Gate Attempt 内调用库存匹配时不得递归提交第二次 auto-progress。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _task_payload
task = SimpleNamespace(task_no='SN-INTERNAL-DISPATCH')
monkeypatch.setattr(
'app.models.ShippingNotice.query',
SimpleNamespace(get=lambda _task_id: task),
)
result = _task_payload(
SimpleNamespace(task_id=123),
{'actor_user_id': 9},
)
# 关键断言:由当前 Gate Worker 直接执行匹配原子步骤,不再绕回 facade。
assert result['_orchestrator_internal_dispatch'] is True
assert result['task_id'] == 'SN-INTERNAL-DISPATCH'
assert result['operator_id'] == 9
def test_manual_business_block_is_a_successful_attempt(app):
"""库存匹配已执行但存在缺口时,Attempt 成功、Gate 保持人工阻断。"""
from app import db
from app.models import ShippingProcessGateAttempt
from app.services.shipping_notice.process_gate_service import (
complete_gate_attempt,
ensure_execution_for_workflow_version,
mark_attempt_running,
queue_gate_attempt,
)
from tests.test_shipping_process_gate_service import _seed_workflow_version
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='manual-block-success')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_sufficiency',
trigger_type='user_retry',
actor_type='user',
actor_id=1,
idempotency_key='manual-block-success',
input_snapshot={'action_code': 'retry_inventory_from_matching', 'payload': {}},
)
mark_attempt_running(attempt_id=int(attempt.id), worker_id='test')
gate = complete_gate_attempt(
attempt_id=int(attempt.id),
outcome='blocked_manual',
blocking_reason_code='inventory_insufficient',
effective_result_json={
'match_status': 'partial',
'available_qty': 14,
'shortage_qty': 16,
},
)
db.session.flush()
refreshed_attempt = db.session.get(ShippingProcessGateAttempt, int(attempt.id))
# 关键断言:业务缺口不是执行器失败;数量事实保持只读并留在 Gate 结果。
assert refreshed_attempt.status == 'succeeded'
assert gate.status == 'blocked_manual'
assert gate.effective_result_json['available_qty'] == 14
assert gate.effective_result_json['shortage_qty'] == 16
@@ -10,6 +10,7 @@ backend/tests/test_shipping_processing_projection_invariants.py
from __future__ import annotations
from app.services.shipping_notice.processing_projection_invariants import (
apply_user_projection_fields,
build_stage_nodes,
derivation_status_for_extraction_run,
normalize_action_code,
@@ -66,6 +67,22 @@ def test_completed_clears_write_actions_and_gate():
assert payload['available_actions'] == ['view_result']
def test_projection_fact_read_failure_is_fail_closed():
"""关键事实读取失败时必须进入人工诊断态,不得静默返回旧动作。"""
payload = reconcile_processing_projection_facts({
'status': 'running',
'stage': 'inventory_preparation',
'source_type': 'eml',
'projection_data_inconsistent': True,
'available_actions': ['retry_inventory_preparation'],
})
assert payload['status'] == 'waiting_human'
assert payload['retryable'] is False
assert payload['primary_action'] is None
assert payload['available_actions'] == []
assert payload['blocking_reason']['code'] == 'projection_data_inconsistent'
def test_normalize_unknown_action_codes():
"""未知 / 别名动作码映射到契约或丢弃。"""
assert normalize_action_code('retry_failed_documents') == 'retry'
@@ -133,6 +150,47 @@ def test_download_excel_requires_excel_ready_fact():
assert 'regenerate_excel' not in with_ready
def test_artifact_gate_overrides_stale_inventory_stage_and_action():
"""Gate 18 阻断时不得继续展示旧库存匹配阶段或 match_inventory。"""
payload = reconcile_processing_projection_facts({
'status': 'automating',
'stage': 'inventory_matching',
'source_type': 'order_task',
'shipping_notice_no': 'SN-1',
'current_gate': {
'gate_code': 'artifact_generation',
'status': 'blocked_retryable',
'next_action_code': 'regenerate_excel_artifact',
'blocking_reason_code': 'artifact_generation_failed',
},
'available_actions': ['match_inventory'],
})
assert payload['status'] == 'blocked'
assert payload['stage'] == 'excel_generating'
assert payload['stage_label_key'] == 'excel_generating'
assert payload['current_gate']['next_action_code'] == 'regenerate_excel_artifact'
assert payload['available_actions'] == ['regenerate_excel']
def test_artifact_gate_primary_action_uses_gate_not_legacy_stage():
"""用户态主动作必须投影为重新生成 Excel。"""
payload = apply_user_projection_fields({
'status': 'blocked',
'stage': 'excel_generating',
'source_type': 'order_task',
'shipping_notice_no': 'SN-1',
'current_gate': {
'gate_code': 'artifact_generation',
'status': 'blocked_retryable',
'next_action_code': 'regenerate_excel_artifact',
'blocking_reason_code': 'artifact_generation_failed',
},
'available_actions': ['regenerate_excel'],
})
assert payload['user_status'] == 'retryable'
assert payload['primary_action']['code'] == 'regenerate_excel'
def test_map_notice_to_processing_status_stage_domain_mapping():
"""BE-05:Notice 履约态映射属领域层,写/读共用。"""
from types import SimpleNamespace
@@ -207,3 +265,73 @@ def test_derive_available_actions_failed_adds_retry():
excel_ready=False,
)
assert 'retry' in actions
def test_waiting_human_reconcile_action_uses_projected_available_actions():
"""人工阻断存在统一对账动作时,主动作必须从当前投影动作列表中安全选取。"""
payload = apply_user_projection_fields({
'status': 'waiting_review',
'stage': 'inventory_matching',
'current_gate': {
'gate_code': 'inventory_candidates_calculated',
'status': 'blocked',
'blocking_reason_code': 'inventory_candidates_required',
},
'available_actions': ['reconcile_and_progress', 'view_details'],
})
# 关键断言:该分支不得因未定义局部变量返回 500,且必须选中统一恢复入口。
assert payload['user_status'] == 'waiting_human'
assert payload['primary_action']['code'] == 'reconcile_and_progress'
def test_waiting_human_without_reconcile_action_has_no_false_primary_action():
"""未知人工阻断未提供统一对账动作时,不得凭空生成可执行主动作。"""
payload = apply_user_projection_fields({
'status': 'waiting_review',
'stage': 'inventory_matching',
'current_gate': {
'gate_code': 'inventory_candidates_calculated',
'status': 'blocked',
'blocking_reason_code': 'inventory_candidates_required',
},
'available_actions': ['view_details'],
})
# 关键断言:没有正式动作事实时保持 None,避免前端展示无效恢复按钮。
assert payload['user_status'] == 'waiting_human'
assert payload['primary_action'] is None
def test_apply_user_projection_fields_fail_closes_inconsistent_projection():
"""事实读取异常即使发生在用户态计算后,也必须清空动作并进入诊断态。"""
payload = apply_user_projection_fields({
'status': 'running',
'stage': 'inventory_preparation',
'current_gate': {'gate_code': 'inventory_preparation', 'status': 'running'},
'available_actions': ['retry_inventory_preparation'],
'projection_data_inconsistent': True,
})
assert payload['user_status'] == 'waiting_human'
assert payload['retryable'] is False
assert payload['primary_action'] is None
assert payload['available_actions'] == []
assert payload['blocking_reason']['code'] == 'projection_data_inconsistent'
def test_inventory_milestones_are_projection_facts_not_runtime_gate_codes():
"""四个 MVP 库存里程碑必须由正式 Gate 和结构化事实派生,不能创建 APX Gate。"""
payload = apply_user_projection_fields({
'status': 'automating',
'stage': 'inventory_matching',
'current_gate': {'gate_code': 'inventory_matching', 'status': 'running'},
'available_actions': [],
})
assert payload['facts']['inventory_milestones'] == {
'candidates_calculated': 'completed',
'candidates_frozen': 'completed',
'snapshots_ready': 'completed',
'matched': 'pending',
}
@@ -412,6 +412,17 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u
assert synced['status'] == 'automating'
assert synced['stage'] == 'freight_uploading'
# 人工上传回执已落库时,Notice 终态必须覆盖尚未来得及同步的 OT 旧状态。
notice.process_status = 'uploaded'
order_task.status = 'automating'
order_task.stage = 'freight_uploading'
db.session.commit()
completed = _project_order_task_work_item(run)
assert completed['status'] == 'completed'
assert completed['stage'] == 'completed'
assert completed['user_status'] == 'completed'
assert all(node['status'] == 'passed' for node in completed['stage_nodes'])
def test_conversation_processing_rebuild_prefers_work_item_user_status(app):
"""
@@ -137,6 +137,26 @@ def test_inventory_preparation_is_system_wait_not_human_blocker():
assert summary['owner_type'] == 'system'
def test_inventory_preparation_retryable_failure_remains_human_recovery():
"""库存准备明确失败可重试时,正式 OT 后不得被误清为系统等待。"""
summary = apply_post_ot_gate_rules(
{
'current_blocking_gate': {
'gate_code': 'inventory_preparation',
'status': 'blocked_retryable',
'blocking_reason_code': 'inventory_file_missing',
},
'next_action_code': 'retry_inventory_preparation',
'technical_auto_only': False,
},
has_formal_ot=True,
)
assert summary['current_blocking_gate']['gate_code'] == 'inventory_preparation'
assert summary['next_action_code'] == 'retry_inventory_preparation'
assert summary['owner_type'] == 'human'
assert summary['technical_auto_only'] is False
def test_human_inventory_gate_kept_after_ot():
"""正式 OT 后人工库存阻断可保留。"""
summary = apply_post_ot_gate_rules(
@@ -155,6 +175,26 @@ def test_human_inventory_gate_kept_after_ot():
assert summary['technical_auto_only'] is False
def test_artifact_gate_kept_as_actionable_post_ot_gate():
"""正式 OT 后 Excel Artifact Gate 的恢复动作不得被静默隐藏。"""
summary = apply_post_ot_gate_rules(
{
'current_blocking_gate': {
'gate_code': 'artifact_generation',
'status': 'blocked_retryable',
'blocking_reason_code': 'artifact_generation_failed',
},
'next_action_code': 'regenerate_excel_artifact',
'technical_auto_only': False,
},
has_formal_ot=True,
)
assert summary['current_blocking_gate']['gate_code'] == 'artifact_generation'
assert summary['next_action_code'] == 'regenerate_excel_artifact'
assert summary['owner_type'] == 'human'
assert summary['technical_auto_only'] is False
def test_automation_phase_post_ot_waiting_to_start():
"""正式 OT 后无 Job → waiting_to_start + phase=post_ot_progress。"""
result = enrich_automation_status(
@@ -196,6 +236,21 @@ def test_project_stage_for_task_created_is_order_creating():
assert stage['source'] == 'process_status'
def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage():
"""人工上传已完成时,旧 OT freight_uploading 阶段不能覆盖 Notice 终态。"""
task = SimpleNamespace(
id=1,
order_task_id=9,
process_status='uploaded',
current_step='step6_generate_file',
stage_nodes_json=None,
step_payload_json=None,
)
stage = project_stage_for_task(task)
assert stage['code'] == 'completed'
assert stage['source'] == 'notice_terminal'
def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch):
"""Job success + OT 仍 created → failed/retryable,保留 job_id,不得伪装 waiting。"""
from types import SimpleNamespace as NS
@@ -101,7 +101,8 @@ def test_timed_out_upload_is_frozen_until_reconciled(app):
with pytest.raises(ConflictError) as retry_error:
start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key=attempt.idempotency_key)
assert retry_error.value.code == 'SHIPPING.UPLOAD_RESULT_UNKNOWN'
# 冻结合同:未知上传结果使用统一错误码,禁止以旧 timed_out 语义创建重试。
assert retry_error.value.code == 'SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN'
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading'
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
@@ -135,7 +136,8 @@ def test_timed_out_upload_requires_explicit_rejection_before_release(app):
mark_attempt_result_unknown(attempt)
complete_attempt(attempt, success=False, callback_id='late-network-error', error_message='network timeout')
assert attempt.status == 'timed_out'
# 普通迟到网络错误不得把 unknown 收口为可重试失败。
assert attempt.status == 'unknown'
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading'
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
@@ -0,0 +1,88 @@
"""
用途:验证上传未知状态保护,防止未知回执下重复创建或回写旧 Artifact。
依赖:upload_attempt_service、ShippingUploadAttempt 模型。
逻辑:覆盖 unknown 状态创建保护和 Artifact superseded 回调拒绝。
"""
from app.core.errors import ConflictError
def test_unknown_upload_blocks_new_idempotency_key_and_superseded_callback(app):
"""unknown 必须阻断全新重试键;Artifact superseded 后任何回调只返回冲突。"""
from app import db
from app.models import ShippingExportArtifact
from app.services.shipping_notice.upload_attempt_service import (
mark_attempt_result_unknown,
start_rpa_attempt,
)
from tests.test_shipping_upload_attempt import _ready_artifact
with app.app_context():
task, artifact, _reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
mark_attempt_result_unknown(attempt)
try:
start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key='fresh-retry-key')
except ConflictError as exc:
assert exc.code == 'SHIPPING.UPLOAD_RETRY_FORBIDDEN_UNTIL_TERMINAL'
else:
raise AssertionError('unknown upload must block a fresh retry key')
artifact.status = 'superseded'
db.session.flush()
from app.services.shipping_notice.upload_attempt_service import complete_attempt
try:
complete_attempt(attempt, success=True, callback_id='superseded-callback')
except ConflictError as exc:
assert exc.code == 'SHIPPING.ARTIFACT_ALREADY_SUPERSEDED'
else:
raise AssertionError('superseded Artifact must reject callbacks')
def test_upload_unknown_error_codes_are_stable():
"""稳定错误码必须区分未知状态与已失效 Artifact。"""
assert ConflictError('x', code='SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN').code == 'SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN'
assert ConflictError('x', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED').code == 'SHIPPING.ARTIFACT_ALREADY_SUPERSEDED'
def test_inventory_callback_id_is_checked_before_attempt_identity(app):
"""库存回调先按 callback_id 去重,跨 Attempt 重放不得写入另一条 Attempt。"""
from app import db
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
with app.app_context():
task = ShippingNotice(task_no='SN-CB-ID-FIRST', source_type='manual', process_status='waiting_inventory')
db.session.add(task)
db.session.flush()
first = ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='SRC-A', attempt_no=1,
source_run_no='PSR-FIRST', status='failed', callback_id=None,
)
second = ShippingTaskInventoryRpaAttempt(
task_no='SN-CB-ID-OTHER', source_code='SRC-B', attempt_no=1,
source_run_no='PSR-SECOND', status='failed', callback_id=None,
)
db.session.add_all([first, second])
db.session.flush()
result, handled = per_source_callback_handler(
task, source_code='SRC-A', run_no='PSR-FIRST',
callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'},
)
assert result == 'failed'
assert handled.id == first.id
result, handled = per_source_callback_handler(
task, source_code='SRC-A', run_no='PSR-FIRST',
callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'},
)
assert result == 'idempotent_ok'
assert handled.id == first.id
result, handled = per_source_callback_handler(
task, source_code='SRC-B', run_no='PSR-SECOND',
callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'},
)
assert result == 'callback_conflict'
assert handled.id == first.id
@@ -14,6 +14,10 @@ from app.services.shipping_notice.line_inventory_match_projection import project
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,
)
@@ -76,6 +80,27 @@ def test_decide_rpa_pending_already_running():
assert decided['reason_code'] == 'already_running'
def test_fulfillable_task_without_excel_continues_auto_progress(monkeypatch):
"""库存已完全匹配但 Excel 尚未生成时,任务级重试必须推进后续 Gate。"""
task = _task(
process_status='matched',
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')
@@ -123,3 +148,146 @@ def test_structured_running_attempt_blocks_duplicate_retry(monkeypatch):
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'
@@ -1,12 +1,32 @@
from dotenv import dotenv_values
from app import db, env_persistence
from app.models import AppSetting
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.core.config import env_persistence
from app.models import AppSetting, User
def _admin_auth_headers(app) -> dict[str, str]:
"""使用当前 JWT 鉴权合同构造企微管理端请求身份。"""
with app.app_context():
admin = db.session.query(User).filter_by(username='wecom-settings-admin').first()
if admin is None:
admin = User(
username='wecom-settings-admin',
email='wecom-settings-admin@example.com',
role='admin',
status='active',
)
admin.set_password('test-password')
db.session.add(admin)
db.session.commit()
token = issue_local_access_token(admin)
return {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}
def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path):
env_file = tmp_path / '.env'
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file)
monkeypatch.setattr(env_persistence, 'ROOT_ENV_LOCAL_PATH', env_file)
payload = {
'enabled': True,
@@ -27,7 +47,7 @@ def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_head
'public_base_url': 'https://example.com',
}
res = client.put('/api/admin/wecom/system-settings', json=payload, headers=admin_headers)
res = client.put('/api/admin/wecom/system-settings', json=payload, headers=_admin_auth_headers(app))
assert res.status_code == 200
saved = dotenv_values(env_file)
@@ -49,7 +69,7 @@ def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_head
app.config['WECOM_MATCH_OPERATOR'] = 'AND'
app.config['WECOM_PUBLIC_BASE_URL'] = ''
res = client.get('/api/admin/wecom/system-settings', headers=admin_headers)
res = client.get('/api/admin/wecom/system-settings', headers=_admin_auth_headers(app))
assert res.status_code == 200
data = res.get_json()
assert data['enabled'] is True
@@ -60,7 +80,7 @@ def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_head
def test_wecom_notify_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path):
env_file = tmp_path / '.env'
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file)
monkeypatch.setattr(env_persistence, 'ROOT_ENV_LOCAL_PATH', env_file)
payload = {
'enabled': False,
@@ -68,7 +88,7 @@ def test_wecom_notify_settings_persist_to_env_and_reload(client, app, admin_head
'events': ['task_completed', 'permission_batch_updated'],
}
res = client.put('/api/admin/wecom/notify-settings', json=payload, headers=admin_headers)
res = client.put('/api/admin/wecom/notify-settings', json=payload, headers=_admin_auth_headers(app))
assert res.status_code == 200
saved = dotenv_values(env_file)
@@ -87,7 +107,7 @@ def test_wecom_notify_settings_persist_to_env_and_reload(client, app, admin_head
app.config['WECOM_NOTIFY_BASE_URL'] = ''
app.config['WECOM_NOTIFY_EVENTS'] = ''
res = client.get('/api/admin/wecom/notify-settings', headers=admin_headers)
res = client.get('/api/admin/wecom/notify-settings', headers=_admin_auth_headers(app))
assert res.status_code == 200
data = res.get_json()
assert data['enabled'] is False
@@ -99,12 +119,12 @@ def test_wecom_system_settings_survive_when_env_file_is_wiped(client, app, admin
"""Simulate a container rebuild that wipes backend/.env. The DB row must
still drive the runtime configuration."""
env_file = tmp_path / '.env'
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file)
monkeypatch.setattr(env_persistence, 'ROOT_ENV_LOCAL_PATH', env_file)
res = client.put(
'/api/admin/wecom/system-settings',
json={'corp_id': 'ww-from-db-only', 'enabled': True},
headers=admin_headers,
headers=_admin_auth_headers(app),
)
assert res.status_code == 200
@@ -118,7 +138,7 @@ def test_wecom_system_settings_survive_when_env_file_is_wiped(client, app, admin
app.config['WECOM_CORP_ID'] = ''
app.config['WECOM_ENABLED'] = False
res = client.get('/api/admin/wecom/system-settings', headers=admin_headers)
res = client.get('/api/admin/wecom/system-settings', headers=_admin_auth_headers(app))
assert res.status_code == 200
data = res.get_json()
assert data['corp_id'] == 'ww-from-db-only'