Merge branch 'dev' into departmental-structure

This commit is contained in:
HTEWJ\26070045 committed 2026-10-29 17:11:21 +08:00
commit be49b44004
959 files changed
+89908 -34315

No files matched your search

+306
View File
@@ -0,0 +1,306 @@
"""
tests/api/test_freight_rpa_api.py
用途:/api/freight-rpa/* 回调蓝图的 HTTP 契约测试(批次 R Task 8 建立、Task 9 补 sink 注册后契约)。
依赖:tests/conftest.py 的 app/client fixture;freight_rpa.common.callback_sinks。
逻辑:锁定四条关键契约——① 心跳新路由鉴权必备;② 旧 shipping-notice rpa 回调前缀无双路由
(脏回调显式 404);③ 未注册 sink 的 kind 显式 404 且错误码 FREIGHT_RPA.SINK_NOT_REGISTERED
(分发层语义,用自造 kind 单测锁定);④ Task 9 组合根注册真实 sink 后,8 个 onhand 端点
的响应 envelope 与旧 shipping-notice rpa 回调端点逐 kind 逐字一致(禁止统一 envelope):
inventory-ready / batch-ready / batch-progress 返回裸业务 tool_response dict,
batch-claimed 返回 {'success':True,'data':...},configuration-test-* 返回 {'status':'ok','data':...};
⑤ Task 10 注册 inbound sink 后,3 个 inbound 端点维持 {'success':True,'data':...} 旧形态,
业务校验路径(400/404 错误码)与拆分前直连逐字一致。
"""
from __future__ import annotations
from datetime import datetime
import pytest
TEST_TOOL_KEY = 'test-tool-key'
@pytest.fixture
def tool_auth_headers(app):
"""以测试 integration key 生成 Bearer 鉴权头(与生产 Worker 的 Bearer 形态一致)。"""
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY
return {'Authorization': f'Bearer {TEST_TOOL_KEY}'}
@pytest.fixture
def terminal_configuration_test_run(app):
"""预置一个已终态的配置测试运行 + 批次,供 configuration-test 三端点走 OK envelope 路径。"""
from app import db
from app.models import (
FreightRpaOnhandConfigurationTestRun,
FreightRpaSource,
FreightRpaOnhandValidationBatch,
)
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
batch = FreightRpaOnhandValidationBatch(batch_no='CONFIG-BATCH-ENV-TEST', status='running', total_count=1)
db.session.add(batch)
db.session.flush()
run = FreightRpaOnhandConfigurationTestRun(
run_no='CONFIG-ENV-TEST-RUN', validation_batch_id=batch.id, source_id=source.id,
source_config_version=source.config_version,
rpa_profile_config_version=source.rpa_profile.config_version,
status='completed', stage='current_profile_verified', result_json={},
completed_at=datetime.utcnow(),
)
db.session.add(run)
db.session.commit()
return {'batch_id': batch.id, 'run_no': run.run_no}
def test_heartbeat_requires_auth(client, app):
"""heartbeat 走新路由且鉴权必备:无 Header 必须 401,绝不能匿名写心跳。"""
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY
assert client.post("/api/freight-rpa/heartbeat", json={}).status_code == 401
def test_legacy_rpa_routes_removed(client):
"""旧路由已死(无兼容层,脏回调显式 404):旧 URL 不得再被任何蓝图接住。"""
assert client.post("/api/shipping-notice" + "/rpa/heartbeat", json={}).status_code == 404
def test_onhand_ready_registered_sink_returns_tool_envelope(client, tool_auth_headers):
"""Task 9 注册 sink 后 onhand-ready 可达:空载荷走业务失败分支,envelope 与旧
/rpa/inventory-ready 的裸 tool_response dict 逐字一致(status/message/data 顶层键)。"""
resp = client.post("/api/freight-rpa/onhand-ready", json={}, headers=tool_auth_headers)
assert resp.status_code == 200
body = resp.get_json()
# [断言意图] 旧端点 = jsonify(rpa_report_inventory(payload)),tool_response 顶层键固定为
# status/message/data;失败文案必须保留旧值「未找到任务编号」。
assert set(body) == {"status", "message", "data"}
assert body["status"] == "failed"
assert body["message"] == "未找到任务编号"
assert body["data"] == {}
def test_unauthenticated_sink_endpoint_is_401_not_404(client, app):
"""鉴权先于分发:未携带 key 打 sink 端点是 401(未授权),不能泄漏 404 分发语义。"""
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY
assert client.post("/api/freight-rpa/onhand-ready", json={}).status_code == 401
# ---------------------------------------------------------------------------
# Task 9 envelope 逐 kind 契约:以 git HEAD 旧端点实现为基准写死期望 shape。
# ---------------------------------------------------------------------------
def test_onhand_batch_ready_envelope_matches_legacy(client, tool_auth_headers):
"""onhand-batch-ready(旧 /rpa/inventory-batch-ready = jsonify(rpa_report_inventory(...))):
裸业务 dict;schema 非法分支 data 内 transport_status/business_status/error_code 三键。"""
resp = client.post("/api/freight-rpa/onhand-batch-ready", json={}, headers=tool_auth_headers)
assert resp.status_code == 200
body = resp.get_json()
assert set(body) == {"status", "message", "data"}
assert body["status"] == "failed"
assert body["message"] == "callback_schema_invalid"
assert body["data"] == {
"transport_status": "invalid",
"business_status": "rejected",
"error_code": "callback_schema_invalid",
}
def test_onhand_batch_claimed_envelope_matches_legacy(client, tool_auth_headers):
"""onhand-batch-claimed(旧 /rpa/inventory-batch-claimed):
envelope = {'success': True, 'data': claim_inventory_batch(payload)},禁止裸 dict。"""
resp = client.post("/api/freight-rpa/onhand-batch-claimed", json={}, headers=tool_auth_headers)
assert resp.status_code == 200
body = resp.get_json()
# [断言意图] 旧端点包裹 {'success': True, 'data': ...};schema 非法时业务层返回三键拒绝体。
assert set(body) == {"success", "data"}
assert body["success"] is True
assert body["data"] == {
"transport_status": "invalid",
"business_status": "rejected",
"error_code": "callback_schema_invalid",
}
def test_onhand_batch_progress_envelope_matches_legacy(client, tool_auth_headers):
"""onhand-batch-progress(旧 /rpa/inventory-batch-progress):
裸业务 dict;schema 非法分支 data.progress_status='invalid'。"""
resp = client.post("/api/freight-rpa/onhand-batch-progress", json={}, headers=tool_auth_headers)
assert resp.status_code == 200
body = resp.get_json()
assert set(body) == {"status", "message", "data"}
assert body["status"] == "failed"
assert body["message"] == "callback_schema_invalid"
assert body["data"] == {
"progress_status": "invalid",
"error_code": "callback_schema_invalid",
}
def test_onhand_configuration_test_start_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run):
"""onhand-configuration-test-start(旧 /rpa/inventory-configuration-test-batch-progress =
report_batch_test_progress):envelope = {'status':'ok','data':测试运行投影}。"""
resp = client.post(
"/api/freight-rpa/onhand-configuration-test-start",
json={
'validation_batch_id': terminal_configuration_test_run['batch_id'],
'validation_run_no': terminal_configuration_test_run['run_no'],
},
headers=tool_auth_headers,
)
assert resp.status_code == 200
body = resp.get_json()
# [断言意图] 旧端点 = jsonify({'status':'ok','data': report_batch_test_progress(...)});
# 终态 run 早退分支返回 _payload(run)(含 id/run_no/status)。
assert set(body) == {"status", "data"}
assert body["status"] == "ok"
assert body["data"]["run_no"] == terminal_configuration_test_run['run_no']
assert body["data"]["status"] == "completed"
def test_onhand_configuration_test_analyze_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run):
"""onhand-configuration-test-analyze(旧 /rpa/inventory-configuration-test-ready =
report_test_export):envelope = {'status':'ok','data':测试运行投影}。"""
resp = client.post(
"/api/freight-rpa/onhand-configuration-test-analyze",
json={'run_no': terminal_configuration_test_run['run_no']},
headers=tool_auth_headers,
)
assert resp.status_code == 200
body = resp.get_json()
assert set(body) == {"status", "data"}
assert body["status"] == "ok"
assert body["data"]["run_no"] == terminal_configuration_test_run['run_no']
def test_onhand_configuration_test_complete_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run):
"""onhand-configuration-test-complete(旧 /rpa/inventory-configuration-test-batch-ready =
report_batch_test_exports):envelope = {'status':'ok','data':批次投影+updated/ignored 计数}。"""
resp = client.post(
"/api/freight-rpa/onhand-configuration-test-complete",
json={'validation_batch_id': terminal_configuration_test_run['batch_id'], 'results': []},
headers=tool_auth_headers,
)
assert resp.status_code == 200
body = resp.get_json()
assert set(body) == {"status", "data"}
assert body["status"] == "ok"
assert body["data"]["updated_count"] == 0
assert body["data"]["ignored_count"] == 0
assert body["data"]["batch_no"] == "CONFIG-BATCH-ENV-TEST"
def test_onhand_repair_envelope_matches_legacy(client, tool_auth_headers):
"""onhand-repair(旧 /rpa/inventory-repair = repair=True 后 jsonify(rpa_report_inventory(...))):
裸业务 dict,schema 非法分支与 batch-ready 同形。"""
resp = client.post("/api/freight-rpa/onhand-repair", json={}, headers=tool_auth_headers)
assert resp.status_code == 200
body = resp.get_json()
assert set(body) == {"status", "message", "data"}
assert body["status"] == "failed"
assert body["data"] == {
"transport_status": "invalid",
"business_status": "rejected",
"error_code": "callback_schema_invalid",
}
# ---------------------------------------------------------------------------
# Task 10 inbound sink 注册后契约:三端点改 dispatch_sink 后 envelope 与拆分前直连
# 形态(jsonify({'success': True, 'data': 业务结果}))逐字一致,禁止裸 dict / 统一 envelope。
# ---------------------------------------------------------------------------
def test_inbound_unit_progress_envelope_matches_legacy(client, tool_auth_headers):
"""inbound-unit-progress(旧直连 jsonify({'success':True,'data':mark_inbound_unit_processing(p)})):
schema 非法分支 data={'updated':False,'reason':'callback_schema_invalid'},证明 sink 已注册
(未注册会是 404 FREIGHT_RPA.SINK_NOT_REGISTERED)且 envelope 未漂移。"""
resp = client.post("/api/freight-rpa/inbound-unit-progress", json={}, headers=tool_auth_headers)
assert resp.status_code == 200
body = resp.get_json()
assert set(body) == {"success", "data"}
assert body["success"] is True
assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"}
def test_inbound_batch_progress_envelope_matches_legacy(client, tool_auth_headers):
"""inbound-batch-progress(旧直连同款 envelope):schema 非法分支与 unit-progress 同形。"""
resp = client.post("/api/freight-rpa/inbound-batch-progress", json={}, headers=tool_auth_headers)
assert resp.status_code == 200
body = resp.get_json()
assert set(body) == {"success", "data"}
assert body["success"] is True
assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"}
def test_inbound_batch_ready_schema_invalid_reaches_business_validation(client, tool_auth_headers):
"""inbound-batch-ready sink 已注册:schema 非法穿透到业务校验(400 +
SHIPPING.INBOUND_CALLBACK_INVALID),而非未注册 404;错误 envelope 与拆分前同形
(旧端点在 jsonify 之前由 ingest 抛 ValidationError → 全局 AppError handler)。"""
resp = client.post("/api/freight-rpa/inbound-batch-ready", json={}, headers=tool_auth_headers)
assert resp.status_code == 400
body = resp.get_json()
assert body["success"] is False
assert body["error"]["code"] == "SHIPPING.INBOUND_CALLBACK_INVALID"
def test_inbound_batch_ready_unknown_unit_is_404(client, tool_auth_headers):
"""inbound-batch-ready 未知 callback_id:404 + SHIPPING.INBOUND_UNIT_NOT_FOUND,
与拆分前 ingest 直连时的 NotFoundError 路径逐字一致。"""
resp = client.post(
"/api/freight-rpa/inbound-batch-ready",
json={"schema_version": "freight_rpa.inbound.v1", "callback_id": "no-such-callback"},
headers=tool_auth_headers,
)
assert resp.status_code == 404
body = resp.get_json()
assert body["error"]["code"] == "SHIPPING.INBOUND_UNIT_NOT_FOUND"
@pytest.mark.pure_unit
def test_dispatch_sink_unregistered_raises_app_error():
"""注册表单测:未注册 kind 抛 AppError(404, FREIGHT_RPA.SINK_NOT_REGISTERED),不静默吞回调。"""
from app.core.errors import AppError
from app.services.freight_rpa.common.callback_sinks import dispatch_sink, register_sink
seen: dict[str, object] = {}
def _handler(**payload):
seen.update(payload)
return {'ok': True}
register_sink('unit-test-kind', _handler)
assert dispatch_sink('unit-test-kind', callback_id='cb-1') == {'ok': True}
assert seen == {'callback_id': 'cb-1'}
with pytest.raises(AppError) as excinfo:
dispatch_sink('never-registered-kind', callback_id='cb-2')
assert excinfo.value.code == 'FREIGHT_RPA.SINK_NOT_REGISTERED'
assert excinfo.value.http_status == 404
def test_admin_rpa_profiles_routes_migrated(app, client):
"""admin rpa-profiles 已迁 /api/admin/freight-rpa/*:管理员可达、旧 URL 404、普通用户 403。"""
from app import db
from app.models import User
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
db.session.add_all([
User(username='rpa-admin', email='rpa-admin@example.com', role='admin', status='active'),
User(username='rpa-user', email='rpa-user@example.com', role='user', status='active'),
])
db.session.commit()
admin_headers = {'X-Username': 'rpa-admin', 'X-Role': 'admin'}
user_headers = {'X-Username': 'rpa-user', 'X-Role': 'user'}
migrated = client.get('/api/admin/freight-rpa/rpa-profiles', headers=admin_headers)
assert migrated.status_code == 200
assert migrated.get_json()['success'] is True
# [断言意图] 普通用户必须被 require_admin 拦截(迁移未放松权限)。
assert client.get('/api/admin/freight-rpa/rpa-profiles', headers=user_headers).status_code == 403
# [断言意图] 旧 admin URL 无双路由:脏调用显式 404(前端已同窗口切换)。
assert client.get('/api/admin/shipping-notice/rpa-profiles', headers=admin_headers).status_code == 404
File diff suppressed because it is too large. Load diff
+336
View File
@@ -0,0 +1,336 @@
"""调拨类型 API 契约测试(admin CRUD + chat 最小暴露列表 + 四语言错误码)。
用途:锁定调拨类型配置两个 API 入口的外部契约——admin 列表/创建/更新
(平台管理员、重复 code 与并发唯一键冲突统一 422、code 不可变 422、
enabled/sort_order 参数形态门禁),chat GET /transfer-types(仅启用、
最小暴露、Agent 权限即可不要求平台管理员),以及四语言 errors.json
与后端稳定错误码同 key 集。
依赖:app/client 夹具、issue_local_access_token、transfer_type_config_service
(前置数据走服务层唯一写入入口)。
逻辑:服务层校验契约由 test_transfer_type_config_service.py 覆盖,本文件只测
API 壳(鉴权/状态码映射/序列化暴露面/i18n 文案登记)。
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from sqlalchemy.exc import IntegrityError
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import Agent, User
from app.services.in_transit_transfer.transfer_type_config_service import (
create_config as create_type_config,
)
ADMIN_PREFIX = "/api/admin/in-transit-transfer/transfer-types"
CHAT_PREFIX = "/api/in-transit-transfer/transfer-types"
# 四语言 errors.json 必须与后端稳定错误码保持同 key 集(前端文案映射契约)。
EXPECTED_ERROR_KEYS = (
"TRANSFER.TRANSFER_TYPE_REQUIRED",
"TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED",
"TRANSFER.TRANSFER_TYPE_DISABLED",
"TRANSFER.TRANSFER_TYPE_CODE_EXISTS",
"TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE",
"TRANSFER.SCOPE_RULE_INVALID",
"TRANSFER.WAREHOUSE_CONFIG_INVALID",
"TRANSFER.TRANSFORM_RULE_INVALID",
)
# [FIXTURE] 合法创建载荷基线(与 test_transfer_type_config_service.VALID_PAYLOAD 同构)。
VALID_PAYLOAD = {
"code": "in_transit_to_hub",
"names": {"zh-CN": "在途仓至HUB仓", "en": "In-transit to Hub"},
"enabled": True,
"sort_order": 10,
"scope_rules": [
{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]},
],
"warehouse_config": {
"from": {"mode": "mapped"},
"to": {"mode": "mapped"},
},
"transform_rules": [
{"field": "lot_no", "op": "prefix_replace", "source": "wtp", "target": "HOW"},
],
"description": "一期默认类型",
}
def _headers(user: User) -> dict:
"""为指定用户签发 Bearer JWT 请求头(须在 app context 内调用)。"""
token = issue_local_access_token(user)
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
def _seed_type(**overrides) -> None:
"""按基线载荷落一个类型配置(API 测试前置数据,走服务层唯一写入入口)。"""
create_type_config({**VALID_PAYLOAD, **overrides})
@pytest.fixture
def admin_headers(app):
"""平台管理员 JWT 请求头(token 在 app context 内签发)。"""
with app.app_context():
user = db.session.query(User).filter_by(username="admin").first()
if not user:
user = User(username="admin", email="admin@example.com", role="admin", status="active")
user.set_password("admin")
db.session.add(user)
db.session.commit()
return _headers(user)
@pytest.fixture
def warehouse_headers(app):
"""持有 in_transit_transfer Agent 权限的仓库管理员 JWT 请求头(非平台管理员)。"""
with app.app_context():
agent = Agent.query.filter_by(agent_code="in_transit_transfer").first()
if not agent:
agent = Agent(name="在途仓调拨", agent_code="in_transit_transfer",
type="api", is_active=True)
db.session.add(agent)
db.session.flush()
user = db.session.query(User).filter_by(username="warehouse").first()
if not user:
user = User(username="warehouse", email="warehouse@example.com",
role="user", status="active")
user.set_password("x")
db.session.add(user)
db.session.flush()
if agent not in user.agents:
user.agents.append(agent)
db.session.commit()
return _headers(user)
@pytest.fixture
def unauthorized_headers(app):
"""已认证但无 Agent 权限的普通用户 JWT 请求头。"""
with app.app_context():
user = db.session.query(User).filter_by(username="no_perm").first()
if not user:
user = User(username="no_perm", email="no_perm@example.com", role="user", status="active")
user.set_password("x")
db.session.add(user)
db.session.commit()
return _headers(user)
# ---------------------------------------------------------------------------
# admin CRUD(平台管理员)
# ---------------------------------------------------------------------------
def test_admin_create_returns_201_with_normalized_config(app, client, admin_headers):
"""POST 创建 → 201 envelope;三块配置经服务层规范化后回读(transform 大写化)。"""
response = client.post(ADMIN_PREFIX, headers=admin_headers, json=VALID_PAYLOAD)
assert response.status_code == 201
body = response.get_json()
assert body["success"] is True
assert body.get("request_id")
data = body["data"]
assert data["code"] == "in_transit_to_hub"
assert data["names"]["zh-CN"] == "在途仓至HUB仓"
assert data["enabled"] is True
assert data["sort_order"] == 10
# [断言意图] scope_rules/transform_rules 是引擎规范化产物(source/target 统一大写),
# 前端编辑表单依赖该形态回显,形态漂移必须显式同步。
assert data["scope_rules"] == [
{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]},
]
assert data["transform_rules"] == [
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
]
assert data["warehouse_config"]["from"]["mode"] == "mapped"
assert data["description"] == "一期默认类型"
assert data["updated_at"].endswith("Z")
def test_admin_list_returns_configs_including_disabled(app, client, admin_headers):
"""GET 列表 → 全量配置(含停用项),sort_order 升序;管理端可见三块配置。"""
_seed_type(sort_order=20)
_seed_type(code="hub_to_line", enabled=False, sort_order=10, description="停用类型")
response = client.get(ADMIN_PREFIX, headers=admin_headers)
assert response.status_code == 200
body = response.get_json()
assert body["success"] is True
data = body["data"]
assert [item["code"] for item in data] == ["hub_to_line", "in_transit_to_hub"]
assert {item["enabled"] for item in data} == {True, False}
# [断言意图] 管理列表是全量视图(与 chat 最小暴露相对):三块配置均必须可见。
for key in ("scope_rules", "warehouse_config", "transform_rules", "description"):
assert key in data[0]
def test_admin_update_partial_keeps_other_fields(app, client, admin_headers):
"""PUT 部分更新:提供的字段生效,未提供的字段保持原值。"""
_seed_type()
response = client.put(
f"{ADMIN_PREFIX}/in_transit_to_hub", headers=admin_headers,
json={"enabled": False, "sort_order": 5},
)
assert response.status_code == 200
data = response.get_json()["data"]
assert data["enabled"] is False
assert data["sort_order"] == 5
assert data["description"] == "一期默认类型"
def test_admin_requires_platform_admin(app, client, unauthorized_headers):
"""admin 端点:已认证但非平台管理员 → 403。"""
response = client.get(ADMIN_PREFIX, headers=unauthorized_headers)
assert response.status_code == 403
assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN"
def test_admin_create_duplicate_code_maps_422(app, client, admin_headers):
"""重复 code → 422 + TRANSFER.TRANSFER_TYPE_CODE_EXISTS(服务层预检路径)。"""
client.post(ADMIN_PREFIX, headers=admin_headers, json=VALID_PAYLOAD)
response = client.post(ADMIN_PREFIX, headers=admin_headers, json=VALID_PAYLOAD)
assert response.status_code == 422
assert response.get_json()["error"]["code"] == "TRANSFER.TRANSFER_TYPE_CODE_EXISTS"
def test_admin_create_concurrent_integrity_error_maps_422(
app, client, admin_headers, monkeypatch,
):
"""并发兜底:预检通过后唯一键仍冲突(IntegrityError)→ 422 而非 500。"""
def _raise(payload, operator_id=None):
raise IntegrityError("INSERT INTO transfer_type_configs", {}, Exception("UNIQUE constraint failed"))
monkeypatch.setattr("app.api.admin.transfer_type.service.create_config", _raise)
response = client.post(ADMIN_PREFIX, headers=admin_headers, json=VALID_PAYLOAD)
assert response.status_code == 422
assert response.get_json()["error"]["code"] == "TRANSFER.TRANSFER_TYPE_CODE_EXISTS"
def test_admin_update_code_immutable_maps_422(app, client, admin_headers):
"""改 code(transfer_runs.transfer_type 引用其改名即断链)→ 422 + CODE_IMMUTABLE。"""
_seed_type()
response = client.put(
f"{ADMIN_PREFIX}/in_transit_to_hub", headers=admin_headers,
json={"code": "renamed_type"},
)
assert response.status_code == 422
assert response.get_json()["error"]["code"] == "TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE"
def test_admin_update_unknown_code_maps_404(app, client, admin_headers):
"""更新不存在的 code → 404 + TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED。"""
response = client.put(f"{ADMIN_PREFIX}/no_such_type", headers=admin_headers, json={"enabled": True})
assert response.status_code == 404
assert response.get_json()["error"]["code"] == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
def test_admin_create_rejects_string_enabled(app, client, admin_headers):
"""API 层类型门禁:字符串 "false" 不得直通服务层被 bool() 强转为真值。"""
response = client.post(ADMIN_PREFIX, headers=admin_headers, json={**VALID_PAYLOAD, "enabled": "false"})
assert response.status_code == 400
assert response.get_json()["error"]["code"] == "VALIDATION.INVALID_PARAM"
def test_admin_create_rejects_string_sort_order(app, client, admin_headers):
"""API 层类型门禁:sort_order 只接受整数,数字字符串拒绝。"""
response = client.post(ADMIN_PREFIX, headers=admin_headers, json={**VALID_PAYLOAD, "sort_order": "10"})
assert response.status_code == 400
assert response.get_json()["error"]["code"] == "VALIDATION.INVALID_PARAM"
def test_admin_update_rejects_string_enabled(app, client, admin_headers):
"""API 层类型门禁同样作用于更新路径。"""
_seed_type()
response = client.put(
f"{ADMIN_PREFIX}/in_transit_to_hub", headers=admin_headers, json={"enabled": "true"},
)
assert response.status_code == 400
assert response.get_json()["error"]["code"] == "VALIDATION.INVALID_PARAM"
def test_admin_create_rejects_non_object_body(app, client, admin_headers):
"""body 为非对象 JSON(如数组)→ 400 参数错误,而非 500。"""
response = client.post(ADMIN_PREFIX, headers=admin_headers, json=["in_transit_to_hub"])
assert response.status_code == 400
assert response.get_json()["success"] is False
# ---------------------------------------------------------------------------
# chat 列表(Agent 权限,最小暴露)
# ---------------------------------------------------------------------------
def test_chat_transfer_types_returns_enabled_only_with_minimal_fields(
app, client, warehouse_headers,
):
"""chat 列表:仅启用项、sort_order 升序、最小暴露,并附推导出的 record_kinds。"""
_seed_type(sort_order=20)
_seed_type(
code="hub_to_line",
sort_order=10,
scope_rules=[{"field": "record_kind", "match": "equals", "values": ["inbound"]}],
)
_seed_type(code="disabled_type", enabled=False, sort_order=1)
response = client.get(CHAT_PREFIX, headers=warehouse_headers)
assert response.status_code == 200
body = response.get_json()
assert body["success"] is True
data = body["data"]
# [断言意图] 仅 enabled 限定 + sort_order 升序是前端类型选择器的顺序契约。
assert [item["code"] for item in data] == ["hub_to_line", "in_transit_to_hub"]
for item in data:
# [断言意图] 最小暴露:在原四键上只增加 record_kinds。scope_rules /
# warehouse_config / description 仍不回传。record_kinds 由
# record_kinds_of 现算:hub_to_line 只写 inbound,另一条没有
# 记录类型规则所以入站和出站都要。
assert set(item.keys()) == {
"code", "names", "sort_order", "transform_rules", "record_kinds",
}
assert data[0]["record_kinds"] == ["inbound"]
assert data[1]["record_kinds"] == ["inbound", "outbound"]
assert data[0]["transform_rules"] == [
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
]
def test_chat_transfer_types_agent_permission_sufficient(app, client, warehouse_headers):
"""chat 列表不要求平台管理员:持有 in_transit_transfer Agent 权限即可。"""
_seed_type()
response = client.get(CHAT_PREFIX, headers=warehouse_headers)
assert response.status_code == 200
assert len(response.get_json()["data"]) == 1
def test_chat_transfer_types_requires_authentication(client):
"""未认证 → 401。"""
response = client.get(CHAT_PREFIX)
assert response.status_code == 401
assert response.get_json()["success"] is False
def test_chat_transfer_types_forbidden_without_permission(client, unauthorized_headers):
"""已认证但无 Agent 权限 → 403。"""
response = client.get(CHAT_PREFIX, headers=unauthorized_headers)
assert response.status_code == 403
assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN"
# ---------------------------------------------------------------------------
# 四语言 errors.json 文案登记
# ---------------------------------------------------------------------------
def test_error_codes_present_in_all_locales():
"""四语言 errors.json 与后端稳定错误码同 key 集且文案非空。"""
repo_root = Path(__file__).resolve().parents[3]
for locale in ("zh-CN", "zh-TW", "en", "th"):
path = repo_root / "frontend" / "src" / "locales" / locale / "errors.json"
assert path.exists(), f"missing errors.json: {locale}"
codes = json.loads(path.read_text(encoding="utf-8"))["codes"]
for key in EXPECTED_ERROR_KEYS:
assert key in codes, f"{locale} missing {key}"
assert isinstance(codes[key], str) and codes[key].strip(), f"{locale}:{key} has empty copy"
+67 -55
View File
@@ -90,19 +90,19 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
)
if request.node.get_closest_marker("auto_rpa"):
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
"app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None,
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_freight_upload_rpa_ready",
"app.services.freight_rpa.common.worker_heartbeat.assert_freight_upload_rpa_ready",
lambda: None,
)
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_RPA_ONHAND_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
# 货代自动上传默认 fail-closed;单测与产品默认一致关闭。
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
@@ -111,10 +111,10 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
from app.services.freight_rpa.common.worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
reset_rpa_worker_heartbeat_state_for_tests()
from app.services.shipping_notice.rpa_worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests
from app.services.freight_rpa.common.worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests
reset_rpa_worker_alert_state_for_tests()
@@ -123,9 +123,9 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
def _shipping_test_default_destination(monkeypatch, request):
"""
为未提供目的地线索的发货通知单测注入 Dublin,以唯一命中 DSV360_AWSDU。
标记 inventory_source_gate 的用例跳过,避免干扰库存源门禁专项测试。
标记 onhand_source_gate 的用例跳过,避免干扰库存源门禁专项测试。
"""
if request.node.get_closest_marker("inventory_source_gate"):
if request.node.get_closest_marker("onhand_source_gate"):
return
from app.services.shipping_notice import extract as extract_mod
@@ -170,9 +170,9 @@ def seed_task_inventory_source(
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
if owner is None:
raise ValueError('test task must be linked to ShippingOrderTask')
from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_candidates_for_task
from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication
from app.services.shipping_notice.inventory_source_repository import (
from app.services.shipping_notice.onhand_candidate_freeze_service import freeze_candidates_for_task
from app.services.shipping_notice.onhand_source_rules import InventorySourceAdjudication
from app.services.shipping_notice.onhand_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
@@ -391,7 +391,7 @@ def seed_rpa_inventory_trigger(
run_no: str = "RUN-TEST-001",
trigger_path: str | None = None,
) -> None:
"""测试辅助:写入 inventory_rpa_triggered 事件,供单任务回调 run_no 校验。"""
"""测试辅助:写入 onhand_rpa_triggered 事件,供单任务回调 run_no 校验。"""
from app import db
from app.services.shipping_notice.tool_common import log_task_event
@@ -401,7 +401,7 @@ def seed_rpa_inventory_trigger(
trigger = trigger_path or f"inventory_export_batch_{run_no}.json"
log_task_event(
task,
"inventory_rpa_triggered",
"onhand_rpa_triggered",
{"trigger": trigger, "run_no": run_no, "attempt": 1, "manual_retry_round": False},
)
@@ -448,10 +448,10 @@ def inventory_csv_with_warehouse(
def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]:
"""构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。"""
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
source_code = next(iter(task_frozen_onhand_source_codes(task)), '')
source = get_database_inventory_source(source_code) or {}
return {
"source_code": str(source_code or ""),
@@ -461,7 +461,7 @@ def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]:
def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
"""构造定时 batch 成功回调 item 的 Source/Warehouse 身份(与数据库配置一致)。"""
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
source = get_database_inventory_source(source_code)
if not source:
@@ -475,10 +475,10 @@ def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
def v2_inventory_batch_payload(payload: dict) -> dict:
"""测试构造器:补齐冻结 shipping_inventory_rpa.v2 回调 envelope。"""
"""测试构造器:补齐冻结 freight_rpa.onhand.v1 回调 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('schema_version', 'freight_rpa.onhand.v1')
body.setdefault('callback_id', f'test-callback:{run_no or "unknown"}')
body.setdefault('batch_run_no', run_no)
return body
@@ -492,13 +492,13 @@ def rpa_callback_payload(
status: str = "success",
) -> dict:
"""构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。"""
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.onhand_source_repository import get_database_inventory_source
from app.services.shipping_notice.stp_onhand_freeze import task_frozen_onhand_source_codes
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
source_code = next(iter(task_frozen_onhand_source_codes(task)), '')
source = get_database_inventory_source(source_code) or {}
return {
"schema_version": "shipping_inventory_rpa.v2",
"schema_version": "freight_rpa.onhand.v1",
"callback_id": f"test-callback:{run_no}",
"task_id": task.task_no,
"status": status,
@@ -528,7 +528,7 @@ def pytest_configure(config):
)
config.addinivalue_line(
"markers",
"inventory_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
"onhand_source_gate: 库存源门禁专项测试,跳过默认 Dublin 注入",
)
config.addinivalue_line(
"markers",
@@ -572,13 +572,17 @@ def app():
def _seed_test_inventory_configuration() -> None:
"""为发货测试创建数据库库存源与发布路由规则,测试运行期不读取 YAML。"""
"""为发货测试创建数据库库存源、在手报表配置与发布路由规则,测试运行期不读取 YAML。
s18 起:报表路径/查询条件/解析方案挂在 FreightRpaOnhandReportConfig 上,
站点行只剩连接、模板绑定与启停。
"""
from app import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource,
ShippingRpaProfile,
ShippingExcelTemplate, FreightRpaOnhandField, FreightRpaOnhandReportConfig,
FreightRpaParsingProfile, FreightRpaSource, FreightRpaProfile,
)
from app.services.shipping_notice.inventory_structure_fingerprint import (
from app.services.shipping_notice.onhand_structure_fingerprint import (
FINGERPRINT_VERSION,
compatibility_fingerprint,
exact_fingerprint,
@@ -586,24 +590,24 @@ def _seed_test_inventory_configuration() -> None:
)
# 各测试显式创建所需用户字段;生产目录本身保持零预置。
if not ShippingInventoryField.query.filter_by(field_code='part_number').first():
if not FreightRpaOnhandField.query.filter_by(field_code='part_number').first():
db.session.add_all([
ShippingInventoryField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10),
ShippingInventoryField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20),
ShippingInventoryField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30),
ShippingInventoryField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40),
ShippingInventoryField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100),
ShippingInventoryField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110),
ShippingInventoryField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120),
ShippingInventoryField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130),
ShippingInventoryField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140),
FreightRpaOnhandField(field_code='part_number', display_name='内部料号', value_type='text', usage_type='match_identity', status='active', sort_order=10),
FreightRpaOnhandField(field_code='reservation_id', display_name='预约号', value_type='text', usage_type='match_identity', status='active', sort_order=20),
FreightRpaOnhandField(field_code='available_qty', display_name='可用库存数量', value_type='decimal', usage_type='inventory_quantity', status='active', sort_order=30),
FreightRpaOnhandField(field_code='warehouse_id', display_name='仓库标识', value_type='text', usage_type='warehouse_identity', status='active', sort_order=40),
FreightRpaOnhandField(field_code='aws_part_number', display_name='AWS 料号', value_type='text', usage_type='general', status='active', sort_order=100),
FreightRpaOnhandField(field_code='odm_id', display_name='ODM 编号', value_type='text', usage_type='general', status='active', sort_order=110),
FreightRpaOnhandField(field_code='warehouse_code', display_name='仓库编码', value_type='text', usage_type='general', status='active', sort_order=120),
FreightRpaOnhandField(field_code='lot_no', display_name='批次号', value_type='text', usage_type='general', status='active', sort_order=130),
FreightRpaOnhandField(field_code='location', display_name='库位', value_type='text', usage_type='general', status='active', sort_order=140),
])
db.session.flush()
inventory_fields = {
item.field_code: item
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_([
for item in FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.field_code.in_([
'part_number', 'reservation_id', 'available_qty', 'warehouse_id',
])
).all()
@@ -641,7 +645,7 @@ def _seed_test_inventory_configuration() -> None:
checksum = hashlib.sha256(
json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
).hexdigest()
parsing_profile = ShippingInventoryParsingProfile(
parsing_profile = FreightRpaParsingProfile(
profile_code='TEST_RUNTIME', display_name='Test Runtime', version=1, status='published',
file_format='xlsx', definition_json=definition, checksum=checksum,
structure_definition_json=structure,
@@ -658,14 +662,20 @@ def _seed_test_inventory_configuration() -> None:
file_checksum='0' * 64, definition_json={}, definition_checksum='0' * 64,
)
profile = ShippingRpaProfile(
profile = FreightRpaProfile(
profile_code='DBS_DUB_TEST', display_name='DBS Dublin', connector_type='dbs',
login_url='https://test.invalid/dbs', login_config_json={'auth_mode': 'password'},
)
source = ShippingInventorySource(
source = FreightRpaSource(
source_code='DSV360_AWSDU', display_name='DBS Dublin AWSDU', connector_type='dbs',
rpa_profile=profile, parsing_profile=parsing_profile, excel_template=excel_template,
rpa_profile=profile, excel_template=excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU',
enabled=True,
)
# s18 起报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig,站点行不再承载。
report_config = FreightRpaOnhandReportConfig(
source=source,
parsing_profile=parsing_profile,
report_path_json={
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
@@ -673,9 +683,8 @@ def _seed_test_inventory_configuration() -> None:
query_parameters_json=[
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': True, 'select_all': False},
],
enabled=True,
)
db.session.add_all([profile, parsing_profile, excel_template, source])
db.session.add_all([profile, parsing_profile, excel_template, source, report_config])
db.session.commit()
@@ -691,11 +700,13 @@ def dbs_ready_file() -> dict:
rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date),
与真实仓库 movement_file_repository 产出一致(B5 接线后 run_matching 按
parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。
【T−2 成熟封顶 2026-10-21】rows 异动日期取 2026-08-04(= 业务日 08-06 的
T−2 恰好成熟边界);更晚日期(T−1/当天)已被圈档封顶排除,不得再作夹具日期。
"""
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-001",
"file_version": "v3",
"checksum": "d" * 64,
@@ -703,13 +714,13 @@ def dbs_ready_file() -> dict:
"rows": [
{"sheet": "Receipt", "row_no": 10, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "500", "unit": "个", "source_code": "DBS-AWSBI"},
"movement_date": "2026-08-04", "quantity": "500", "unit": "个", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 11, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "700", "unit": "个", "source_code": "DBS-AWSBI"},
"movement_date": "2026-08-04", "quantity": "700", "unit": "个", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 20, "doc_no": "HOX-002", "lot_no": "LOT-20", "material_code": "MAT-002",
"material_name": "控制器组件", "specification": "标准型 / 48V",
"movement_date": "2026-08-05", "quantity": "1200", "unit": "PCS", "source_code": "DBS-AWSBI"},
"movement_date": "2026-08-04", "quantity": "1200", "unit": "PCS", "source_code": "DBS-AWSBI"},
],
}
@@ -719,11 +730,12 @@ def crane_ready_file() -> dict:
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
异动日期=T−2 成熟边界(见 dbs_ready_file 注释)。
"""
return {
"source_code": "CRANE-SZ",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-002",
"file_version": "v4",
"checksum": "c" * 64,
@@ -731,21 +743,21 @@ def crane_ready_file() -> dict:
"rows": [
{"sheet": "Inbound", "row_no": 5, "doc_no": "WTP-008", "lot_no": "LOT-8", "material_code": "MAT-200",
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
"movement_date": "2026-08-05", "quantity": "600", "unit": "PCS", "source_code": "CRANE-SZ"},
"movement_date": "2026-08-04", "quantity": "600", "unit": "PCS", "source_code": "CRANE-SZ"},
],
}
@pytest.fixture
def same_day_receipt_file() -> dict:
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。
def same_day_inbound_file() -> dict:
"""含业务日期当天异动数据的文件(T−2 成熟封顶 2026-10-21:当天未成熟不匹配)。
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
"""
return {
"source_code": "DBS-AWSSG",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-003",
"file_version": "v2",
"checksum": "s" * 64,
@@ -19,6 +19,14 @@ from app.services.in_transit_transfer.matching_service import create_matching
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
@pytest.fixture(autouse=True)
def _seed_transfer_type(app):
"""类型配置化(Task 11/D8):Job 域用例预置默认启用类型(匹配创建必填)。"""
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
seed_transfer_type_config()
@pytest.fixture
def transfer_deps(app, monkeypatch, dbs_ready_file):
"""注入 Fake 依赖并预置库存;同时把执行文件对账投影替换为 ready(sha=夹具 checksum)。
@@ -32,8 +40,9 @@ def transfer_deps(app, monkeypatch, dbs_ready_file):
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
def _resolve(*, source_code: str) -> dict:
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
# 执行门禁②(文件版本对账)替身:来源恒 ready 且 sha 与夹具行版本戳同源。
del record_kind
return {"file_status": "ready", "has_ready_file": True, "file_no": "REC-TEST", "file_sha256": "d" * 64}
monkeypatch.setattr(
@@ -61,7 +70,7 @@ def test_matching_job_type_registered():
def test_matching_job_handler_runs_and_updates_matching(transfer_db, dbs_ready_file, transfer_deps):
"""handler 执行后匹配状态进入 ready_to_execute,明细落库。"""
summary = create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, transfer_type="in_transit_to_hub"
)
handler = get_handler(JobType.TRANSFER_MATCH)
handler(None, {"matching_id": summary.matching_id})
@@ -70,8 +79,8 @@ def test_matching_job_handler_runs_and_updates_matching(transfer_db, dbs_ready_f
assert matching is not None
assert matching.status == "ready_to_execute"
assert matching.matching_hash.startswith("sha256:")
# 2026-09-25 行归属解耦:行由证据同步落地(matching_id=None),匹配卡不再
# 持有行(matching.items 恒空)——明细断言改为按来源圈行。
# 2026-10-14 items 出生翻转:行在匹配创建时从异动档圈行出生(matching_id
# 出生即绑定,D17),证据落地只写档不写行——明细断言按来源圈行验证落地等价。
rows = db.session.query(TransferInvoiceItem).filter_by(source_code="DBS-AWSBI").all()
assert len(rows) == 2
assert all(row.status == "ready_to_execute" for row in rows)
@@ -97,7 +106,7 @@ def test_run_job_handler_executes_run(transfer_db, dbs_ready_file, transfer_deps
from app.services.in_transit_transfer.execution_service import prepare_execution
create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, transfer_type="in_transit_to_hub"
)
from app.models import TransferInvoiceItem
@@ -125,7 +134,7 @@ def test_run_job_handler_missing_run_id_raises(transfer_db):
def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, transfer_deps):
"""item handler 执行单个 Invoice 写入并置 success。"""
create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, transfer_type="in_transit_to_hub"
)
from app.services.in_transit_transfer.execution_service import prepare_execution
@@ -157,7 +166,7 @@ def test_run_job_handler_finishes_job_row(transfer_db, dbs_ready_file, transfer_
from app.services.in_transit_transfer.execution_service import prepare_execution
create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps, transfer_type="in_transit_to_hub"
)
ready_ids = [
item.id for item in TransferInvoiceItem.query.filter_by(status="ready_to_execute").all()
+5 -5
View File
@@ -23,14 +23,14 @@ from app.services.schedule.queue_service import (
def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycle(app, monkeypatch):
"""关键断言:调拨来源等待回调 Job 的超时回收每轮领取都执行,不只在 worker 启动时扫一次。
[STEP 1] 用计数桩替换 receipt_callback_bridge.recover_stale_waiting_source_jobs(queue_service
[STEP 1] 用计数桩替换 inbound_callback_bridge.recover_stale_waiting_source_jobs(queue_service
在函数体内延迟 import,桩生效)并复位 _worker_initialized,隔离模块级启动标记。
[STEP 2] 连续两轮调用真实 prepare_schedule_queue(空库下其余恢复均为 no-op)。
[STEP 3] 第二轮后计数必须为 2:若回收仍挂在启动一次性分支,第二次调用不会触发,计数停留 1。
"""
from app.services.in_transit_transfer import receipt_callback_bridge
from app.services.in_transit_transfer import inbound_callback_bridge
from app.services.schedule import queue_service
from app.services.shipping_notice import rpa_worker_heartbeat_alert
from app.services.freight_rpa.common import worker_heartbeat_alert
calls: list[int] = []
@@ -41,8 +41,8 @@ def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycl
def _fake_heartbeat(**_kwargs):
return {"skipped": True, "reason": "test_stub"}
monkeypatch.setattr(receipt_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
monkeypatch.setattr(rpa_worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
monkeypatch.setattr(inbound_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
monkeypatch.setattr(worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
monkeypatch.setattr(queue_service, "_worker_initialized", False)
assert prepare_schedule_queue() == 0
+2 -2
View File
@@ -68,7 +68,7 @@ def test_claim_next_shipping_claims_inventory_callback_process_job(app):
with app.app_context():
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS.value,
job_type=JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS.value,
status='queued',
payload_json={'callback_id': 'callback-test'},
)
@@ -79,7 +79,7 @@ def test_claim_next_shipping_claims_inventory_callback_process_job(app):
assert claimed is not None
assert claimed['id'] == job.id
assert claimed['job_type'] == JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS
assert claimed['job_type'] == JobType.FREIGHT_RPA_ONHAND_CALLBACK_PROCESS
def test_claim_next_transfer_claims_run_job(app):
@@ -48,10 +48,17 @@ def test_bulk_matching_300_invoices(transfer_db):
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
started = time.perf_counter()
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
elapsed = time.perf_counter() - started
assert summary.counts.executable_count == 300
assert summary.counts.file_invoice_count == 300
restored = restore_matching(summary.matching_id)
assert len(restored["items"]) == 300
print(f"\n[perf] bulk matching 300 invoices: {elapsed:.3f}s")
@pytest.fixture(autouse=True)
def _seed_transfer_type(transfer_db):
"""类型配置化(Task 11/D8):性能用例预置默认启用类型(匹配创建必填)。"""
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
seed_transfer_type_config()
@@ -2,8 +2,8 @@
tests/services/admin/test_shipping_inventory_service.py
用途:验证库存主数据管理服务的安全性和关键业务约束。
依赖:Flask app/db、shipping_inventory_service、库存配置模型。
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
逻辑:管理后台写配置前锁定用户名可回显、密码与密文不回传、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
"""
from __future__ import annotations
@@ -12,16 +12,17 @@ from cryptography.fernet import Fernet
import pytest
from app.core.errors import ConflictError, ValidationError
from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import inventory_parsing_profile
from app.services.admin import freight_rpa_source_admin_service, shipping_onhand_admin_service
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingInventoryField,
ShippingInventorySource,
ShippingInventorySourceParsingBindingAudit,
ShippingInventoryStructureAnalysis,
FreightRpaOnhandField,
FreightRpaSource,
FreightRpaSourceParsingBindingAudit,
FreightRpaOnhandStructureAnalysis,
FreightRpaProfile,
)
@@ -35,7 +36,7 @@ def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict:
def _sample_evidence() -> int:
"""创建最小表头证据,确保库存源服务测试不绕过解析方案样本门禁。"""
item = ShippingInventoryStructureAnalysis(
item = FreightRpaOnhandStructureAnalysis(
source_kind='sample_upload', source_file_name='service-sample.xlsx', storage_path=None,
file_checksum='b' * 64, file_format='xlsx', analysis_status='ready',
structure_json={'candidates': [{
@@ -88,13 +89,13 @@ def _parsing_profile() -> dict:
)
inventory_fields = {
item.field_code: str(item.id)
for item in ShippingInventoryField.query.filter(
ShippingInventoryField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
ShippingInventoryField.status == 'active',
for item in FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.field_code.in_(['part_number', 'reservation_id', 'available_qty']),
FreightRpaOnhandField.status == 'active',
).all()
}
assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'}
draft = inventory_parsing_profile.save_draft({
draft = onhand_parsing_profile.save_draft({
'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx',
'sample_analysis_id': _sample_evidence(),
'definition': {
@@ -110,7 +111,7 @@ def _parsing_profile() -> dict:
}],
},
}, actor_id=None)
return inventory_parsing_profile.publish(draft['id'], actor_id=None)
return onhand_parsing_profile.publish(draft['id'], actor_id=None)
def _excel_template_id() -> int:
@@ -133,17 +134,21 @@ def _excel_template_id() -> int:
def _source_data(profile_id: int, *, parsing_profile_id: int | None = None, code: str = 'DBS_DUB', connector_type: str = 'dbs') -> dict:
return {
'source_code': code, 'display_name': code, 'connector_type': connector_type,
'rpa_profile_id': profile_id, 'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'],
'rpa_profile_id': profile_id,
'excel_template_id': _excel_template_id(),
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB',
'snapshot_ttl_seconds': 3600, 'enabled': True,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
# s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行,站点载荷不再平铺。
'onhand_report_config': {
'parsing_profile_id': parsing_profile_id or _parsing_profile()['id'],
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand Inventory By Location 3lv',
},
'query_parameters_json': [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
],
},
'query_parameters_json': [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
],
}
@@ -156,15 +161,50 @@ def _published_route_field_id() -> str:
)
def test_profile_credentials_are_not_returned(app):
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
def test_profile_returns_username_and_keeps_password_secret(app):
"""Profile 回执返回用户名明文,密码与密文不得出现。相同用户名再次保存不轮换密文。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
# 用户名是账号标识,管理端需要明文辨认;密码只报告已配置。
assert payload['username'] == 'test-user'
assert payload['password_configured'] is True
assert payload['username_masked'] == 'configured'
assert 'password' not in payload
assert 'ciphertext' not in payload
stored = db.session.get(FreightRpaProfile, payload['id'])
original_username = stored.username_ciphertext
original_password = stored.password_ciphertext
original_updated_at = stored.credential_updated_at
unchanged = _profile_data()
unchanged.pop('password')
unchanged['display_name'] = 'DBS EU renamed'
again = freight_rpa_source_admin_service.save_profile(unchanged, actor_id=None, profile_id=payload['id'])
# 回显后的原用户名随表单提交时,不得重加密或刷新凭据时间。
assert again['username'] == 'test-user'
db.session.refresh(stored)
assert stored.username_ciphertext == original_username
assert stored.password_ciphertext == original_password
assert stored.credential_updated_at == original_updated_at
assert stored.display_name == 'DBS EU renamed'
def test_profile_username_change_reencrypts_without_touching_password(app):
"""只改用户名时重写用户名密文,密码密文保持不变。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
stored = db.session.get(FreightRpaProfile, payload['id'])
original_username = stored.username_ciphertext
original_password = stored.password_ciphertext
changed = _profile_data()
changed.pop('password')
changed['username'] = 'other-user'
updated = freight_rpa_source_admin_service.save_profile(changed, actor_id=None, profile_id=payload['id'])
assert updated['username'] == 'other-user'
db.session.refresh(stored)
assert stored.username_ciphertext != original_username
assert stored.password_ciphertext == original_password
def test_profile_rejects_page_operation_configuration(app):
@@ -174,7 +214,7 @@ def test_profile_rejects_page_operation_configuration(app):
payload = _profile_data()
payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}}
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_profile(payload, actor_id=None)
freight_rpa_source_admin_service.save_profile(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_CONFIG_INVALID'
@@ -182,10 +222,10 @@ def test_multiple_dbs_profiles_bind_independent_sources(app):
"""同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
second = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
first_source = shipping_inventory_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None)
second_source = shipping_inventory_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None)
first = freight_rpa_source_admin_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
second = freight_rpa_source_admin_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
first_source = freight_rpa_source_admin_service.save_source(_source_data(first['id'], code='DBS_DUB'), actor_id=None)
second_source = freight_rpa_source_admin_service.save_source(_source_data(second['id'], code='DBS_RTM'), actor_id=None)
assert first_source['rpa_profile_id'] == first['id']
assert second_source['rpa_profile_id'] == second['id']
@@ -194,34 +234,36 @@ def test_source_rejects_profile_connector_mismatch(app):
"""库存源不能绑定不同 Driver 的 Profile。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH'
freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_PROFILE_CONNECTOR_MISMATCH'
def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
"""禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
login = freight_rpa_source_admin_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='DRAFT_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
draft = shipping_inventory_service.save_source(payload, actor_id=None)
payload.update({'enabled': False, 'excel_template_id': None})
payload['onhand_report_config']['parsing_profile_id'] = None
draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None)
assert draft['enabled'] is False
assert draft['parsing_profile_id'] is None
assert draft['onhand_report_config']['parsing_profile_id'] is None
assert draft['excel_template_id'] is None
payload.update({'enabled': True})
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id'])
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED'
freight_rpa_source_admin_service.save_source(payload, actor_id=None, source_id=draft['id'])
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'
# 拒绝后回滚脏会话(等价于请求边界回滚):s18 服务在赋值后才触发启用门禁,
# 不回滚会让后续查询的 autoflush 把 enabled=True + 空模板撞 CHECK。
db.session.rollback()
payload.update({
'parsing_profile_id': _parsing_profile()['id'],
'excel_template_id': _excel_template_id(),
})
enabled = shipping_inventory_service.save_source(payload, actor_id=None, source_id=draft['id'])
payload['onhand_report_config']['parsing_profile_id'] = _parsing_profile()['id']
payload['excel_template_id'] = _excel_template_id()
enabled = freight_rpa_source_admin_service.save_source(payload, actor_id=None, source_id=draft['id'])
assert enabled['enabled'] is True
@@ -229,22 +271,23 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
"""普通保存只能保留停用站点;独立启用动作必须返回尚未完成的硬门槛。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
login = freight_rpa_source_admin_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='ACTIVATION_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
payload.update({'enabled': False, 'excel_template_id': None})
payload['onhand_report_config']['parsing_profile_id'] = None
draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
assert draft['activation']['ready'] is False
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template']
payload['enabled'] = True
saved = shipping_inventory_service.save_source(
saved = freight_rpa_source_admin_service.save_source(
payload, actor_id=None, source_id=draft['id'], allow_enable_transition=False,
)
assert saved['enabled'] is False
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.activate_source(draft['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
freight_rpa_source_admin_service.activate_source(draft['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED'
assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template']
@@ -252,18 +295,23 @@ def test_activation_status_exposes_only_hard_gate_checks(app):
"""启用门禁仅暴露连接/解析/发货模板硬门槛,不再包含测试导出或后续准备项。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
login = freight_rpa_source_admin_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
payload = {
'source_code': 'CHECKS_SOURCE', 'display_name': 'Checks Source', 'connector_type': 'dbs',
'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None,
'rpa_profile_id': login['id'], 'excel_template_id': None,
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand',
# s18 起报表路径/查询条件/解析方案绑定经内嵌 onhand_report_config 写配置行。
'onhand_report_config': {
'parsing_profile_id': None,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand',
},
'query_parameters_json': [],
},
'query_parameters_json': [], 'enabled': False,
'enabled': False,
}
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
draft = freight_rpa_source_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
checks = {item['code']: item for item in draft['activation']['checks']}
@@ -280,11 +328,11 @@ def test_enabled_source_rejects_disabled_rpa_profile(app):
"""启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(
profile = freight_rpa_source_admin_service.save_profile(
{**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None,
)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None)
freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='BLOCKED_SOURCE'), actor_id=None)
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLED'
@@ -292,10 +340,11 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app):
"""数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
assert source['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv'
assert source['query_parameters_json'] == [
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
# s18 起报表路径/查询条件挂在响应的 onhand_report_config 嵌套对象上。
assert source['onhand_report_config']['report_path_json']['report_name'] == 'On Hand Inventory By Location 3lv'
assert source['onhand_report_config']['query_parameters_json'] == [
{'name': 'Warehouse', 'mode': 'single', 'values': ['DUB'], 'required': True, 'select_all': False},
]
@@ -304,52 +353,54 @@ def test_source_rejects_driver_selector_in_business_parameters(app):
"""业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
payload = _source_data(profile['id'])
payload['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
payload['onhand_report_config']['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
freight_rpa_source_admin_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID'
def test_crane_source_rejects_dbs_report_path(app):
"""动态仓 Crane 库存源不得误填 DBS 四级报表路径。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
payload = _source_data(profile['id'], code='CRANE', connector_type='crane')
payload['warehouse_resolution_mode'] = 'inventory_match'
payload['fixed_warehouse_id'] = None
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
freight_rpa_source_admin_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_CONFIG_INVALID'
def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app):
"""停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
login = freight_rpa_source_admin_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None})
source = shipping_inventory_service.save_source(payload, actor_id=7, allow_enable_transition=False)
payload.update({'enabled': False})
payload['onhand_report_config']['parsing_profile_id'] = None
source = freight_rpa_source_admin_service.save_source(payload, actor_id=7, allow_enable_transition=False)
profile = _parsing_profile()
bound = shipping_inventory_service.bind_source_parsing_profile(
bound = freight_rpa_source_admin_service.bind_source_parsing_profile(
[source['id']], profile['id'], actor_id=7, operation='direct',
)
# 关键断言:直接绑定只配置解析定义,绝不绕过独立启用门禁。
assert bound[0]['enabled'] is False
assert bound[0]['parsing_profile_id'] == profile['id']
# s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。
assert bound[0]['onhand_report_config']['parsing_profile_id'] == profile['id']
assert bound[0]['config_version'] == source['config_version'] + 1
audit = ShippingInventorySourceParsingBindingAudit.query.one()
audit = FreightRpaSourceParsingBindingAudit.query.one()
assert audit.operation == 'direct'
# 关键断言:审计保留系统动作说明,不要求管理员额外填写“绑定原因”。
assert audit.reason == '管理员直接绑定已发布解析方案'
assert audit.before_snapshot_json['parsing_profile_id'] is None
assert audit.after_snapshot_json['parsing_profile_id'] == profile['id']
history = shipping_inventory_service.get_source_parsing_binding_audits(source['id'])
history = freight_rpa_source_admin_service.get_source_parsing_binding_audits(source['id'])
assert history[0]['actor_id'] == 7
assert history[0]['source_config_version_after'] == bound[0]['config_version']
@@ -358,33 +409,36 @@ def test_bulk_parsing_profile_binding_allows_enabled_sites(app):
"""批量绑定允许包含已启用站点;全部预检通过后原子写入。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
login = freight_rpa_source_admin_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED')
disabled_payload.update({'enabled': False, 'parsing_profile_id': None})
disabled = shipping_inventory_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False)
enabled = shipping_inventory_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None)
disabled_payload.update({'enabled': False})
disabled_payload['onhand_report_config']['parsing_profile_id'] = None
disabled = freight_rpa_source_admin_service.save_source(disabled_payload, actor_id=None, allow_enable_transition=False)
enabled = freight_rpa_source_admin_service.save_source(_source_data(login['id'], code='BULK_BIND_ENABLED'), actor_id=None)
profile = _parsing_profile()
bound = shipping_inventory_service.bind_source_parsing_profile(
bound = freight_rpa_source_admin_service.bind_source_parsing_profile(
[disabled['id'], enabled['id']], profile['id'], actor_id=None,
reason='批量迁移同类报表', operation='bulk',
)
# 关键断言:已启用站点可直接换绑;两站同步写入且留下审计。
assert {row['id'] for row in bound} == {disabled['id'], enabled['id']}
assert all(row['parsing_profile_id'] == profile['id'] for row in bound)
assert db.session.get(ShippingInventorySource, enabled['id']).enabled is True
assert ShippingInventorySourceParsingBindingAudit.query.count() == 2
# s18 起解析绑定挂在响应的 onhand_report_config 嵌套对象上。
assert all(row['onhand_report_config']['parsing_profile_id'] == profile['id'] for row in bound)
assert db.session.get(FreightRpaSource, enabled['id']).enabled is True
assert FreightRpaSourceParsingBindingAudit.query.count() == 2
def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app):
"""直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
login = freight_rpa_source_admin_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE')
payload.update({'enabled': False, 'parsing_profile_id': None})
source = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
payload.update({'enabled': False})
payload['onhand_report_config']['parsing_profile_id'] = None
source = freight_rpa_source_admin_service.save_source(payload, actor_id=None, allow_enable_transition=False)
template = db.session.get(ShippingExcelTemplate, source['excel_template_id'])
template.definition_json = {
'filename_pattern': '{business_no}.xlsx',
@@ -393,50 +447,51 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app
db.session.commit()
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.bind_source_parsing_profile(
freight_rpa_source_admin_service.bind_source_parsing_profile(
[source['id']], _parsing_profile()['id'], actor_id=None,
reason='模板字段契约预检', operation='direct',
)
# 关键断言:模板依赖缺失必须在绑定时拒绝,不能产生半成品站点绑定。
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_BINDING_TEMPLATE_INVALID'
assert db.session.get(ShippingInventorySource, source['id']).parsing_profile_id is None
assert ShippingInventorySourceParsingBindingAudit.query.count() == 0
assert exc_info.value.code == 'SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID'
# s18 起解析绑定归 onhand_report_config 配置行;被拒后配置行必须保持未绑定。
assert db.session.get(FreightRpaSource, source['id']).onhand_report_config.parsing_profile_id is None
assert FreightRpaSourceParsingBindingAudit.query.count() == 0
def test_published_rule_cannot_be_mutated_in_place(app):
"""发布规则必须依靠新版本演进,避免改写历史任务依据。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
reservation_field_id = _published_route_field_id()
rule = shipping_inventory_service.save_rule({
rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Reservation starts with 1', 'scope': 'line',
'priority': 100, 'match_mode': 'all', 'action_type': 'add_source_candidates',
'action_payload_json': {'source_codes': [source['source_code']]}, 'version': 1,
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None)
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None)
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.save_rule({
shipping_onhand_admin_service.save_rule({
'rule_code': 'RSV_PREFIX_1', 'rule_name': 'Changed', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None, rule_id=rule['id'])
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_IMMUTABLE'
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_IMMUTABLE'
def test_draft_rule_update_keeps_the_same_draft(app):
"""草稿更新应原地替换条件,不能偷偷新增同版本规则记录。"""
with app.app_context():
reservation_field_id = _published_route_field_id()
rule = shipping_inventory_service.save_rule({
rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'Before', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'DUB'}],
}, actor_id=None)
updated = shipping_inventory_service.save_rule({
updated = shipping_onhand_admin_service.save_rule({
'rule_code': 'DRAFT_UPDATE', 'rule_name': 'After', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['CRANE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'equals', 'expected_value_json': 'FRA'}],
@@ -450,7 +505,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
"""列表、长度和空值操作符必须保存受控值类型,不能把配置错误拖到运行期。"""
with app.app_context():
reservation_field_id = _published_route_field_id()
rule = shipping_inventory_service.save_rule({
rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'RSV_IN', 'rule_name': 'Reservation list', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': ['1001', '1002']}],
@@ -458,106 +513,107 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
assert rule['conditions'][0]['expected_value_json'] == ['1001', '1002']
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_rule({
shipping_onhand_admin_service.save_rule({
'rule_code': 'RSV_BAD_IN', 'rule_name': 'Invalid list', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DBS_DUB']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'in', 'expected_value_json': '1001'}],
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_CONDITION_INVALID'
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_CONDITION_INVALID'
def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
"""未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
shipping_inventory_service.delete_profile(unused['id'])
assert all(item['profile_code'] != 'UNUSED' for item in shipping_inventory_service.list_profiles())
unused = freight_rpa_source_admin_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
freight_rpa_source_admin_service.delete_profile(unused['id'])
assert all(item['profile_code'] != 'UNUSED' for item in freight_rpa_source_admin_service.list_profiles())
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.delete_profile(profile['id'])
freight_rpa_source_admin_service.delete_profile(profile['id'])
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DELETE_BLOCKED'
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id'])
freight_rpa_source_admin_service.save_profile({**_profile_data(), 'enabled': False}, actor_id=None, profile_id=profile['id'])
assert exc_info.value.code == 'SHIPPING.RPA_PROFILE_DISABLE_BLOCKED'
reservation_field_id = _published_route_field_id()
rule = shipping_inventory_service.save_rule({
rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'RETIRE_ME', 'rule_name': 'Retire me', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None)
shipping_inventory_service.publish_rule(rule['id'], actor_id=None)
retired = shipping_inventory_service.retire_rule(rule['id'], actor_id=None)
shipping_onhand_admin_service.publish_rule(rule['id'], actor_id=None)
retired = shipping_onhand_admin_service.retire_rule(rule['id'], actor_id=None)
assert retired['status'] == 'retired'
with pytest.raises(ConflictError) as exc_info:
shipping_inventory_service.delete_draft_rule(rule['id'])
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_DELETE_BLOCKED'
shipping_onhand_admin_service.delete_draft_rule(rule['id'])
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_DELETE_BLOCKED'
def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
"""发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None)
disabled_payload = _source_data(profile['id'], code='DISABLED_ROUTE_SOURCE')
disabled_payload.update({'enabled': False, 'parsing_profile_id': None, 'excel_template_id': None})
shipping_inventory_service.save_source(disabled_payload, actor_id=None)
disabled_payload.update({'enabled': False, 'excel_template_id': None})
disabled_payload['onhand_report_config']['parsing_profile_id'] = None
freight_rpa_source_admin_service.save_source(disabled_payload, actor_id=None)
reservation_field_id = _published_route_field_id()
missing_rule = shipping_inventory_service.save_rule({
missing_rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'MISSING_SOURCE', 'rule_name': 'Missing source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['MISSING_SOURCE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '1'}],
}, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.publish_rule(missing_rule['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_RULE_SOURCE_INVALID'
shipping_onhand_admin_service.publish_rule(missing_rule['id'], actor_id=None)
assert exc_info.value.code == 'SHIPPING.ONHAND_RULE_SOURCE_INVALID'
disabled_rule = shipping_inventory_service.save_rule({
disabled_rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'DISABLED_SOURCE', 'rule_name': 'Disabled source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': ['DISABLED_ROUTE_SOURCE']},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '2'}],
}, actor_id=None)
assert shipping_inventory_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published'
assert shipping_onhand_admin_service.publish_rule(disabled_rule['id'], actor_id=None)['status'] == 'published'
valid_rule = shipping_inventory_service.save_rule({
valid_rule = shipping_onhand_admin_service.save_rule({
'rule_code': 'VALID_SOURCE', 'rule_name': 'Valid source rule', 'scope': 'line',
'action_type': 'add_source_candidates', 'action_payload_json': {'source_codes': [source['source_code']]},
'conditions': [{'source_kind': 'order_field', 'order_field_id': reservation_field_id, 'operator': 'prefix', 'expected_value_json': '9'}],
}, actor_id=None)
assert shipping_inventory_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published'
assert shipping_onhand_admin_service.publish_rule(valid_rule['id'], actor_id=None)['status'] == 'published'
def test_active_default_external_mapping_is_unique_per_source(app):
"""同一库存源同一货代仓库身份只能有一条启用的映射。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
payload = {
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
'external_organization_code': None, 'external_site_code': 'EU01',
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
'in_transit_warehouse_code': 'TZR2', 'enabled': True,
}
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None)
with pytest.raises(ConflictError):
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
shipping_onhand_admin_service.save_external_mapping(payload, actor_id=None)
def test_external_mapping_allows_empty_freight_warehouse(app):
"""货代仓库改为可选:空值保存为 NULL(空库位默认映射行),供 inventory_match 源兜底匹配。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
# [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。
mapping = shipping_inventory_service.save_external_mapping({
'inventory_source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
mapping = shipping_onhand_admin_service.save_external_mapping({
'source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
'in_transit_warehouse_code': 'tzr2', 'enabled': True,
}, actor_id=None)
@@ -569,12 +625,12 @@ def test_external_mapping_requires_in_transit_warehouse_code(app):
"""在途仓编码是在途调拨拨出库位来源——缺省必须在保存端拒绝(fail-closed 前置)。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
# [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。
with pytest.raises(ValidationError):
shipping_inventory_service.save_external_mapping({
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
shipping_onhand_admin_service.save_external_mapping({
'source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
}, actor_id=None)
@@ -583,10 +639,10 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app):
"""配置端小写货代仓应与收料文件仓库值(大写归一后)使用同一精确映射身份。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
mapping = shipping_inventory_service.save_external_mapping({
'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub',
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
source = freight_rpa_source_admin_service.save_source(_source_data(profile['id']), actor_id=None)
mapping = shipping_onhand_admin_service.save_external_mapping({
'source_id': source['id'], 'freight_warehouse_id': 'dub',
'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01',
'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True,
}, actor_id=None)
@@ -597,32 +653,26 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
"""连接级上传配置(upload_config_json)变更不递增 config_version。"""
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
base_version = profile['config_version']
upload_cfg = {
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
'enabled': True, 'entry_url': 'https://evil.example/steal',
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file',
}
updated = shipping_inventory_service.save_profile(
updated = freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
)
assert updated['config_version'] == base_version
assert updated['upload_config_json']['enabled'] is True
assert updated['upload_config_json'] == {'enabled': True}
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
bumped = shipping_inventory_service.save_profile(
bumped = freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
actor_id=None, profile_id=profile['id'],
)
assert bumped['config_version'] == base_version + 1
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
# 上传配置必须是对象;页面字段不再作为校验对象。
with pytest.raises(ValidationError):
shipping_inventory_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
actor_id=None, profile_id=profile['id'],
)
with pytest.raises(ValidationError):
shipping_inventory_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
freight_rpa_source_admin_service.save_profile(
{**_profile_data(), 'upload_config_json': 'not-an-object'},
actor_id=None, profile_id=profile['id'],
)
@@ -0,0 +1,79 @@
"""
backend/tests/services/file_assets/test_storage_presign.py
用途:验证业务文件预签名下载地址使用浏览器可访问的 MinIO 主机。
依赖:file_assets.storage、minio。
逻辑:正式环境内网端点与公网基址不同;断言签名 URL 的主机是公网基址,读写客户端仍是内网端点。
"""
from __future__ import annotations
import pytest
from app.services.file_assets import storage as storage_mod
from app.services.file_assets.storage import resolve_presign_endpoint
pytestmark = pytest.mark.pure_unit
def _patch_minio_config(monkeypatch, *, public_base: str, secure: bool = False) -> None:
"""把存储配置钉成正式环境形态:容器内网端点 + 浏览器公网基址。"""
monkeypatch.setattr(storage_mod._cfg, "MINIO_ENDPOINT", "host.docker.internal:9000")
monkeypatch.setattr(storage_mod._cfg, "MINIO_ACCESS_KEY", "test-access")
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECRET_KEY", "test-secret")
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECURE", secure)
monkeypatch.setattr(storage_mod._cfg, "MINIO_PUBLIC_BASE_URL", public_base)
monkeypatch.setattr(storage_mod._cfg, "MINIO_FILE_ASSETS_BUCKET", "hxops-file-assets")
def test_resolve_presign_endpoint_keeps_explicit_port():
"""公网基址的非默认端口必须留在预签名端点里。"""
endpoint, secure = resolve_presign_endpoint(
"http://ai.well-trust.com:9000",
"host.docker.internal:9000",
False,
)
# [断言意图] 正式环境浏览器入口是 9000,不能收成 80。
assert endpoint == "ai.well-trust.com:9000"
assert secure is False
def test_resolve_presign_endpoint_falls_back_when_public_base_empty():
"""公网基址为空时继续用内网端点,避免签出空主机。"""
endpoint, secure = resolve_presign_endpoint("", "192.168.100.192:9000", False)
# [断言意图] 未配置公网基址时行为与改前一致。
assert endpoint == "192.168.100.192:9000"
assert secure is False
def test_presigned_get_url_uses_public_host(monkeypatch):
"""正式环境下载链接的主机必须是 MINIO_PUBLIC_BASE_URL。"""
_patch_minio_config(monkeypatch, public_base="http://ai.well-trust.com:9000")
store = storage_mod.FileAssetStorage()
monkeypatch.setattr(store, "_ensure_bucket_exists", lambda: None)
url = store.presigned_get_url(
"shipping/outbound-reports/2026/10/1/abc.xlsx",
expires_seconds=300,
download_name="CRANE_20261020_1815.xlsx",
)
# [断言意图] 浏览器打开的是公网 MinIO,签名里不能再出现容器内网主机。
assert url.startswith(
"http://ai.well-trust.com:9000/hxops-file-assets/shipping/outbound-reports/2026/10/1/abc.xlsx?"
)
assert "host.docker.internal" not in url
assert "X-Amz-Signature=" in url
assert "response-content-disposition=" in url
# [断言意图] 读写仍走容器内网端点,避免把公网主机写进上传客户端。
assert store.client is not store.presign_client
assert store.client._base_url.host == "host.docker.internal:9000"
assert store.presign_client._base_url.host == "ai.well-trust.com:9000"
def test_presigned_get_url_reuses_client_when_hosts_match(monkeypatch):
"""内网端点与公网基址相同时不另建客户端。"""
_patch_minio_config(monkeypatch, public_base="http://host.docker.internal:9000")
store = storage_mod.FileAssetStorage()
# [断言意图] 开发环境两端点一致,预签名与读写共用同一客户端。
assert store.presign_client is store.client
@@ -0,0 +1,100 @@
"""
backend/tests/services/freight_rpa/test_crane_upload_recheck.py
用途:验证上传配置只保留开关,以及 Crane 分配中只排一次定时回查。
依赖:page_contract、upload_attempt_service、crane_recheck、Flask 测试库。
逻辑:先断言入口 URL 和行分类,再走 complete_attempt、定时回查和手动刷新。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app import db
from app.core.errors import ConflictError
from app.services.freight_rpa.upload.crane_recheck import (
fire_scheduled_crane_recheck,
request_manual_crane_refresh,
)
from app.services.freight_rpa.upload.page_contract import (
build_upload_entry_url,
classify_crane_order_row,
)
from app.services.shipping_notice.upload_attempt_service import (
complete_attempt,
project_notice_upload_status,
start_rpa_attempt,
)
from tests.test_shipping_upload_attempt import _ready_artifact
def test_upload_entry_url_comes_from_login_host_and_crane_row_is_classified():
"""DBS/Crane 上传页由登录主机拼接;只有两句固定文案分别表示已分配和分配中。"""
assert build_upload_entry_url('dbs', 'https://s360.dbschenker.com/login') == (
'https://s360.dbschenker.com/main/portal/frame/WMSUpload2'
)
assert build_upload_entry_url('crane', 'https://wms-portal.craneww.com/') == (
'https://wms-portal.craneww.com/#/shipping-order-upload'
)
assert classify_crane_order_row('Processing', 'Shipping Order Allocated') == 'allocated'
assert classify_crane_order_row('Processing', 'Allocating the Shipping Order') == 'allocating'
assert classify_crane_order_row('Completed', 'Shipping Order Allocated') == 'other'
def test_allocating_schedules_one_recheck_and_blocks_another_upload(app):
"""首次分配中写下 10 分钟回查;第二次回调不改到期时间,也不能重新上传。"""
with app.app_context():
notice, artifact, _reservation = _ready_artifact()
artifact.file_name = 'MXI26082801.xlsx'
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key')
started = datetime(2026, 10, 23, 3, 0, 0)
complete_attempt(attempt, success=False, callback_id='upload-1', result='allocating')
# remember 使用 utcnow;这里只断言间隔为 10 分钟,不绑定测试开始时刻。
due_at = datetime.fromisoformat(attempt.success_evidence_json['crane_recheck']['due_at'])
assert timedelta(minutes=9) < due_at - datetime.utcnow() <= timedelta(minutes=10)
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
assert project_notice_upload_status(notice) == 'allocating'
complete_attempt(attempt, success=False, callback_id='recheck-1', result='allocating')
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at.isoformat(timespec='seconds')
with pytest.raises(ConflictError) as blocked:
start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key-2')
assert blocked.value.code == 'SHIPPING.UPLOAD_CRANE_ALLOCATING'
assert started < due_at
def test_manual_refresh_does_not_move_the_one_scheduled_recheck(app):
"""手动刷新另写一条状态回查,不改定时到期时间,也不把定时标记成已触发。"""
with app.app_context():
notice, artifact, _reservation = _ready_artifact()
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-manual')
complete_attempt(attempt, success=False, callback_id='upload-manual', result='allocating')
due_at = attempt.success_evidence_json['crane_recheck']['due_at']
source = {'login_url': 'https://wms-portal.craneww.com/', 'connector_type': 'crane'}
first = request_manual_crane_refresh(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
)
assert first.endswith(f'upload_recheck_{notice.task_no}_manual.json')
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
with pytest.raises(ConflictError) as inflight:
request_manual_crane_refresh(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
)
assert inflight.value.code == 'SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT'
future = datetime.fromisoformat(due_at) + timedelta(seconds=1)
assert fire_scheduled_crane_recheck(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
) is True
assert fire_scheduled_crane_recheck(
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
) is False
db.session.refresh(attempt)
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
assert attempt.success_evidence_json['crane_recheck']['fired'] is True
@@ -0,0 +1,40 @@
"""freight_rpa 包 import 边界适应度测试。
用途:锁死阶段 B 验收标准——freight_rpa 不寄生业务编排。
依赖:app/services/freight_rpa 包、ast。
逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败;
白名单为空集(批次 B Task 6 起审计写入已下沉本包
common/report_audit,包内不再引用任何 shipping_notice 业务模块;
历史 file_assets 白名单条目随迁移一并删除——包内只引用
app.services.file_assets,不属 shipping_notice 命名空间)。
"""
from __future__ import annotations
import ast
from pathlib import Path
PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa"
# 空集:freight_rpa 禁止 import 任何 app.services.shipping_notice.* 模块
# (审计写入走本包 common/report_audit;模型 import 走 app.models,不在此列)。
ALLOWED_SHIPPING_NOTICE: set[str] = set()
def _imported_modules(path: Path) -> set[str]:
tree = ast.parse(path.read_text(encoding="utf-8"))
mods: set[str] = set()
for node in ast.walk(tree):
if isinstance(node, ast.Import):
mods.update(a.name for a in node.names)
elif isinstance(node, ast.ImportFrom) and node.module:
mods.add(node.module)
return mods
def test_freight_rpa_import_boundary():
assert PKG.exists(), "freight_rpa 包不存在"
violations: list[str] = []
for py in PKG.rglob("*.py"):
for mod in _imported_modules(py):
if mod.startswith("app.services.shipping_notice") and mod not in ALLOWED_SHIPPING_NOTICE:
violations.append(f"{py.name}: {mod}")
assert not violations, "freight_rpa 违规 import:\n" + "\n".join(violations)
@@ -0,0 +1,16 @@
"""
tests/services/freight_rpa/test_outbound_trigger_contract.py
用途:出站 RPA trigger_io 与 Worker 心跳能力串的契约常量回归。
依赖:freight_rpa.outbound.trigger_io、worker_heartbeat.OUTBOUND_EXPORT_CAPABILITY。
逻辑:Task 7 接口清单的单一真相,防止 schema/action/能力名漂移。
"""
from app.services.freight_rpa.outbound import trigger_io
from app.services.freight_rpa.common.worker_heartbeat import OUTBOUND_EXPORT_CAPABILITY
def test_outbound_trigger_constants():
"""出站 trigger schema/action 与 Worker outbound_export 能力须与设计 spec 一致。"""
assert trigger_io.SCHEMA == "freight_rpa.outbound.v1"
assert trigger_io.ACTION_OUTBOUND_EXPORT_BATCH == "outbound_export_batch"
assert OUTBOUND_EXPORT_CAPABILITY == "outbound_export"
@@ -0,0 +1,196 @@
"""tests/services/freight_rpa/test_report_fact_dispatch.py
用途:锁定阶段 B Task 6——inbound 回调「先提交文件/终态,再投递事实」的顺序契约。
依赖:pytest、tests/conftest 的 app 夹具(种子站点 DSV360_AWSDU)、
app.core.errors.AppError、app.services.freight_rpa.reports.facts.ReportFact、
freight_rpa.reports.dispatch.register_report_handler(Task 6 新增)、
freight_rpa.inbound.report_archive.ingest_inbound_callback。
逻辑:(1)处理函数抛异常时已 commit 的归档文件行仍在(不回滚)且异常原样外抛;
(2)同一 unit_run_id + sha256 重复回调不插第二行,事实仍重复投递 ok=True
(供处理函数重试);(3)kind 未注册处理函数时 404
FREIGHT_RPA.SINK_NOT_REGISTERED,已提交文件行不受影响;
(4)empty 终态同样先 commit 再投递 ok=False 事实。
"""
from __future__ import annotations
import hashlib
import pytest
from app.services.freight_rpa.reports.facts import ReportFact
SEED_SOURCE_CODE = "DSV360_AWSDU"
# 归档 IO 替身的注入字节:_fake_archive_io 夹具把它喂给
# _read_inbound_callback_file,_success_payload 按需覆写。
_FAKE_FILE_BYTES: dict[str, bytes] = {"data": b"abc"}
# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。
_CALLBACK_SEQ: dict[str, int] = {"n": 0}
@pytest.fixture
def db_session(app):
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
@pytest.fixture(autouse=True)
def _reset_report_handlers():
"""每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。
[断言意图] 缺处理器用例必须跑在"干净注册表"上——否则前序用例注册的
inbound 处理函数会让 404 用例假绿。
"""
from app.services.freight_rpa.reports import dispatch as dispatch_module
saved = dict(dispatch_module._REPORT_HANDLERS)
dispatch_module._REPORT_HANDLERS.clear()
yield
dispatch_module._REPORT_HANDLERS.clear()
dispatch_module._REPORT_HANDLERS.update(saved)
@pytest.fixture(autouse=True)
def _fake_archive_io(monkeypatch):
"""替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。
核心逻辑:与旧回调测试同一 monkeypatch 姿态(patch report_archive 模块属性),
使 ingest 的 success 分支可脱离真实文件系统与对象存储走完全程。
"""
from app.services.freight_rpa.inbound import report_archive
monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: _FAKE_FILE_BYTES["data"])
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
def _next_callback_id(prefix: str) -> str:
"""生成跨用例唯一的 callback_id(满足 unit run 唯一约束)。"""
_CALLBACK_SEQ["n"] += 1
return f"{prefix}-{_CALLBACK_SEQ['n']}"
def _awaiting_unit(*, source_code: str = "DSV"):
"""构造一个处于 awaiting_rpa 的 inbound 执行单元(挂种子站点满足外键)。
核心逻辑:source_code 列允许测试值(如 "DSV"),source_id 外键挂种子站点
DSV360_AWSDU——与 test_report_queries.py 的 _inbound_file 同构。
"""
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
return FreightRpaInboundUnitRun(
source_id=source.id,
source_code=source_code,
connector_type="dbs",
callback_id=_next_callback_id("report-fact-dispatch"),
status="awaiting_rpa",
config_snapshot_json={},
)
def _success_payload(unit, *, sha256_file: bytes = b"abc") -> dict:
"""构造通过 schema 校验的 success 回调载荷;sha256_file 即被模拟读取的 xlsx 字节。"""
_FAKE_FILE_BYTES["data"] = sha256_file
return {
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": f"receipt_{unit.id or 'x'}.xlsx",
"original_filename": "receipt.xlsx",
"sha256": hashlib.sha256(sha256_file).hexdigest(),
}
def test_handler_failure_keeps_committed_file(app, db_session, monkeypatch):
"""处理函数失败绝不回滚已 commit 的归档文件行,异常原样外抛(不吞)。"""
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
def boom(fact: ReportFact) -> None:
raise RuntimeError("handler down")
register_report_handler("inbound", boom)
with pytest.raises(RuntimeError, match="handler down"):
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
# [断言意图] 异常外抛但文件行已提交:count==1 锁死「先 commit 再投递」顺序。
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
def test_second_delivery_does_not_insert_another_file(app, db_session):
"""同一回调重放不插第二行文件,事实仍重复投递(同一 file_id、ok=True)。"""
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
seen: list[ReportFact] = []
register_report_handler("inbound", seen.append)
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
payload = _success_payload(unit, sha256_file=b"abc")
ingest_inbound_callback(payload)
ingest_inbound_callback(payload)
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
# [断言意图] 幂等重放仍两次投递 ok=True 事实(同一 file_id),供处理函数重试。
assert [fact.file_id for fact in seen] == [seen[0].file_id, seen[0].file_id]
assert all(fact.ok is True for fact in seen)
def test_missing_handler_raises_sink_not_registered(app, db_session):
"""kind 未注册处理函数 → 404 FREIGHT_RPA.SINK_NOT_REGISTERED,文件行已提交。"""
from app.core.errors import AppError
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
with pytest.raises(AppError) as exc:
ingest_inbound_callback(_success_payload(unit, sha256_file=b"abc"))
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
# [断言意图] 分发失败不回滚归档:文件行保留,Worker 重试整笔回调即可补投递。
assert FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id).count() == 1
def test_empty_callback_dispatches_failure_fact(app, db_session):
"""empty 终态同样先 commit 再投递 ok=False 事实(error_code 随载荷落库值)。"""
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
seen: list[ReportFact] = []
register_report_handler("inbound", seen.append)
unit = _awaiting_unit(source_code="DSV")
db_session.add(unit)
db_session.commit()
result = ingest_inbound_callback(
{
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "empty",
"error_code": "no_inbound_data",
"error_message": "no_inbound_data",
}
)
assert result["status"] == "empty"
assert len(seen) == 1
fact = seen[0]
# [断言意图] empty 是合法业务结果 → ok=False + error_code=no_inbound_data 的事实。
assert fact.report_kind == "inbound"
assert fact.source_code == "DSV"
assert fact.ok is False
assert fact.file_id is None
assert fact.sha256 is None
assert fact.error_code == "no_inbound_data"
assert fact.error_message == "no_inbound_data"
@@ -0,0 +1,282 @@
"""tests/services/freight_rpa/test_report_queries.py
用途:锁定阶段 B Task 3——freight_rpa.reports 只读查询模块的行为契约。
依赖:pytest、app fixture(tests/conftest)、app.core.errors、
app.services.freight_rpa.reports(待实现模块)。
逻辑:覆盖(1)latest_usable_inbound_file 的可用门禁——未删除、当天
(Asia/Shanghai 业务日)抓取、未过期、最新优先;(2)require_report_kind 的
白名单校验;(3)站点/在手/入站配置只读视图;(4)按 storage_key 读文件
字节 + 缺文件 NotFoundError;(5)解析失败三列的标记与清除(仅 flush
不 commit)。(6)业务日窗口内外的定向拒收/放行。
时间口径:查询的 now 参数显式传 naive UTC;文件 created_at 也按 naive UTC
存入,两者用同一业务日窗口锚点(now=2026-10-05 12:00 UTC → 上海业务日
10-05,UTC 窗口 [10-04 16:00, 10-05 16:00))。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app.core.errors import NotFoundError, ValidationError
from app.services.freight_rpa.reports import (
clear_inbound_parse_failure,
get_inbound_config,
get_onhand_config,
get_site,
latest_usable_inbound_file,
mark_inbound_parse_failure,
read_inbound_file_bytes,
require_report_kind,
)
SEED_SOURCE_CODE = "DSV360_AWSDU"
# 业务日窗口锚点(naive UTC):2026-10-05 12:00 UTC = 上海 10-05 20:00,
# 对应业务日 2026-10-05 的 UTC 存储窗口 [10-04 16:00, 10-05 16:00)。
FROZEN_NOW = datetime(2026, 10, 5, 12, 0, 0)
@pytest.fixture
def db_session(app):
"""复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
def _inbound_file(*, source_code: str, sha256: str, created_at: datetime, **overrides):
"""构造一条挂在指定 source_code 执行单元下的入站归档文件(含 unit run)。
核心逻辑:外键要求文件必须挂在 FreightRpaInboundUnitRun 下,unit run 再挂
种子站点(DSV360_AWSDU);source_code 写进 unit run 列(非外键,允许 "DSV"
等测试值),便于验证查询按 unit run 的 source_code 过滤。
"""
from app import db
from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
unit = FreightRpaInboundUnitRun(
source_id=source.id,
source_code=source_code,
connector_type="dbs",
callback_id=f"test-callback:{source_code}:{sha256[:8]}",
status="success",
config_snapshot_json={},
**overrides,
)
db.session.add(unit)
db.session.flush()
report_file = FreightRpaInboundReportFile(
unit_run_id=unit.id,
storage_provider="minio",
storage_bucket="test",
storage_key=f"freight_rpa/inbound/{source_code}/{sha256[:12]}.xlsx",
original_filename=f"{sha256[:8]}.xlsx",
file_size=16,
sha256=sha256,
created_at=created_at,
)
db.session.add(report_file)
return report_file
def test_latest_usable_inbound_file_returns_newest(app, db_session):
"""同一业务日窗口内的两份可用文件 → 按 created_at 倒序取最新一份。
[断言意图] 两份文件的 created_at 均落在 FROZEN_NOW 的业务日 UTC 窗口
([10-04 16:00, 10-05 16:00))内,证明「最新优先」在当天门禁内生效,
而不是因为当天新鲜度被丢掉才命中。
"""
older = _inbound_file(source_code="DSV", sha256="a" * 64, created_at=datetime(2026, 10, 4, 18, 0, 0))
newer = _inbound_file(source_code="DSV", sha256="b" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0))
db_session.add_all([older, newer])
db_session.commit()
view = latest_usable_inbound_file("DSV", now=FROZEN_NOW)
assert view is not None
assert view.file_id == newer.id
assert view.sha256 == "b" * 64
def test_latest_usable_inbound_file_rejects_out_of_business_day(app, db_session):
"""「当天(Asia/Shanghai 业务日)抓取」是可用门禁的一部分:隔日文件不可用。
[断言意图] 同一份文件(expries 为空、未删除)在非当天业务日查 → None;
把判定时刻推回文件被抓取的那个业务日 → 又可用;差异只能来自当天窗口,
锁死修复轮补回的新鲜度条件。
"""
report = _inbound_file(source_code="STL", sha256="0" * 64, created_at=datetime(2026, 10, 3, 10, 0, 0))
db_session.commit()
# FROZEN_NOW(业务日 10-05)下,10-03 抓取的文件是隔日旧文件 → 不可用。
assert latest_usable_inbound_file("STL", now=FROZEN_NOW) is None
# 业务日 10-03 的窗口为 UTC [10-02 16:00, 10-03 16:00):10-03 10:00 UTC 在窗口内 → 可用。
in_day_now = datetime(2026, 10, 3, 12, 0, 0)
view = latest_usable_inbound_file("STL", now=in_day_now)
assert view is not None
assert view.file_id == report.id
def test_latest_usable_inbound_file_skips_deleted_and_expired(app, db_session):
"""已删除/已过期的文件不得被当作可用文件返回;同来源保留最新可用一份。"""
# [断言意图] 三份文件都在 FROZEN_NOW 的业务日窗口内,且已删除/已过期两份
# 更新——若门禁失效,“最新优先”会先命中它们;断言只能命中唯一的可用文件。
usable = _inbound_file(source_code="CRN", sha256="c" * 64, created_at=datetime(2026, 10, 4, 20, 0, 0))
deleted = _inbound_file(source_code="CRN", sha256="d" * 64, created_at=datetime(2026, 10, 5, 1, 0, 0))
deleted.archive_deleted_at = datetime(2026, 10, 5, 5, 0, 0)
expired = _inbound_file(source_code="CRN", sha256="e" * 64, created_at=datetime(2026, 10, 5, 2, 0, 0))
# 保留期早于判定时刻(仍未被清理任务删除)→ 过期不可用。
expired.archive_expires_at = FROZEN_NOW - timedelta(hours=1)
db_session.add_all([usable, deleted, expired])
db_session.commit()
view = latest_usable_inbound_file("CRN", now=FROZEN_NOW)
assert view is not None
assert view.sha256 == "c" * 64
assert view.source_code == "CRN"
assert view.storage_key.endswith(f"{'c' * 12}.xlsx")
assert view.original_filename == f"{'c' * 8}.xlsx"
assert view.created_at == datetime(2026, 10, 4, 20, 0, 0)
def test_latest_usable_inbound_file_no_match_returns_none(app, db_session):
"""来源无任何归档文件(或全部不可用)时返回 None,不抛异常。"""
assert latest_usable_inbound_file("NOPE") is None
def test_report_kind_rejects_shipment():
with pytest.raises(ValidationError):
require_report_kind("shipment")
assert require_report_kind("outbound") == "outbound"
def test_get_site_returns_view_of_seeded_source(app):
"""get_site 返回站点连接与模板绑定的只读视图;未知来源返回 None。"""
view = get_site(SEED_SOURCE_CODE)
assert view is not None
assert view.source_code == SEED_SOURCE_CODE
assert view.display_name == "DBS Dublin AWSDU"
assert view.connector_type == "dbs"
assert view.excel_template_id is not None
assert view.enabled is True
assert get_site("NOPE") is None
def test_get_onhand_config_returns_report_definition(app):
"""get_onhand_config 返回 s18 起挂在配置行上的报表路径/查询条件/解析方案。"""
config = get_onhand_config(SEED_SOURCE_CODE)
assert config is not None
assert config.report_path_json.get("program_group") == "Bison"
assert config.query_parameters_json == [
{"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "required": True, "select_all": False},
]
assert config.parsing_profile_id is not None
# [断言意图] 未知来源与存在但未配置报表的来源都必须返回 None(fail-closed)。
assert get_onhand_config("NOPE") is None
def test_get_inbound_config_returns_none_without_config_row(app):
"""种子站点没有入站报表配置行 → get_inbound_config 返回 None。"""
from app import db
from app.models import FreightRpaInboundReportConfig, FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SEED_SOURCE_CODE).one()
assert get_inbound_config(SEED_SOURCE_CODE) is None
# [断言意图] 补一条配置行后即可读出三个字段(与在手配置视图同构)。
db.session.add(FreightRpaInboundReportConfig(
source=source,
report_path_json={"program_group": "Bison", "report_name": "Receipt"},
query_parameters_json=[{"name": "Date", "mode": "range"}],
parsing_profile_id=None,
))
db.session.commit()
config = get_inbound_config(SEED_SOURCE_CODE)
assert config is not None
assert config.report_path_json["report_name"] == "Receipt"
assert config.query_parameters_json == [{"name": "Date", "mode": "range"}]
assert config.parsing_profile_id is None
def test_read_inbound_file_bytes_reads_by_storage_key(app, db_session, monkeypatch):
"""read_inbound_file_bytes 按文件的 storage_key 调 file_asset_storage 读取。"""
from app.services.freight_rpa.reports import queries as queries_module
report_file = _inbound_file(source_code="DSV", sha256="f" * 64, created_at=datetime(2026, 10, 6))
db_session.commit()
captured: dict[str, bytes] = {}
def fake_get_bytes(storage_key):
captured["key"] = storage_key
return b"xlsx-bytes"
monkeypatch.setattr(queries_module.file_asset_storage, "get_bytes", fake_get_bytes)
assert read_inbound_file_bytes(report_file.id) == b"xlsx-bytes"
assert captured["key"] == report_file.storage_key
def test_read_inbound_file_bytes_missing_file_raises(app):
"""文件 id 不存在 → NotFoundError(fail-closed,不吞 404)。"""
with pytest.raises(NotFoundError):
read_inbound_file_bytes(999999)
def test_mark_and_clear_inbound_parse_failure_roundtrip(app, db_session):
"""mark 写入三列并 flush(不 commit 由调用方决定);clear 清空恢复。"""
from datetime import timedelta
report_file = _inbound_file(source_code="DSV", sha256="9" * 64, created_at=datetime(2026, 10, 7))
db_session.commit()
file_id = report_file.id
mark_inbound_parse_failure(
file_id,
error_code="X" * 80,
error_message="m" * 2500,
)
# [断言意图] 只 flush 不 commit——新开的同一事务查询立即可见,且列宽截断生效。
from app import db
from app.models import FreightRpaInboundReportFile
marked = db.session.get(FreightRpaInboundReportFile, file_id)
assert marked.parse_failed_at is not None
assert marked.parse_failed_at > datetime.utcnow() - timedelta(minutes=1)
assert marked.parse_error_code == "X" * 64
assert marked.parse_error_message == "m" * 2000
db_session.commit()
clear_inbound_parse_failure(file_id)
cleared = db.session.get(FreightRpaInboundReportFile, file_id)
assert cleared.parse_failed_at is None
assert cleared.parse_error_code is None
assert cleared.parse_error_message is None
db_session.commit()
def test_mark_inbound_parse_failure_missing_file_raises(app):
"""文件 id 不存在 → NotFoundError,与其他按 id 操作一致。"""
with pytest.raises(NotFoundError):
mark_inbound_parse_failure(999999, error_code="E", error_message="m")
def test_import_boundary_no_business_module_imports():
"""本模块(发货与调拨读报表唯一入口)不得 import shipping_notice / in_transit_transfer。"""
import ast
from pathlib import Path
pkg = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa" / "reports"
assert pkg.exists()
for py in pkg.rglob("*.py"):
tree = ast.parse(py.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
mods = [a.name for a in node.names]
elif isinstance(node, ast.ImportFrom) and node.module:
mods = [node.module]
else:
continue
for mod in mods:
assert not mod.startswith("app.services.shipping_notice"), f"{py.name}: {mod}"
assert not mod.startswith("app.services.in_transit_transfer"), f"{py.name}: {mod}"
@@ -0,0 +1,59 @@
"""
backend/tests/services/freight_rpa/test_upload_trigger_contract.py
用途:锁死 upload trigger 写入契约——action 与心跳能力 freight_rpa_upload 对齐,schema 为 freight_rpa.upload.v1。
依赖:app.services.freight_rpa.upload.trigger_io、Flask app fixture。
逻辑:断言模块常量;write_upload_trigger 落盘后 JSON 的 action/schema_version 与常量一致。
"""
from __future__ import annotations
import json
from pathlib import Path
from app.services.freight_rpa.common.worker_heartbeat import FREIGHT_RPA_UPLOAD_CAPABILITY
from app.services.freight_rpa.upload import trigger_io
def test_upload_trigger_constants_align_with_heartbeat_capability():
"""upload action 必须与 Worker 心跳能力串 freight_rpa_upload 一致。"""
assert trigger_io.SCHEMA == "freight_rpa.upload.v1"
assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == "freight_rpa_upload"
assert trigger_io.ACTION_FREIGHT_RPA_UPLOAD == FREIGHT_RPA_UPLOAD_CAPABILITY
assert "outbound_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD
assert "shipment_upload" not in trigger_io.ACTION_FREIGHT_RPA_UPLOAD
def test_write_upload_trigger_persists_freight_upload_action(app, tmp_path):
"""落盘 trigger JSON 的 action/schema_version 须与模块常量一致。"""
export_file = tmp_path / "queue_src" / "SN-001.xlsx"
export_file.parent.mkdir(parents=True)
export_file.write_bytes(b"fake-xlsx")
upload_queue = tmp_path / "upload_queue"
upload_trigger = tmp_path / "upload_triggers"
upload_queue.mkdir()
upload_trigger.mkdir()
with app.app_context():
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
queue_path, trigger_path, callback_id = trigger_io.write_upload_trigger(
"TASK-UP-1",
str(export_file),
attempt_id=10,
artifact_id=20,
connector_type="dbs",
callback_id="upload-cb-1",
)
assert queue_path
assert trigger_path
assert callback_id == "upload-cb-1"
payload = json.loads(Path(trigger_path).read_text(encoding="utf-8"))
# [断言意图] Worker 侧不校验 action 字面量,但双侧契约文档须与心跳能力 freight_rpa_upload 对齐。
assert payload["action"] == trigger_io.ACTION_FREIGHT_RPA_UPLOAD
assert payload["schema_version"] == trigger_io.SCHEMA
assert payload["action"] == "freight_rpa_upload"
assert payload["schema_version"] == "freight_rpa.upload.v1"
@@ -1,8 +1,8 @@
"""
backend/tests/test_rpa_worker_heartbeat.py
backend/tests/services/freight_rpa/test_worker_heartbeat.py
用途:货代库存/上传 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。
依赖:freight_rpa.common.worker_heartbeat、shipping_notice_tools heartbeat 路由。
逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配、货代上传就绪与 fail-fast 断言。
"""
@@ -14,10 +14,10 @@ from typing import Any
import pytest
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.rpa_worker_heartbeat import (
FREIGHT_UPLOAD_CAPABILITY,
INVENTORY_EXPORT_CAPABILITY,
RECEIPT_EXPORT_CAPABILITY,
from app.services.freight_rpa.common.worker_heartbeat import (
FREIGHT_RPA_UPLOAD_CAPABILITY,
ONHAND_EXPORT_CAPABILITY,
INBOUND_EXPORT_CAPABILITY,
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
RPA_WORKER_OFFLINE_MESSAGE,
@@ -53,7 +53,7 @@ def _heartbeat_payload(
"worker_id": worker_id,
"hostname": "WIN-RPA-HOST",
"environment": environment or resolve_backend_rpa_environment(),
"capabilities": capabilities or [INVENTORY_EXPORT_CAPABILITY],
"capabilities": capabilities or [ONHAND_EXPORT_CAPABILITY],
"status": "idle",
"trigger_dir": trigger_dir,
"drop_dir": str(trigger_dir).replace("triggers", "drop"),
@@ -68,7 +68,7 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d
trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id=scope_id)
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
@@ -133,7 +133,7 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
@@ -155,11 +155,11 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
"""生产策略要求 Redis 时,写入失败应抛存储不可用。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
"app.services.freight_rpa.common.worker_heartbeat._redis_store_worker",
lambda _worker: False,
)
@@ -172,20 +172,20 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
"""fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
from app.services.freight_rpa.common.worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
# 隔离:强制无 Redis 分支(_redis_client 为模块级单例,config 置空不可靠,须 monkeypatch);
# 并清空心跳存储,确保走 no_worker_heartbeat + 进程内存储原因码。
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
reset_rpa_worker_heartbeat_state_for_tests()
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
@@ -202,13 +202,13 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path
assert (exc_info.value.details or {}).get("detail_message")
def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
def test_assert_inbound_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
"""收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。"""
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
from app.services.shipping_notice.rpa_worker_heartbeat import (
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_receipt_rpa_worker_ready,
assert_inbound_rpa_worker_ready,
reset_rpa_worker_heartbeat_state_for_tests,
)
@@ -217,14 +217,14 @@ def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path,
trigger_dir = tmp_path / 'receipt_triggers'
trigger_dir.mkdir()
app.config['ENV_NAME'] = 'test'
app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(trigger_dir)
app.config['FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR'] = str(trigger_dir)
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED'] = True
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK'] = True
app.config['FREIGHT_RPA_WORKER_MOCK'] = 'false'
with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info:
assert_receipt_rpa_worker_ready()
assert_inbound_rpa_worker_ready()
# [断言意图] 与库存同构的用户可见文案与 reasons;缺哨兵与无心跳同时暴露,
# 对应部署侧必须由 ps1 注入 FREIGHT_RPA_SHARED_SCOPE_ID 写哨兵。
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
@@ -249,7 +249,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path,
)
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.time.time",
"app.services.freight_rpa.common.worker_heartbeat.time.time",
lambda: base_now + 120,
)
result = check_inventory_rpa_worker_ready()
@@ -258,7 +258,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path,
def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
"""POST /rpa/heartbeat 应写入心跳并返回 ok。"""
"""POST /api/freight-rpa/heartbeat 应写入心跳并返回 ok(旧 shipping-notice 路由已删)。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
@@ -266,7 +266,7 @@ def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
res = client.post(
"/api/shipping-notice/rpa/heartbeat",
"/api/freight-rpa/heartbeat",
headers={"X-Integration-Key": "test-tool-key"},
json=payload,
)
@@ -283,7 +283,7 @@ def test_rpa_heartbeat_api_rejects_missing_auth(client, app, tmp_path):
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
res = client.post("/api/shipping-notice/rpa/heartbeat", json=payload)
res = client.post("/api/freight-rpa/heartbeat", json=payload)
assert res.status_code == 401
@@ -295,7 +295,7 @@ def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
res = client.post(
"/api/shipping-notice/rpa/heartbeat",
"/api/freight-rpa/heartbeat",
headers={"X-Integration-Key": "wrong-key"},
json=payload,
)
@@ -306,9 +306,9 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
from app.services.shipping_notice.rpa_worker_heartbeat import (
from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
from app.services.freight_rpa.common.worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
@@ -326,7 +326,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
schedule_no="SCH-HB-OFFLINE",
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
platform_api_path="freight-rpa-onhand",
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
@@ -337,7 +337,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
db.session.add(run)
db.session.commit()
total, success, failed, skipped, _details, errors, logs = run_shipping_inventory_rpa_schedule(task, run)
total, success, failed, skipped, _details, errors, logs = run_freight_rpa_onhand_schedule(task, run)
assert total >= 1
assert success == 0
assert failed >= 1
@@ -364,7 +364,7 @@ def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_pat
raise ConnectionError("redis read failed")
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
lambda: BrokenRedis(),
)
@@ -400,7 +400,7 @@ def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch)
return bucket.get(key)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
lambda: FakeRedis(),
)
@@ -417,13 +417,13 @@ def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch)
def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path):
"""未显式配置 scope 时,可从 /mnt/hxops-rpa-* 挂载路径推导。"""
from app.services.shipping_notice.rpa_worker_heartbeat import shared_scope_id
from app.services.freight_rpa.common.worker_heartbeat import shared_scope_id
trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
trigger_dir.mkdir(parents=True)
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None)
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
assert shared_scope_id() == "hxops-rpa-test-data"
@@ -457,24 +457,24 @@ def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app,
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[INVENTORY_EXPORT_CAPABILITY],
capabilities=[ONHAND_EXPORT_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()
# 关键断言:缺少 freight_upload 能力必须阻断自动上传。
# 关键断言:缺少 freight_rpa_upload 能力必须阻断自动上传。
assert result.ready is False
assert any("missing_freight_upload_capability" in reason for reason in result.reasons)
assert any("missing_freight_rpa_upload_capability" in reason for reason in result.reasons)
def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
"""Worker 声明 freight_upload 且目录/凭据齐全时应 ready。"""
"""Worker 声明 freight_rpa_upload 且目录/凭据齐全时应 ready。"""
upload_trigger = _enable_freight_upload_checks(app, tmp_path)
with app.app_context():
record_rpa_worker_heartbeat(
_heartbeat_payload(
trigger_dir=str(upload_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[INVENTORY_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_RPA_UPLOAD_CAPABILITY],
)
)
result = check_freight_upload_rpa_ready()
@@ -483,7 +483,7 @@ def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
"""上传 fail-fast 须带 reasons,供建单前/触发时展示阻断原因。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
from app.services.freight_rpa.common.worker_heartbeat import (
reset_rpa_worker_heartbeat_state_for_tests,
)
@@ -501,8 +501,8 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
"""收料 ready 与库存同口径:要求共享哨兵;仅有库存 Worker 不能冒充收料在线。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
check_receipt_rpa_worker_ready,
from app.services.freight_rpa.common.worker_heartbeat import (
check_inbound_rpa_worker_ready,
reset_rpa_worker_heartbeat_state_for_tests,
serialize_rpa_worker_status,
)
@@ -513,8 +513,8 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
inventory_trigger.mkdir(parents=True)
_write_shared_sentinel(inventory_trigger, scope_id="hxops-rpa-test-data")
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(inventory_trigger)
app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger)
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(inventory_trigger)
app.config["FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR"] = str(receipt_trigger)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
@@ -528,7 +528,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
trigger_dir=str(inventory_trigger),
shared_scope_id="hxops-rpa-test-data",
))
receipt_offline = check_receipt_rpa_worker_ready()
receipt_offline = check_inbound_rpa_worker_ready()
assert receipt_offline.ready is False
assert receipt_offline.workers == []
@@ -537,18 +537,18 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
worker_id="HOST-receipt",
trigger_dir=str(receipt_trigger),
shared_scope_id="hxops-rpa-test-data",
capabilities=[RECEIPT_EXPORT_CAPABILITY],
capabilities=[INBOUND_EXPORT_CAPABILITY],
))
without_sentinel = check_receipt_rpa_worker_ready()
without_sentinel = check_inbound_rpa_worker_ready()
assert without_sentinel.ready is False
_write_shared_sentinel(receipt_trigger, scope_id="hxops-rpa-test-data")
receipt_ready = check_receipt_rpa_worker_ready()
receipt_ready = check_inbound_rpa_worker_ready()
assert receipt_ready.ready is True
assert [w["worker_id"] for w in receipt_ready.workers] == ["HOST-receipt"]
payload = serialize_rpa_worker_status(scope="receipt")
assert payload["scope"] == "receipt"
payload = serialize_rpa_worker_status(scope="inbound")
assert payload["scope"] == "inbound"
assert payload["ready"] is True
assert payload["trigger_dir"] == str(receipt_trigger)
assert [w["worker_id"] for w in payload["workers"]] == ["HOST-receipt"]
@@ -556,15 +556,15 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tmp_path):
"""未注入 *-receipt 身份时,仍可用收料 trigger_dir 识别在线收料 Worker。"""
from app.services.shipping_notice.rpa_worker_heartbeat import (
check_receipt_rpa_worker_ready,
from app.services.freight_rpa.common.worker_heartbeat import (
check_inbound_rpa_worker_ready,
reset_rpa_worker_heartbeat_state_for_tests,
)
receipt_trigger = tmp_path / "receipt" / "triggers"
receipt_trigger.mkdir(parents=True)
app.config["ENV_NAME"] = "dev"
app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger)
app.config["FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR"] = str(receipt_trigger)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = ""
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
@@ -577,8 +577,8 @@ def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tm
worker_id="Hugo-30820",
trigger_dir=str(receipt_trigger),
shared_scope_id="",
capabilities=[RECEIPT_EXPORT_CAPABILITY],
capabilities=[INBOUND_EXPORT_CAPABILITY],
))
result = check_receipt_rpa_worker_ready()
result = check_inbound_rpa_worker_ready()
assert result.ready is True
assert [w["worker_id"] for w in result.workers] == ["Hugo-30820"]
@@ -1,8 +1,8 @@
"""
backend/tests/test_rpa_worker_heartbeat_alert.py
backend/tests/services/freight_rpa/test_worker_heartbeat_alert.py
用途:RPA Worker 心跳告警冷却、Redis/DB 不可用兜底与接收人回退单测。
依赖:rpa_worker_heartbeat_alert、rpa_worker_heartbeat、models.AppSetting。
依赖:freight_rpa.common.worker_heartbeat_alert、freight_rpa.common.worker_heartbeat、models.AppSetting。
逻辑:验证 DB 权威读取、Redis 陈旧/空 DB 清理、并发 claim、企微失败可重试、恢复与 admin 回退。
"""
@@ -17,7 +17,7 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.models import AppSetting, User
from app.services.shipping_notice.rpa_worker_heartbeat_alert import (
from app.services.freight_rpa.common.worker_heartbeat_alert import (
_DB_ALERT_STATE_KEY,
_STATUS_SENDING,
_claim_alert_send_lock,
@@ -32,7 +32,7 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["ENV_NAME"] = "test"
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
@@ -62,7 +62,7 @@ def test_alert_state_memory_fallback_when_redis_save_fails(app, monkeypatch):
raise ConnectionError("redis down")
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
lambda: BrokenRedis(),
)
@@ -89,15 +89,15 @@ def test_storage_unavailable_alert_respects_memory_cooldown(app, tmp_path, monke
raise ConnectionError("redis write failed")
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
lambda: BrokenRedis(),
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
lambda: BrokenRedis(),
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
lambda **kwargs: send_calls.append(kwargs["title"]) or True,
)
@@ -129,11 +129,11 @@ def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch):
return True
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
_capture_send,
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
lambda: type(
"Ready",
(),
@@ -147,7 +147,7 @@ def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch):
)
with app.app_context():
from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients
from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients
recipients = _alert_recipients()
assert len(recipients) == 1
@@ -170,7 +170,7 @@ def test_alert_state_persists_to_db_when_redis_unavailable(app, monkeypatch):
raise ConnectionError("redis down")
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
lambda: BrokenRedis(),
)
@@ -191,7 +191,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch
app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
lambda: type(
"Ready",
(),
@@ -225,7 +225,7 @@ def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatc
)
db.session.commit()
from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients
from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients
recipients = _alert_recipients()
assert len(recipients) == 1
@@ -242,11 +242,11 @@ def test_alert_wecom_send_failure_allows_retry_before_cooldown(app, tmp_path, mo
return send_attempts["count"] >= 2
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
_flaky_send,
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
lambda: type(
"Ready",
(),
@@ -302,7 +302,7 @@ def test_concurrent_first_claim_integrity_error_does_not_claim(app, monkeypatch)
raise IntegrityError("INSERT", {}, Exception("duplicate key"))
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._claim_alert_send_lock_db",
"app.services.freight_rpa.common.worker_heartbeat_alert._claim_alert_send_lock_db",
_raise_integrity,
)
@@ -342,11 +342,11 @@ def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
return True
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
_capture_send,
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
lambda: type(
"Ready",
(),
@@ -359,7 +359,7 @@ def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
)(),
)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
lambda: type("BrokenRedis", (), {"get": lambda *_a, **_k: None, "set": lambda *_a, **_k: None, "delete": lambda *_a, **_k: None})(),
)
@@ -404,7 +404,7 @@ def test_load_alert_state_prefers_db_over_stale_redis(app, monkeypatch):
redis_bucket.pop(key, None)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
lambda: FakeRedis(),
)
@@ -448,7 +448,7 @@ def test_load_alert_state_overwrites_newer_stale_redis_from_db(app, monkeypatch)
redis_bucket.pop(key, None)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
lambda: FakeRedis(),
)
@@ -488,7 +488,7 @@ def test_load_alert_state_clears_stale_redis_when_db_has_no_row(app, monkeypatch
redis_bucket.pop(key, None)
monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
lambda: FakeRedis(),
)
@@ -1,8 +1,8 @@
"""在途调拨测试固定夹具:时钟、收料文件样例、外部替身与数据库隔离。
"""在途调拨测试固定夹具:时钟、入站文件样例、外部替身与数据库隔离。
用途:为 tests/services/in_transit_transfer 提供与 TDD 文档一致的固定输入
(fixed_clock 默认 2026-08-06 09:00:00+08:00、dbs/crane ready 文件、
same_day_receipt_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。
same_day_inbound_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。
依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。
逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB;
请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。
@@ -35,19 +35,20 @@ def _stub_doc_sequence(monkeypatch):
@pytest.fixture(autouse=True)
def _pin_maturity_lag_legacy(request):
"""在途套件钉成熟滞后=1(T+1)。
def _seed_default_transfer_type(request):
"""默认启用类型配置种子(autouse,出生翻转后匹配创建必填且配置驱动)。
用途:存量夹具生态按 T+1 语义构建(fixed_clock 业务日 2026-08-06、收料日期
2026-08-05=T-1);生产默认 T+2(settings IN_TRANSIT_TRANSFER_MATURITY_
LAG_DAYS=2)的边界行为由 test_matching_service / test_date_policy 专项
用例显式覆盖,不被本钉值掩盖。
逻辑:仅对已请求 app 的用例钉值(request.fixturenames 判定),pure_unit 用例
(如 test_date_policy)不触碰 Flask,继续走 date_policy 的无上下文回退。
用途:Task 11 切换后 run_matching/create_matching 必填 transfer_type 且类型
合法值=配置表 code;本 fixture 为请求 app 的用例预置一条与旧「类型 1
硬编码」语义对齐的启用配置(doc_no 前缀 HOM/HOX/WTP + WTP→HOW 转换 +
from/to 全 mapped),存量用例随语义平移后行为等价。专项用例可按 code
覆盖/停用/补建其它类型。
"""
if "app" in getattr(request, "fixturenames", []):
app = request.getfixturevalue("app")
app.config["IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS"] = 1
request.getfixturevalue("app")
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
seed_transfer_type_config()
@pytest.fixture
@@ -78,9 +79,10 @@ def wecom_fake() -> FakeWeCom:
def patch_source_file_status(monkeypatch):
"""执行文件对账门禁替身工厂:替换 execution_service 的来源文件状态投影。
用途:execute_items 门禁②按去重来源调 resolve_source_file_status(真实查询
收料文件表);单元测试注入替身避免触碰表数据。缺省全部来源投影为
ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file 行版本戳同源)。
用途:execute_items 门禁②按 (来源, record_kind) 调 resolve_source_file_status
(真实查询收料/出站文件表);单元测试注入替身避免触碰表数据。缺省全部
来源投影为 ready 且 sha=dbs 夹具 checksum("d"*64,与 dbs_ready_file
行版本戳同源)。record_kind 入参接受但不区分,存量用例仍按来源给 sha。
Args:
mapping: source_code → sha 映射;值为 None 表示该来源无可用文件
@@ -91,7 +93,8 @@ def patch_source_file_status(monkeypatch):
def _patch(mapping: dict[str, str | None] | None = None) -> None:
table = mapping or {}
def _resolve(*, source_code: str) -> dict:
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
del record_kind # 本替身按来源给 sha;出站分流用例自行覆盖本函数。
if source_code in table:
sha = table[source_code]
if sha is None:
@@ -1,63 +1,362 @@
"""在途调拨领域测试的对象工厂。
用途:集中构造合法 Invoice / 文件行 / 预检 DTO,避免各测试重复内联样板。
依赖:标准库(dataclasses / decimal)。
用途:集中构造调拨类型配置种子与「清空并重新解析」(spec §6)用例种子
(来源+入站解析规则+归档文件+档行),避免各测试重复内联样板。
依赖:标准库(datetime)、openpyxl(内存 xlsx 构造)。
逻辑:工厂只生成业务合法的默认值;测试用 override 注入变体。
归档文件字节不落真存储:用例经 FakeArchiveStorage 注入并 monkeypatch
file_asset_storage.get_bytes。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from typing import Any
from datetime import datetime
# ---------------------------------------------------------------------------
# 调拨类型配置种子(出生翻转后匹配创建必填且配置驱动,Task 11)
# ---------------------------------------------------------------------------
# 默认种子类型:与旧类型 1 硬编码语义对齐(doc_no 前缀 HOM/HOX/WTP + WTP→HOW
# 批号转换 + from/to 全 mapped),保证存量用例随语义平移后行为等价。
DEFAULT_TYPE_CODE = "in_transit_to_hub"
DEFAULT_SCOPE_RULES = [{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}]
DEFAULT_WAREHOUSE_CONFIG = {
"from": {"mode": "mapped", "warehouse_code": None, "external_org": None},
"to": {"mode": "mapped", "warehouse_code": None, "external_org": None},
}
DEFAULT_TRANSFORM_RULES = [{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}]
@dataclass(frozen=True)
class ReceiptRow:
"""单行收料文件记录(含 Sheet/行号追溯证据)。"""
sheet: str = "Receipt"
row_no: int = 1
invoice_no: str = "HOM-001"
material_no: str = "MAT-001"
material_name: str = "连接器组件"
specification: str = "A 型 / 24PIN"
receipt_date: str = "2026-08-05"
receipt_quantity: str = "1200"
source_code: str = "DBS-AWSBI"
def to_dict(self) -> dict[str, Any]:
"""转 dict,供 parser/aggregator 输入。"""
return {
"sheet": self.sheet,
"row_no": self.row_no,
"invoice_no": self.invoice_no,
"material_no": self.material_no,
"material_name": self.material_name,
"specification": self.specification,
"receipt_date": self.receipt_date,
"receipt_quantity": self.receipt_quantity,
"source_code": self.source_code,
}
def make_invoice_item(
def seed_transfer_type_config(
code: str = DEFAULT_TYPE_CODE,
*,
invoice_no: str = "HOM-001",
source_code: str = "DBS-AWSBI",
material_no: str = "MAT-001",
receipt_quantity: Decimal | str | int = "1200",
external_quantity: Decimal | str | int | None = "1200",
receipt_date: str = "2026-08-05",
) -> dict[str, Any]:
"""构造一条预检明细项(默认严格匹配、可执行)。"""
return {
"invoice_no": invoice_no,
"source_code": source_code,
"material_no": material_no,
"material_name": "连接器组件",
"specification": "A 型 / 24PIN",
"receipt_date": receipt_date,
"receipt_quantity": Decimal(str(receipt_quantity)),
"external_quantity": None if external_quantity is None else Decimal(str(external_quantity)),
}
enabled: bool = True,
scope_rules: list[dict] | None = None,
warehouse_config: dict | None = None,
transform_rules: list[dict] | None = None,
):
"""get-or-create 一条调拨类型配置(测试种子;直接 ORM 插入绕过服务校验)。
Args:
code: 类型编码。
enabled: 启停(默认启用)。
scope_rules / warehouse_config / transform_rules: 缺省与旧类型 1 硬编码
语义对齐(HOM/HOX/WTP 前缀 + mapped/mapped + WTP→HOW)。
Returns:
TransferTypeConfig ORM 行。
"""
from app import db
from app.models import TransferTypeConfig
row = db.session.query(TransferTypeConfig).filter_by(code=code).first()
if row is not None:
return row
row = TransferTypeConfig(
code=code,
names_json={"zh-CN": f"类型 {code}"},
enabled=enabled,
sort_order=0,
scope_rules_json=DEFAULT_SCOPE_RULES if scope_rules is None else scope_rules,
warehouse_config_json=DEFAULT_WAREHOUSE_CONFIG if warehouse_config is None else warehouse_config,
transform_rules_json=DEFAULT_TRANSFORM_RULES if transform_rules is None else transform_rules,
)
db.session.add(row)
db.session.commit()
return row
# ---------------------------------------------------------------------------
# 清空并重新解析(spec §6,Task 7)用例种子
# ---------------------------------------------------------------------------
# 入站解析规则缺省 field_mapping(movement 定死领域字段 → 表头别名,CRANE 风格)。
INBOUND_MOVEMENT_FIELD_MAPPING = {
"doc_no": "单据编号",
"line_no": "项次",
"in_out_flag": "进出库别",
"material_code": "料号",
"material_name": "品名",
"lot_no": "批号",
"quantity": "数量",
"movement_date": "异动日期",
}
# 与 INBOUND_MOVEMENT_FIELD_MAPPING 对齐的 xlsx 表头行(build_movement_xlsx 缺省表头)。
INBOUND_MOVEMENT_HEADERS = ["单据编号", "项次", "进出库别", "料号", "品名", "批号", "数量", "异动日期"]
def build_movement_xlsx(data_rows: list[list], *, sheet_name: str = "Receipt",
headers: list[str] | None = None) -> bytes:
"""构造内存 xlsx 字节(表头 + 数据行),供归档假存储注入。
Args:
data_rows: 数据行(列序与 headers 一致;数量 int、日期 str)。
sheet_name: 工作表标题(溯源 sheet 字段来源)。
headers: 表头行;缺省 INBOUND_MOVEMENT_HEADERS。
Returns:
xlsx 原始字节。
"""
from io import BytesIO
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = sheet_name
ws.append(list(headers if headers is not None else INBOUND_MOVEMENT_HEADERS))
for row in data_rows:
ws.append(list(row))
buf = BytesIO()
wb.save(buf)
return buf.getvalue()
class FakeArchiveStorage:
"""file_asset_storage 内存假件(storage_key → bytes),按 repo_fakes 风格最小实现。"""
def __init__(self, objects: dict[str, bytes] | None = None) -> None:
self.objects: dict[str, bytes] = dict(objects or {})
def get_bytes(self, storage_key: str) -> bytes:
"""读取注入对象;缺失键抛 KeyError(用例内即失败,不静默)。"""
return self.objects[storage_key]
def seed_inbound_reparse_source(source_code: str, *, profile_code: str | None = None,
version: int = 1, field_mapping: dict | None = None,
sheet_name: str = "Receipt", header_row_index: int = 1,
status: str = "published"):
"""建「启用来源 + 已发布 inbound 解析规则 + 收料配置绑定」全套种子(幂等)。
用途:清空并重新解析(spec §6)服务/端点用例的来源侧种子;来源自身
在手解析绑定(在手口径)按约束置最小占位配置行(s18 起归
FreightRpaOnhandReportConfig),真实重建规则挂
FreightRpaInboundReportConfig.parsing_profile_id(与运行期口径一致)。
Args:
source_code: 来源实例编码。
profile_code: 入站解析规则 code(缺省 MV_<source_code>)。
version: 入站解析规则版本。
field_mapping: 领域字段→表头别名;缺省 INBOUND_MOVEMENT_FIELD_MAPPING。
sheet_name / header_row_index: definition_json 结构参数。
status: 入站规则状态(缺省 published;用例可注入 draft 验证 abort)。
Returns:
(FreightRpaSource, FreightRpaParsingProfile) 元组。
"""
from app import db
from app.models import (
ShippingExcelTemplate,
FreightRpaOnhandReportConfig,
FreightRpaParsingProfile,
FreightRpaSource,
FreightRpaProfile,
FreightRpaInboundReportConfig,
)
source = FreightRpaSource.query.filter_by(source_code=source_code).first()
if source is not None:
config = source.inbound_report_config
return source, (config.parsing_profile if config else None)
resolved_code = profile_code or f"MV_{source_code}"
onhand = FreightRpaParsingProfile(
purpose="onhand", profile_code=f"ONHAND_{source_code}", display_name=source_code,
version=1, status="published", file_format="xlsx",
definition_json={}, structure_definition_json={},
)
profile = FreightRpaParsingProfile(
purpose="inbound", profile_code=resolved_code, display_name=resolved_code,
version=version, status=status, file_format="xlsx",
definition_json={
"sheet_name": sheet_name, "header_row_index": header_row_index,
"field_mapping": dict(
INBOUND_MOVEMENT_FIELD_MAPPING if field_mapping is None else field_mapping),
},
structure_definition_json={},
)
rpa = FreightRpaProfile(
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="dbs",
login_url="https://test.invalid/dbs", login_config_json={"auth_mode": "password"},
)
template = ShippingExcelTemplate(
template_code=f"TPL_{source_code}", display_name=source_code, version=1,
status="published", storage_provider="minio", storage_bucket="test",
storage_key=f"test/{source_code}/template.xlsx", original_filename="template.xlsx",
file_checksum="0" * 64, definition_json={}, definition_checksum="0" * 64,
)
source = FreightRpaSource(
source_code=source_code, display_name=source_code, connector_type="dbs",
rpa_profile=rpa, excel_template=template,
warehouse_resolution_mode="fixed", fixed_warehouse_id="AWSDU", enabled=True,
)
db.session.add_all([onhand, profile, rpa, template, source])
db.session.flush()
# s18 起在手解析方案绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载。
db.session.add(FreightRpaOnhandReportConfig(
source_id=source.id, parsing_profile_id=onhand.id,
report_path_json={}, query_parameters_json=[],
))
db.session.add(FreightRpaInboundReportConfig(
source_id=source.id, parsing_profile_id=profile.id))
db.session.commit()
return source, profile
def seed_reparse_archive_file(source, *, sha: str, storage_key: str, created_at: datetime,
archive_expires_at: datetime | None = None,
archive_deleted_at: datetime | None = None,
callback_id: str | None = None):
"""建一条收料执行单元 + 原样归档文件行(清空重建用例种子)。
字节不落真存储:用例把 build_movement_xlsx 产物注入 FakeArchiveStorage
(键=storage_key)并 monkeypatch file_asset_storage.get_bytes。
Args:
source: seed_inbound_reparse_source 返回的来源行。
sha: 归档文件 sha256(唯一约束 unit_run+sha,用例间取不同值)。
storage_key: 对象存储键(与假存储注入键一致)。
created_at: 归档时间(= repository 的 archived_at,排序依据)。
archive_expires_at: 保留期截止;None=长期有效。
archive_deleted_at: 清理时间;None=未清理。
callback_id: 收料执行单元回调键(缺省按 sha 派生保证唯一)。
Returns:
已入库的 FreightRpaInboundReportFile。
"""
from app import db
from app.models import FreightRpaInboundReportFile, FreightRpaInboundUnitRun
unit = FreightRpaInboundUnitRun(
source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type,
callback_id=callback_id or f"cb-{sha[:12]}",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = FreightRpaInboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=storage_key, original_filename=f"{callback_id or 'cb'}.xlsx",
file_size=16, sha256=sha, created_at=created_at,
archive_expires_at=archive_expires_at, archive_deleted_at=archive_deleted_at,
)
db.session.add(report)
db.session.commit()
return report
def seed_reparse_ledger_row(source_code: str, doc_no: str, *, line_no: str = "1",
in_out_flag: str = "I", lot_no: str = "LOT-1",
source_file_id: int | None = None,
sha: str = "9" * 64, quantity: str = "1",
material_code: str = "MAT-OLD", material_name: str = "旧映射名称",
movement_date: str = "2026-08-05",
transfer_executed: bool = False,
executed_doc_no: str | None = None,
updated_at: datetime | None = None,
record_kind: str = "inbound"):
"""插一条旧映射库存异动档行(清空重建用例种子;业务值=旧映射形态)。
Args:
source_code / doc_no: 来源与单号(自然键主干)。
line_no / in_out_flag / lot_no: 自然键可变成分(与解析行对齐便于断言覆写)。
source_file_id: 溯源归档文件 id;None=证据缺失行形态。
sha: 档行 file_sha256(缺省 9*64 表示旧文件指纹)。
quantity / material_code / material_name / movement_date: 旧业务值。
transfer_executed / executed_doc_no: 封存形态注入。
updated_at: 显式更新时间(封存不动行断言用)。
record_kind: inbound(默认)或 outbound。
Returns:
已入库的 TransferMovementLedger。
"""
from app import db
from app.models import TransferMovementLedger
row = TransferMovementLedger(
source_code=source_code, record_kind=record_kind,
doc_no=doc_no, line_no=line_no, line_seq="", in_out_flag=in_out_flag,
carton_id="", lot_no=lot_no,
material_code=material_code, material_name=material_name,
quantity=quantity, movement_date=movement_date,
source_file_id=source_file_id, file_version=None, file_sha256=sha,
transfer_executed=transfer_executed, executed_doc_no=executed_doc_no,
updated_at=updated_at or datetime(2026, 10, 1, 8, 0, 0),
)
db.session.add(row)
db.session.commit()
return row
def seed_outbound_reparse_source(source_code: str, *, profile_code: str | None = None,
version: int = 1, status: str = "published"):
"""建「启用来源 + 已发布 outbound 解析规则 + 出站配置绑定」种子(幂等)。
用途:清空并重新解析出站流用例。若来源已存在则只补出站配置/规则。
Returns:
(FreightRpaSource, FreightRpaParsingProfile) 元组。
"""
from app import db
from app.models import (
FreightRpaOutboundReportConfig,
FreightRpaParsingProfile,
FreightRpaSource,
)
source, _inbound = seed_inbound_reparse_source(source_code)
existing = source.outbound_report_config
if existing is not None and existing.parsing_profile is not None:
return source, existing.parsing_profile
resolved_code = profile_code or f"OUT_{source_code}"
profile = FreightRpaParsingProfile(
purpose="outbound", profile_code=resolved_code, display_name=resolved_code,
version=version, status=status, file_format="xlsx",
definition_json={
"sheet_name": "Receipt", "header_row_index": 1,
"field_mapping": dict(INBOUND_MOVEMENT_FIELD_MAPPING),
},
structure_definition_json={},
)
db.session.add(profile)
db.session.flush()
if existing is None:
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id, parsing_profile_id=profile.id,
report_path_json={"report_name": "Outbound"},
query_parameters_json=[],
))
else:
existing.parsing_profile_id = profile.id
db.session.commit()
return source, profile
def seed_reparse_outbound_archive_file(source, *, sha: str, storage_key: str,
created_at: datetime,
archive_expires_at: datetime | None = None,
callback_id: str | None = None):
"""建一条出站执行单元 + 归档文件行(清空重建出站用例种子)。
Returns:
已入库的 FreightRpaOutboundReportFile。
"""
from app import db
from app.models import FreightRpaOutboundReportFile, FreightRpaOutboundUnitRun
unit = FreightRpaOutboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type, warehouse_id="AWSDU",
callback_id=callback_id or f"out-cb-{sha[:12]}",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = FreightRpaOutboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=storage_key, original_filename=f"{callback_id or 'out'}.xlsx",
file_size=16, sha256=sha, created_at=created_at,
archive_expires_at=archive_expires_at,
)
db.session.add(report)
db.session.commit()
return report
@@ -285,7 +285,7 @@ class FakeRPA:
})
if source_code in self.fail_on:
return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
return {"ok": True, "callback_id": f"inbound:{source_code}:{business_date}"}
class FakeWeCom:
@@ -1,7 +1,7 @@
"""在途调拨测试的仓库/路由/依赖替身。
用途:为 file_preparation / matching_service / API / Job 测试提供可注入的
ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps;
InboundFileRepository、RouteResolver 与组装好的 TransferDeps;
并提供 seed_rows_from_file 迁移桥(2026-09-25 起匹配不解析文件,
行须经 evidence_sync 落地)。
依赖:app.services.in_transit_transfer(仅类型)、fakes。
@@ -13,15 +13,15 @@ from __future__ import annotations
from datetime import datetime
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
from app.services.in_transit_transfer.matching_service import RouteMapping, TransferDeps
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA
class FakeReceiptFileRepository:
class FakeInboundFileRepository:
"""按 (source_code, business_date) 返回可注入 ready 文件。"""
def __init__(self, files: dict[tuple[str, str], ReadyReceiptFile] | None = None) -> None:
def __init__(self, files: dict[tuple[str, str], ReadyInboundFile] | None = None) -> None:
self.files = files or {}
self.lookups: list[tuple[str, str]] = []
# 一次性覆盖:下一次 latest_ready_file 对该来源返回此文件(用后即弃,
@@ -34,7 +34,7 @@ class FakeReceiptFileRepository:
Args:
source_code: 来源实例编码(覆盖该来源的下一次查询)。
rows: 文件原始行集(透传为 ReadyReceiptFile.rows)。
rows: 文件原始行集(透传为 ReadyInboundFile.rows)。
checksum: 文件 sha256 版本戳。
file_version: 文件版本号(缺省 "override")。
"""
@@ -42,12 +42,12 @@ class FakeReceiptFileRepository:
"rows": tuple(rows), "checksum": checksum, "file_version": file_version,
}
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
"""记录查询并返回匹配文件;有一次性覆盖时优先返回并消费之。"""
self.lookups.append((source_code, business_date))
override = self._next_files.pop(source_code, None)
if override is not None:
return ReadyReceiptFile(
return ReadyInboundFile(
source_code=source_code,
business_date=business_date,
file_no=f"REC-OVERRIDE-{source_code}",
@@ -64,7 +64,7 @@ def seed_rows_from_file(source_code: str, deps: TransferDeps, business_date: str
【2026-09-25】匹配不再解析文件(行由 evidence_sync 落地);凡旧用例
「文件夹具直接进 run_matching/create_matching」的,须先经本助手把文件行
落成待查行(status='matching' + result_code='pending_stock_check'),
再进入匹配管道(成熟过滤→查库存→落位)。须在 app/DB 上下文内调用。
再进入匹配管道(未来日期阻断→查库存→落位)。须在 app/DB 上下文内调用。
Args:
source_code: 来源实例编码(须与 deps.file_repository 注入的文件一致)。
@@ -82,11 +82,11 @@ def seed_rows_from_file(source_code: str, deps: TransferDeps, business_date: str
)
def make_ready_repo(*files: dict) -> FakeReceiptFileRepository:
"""由 fixture 文件 dict 构建仓库;rows 透传为 ReadyReceiptFile.rows。"""
repository = FakeReceiptFileRepository()
def make_ready_repo(*files: dict) -> FakeInboundFileRepository:
"""由 fixture 文件 dict 构建仓库;rows 透传为 ReadyInboundFile.rows。"""
repository = FakeInboundFileRepository()
for item in files:
repository.files[(item["source_code"], item["business_date"])] = ReadyReceiptFile(
repository.files[(item["source_code"], item["business_date"])] = ReadyInboundFile(
source_code=item["source_code"],
business_date=item["business_date"],
file_no=item["file_no"],
@@ -20,7 +20,6 @@ def _summary(executable_count: int) -> MatchingSummaryDTO:
matching_id="MTG-20260928-ABC123",
status="matched",
business_date="2026-09-28",
eligible_receipt_date_to="2026-09-27",
expires_at="2026-09-28T10:00:00",
counts=MatchingCountsDTO(executable_count=executable_count),
estimated_transfer_quantity="0",
@@ -66,8 +65,8 @@ def test_executes_and_propagates_result_when_executable(monkeypatch):
assert outcome.errors == []
def test_passes_receipt_date_range_to_matching(monkeypatch):
"""可选收料日期范围透传匹配层;缺省时为 None(=全部成熟积压)。"""
def test_passes_movement_date_range_to_matching(monkeypatch):
"""可选异动日期范围透传匹配层;缺省时为 None(=全部积压)。"""
captured = {}
def _fake_create(**kwargs):
@@ -78,15 +77,15 @@ def test_passes_receipt_date_range_to_matching(monkeypatch):
at.run_auto_transfer(
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
receipt_date_from="2026-09-01", receipt_date_to="2026-09-05",
movement_date_from="2026-09-01", movement_date_to="2026-09-05",
)
# 断言:显式范围原样透传(成熟上限/起止合法性由匹配层 ValidationError 卡控)。
assert captured["receipt_date_from"] == "2026-09-01"
assert captured["receipt_date_to"] == "2026-09-05"
# 断言:显式范围原样透传(起止合法性由匹配层 ValidationError 卡控)。
assert captured["movement_date_from"] == "2026-09-01"
assert captured["movement_date_to"] == "2026-09-05"
at.run_auto_transfer(
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
)
# 断言:缺省(留空)不缩小匹配面,范围参数为 None。
assert captured["receipt_date_from"] is None
assert captured["receipt_date_to"] is None
assert captured["movement_date_from"] is None
assert captured["movement_date_to"] is None
@@ -0,0 +1,443 @@
"""backlog_reparse_service:清空并重解析的守卫矩阵(spec §6,Task 7)。
用途:锁死「清空并重新解析」的安全不变量与五条守卫——①正常路径旧映射行被清、
按当前模板重落、计数/溯源正确、审计事件落库;②任一归档解析失败整体中止
一行不删(先解析后删除);③封存行(transfer_executed=true)与被有效 items
占用行幸存;④证据缺失(归档已清理/过保留期/无溯源)的行保留并计入
kept_unrebuildable;⑤预检形状(files/profile/clearable_rows/kept_rows)。
依赖:factories(来源/归档/档行种子 + FakeArchiveStorage + build_movement_xlsx)、
ledger_sync.movement_file_version、app fixture。
逻辑:归档文件字节经假存储注入(monkeypatch file_asset_storage.get_bytes);
归档文件 created_at 均早于 NOW 数日——若 repository 仍带运行期「当日抓取」
门禁则清单为空,本套件即红(锁定维护路径无当日门禁)。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.core.errors import AppError
from app.models import (
TransferAuditEvent,
TransferInvoiceItem,
TransferMatching,
TransferMovementLedger,
)
from app.services.in_transit_transfer import evidence_sync
from app.services.in_transit_transfer.ledger_sync import movement_file_version
from app.services.in_transit_transfer.backlog_reparse_service import (
preview_pending_match_reparse,
reparse_pending_match,
)
from tests.services.in_transit_transfer import factories
pytestmark = [pytest.mark.usefixtures("app")]
SOURCE = "CRANE_NA"
NOW = datetime(2026, 10, 15, 10, 0, 0)
OLD_SHA = "9" * 64
SHA_A = "a" * 64
SHA_B = "b" * 64
SHA_GONE = "e" * 64 # 已过保留期归档文件的 sha(证据缺失形态)
REPARSE_EVENT = "TRANSFER_PENDING_MATCH_REPARSED"
@pytest.fixture
def archive_storage(monkeypatch):
"""归档假存储:注入 FakeArchiveStorage 并替换单例 get_bytes(所有引用方同源)。"""
fake = factories.FakeArchiveStorage()
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
return fake
def _seed_world(*, profile_status: str = "published") -> tuple:
"""标准场景种子:来源+已发布入站规则 + 两份可用归档(A 先 B 后)。
Returns:
(source, profile, file_a, file_b) 元组。
"""
source, profile = factories.seed_inbound_reparse_source(SOURCE, status=profile_status)
file_a = factories.seed_reparse_archive_file(
source, sha=SHA_A, storage_key=f"archive/{SOURCE}/a.xlsx",
created_at=datetime(2026, 10, 10, 8, 0, 0))
file_b = factories.seed_reparse_archive_file(
source, sha=SHA_B, storage_key=f"archive/{SOURCE}/b.xlsx",
created_at=datetime(2026, 10, 11, 8, 0, 0))
return source, profile, file_a, file_b
def _count_ledger(source_code: str = SOURCE) -> int:
"""该来源 inbound 档行总数(中止/幸存断言主对象)。"""
return TransferMovementLedger.query.filter_by(
source_code=source_code, record_kind="inbound").count()
def test_reparse_clears_and_relands(app, archive_storage):
# [断言意图] 正常路径:旧映射行全清(3)、按当前模板重落(3)、date_skipped
# 计入结果、审计事件 TRANSFER_PENDING_MATCH_REPARSED 落库且 payload 完整
# (operator/source_code/files/profile/cleared/reinserted/date_skipped/kept)。
source, profile, file_a, file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 300, "2026-08-05"],
])
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([
["ASN-B1", "1", "I", "MAT-3", "模块", "LOT-3", 700, "2026-08-06"],
])
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id,
sha=OLD_SHA, quantity="1")
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id,
sha=OLD_SHA, quantity="2")
factories.seed_reparse_ledger_row(SOURCE, "ASN-B1", source_file_id=file_b.id,
sha=OLD_SHA, quantity="3")
assert _count_ledger() == 3
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert (outcome.cleared, outcome.reinserted) == (3, 3) # [断言意图] 清 3 落 3
assert outcome.date_skipped == 0 and outcome.kept_unrebuildable == 0
assert _count_ledger() == 3 # [断言意图] 无重复无丢失
db.session.expire_all()
a1 = TransferMovementLedger.query.filter_by(
source_code=SOURCE, doc_no="ASN-A1").one()
# [断言意图] 新映射值生效:业务值来自当前归档重解析,溯源换新文件三元组
# (真实 source_file_id / sha256: 版本戳),不再是旧映射值。
assert a1.quantity == "500" and a1.material_code == "MAT-1"
assert a1.file_sha256 == SHA_A and a1.source_file_id == file_a.id
# [断言意图] 重建写入的版本戳走 movement_file_version,与运行期落档同一串。
assert a1.file_version == movement_file_version(SHA_A)
assert a1.movement_date == "2026-08-05"
# [断言意图] 文件顺序:按归档时间升序逐文件重落(files 概要 A 在前)。
assert [f["sha256"] for f in outcome.files] == [SHA_A, SHA_B]
assert [f["inserted"] for f in outcome.files] == [2, 1]
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert event.aggregate_type == "transfer_source"
assert event.aggregate_id == SOURCE
payload = event.after_json
assert payload["operator"] == "admin" and payload["source_code"] == SOURCE
assert payload["record_kind"] == "inbound"
assert payload["cleared"] == 3 and payload["reinserted"] == 3
assert payload["date_skipped"] == 0 and payload["kept"] == 0
assert payload["profile_code"] == profile.profile_code
assert payload["profile_version"] == 1
assert [f["sha256"] for f in payload["files"]] == [SHA_A, SHA_B]
def test_abort_on_parse_failure_deletes_nothing(app, archive_storage):
# [断言意图] 安全不变量:任一归档解析失败(坏表头→必填缺失)→ 整体中止
# TRANSFER.REPARSE_PARSE_FAILED,一行未删、无审计事件(先解析后删除)。
_source, _profile, file_a, file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
])
# 坏文件:料号可映射但缺单号列 → 行级 missing_invoice_no → 解析必失败。
# 【不能用全垃圾表头】料号空行按 2026-10-21 规则静默跳过(不做管控不进
# 异动表),表头全不匹配的文件会以 0 行成功收场,不再触发中止。
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx(
[["MAT-BAD"]], headers=["料号"])
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id, sha=OLD_SHA)
factories.seed_reparse_ledger_row(SOURCE, "ASN-B1", source_file_id=file_b.id, sha=OLD_SHA)
with pytest.raises(AppError) as exc_info:
reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert exc_info.value.code == "TRANSFER.REPARSE_PARSE_FAILED"
# [断言意图] 中止详情可精确定位失败文件:details 逐项断言(来源/文件身份/
# 失败原因),不得用 or 短路式恒真断言掩盖缺键。
details = exc_info.value.details
assert details["source_code"] == SOURCE
assert details["sha256"] == SHA_B # 失败文件=坏表头那份
assert details["storage_key"] == f"archive/{SOURCE}/b.xlsx"
assert details["file_id"] == file_b.id
assert "missing_invoice_no" in details["reason"] # 行级失败原因透传
assert _count_ledger() == 3 # [断言意图] 一行未删
assert TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).count() == 0
def test_sealed_and_occupied_rows_survive(app, archive_storage):
# [断言意图] 删除范围三重过滤:封存行(transfer_executed=true)不动不复活;
# 被有效 items 占用行不被删除(item 引用保持有效),重落按常规幂等语义
# 走原行更新(新映射值生效、无第二行)。
_source, _profile, file_a, _file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 600, "2026-08-05"],
])
# 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([])
sealed_at = datetime(2026, 10, 2, 8, 0, 0)
sealed = factories.seed_reparse_ledger_row(
SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA, quantity="1",
transfer_executed=True, executed_doc_no="TRF-9", updated_at=sealed_at)
occupied = factories.seed_reparse_ledger_row(
SOURCE, "ASN-A2", line_no="1", in_out_flag="I", lot_no="LOT-2",
source_file_id=file_a.id, sha=OLD_SHA, quantity="2")
db.session.add(TransferInvoiceItem(
matching_id=None, ledger_record_id=occupied.id, source_code=SOURCE,
invoice_no="ASN-A2", material_no="MAT-OLD", from_warehouse="W1",
to_warehouse="W2", movement_quantity="2", status="matching",
result_code="pending_stock_check",
))
db.session.commit()
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert outcome.cleared == 0 # [断言意图] 无可删行
assert outcome.reinserted == 0 # [断言意图] 封存跳过+占用原行更新
assert _count_ledger() == 2 # [断言意图] 无新增行
db.session.expire_all()
sealed_after = TransferMovementLedger.query.filter_by(id=sealed.id).one()
assert sealed_after.transfer_executed is True
assert sealed_after.executed_doc_no == "TRF-9"
assert sealed_after.quantity == "1" # [断言意图] 封存行零写入
occupied_after = TransferMovementLedger.query.filter_by(id=occupied.id).one()
assert occupied_after.quantity == "600" # [断言意图] 占用行走更新分支换新映射
assert occupied_after.file_sha256 == SHA_A
item = TransferInvoiceItem.query.filter_by(ledger_record_id=occupied.id).one()
assert item.result_code == "pending_stock_check" # [断言意图] item 引用仍然有效
def test_unrebuildable_rows_kept_and_reported(app, archive_storage):
# [断言意图] 证据缺失行保留并计入 kept_unrebuildable:归档已过保留期
# (repository 可用清单排除)或无溯源(source_file_id=NULL)的行原样留存。
source, _profile, file_a, _file_b = _seed_world()
expired = factories.seed_reparse_archive_file(
source, sha=SHA_GONE, storage_key=f"archive/{SOURCE}/gone.xlsx",
created_at=datetime(2026, 10, 9, 8, 0, 0),
archive_expires_at=datetime(2026, 10, 14, 0, 0, 0)) # NOW 前已过保留期
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
])
# 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([])
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
factories.seed_reparse_ledger_row(SOURCE, "ASN-X", source_file_id=expired.id,
sha=SHA_GONE, quantity="9")
factories.seed_reparse_ledger_row(SOURCE, "ASN-Y", source_file_id=None,
sha=None, quantity="8")
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert (outcome.cleared, outcome.reinserted) == (1, 1) # [断言意图] 仅可重建行被清/重落
assert outcome.kept_unrebuildable == 2 # [断言意图] 证据缺失=2 行
db.session.expire_all()
kept_x = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-X").one()
kept_y = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-Y").one()
assert kept_x.quantity == "9" and kept_x.file_sha256 == SHA_GONE # [断言意图] 原样留存
assert kept_y.quantity == "8" and kept_y.file_sha256 is None
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert event.after_json["kept"] == 2
def test_preview_shape(app, archive_storage):
# [断言意图] 预检形状:files(archived_at/sha256/预估行数,按归档时间升序)、
# profile{code,version}、clearable_rows(可重建可清除)与 kept_rows(证据缺失
# 保留)与执行口径 1:1;只读(不删行、不落审计、不重落)。
source, profile, file_a, file_b = _seed_world()
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
factories.seed_reparse_ledger_row(SOURCE, "ASN-A2", source_file_id=file_a.id,
sha=OLD_SHA, transfer_executed=True,
executed_doc_no="TRF-8")
factories.seed_reparse_ledger_row(SOURCE, "ASN-Y", source_file_id=None,
sha=None, quantity="8")
preview = preview_pending_match_reparse(source_code=SOURCE, now=NOW)
assert set(preview.keys()) == {
"record_kind", "files", "profile", "clearable_rows", "kept_rows",
}
assert preview["record_kind"] == "inbound"
assert preview["profile"] == {"code": profile.profile_code, "version": 1}
assert [f["sha256"] for f in preview["files"]] == [SHA_A, SHA_B] # 归档时间升序
assert preview["files"][0]["archived_at"] == datetime(2026, 10, 10, 8, 0, 0).isoformat()
# [断言意图] 预估行数口径=现有档行按 source_file_id 计数(含封存;docstring 声明),
# 不在预检里解析归档字节。
assert preview["files"][0]["rows"] == 2 and preview["files"][1]["rows"] == 0
assert preview["clearable_rows"] == 1 # [断言意图] 仅未封存未占用有据行
assert preview["kept_rows"] == 1 # [断言意图] 证据缺失行计入保留
assert _count_ledger() == 3 # [断言意图] 预检只读零副作用
assert TransferAuditEvent.query.count() == 0
def test_reparse_aborts_without_published_profile(app, archive_storage):
# [断言意图] 无已发布入站规则=无重建通道:即使存在档行也整体中止
# (REPARSE_PARSE_FAILED),一行不删——防「删了装不回去」。
factories.seed_inbound_reparse_source(SOURCE, status="draft")
factories.seed_reparse_ledger_row(SOURCE, "ASN-A1", source_file_id=None, sha=None)
with pytest.raises(AppError) as exc_info:
reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert exc_info.value.code == "TRANSFER.REPARSE_PARSE_FAILED"
assert _count_ledger() == 1 # [断言意图] 一行未删
def test_cancelled_and_isolated_items_unlinked_before_delete(app, archive_storage):
# [断言意图] R9/方案 D(FK 悬挂修复):已取消匹配 items 与 blocked_file_removed
# 隔离 items 仍持有待删档行的 ledger_record_id(普通 FK 无 ondelete)——删除前
# 必须同事务置空,否则 PG flush 撞 IntegrityError 且此后每次重建复发。
# 范围严格限于待删集合:有效占用行不在删除集,其 items 引用保持不变。
_source, _profile, file_a, file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-A1", "1", "I", "MAT-1", "连接器", "LOT-1", 500, "2026-08-05"],
["ASN-A2", "1", "I", "MAT-2", "传感器", "LOT-2", 600, "2026-08-05"],
])
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([
["ASN-B1", "1", "I", "MAT-3", "模块", "LOT-3", 700, "2026-08-06"],
])
row_a1 = factories.seed_reparse_ledger_row(
SOURCE, "ASN-A1", source_file_id=file_a.id, sha=OLD_SHA)
row_a2 = factories.seed_reparse_ledger_row(
SOURCE, "ASN-A2", lot_no="LOT-2", source_file_id=file_a.id, sha=OLD_SHA)
row_b1 = factories.seed_reparse_ledger_row(
SOURCE, "ASN-B1", lot_no="LOT-3", source_file_id=file_b.id, sha=OLD_SHA)
# ① 已取消匹配的 item → 引用待删行 row_a1。
matching = TransferMatching(
matching_no="MTG-R9-1", business_date="2026-08-06", status="cancelled",
scope_json={}, file_snapshot_json={}, counts_json={}, matching_hash="sha256:r9",
)
db.session.add(matching)
db.session.flush()
cancelled_item = TransferInvoiceItem(
matching_id=matching.id, ledger_record_id=row_a1.id, source_code=SOURCE,
invoice_no="ASN-A1", material_no="MAT-OLD", from_warehouse="W1",
to_warehouse="W2", movement_quantity="1", status="cancelled",
)
# ② 失效隔离 item(blocked_file_removed 不构成占用)→ 引用待删行 row_a2。
isolated_item = TransferInvoiceItem(
matching_id=None, ledger_record_id=row_a2.id, source_code=SOURCE,
invoice_no="ASN-A2", material_no="MAT-OLD", from_warehouse="W1",
to_warehouse="W2", movement_quantity="2", status="cancelled",
result_code="blocked_file_removed",
)
# ③ 对照:有效占用 item(普通 pending 引用即占用)→ row_b1 不在删除集。
occupied_item = TransferInvoiceItem(
matching_id=None, ledger_record_id=row_b1.id, source_code=SOURCE,
invoice_no="ASN-B1", material_no="MAT-OLD", from_warehouse="W1",
to_warehouse="W2", movement_quantity="3", status="matching",
result_code="pending_stock_check",
)
db.session.add_all([cancelled_item, isolated_item, occupied_item])
db.session.commit()
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
# [断言意图] 删除成功(无 FK IntegrityError)且仅删未占用两行;解绑计数=2。
assert (outcome.cleared, outcome.reinserted) == (2, 2)
assert outcome.unlinked_items == 2
db.session.expire_all()
# [断言意图] 待删行的两枚废弃 items 引用被置空(溯源装饰让位于可重建性)。
assert TransferInvoiceItem.query.filter_by(id=cancelled_item.id).one().ledger_record_id is None
assert TransferInvoiceItem.query.filter_by(id=isolated_item.id).one().ledger_record_id is None
# [断言意图] 占用行不在删除集:行原样幸存(原行更新换新映射),其 item 引用
# 仍指向同一档行 id——有效匹配的圈定关系不受重建波及。
row_b1_after = TransferMovementLedger.query.filter_by(id=row_b1.id).one()
assert row_b1_after.quantity == "700" and row_b1_after.file_sha256 == SHA_B
assert TransferInvoiceItem.query.filter_by(id=occupied_item.id).one().ledger_record_id == row_b1.id
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert event.after_json["unlinked_items"] == 2
def test_reparse_writes_collapse_audit_for_multi_material_same_key(app, archive_storage):
# [断言意图] 终审遗留(坍缩审计接重建路径):重建与运行期同一坍缩守卫——同自然键
# 六成分批内双料号(行级项次全空)重落时第二料号行仍被幂等吞掉(首见为准,
# 行为与运行期一致),但必须落 ledger_natural_key_collapse 审计事件——改模板
# 后的清空重建恰是坍缩易发时刻,静默吞行必须显式可观测;重建概要审计携带
# collapses 计数。
_source, _profile, file_a, _file_b = _seed_world()
archive_storage.objects[f"archive/{SOURCE}/a.xlsx"] = factories.build_movement_xlsx([
["ASN-C1", "1", "I", "MAT-X", "物料甲", "LOT-9", 500, "2026-08-05"],
["ASN-C1", "1", "I", "MAT-Y", "物料乙", "LOT-9", 300, "2026-08-05"],
])
# 文件 B 可用但无数据行(仅表头):不参与断言,只为预解析通道完整。
archive_storage.objects[f"archive/{SOURCE}/b.xlsx"] = factories.build_movement_xlsx([])
factories.seed_reparse_ledger_row(SOURCE, "ASN-C1", lot_no="LOT-9",
source_file_id=file_a.id, sha=OLD_SHA)
outcome = reparse_pending_match(source_code=SOURCE, operator="admin", now=NOW)
assert (outcome.cleared, outcome.reinserted) == (1, 1) # [断言意图] 旧行清 1、重落仅首见 1 行
assert outcome.collapses == 1 # [断言意图] 坍缩键计数进结果
db.session.expire_all()
rows = TransferMovementLedger.query.filter_by(source_code=SOURCE, doc_no="ASN-C1").all()
assert len(rows) == 1 and rows[0].material_code == "MAT-X" # [断言意图] 首见为准吞行不丢账
# [断言意图] 坍缩审计事件落库且与运行期同构造:定位单号、failure 级、料号可追溯。
event = TransferAuditEvent.query.filter_by(
event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).one()
assert "ASN-C1" in event.aggregate_id
assert event.result == "failure"
assert event.after_json["material_codes"] == ["MAT-X", "MAT-Y"]
assert event.after_json["dropped_material_codes"] == ["MAT-Y"]
assert event.after_json["resolution"] == "first_seen_wins"
# [断言意图] 重建概要事件携带坍缩计数(运维一眼判断本次重建是否有数据质量降级)。
reparse_event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert reparse_event.after_json["collapses"] == 1
def test_outbound_reparse_clears_and_relands_without_touching_inbound(app, archive_storage):
"""出站流清空重建:只动 record_kind=outbound,入站档行幸存。"""
source, profile = factories.seed_outbound_reparse_source(SOURCE)
out_file = factories.seed_reparse_outbound_archive_file(
source, sha=SHA_A, storage_key=f"archive/{SOURCE}/out-a.xlsx",
created_at=datetime(2026, 10, 10, 8, 0, 0),
)
archive_storage.objects[f"archive/{SOURCE}/out-a.xlsx"] = factories.build_movement_xlsx([
["HOX-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-08-05"],
])
# 入站旧行 + 出站旧行并存:出站重建不得误删入站。
factories.seed_reparse_ledger_row(
SOURCE, "ASN-IN1", source_file_id=None, sha=OLD_SHA, record_kind="inbound",
)
factories.seed_reparse_ledger_row(
SOURCE, "HOX-O1", source_file_id=out_file.id, sha=OLD_SHA,
quantity="1", record_kind="outbound", in_out_flag="O",
)
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="inbound").count() == 1
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 1
outcome = reparse_pending_match(
source_code=SOURCE, operator="admin", now=NOW, record_kind="outbound",
)
assert outcome.record_kind == "outbound"
assert (outcome.cleared, outcome.reinserted) == (1, 1)
db.session.expire_all()
# [断言意图] 入站行未动;出站行按新映射重落。
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="inbound", doc_no="ASN-IN1").count() == 1
out_row = TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound", doc_no="HOX-O1").one()
assert out_row.quantity == "120" and out_row.material_code == "MAT-O1"
assert out_row.source_file_id == out_file.id and out_row.file_sha256 == SHA_A
# [断言意图] 出站重建的版本戳同样走共享函数。
assert out_row.file_version == movement_file_version(SHA_A)
event = TransferAuditEvent.query.filter_by(event_type=REPARSE_EVENT).one()
assert event.after_json["record_kind"] == "outbound"
assert event.after_json["profile_code"] == profile.profile_code
def test_outbound_preview_uses_outbound_archives(app, archive_storage):
"""出站预检只统计 outbound 归档与档行。"""
source, profile = factories.seed_outbound_reparse_source(SOURCE)
out_file = factories.seed_reparse_outbound_archive_file(
source, sha=SHA_A, storage_key=f"archive/{SOURCE}/out-preview.xlsx",
created_at=datetime(2026, 10, 10, 8, 0, 0),
)
factories.seed_reparse_ledger_row(
SOURCE, "HOX-P1", source_file_id=out_file.id, sha=SHA_A, record_kind="outbound",
)
preview = preview_pending_match_reparse(
source_code=SOURCE, now=NOW, record_kind="outbound",
)
assert preview["record_kind"] == "outbound"
assert preview["profile"] == {"code": profile.profile_code, "version": 1}
assert preview["clearable_rows"] == 1
assert len(preview["files"]) == 1 and preview["files"][0]["sha256"] == SHA_A
@@ -28,7 +28,7 @@ def _blocked_matching(dbs_ready_file):
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # 1200 ≠ 1000 → blocked
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
return summary
@@ -44,7 +44,7 @@ def test_aging_level_thresholds():
def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file):
"""待处理池收纳 blocked_recoverable,排除 success / not_matured。"""
"""待处理池收纳 blocked_recoverable,排除 success(not_matured 已退役)。"""
_blocked_matching(dbs_ready_file)
items = list_backlog()
invoice_set = {item.invoice_no for item in items}
@@ -59,14 +59,14 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file):
updated_at 会让正在处理的行跳位(用户实测:恢复后被处理的行跳到列表末尾)。
业务稳定键下,触碰前后列表顺序完全一致。
"""
_blocked_matching(dbs_ready_file) # HOM-001(receipt 2026-08-05)与 HOX-002 不进池,构造两笔 blocked
_blocked_matching(dbs_ready_file) # HOM-001(inbound 2026-08-04)与 HOX-002 不进池,构造两笔 blocked
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
# 手工造第二笔 blocked:不同收料日期、更晚创建
second = TransferInvoiceItem(
matching_id=item.matching_id, source_code=item.source_code,
invoice_no="HOM-002", material_no="MAT-003", material_name="垫片",
receipt_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
receipt_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found",
movement_date="2026-08-01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
movement_quantity="10", status="blocked_recoverable", result_code="blocked_inventory_not_found",
)
db.session.add(second)
db.session.commit()
@@ -75,7 +75,7 @@ def test_backlog_order_stable_across_requery_touch(transfer_db, dbs_ready_file):
db.session.commit()
invoices = [dto.invoice_no for dto in list_backlog()]
# 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-05),尽管它刚被触碰过
# 排序只看业务键:HOM-002 收料日期(08-01) 早于 HOM-001(08-04),尽管它刚被触碰过
# (两行同来源,数据源键不改变先后)。
assert invoices == ["HOM-002", "HOM-001"]
@@ -119,3 +119,28 @@ def test_list_backlog_exposes_result_code(transfer_db, dbs_ready_file):
# 未打标的结果码为 None(普通阻断行不受影响)。
others = [entry for entry in items if entry.invoice_no != "HOM-001"]
assert all(entry.result_code is None for entry in others)
def test_backlog_summary_includes_pending_match_count(transfer_db, dbs_ready_file):
"""[断言意图·Task 12 D16] 汇总带「待匹配」桶计数(首页第 4 张数字卡):
已落档且无有效 items 的收料记录计入,行桶(可恢复/已关闭)语义保持不变。"""
_blocked_matching(dbs_ready_file)
# 直接种子一条未匹配档记录(默认类型范围 HOM 前缀;无 items 引用)。
from app.models import TransferMovementLedger
db.session.add(TransferMovementLedger(
source_code="DBS-AWSBI", record_kind="inbound",
doc_no="HOM-901", line_no="1", line_seq="", in_out_flag="",
material_code="MAT-9", material_name="未匹配物料", specification="",
lot_no="LOT-9", quantity="55", unit="PCS",
warehouse_code="", storage_code="", movement_date="2026-08-04",
file_version="v1", file_sha256="a" * 64,
sheet_name="Receipt", row_no=9,
))
db.session.commit()
summary = backlog_summary()
assert summary.pending_match_count == 1 # [断言意图] 待匹配桶计数独立于行桶
assert summary.matchable_count == 1 # [断言意图] 范围内未匹配行同时计入可匹配
assert summary.recoverable_count == 1 # [断言意图] 原行桶语义保持
@@ -28,7 +28,7 @@ def _seed(dbs_ready_file):
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 → blocked
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
return deps, erp, blocked
@@ -24,7 +24,7 @@ def _ready_matching(dbs_ready_file):
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
items = (
db.session.query(TransferInvoiceItem)
.filter_by(status="ready_to_execute")
@@ -65,3 +65,53 @@ def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file, patch_so
assert items["HOM-001"].status == "success" # 已成功单据保留
assert items["HOX-002"].status == "cancelled" # 未开始项取消
assert result["cancelled_count"] == 1
def test_cancel_matching_retires_ready_rows_and_releases_ledger(transfer_db, dbs_ready_file):
"""[Critical-2] 取消匹配:ready 行按 matching_id 退役(队列/执行门禁双拒),
档记录释放后可被新匹配重圈——同批档记录不产生双份可执行行。"""
from app.models import TransferMatching
from app.services.in_transit_transfer.matching_service import list_executable_items
deps, items = _ready_matching(dbs_ready_file)
ready_ids = [item.id for item in items]
assert len(ready_ids) == 2
matching_a = TransferMatching.query.filter(
TransferMatching.id == items[0].matching_id).one()
result = cancel_run(run_no=matching_a.run.run_no, reason="业务裁定不拨")
# [断言意图] 出生行 run_id=None:取消必须按 matching_id 圈定才能退役 ready 行。
rows = {row.id: row for row in db.session.query(TransferInvoiceItem).filter_by(
matching_id=matching_a.id).all()}
assert result["cancelled_count"] == 2
assert all(rows[i].status == "cancelled" for i in ready_ids)
db.session.refresh(matching_a)
assert matching_a.status == "cancelled"
# [断言意图] 队列不再出现 A 的行(可执行面清零)。
payload = list_executable_items(deps=deps)
assert payload["counts"]["executable_count"] == 0
# [断言意图·防御双保险] 模拟绕过取消路径的残留 ready 行(匹配已取消):
# 队列不展示 + 执行门禁拒绝(EXECUTE_ITEMS_INVALID)。
zombie = rows[ready_ids[0]]
zombie.status = "ready_to_execute"
zombie.result_code = None
db.session.commit()
payload = list_executable_items(deps=deps)
assert all(item.item_id != zombie.id for item in payload["items"])
with pytest.raises(ValidationError) as gate:
execute_items(item_ids=[zombie.id], deps=deps)
assert gate.value.code == "TRANSFER.EXECUTE_ITEMS_INVALID"
# [断言意图·D17 释放] 取消已释放档记录占用(A 的行→cancelled、匹配→cancelled):
# 匹配 B 出生翻转时重圈同批档记录、重建 2 行——新行绑定 matching B,
# ledger_record_id 与 A 的退役行同源,但行身份独立(一生一次绑定随取消重置)。
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
matching_b = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
born_b = db.session.query(TransferInvoiceItem).filter_by(matching_id=matching_b.id).all()
assert len(born_b) == 2
assert {row.ledger_record_id for row in born_b} == {
row.ledger_record_id for row in rows.values()}
@@ -78,6 +78,7 @@ def test_matching_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
events = list(TransferMatchAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_MATCH, {
"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06",
"transfer_type": "in_transit_to_hub",
})))
assert len(events) == 1
event = events[0]
@@ -103,7 +104,8 @@ def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeyp
# 先跑匹配拿 matching_id
matching_events = list(TransferMatchAction().stream(_ctx(
"in_transit_transfer", ACTION_TRANSFER_MATCH,
{"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06"},
{"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06",
"transfer_type": "in_transit_to_hub"},
)))
matching_id = matching_events[0].data["payload"]["summary"]["matching_id"]
@@ -29,7 +29,6 @@ pytestmark = pytest.mark.pure_unit
EXPECTED_ERROR_CODES = {
"TRANSFER_PERMISSION_DENIED",
"TRANSFER_RECEIPT_NOT_MATURED",
"TRANSFER_FILE_NOT_READY",
"TRANSFER_FILE_SCHEMA_INVALID",
"TRANSFER_INVOICE_CONFLICT",
@@ -67,13 +66,13 @@ def test_require_known_error_code_rejects_unknown():
def test_matching_counts_dto_fields():
"""匹配计数 DTO 包含文件内/未成熟/已匹配/可执行/阻断五类计数。"""
"""匹配计数 DTO 包含文件内/已匹配/可执行/阻断等计数(not_matured 已退役)。"""
counts = MatchingCountsDTO(
file_invoice_count=40, not_matured_count=8, matched_count=32,
file_invoice_count=40, matched_count=32,
executable_count=27, blocked_count=5,
)
assert counts.executable_count == 27
assert counts.not_matured_count == 8
assert counts.matched_count == 32
def test_matching_summary_dto_carries_estimate_and_hash():
@@ -82,9 +81,8 @@ def test_matching_summary_dto_carries_estimate_and_hash():
matching_id="MTG-20260806-001",
status="ready_to_execute",
business_date="2026-08-06",
eligible_receipt_date_to="2026-08-05",
expires_at="2026-08-06T09:20:00+08:00",
counts=MatchingCountsDTO(40, 8, 32, 27, 5),
counts=MatchingCountsDTO(40, 32, 27, 5),
estimated_transfer_quantity="18460",
estimated_external_write_count=27,
matching_hash="sha256:abc",
@@ -0,0 +1,277 @@
"""current_file_reparse:当前归档重解析(不触发 RPA)守卫矩阵。
用途:锁定「当前最新可用入站/出站归档本地重解析落档」——成功落档、幂等跳过、
入站/出站 schema 失败标 parse_failed、无规则/无文件 fail-closed、
非 schema 异常与存储 AppError 回 ok=false 且不回标。
依赖:factories、movement_file_version、app fixture、core.errors.ServiceUnavailableError;
出站种子 DSV360_AWSDU,入站种子 seed_inbound_reparse_source。
逻辑:归档字节经假存储注入;不新增 RPA 执行单元。
"""
from __future__ import annotations
import logging
from datetime import datetime
import pytest
from app import db
from app.core.errors import AppError, ServiceUnavailableError
from app.models import (
FreightRpaInboundReportFile,
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
FreightRpaParsingProfile,
TransferAuditEvent,
TransferMovementLedger,
)
from app.services.in_transit_transfer.current_file_reparse import reparse_current_file
from app.services.in_transit_transfer.ledger_sync import movement_file_version
from tests.services.in_transit_transfer import factories
pytestmark = [pytest.mark.usefixtures("app")]
SOURCE = "DSV360_AWSDU"
STORAGE_KEY = "shipping/outbound/evidence-sync.xlsx"
@pytest.fixture
def outbound_storage(monkeypatch):
"""归档假存储:替换单例 get_bytes(所有引用方同源)。"""
fake = factories.FakeArchiveStorage()
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
return fake
@pytest.fixture
def archive_storage(monkeypatch):
"""归档假存储:注入 FakeArchiveStorage 并替换单例 get_bytes(所有引用方同源)。"""
fake = factories.FakeArchiveStorage()
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
return fake
def _seed_outbound_world(*, profile_status: str = "published") -> FreightRpaOutboundReportFile:
"""出站世界种子:出站配置(绑定解析规则)+ 执行单元 + 当天可用归档文件行。
Returns:
已入库的 FreightRpaOutboundReportFile(字节由用例注入假存储)。
"""
from app.models import FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SOURCE).one()
profile = FreightRpaParsingProfile(
purpose="outbound", profile_code=f"OUT_{SOURCE}", display_name=SOURCE,
version=1, status=profile_status, file_format="xlsx",
definition_json={
"field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING,
"sheet_name": "Receipt", "header_row_index": 1,
},
structure_definition_json={},
)
db.session.add(profile)
db.session.flush()
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={"report_name": "Outbound"},
query_parameters_json=[],
parsing_profile_id=profile.id,
))
unit = FreightRpaOutboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=SOURCE,
connector_type="dbs", warehouse_id="AWSDU", callback_id="outbound-sync-001",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
import hashlib
digest = hashlib.sha256(b"outbound evidence workbook").hexdigest()
report = FreightRpaOutboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=STORAGE_KEY, original_filename="outbound-sync.xlsx",
file_size=16, sha256=digest,
created_at=datetime.utcnow(),
)
db.session.add(report)
db.session.commit()
return report
def test_reparse_outbound_inserts_ledger_without_new_rpa_run(outbound_storage):
# [断言意图] 已落地出站文件重解析后出现 outbound 档行,且不新增出站执行单元。
report = _seed_outbound_world()
runs_before = FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is True
assert result.file_id == report.id
assert result.inserted == 1
assert result.file_status == "ready"
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound", doc_no="ASN-O1").count() == 1
assert FreightRpaOutboundUnitRun.query.filter_by(source_code=SOURCE).count() == runs_before
assert TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").count() == 1
def test_reparse_same_outbound_file_skips_existing_row(outbound_storage):
# [断言意图] 同一份摘要再解析一次不插入第二行。
_seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
again = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert again.ok is True
assert again.inserted == 0
assert again.skipped == 1
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 1
def test_reparse_schema_failure_marks_file_and_lands_nothing(outbound_storage):
# [断言意图] 单号缺失是结构失败:零档行,文件变为 parse_failed,响应带原因。
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx(
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is False
assert result.file_status == "parse_failed"
assert result.inserted == 0
assert "missing_invoice_no" in (result.error_message or "")
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is not None
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 0
def test_reparse_without_published_profile_does_not_mark_parse_failed(outbound_storage):
# [断言意图] 规则未发布不是文件错误,不写 parse_failed。
report = _seed_outbound_world(profile_status="draft")
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
with pytest.raises(AppError) as exc_info:
reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE"
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is None
def test_reparse_without_file_raises():
# [断言意图] 没有可用归档时拒绝,而不是去触发 RPA。
with pytest.raises(AppError) as exc_info:
reparse_current_file(
source_code="DSV360_AWSDU", record_kind="outbound", now=datetime.utcnow())
assert exc_info.value.code == "TRANSFER.CURRENT_REPARSE_NO_FILE"
assert exc_info.value.http_status == 422
def test_reparse_non_schema_error_does_not_mark_parse_failed(outbound_storage, monkeypatch, caplog):
# [断言意图] 数据库一类异常回滚后不把文件标成解析失败,并把异常文本带回。
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
def _boom(**_kwargs):
raise RuntimeError("value too long for varchar(64)")
monkeypatch.setattr(
"app.services.in_transit_transfer.current_file_reparse.sync_outbound_source_rows",
_boom,
)
with caplog.at_level(logging.ERROR):
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is False
assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED"
assert "varchar(64)" in (result.error_message or "")
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is None
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 0
assert any(
"TRANSFER_CURRENT_REPARSE_FAILED" in record.message and "kind=outbound" in record.message
for record in caplog.records
)
def test_reparse_storage_unavailable_returns_ok_false(outbound_storage, monkeypatch):
# [断言意图] 存储读抛 ServiceUnavailableError 时走 ok=false,不把文件标成解析失败。
report = _seed_outbound_world()
def _unavailable(_storage_key: str) -> bytes:
raise ServiceUnavailableError("object storage unreachable")
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes",
_unavailable,
)
result = reparse_current_file(source_code=SOURCE, record_kind="outbound", now=datetime.utcnow())
assert result.ok is False
assert result.error_code == "TRANSFER.CURRENT_REPARSE_FAILED"
assert "object storage unreachable" in (result.error_message or "")
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is None
assert TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").count() == 0
def test_reparse_inbound_inserts_ledger(archive_storage):
# [断言意图] 入站当前文件走 sync_source_rows,record_kind 为 inbound。
source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_NOW")
storage_key = "archive/CRANE_REPARSE_NOW/current.xlsx"
report = factories.seed_reparse_archive_file(
source, sha="c" * 64, storage_key=storage_key, created_at=datetime.utcnow())
archive_storage.objects[storage_key] = factories.build_movement_xlsx([
["ASN-I1", "1", "I", "MAT-I1", "连接器", "LOT-I1", 10, "2026-08-05"],
])
result = reparse_current_file(
source_code="CRANE_REPARSE_NOW", record_kind="inbound", now=datetime.utcnow())
assert result.ok is True
assert result.file_id == report.id
assert result.inserted == 1
row = TransferMovementLedger.query.filter_by(
source_code="CRANE_REPARSE_NOW", record_kind="inbound").one()
assert row.doc_no == "ASN-I1"
assert row.file_version == movement_file_version("c" * 64)
def test_reparse_inbound_schema_failure_marks_file_and_lands_nothing(archive_storage):
# [断言意图] 入站单号缺失是结构失败:零档行,入站文件变为 parse_failed。
source, _profile = factories.seed_inbound_reparse_source("CRANE_REPARSE_SCHEMA")
storage_key = "archive/CRANE_REPARSE_SCHEMA/current.xlsx"
report = factories.seed_reparse_archive_file(
source, sha="d" * 64, storage_key=storage_key, created_at=datetime.utcnow())
archive_storage.objects[storage_key] = factories.build_movement_xlsx(
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
result = reparse_current_file(
source_code="CRANE_REPARSE_SCHEMA", record_kind="inbound", now=datetime.utcnow())
assert result.ok is False
assert result.file_status == "parse_failed"
assert result.inserted == 0
assert "missing_invoice_no" in (result.error_message or "")
marked = FreightRpaInboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is not None
assert TransferMovementLedger.query.filter_by(
source_code="CRANE_REPARSE_SCHEMA", record_kind="inbound").count() == 0
@@ -1,9 +1,12 @@
"""在途调拨日期成熟度策略测试(L0 纯单元)。
"""在途调拨业务日期与日期解析测试(L0 纯单元)。
用途:验证 T+lag 成熟规则(默认 T+2)、当天/T-1 not_matured、未来日期阻断与上海业务时区;
以及 parse_date 对 ISO / 美式 MM/DD/YYYY 收料日期的归一化。
用途:验证 parse_date 对 ISO / 美式 MM/DD/YYYY 异动日期的归一化与上海业务时区
换算(business_date_now / business_date_utc_window)。
依赖:app.services.in_transit_transfer.date_policy(纯函数)。
逻辑:全部断言只依赖业务日期与收料日期,不接触 Flask/DB(pure_unit)。
逻辑:全部断言只依赖入参日期,不接触 Flask/DB(pure_unit)。
【成熟度规则已退役 2026-10-16】原 T+lag 成熟策略用例随概念一并删除;
日期边界现在由调用方入参给定(交互=用户范围,排程=T−N 偏移参数),
引擎仅保留「截止 ≤ 业务日期」入参校验(matching_service 用例覆盖)。
"""
from __future__ import annotations
@@ -16,63 +19,11 @@ import pytest
from app.services.in_transit_transfer.date_policy import (
business_date_now,
business_date_utc_window,
eligible_receipt_date_to,
maturity_status,
parse_date,
)
pytestmark = pytest.mark.pure_unit
BUSINESS_T = date(2026, 8, 6)
def test_same_day_receipt_is_not_matured():
"""当天收料必须返回 not_matured;成熟门禁不查询 外部系统(调用次数由服务层保证为 0)。"""
assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured"
def test_yesterday_receipt_is_not_matured():
"""T+2 默认:昨天(T-1)收料尚未成熟(海外时差:28 号最早处理 26 号)。"""
assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "not_matured"
def test_t_minus_2_receipt_is_eligible():
"""T+2 默认:前天(T-2)收料起可预检(纯单元无 app 上下文 → 回退默认 lag=2)。"""
assert maturity_status(date(2026, 8, 4), BUSINESS_T) == "eligible"
def test_older_receipt_is_eligible():
"""更早收料同样可预检。"""
assert maturity_status(date(2026, 8, 1), BUSINESS_T) == "eligible"
def test_future_receipt_is_blocked():
"""未来日期收料返回结构化阻断值。"""
assert maturity_status(date(2026, 8, 7), BUSINESS_T) == "future"
def test_maturity_status_accepts_iso_strings():
"""字符串日期与 date 对象等价。"""
assert maturity_status("2026-08-04", "2026-08-06") == "eligible"
assert maturity_status("2026-08-05", "2026-08-06") == "not_matured"
assert maturity_status("2026-08-06", "2026-08-06") == "not_matured"
def test_explicit_lag_days_overrides_default():
"""显式 lag=1 复现旧 T+1 口径(兼容回滚与测试钉值场景)。"""
assert maturity_status(date(2026, 8, 5), BUSINESS_T, lag_days=1) == "eligible"
assert maturity_status(date(2026, 8, 6), BUSINESS_T, lag_days=1) == "not_matured"
def test_eligible_receipt_date_to_is_t_minus_two():
"""可调拨收料截止日期 = 业务日期 - 2 天(默认 lag)。"""
assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 4)
def test_eligible_receipt_date_to_explicit_lag():
"""显式 lag=1 时截止 = 业务日期 - 1 天。"""
assert eligible_receipt_date_to(BUSINESS_T, lag_days=1) == date(2026, 8, 5)
def test_business_date_now_uses_shanghai_across_utc_midnight():
"""UTC 17:00(北京时间次日 01:00)业务日期不得漂移回 UTC 日期。"""
@@ -108,17 +59,11 @@ def test_business_date_utc_window_maps_shanghai_day_to_utc():
assert (end_next - start_next).total_seconds() == 24 * 3600
def test_invalid_date_string_raises():
"""非法日期字符串必须抛 ValueError,不得静默解析。"""
with pytest.raises(ValueError):
maturity_status("2026/13/99", BUSINESS_T)
def test_parse_date_accepts_us_mdy_with_time():
"""DSV SSRS Date Received(美式带时分秒)须解析为业务 date。
[断言意图] 收料文件常见 '08/13/2026 13:08:00';仅认 ISO 会导致
evidence_sync 整链 invalid_receipt_date,transfer_invoice_items 零写入。
[断言意图] 异动文件常见 '08/13/2026 13:08:00';仅认 ISO 会导致
evidence_sync 整链 invalid_movement_date,transfer_invoice_items 零写入。
"""
assert parse_date("08/13/2026 13:08:00") == date(2026, 8, 13)
assert parse_date("6/11/2026 08:37:07") == date(2026, 6, 11)
@@ -33,7 +33,7 @@ def _failed_document(dbs_ready_file, patch_source_file_status):
for material, warehouse, lot in _INVOICE_TUPLES.values():
erp.seed_stock(material, warehouse, lot, "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
patch_source_file_status()
ready_ids = [
item.id for item in TransferInvoiceItem.query.filter_by(status="ready_to_execute").all()
@@ -1,12 +1,18 @@
"""证据同步三分类写入回归。
"""证据同步落档回归(出生翻转:断言对象=库存异动档)。
用途:锁死 evidence_sync 的核心语义——新行插入(待查态)、既有行按文件刷新、
值变重置库存侧、缺席行存续(只换戳不改状态)、终态行绝不触碰、全程零 ERP 调用;
解析失败分层(2026-09-29):同步成功清除当前可用文件的解析失败标记,
桥内 schema 类解析失败把失败事实独立 commit 落到当前可用文件上。
用途:锁死 evidence_sync 的核心语义——解析行按明细粒度聚合成领域行落档
(数量相加、首行溯源)、幂等(同文件重落完全不动行)、证据变原行更新
(业务值换新 + 溯源五列换新)、缺席不删、封存行永不更新永不复活、
全程零 ERP 调用;解析失败分层(2026-09-29):同步成功清除当前可用文件的
解析失败标记,桥内 schema 类解析失败把失败事实独立 commit 落到当前可用
文件上;桥隔离(异常不向收料回调链路传播、成功自行 commit);
档自然键坍缩守卫(终审 I3):同自然键批内料号不同的坍缩形态写
ledger_natural_key_collapse 审计事件(静默丢行 → 显式可观测,行处理不变)。
依赖:repo_fakes(Fake 文件仓库注入文件行)、app fixture。
逻辑:通过 Fake repository 的 latest_ready_file 提供文件;直接断言行级状态;
解析失败标记用例另建真实 ORM 收料单元/归档文件(当天业务日窗口内 → 可用)。
逻辑:通过 Fake repository 的 latest_ready_file 提供文件;断言对象从 items
平移到档(TransferMovementLedger,「档断言等价于原 items 断言」——
数量=旧 items 汇总值、行数=旧 items 汇总行数);解析失败标记用例另建
真实 ORM 收料单元/归档文件(当天业务日窗口内 → 可用)。
"""
from __future__ import annotations
@@ -17,12 +23,9 @@ from datetime import datetime
import pytest
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer.evidence_sync import (
SYNC_RESULT_PENDING,
align_scope_rows,
sync_source_rows,
)
from app.models import TransferAuditEvent, TransferInvoiceItem, TransferMovementLedger
from app.services.in_transit_transfer import evidence_sync
from app.services.in_transit_transfer.evidence_sync import sync_source_rows
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
pytestmark = [pytest.mark.usefixtures("app")]
@@ -30,10 +33,20 @@ pytestmark = [pytest.mark.usefixtures("app")]
NOW = datetime(2026, 9, 25, 10, 0, 0)
def _pending_count(source_code="DBS-AWSBI"):
"""统计某来源处于待查态(pending_stock_check)的行数。"""
return TransferInvoiceItem.query.filter_by(
source_code=source_code, result_code=SYNC_RESULT_PENDING).count()
def _ledger_rows(source_code="DBS-AWSBI") -> list[TransferMovementLedger]:
"""按自然键序取某来源全部档行(断言主对象)。"""
return (
TransferMovementLedger.query
.filter_by(source_code=source_code, record_kind="inbound")
.order_by(TransferMovementLedger.doc_no.asc(), TransferMovementLedger.id.asc())
.all()
)
def _by_doc(doc_no: str, source_code="DBS-AWSBI") -> TransferMovementLedger:
"""按单号取档行(fixture 内单号唯一)。"""
return TransferMovementLedger.query.filter_by(
source_code=source_code, doc_no=doc_no).one()
def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str):
@@ -44,24 +57,24 @@ def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str):
sha: 归档文件 sha256(与 Fake 仓库 checksum 保持同值,模拟同一份文件)。
callback_id: 收料执行单元回调键(唯一约束,用例间取不同值)。
Returns:
已入库的 ShippingReceiptReportFile。
已入库的 FreightRpaInboundReportFile。
"""
from app import db
from app.models import (
ShippingInventorySource,
ShippingReceiptReportFile,
ShippingReceiptRpaUnitRun,
FreightRpaSource,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
source = ShippingInventorySource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=source.id, source_code=source_code,
source = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = FreightRpaInboundUnitRun(
source_id=source.id, source_code=source_code,
connector_type="dbs", callback_id=callback_id,
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
report = ShippingReceiptReportFile(
report = FreightRpaInboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=f"shipping/receipt/{callback_id}.xlsx",
original_filename=f"{callback_id}.xlsx", file_size=16, sha256=sha,
@@ -71,198 +84,141 @@ def _seed_usable_report_file(*, source_code: str, sha: str, callback_id: str):
return report
def test_sync_inserts_pending_rows_without_erp(app, dbs_ready_file):
# [断言意图] 首次同步:文件行全部落库为待查态;ERP 能力零调用。
def test_sync_inserts_ledger_rows_without_erp(app, dbs_ready_file):
# [断言意图] 首次同步:解析行按明细粒度聚合落档(HOM-001 两行数量相加、
# HOX-002 单行),档行携带 record_kind/溯源;明细表不再落地(停写 items);
# ERP 能力零调用。
deps, erp, _ = make_transfer_deps(dbs_ready_file)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert outcome is not None and outcome.inserted > 0 # [断言意图] 有新行
assert outcome.absent_kept == 0
assert _pending_count() == outcome.inserted # [断言意图] 插入行全部待查态
row = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").first()
assert row.status == "matching" # [断言意图] 13 状态内的待查表达
assert row.result_code == SYNC_RESULT_PENDING
assert row.matching_id is None # [断言意图] 落地行尚无匹配归属
assert erp.query_calls == 0 # [断言意图] 零 ERP 调用
assert outcome is not None and outcome.inserted == 2 # [断言意图] 两张单各一条档行
rows = _ledger_rows()
assert len(rows) == 2
assert all(row.record_kind == "inbound" for row in rows)
hom = _by_doc("HOM-001")
# [断言意图] 数量聚合等价于旧 items 汇总断言:500+700=1200(档是匹配圈定的
# 数量真相源,与旧 items movement_quantity 等值)。
assert hom.quantity == "1200"
assert hom.material_code == "MAT-001" and hom.lot_no == "LOT-10"
assert hom.movement_date == "2026-08-04"
assert hom.file_version == "v3" and hom.file_sha256 == "d" * 64
assert hom.sheet_name == "Receipt" and hom.row_no == 10 # 组内首行溯源
assert TransferInvoiceItem.query.count() == 0 # [断言意图] 停写 items
assert erp.query_calls == 0 # [断言意图] 零 ERP 调用
def test_sync_is_idempotent_when_sha_unchanged(app, dbs_ready_file):
# [断言意图] 同文件重复同步:整行跳过,不续新鲜度、不产生新行。
# [断言意图] 同文件重复落档:全部跳过,档行完全不动(不续 updated_at、无新行)。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
before = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all()
stamps = [r.updated_at for r in before]
before = _ledger_rows()
stamps = [(r.id, r.updated_at, r.quantity) for r in before]
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
after = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all()
assert [r.id for r in after] == [r.id for r in before] # [断言意图] 不产生新行
assert [r.updated_at for r in after] == stamps # [断言意图] sha 一致零写入
assert outcome is not None and outcome.skipped == 2 # [断言意图] 幂等跳过计数
assert outcome.inserted == 0 and outcome.updated == 0
after = _ledger_rows()
assert [(r.id, r.updated_at, r.quantity) for r in after] == stamps # [断言意图] 零写入
def test_sync_keeps_absent_rows_and_never_touches_terminal(app, dbs_ready_file):
# [断言意图] 新版文件缺席的行 → 存续:状态/结果码原样保留,只换版本戳;
# 终态行保持既定事实。(收料 RPA 非全量导出:缺席≠删除,2026-09-28 语义)
def test_sync_keeps_absent_rows(app, dbs_ready_file):
# [断言意图] 新版文件缺席的档行 → 保留不删(收料 RPA 非全量导出,缺席≠删除);
# 档无 TTL:缺席也不换戳(与旧 items 存续换戳的差异,档以 sha 幂等为准)。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
doomed = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").first()
doomed.status = "ready_to_execute" # 模拟上一版可执行
db.session.flush()
terminal = TransferInvoiceItem(
matching_id=None, source_code="DBS-AWSBI", invoice_no="HOX-TERMINAL",
material_no="MAT-X", material_name="n", specification="", receipt_date="2026-09-19",
status="success", result_code=None, from_warehouse="W", to_warehouse="H",
receipt_quantity="1", lot_no="L", receipt_warehouse_code="W1", unit="PCS",
raw_lines_json=[], updated_at=NOW,
)
db.session.add(terminal)
db.session.flush()
frozen = [(r.id, r.quantity, r.file_sha256) for r in _ledger_rows()]
deps2, _, _ = make_transfer_deps(dbs_ready_file)
# 换一版不含任何行的文件:经 Fake 仓库一次性覆盖注入空 rows(新 sha)。
repo2 = deps2.file_repository
repo2.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64)
deps2.file_repository.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps2,
business_date="2026-08-06", now=NOW)
assert outcome is not None and outcome.absent_kept == 2 # [断言意图] 两行缺席存续
db.session.refresh(doomed)
assert doomed.status == "ready_to_execute" # [断言意图] 状态不被缺席改写
assert doomed.result_code == SYNC_RESULT_PENDING # [断言意图] 结果码保留
assert doomed.raw_lines_json[0]["file_sha256"] == "e" * 64 # [断言意图] 版本戳已换新
db.session.refresh(terminal)
assert terminal.status == "success" # [断言意图] 终态行不复活
assert outcome is not None and outcome.inserted == 0
assert [(r.id, r.quantity, r.file_sha256) for r in _ledger_rows()] == frozen
# [断言意图] 缺席行的档记录原样留存(事实不随文件消失)。
def test_sync_does_not_resurrect_terminal_rows_on_relanding(app, dbs_ready_file):
# [断言意图] 来源全终态后同文件重落地(同日 RPA 重试 / align 兜底重解析):
# 不重插新 pending 行、终态行原样保留——已执行调拨单不得复活回待办池。
def test_sync_never_touches_sealed_rows_on_relanding(app, dbs_ready_file):
# [断言意图] 已执行封存行(transfer_executed=true):同文件重落地不更新、
# 不复活(防二次调拨;命中即计 sealed_skipped)。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
rows = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all()
assert len(rows) == 2 # [断言意图] 前置:文件聚合成两行
for r in rows:
r.status = "success" # 全部推到终态(模拟已执行)
r.result_code = None # 执行终态清待查标记
hom = _by_doc("HOM-001")
hom.transfer_executed = True
hom.executed_doc_no = "TRF-0001"
db.session.flush()
frozen = {r.id: (r.status, r.result_code, r.updated_at) for r in rows}
frozen = (hom.quantity, hom.updated_at, hom.file_sha256)
# 同一文件重落地:set_next_file 重注同 rows / 同 checksum(一次有效覆盖)。
deps.file_repository.set_next_file(
source_code="DBS-AWSBI", rows=tuple(dbs_ready_file["rows"]), checksum="d" * 64)
later = datetime(2026, 9, 25, 11, 0, 0) # 后续新鲜度基准:任何写入都会暴露
later = datetime(2026, 9, 25, 11, 0, 0)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=later)
assert outcome is not None
assert outcome.inserted == 0 # [断言意图] 终态 quad 不重插新行
assert outcome.skipped == 2 # [断言意图] 全部计入跳过口径
assert _pending_count() == 0 # [断言意图] 已执行单据不重回待办池
after = TransferInvoiceItem.query.filter_by(source_code="DBS-AWSBI").all()
assert [r.id for r in after] == [r.id for r in rows] # [断言意图] 行集合不变
assert {r.id: (r.status, r.result_code, r.updated_at) for r in after} == frozen
# [断言意图] 终态行零写入(含 updated_at 未被续新)
assert outcome.sealed_skipped == 1 # [断言意图] 封存行命中即计
db.session.expire_all()
hom = _by_doc("HOM-001")
assert (hom.quantity, hom.updated_at, hom.file_sha256) == frozen # [断言意图] 零写入
assert hom.transfer_executed is True and hom.executed_doc_no == "TRF-0001"
def test_sync_refreshes_display_fields_without_reset(app, dbs_ready_file):
# [断言意图] 纯名称/规格变更(sha 变、三证据字段未变)→ refreshed 且展示值已更新。
def test_sync_updates_row_on_evidence_change(app, dbs_ready_file):
# [断言意图] 证据变化(数量)→ 原行更新:业务值换新 + 溯源五列整体换新,
# 不产生第二行(自然键幂等);未变行只跳过。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
changed_rows = [
{**row, "quantity": "1300"} if row["doc_no"] == "HOM-001" else row
for row in dbs_ready_file["rows"]
]
deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=changed_rows,
checksum="f" * 64)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
# [断言意图] 新文件版本(sha 变)下两行都走原行更新分支:HOM-001 业务值换新,
# HOX-002 业务值未变仅溯源换新(sha 变=证据换新版本,计数同归 updated)。
assert outcome.updated == 2 and outcome.inserted == 0
hom = _by_doc("HOM-001")
# [断言意图] 数量随新文件换新:夹具 HOM-001 两行的 quantity 均被替换为 1300,
# 聚合落档 2600(档=聚合镜像,聚合语义由 ledger 落地承接)。
assert hom.quantity == "2600"
assert hom.file_sha256 == "f" * 64 # [断言意图] 溯源换新
hox = _by_doc("HOX-002")
assert hox.quantity == "1200" and hox.file_sha256 == "f" * 64 # [断言意图] 值不变仅换溯源
def test_sync_refreshes_display_fields_on_evidence_change(app, dbs_ready_file):
# [断言意图] 名称/规格属档镜像列:随原行更新分支整体换新(档=忠实镜像,
# 无「仅展示变更不重置」分支——那是 items 时代为保护库存评估的语义)。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
# 同证据(数量/批号/仓库/单号/料号/日期不变),只改 material_name/specification。
renamed_rows = [
{**row, "material_name": "改名组件", "specification": "改规格 / NEW"}
{**row, "material_name": "改名组件", "specification": "改规格 / NEW", "quantity": "999"}
for row in dbs_ready_file["rows"]
]
deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=renamed_rows, checksum="f" * 64)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert outcome.refreshed == 2 and outcome.reset_pending == 0 # [断言意图] 展示变更不重置待查
row = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOM-001").first()
assert row.material_name == "改名组件" # [断言意图] 展示值随新文件刷新
assert row.specification == "改规格 / NEW" # [断言意图] 规格同步刷新
assert row.status == "matching" # [断言意图] 状态不受展示变更影响
assert row.result_code == SYNC_RESULT_PENDING
assert row.raw_lines_json[0]["file_sha256"] == "f" * 64 # [断言意图] 版本戳已换新
assert outcome.updated == 2
hom = _by_doc("HOM-001")
assert hom.material_name == "改名组件" # [断言意图] 展示值随新文件换新
assert hom.specification == "改规格 / NEW"
def test_absent_rows_restamped_so_align_passes_through(app, dbs_ready_file, monkeypatch):
# [断言意图] 缺席行已换最新文件戳 → align 判据 row_shas == latest_sha 直通(None)。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
row = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOX-002").first()
assert row.result_code == SYNC_RESULT_PENDING # [断言意图] 缺席不改结果码(存续)
assert row.raw_lines_json[0]["file_sha256"] == "e" * 64 # [断言意图] 缺席行已换新戳
# 文件状态投影返回空 files 版 sha(align 判据输入);测试注入替身避免触碰真实表。
monkeypatch.setattr(
"app.services.in_transit_transfer.evidence_sync.resolve_source_file_status",
lambda *, source_code: {"file_status": "ready", "has_ready_file": True,
"file_no": "REC-E", "file_sha256": "e" * 64},
)
outcomes = align_scope_rows(source_codes=["DBS-AWSBI"], deps=deps,
business_date="2026-08-06", now=NOW)
assert outcomes["DBS-AWSBI"] is None # [断言意图] 已对齐:直通零解析
def test_reappeared_absent_rows_refresh_without_reset(app, dbs_ready_file):
# [断言意图] 缺席存续行重新出现且证据未变 → refreshed(只换戳),状态保持待查。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=(), checksum="e" * 64)
absent_outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert absent_outcome.absent_kept == 2 # [断言意图] 前置:两行缺席存续
deps.file_repository.set_next_file(
source_code="DBS-AWSBI", rows=tuple(dbs_ready_file["rows"]), checksum="a" * 64)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert outcome.refreshed == 2 # [断言意图] 复现行走刷新分支
assert outcome.reset_pending == 0 # [断言意图] 证据未变不重置
row = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOX-002").first()
assert row.status == "matching" # [断言意图] 状态保持待查
assert row.result_code == SYNC_RESULT_PENDING
assert row.raw_lines_json[0]["file_sha256"] == "a" * 64 # [断言意图] 已换最新戳
def test_historical_removed_row_restored_on_reappear(app, dbs_ready_file):
# [断言意图] 历史残留 blocked_file_removed 行复现 → 无条件恢复待查(防御路径,
# 2026-09-28 起不再新产生,但存量行修复前仍可能命中)。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
row = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOX-002").first()
row.status = "blocked_recoverable"
row.result_code = "blocked_file_removed"
row.result_message = "receipt row removed from latest file"
db.session.flush()
deps.file_repository.set_next_file(
source_code="DBS-AWSBI", rows=tuple(dbs_ready_file["rows"]), checksum="a" * 64)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
db.session.refresh(row)
assert outcome.reset_pending >= 1 # [断言意图] 复现行计入重置口径
assert row.status == "matching" # [断言意图] 脱离 blocked
assert row.result_code == SYNC_RESULT_PENDING
assert row.result_message is None # [断言意图] 删除解释清除
def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog):
# [断言意图] 同步崩溃只记日志:异常绝不向收料回调链路传播。
def test_inbound_bridge_is_failure_isolated(app, monkeypatch, caplog):
# [断言意图] 落档崩溃只记日志:异常绝不向收料回调链路传播。
from app.services.in_transit_transfer import evidence_sync
def _boom(**kwargs):
@@ -277,8 +233,9 @@ def test_receipt_bridge_is_failure_isolated(app, monkeypatch, caplog):
assert any("TRANSFER_EVIDENCE_SYNC" in r.message for r in caplog.records)
def test_receipt_bridge_commits_on_success(app, dbs_ready_file, monkeypatch):
# [断言意图] 成功路径自行 commit(B3 教训:不依赖调用方提交时机)。
def test_inbound_bridge_commits_ledger_on_success(app, dbs_ready_file, monkeypatch):
# [断言意图] 成功路径自行 commit(B3 教训:不依赖调用方提交时机);
# 端到端一遍:桥 → 解析 → 聚合落档(档行持久化,items 停写)。
from app.services.in_transit_transfer import evidence_sync
deps, _, _ = make_transfer_deps(dbs_ready_file)
monkeypatch.setattr(
@@ -288,29 +245,31 @@ def test_receipt_bridge_commits_on_success(app, dbs_ready_file, monkeypatch):
source_code="DBS-AWSBI", business_date="2026-08-06", now=NOW)
assert ok is True
assert _pending_count("DBS-AWSBI") > 0 # [断言意图] 已持久化(含 commit)
db.session.expire_all()
assert len(_ledger_rows()) == 2 # [断言意图] 档行已持久化(含 commit)
assert TransferInvoiceItem.query.count() == 0 # [断言意图] items 停写
def test_receipt_bridge_skips_when_no_file(app):
def test_inbound_bridge_skips_when_no_file(app):
# [断言意图] 来源无可用文件:静默返回 True(无事发生,非错误)。
from app.services.in_transit_transfer import evidence_sync
assert evidence_sync.sync_and_commit_for_callback(
source_code="NO-SUCH", business_date="2026-09-25", now=NOW) is True
def test_receipt_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, monkeypatch):
# [断言意图] 桥内同步抛 ReceiptFileSchemaError(schema 类解析失败)→ 失败事实
def test_inbound_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, monkeypatch):
# [断言意图] 桥内同步抛 MovementFileSchemaError(schema 类解析失败)→ 失败事实
# 独立 commit 落到当前可用文件(parse_failed 三列),来源投影转 parse_failed;
# 同步数据已回滚(桥隔离保持)。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
from app.services.in_transit_transfer import evidence_sync
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
report = _seed_usable_report_file(
source_code="DBS-AWSBI", sha="d" * 64, callback_id="cb-schema-bad")
deps, _, _ = make_transfer_deps(dbs_ready_file)
# 行缺单号(doc_no 置空)→ 解析必抛 ReceiptFileSchemaError(行级 missing_invoice_no)。
# 行缺单号(doc_no 置空)→ 解析必抛 MovementFileSchemaError(行级 missing_invoice_no)。
bad_row = {**dbs_ready_file["rows"][0], "doc_no": ""}
deps.file_repository.set_next_file(
source_code="DBS-AWSBI", rows=[bad_row], checksum="d" * 64)
@@ -321,9 +280,9 @@ def test_receipt_bridge_schema_failure_marks_parse_failed(app, dbs_ready_file, m
source_code="DBS-AWSBI", business_date="2026-08-06", now=NOW)
assert ok is False # [断言意图] 同步失败被吞(桥隔离)
assert _pending_count() == 0 # [断言意图] 坏行未落库(同步数据已回滚)
assert TransferMovementLedger.query.count() == 0 # [断言意图] 坏行未落档(同步数据已回滚)
db.session.expire_all() # 标记经桥内独立 commit:失效缓存重读
row = db.session.query(ShippingReceiptReportFile).filter_by(id=report.id).one()
row = db.session.query(FreightRpaInboundReportFile).filter_by(id=report.id).one()
assert row.parse_failed_at is not None # [断言意图] 失败事实已落库
assert row.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID"
assert row.parse_error_message
@@ -335,13 +294,13 @@ def test_sync_success_clears_parse_failed_mark(app, dbs_ready_file):
# [断言意图] 同步成功 = 当前可用文件已成功解析:此前落下的 parse_failed 三列
# 被清除,来源投影恢复 ready(只 flush 不 commit,事务归属调用方不变)。
from app.services.in_transit_transfer.source_file_status import (
record_receipt_parse_failure,
record_inbound_parse_failure,
resolve_source_file_status,
)
report = _seed_usable_report_file(
source_code="DBS-AWSBI", sha="d" * 64, callback_id="cb-schema-clear")
record_receipt_parse_failure(
record_inbound_parse_failure(
report=report, error_code="TRANSFER_FILE_SCHEMA_INVALID", error_message="stale mark")
assert resolve_source_file_status(
source_code="DBS-AWSBI")["file_status"] == "parse_failed" # [断言意图] 前置:确已标记
@@ -359,41 +318,144 @@ def test_sync_success_clears_parse_failed_mark(app, dbs_ready_file):
source_code="DBS-AWSBI")["file_status"] == "ready" # [断言意图] 投影恢复 ready
def test_sync_never_renews_inventory_checked_at_and_resets_nulls_it(app, dbs_ready_file):
# [断言意图] stale 时钟不被换戳续期:refreshed(三证据未变)→
# inventory_checked_at 保持原值(仅 updated_at 续期);reset_pending
# (证据变化,旧库存作废)→ 取数时刻随 external_quantity 一并置空。
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps, business_date="2026-08-06", now=NOW)
row = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOM-001").first()
assert row.inventory_checked_at is None # [断言意图] 新落行未取数
checked = datetime(2026, 9, 24, 9, 0, 0)
row.inventory_checked_at = checked
db.session.commit()
# 同证据换戳(新 sha、收料事实不变)→ refreshed:取数时刻不得被续期。
deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=dbs_ready_file["rows"],
checksum="e" * 64)
def test_sync_writes_cross_flag_for_contradictory_in_out_flag(app):
# [断言意图] record_kind='inbound' 行出现出库语义 '-1':照常落档 + 计
# cross_flagged(解析错位标记由 ledger_sync 落审计事件,档不拒收)。
deps, _, _ = make_transfer_deps({
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "inbound",
"file_no": "REC-X",
"file_version": "v1",
"checksum": "x" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-X1", "line_no": "1",
"in_out_flag": "-1", "lot_no": "LOT-X", "material_code": "MAT-X",
"movement_date": "2026-08-05", "quantity": "10", "source_code": "DBS-AWSBI"},
],
})
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert outcome.refreshed >= 1
db.session.expire_all()
row = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOM-001").first()
assert row.inventory_checked_at == checked # [断言意图] 换戳≠查过库存
assert outcome is not None and outcome.cross_flagged == 1
row = _by_doc("HOM-X1")
assert row.in_out_flag == "-1" # [断言意图] 原值落档不拒收
# 收料数量变化 → reset_pending:旧库存作废,取数时刻同步置空。
changed = [{**r, "quantity": "1300"} if r["doc_no"] == "HOM-001" else r
for r in dbs_ready_file["rows"]]
deps.file_repository.set_next_file(source_code="DBS-AWSBI", rows=changed,
checksum="d" * 64)
def test_sync_lands_external_doc_line_and_expands_natural_key(app):
# [断言意图] 外部单据身份(外部单号/外部项次=WMS Order #/行号)经落档链路
# 写入档列并参与自然键:同单号同行不同外部单号 = 两行独立落档(2026-10-21
# 档幂等主键管控扩维),外部身份列原值随行留存。
deps, _, _ = make_transfer_deps({
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "inbound",
"file_no": "REC-EXT",
"file_version": "v1",
"checksum": "e" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-E1", "line_no": "1",
"external_doc_no": "WMS-001", "external_line_no": "10",
"lot_no": "LOT-E", "material_code": "MAT-E", "material_name": "外部身份料号",
"movement_date": "2026-08-05", "quantity": "10", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-E1", "line_no": "1",
"external_doc_no": "WMS-002", "external_line_no": "10",
"lot_no": "LOT-E", "material_code": "MAT-E", "material_name": "外部身份料号",
"movement_date": "2026-08-05", "quantity": "20", "source_code": "DBS-AWSBI"},
],
})
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert outcome.reset_pending >= 1
db.session.expire_all()
row = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOM-001").first()
assert row.external_quantity is None
assert row.inventory_checked_at is None
assert outcome is not None and outcome.inserted == 2 # [断言意图] 不同外部单号各自成行
rows = TransferMovementLedger.query.filter_by(
source_code="DBS-AWSBI", doc_no="HOM-E1").order_by(TransferMovementLedger.id).all()
assert [(r.external_doc_no, r.external_line_no) for r in rows] == [
("WMS-001", "10"), ("WMS-002", "10")] # [断言意图] 外部身份列原值落档
def _collapsed_multi_material_file() -> dict:
"""同单号双料号、行级 line_no/line_seq/in_out_flag 全空且 carton/lot 等值的坍缩形态文件。
档自然键 (source_code, record_kind, doc_no, line_no, line_seq, in_out_flag,
carton_id, lot_no) 不含料号(tt14 起含箱号/批号,批内等值才同键):两行在批内
折叠为同一自然键,第二料号行会被幂等吞掉(首见为准)。
"""
return {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "inbound",
"file_no": "REC-C1",
"file_version": "v1",
"checksum": "c1" + "0" * 62,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-C1", "lot_no": "LOT-A",
"material_code": "MAT-A", "movement_date": "2026-08-05", "quantity": "10",
"source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-C1", "lot_no": "LOT-A",
"material_code": "MAT-B", "movement_date": "2026-08-05", "quantity": "20",
"source_code": "DBS-AWSBI"},
],
}
def test_sync_flags_natural_key_collapse_for_multi_material_without_line_fields(app):
# [断言意图] 终审 I3 坍缩守卫:同单号双料号且行级项次全空 → 第二料号行仍被
# 自然键幂等吞掉(首见为准,数据行为维持现状),但必须留下
# ledger_natural_key_collapse 审计事件——静默丢行变显式可观测。
deps, _, _ = make_transfer_deps(_collapsed_multi_material_file())
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
rows = TransferMovementLedger.query.filter_by(
source_code="DBS-AWSBI", doc_no="HOM-C1").all()
assert len(rows) == 1 # [断言意图] 第二料号行被吞(首见为准)
assert rows[0].material_code == "MAT-A" and rows[0].line_no == ""
assert outcome is not None
assert outcome.inserted == 1 and outcome.skipped == 1 # [断言意图] 吞掉的行计 skipped
event = TransferAuditEvent.query.filter_by(
event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).one()
assert event.aggregate_type == "transfer_movement_ledger"
assert "HOM-C1" in event.aggregate_id # [断言意图] 事件定位到坍缩单号
assert event.result == "failure" # [断言意图] 数据质量降级事件
assert event.after_json["material_codes"] == ["MAT-A", "MAT-B"] # 首见序全量料号
assert event.after_json["dropped_material_codes"] == ["MAT-B"] # 被吞料号可定位
assert event.after_json["resolution"] == "first_seen_wins"
def test_collapse_event_not_reemitted_on_idempotent_relanding(app):
# [断言意图] 幂等重落不重复打事件(防只追加审计表被同文件重落刷爆,与
# ledger_sync 交叉校验事件同款防刷口径);换文件版本(sha 变)才会再打。
deps, _, _ = make_transfer_deps(_collapsed_multi_material_file())
sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
deps.file_repository.set_next_file(
source_code="DBS-AWSBI", rows=tuple(_collapsed_multi_material_file()["rows"]),
checksum="c1" + "0" * 62)
sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert TransferAuditEvent.query.filter_by(
event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).count() == 1
def test_no_collapse_event_when_line_fields_present(app):
# [断言意图] 同单号双料号但项次列齐全(line_no 各异)→ 两个自然键两行落档,
# 不触发坍缩事件(真实 WMS 导出形态零误报)。
file = _collapsed_multi_material_file()
file["rows"][0]["line_no"] = "1"
file["rows"][1]["line_no"] = "2"
deps, _, _ = make_transfer_deps(file)
outcome = sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
assert outcome is not None and outcome.inserted == 2 # [断言意图] 双料号各自成行
assert TransferMovementLedger.query.filter_by(
source_code="DBS-AWSBI", doc_no="HOM-C1").count() == 2
assert TransferAuditEvent.query.filter_by(
event_type=evidence_sync.LEDGER_NATURAL_KEY_COLLAPSE_EVENT).count() == 0
@@ -29,7 +29,7 @@ def _executed_run(dbs_ready_file, patch_source_file_status):
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
erp.write_scenarios["HOM-001"] = "business_failed"
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
items = (
db.session.query(TransferInvoiceItem)
.filter_by(status="ready_to_execute")
@@ -1,16 +1,18 @@
"""在途调拨单据级执行测试(execute_items 同步组合路径:门禁 + 组建单 + 逐单执行)。
用途:验证同步执行组合入口的两道门禁(①存在且可执行 ②文件版本对账,失败路径
均携带 details 列表且外部系统 写入为 0;原「行级新鲜度 TTL」门禁已于
2026-09-25 退役——items_stale 拒绝用例随之删除,TTL 降级为前端展示徽标)、
D1 五元组建单与单据级写语义(一单一次 create_transfer、单内行共享单结果)、
写前路由复查(漂移阻断)、result_unknown 不自动重试、单间失败隔离
(不同组互不影响)、匹配 scope 执行入口(execute_matching_items)与按
外部系统 单号投影。
用途:验证同步执行组合入口的执行存在性门禁(①存在且可执行,失败携带 details
列表且外部系统 写入为 0;原「文件版本对账」门禁已于 2026-10-22 退役——
文件更新/缺失不再拦执行,行装饰 file_current 徽标仅提示,防错下沉 worker
写前库存复查;原「行级新鲜度 TTL」门禁已于 2026-09-25 退役——items_stale
拒绝用例随之删除,TTL 降级为前端展示徽标)、D1 五元组建单与单据级写语义
(一单一次 create_transfer、单内行共享单结果)、写前路由复查(漂移阻断)、
result_unknown 不自动重试、单间失败隔离(不同组互不影响)、匹配 scope
执行入口(execute_matching_items)与按外部系统单号投影。
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
逻辑:T10 单据级重构后执行单元 = ERP 调拨单(TransferDocument);本文件为存量按行
执行测试的按单改写版(场景不弱化:门禁/幂等/隔离/投影逐一保留);
文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。
来源文件状态投影经 patch_source_file_status 夹具注入替身(装饰断言另打
matching_service 命名空间)。
"""
from __future__ import annotations
@@ -29,6 +31,7 @@ from app.services.in_transit_transfer.matching_service import (
RouteMapping,
TransferDeps,
create_matching,
list_executable_items,
)
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
@@ -47,7 +50,7 @@ def _ready_items(dbs_ready_file, *seeds) -> tuple:
erp.seed_stock(*_INVOICE_TUPLES[invoice_no], quantity)
deps, erp, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = (
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
.order_by(TransferInvoiceItem.id)
@@ -76,7 +79,7 @@ def test_execute_items_writes_one_order_and_aggregates(transfer_db, dbs_ready_fi
deps, erp, items = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first()
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-07").first()
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
# Run 终态与单据聚合:同组两 Invoice 合并一张 ERP 单(D1 五元组一组一单),无异常。
@@ -145,7 +148,7 @@ def _two_group_deps(dbs_ready_file, patch_source_file_status):
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
deps, erp, _ = make_transfer_deps(file, capabilities=erp)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = (
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
.order_by(TransferInvoiceItem.id)
@@ -252,35 +255,57 @@ def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_f
assert _execution_runs() == []
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status):
"""门禁②:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。"""
# monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配",
# (重跑匹配会把行原地刷成新版本,无法构造本场景)。
def test_execute_items_proceeds_when_file_updated_and_decorates_not_current(
transfer_db, dbs_ready_file, patch_source_file_status, monkeypatch,
):
"""[2026-10-22 文件版本对账门禁退役] 文件已更新不再是执行门禁。
入站抓取是部分导出——新文件不含某行 ≠ 该行失效/已处理,按最新文件 sha
对账曾把大量未处理行错误卡死(业务实测 557 行积压)。执行照常写 ERP;
行装饰 file_current=False 仅提示不拦截,防错下沉 worker 写前库存复查。
"""
patch_source_file_status({"DBS-AWSBI": "e" * 64})
# 装饰读取走 matching_service 命名空间的同名投影(退役后该函数仅剩展示
# 消费方),此处同步打桩保持与执行侧替身同源。
monkeypatch.setattr(
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
lambda *, source_code, record_kind="inbound": {
"file_status": "ready", "has_ready_file": True,
"file_no": "REC-TEST", "file_sha256": "e" * 64,
},
)
deps, erp, items = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
# 断言:行当前性徽标如实提示「行评估版本戳 ≠ 最新可用文件」。
listing = list_executable_items(deps=deps)
decorated = {row.item_id: row for row in listing["items"]}
assert all(decorated[item.id].file_current is False for item in items)
with pytest.raises(ValidationError) as excinfo:
execute_items(item_ids=[item.id for item in items], deps=deps)
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
assert erp.write_calls() == []
assert _execution_runs() == []
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
# 断言:徽标不拦截执行——同组两 Invoice 合并一单、一次写调用、行全 success。
assert outcome.status == "success"
assert len(erp.write_calls()) == 1
linked = _load_items(outcome.run_no)
assert all(item.status == "success" for item in linked.values())
def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
"""门禁②:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。"""
def test_execute_items_proceeds_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
"""[2026-10-22 门禁退役] 来源无可用文件同样不拦执行。
档是镜像事实,不随当日文件可用性消失(evidence_sync 已落档的行照常可执行)。
"""
patch_source_file_status({"DBS-AWSBI": None})
deps, erp, items = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
with pytest.raises(ValidationError) as excinfo:
execute_items(item_ids=[item.id for item in items], deps=deps)
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
assert erp.write_calls() == []
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
# 断言:无可用文件不拒绝执行——照常组建单并写入外部系统。
assert outcome.status == "success"
assert len(erp.write_calls()) == 1
linked = _load_items(outcome.run_no)
assert all(item.status == "success" for item in linked.values())
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
@@ -289,7 +314,7 @@ def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_read
deps, erp, _ = _ready_items(
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
)
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-06").first()
matching = db.session.query(TransferMatching).filter_by(business_date="2026-08-07").first()
outcome = execute_matching_items(
matching_id=matching.matching_no, deps=deps, invoice_nos=["HOM-001"],
@@ -10,7 +10,10 @@
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service、jobs.queue。
逻辑:场景编号对应计划 Task 10 Step 1 场景①-⑪;SQLite 无 PG 序列,单号序列经
monkeypatch execution_service._sequence_loader 注入替身;文件对账门禁经
patch_source_file_status 夹具注入 ready 投影。
patch_source_file_status 夹具注入 ready 投影。出站档行用例把入站/出站
投影分成两个 sha,确认门禁与 file_current 读档上的 record_kind。
【T−2 成熟封顶 2026-10-21】匹配 business_date 用 2026-08-07(行日期
2026-08-04/08-05 均 ≤T−2 成熟可圈;文件/种子新鲜度仍用 2026-08-06)。
"""
from __future__ import annotations
@@ -32,6 +35,7 @@ from app.models import (
TransferDocument,
TransferInvoiceItem,
TransferMatching,
TransferMovementLedger,
TransferRun,
)
from app.services.in_transit_transfer.execution_service import (
@@ -41,7 +45,7 @@ from app.services.in_transit_transfer.execution_service import (
retrigger_document,
)
from app.services.in_transit_transfer.serializers import serialize_order
from app.services.in_transit_transfer.matching_service import create_matching
from app.services.in_transit_transfer.matching_service import create_matching, restore_matching
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
READY_SHA = "d" * 64
@@ -63,7 +67,7 @@ def _file(rows: list[dict], *, checksum: str = READY_SHA) -> dict:
"""由行构造 DBS-AWSBI ready 收料文件 dict。"""
return {
"source_code": "DBS-AWSBI", "business_date": "2026-08-06",
"file_purpose": "receipt", "file_no": "REC-TEST", "file_version": "v9",
"file_purpose": "inbound", "file_no": "REC-TEST", "file_version": "v9",
"checksum": checksum, "status": "ready", "rows": rows,
}
@@ -146,7 +150,7 @@ def _order_call(erp, doc: TransferDocument) -> dict:
# 场景①:两单不同收料日期 → 两张单各一单号(D1 收料日期入组键)
# ---------------------------------------------------------------------------
def test_two_receipt_dates_create_two_documents(
def test_two_movement_dates_create_two_documents(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""不同收料日期的同来源行必须拆为两张单,各自终身独立单号/时间戳。"""
@@ -154,7 +158,7 @@ def test_two_receipt_dates_create_two_documents(
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-04", "700"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
assert outcome.status == "queued"
@@ -162,7 +166,7 @@ def test_two_receipt_dates_create_two_documents(
docs = _docs_of(run)
# 断言意图:收料日期入组键(D1)→ 两日期两单,且单初态 pending。
assert len(docs) == 2
assert {doc.receipt_date for doc in docs} == {"2026-08-05", "2026-08-04"}
assert {doc.movement_date for doc in docs} == {"2026-08-05", "2026-08-04"}
assert all(doc.status == "pending" for doc in docs)
assert len({doc.doc_no for doc in docs}) == 2
assert len({doc.submit_timestamp for doc in docs}) == 2
@@ -185,7 +189,7 @@ def test_same_order_same_material_lot_across_invoices_aggregates_line(
])
# 严格数量匹配逐 Invoice 核对:库存须等于单 Invoice 数量(聚合发生在执行组建单时)。
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "500.5")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -205,14 +209,14 @@ def test_same_order_same_material_lot_across_invoices_aggregates_line(
# 场景③:制单日期=组收料日期(gls_cm06 必须等于 Excel 异动日期,D1)
# ---------------------------------------------------------------------------
def test_order_doc_date_equals_group_receipt_date(
def test_order_doc_date_equals_group_movement_date(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""单 doc_date 必须等于组收料日期;posting_date 为执行当天业务日。"""
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -221,7 +225,7 @@ def test_order_doc_date_equals_group_receipt_date(
call = _order_call(erp, doc)
# 断言意图:制单日期=组收料日期(2026-08-05),过账日期=执行当天(run 业务日)。
assert call.doc_date == "2026-08-05"
assert doc.receipt_date == "2026-08-05"
assert doc.movement_date == "2026-08-05"
assert call.posting_date == run.business_date
@@ -237,7 +241,7 @@ def test_order_success_propagates_to_all_items(
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-05", "700"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -274,7 +278,7 @@ def test_order_failure_isolates_to_its_items(
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-04", "700"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = _ready_items()
outcome = prepare_execution(item_ids=[i.id for i in items], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
@@ -310,7 +314,7 @@ def test_worker_reclaim_executing_stage_confirmed_runs_final_only(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -342,7 +346,7 @@ def test_failed_order_reused_with_new_row_full_rerun(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run1 = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run1)
@@ -353,7 +357,10 @@ def test_failed_order_reused_with_new_row_full_rerun(
assert doc.status == "business_failed"
old_doc_no, old_ts = doc.doc_no, doc.submit_timestamp
# 新一轮匹配新增同组新行(新料号),原 blocked 行原地刷新回 ready。
# 2026-10-14 出生翻转后:新一轮匹配从当前档版本出生新行(新料号 HOM-C;
# HOM-A 档记录仍被首匹配的 blocked 行有效占用,不再出生)。原单
# blocked_recoverable 旧行由 D7① 复用分支重关联新 Run(executing)随全量
# 重跑——并非原地刷回 ready。
erp.write_scenarios_by_doc.pop(doc.doc_no)
deps2, erp2, _ = make_transfer_deps(_file([
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
@@ -363,7 +370,7 @@ def test_failed_order_reused_with_new_row_full_rerun(
erp2.seed_stock("MAT-003", "DBS-TRANSIT", "LOT-30", "300")
patch_source_file_status()
seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06") # 新行 HOM-C 落地;HOM-A 幂等跳过
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps2, transfer_type="in_transit_to_hub")
second = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps2)
run2 = TransferRun.query.filter_by(run_no=second.run_no).first()
@@ -399,7 +406,7 @@ def test_result_unknown_order_blocks_new_rows(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run1 = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run1)
@@ -415,9 +422,9 @@ def test_result_unknown_order_blocks_new_rows(
db.session.add(TransferInvoiceItem(
matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="HOM-NEW",
material_no="MAT-009", material_name="新行", specification="",
receipt_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
receipt_quantity="100", unit="PCS", status="ready_to_execute",
receipt_warehouse_code="DBS-TRANSIT",
movement_date="2026-08-05", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
movement_quantity="100", unit="PCS", status="ready_to_execute",
movement_warehouse_code="DBS-TRANSIT",
raw_lines_json=[{"sheet": "Receipt", "row_no": 9, "file_version": "v9", "file_sha256": READY_SHA}],
))
db.session.commit()
@@ -458,7 +465,7 @@ def test_retrigger_document_full_chain(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run)
@@ -528,7 +535,7 @@ def test_partial_unique_index_race_falls_back_to_reuse(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = _ready_items()
original_insert = execution_service._insert_document
@@ -540,7 +547,7 @@ def test_partial_unique_index_race_falls_back_to_reuse(
if state["called"] == 1:
winner = TransferDocument(
source_code=doc.source_code, external_org=doc.external_org,
receipt_date=doc.receipt_date, from_warehouse=doc.from_warehouse,
movement_date=doc.movement_date, from_warehouse=doc.from_warehouse,
to_warehouse=doc.to_warehouse,
doc_no="HX-CN01-OR-26099999999", submit_timestamp="concurrent" + "0" * 38,
status="pending",
@@ -557,7 +564,7 @@ def test_partial_unique_index_race_falls_back_to_reuse(
db.session.expire_all()
docs = TransferDocument.query.filter_by(
source_code="DBS-AWSBI", receipt_date="2026-08-05",
source_code="DBS-AWSBI", movement_date="2026-08-05",
).all()
# 断言意图:竞态后同组仅一张单(DB 部分唯一索引兜底 + 复用重试成立)。
assert len(docs) == 1
@@ -580,7 +587,7 @@ def test_prepare_enqueues_single_transfer_run_job(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
ids = [i.id for i in _ready_items()]
outcome = prepare_execution(item_ids=ids, deps=deps)
@@ -605,30 +612,37 @@ def test_prepare_enqueues_single_transfer_run_job(
# ---------------------------------------------------------------------------
# 补充:worker 二次门禁(Hash 失效 fail-closed,不触外部)
# 补充:文件版本对账门禁退役(2026-10-22)——版本变化不再拦截 worker 执行
# ---------------------------------------------------------------------------
def test_execute_run_rechecks_file_hash_fail_closed(
def test_worker_executes_despite_file_version_change(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""worker 二次门禁:文件版本对账失败 → fail-closed(单置 technical_failed、行阻断、零写入)。"""
"""文件版本对账门禁退役:最新文件 sha 变化后 worker 仍逐单执行到底。
[断言意图] 入站抓取是部分导出——新文件不含旧行 ≠ 旧行失效,按最新文件 sha
对账会错误卡死未处理行(557 行积压实测);门禁退役后版本滞后的行照常执行,
证据漂移的防护由写前库存复查(ERP 账面严格相等)承担。
"""
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
# 文件已更新未重新匹配:worker 复核必须拒绝执行。
# 文件已更新(最新投影 sha=e,行/档仍持旧版本):旧门禁在此整 Run 落败。
patch_source_file_status({"DBS-AWSBI": "e" * 64})
execute_run(run_id=run.id, deps=deps)
db.session.expire_all()
doc = db.session.get(TransferDocument, doc.id)
assert doc.status == "technical_failed"
# [断言意图] 版本滞后不再拦截:单成功、行成功、ERP 照常写入(写前复查因
# 账面 500==500 通过)。
assert doc.status == "success"
linked = TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
assert all(item.status == "blocked_recoverable" for item in linked)
assert erp.write_calls() == []
assert all(item.status == "success" for item in linked)
assert len(erp.write_calls()) == 1
db.session.expire_all()
# ---------------------------------------------------------------------------
@@ -643,7 +657,7 @@ def test_full_run_passes_stage_callback_and_marks_stage_confirmed(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -669,7 +683,7 @@ def test_retrigger_final_only_does_not_pass_stage_callback(
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run)
@@ -699,11 +713,12 @@ def test_requeried_rows_reuse_order_without_new_rows(
transfer_db, dbs_ready_file, patch_source_file_status,
):
"""失败单 → 行重查回 ready(run_id 留旧 Run)→ 纯旧行再次提交新 Run:
归属补齐进新 Run(attempt_no 防双跳)、二次门禁覆盖该行、复用同单、投影非空。"""
归属补齐进新 Run(attempt_no 防双跳)、复用同单、执行到底、投影非空
(原「二次门禁覆盖该行」段随文件版本对账门禁退役 2026-10-22 删除)。"""
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
first = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run1 = TransferRun.query.filter_by(run_no=first.run_no).first()
doc = _doc_for(run1)
@@ -740,38 +755,17 @@ def test_requeried_rows_reuse_order_without_new_rows(
assert reused.submit_timestamp == old_ts
assert reused.run_id == run2.id
# [二次门禁覆盖该行] 文件 Hash 失效 → 行被阻断(证明门禁按新 Run 行集复核)。
patch_source_file_status({"DBS-AWSBI": "e" * 64})
# [执行完成] 文件版本对账门禁退役(2026-10-22):重查回 ready 的旧行不再被
# 版本戳拦截,直接执行到底——单/行/Run 同成功族,投影非空。
execute_run(run_id=run2.id, deps=deps)
db.session.expire_all()
row = db.session.get(TransferInvoiceItem, row.id)
reused = db.session.get(TransferDocument, doc.id)
run2 = TransferRun.query.filter_by(run_no=run2.run_no).first()
assert row.status == "blocked_recoverable"
assert row.result_code == "file_changed"
# 断言意图:P2-1——executing 单遇门禁失败统一落 technical_failed(不留组锁悬挂),
# Run 终态与单一致(失败族)。
assert reused.status == "technical_failed"
assert run2.status == "failed"
# [修复后重跑] 行再次重查回 ready → 新 Run 复用同单全量重跑 → 投影非空。
patch_source_file_status()
row.status = "ready_to_execute"
row.result_code = None
row.result_message = None
db.session.commit()
third = prepare_execution(item_ids=[row.id], deps=deps)
run3 = TransferRun.query.filter_by(run_no=third.run_no).first()
execute_run(run_id=run3.id, deps=deps)
db.session.expire_all()
run3 = TransferRun.query.filter_by(run_no=run3.run_no).first()
reused = db.session.get(TransferDocument, doc.id)
row = db.session.get(TransferInvoiceItem, row.id)
# 断言意图:终态与投影一致——单/行/Run 同成功族,_build_run_result 投影非空。
assert reused.status == "success"
assert run3.status == "success"
assert run2.status == "success"
assert row.status == "success"
restored = get_run_projection(run3.run_no)
restored = get_run_projection(run2.run_no)
assert len(restored["result"]["external_documents"]) == 1
assert restored["result"]["exceptions"] == []
db.session.expire_all()
@@ -785,18 +779,23 @@ def get_run_projection(run_no: str) -> dict:
# ---------------------------------------------------------------------------
# 评审修正 P2-1:executing 单遇二次门禁失败 → technical_failed(不留组锁悬挂)
# 评审修正 P2-1 历史段:executing 单遇门禁失败曾落 technical_failed——
# 该门禁已随文件版本对账退役(2026-10-22),本用例改为锁定新行为
# ---------------------------------------------------------------------------
def test_recheck_failure_marks_executing_order_technical_failed(
def test_executing_stalled_order_executes_despite_file_version_change(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""上次 worker 中途搁浅的 executing 单,本次门禁复核失败 → 单 technical_failed
(可被 D18 关闭释放组锁),行阻断、Run failed、零外部写入。"""
"""上次 worker 中途搁浅的 executing 单,文件版本变化后重跑仍正常执行到底。
[断言意图] 门禁退役(2026-10-22):executing 搁浅单不再因文件 Hash 复核失败
落 technical_failed——逐单执行照常走写前库存复查(账面 500==500 通过),
单/行/Run 同成功族、ERP 恰一次写入。
"""
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
@@ -808,12 +807,11 @@ def test_recheck_failure_marks_executing_order_technical_failed(
execute_run(run_id=run.id, deps=deps)
db.session.expire_all()
doc = db.session.get(TransferDocument, doc.id)
# 断言意图:P2-1——executing 单门禁失败同样落 technical_failed(而非停在 executing)。
assert doc.status == "technical_failed"
assert doc.error_code == "file_changed"
# [断言意图] 版本变化不再拦截:搁浅单继续执行成功,行 success、ERP 恰一次写入。
assert doc.status == "success"
linked = TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
assert all(item.status == "blocked_recoverable" for item in linked)
assert erp.write_calls() == []
assert all(item.status == "success" for item in linked)
assert len(erp.write_calls()) == 1
db.session.expire_all()
@@ -829,13 +827,13 @@ def test_serialize_run_orders_projects_multi_status_order_list(
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500", unit="个"),
_row("Receipt", 2, "HOX-B", "LOT-20", "MAT-002", "2026-08-04", "700", unit="PCS"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
docs = _docs_of(run)
assert len(docs) == 2
# 按单号注入写场景:收料日期 08-04 单失败、08-05 单成功(组建单按组键升序)。
by_date = {doc.receipt_date: doc for doc in docs}
by_date = {doc.movement_date: doc for doc in docs}
erp.write_scenarios_by_doc[by_date["2026-08-04"].doc_no] = "business_failed"
execute_run(run_id=run.id, deps=deps)
@@ -846,13 +844,13 @@ def test_serialize_run_orders_projects_multi_status_order_list(
assert len(orders) == 2
# 断言意图:单序稳定(2026-09-29 投影排序=收料日期→数据源→库位,跨数据源
# 不再随建单序乱序;本例同数据源,收料日期升序)。
assert [t["receipt_date"] for t in orders] == ["2026-08-04", "2026-08-05"]
assert [t["movement_date"] for t in orders] == ["2026-08-04", "2026-08-05"]
failed, success = orders
# 断言意图:计划 Task 11 JSON 规格逐键——order 八键、line 七键(+invoice_no:
# 行级溯源收料通知号 2026-09-29 契约扩充;+reason:框线图失败行原因展示契约,
# 控制器裁决扩充,T13-3)。
assert set(failed.keys()) == {
"doc_no", "receipt_date", "from_warehouse", "to_warehouse",
"doc_no", "movement_date", "from_warehouse", "to_warehouse",
"status", "erp_document_no", "error_message", "lines",
}
assert failed["status"] == "business_failed"
@@ -882,15 +880,24 @@ def test_order_lines_group_by_external_lot_form():
Why: ERP 行粒度=外部批号身份;WMS 文件批号 WTP 形态对应 ERP 账面 HOW 形态
(2026-09-25 生产实证)。聚合前派生,行下传 lot_no 即外部形态。
"""
# [出生翻转] 批号派生按行所属匹配快照的转换规则(scope_json.transform_rules):
# 构造携带 WTP→HOW 规则的匹配对象并挂到两行(transient 赋值,不触库)。
matching = TransferMatching(
matching_no="MTG-LOT", business_date="2026-08-07", status="success",
scope_json={"transform_rules": [
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
]},
counts_json={}, matching_hash="sha256:lot",
)
item_wtp = TransferInvoiceItem(
invoice_no="HOX-900", material_no="MAT-900", lot_no="WTP26060612",
from_warehouse="W1", to_warehouse="W2",
receipt_quantity="200", unit="PCS",
movement_quantity="200", unit="PCS", matching=matching,
)
item_how = TransferInvoiceItem(
invoice_no="HOX-901", material_no="MAT-900", lot_no="HOW26060612",
from_warehouse="W1", to_warehouse="W2",
receipt_quantity="50", unit="PCS",
movement_quantity="50", unit="PCS", matching=matching,
)
lines = _build_order_lines([item_wtp, item_how])
# [断言意图] WTP/HOW 两形态同属一个 ERP 批次 → 聚合为一行且数量相加,
@@ -908,13 +915,21 @@ def test_serialize_order_reason_join_uses_external_lot_form():
_build_order_lines 聚合键必须经同一 external_lot_no 派生,否则
WTP 前缀行投影出空品名/空原因。
"""
matching = TransferMatching(
matching_no="MTG-LOT-2", business_date="2026-08-07", status="success",
scope_json={"transform_rules": [
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
]},
counts_json={}, matching_hash="sha256:lot",
)
item = TransferInvoiceItem(
invoice_no="HOX-900", material_no="MAT-900", material_name="汇流排",
lot_no="WTP26060612", from_warehouse="W1", to_warehouse="W2",
receipt_quantity="200", unit="PCS", result_message="strict quantity mismatch",
movement_quantity="200", unit="PCS", result_message="strict quantity mismatch",
matching=matching,
)
doc = SimpleNamespace(
doc_no="DOC-1", receipt_date="2026-08-05", from_warehouse="W1",
doc_no="DOC-1", movement_date="2026-08-05", from_warehouse="W1",
to_warehouse="W2", status="failed", erp_document_no=None, error_message=None,
)
order = serialize_order(doc, [item])
@@ -922,3 +937,197 @@ def test_serialize_order_reason_join_uses_external_lot_form():
assert line["lot_no"] == "HOW26060612"
assert line["material_name"] == "汇流排"
assert line["reason"] == "strict quantity mismatch"
# ---------------------------------------------------------------------------
# Task 12 档级封存回写(规格 §9 防二次执行):票据成功 → 档 transfer_executed=true
# ---------------------------------------------------------------------------
def test_order_success_seals_ledger_records(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""执行成功落 ERP 单号时回写 items 关联的档记录:transfer_executed=true + executed_doc_no。"""
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
_row("Receipt", 2, "HOM-B", "LOT-20", "MAT-002", "2026-08-05", "700"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
record_ids = [
item.ledger_record_id
for item in TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
if item.ledger_record_id is not None
]
assert record_ids # 出生翻转后行必挂档
execute_run(run_id=run.id, deps=deps)
db.session.expire_all()
erp_no = erp.write_calls()[0].document_no
from app.models import TransferMovementLedger
sealed = {r.id: r for r in db.session.query(TransferMovementLedger).filter(
TransferMovementLedger.id.in_(record_ids)).all()}
# [断言意图] 档级封存回写:单内行关联的全部档记录封存位=true 且单号=ERP 单号
# (防二次执行的档级兜底,规格 §9)。
assert all(sealed[rid].transfer_executed is True for rid in record_ids)
assert {sealed[rid].executed_doc_no for rid in record_ids} == {erp_no}
db.session.expire_all()
def test_order_success_seal_is_idempotent_and_stays_sealed_on_duplicate(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""封存回写幂等:重复回写/复用单以 duplicate_success 重跑后封存位恒 true 不报错。"""
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
outcome = prepare_execution(item_ids=[i.id for i in _ready_items()], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
execute_run(run_id=run.id, deps=deps)
db.session.expire_all()
doc = db.session.get(TransferDocument, doc.id)
assert doc.status == "success"
# 幂等回写(同值覆盖不抛错、封存位不变)。
from app.models import TransferMovementLedger
from app.services.in_transit_transfer.execution_service import _seal_ledger_records
items = TransferInvoiceItem.query.filter_by(document_id=doc.id).all()
_seal_ledger_records(items, executed_doc_no=doc.erp_document_no)
db.session.commit()
db.session.expire_all()
sealed = db.session.query(TransferMovementLedger).filter(
TransferMovementLedger.id.in_([i.ledger_record_id for i in items if i.ledger_record_id])).all()
assert all(r.transfer_executed is True for r in sealed)
# [断言意图] 复用单 duplicate_success 重跑:封存位恒 true(封存事实不可逆)。
run2 = TransferRun.query.filter_by(run_no=outcome.run_no).first()
execute_run(run_id=run2.id, deps=deps)
db.session.expire_all()
sealed = db.session.query(TransferMovementLedger).filter(
TransferMovementLedger.id.in_([i.ledger_record_id for i in items if i.ledger_record_id])).all()
assert all(r.transfer_executed is True for r in sealed)
db.session.expire_all()
def test_order_failure_does_not_seal_ledger_records(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""执行失败(business_failed)不封存:记录仍可被圈定/待匹配可见。"""
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
items = _ready_items()
outcome = prepare_execution(item_ids=[i.id for i in items], deps=deps)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
doc = _doc_for(run)
erp.write_scenarios_by_doc[doc.doc_no] = "business_failed"
execute_run(run_id=run.id, deps=deps)
db.session.expire_all()
from app.models import TransferMovementLedger
record_ids = [i.ledger_record_id for i in TransferInvoiceItem.query.filter_by(
document_id=doc.id).all() if i.ledger_record_id is not None]
sealed = db.session.query(TransferMovementLedger).filter(
TransferMovementLedger.id.in_(record_ids)).all()
# [断言意图] 未成事实不封存:失败单的档记录保持可圈定(重跑/重新匹配合法)。
assert all(r.transfer_executed is False and r.executed_doc_no is None for r in sealed)
db.session.expire_all()
def test_file_version_change_no_longer_blocks_execution(
transfer_db, dbs_ready_file, patch_source_file_status, seq_loader,
):
"""文件版本对账门禁退役(2026-10-22):档记录 sha 滞后最新文件不再拒绝执行
(部分导出缺席≠失效);行级 file_current 徽标仍提示滞后,防护下沉写前库存复查。"""
deps, erp = _setup(dbs_ready_file, patch_source_file_status, [
_row("Receipt", 1, "HOM-A", "LOT-10", "MAT-001", "2026-08-05", "500"),
])
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
item = _ready_items()[0]
from app.models import TransferMovementLedger
record = db.session.get(TransferMovementLedger, item.ledger_record_id)
# 档记录滞后最新文件(记录 e,最新投影 f):旧门禁在此抛 TRANSFER.FILE_CHANGED。
record.file_sha256 = "e" * 64
db.session.commit()
patch_source_file_status({"DBS-AWSBI": "f" * 64})
outcome = prepare_execution(item_ids=[item.id], deps=deps)
assert outcome.run_no # [断言意图] 版本滞后不再拒绝执行(不回退旧门禁)
run = TransferRun.query.filter_by(run_no=outcome.run_no).first()
execute_run(run_id=run.id, deps=deps)
db.session.expire_all()
item = db.session.get(TransferInvoiceItem, item.id)
assert item.status == "success" # 写前复查(账面 500==500)通过后正常写 ERP
# [断言意图] 行级「文件已更新」徽标仍提示滞后(提示不拦截,与门禁退役配套)。
restored = restore_matching(summary.matching_id, deps=deps)
restored_item = next(i for i in restored["items"] if i.invoice_no == "HOM-A")
assert restored_item.file_current is False
def test_file_current_badge_uses_outbound_evidence_for_outbound_rows(
transfer_db, monkeypatch, seq_loader,
):
"""出站档行的 file_current 徽标按出站文件 sha 计算,不拿入站投影比较。
核心逻辑:同一来源入站投影 sha 与出站不同。出站档 file_sha256 等于出站投影
→ 徽标 file_current=True(执行门禁已退役 2026-10-22,本用例只锁徽标口径;
若徽标误用入站投影,file_current 为假)。
"""
del seq_loader # 夹具注入单号序列;本用例只确认门禁放行。
out_sha = "o" * 64
in_sha = "i" * 64
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
"""入站与出站返回不同 sha,用来区分门禁读了哪一条流。"""
del source_code
sha = out_sha if record_kind == "outbound" else in_sha
return {
"file_status": "ready", "has_ready_file": True,
"file_no": f"{record_kind}-file", "file_sha256": sha,
}
monkeypatch.setattr(
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
_resolve,
)
monkeypatch.setattr(
"app.services.in_transit_transfer.execution_service.resolve_source_file_status",
_resolve,
)
deps, erp, _rpa = make_transfer_deps()
erp.seed_stock("MAT-OUT", "DBS-TRANSIT", "LOT-OUT", "100")
db.session.add(TransferMovementLedger(
source_code="DBS-AWSBI", record_kind="outbound",
doc_no="HOX-OUT", line_no="1", line_seq="", in_out_flag="",
material_code="MAT-OUT", material_name="出站物料", specification="",
lot_no="LOT-OUT", quantity="100", unit="PCS",
warehouse_code="", storage_code="", movement_date="2026-08-05",
source_file_id=None, file_version="v1", file_sha256=out_sha,
sheet_name="Shipment", row_no=1, updated_at=datetime.utcnow(),
transfer_executed=False,
))
db.session.commit()
summary = create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps,
transfer_type="in_transit_to_hub",
)
restored = restore_matching(summary.matching_id, deps=deps)
row = next(item for item in restored["items"] if item.invoice_no == "HOX-OUT")
# [断言意图] 入站 sha 与档不同;file_current 仍为真,说明比的是出站证据文件。
assert row.file_current is True
item = TransferInvoiceItem.query.filter_by(invoice_no="HOX-OUT").one()
assert item.ledger_record.record_kind == "outbound"
assert item.status == "ready_to_execute"
outcome = prepare_execution(item_ids=[item.id], deps=deps)
# [断言意图] 执行照常提交(门禁已退役,本行仅确认链路完好)。
assert outcome.run_no
@@ -0,0 +1,51 @@
"""字段转换引擎契约:前缀替换链式生效、字段白名单、原值不篡改(返回新值)。
用途:锁定 field_transforms 引擎对外契约——TRANSFORM_FIELDS/TRANSFORM_OPS 白名单
校验(错误码 TRANSFER.TRANSFORM_RULE_INVALID)、apply 按序链式派生与
None/空串透传;Task 11(六边界点接线)与 Task 5/6(校验与 UI)消费本契约。
依赖:app.core.errors.ValidationError、field_transforms 引擎。
逻辑:纯函数测试(pure_unit),不创建 Flask/DB;仅断言内存派生行为,
不触碰调拨类型模型与匹配快照(那些由各自任务的契约测试覆盖)。
"""
from __future__ import annotations
import pytest
from app.core.errors import ValidationError
from app.services.in_transit_transfer.field_transforms import (
apply_field_transforms, parse_transform_rules,
)
pytestmark = pytest.mark.pure_unit
RULES = parse_transform_rules([
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
])
def test_prefix_replace():
"""命中前缀派生新值;未命中前缀恒等返回原值。"""
assert apply_field_transforms("lot_no", "WTP26062302", RULES) == "HOW26062302" # WTP→HOW 替换
assert apply_field_transforms("lot_no", "ABC123", RULES) == "ABC123" # 非 WTP 前缀不替换
def test_none_and_empty_passthrough():
"""None 与空串原样透传,不做替换(防 NoneType.startswith 崩溃)。"""
assert apply_field_transforms("lot_no", None, RULES) is None
assert apply_field_transforms("lot_no", "", RULES) == ""
def test_chained_rules_apply_in_order():
"""多条规则按配置序链式生效:WTP→HOW 后再 HOW→HOWX。"""
rules = parse_transform_rules([
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"},
{"field": "lot_no", "op": "prefix_replace", "source": "HOW", "target": "HOWX"},
])
assert apply_field_transforms("lot_no", "WTP1", rules) == "HOWX1" # 两条规则先后各命中一次
def test_field_whitelist():
"""字段不在 TRANSFORM_FIELDS 白名单必须拒绝(校验在 parse 期,非 apply 期)。"""
with pytest.raises(ValidationError):
parse_transform_rules([{"field": "quantity", "op": "prefix_replace", "source": "A", "target": "B"}])
@@ -12,16 +12,16 @@ import pytest
from app.services.in_transit_transfer.file_preparation import (
FilePreparationResult,
ReadyReceiptFile,
ReceiptFileRepository,
ensure_receipt_file_ready,
ReadyInboundFile,
InboundFileRepository,
ensure_inbound_file_ready,
)
from tests.services.in_transit_transfer.fakes import FakeRPA
from tests.services.in_transit_transfer.repo_fakes import FakeReceiptFileRepository
from tests.services.in_transit_transfer.repo_fakes import FakeInboundFileRepository
def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyReceiptFile:
return ReadyReceiptFile(
def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyInboundFile:
return ReadyInboundFile(
source_code=source_code,
business_date=business_date,
file_no=f"REC-{source_code}-001",
@@ -33,9 +33,9 @@ def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08
def test_ready_file_reused_without_rpa_trigger():
"""当日 ready 文件存在 → 复用(stage=file_ready),不触发 RPA。"""
repository = FakeReceiptFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()})
repository = FakeInboundFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()})
rpa = FakeRPA()
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -46,9 +46,9 @@ def test_ready_file_reused_without_rpa_trigger():
def test_missing_file_triggers_rpa_once():
"""缺文件 → 触发 RPA 一次并进入 waiting_rpa_callback。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -60,9 +60,9 @@ def test_missing_file_triggers_rpa_once():
def test_active_source_job_binds_existing_task_no_new_trigger():
"""存在活动 Source Job → 绑定已有任务,不重复触发 RPA。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
)
@@ -72,10 +72,10 @@ def test_active_source_job_binds_existing_task_no_new_trigger():
def test_concurrent_requests_share_one_trigger():
"""并发请求携带同一活动键 → 全部绑定已有任务,不重复触发 RPA。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
for _ in range(3):
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
)
@@ -85,13 +85,13 @@ def test_concurrent_requests_share_one_trigger():
def test_without_active_key_each_call_triggers_once():
"""无活动键时每次调用各触发一次;幂等由调用方 SourceJob 唯一键兜底。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
ensure_receipt_file_ready(
ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
ensure_receipt_file_ready(
ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -100,10 +100,10 @@ def test_without_active_key_each_call_triggers_once():
def test_rpa_trigger_failure_is_fail_closed():
"""RPA 触发失败 → stage=failed 且带错误码,不误报 file_ready。"""
repository = FakeReceiptFileRepository()
repository = FakeInboundFileRepository()
rpa = FakeRPA()
rpa.fail_on.add("DBS-AWSBI")
result = ensure_receipt_file_ready(
result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -113,14 +113,14 @@ def test_rpa_trigger_failure_is_fail_closed():
def test_dbs_and_crane_sources_isolated():
"""DBS 失败不影响 Crane 的文件准备(来源隔离)。"""
repository = FakeReceiptFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")})
repository = FakeInboundFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")})
rpa = FakeRPA()
rpa.fail_on.add("DBS-AWSBI")
dbs_result = ensure_receipt_file_ready(
dbs_result = ensure_inbound_file_ready(
source_code="DBS-AWSBI", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
crane_result = ensure_receipt_file_ready(
crane_result = ensure_inbound_file_ready(
source_code="CRANE-SZ", business_date="2026-08-06",
repository=repository, rpa_trigger=rpa,
)
@@ -12,8 +12,8 @@ from datetime import datetime, timedelta
from app import db
from app.models import TransferSourceJob, TransferRun
from app.services.in_transit_transfer.receipt_callback_bridge import (
advance_source_job_from_receipt_callback,
from app.services.in_transit_transfer.inbound_callback_bridge import (
advance_source_job_from_inbound_callback,
)
@@ -31,7 +31,7 @@ def _make_waiting_job(run_no: str, source_code: str = "DSV360_AWSDU") -> Transfe
def test_success_callback_advances_job_to_file_ready(app):
"""成功回调(含文件号/sha256)应把最新等待任务推进为 file_ready。"""
job = _make_waiting_job("RUN-BRIDGE-1")
advanced = advance_source_job_from_receipt_callback(
advanced = advance_source_job_from_inbound_callback(
source_code=job.source_code, file_no="42", file_sha256="abc", callback_ok=True,
)
assert advanced is not None and advanced.status == "file_ready"
@@ -41,7 +41,7 @@ def test_success_callback_advances_job_to_file_ready(app):
def test_recover_stale_waiting_source_jobs(app):
"""超过收料回调超时的等待任务回收为 failed;新任务不动。"""
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
from app.services.in_transit_transfer.inbound_callback_bridge import recover_stale_waiting_source_jobs
stale = _make_waiting_job("RUN-BRIDGE-STALE-1", "DSV360_AWSDU")
stale.updated_at = datetime.utcnow() - timedelta(seconds=3600)
@@ -51,5 +51,5 @@ def test_recover_stale_waiting_source_jobs(app):
db.session.expire_all()
assert recovered == 1
assert db.session.get(TransferSourceJob, stale.id).status == "failed"
assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_RECEIPT_CALLBACK_TIMEOUT"
assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_INBOUND_CALLBACK_TIMEOUT"
assert db.session.get(TransferSourceJob, fresh.id).status == "waiting_rpa_callback"
@@ -0,0 +1,175 @@
"""在途调拨异动文件字段/结构校验测试(L0 纯单元)。
用途:验证必填列缺失、空值、非法数量(0/负数/非数字)、非法日期与
来源身份不一致均整行阻断并抛出 MovementFileSchemaError。
依赖:app.services.in_transit_transfer.file_parser(纯函数)。
逻辑:解析不接触文件存储;所有错误带行号细节,供预检页展示原因。
tt14 入站化后统一走 movement 契约行(parse_movement_rows 单一入口),
本文件聚焦「原始行 → 调拨语义字段」投影后的校验行为(与
test_movement_parser 的契约映射用例互补)。
"""
from __future__ import annotations
from datetime import date
from decimal import Decimal
import pytest
from app.services.in_transit_transfer.file_parser import (
MovementFileSchemaError,
ParsedMovementRow,
parse_movement_rows,
)
pytestmark = pytest.mark.pure_unit
VALID_ROW = {
"sheet": "Movement",
"row_no": 10,
"doc_no": "INV-001",
"material_code": "MAT-001",
"material_name": "连接器组件",
"specification": "A 型 / 24PIN",
"movement_date": "2026-08-05",
"quantity": "500",
"source_code": "DBS-AWSBI",
}
def _rows(**overrides) -> list[dict]:
"""以 VALID_ROW 为基底覆盖字段构造测试行。"""
base = dict(VALID_ROW)
base.update(overrides)
return [base]
def test_valid_rows_parse():
"""合法行解析出全部字段(数量 Decimal、日期 date)。"""
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
assert len(parsed) == 1
row = parsed[0]
assert isinstance(row, ParsedMovementRow)
assert row.invoice_no == "INV-001"
assert row.material_no == "MAT-001"
assert row.material_name == "连接器组件"
assert row.specification == "A 型 / 24PIN"
assert row.movement_date == date(2026, 8, 5)
assert row.movement_quantity == Decimal("500")
assert row.sheet == "Movement"
assert row.row_no == 10
def test_missing_invoice_no_rejected():
"""单号(doc_no)缺失必须整行阻断(管控保留:配置错列由解析失败暴露)。"""
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no=""))
def test_missing_material_no_row_skipped_not_blocked():
"""料号空行=非可用异动行:静默跳过——不管控、不进异动表(2026-10-21 实测反转)。
Why: CRANE/Lognet 出站报告携带说明行/占位行(料号为空),旧逻辑按
missing_material_no 整文件阻断致出站解析失败;此类行不是可用异动事实,
跳过语义与零数量行同家族(_is_unusable_movement_row)。
"""
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(material_code=""))
assert parsed == []
def test_empty_material_rows_mixed_with_valid_rows_only_valid_parsed():
"""料号空行与合法行混排:只放行有料号的行,空料号行不阻断整文件。"""
rows = [
dict(VALID_ROW, row_no=2, material_code=""), # 说明/占位行:跳过
dict(VALID_ROW, row_no=3, material_code="MAT-002", doc_no="INV-002"),
]
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
assert [row.row_no for row in parsed] == [3]
def test_material_and_invoice_both_empty_row_skipped():
"""料号与单号双空行按料号空行处理:静默跳过而非 missing_invoice_no 阻断。"""
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no="", material_code=""))
assert parsed == []
def test_invalid_quantity_rejected():
"""非数字数量必须阻断。"""
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc"))
def test_zero_quantity_stamped_row_skipped():
"""零数量异动行(日期已盖章、数量 0)为非可用异动事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。"""
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="0"))
assert parsed == []
def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed():
"""合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。"""
rows = [
dict(VALID_ROW, row_no=788, doc_no="WTP26082227", quantity="0",
movement_date="2026-10-01 14:37:43"),
dict(VALID_ROW, row_no=789, doc_no="INV-002", quantity="120"),
]
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
assert [row.row_no for row in parsed] == [789]
assert parsed[0].invoice_no == "INV-002"
def test_negative_quantity_rejected():
"""负数数量必须阻断。"""
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="-5"))
def test_invalid_date_rejected():
"""非法日期必须阻断。"""
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99"))
def test_source_identity_mismatch_rejected():
"""行内来源与任务来源不一致(Callback 身份漂移)必须阻断。"""
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
def test_missing_sheet_or_row_no_rejected():
"""Sheet/原始行号缺失无法追溯,必须阻断。"""
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0))
def test_material_name_and_specification_optional():
"""品名/规格允许为空(后续由明细 DTO 展示空值)。"""
parsed = parse_movement_rows(
source_code="DBS-AWSBI",
rows=_rows(material_name="", specification=""),
)
assert parsed[0].material_name == ""
assert parsed[0].specification == ""
def test_error_carries_row_details():
"""错误细节必须携带行号与原因,供页面定位。"""
with pytest.raises(MovementFileSchemaError) as excinfo:
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, quantity="abc"))
details = excinfo.value.details
assert any(str(item.get("row_no")) == "77" for item in details.get("rows", []))
def test_schema_error_message_carries_row_details():
"""诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。"""
rows = [
dict(VALID_ROW, row_no=5, doc_no=""),
dict(VALID_ROW, row_no=9, quantity="abc"),
]
with pytest.raises(MovementFileSchemaError) as exc_info:
parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
# [断言意图] 消息不再只是通用 "movement file schema invalid",须含行号与原因;
# 明细同时保留在 details.rows 供管理端展示。
text = str(exc_info.value) or (exc_info.value.message or "")
assert "row 5" in text and "missing_invoice_no" in text
detail_rows = (exc_info.value.details or {}).get("rows") or []
assert {"row_no": 5, "reason": "missing_invoice_no"} in detail_rows
@@ -0,0 +1,320 @@
"""tests/services/in_transit_transfer/test_inbound_report_handler.py
用途:阶段 B Task 7——inbound 报表事实处理函数(handle_inbound_report)的契约测试:
未注册不推进、处理函数先失败后成功只推进一次且文件只留一行、无等待任务时回调成功、
同来源两单元分属两排程 run 时收口只打「本次回调收尾的单元」的 run(修复轮)。
依赖:app(SQLite)fixture、freight_rpa.reports.dispatch(注册表)、
freight_rpa.inbound.report_archive.ingest_inbound_callback(归档+投递入口)、
in_transit_transfer.inbound_callback_bridge / TransferSourceJob(调拨侧事实)。
逻辑:复刻 test_report_fact_dispatch 的注册表隔离与归档 IO 替身——组合根
(create_app→register_inbound_sinks)启动即注册 handle_inbound_report,
未注册用例必须先清空注册表,否则 404 断言假绿;success 归档走替身 IO
(drop 根读取返回注入字节、MinIO 上传 no-op),不依赖真实文件系统;
收口定位用例构造两个 awaiting 排程 run(各挂一个同来源单元),
对旧单元回调后断言只有旧 run 被收口、新 run 保持等待。
"""
from __future__ import annotations
import hashlib
import pytest
@pytest.fixture
def db_session(app):
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
@pytest.fixture(autouse=True)
def _reset_report_handlers():
"""每用例隔离 dispatch 注册表(模块级全局字典),避免用例间处理函数串扰。
[断言意图] 未注册用例必须跑在"干净注册表"上——组合根启动已注册
handle_inbound_report,不清空会让 FREIGHT_RPA.SINK_NOT_REGISTERED 断言假绿。
"""
from app.services.freight_rpa.reports import dispatch as dispatch_module
saved = dict(dispatch_module._REPORT_HANDLERS)
dispatch_module._REPORT_HANDLERS.clear()
yield
dispatch_module._REPORT_HANDLERS.clear()
dispatch_module._REPORT_HANDLERS.update(saved)
@pytest.fixture(autouse=True)
def _fake_archive_io(monkeypatch):
"""替身归档 IO:drop 根读取返回注入字节,MinIO 上传 no-op。
核心逻辑:与 test_report_fact_dispatch 同一 monkeypatch 姿态(patch
report_archive 模块属性),使 success 归档分支脱离真实文件系统与对象存储。
"""
from app.services.freight_rpa.inbound import report_archive
monkeypatch.setattr(report_archive, "_read_inbound_callback_file", lambda _path: b"handler-bytes")
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
# callback_id 唯一约束的测试序号(跨用例递增,避免 unique 冲突)。
_CALLBACK_SEQ: dict[str, int] = {"n": 0}
def _next_callback_id() -> str:
"""生成跨用例唯一的 callback_id(unit run 唯一约束)。"""
_CALLBACK_SEQ["n"] += 1
return f"inbound-handler-{_CALLBACK_SEQ['n']}"
def _waiting_job(source_code: str):
"""构造一个未落库的 waiting_rpa_callback 来源任务(先建 TransferRun 满足外键)。
核心逻辑:TransferRun 只 add+flush(拿 run_id);TransferSourceJob 由调用方
add+commit——与用例体里的 db_session.add(job) 契约一致。
"""
from app import db
from app.models import TransferRun, TransferSourceJob
run = TransferRun(
run_no=f"RUN-HANDLER-{_next_callback_id()}",
business_date="2026-09-17",
status="preparing_files",
trigger_type="manual",
)
db.session.add(run)
db.session.flush()
return TransferSourceJob(run_id=run.id, source_code=source_code, status="waiting_rpa_callback")
def _success_payload_for(source_code: str) -> dict:
"""构造一个挂种子站点的 awaiting 单元及其 success 回调载荷(可通过 schema 校验)。
核心逻辑:source_code 列允许测试值(如 "DSV",与调拨任务匹配),source_id
外键挂 conftest 种子站点 DSV360_AWSDU;替身 IO 注入字节与 sha256 对齐。
"""
from app import db
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = FreightRpaInboundUnitRun(
source_id=anchor.id,
source_code=source_code,
connector_type="dbs",
callback_id=_next_callback_id(),
status="awaiting_rpa",
config_snapshot_json={},
)
db.session.add(unit)
db.session.commit()
data = b"handler-bytes"
return {
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit.callback_id,
"status": "success",
"file_path": f"receipt_{unit.id}.xlsx",
"original_filename": "receipt.xlsx",
"sha256": hashlib.sha256(data).hexdigest(),
}
def test_unregistered_transfer_handler_leaves_job_waiting(app, db_session):
"""未注册处理函数:归档 404 后调拨任务必须原地保持 waiting_rpa_callback。"""
from app.core.errors import AppError
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
job = _waiting_job(source_code="DSV")
db_session.add(job)
db_session.commit()
# 不注册 handle_inbound_report
with pytest.raises(AppError) as exc:
ingest_inbound_callback(_success_payload_for("DSV"))
assert exc.value.code == "FREIGHT_RPA.SINK_NOT_REGISTERED"
db_session.refresh(job)
assert job.status == "waiting_rpa_callback"
def test_handler_fail_then_success_advances_once(app, db_session, monkeypatch):
"""处理函数先失败后成功:文件只留一行,调拨任务只推进一次到 file_ready。"""
from app.models import FreightRpaInboundReportFile
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
job = _waiting_job(source_code="DSV")
db_session.add(job)
db_session.commit()
calls = {"n": 0}
def flaky(fact: ReportFact) -> None:
calls["n"] += 1
if calls["n"] == 1:
raise RuntimeError("once")
handle_inbound_report(fact)
register_report_handler("inbound", flaky)
payload = _success_payload_for("DSV")
with pytest.raises(RuntimeError):
ingest_inbound_callback(payload)
ingest_inbound_callback(payload)
db_session.refresh(job)
assert job.status == "file_ready"
assert FreightRpaInboundReportFile.query.count() == 1
def test_no_waiting_job_is_success(app, db_session):
"""无等待中的调拨任务:处理函数照常成功返回,且不产生任何调拨来源任务行。"""
from app.models import TransferSourceJob
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
register_report_handler("inbound", handle_inbound_report)
ingest_inbound_callback(_success_payload_for("DSV"))
assert TransferSourceJob.query.filter_by(source_code="DSV").count() == 0
def _awaiting_schedule_run(db_session, *, schedule_no: str, run_no: str, awaiting: bool = True):
"""构造一个收料排程 task/run 对;awaiting=True 时挂 awaiting_inbound_rpa 等待态。"""
from app.models import ScheduleRun, ScheduleTask
task = ScheduleTask(
schedule_no=schedule_no, name=f'Receipt {schedule_no}', schedule_type='platform_job',
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
)
db_session.add(task)
db_session.flush()
run = ScheduleRun(
run_no=run_no, schedule_task_id=task.id, status='running', total_count=1,
success_count=0, failed_count=0, skipped_count=0,
response_summary_json={'awaiting_inbound_rpa': awaiting},
)
db_session.add(run)
db_session.commit()
return run
def _unit_on_run(db_session, run, *, callback_id: str):
"""在指定排程 run 下造一个挂种子站点的 awaiting 收料单元(source_code=DSV)。"""
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
anchor = FreightRpaSource.query.filter_by(source_code="DSV360_AWSDU").one()
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id, source_id=anchor.id, source_code="DSV",
connector_type="dbs", callback_id=callback_id,
status="awaiting_rpa", config_snapshot_json={},
)
db_session.add(unit)
db_session.commit()
return unit
def test_finalize_targets_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch):
"""同来源两个单元分属两个排程 run:本回调收尾的单元(按文件反查)只收口它自己的 run。
[断言意图] 修复「按来源取最新单元」的错位:旧逻辑会把收口打到更新单元的 run,
本回调刚完成的 run 永久滞留 awaiting_inbound_rpa。
"""
from app.models import ScheduleRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file",
lambda _path: b"handler-bytes",
)
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
register_report_handler("inbound", handle_inbound_report)
run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-OLD", run_no="RUN-ONHAND-OLD")
run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-ONHAND-NEW", run_no="RUN-ONHAND-NEW")
unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-old")
_unit_on_run(db_session, run_new, callback_id="inbound-handler-new")
ingest_inbound_callback({
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit_old.callback_id,
"status": "success",
"file_path": "receipt_old.xlsx",
"original_filename": "receipt.xlsx",
"sha256": hashlib.sha256(b"handler-bytes").hexdigest(),
})
db_session.rollback()
db_session.expire_all()
# [断言意图] 本回调收尾的是旧单元:只有旧 run 被收口(全终态 → success)。
refreshed_old = db_session.get(ScheduleRun, run_old.id)
assert refreshed_old.status == "success"
assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_rpa")
# 新单元的 run 原样保持等待态——未被本次回调误收口。
refreshed_new = db_session.get(ScheduleRun, run_new.id)
assert refreshed_new.status == "running"
assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_rpa") is True
def test_finalize_targets_failed_unit_of_this_callback_not_newest_unit(app, db_session, monkeypatch):
"""同来源两单元、同失败错误文本、分属两 run:失败回调只收口本单元(unit_run_id)的 run。
[断言意图] 修复「按来源+终态+错误文本取最新单元」的错位:错误文本碰撞时旧回调
会收口新单元的 run,本回调刚失败的 run 永久滞留 awaiting_inbound_rpa。
"""
from datetime import datetime
from app.models import ScheduleRun, FreightRpaInboundUnitRun
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file",
lambda _path: b"handler-bytes",
)
monkeypatch.setattr(
"app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes",
lambda **_kwargs: None,
)
register_report_handler("inbound", handle_inbound_report)
run_old = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-OLD", run_no="RUN-FAIL-OLD")
run_new = _awaiting_schedule_run(db_session, schedule_no="SCH-FAIL-NEW", run_no="RUN-FAIL-NEW")
unit_old = _unit_on_run(db_session, run_old, callback_id="inbound-handler-fail-old")
unit_new = _unit_on_run(db_session, run_new, callback_id="inbound-handler-fail-new")
# [RED 场景] 新单元已先以同错误文本终态失败落库——旧逻辑按 (来源, 终态, 错误文本)
# 取最新单元会命中新单元,把收口打到新 run。
unit_new.status = "failed"
unit_new.error_code = "RPA_TEST_FAIL"
unit_new.error_message = "boom"
unit_new.finished_at = datetime.utcnow()
db_session.commit()
result = ingest_inbound_callback({
"schema_version": "freight_rpa.inbound.v1",
"callback_id": unit_old.callback_id,
"status": "failed",
"error_code": "RPA_TEST_FAIL",
"error_message": "boom",
})
assert result["status"] == "failed"
db_session.rollback()
db_session.expire_all()
# [断言意图] 只有旧单元的 run 被收口(唯一单元终态失败 → failed、awaiting 清除)。
refreshed_old = db_session.get(ScheduleRun, run_old.id)
assert refreshed_old.status == "failed"
assert not (refreshed_old.response_summary_json or {}).get("awaiting_inbound_rpa")
refreshed_saved_old = db_session.get(FreightRpaInboundUnitRun, unit_old.id)
assert refreshed_saved_old.status == "failed"
assert refreshed_saved_old.error_code == "RPA_TEST_FAIL"
# 新单元的 run 原样保持等待态——未被本次回调误收口(新单元自身终态由其回调收口)。
refreshed_new = db_session.get(ScheduleRun, run_new.id)
assert refreshed_new.status == "running"
assert (refreshed_new.response_summary_json or {}).get("awaiting_inbound_rpa") is True
@@ -0,0 +1,36 @@
"""tests/services/in_transit_transfer/test_inbound_report_read_boundary.py
用途:锁定阶段 B Task 4——in_transit_transfer 包不得引用 freight_rpa 报表模型
(站点与报表文件/配置的读取一律改走 app.services.freight_rpa.reports
只读入口,业务方只按 source_code / file_id 消费)。
依赖:pathlib(纯文本扫描;无 app/DB fixture,秒级运行)。
逻辑:对包内全部 .py 逐文件做 banned 字符串扫描(含注释/docstring——模型名
出现在任何位置都算引用面),命中即 fail 并按「文件名: 模型名」逐条列出,
防止调拨域绕过只读入口直接 import 报表模型造成域间漂移。
"""
from __future__ import annotations
from pathlib import Path
def test_in_transit_does_not_import_rpa_report_models():
"""in_transit_transfer 包内任何 .py 不得出现 freight_rpa 报表模型名。
banned 集合与计划 Task 4 冻结一致:入站归档文件、入站报表配置、库存站点、
在手报表配置四类模型自本任务起归 freight_rpa 域读写;调拨域(含注释与
docstring)不得再引用其类名——命中即边界破坏,须收敛到
freight_rpa.reports.queries 的只读函数。
"""
root = Path(__file__).resolve().parents[3] / "app" / "services" / "in_transit_transfer"
banned = ("FreightRpaInboundReportFile", "FreightRpaInboundReportConfig",
"FreightRpaSource", "FreightRpaOnhandReportConfig")
hits = []
for path in root.rglob("*.py"):
text = path.read_text(encoding="utf-8")
for name in banned:
if name in text:
hits.append(f"{path.name}: {name}")
# [断言意图] hits 必须为空:任一命中都意味着调拨域仍在直接引用
# freight_rpa 报表模型(import、类型标注或文档残句),边界未闭合。
assert hits == []
@@ -1,10 +1,10 @@
"""真实收料 RPA 触发服务测试。
用途:验证 trigger_receipt_rpa / trigger_receipt_rpa_batch 按来源装配收料 trigger unit
并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
用途:验证 trigger_inbound_rpa / trigger_inbound_rpa_batch 按来源装配收料 trigger unit
并调用写者;触发先落 FreightRpaInboundUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa(_batch)、
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
依赖:app(SQLite)fixture、inbound_trigger_service.trigger_inbound_rpa(_batch)、
既有测试种子(FreightRpaProfile/FreightRpaSource)。
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False;
批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批,
parse_failed 先本地重解析不触发 RPA)。
@@ -14,20 +14,20 @@ from __future__ import annotations
import pytest
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.services.in_transit_transfer.receipt_trigger_service import (
trigger_receipt_rpa,
trigger_receipt_rpa_batch,
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
from app.services.in_transit_transfer.inbound_trigger_service import (
trigger_inbound_rpa,
trigger_inbound_rpa_batch,
)
@pytest.fixture
def receipt_source():
"""复用种子来源并为其创建收料配置。"""
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
assert source is not None
config = ShippingReceiptReportConfig(
inventory_source_id=source.id,
config = FreightRpaInboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
)
@@ -38,7 +38,7 @@ def receipt_source():
return source
def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source):
"""来源有效 → 写入 trigger 并返回 callback_id / trigger_path。"""
calls = {}
@@ -48,9 +48,9 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
calls['payload'] = payload or {}
return f'/tmp/trigger/{run_no}.json'
result = trigger_receipt_rpa(
result = trigger_inbound_rpa(
source_code='DSV360_AWSDU', business_date='2026-08-06',
reason='transfer_retry_receipt', writer=fake_writer,
reason='transfer_retry_inbound', writer=fake_writer,
)
assert result['ok'] is True
assert result['callback_id']
@@ -62,31 +62,31 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
]
assert calls['units'][0]['credential_envelope']
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
assert calls['payload']['schema_version'] == 'freight_rpa.inbound.v1'
def test_trigger_receipt_rpa_disabled_source_fails_closed(app):
def test_trigger_inbound_rpa_disabled_source_fails_closed(app):
"""来源停用 → ok=False,不写 trigger。"""
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
source.enabled = False
from app import db
db.session.commit()
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
result = trigger_inbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
assert result['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
assert result['error_code'] == 'RPA_INBOUND_CONFIG_MISSING'
def test_trigger_receipt_rpa_missing_config_fails_closed(app):
def test_trigger_inbound_rpa_missing_config_fails_closed(app):
"""来源启用但无收料配置 → ok=False。"""
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
result = trigger_inbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
"""触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
def test_trigger_inbound_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
"""触发必须先落 FreightRpaInboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
captured: dict = {}
@@ -96,28 +96,28 @@ def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receip
captured["units"] = units
return "trigger.json"
outcome = trigger_receipt_rpa(
outcome = trigger_inbound_rpa(
source_code=receipt_source.source_code, business_date="2026-09-17",
reason="transfer_retry_receipt", writer=fake_writer,
reason="transfer_retry_inbound", writer=fake_writer,
)
assert outcome["ok"] is True
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
assert unit.status == "awaiting_rpa"
# [断言意图] 按需触发无排程 run,schedule_run_id 必须为 NULL——
# PostgreSQL 上 FK 禁止 0 占位(SQLite 测试库不强制 FK,需显式守住列可空契约)。
assert unit.schedule_run_id is None
assert ShippingReceiptRpaUnitRun.__table__.columns['schedule_run_id'].nullable is True
assert FreightRpaInboundUnitRun.__table__.columns['schedule_run_id'].nullable is True
assert captured["units"][0]["unit_run_id"] == unit.id
assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id
def _bind_published_movement_profile(config: ShippingReceiptReportConfig) -> None:
"""给收料配置绑定一条已发布 movement 规则(仅满足守卫校验,不参与解析)。"""
def _bind_published_inbound_profile(config: FreightRpaInboundReportConfig) -> None:
"""给收料配置绑定一条已发布 inbound 规则(仅满足守卫校验,不参与解析)。"""
from app import db
from app.models import ShippingInventoryParsingProfile
from app.models import FreightRpaParsingProfile
profile = ShippingInventoryParsingProfile(
purpose='movement', profile_code='MOVE_TRIGGER_STD', display_name='收料异动规则',
profile = FreightRpaParsingProfile(
purpose='inbound', profile_code='MOVE_TRIGGER_STD', display_name='入站解析规则',
version=1, status='published', file_format='xlsx',
definition_json={'sheet_name': None, 'header_row_index': 1,
'field_mapping': {'doc_no': '单据编号', 'material_code': '料号',
@@ -135,77 +135,85 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
with app.app_context():
config = ShippingReceiptReportConfig.query.filter_by(
inventory_source_id=receipt_source.id).one()
_bind_published_movement_profile(config)
config = FreightRpaInboundReportConfig.query.filter_by(
source_id=receipt_source.id).one()
_bind_published_inbound_profile(config)
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
outcome = _DefaultRpaTrigger().trigger(
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
)
assert outcome["ok"] is True
# [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
# [断言意图] 真实落盘:Worker 轮询目录必须能看到 inbound_export_batch_*.json
# (批次 R 自 receipt_export_batch_* 改名,旧 glob 会把已写入的文件判成没写)。
assert list(tmp_path.glob("inbound_export_batch_*.json")), "trigger file not written"
def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt_source, tmp_path, monkeypatch):
"""收料配置存在但未绑已发布 movement 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_source, tmp_path, monkeypatch):
"""收料配置存在但未绑已发布 inbound 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
outcome = _DefaultRpaTrigger().trigger(
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
)
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 inbound trigger 文件。
assert outcome["ok"] is False
assert outcome["error_code"] == "RPA_RECEIPT_MOVEMENT_PROFILE_MISSING"
assert list(tmp_path.glob("receipt_export_batch_*.json")) == []
assert outcome["error_code"] == "RPA_INBOUND_PROFILE_MISSING"
assert list(tmp_path.glob("inbound_export_batch_*.json")) == []
def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
outcome = trigger_receipt_rpa(
outcome = trigger_inbound_rpa(
source_code=receipt_source.source_code, business_date="2026-09-17",
reason="transfer_retry_receipt", writer=lambda *a, **k: None,
reason="transfer_retry_inbound", writer=lambda *a, **k: None,
)
assert outcome["ok"] is False
unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
ShippingReceiptRpaUnitRun.id.desc()).first()
unit = FreightRpaInboundUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
FreightRpaInboundUnitRun.id.desc()).first()
assert unit.status == "failed"
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
assert unit.error_code == "RPA_INBOUND_TRIGGER_UNAVAILABLE"
# ---------------------------------------------------------------------------
# 批量触发(trigger_receipt_rpa_batch):多来源合并一个 batch trigger 文件,
# 批量触发(trigger_inbound_rpa_batch):多来源合并一个 batch trigger 文件,
# Worker 单次浏览器会话串行处理(2026-10-09 批量重试效率修复)。
# ---------------------------------------------------------------------------
@pytest.fixture
def second_receipt_source(app):
"""再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定
解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。"""
"""再造一个启用来源 + 收料配置(批量用例需要多来源);s18 起启用态要求
Excel 模板绑定(ck_freight_rpa_sources_enabled_template),解析绑定复用种子源配置行。"""
from app import db
from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig
from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaInboundReportConfig
seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
profile = ShippingRpaProfile(
seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
profile = FreightRpaProfile(
profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs',
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
)
source = ShippingInventorySource(
source = FreightRpaSource(
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
rpa_profile=profile,
parsing_profile=seed.parsing_profile, excel_template=seed.excel_template,
excel_template=seed.excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
enabled=True,
)
# s18 起在手解析绑定/报表路径归配置行,复用种子源绑定形态。
seed_config = seed.onhand_report_config
FreightRpaOnhandReportConfig(
source=source,
parsing_profile=seed_config.parsing_profile if seed_config is not None else None,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[],
)
db.session.add_all([profile, source])
db.session.flush() # 先取 source.id(新建对象 flush 前无主键)
config = ShippingReceiptReportConfig(
inventory_source_id=source.id,
config = FreightRpaInboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[],
)
@@ -214,9 +222,9 @@ def second_receipt_source(app):
return source
def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
calls: list = []
@@ -224,27 +232,27 @@ def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt
calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}})
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_receipt_rpa_batch(
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
reason='transfer_retry_receipt', writer=fake_writer,
reason='transfer_retry_inbound', writer=fake_writer,
)
# [断言意图] 合并单文件是本修复的核心:writer 恰好调用 1 次、units 装下全部来源。
assert len(calls) == 1
assert outcome['ok'] is True and outcome['triggered'] is True
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
assert calls[0]['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
assert calls[0]['payload']['schema_version'] == 'freight_rpa.inbound.v1'
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
callback_ids = {u['callback_id'] for u in calls[0]['units']}
assert len(callback_ids) == 2
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_(
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
assert {row.status for row in rows} == {'awaiting_rpa'}
assert all(row.schedule_run_id is None for row in rows)
assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']}
def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
def test_trigger_inbound_rpa_batch_skips_invalid_source(app, receipt_source):
"""单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。"""
captured: dict = {}
@@ -252,7 +260,7 @@ def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
captured['units'] = units
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_receipt_rpa_batch(
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-09',
writer=fake_writer,
)
@@ -262,36 +270,36 @@ def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
by_code = {item['source_code']: item for item in outcome['results']}
assert by_code['DSV360_AWSDU']['ok'] is True
assert by_code['DSV360_NOPE']['ok'] is False
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_INBOUND_CONFIG_MISSING'
def test_trigger_receipt_rpa_batch_all_invalid_no_trigger(app):
"""全部来源无效 → 不写 trigger,ok=False + RPA_RECEIPT_NO_TRIGGERABLE_SOURCE。"""
outcome = trigger_receipt_rpa_batch(
def test_trigger_inbound_rpa_batch_all_invalid_no_trigger(app):
"""全部来源无效 → 不写 trigger,ok=False + RPA_INBOUND_NO_TRIGGERABLE_SOURCE。"""
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_NOPE'], business_date='2026-10-09',
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_RECEIPT_NO_TRIGGERABLE_SOURCE'
assert outcome['error_code'] == 'RPA_INBOUND_NO_TRIGGERABLE_SOURCE'
def test_trigger_receipt_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
def test_trigger_inbound_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
outcome = trigger_receipt_rpa_batch(
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
writer=lambda *a, **k: None,
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
assert outcome['error_code'] == 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
rows = FreightRpaInboundUnitRun.query.filter(FreightRpaInboundUnitRun.source_code.in_(
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
assert {row.status for row in rows} == {'failed'}
assert {row.error_code for row in rows} == {'RPA_RECEIPT_TRIGGER_UNAVAILABLE'}
assert {row.error_code for row in rows} == {'RPA_INBOUND_TRIGGER_UNAVAILABLE'}
def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch):
def test_trigger_inbound_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch):
"""parse_failed 来源先本地重解析(成功则不触发 RPA),与单来源端点分层语义一致。"""
statuses = {
'DSV360_AWSDU': [
@@ -320,7 +328,7 @@ def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receip
def fake_writer(run_no, units, payload=None):
raise AssertionError('reparsed source must not be triggered via RPA')
outcome = trigger_receipt_rpa_batch(
outcome = trigger_inbound_rpa_batch(
source_codes=['DSV360_AWSDU'], business_date='2026-10-09', writer=fake_writer,
)
# [断言意图] 重解析恢复 ready → 无需写盘,整体 ok=True(请求已达成目的)。
@@ -1,9 +1,10 @@
"""在途调拨 Invoice 多行汇总与冲突测试(L0 纯单元)。
用途:验证相同 Invoice 多行只汇总收料数量并永久保留原始行追溯;
同一 Invoice 出现多料号/多收料日期时整单阻断(InvoiceConflictError)。
用途:验证相同 Invoice 多行只汇总异动数量并永久保留原始行追溯;
同一 Invoice 出现多料号/多异动日期时自然拆分(InvoiceConflictError 保留为防御)。
依赖:app.services.in_transit_transfer.invoice_aggregator + file_parser。
逻辑:汇总键为 (source_code, invoice_no);冲突判定基于料号与收料日期。
逻辑:汇总键为 (source_code, invoice_no);拆分维度为料号与异动日期。
tt14 入站化后经 parse_movement_rows(movement 契约行)构造解析行。
"""
from __future__ import annotations
@@ -13,7 +14,7 @@ from decimal import Decimal
import pytest
from app.services.in_transit_transfer.file_parser import parse_receipt_rows
from app.services.in_transit_transfer.file_parser import parse_movement_rows
from app.services.in_transit_transfer.invoice_aggregator import (
AggregatedInvoice,
aggregate_invoices,
@@ -23,19 +24,19 @@ pytestmark = pytest.mark.pure_unit
def _parsed(rows: list[dict]) -> list:
"""将原始行解析为 ParsedReceiptRow。"""
return parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
"""将原始 movement 契约行解析为 ParsedMovementRow。"""
return parse_movement_rows(source_code="DBS-AWSBI", rows=rows)
def _row(invoice_no: str, *, material_no: str = "MAT-001", material_name: str = "连接器组件",
specification: str = "A 型 / 24PIN", receipt_date: str = "2026-08-05",
quantity: str = "500", row_no: int = 10, sheet: str = "Receipt",
def _row(doc_no: str, *, material_code: str = "MAT-001", material_name: str = "连接器组件",
specification: str = "A 型 / 24PIN", movement_date: str = "2026-08-05",
quantity: str = "500", row_no: int = 10, sheet: str = "Movement",
warehouse_code: str = "WMS-A") -> dict:
return {
"sheet": sheet, "row_no": row_no, "invoice_no": invoice_no,
"material_no": material_no, "material_name": material_name,
"specification": specification, "receipt_date": receipt_date,
"receipt_quantity": quantity, "source_code": "DBS-AWSBI",
"sheet": sheet, "row_no": row_no, "doc_no": doc_no,
"material_code": material_code, "material_name": material_name,
"specification": specification, "movement_date": movement_date,
"quantity": quantity, "source_code": "DBS-AWSBI",
"warehouse_code": warehouse_code,
}
@@ -50,11 +51,11 @@ def test_same_invoice_multiple_rows_sum_quantity():
assert len(invoices) == 1
invoice = invoices[0]
assert invoice.invoice_no == "INV-001"
assert invoice.receipt_quantity == Decimal("1200")
assert invoice.movement_quantity == Decimal("1200")
assert len(invoice.raw_lines) == 2
assert invoice.raw_lines[0].row_no == 10
assert invoice.raw_lines[1].row_no == 11
assert all(line.sheet == "Receipt" for line in invoice.raw_lines)
assert all(line.sheet == "Movement" for line in invoice.raw_lines)
def test_distinct_invoices_stay_separate_and_sorted():
@@ -70,41 +71,41 @@ def test_distinct_invoices_stay_separate_and_sorted():
def test_same_invoice_multiple_materials_split_into_separate_invoices():
"""同一 Invoice(ASN)跨料号 → 按料号拆分为多张调拨发票,不再整单阻断。"""
rows = [
_row("ASN-001", material_no="MAT-001", row_no=1, quantity="100"),
_row("ASN-001", material_no="MAT-002", row_no=2, quantity="200"),
_row("ASN-001", material_code="MAT-001", row_no=1, quantity="100"),
_row("ASN-001", material_code="MAT-002", row_no=2, quantity="200"),
]
invoices = aggregate_invoices(_parsed(rows))
# [断言意图] Invoice 语义 = 调拨拨出单据号;料号维度自然拆分,保留各自数量与原始行。
assert [(i.material_no, i.receipt_quantity) for i in invoices] == [
assert [(i.material_no, i.movement_quantity) for i in invoices] == [
("MAT-001", Decimal("100")), ("MAT-002", Decimal("200")),
]
assert all(i.invoice_no == "ASN-001" for i in invoices)
def test_same_invoice_material_multiple_dates_split_by_date():
"""同 Invoice 同料号跨收料日期(部分交付)→ 按日期拆分,不再整单阻断。"""
"""同 Invoice 同料号跨异动日期(部分交付)→ 按日期拆分,不再整单阻断。"""
rows = [
_row("ASN-001", receipt_date="2026-08-05", row_no=1, quantity="100"),
_row("ASN-001", receipt_date="2026-08-06", row_no=2, quantity="50"),
_row("ASN-001", movement_date="2026-08-05", row_no=1, quantity="100"),
_row("ASN-001", movement_date="2026-08-06", row_no=2, quantity="50"),
]
invoices = aggregate_invoices(_parsed(rows))
assert [str(i.receipt_date) for i in invoices] == ["2026-08-05", "2026-08-06"]
assert [i.receipt_quantity for i in invoices] == [Decimal("100"), Decimal("50")]
assert [str(i.movement_date) for i in invoices] == ["2026-08-05", "2026-08-06"]
assert [i.movement_quantity for i in invoices] == [Decimal("100"), Decimal("50")]
def test_aggregated_invoice_keeps_material_identity():
"""汇总结果保留料号、品名、规格与收料日期。"""
"""汇总结果保留料号、品名、规格与异动日期。"""
rows = [
_row("INV-001", material_no="MAT-001", material_name="连接器组件",
specification="A 型 / 24PIN", receipt_date="2026-08-05", row_no=1),
_row("INV-001", material_no="MAT-001", row_no=2),
_row("INV-001", material_code="MAT-001", material_name="连接器组件",
specification="A 型 / 24PIN", movement_date="2026-08-05", row_no=1),
_row("INV-001", material_code="MAT-001", row_no=2),
]
invoices = aggregate_invoices(_parsed(rows))
invoice = invoices[0]
assert invoice.material_no == "MAT-001"
assert invoice.material_name == "连接器组件"
assert invoice.specification == "A 型 / 24PIN"
assert invoice.receipt_date == date(2026, 8, 5)
assert invoice.movement_date == date(2026, 8, 5)
def test_aggregated_invoice_keeps_first_row_warehouse_code():
@@ -0,0 +1,283 @@
"""库存异动档落地(ledger_sync)幂等语义回归。
用途:锁定 ledger_sync.sync_ledger_rows 的规格 §5 五条幂等语义——首落插入、
同文件重落全跳过(完全不动行)、证据变原行更新+换溯源、缺席不删、
封存行(transfer_executed=True)永不更新永不复活;以及交叉校验矛盾
(inbound 行出库语义 '-1')计 cross_flagged 并写 ledger_cross_check_failed
审计事件且记录照常落档;shipment 预留合法值放行、同批自然键重复首见为准。
依赖:app fixture(pytestmark)、models.TransferMovementLedger / TransferAuditEvent、
ledger_sync.sync_ledger_rows / FileMeta / movement_file_version。
逻辑:parsed_rows 以「movement 契约 field code → 值」的领域行 dict 直接构造
(扩展字段值从 dict 取,非 ParsedMovementRow 属性——Task 11 接线同形态);
直连 SQLite 内存库断言行级状态与审计事件,全程零外部调用。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import TransferAuditEvent, TransferMovementLedger
from app.services.in_transit_transfer.ledger_sync import (
FileMeta,
movement_file_version,
sync_ledger_rows,
)
pytestmark = [pytest.mark.usefixtures("app")]
SOURCE = "DBS-AWSBI"
NOW = datetime(2026, 10, 14, 10, 0, 0)
NOW2 = datetime(2026, 10, 14, 11, 0, 0)
SHA_V1 = "a" * 64
SHA_V2 = "b" * 64
def _row(**overrides) -> dict:
"""构造一条标准领域行 dict(键=movement 契约 field code + 可选溯源键)。
Args:
**overrides: 按需覆盖的字段(doc_no/quantity/in_out_flag 等)。
Returns:
领域行 dict(既有 11 + 扩展 7 字段,另含 sheet_name/row_no 溯源键)。
"""
row = {
"doc_no": "HOM-20261014-001", "line_no": "10", "in_out_flag": "1",
"material_code": "MAT-001", "material_name": "连接器",
"warehouse_code": "WTP", "storage_code": "A01", "lot_no": "WTP123",
"quantity": "12.5", "movement_date": "2026-10-14", "unit": "PCS",
"line_seq": "1", "specification": "C 型", "order_type": "ZRO1",
"odm_id": "ODM-1", "odm_name": "奥的斯", "carton_id": "CTN-1",
"pallet_id": "PLT-1", "sheet_name": "Sheet1", "row_no": 2,
}
row.update(overrides)
return row
def _meta(*, sha: str = SHA_V1, version: str = "v1", file_id: int = 101) -> FileMeta:
"""构造来源文件证据三元组(source_file_id 用任意整数:测试库无 FK 强制)。"""
return FileMeta(source_file_id=file_id, file_version=version, file_sha256=sha)
def _sync(parsed_rows, *, record_kind: str = "inbound", meta: FileMeta | None = None, now=NOW):
"""按默认来源发起一次落档(省略重复实参)。"""
return sync_ledger_rows(
source_code=SOURCE, record_kind=record_kind,
parsed_rows=parsed_rows, file_meta=meta or _meta(), now=now,
)
def test_first_landing_inserts_rows_with_provenance():
# [断言意图] 首落六分类归插入:业务镜像列(含扩展字段)与溯源五列随行写入。
outcome = _sync([_row(), _row(doc_no="HOM-20261014-002", line_no="20")])
assert (outcome.inserted, outcome.updated, outcome.skipped,
outcome.sealed_skipped, outcome.cross_flagged) == (2, 0, 0, 0, 0)
rows = TransferMovementLedger.query.order_by(TransferMovementLedger.doc_no).all()
assert len(rows) == 2
first = rows[0]
assert (first.source_code, first.record_kind) == (SOURCE, "inbound")
assert first.quantity == "12.5" and first.lot_no == "WTP123"
# 扩展字段取自领域行 dict(movement 契约 code ↔ 档列 1:1 镜像)。
assert first.specification == "C 型" and first.order_type == "ZRO1"
assert first.odm_name == "奥的斯" and first.carton_id == "CTN-1" and first.pallet_id == "PLT-1"
# 溯源:文件级三元组 + 行级 sheet/row_no + 显式 updated_at。
assert first.source_file_id == 101 and first.file_version == "v1"
assert first.file_sha256 == SHA_V1 and first.sheet_name == "Sheet1" and first.row_no == 2
assert first.updated_at == NOW
def test_same_file_relanding_all_skipped_without_touch():
# [断言意图] 同文件重落全 skipped 且完全不动行:updated_at 不续、零审计事件。
_sync([_row()])
outcome = _sync([_row()], now=NOW2)
assert (outcome.inserted, outcome.updated, outcome.skipped) == (0, 0, 1)
row = TransferMovementLedger.query.one()
assert row.updated_at == NOW # 跳过=不动行(档无 TTL,无新鲜度可续)
assert TransferAuditEvent.query.count() == 0 # 幂等重落不写任何审计事件
def test_evidence_change_updates_row_and_swaps_provenance():
# [断言意图] 证据变(quantity)原行更新:业务值换新 + 溯源五列整体换新,不产生第二行。
_sync([_row(quantity="12.5")])
outcome = _sync(
[_row(quantity="30", sheet_name="Sheet2", row_no=7)],
meta=_meta(sha=SHA_V2, version="v2", file_id=102), now=NOW2,
)
assert (outcome.updated, outcome.inserted, outcome.skipped) == (1, 0, 0)
assert TransferMovementLedger.query.count() == 1 # 原行更新,永不双行
row = TransferMovementLedger.query.one()
assert row.quantity == "30"
assert row.file_version == "v2" and row.file_sha256 == SHA_V2
assert row.source_file_id == 102 and row.sheet_name == "Sheet2" and row.row_no == 7
assert row.updated_at == NOW2
def test_absent_rows_kept_not_deleted():
# [断言意图] 文件缺席的档行原样留存:收料 RPA 非全量导出,缺席≠删除。
_sync([_row(), _row(doc_no="HOM-20261014-002", line_no="20")])
outcome = _sync([_row()], now=NOW2)
assert outcome.skipped == 1
assert TransferMovementLedger.query.count() == 2 # 缺席行不删
absent = TransferMovementLedger.query.filter_by(doc_no="HOM-20261014-002").one()
assert absent.quantity == "12.5" and absent.updated_at == NOW # 原样留存
def test_sealed_row_never_updated_nor_revived():
# [断言意图] 封存行证据再变:不更新业务值、不换溯源、不动时间戳、不产生第二行。
_sync([_row(quantity="12.5")])
sealed = TransferMovementLedger.query.one()
sealed.transfer_executed = True
sealed.executed_doc_no = "TDO-0001"
db.session.commit()
# 封存提交触发行 UPDATE(onupdate 续戳),以封存落库后的时间戳为「零写入」基准。
sealed_at = TransferMovementLedger.query.one().updated_at
outcome = _sync(
[_row(quantity="999", sheet_name="Sheet9", row_no=99)],
meta=_meta(sha=SHA_V2, version="v2", file_id=102), now=NOW2,
)
assert (outcome.sealed_skipped, outcome.inserted, outcome.updated) == (1, 0, 0)
loaded = TransferMovementLedger.query.one()
assert loaded.quantity == "12.5" # 证据再变不更新
assert loaded.file_sha256 == SHA_V1 and loaded.file_version == "v1"
assert loaded.source_file_id == 101 # 溯源不换新
assert loaded.transfer_executed is True and loaded.executed_doc_no == "TDO-0001"
assert loaded.updated_at == sealed_at # 封存同步零写入
assert TransferMovementLedger.query.count() == 1 # 永不复活(同键无第二行)
def test_inbound_outbound_flag_cross_flagged_but_landed():
# [断言意图] inbound 行出库语义 '-1':计 cross_flagged、写审计事件,记录照常落档;
# 幂等重落同一矛盾文件不重复打事件(只追加审计表防刷爆)。
outcome = _sync([_row(in_out_flag="-1"), _row(doc_no="HOM-20261014-002", line_no="20")])
assert (outcome.cross_flagged, outcome.inserted) == (1, 2)
event = TransferAuditEvent.query.one()
assert event.event_type == "ledger_cross_check_failed"
assert event.aggregate_type == "transfer_movement_ledger"
assert "HOM-20261014-001" in event.aggregate_id
assert event.result == "failure"
assert event.after_json["in_out_flag"] == "-1"
bad = TransferMovementLedger.query.filter_by(doc_no="HOM-20261014-001").one()
assert bad.in_out_flag == "-1" # 矛盾记录照常落档
outcome2 = _sync(
[_row(in_out_flag="-1"), _row(doc_no="HOM-20261014-002", line_no="20")], now=NOW2,
)
assert (outcome2.cross_flagged, outcome2.skipped) == (0, 2)
assert TransferAuditEvent.query.count() == 1 # 无新增事件
def test_shipment_kind_is_legal_and_not_cross_flagged():
# [断言意图] record_kind='outbound'(出货侧,预留)为合法值:校验放行、无 inbound 侧矛盾判定。
outcome = _sync([_row(in_out_flag="-1")], record_kind="outbound")
assert (outcome.inserted, outcome.cross_flagged) == (1, 0)
assert TransferMovementLedger.query.one().record_kind == "outbound"
def test_sealed_row_dominates_even_when_sha_unchanged():
# [断言意图] 封存是最高优先事实:同 sha 重落命中封存行也计 sealed_skipped(非 skipped)。
_sync([_row()])
sealed = TransferMovementLedger.query.one()
sealed.transfer_executed = True
db.session.commit()
sealed_at = TransferMovementLedger.query.one().updated_at # 零写入基准(onupdate 后)
outcome = _sync([_row()], now=NOW2)
assert (outcome.sealed_skipped, outcome.skipped) == (1, 0)
assert TransferMovementLedger.query.one().updated_at == sealed_at # 依旧零写入
def test_duplicate_natural_key_in_batch_first_wins():
# [断言意图] 同批自然键重复:首见为准,后续幂等跳过(自然键唯一索引 DB 兜底防双行)。
outcome = _sync([_row(quantity="12.5"), _row(quantity="88")])
assert (outcome.inserted, outcome.skipped) == (1, 1)
assert TransferMovementLedger.query.count() == 1
assert TransferMovementLedger.query.one().quantity == "12.5"
def test_carton_dimension_expands_natural_key():
# [断言意图] 同单号同行不同箱号=两行独立落档(旧四成分键会塌缩为首见为准丢行)。
outcome = _sync([
_row(doc_no="DUB1", line_no="10", carton_id="C1", quantity="5"),
_row(doc_no="DUB1", line_no="10", carton_id="C2", quantity="7"),
], record_kind="inbound")
assert (outcome.inserted, outcome.date_skipped) == (2, 0)
def test_lot_no_expands_natural_key():
# [断言意图] 同单号同行不同批号=两行独立落档(tt14 键扩维防同批号塌缩丢行)。
outcome = _sync([
_row(doc_no="WTP1", line_no="1", lot_no="HOW001", quantity="1"),
_row(doc_no="WTP1", line_no="1", lot_no="HOW002", quantity="2"),
], record_kind="inbound")
assert outcome.inserted == 2
def test_external_doc_line_expands_natural_key():
# [断言意图] 外部单据身份(外部单号/外部项次)入自然键:同单号同行但外部单号
# 不同 = 两行独立落档(2026-10-21 档幂等主键管控扩维,防外部身份塌缩丢行)。
outcome = _sync([
_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001", quantity="1"),
_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-002", quantity="2"),
], record_kind="inbound")
assert outcome.inserted == 2
assert outcome.skipped == 0
def test_external_doc_line_same_identity_converges_to_one_row():
# [断言意图] 主键管控收敛面:同外部单号+项次的重复落档收敛同一档行——
# 证据变化走原行更新(不是插入第二行),与 tt14 箱号/批号扩维同语义。
outcome = _sync([_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001",
external_line_no="5", quantity="1")])
assert outcome.inserted == 1
outcome2 = _sync([_row(doc_no="WTP1", line_no="1", external_doc_no="WMS-001",
external_line_no="5", quantity="3")], meta=_meta(sha=SHA_V2), now=NOW2)
assert (outcome2.inserted, outcome2.updated, outcome2.skipped) == (0, 1, 0)
row = TransferMovementLedger.query.one()
assert row.quantity == "3"
assert row.external_doc_no == "WMS-001" and row.external_line_no == "5"
def test_empty_movement_date_rows_skipped():
# [断言意图] movement_date 空 = 未发生异动:不落档、不计入其他分类(date_skipped 单列)。
outcome = _sync([
_row(doc_no="EXP1", line_no="1", movement_date="", quantity="3"),
_row(doc_no="OK1", line_no="1", movement_date="2026-10-15", quantity="1"),
], record_kind="inbound")
assert (outcome.inserted, outcome.date_skipped) == (1, 1)
def test_constants_inbound_outbound():
# [断言意图] record_kind 常量契约:说辞清扫(Task 3)以这些常量名为准,不再散落字面量。
from app.services.in_transit_transfer import ledger_sync
assert ledger_sync.RECORD_KIND_INBOUND == "inbound"
assert ledger_sync.RECORD_KIND_OUTBOUND == "outbound"
assert ledger_sync.INBOUND_CONTRADICTORY_FLAGS == frozenset({"-1"})
def test_batch_external_doc_no_row_untouched_by_landing():
# [断言意图] 评审 Important 回归(STEP 1 只圈批内 doc_no):同来源同种类的批外
# 档行不被水化、不被触碰(updated_at/内容不变),outcome 计数只反映批内。
db.session.add(TransferMovementLedger(
source_code=SOURCE, record_kind="inbound",
doc_no="HOM-20261013-999", line_no="1", line_seq="", in_out_flag="1",
quantity="7", file_sha256=SHA_V1, file_version="v0", source_file_id=201,
updated_at=NOW,
))
db.session.commit()
external_at = TransferMovementLedger.query.filter_by(
doc_no="HOM-20261013-999").one().updated_at
outcome = _sync([_row()]) # 批内仅 HOM-20261014-001,批外 doc_no 不参与
assert (outcome.inserted, outcome.skipped, outcome.sealed_skipped) == (1, 0, 0)
external = TransferMovementLedger.query.filter_by(doc_no="HOM-20261013-999").one()
assert external.quantity == "7" and external.file_sha256 == SHA_V1 # 内容不变
assert external.updated_at == external_at # 零触碰
assert TransferMovementLedger.query.count() == 2 # 缺席不删:批外行留存
def test_movement_file_version_fits_varchar64_column():
# [断言意图] 64 位摘要加 sha256: 前缀共 71 字符;档列 file_version 是 varchar(64),
# 戳必须是这一条已知截断值(2026-10-21 DSV 出站整批插入失败的摘要)。
digest = "7bbca0adaef3d550e0db47955a9b59609313be3b1335c1b498381db3b7a11715"
stamp = movement_file_version(digest)
assert stamp == "sha256:7bbca0adaef3d550e0db47955a9b59609313be3b1335c1b498381db3b"
assert len(stamp) == 64
@@ -1,220 +1,145 @@
"""行原地刷新与文件版本戳测试(L1,SQLite 内存库)。
"""匹配出生与行归属测试(出生翻转后语义,L1,SQLite 内存库)。
用途:验证重复匹配对既有 InvoiceItem 行为"原地刷新"(不迁移 matching_id、显式续
updated_at)、行携带证据同步落地的 file_sha256 版本戳,以及文件新版本缺席行
存续(只换戳不改状态)【2026-09-28 语义:缺席≠删除,归 evidence_sync】;
最近匹配计数按匹配 scope 实时聚合(不再按行归属)。
用途:锁定出生翻转(ADR 0001/D4/D17)后的行归属不变式——行由匹配创建时从档
圈定生成且「创建即绑定」matching_id;重复匹配因圈档互斥不累加行、不改写
他匹配归属;行携带档记录证据版本戳(file_sha256)供执行门禁②文件对账;
scope_item_query / invoice_in_scope 等旧 scope 圈行入口已退役(模块级
断言防回归)。
依赖:transfer_db、matching_service、evidence_sync(seed_rows_from_file 桥)、
transfer_type、repo_fakes。
逻辑:文件行先经 seed_rows_from_file(=evidence_sync.sync_source_rows)落成待查行,
再经 create_matching 落位;用"改 checksum/裁剪 rows"的新文件再次 seed 模拟
文件新版本;版本戳缺失用手工清空 raw_lines_json 的 file_sha256 模拟存量数据。
factories、repo_fakes。
逻辑:文件行先经 seed_rows_from_file(=evidence_sync.sync_source_rows)落成档行,
再经 create_matching 圈档建 items;旧「原地刷新/scope 实时视图」语义已由
「重查对档对账(test_requery_scope)」与「自有 items 视图(test_restore_scope)」
承接,本模块保留翻转后的归属/戳不变式与展示健壮性(§13.1)。
"""
from __future__ import annotations
import pytest
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import matching_service
from app.services.in_transit_transfer.matching_service import (
_item_evaluated_sha,
create_matching,
scope_item_query,
)
from app.services.in_transit_transfer.transfer_type import invoice_in_scope
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
def _file_without(dbs_ready_file: dict, doc_no: str, *, checksum: str) -> dict:
"""构造"新版本文件":剔除指定单号后剩余行,并更换 checksum。"""
return {
**dbs_ready_file,
"checksum": checksum,
"rows": [row for row in dbs_ready_file["rows"] if row["doc_no"] != doc_no],
}
pytestmark = pytest.mark.usefixtures("transfer_db")
def test_rematching_refreshes_rows_in_place(transfer_db, dbs_ready_file):
"""第二次匹配:同一物理行原地刷新(id 不变、matching_id 不变、值更新)。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 blocked
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 executable
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
row = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
old_id, old_matching_id, old_updated = row.id, row.matching_id, row.updated_at
def test_retired_scope_entries_are_gone():
"""scope_item_query / invoice_in_scope 已退役:模块级断言,残留引用即失败。
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
Why: 出生翻转后「这份匹配覆盖哪些行」= matching_id 归属(创建即绑定),
scope 实时圈行与类型前缀谓词的职责移交档圈定(scope_rules 引擎);
二次引入会造成双重口径(D17 占用互斥失效)。
"""
assert not hasattr(matching_service, "scope_item_query")
from app.services.in_transit_transfer import transfer_type
db.session.refresh(row)
# [断言意图] 行不换归属:重复匹配复用同一物理行,matching_id 保持首次创建值,
# 仅业务值与新鲜度(updated_at)被刷新——计数错乱与壳匹配的根源即"迁移行"。
assert row.id == old_id
assert row.matching_id == old_matching_id
assert row.updated_at > old_updated
# 两份匹配记录都存在(评估留痕)。
assert first.matching_id != second.matching_id
assert not hasattr(transfer_type, "invoice_in_scope")
def test_rows_carry_file_sha256_stamp(transfer_db, dbs_ready_file):
"""行 raw_lines_json 携带本次评估所用文件的 file_sha256(新建行写入)。"""
def test_items_are_born_bound_to_matching(transfer_db, dbs_ready_file):
"""创建即绑定:圈档出生行 matching_id/run_id/ledger_record_id 齐备,业务字段=档原值。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
# [断言意图] 版本戳由证据同步落地时写入(与文件 checksum 同源):文件对账读取
# item.raw_lines_json[0].file_sha256,缺失即无法判定行新鲜度。
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
from app.models import TransferMatching
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
rows = TransferInvoiceItem.query.all()
# [断言意图] 出生即绑定:matching_id/run_id 指向本次、ledger_record_id 指向档。
assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"}
for row in rows:
assert row.matching_id == matching.id
# [断言意图] run_id 保持 None:执行 Run 关联归 orchestrator(圈未关联行)。
assert row.run_id is None
assert row.ledger_record_id is not None
hom = next(row for row in rows if row.invoice_no == "HOM-001")
# [断言意图] 业务字段=档原值:数量=档聚合值(500+700),批号/仓库/日期同档。
assert hom.movement_quantity == "1200"
assert hom.lot_no == "LOT-10" and hom.movement_date == "2026-08-04"
assert hom.movement_warehouse_code == "" # 夹具行无仓库列 → 档原值为空串
def test_rematching_never_accumulates_or_steals_rows(transfer_db, dbs_ready_file):
"""重复匹配:圈档互斥(D17)——第二匹配圈不到已占用记录,不累加行、不迁移归属。"""
from app.models import TransferMatching
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
old_rows = {row.id: (row.matching_id, row.status) for row in TransferInvoiceItem.query.all()}
assert len(old_rows) == 2
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
# [断言意图] 总行数不变(无 2×N 累加)、归属保持首建匹配;第二匹配为空壳
# (其自有行集为空)——记录已被有效 items 占用,圈档互斥排除。
assert TransferInvoiceItem.query.count() == 2
for row in TransferInvoiceItem.query.all():
assert (row.matching_id, row.status) == old_rows[row.id]
assert row.matching_id == first_matching.id
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
assert TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).count() == 0
assert TransferMatching.query.count() == 2 # 匹配记录照常逐次留痕
def test_rows_carry_ledger_file_sha_stamp(transfer_db, dbs_ready_file):
"""出生行 raw_lines_json 携带档记录证据版本戳(执行门禁②文件对账依据)。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
# [断言意图] 版本戳随出生行来自档记录(与文件 checksum 同源):文件对账读取
# item.raw_lines_json[0].file_sha256,缺失即无法判定行新鲜度(fail-closed)。
for invoice_no in ("HOM-001", "HOX-002"):
row = db.session.query(TransferInvoiceItem).filter_by(invoice_no=invoice_no).first()
assert row.raw_lines_json, f"{invoice_no} 应有 raw_lines"
assert row.raw_lines_json[0]["file_sha256"] == dbs_ready_file["checksum"]
assert row.raw_lines_json[0]["sheet"] == "Receipt"
assert _item_evaluated_sha(row) == dbs_ready_file["checksum"]
def test_scope_item_query_follows_matching_scope(transfer_db, dbs_ready_file):
"""scope_item_query 按 scope_json(来源+日期区间+类型前缀)圈行,不依赖行归属。"""
from app.models import TransferMatching
def test_display_robust_without_type_config(transfer_db, dbs_ready_file):
"""展示健壮性(规格 §13.1):配置表无该类型 code 时 restore/序列化仍成功。
Why: Run/Matching 展示与审计不得依赖配置表存在性(类型值可能来自已停用/
已改名的配置,展示层读 scope_json 快照不查配置表)。
"""
from app.models import TransferMatching, TransferTypeConfig
from app.services.in_transit_transfer.matching_service import restore_matching
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
receipt_date_from="2026-08-05", receipt_date_to="2026-08-05",
)
matching = db.session.query(TransferMatching).filter_by(matching_no=summary.matching_id).first()
rows = scope_item_query(matching).all()
# [断言意图] 行的 matching_id 即使不指向本匹配,scope 命中的行也必须被圈入
# (Task 2 restore 与最近匹配计数共用该口径)。
assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"}
def test_scope_query_sees_same_rows_for_overlapping_matchings(transfer_db, dbs_ready_file):
"""重匹配不迁移行:两份匹配按各自 scope 实时圈行,命中同一批行(实时视图语义)。"""
from app.models import TransferMatching
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # blocked
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
first = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
# [断言意图] 行不迁移后两份匹配的 scope 都命中同一批活跃行(总数 2、
# 可执行 1、阻断 1)——匹配卡=范围实时视图,不再出现"旧匹配被掏空"。
for matching_no in (first.matching_id, second.matching_id):
matching = db.session.query(TransferMatching).filter_by(matching_no=matching_no).one()
rows = scope_item_query(matching).all()
assert {row.invoice_no for row in rows} == {"HOM-001", "HOX-002"}
assert sum(1 for r in rows if r.status == "ready_to_execute") == 1
assert sum(1 for r in rows if r.status == "blocked_recoverable") == 1
def test_file_absent_keeps_ready_rows_and_restamps(transfer_db, dbs_ready_file):
"""文件新版本缺席该行:evidence_sync 存续(状态原样、只换戳);仍在文件中的行
保持可执行并换新版本戳。(2026-09-28:缺席≠删除)"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # HOM-001 → executable
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
assert hom.status == "ready_to_execute"
# 新文件版本:内容只剩 HOX-002(HOM-001 缺席),checksum 变化——证据同步只换戳。
new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64)
deps2, erp2, _ = make_transfer_deps(new_file)
# 存续行仍会进入匹配圈(缺席≠出清):两边库存都要备齐,避免二次匹配误伤缺席行。
erp2.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp2.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06")
db.session.refresh(hom)
db.session.refresh(hox)
# [断言意图] 同步后:缺席行状态原样保留(ready),只换最新文件戳;不产生 blocked_file_removed。
assert hom.status == "ready_to_execute"
assert hom.result_code != "blocked_file_removed"
assert _item_evaluated_sha(hom) == "e" * 64
assert _item_evaluated_sha(hox) == "e" * 64
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps2)
db.session.refresh(hom)
db.session.refresh(hox)
# [断言意图] 二次匹配后:缺席存续行与在文件行均可执行(两边库存齐备)。
assert hom.status == "ready_to_execute"
assert hox.status == "ready_to_execute"
def test_file_absent_restamps_even_without_prior_stamp(transfer_db, dbs_ready_file):
"""[语义变更 2026-09-28] 缺席存续按四元组身份判定:行上无 file_sha256(存量数据)
同样只换戳不改状态;仍在文件中的无戳行随最新文件回填戳。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
assert hom.status == "ready_to_execute"
# 模拟存量行:清空 raw_lines_json 的 file_sha256 版本戳。
for row in (hom, hox):
row.raw_lines_json = [
{key: value for key, value in line.items() if key != "file_sha256"}
for line in (row.raw_lines_json or [])
]
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
# 模拟类型配置随后被清理(平台侧只停用不删除;此处取更强前提)。
db.session.query(TransferTypeConfig).delete()
db.session.commit()
new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64)
deps2, erp2, _ = make_transfer_deps(new_file)
erp2.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06")
db.session.refresh(hom)
db.session.refresh(hox)
# [断言意图] 身份判定不依赖版本戳:缺席行存续(状态保留),回填最新戳;
# 在文件行无证据变化 → 只换戳不重置待查。
assert hom.status == "ready_to_execute"
assert hom.result_code != "blocked_file_removed"
assert _item_evaluated_sha(hom) == "e" * 64
assert hox.status == "ready_to_execute"
assert _item_evaluated_sha(hox) == "e" * 64
def test_file_absent_keeps_blocked_mismatch_explanation(transfer_db, dbs_ready_file):
"""[语义变更 2026-09-28] 非终态 blocked 行从最新文件缺席 → 存续:保留既有
数量不一致解释(缺席≠删除,不改标 blocked_file_removed)。"""
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # HOM-001 → 数量不一致 blocked
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # HOX-002 → executable
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
hom = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
assert hom.status == "blocked_recoverable"
assert hom.result_code == "blocked_quantity_mismatch"
new_file = _file_without(dbs_ready_file, "HOM-001", checksum="e" * 64)
deps2, erp2, _ = make_transfer_deps(new_file)
erp2.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps2, "2026-08-06")
db.session.refresh(hom)
# [断言意图] 缺席不改写既有阻断解释;版本戳换到最新文件。
assert hom.status == "blocked_recoverable"
assert hom.result_code == "blocked_quantity_mismatch"
assert _item_evaluated_sha(hom) == "e" * 64
def test_invoice_in_scope_predicate():
"""invoice_in_scope:类型 1 按 HOM/HOX/WTP 前缀(大小写不敏感),占位类型恒 False。"""
assert invoice_in_scope("HOM-001", "in_transit_to_hub") is True
assert invoice_in_scope("hox-002", "in_transit_to_hub") is True
assert invoice_in_scope("WTP-008", None) is True # 缺省回落类型 1
assert invoice_in_scope("INV-9", "in_transit_to_hub") is False
assert invoice_in_scope("", "in_transit_to_hub") is False
# [断言意图] 占位类型(规则未启用)必须返回 False:scope 查询不得圈入任何行。
assert invoice_in_scope("HOM-001", "hub_repair_out") is False
restored = restore_matching(summary.matching_id)
# [断言意图] 展示链路零配置依赖:摘要/明细照常投影(scope_json 快照自足)。
assert restored["summary"].matching_hash == summary.matching_hash
assert {item.invoice_no for item in restored["items"]} == {"HOM-001", "HOX-002"}
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
assert matching.scope_json["transfer_type"] == "in_transit_to_hub"
File diff suppressed because it is too large. Load diff
@@ -24,7 +24,7 @@ def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file, patc
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
item_ids = [
item.id for item in db.session.query(TransferInvoiceItem)
.filter_by(status="ready_to_execute").all()
@@ -42,7 +42,7 @@ def test_collect_metrics_backlog_and_notification_failure(transfer_db, dbs_ready
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
item.updated_at = item.updated_at # 保持默认年龄
db.session.commit()
@@ -0,0 +1,177 @@
"""tt14a5f6a7b8c9 入站化迁移契约测试。
用途:锁定 tt14 迁移与模型两侧契约——transfer_invoice_items/transfer_documents
receipt_* 列更名 movement_*(明细/单据方向中立,与异动档 movement_date
对齐);transfer_movement_ledger.record_kind 值迁移 receipt→inbound /
shipment→outbound;自然键唯一约束重建为 8 成分(追加 carton_id/lot_no)。
依赖:migrations/versions(it1a2b3c4d5e 建表 → it2c3d4e5f6a7 → tt0d1e2f3a4b →
tt11b2c3d4e5f → tt14)、app_ctx(根 conftest app fixture 上下文别名)。
逻辑:revision 链断言 + 模型属性/约束成分断言 + SQLite 真实 upgrade/downgrade/
upgrade 往返(test_migration_widen_transfer_run_type 同款模式)。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import pytest
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
pytestmark = pytest.mark.pure_unit
MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions"
@pytest.fixture
def app_ctx(app):
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
return app
def _load(revision_prefix: str):
for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix}*.py")):
spec = importlib.util.spec_from_file_location(path.stem, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
raise AssertionError(f"migration {revision_prefix} not found")
def test_revision_chains_from_mh15_head():
migration = _load("tt14a5f6a7b8c9")
assert migration.down_revision == "mh15f6a7b8c9"
def test_model_inbound_columns_and_ledger_key(app_ctx):
from app.models.in_transit_transfer import (
TransferDocument, TransferInvoiceItem, TransferMovementLedger,
)
item_cols = {c.name for c in TransferInvoiceItem.__table__.columns}
assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= item_cols
assert not {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} & item_cols
doc_cols = {c.name for c in TransferDocument.__table__.columns}
assert "movement_date" in doc_cols and "receipt_date" not in doc_cols
ledger_uq = next(
c for c in TransferMovementLedger.__table__.constraints
if getattr(c, "name", "") == "uq_transfer_movement_ledger_natural_key"
)
assert [col.name for col in ledger_uq.columns] == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq",
"in_out_flag", "carton_id", "lot_no", "external_doc_no", "external_line_no",
]
# R7 终审 + 2026-10-21 外部身份扩维:进键维度列必须 NOT NULL + default ''
#(nullable 成分的 NULL 不参与 PG/SQLite 唯一比对,会逃逸唯一约束)。
ledger_cols = {c.name: c for c in TransferMovementLedger.__table__.columns}
for name in ("carton_id", "lot_no", "external_doc_no", "external_line_no"):
assert ledger_cols[name].nullable is False, f"{name} 进键即 NOT NULL"
assert ledger_cols[name].default.arg == ''
assert ledger_cols[name].server_default.arg == ''
def _ledger_natural_key(connection) -> list[str]:
"""从 SQLite 反射 transfer_movement_ledger 自然键唯一约束的列序。"""
constraints = sa.inspect(connection).get_unique_constraints("transfer_movement_ledger")
for constraint in constraints:
if constraint.get("name") == "uq_transfer_movement_ledger_natural_key":
return list(constraint["column_names"])
raise AssertionError("uq_transfer_movement_ledger_natural_key not found in SQLite schema")
def _item_column_names(connection) -> set[str]:
return {c["name"] for c in sa.inspect(connection).get_columns("transfer_invoice_items")}
def _doc_column_names(connection) -> set[str]:
return {c["name"] for c in sa.inspect(connection).get_columns("transfer_documents")}
def _ledger_dimension_column(connection, name: str) -> dict:
"""从 SQLite 反射 transfer_movement_ledger 维度列(DDL 往返断言用)。"""
columns = {c["name"]: c for c in sa.inspect(connection).get_columns("transfer_movement_ledger")}
assert name in columns
return columns[name]
def test_sqlite_roundtrip_upgrade_downgrade_upgrade():
"""SQLite 真实往返:upgrade 更名+扩键 / downgrade 精确还原 / 再 upgrade。
[断言意图] 前置链(it1a2b3c4d5e 建表 + it2c3d4e5f6a7 加仓库列 + tt0d1e2f3a4b
建单表 + tt11b2c3d4e5f 建档表)就位后,tt14 的 batch RENAME 不丢列、自然键
唯一约束随往返在 6/8 成分间精确翻转,证明 DDL 可回滚且与模型同构。
"""
engine = sa.create_engine("sqlite:///:memory:")
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
# batch copy-and-move 反射时按 FK autoload 目标表:内存库无 Flask 全量
# 元数据,先建最小 users / shipping_receipt_report_files 桩表满足反射。
sa.Table(
"users", sa.MetaData(),
sa.Column("id", sa.Integer(), primary_key=True),
).create(connection)
sa.Table(
"shipping_receipt_report_files", sa.MetaData(),
sa.Column("id", sa.Integer(), primary_key=True),
).create(connection)
# it2c3d4e5f6a7 同时给库存来源映射表加列(与调拨列无关):建最小桩表承接。
sa.Table(
"shipping_inventory_external_mappings", sa.MetaData(),
sa.Column("id", sa.Integer(), primary_key=True),
).create(connection)
for revision in ("it1a2b3c4d5e", "it2c3d4e5f6a7", "tt0d1e2f3a4b", "tt11b2c3d4e5f"):
base = _load(revision)
base.op = operations
base.upgrade()
# 前置基线:items/documents 仍是 receipt_* 列,档自然键为 6 成分。
assert {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} <= _item_column_names(connection)
assert "receipt_date" in _doc_column_names(connection)
assert _ledger_natural_key(connection) == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
]
migration = _load("tt14a5f6a7b8c9")
migration.op = operations
migration.upgrade()
item_cols = _item_column_names(connection)
assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= item_cols
assert not {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} & item_cols
assert "movement_date" in _doc_column_names(connection)
assert "receipt_date" not in _doc_column_names(connection)
# [断言意图] 自然键扩 8 成分(真实 WMS 行身份=单据+行+箱/批)。
assert _ledger_natural_key(connection) == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq",
"in_out_flag", "carton_id", "lot_no",
]
# [断言意图] 维度列 NOT NULL + default ''(R7:防 NULL 逃逸唯一比对)。
for name in ("carton_id", "lot_no"):
column = _ledger_dimension_column(connection, name)
assert column["nullable"] is False
assert "''" in str(column.get("default") or "")
migration.downgrade()
assert {"receipt_date", "receipt_quantity", "receipt_warehouse_code"} <= _item_column_names(connection)
assert "movement_date" not in _item_column_names(connection)
assert "receipt_date" in _doc_column_names(connection)
assert _ledger_natural_key(connection) == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
]
# [断言意图] downgrade 对称还原:维度列回 nullable=True 且默认值移除。
for name in ("carton_id", "lot_no"):
column = _ledger_dimension_column(connection, name)
assert column["nullable"] is True
assert "''" not in str(column.get("default") or "")
migration.upgrade()
assert {"movement_date", "movement_quantity", "movement_warehouse_code"} <= _item_column_names(connection)
assert _ledger_natural_key(connection) == [
"source_code", "record_kind", "doc_no", "line_no", "line_seq",
"in_out_flag", "carton_id", "lot_no",
]
@@ -0,0 +1,127 @@
"""transfer_runs.transfer_type 列宽迁移契约测试(终审 I2 修复)。
用途:锁定 tt13d4e5f6a7b8 迁移与模型两侧契约——transfer_runs.transfer_type 列宽
64(与 transfer_type_configs.code 的 ≤64 上限对齐,消除「33~64 字符 code 建
匹配时 transfer_runs 写入超长 → DB 500」的长度错位);迁移链挂 tt12 之后;
SQLite 真实 upgrade/downgrade/upgrade 往返可执行。
依赖:migrations/versions 迁移脚本(it1a2b3c4d5e 建表 / tt3d4e5f6a7b 加列 /
tt13d4e5f6a7b8 放宽)、app_ctx(根 conftest app fixture 上下文别名)、
models/in_transit_transfer.TransferRun。
逻辑:纯元数据断言(模型列宽/server_default/nullable)+ 迁移脚本字面量断言
(revision 链)+ SQLite 内存库执行断言(upgrade→64 / downgrade→32 /
再 upgrade→64,server_default 全程保持 'in_transit_to_hub')。
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
import pytest
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
from app.models.in_transit_transfer import TransferRun
pytestmark = pytest.mark.pure_unit
REVISION = "tt13d4e5f6a7b8"
DOWN_REVISION = "tt12c3d4e5f6a7"
MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions"
def _migration_path(revision: str) -> Path:
"""按 revision 定位迁移文件(命名规则 <revision>_<slug>.py)。"""
for path in MIGRATIONS_DIR.glob("*.py"):
if path.name.startswith(f"{revision}_"):
return path
raise AssertionError(f"migration file for revision {revision} not found")
def _load_migration(revision: str):
"""按 revision 加载迁移模块(test_migration_execution 同款,不加载 Flask 应用)。"""
path = _migration_path(revision)
spec = importlib.util.spec_from_file_location(f"migration_{revision}", path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.fixture
def app_ctx(app):
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
return app
def test_revision_chains_from_tt12_head():
"""迁移必须存在且挂在 tt12c3d4e5f6a7(实施时实际单 head)之后。"""
text = _migration_path(REVISION).read_text(encoding="utf-8")
assert f"revision = '{REVISION}'" in text
assert f"down_revision = '{DOWN_REVISION}'" in text
def test_model_transfer_type_column_widened_to_64(app_ctx):
"""模型列宽必须为 64:与 transfer_type_configs.code ≤64 上限对齐(I2 错位根因)。"""
column = TransferRun.__table__.columns["transfer_type"]
assert column.type.length == 64
assert column.nullable is False
# server_default 保持建列初值:类型配置为空时匹配 fail-closed,Run 默认仍归
# 「在途仓至HUB仓」(上线 SOP 依赖该默认值,规格 §7)。
assert column.server_default.arg == "in_transit_to_hub"
def _transfer_type_column(connection) -> dict:
"""从 SQLite 反射 transfer_runs.transfer_type 列信息(DDL 往返断言用)。"""
columns = {c["name"]: c for c in sa.inspect(connection).get_columns("transfer_runs")}
assert "transfer_type" in columns
return columns["transfer_type"]
def test_upgrade_widen_downgrade_restore_roundtrip(app):
"""SQLite 真实往返:upgrade 放宽 64 / downgrade 收回 32 / 再 upgrade 回 64。
[断言意图] 前置链(it1a2b3c4d5e 建表 + tt3d4e5f6a7b 加列 String(32))就位后,
tt13 的 copy-and-move 批改不丢列、不丢 server_default;列宽随迁移往返精确
翻转,证明 DDL 与模型同构且可回滚。
"""
engine = sa.create_engine("sqlite:///:memory:")
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
# SQLite batch copy-and-move 反射 transfer_runs 时会 autoload 其 FK 目标表
# (users.id):内存库无 Flask 全量元数据,先建最小 users 表满足反射。
sa.Table(
"users", sa.MetaData(),
sa.Column("id", sa.Integer(), primary_key=True),
).create(connection)
base = _load_migration("it1a2b3c4d5e") # 建调拨 7 表(无 transfer_type 列)
base.op = operations
base.upgrade()
# 前置加列 String(32):按 tt3d4e5f6a7b 的列字面量手工复刻——该迁移的
# create_check_constraint 是 PG-only DDL(SQLite 不支持 ALTER 约束,真实
# 链路该 CHECK 也已随 tt10 移除),与列宽无关,不在本往返范围。
with operations.batch_alter_table("transfer_runs") as batch_op:
batch_op.add_column(sa.Column(
"transfer_type", sa.String(length=32),
nullable=False, server_default="in_transit_to_hub",
))
assert _transfer_type_column(connection)["type"].length == 32 # 前置:初始 32
migration = _load_migration(REVISION)
migration.op = operations
migration.upgrade()
column = _transfer_type_column(connection)
assert column["type"].length == 64 # [断言意图] 放宽至 64
assert "in_transit_to_hub" in str(column.get("default") or "") # 默认值不丢
migration.downgrade()
assert _transfer_type_column(connection)["type"].length == 32 # [断言意图] 收回 32
migration.upgrade()
assert _transfer_type_column(connection)["type"].length == 64 # [断言意图] 再放宽 64
@@ -73,10 +73,10 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
material_no="MAT-001",
material_name="连接器组件",
specification="A 型 / 24PIN",
receipt_date="2026-08-05",
movement_date="2026-08-05",
from_warehouse="DBS-TRANSIT",
to_warehouse="HUB-CN01",
receipt_quantity="1200",
movement_quantity="1200",
external_quantity="1200",
status="ready_to_execute",
raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}],
@@ -123,10 +123,10 @@ def test_invoice_item_unique_per_matching(transfer_db):
source_code="DBS-AWSBI",
invoice_no=invoice_no,
material_no="MAT-001",
receipt_date="2026-08-05",
movement_date="2026-08-05",
from_warehouse="DBS-TRANSIT",
to_warehouse="HUB-CN01",
receipt_quantity="1200",
movement_quantity="1200",
external_quantity="1200",
status="ready_to_execute",
raw_lines_json=[],
@@ -162,9 +162,9 @@ def test_invoice_item_status_check_constraint(transfer_db):
transfer_db.session.flush()
transfer_db.session.add(TransferInvoiceItem(
matching_id=matching.id, source_code="DBS-AWSBI", invoice_no="INV-999",
material_no="MAT-9", receipt_date="2026-08-05",
material_no="MAT-9", movement_date="2026-08-05",
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
receipt_quantity="1", external_quantity="1",
movement_quantity="1", external_quantity="1",
status="no_such_status", raw_lines_json=[],
))
with pytest.raises(IntegrityError):
@@ -1,10 +1,12 @@
"""在途调拨通用异动表领域字段契约测试(L0 纯单元)。
用途:锁定调拨定死的 11 个通用异动/移动字段契约(领域定死、不配置化,
D4 追加第 11 字段 unit),以及通用异动解析器 parse_movement_rows
把字段映射到调拨 ParsedReceiptRow。
用途:锁定调拨定死的通用异动/移动字段契约(领域定死、不配置化;D4 追加第 11 字段
unit;2026-10-14 调拨类型配置化+库存异动档项目追加 7 个可选维度字段——
line_seq/specification/order_type/odm_id/odm_name/carton_id/pallet_id),
以及通用异动解析器 parse_movement_rows 把字段映射到调拨 ParsedMovementRow。
依赖:app.services.in_transit_transfer.movement_contract + file_parser(纯函数)。
逻辑:字段契约是 immutable 常量;解析只认契约字段,供未来出货/入库 Excel 复用。
逻辑:字段契约是 immutable 常量;解析只认契约字段,供未来出货/入库 Excel 复用;
追加字段全部可选非身份,缺列容忍语义由既有 row.get 投影自动继承。
"""
from __future__ import annotations
@@ -14,11 +16,11 @@ from decimal import Decimal
import pytest
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow
from app.services.in_transit_transfer.file_parser import ParsedMovementRow, parse_movement_rows
from app.services.in_transit_transfer.movement_contract import (
MOVEMENT_FIELDS,
MovementField,
external_lot_no,
movement_field_codes,
movement_match_key,
movement_quantity_field,
movement_identity_fields,
@@ -26,14 +28,27 @@ from app.services.in_transit_transfer.movement_contract import (
pytestmark = pytest.mark.pure_unit
# 2026-10-14 扩展追加的可选维度字段(全部 required=False, is_identity=False,
# 按追加顺序排在既有 11 字段之后;Task 10 库存异动档按这些 code 取值)。
EXTENSION_FIELD_CODES = (
"line_seq", "specification", "order_type", "odm_id", "odm_name", "carton_id", "pallet_id",
)
# 2026-10-21 扩展追加的外部单据身份字段(外部单号/外部项次=WMS Order #/行号):
# required=False, is_identity=False(不进匹配身份);但作为异动档自然键成分承担
# 档幂等主键管控(模型 uq_transfer_movement_ledger_natural_key 10 成分)。
EXTERNAL_IDENTITY_FIELD_CODES = ("external_doc_no", "external_line_no")
def test_movement_fields_contract_is_frozen_and_complete():
"""领域字段契约定死:11 个字段(D4 追加第 11 字段 unit)、名称唯一、不可变。"""
assert len(MOVEMENT_FIELDS) == 11
"""领域字段契约定死:既有 11 字段 + 2026-10-14 扩展 7 可选字段 + 2026-10-21
外部单据身份 2 字段、名称唯一、不可变。"""
assert len(MOVEMENT_FIELDS) == 20
codes = {field.code for field in MOVEMENT_FIELDS}
assert codes == {
"doc_no", "line_no", "in_out_flag", "material_code", "material_name",
"warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", "unit",
*EXTENSION_FIELD_CODES,
*EXTERNAL_IDENTITY_FIELD_CODES,
}
@@ -48,6 +63,69 @@ def test_movement_field_metadata():
assert by_code["movement_date"].value_type == "date"
def test_movement_field_extension_codes_appended_optional_non_identity():
"""2026-10-14 扩展 7 字段:追加在既有 11 字段之后、全部可选非身份的文本字段。
Why: 库存异动档(Task 10)需按行留存项序/规格/订单类型/ODM/箱号/栈板号维度;
追加式演进不得扰动既有 11 字段语义与顺序(unit 仍须在第 11 位)。
"""
# [断言意图] 追加字段按 EXTENSION_FIELD_CODES 顺序紧随 unit——文件列顺序契约,
# 前端目录展示与既有测试(unit=第 11 字段)都依赖「只追加、不重排」。
assert [field.code for field in MOVEMENT_FIELDS] == [
"doc_no", "line_no", "in_out_flag", "material_code", "material_name",
"warehouse_code", "storage_code", "lot_no", "quantity", "movement_date", "unit",
*EXTENSION_FIELD_CODES,
*EXTERNAL_IDENTITY_FIELD_CODES,
]
by_code = {field.code: field for field in MOVEMENT_FIELDS}
expected_labels = {
"line_seq": "项序", "specification": "规格", "order_type": "订单类型",
"odm_id": "ODM编号", "odm_name": "ODM名称", "carton_id": "箱号", "pallet_id": "栈板号",
}
for code in EXTENSION_FIELD_CODES:
field = by_code[code]
assert field.label == expected_labels[code], code
assert field.value_type == "text", code
# 扩展字段是展示/圈档维度:源文件缺列放行(解析容忍),不参与幂等/匹配键。
assert field.required is False, code
assert field.is_identity is False, code
def test_external_identity_fields_appended_optional_non_matching_identity():
"""2026-10-21 外部单据身份 2 字段(外部单号/外部项次):追加尾部、可选、非匹配身份。
Why: CRANE/Lognet 出站报告携带 WMS 自己的单据+行身份,需要与调拨单号
(doc_no)分开留存并作为异动档自然键成分(档幂等主键管控);匹配 grain
仍=单号/料号/异动日期,不受外部身份扩维扰动(契约由
test_identity_and_match_key_unchanged_by_extension 锁定)。
"""
by_code = {field.code: field for field in MOVEMENT_FIELDS}
expected_labels = {"external_doc_no": "外部单号", "external_line_no": "外部项次"}
# [断言意图] 只追加不重排:外部身份字段排在既有全部字段之后(文件列顺序契约)。
assert [field.code for field in MOVEMENT_FIELDS][-2:] == list(EXTERNAL_IDENTITY_FIELD_CODES)
for code in EXTERNAL_IDENTITY_FIELD_CODES:
field = by_code[code]
assert field.label == expected_labels[code], code
assert field.value_type == "text", code
# 解析放行空值(存量入站 Profile 未映射时不阻断);不进匹配身份集合。
assert field.required is False, code
assert field.is_identity is False, code
def test_movement_field_codes_include_extension_codes():
"""movement_field_codes() 自动包含全部扩展字段码(管理端字段目录/映射白名单数据源)。"""
codes = movement_field_codes()
assert set(EXTENSION_FIELD_CODES) <= codes
assert codes == {field.code for field in MOVEMENT_FIELDS}
def test_identity_and_match_key_unchanged_by_extension():
"""扩展不得渗入匹配身份:幂等键 doc_no、身份集恰为 3 字段、数量字段 quantity。"""
assert movement_match_key() == "doc_no"
assert movement_identity_fields() == {"doc_no", "material_code", "movement_date"}
assert movement_quantity_field() == "quantity"
def test_match_key_is_doc_no():
"""调拨幂等/汇总键为 doc_no(单号)。"""
assert movement_match_key() == "doc_no"
@@ -64,24 +142,18 @@ def test_identity_fields_cover_match_predicates():
assert {"doc_no", "material_code", "movement_date"} <= ids
def test_external_lot_no_derives_how_from_wtp_prefix():
"""批号外部形态派生:WTP 前缀 → HOW,前缀识别大小写不敏感、余串逐字保留。
def test_external_lot_no_retired_replaced_by_transform_rules():
"""external_lot_no 硬编码已退役(Task 11):批号外部形态改由类型配置转换规则驱动。
Why: ERP 账面批号为 HOW 形态,WMS 文件批号为 WTP 形态——不经派生直查必查空
(2026-09-25 生产实证 13 行假阴性)。前端 transferBatch.ts deriveBatchNo
为展示侧镜像,两侧行为必须逐字节一致。
Why: 原硬编码 WTP→HOW 迁移为 field_transforms 引擎 + 匹配快照规则(规格 §8);
行为回归由 tests/services/in_transit_transfer/test_field_transforms.py 与
test_matching_service.py 的转换规则接线用例承接,本模块不再持有该函数。
"""
assert external_lot_no("WTP26060612") == "HOW26060612"
assert external_lot_no("wtp26060612") == "HOW26060612"
assert external_lot_no("Wtp26-1") == "HOW26-1"
assert external_lot_no(" WTP26060612 ") == "HOW26060612"
import inspect
from app.services.in_transit_transfer import movement_contract
# [断言意图] 函数必须已删除:任何残留调用点会在 import 期/本断言暴露。
assert not hasattr(movement_contract, "external_lot_no")
def test_external_lot_no_identity_for_non_wtp_and_empty():
"""非 WTP 前缀恒等(HOX/HOW/普通批号不受影响);空值/None 归空串。"""
assert external_lot_no("HOX26051805") == "HOX26051805"
assert external_lot_no("HOW26060612") == "HOW26060612"
assert external_lot_no("LOT-10") == "LOT-10"
assert external_lot_no("") == ""
assert external_lot_no(" ") == ""
assert external_lot_no(None) == ""
@@ -180,4 +180,4 @@ def test_extract_movement_rows_normalizes_ssrs_wrapped_headers():
assert rows[0]['row_no'] == 3
parsed = parse_movement_rows(source_code='DSV360_AWSBI_BYAWSPHX01', rows=rows)
assert parsed[0].invoice_no == 'ASN-PHX-1'
assert parsed[0].receipt_quantity == 24
assert parsed[0].movement_quantity == 24
@@ -1,9 +1,9 @@
"""通用异动表解析器测试(L0 纯单元)。
用途:验证 parse_movement_rows 把通用异动字段(doc_no/line_no/...)映射到
调拨 ParsedReceiptRow(invoice_no=doc_no, receipt_quantity=quantity,
receipt_date=movement_date),并保留既有校验(必填/非法值/来源一致)。
依赖:app.services.in_transit_transfer.movement_parser(纯函数)。
调拨 ParsedMovementRow(invoice_no=doc_no, movement_quantity=quantity,
movement_date=movement_date),并保留既有校验(必填/非法值/来源一致)。
依赖:app.services.in_transit_transfer.file_parser.parse_movement_rows(纯函数)。
逻辑:字段映射后进入既有 file_parser 校验链路,保证下游 invoice_aggregator 不变。
"""
@@ -15,8 +15,8 @@ from decimal import Decimal
import pytest
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
ParsedMovementRow,
MovementFileSchemaError,
parse_movement_rows,
)
@@ -46,41 +46,41 @@ def _rows(**overrides) -> list[dict]:
def test_valid_movement_row_maps_to_parsed_rows():
"""通用字段映射为调拨行:doc_no→invoice_no、quantity→receipt_quantity、movement_date→receipt_date。"""
"""通用字段映射为调拨行:doc_no→invoice_no、quantity→movement_quantity、movement_date→movement_date(tt14 入站化后明细侧同名对齐)。"""
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
assert len(parsed) == 1
row = parsed[0]
assert isinstance(row, ParsedReceiptRow)
assert isinstance(row, ParsedMovementRow)
assert row.invoice_no == "MOV-001"
assert row.material_no == "MAT-001"
assert row.material_name == "连接器组件"
assert row.receipt_date == date(2026, 8, 5)
assert row.receipt_quantity == Decimal("500")
assert row.movement_date == date(2026, 8, 5)
assert row.movement_quantity == Decimal("500")
assert row.sheet == "Movement"
assert row.row_no == 7
def test_missing_doc_no_rejected():
"""单号缺失阻断。"""
with pytest.raises(ReceiptFileSchemaError):
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no=""))
def test_invalid_quantity_rejected():
"""非数字数量阻断。"""
with pytest.raises(ReceiptFileSchemaError):
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc"))
def test_invalid_movement_date_rejected():
"""非法异动日期阻断。"""
with pytest.raises(ReceiptFileSchemaError):
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99"))
def test_source_identity_mismatch_rejected():
"""来源身份漂移阻断。"""
with pytest.raises(ReceiptFileSchemaError):
with pytest.raises(MovementFileSchemaError):
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
@@ -124,9 +124,9 @@ def test_receiving_in_progress_rows_are_skipped():
def test_unparseable_date_still_fails():
"""日期有值但不可解析仍是数据损坏——跳过守卫不得吞掉真正的脏数据。"""
corrupted = dict(VALID_MOVEMENT_ROW, row_no=5, doc_no="MOV-300", movement_date="not-a-date")
with pytest.raises(ReceiptFileSchemaError) as exc_info:
with pytest.raises(MovementFileSchemaError) as exc_info:
parse_movement_rows(source_code="DBS-AWSBI", rows=[corrupted])
assert any("invalid_receipt_date" in error.get("reason", "")
assert any("invalid_movement_date" in error.get("reason", "")
for error in exc_info.value.details["rows"])
@@ -140,4 +140,4 @@ def test_datetime_cell_and_timed_string_dates_are_accepted():
movement_date="2026-09-08 00:00:00")
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[datetime_cell, timed_string])
# [断言意图] WMS 报表真实日期形态不能被 ISO 纯日期校验误杀。
assert [row.receipt_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)]
assert [row.movement_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)]
@@ -25,7 +25,7 @@ def _executed_run(dbs_ready_file, patch_source_file_status):
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
item_ids = [
item.id for item in db.session.query(TransferInvoiceItem)
.filter_by(status="ready_to_execute").all()
@@ -28,7 +28,7 @@ def _ready_items(dbs_ready_file):
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
items = (
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
.order_by(TransferInvoiceItem.id)
@@ -0,0 +1,235 @@
"""outbound_evidence_sync:出站证据同步(落档桥)守卫矩阵。
用途:锁定出站回调 success 后的解析落档链——①正常路径按 purpose=outbound 已发布
规则解析归档、record_kind='outbound' 幂等落档 + 审计事件;②schema 类解析
失败把 parse_failed 三列独立落到出站归档文件上(状态投影随之 parse_failed)、
一行不落;③无配置/规则未发布或 purpose 不符 → no-op(fail-closed,不落失败
标记——规则缺失不是文件错误);④handler 接线:success 事实触发同步。
依赖:factories(build_movement_xlsx/INBOUND_MOVEMENT_FIELD_MAPPING + FakeArchiveStorage)、
ledger_sync.movement_file_version、app fixture(全局种子含 DSV360_AWSDU 站点)。
逻辑:归档字节经假存储注入(monkeypatch file_asset_storage.get_bytes);解析组装
与落档口径全部复用入站同一实现(parse_archive_to_ledger_rows / sync_ledger_rows),
差异仅 record_kind 与规则门禁 purpose='outbound'。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
FreightRpaParsingProfile,
TransferAuditEvent,
TransferMovementLedger,
)
from app.services.in_transit_transfer.ledger_sync import movement_file_version
from app.services.in_transit_transfer.outbound_evidence_sync import (
sync_and_commit_for_outbound_callback,
)
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
from tests.services.in_transit_transfer import factories
pytestmark = [pytest.mark.usefixtures("app")]
SOURCE = "DSV360_AWSDU"
# 真实时钟基准:handler/状态投影内部固定取 utcnow(),种子必须同窗口。
NOW = datetime.utcnow()
STORAGE_KEY = "shipping/outbound/evidence-sync.xlsx"
@pytest.fixture
def outbound_storage(monkeypatch):
"""归档假存储:替换单例 get_bytes(所有引用方同源)。"""
fake = factories.FakeArchiveStorage()
monkeypatch.setattr(
"app.services.file_assets.storage.file_asset_storage.get_bytes", fake.get_bytes)
return fake
def _seed_outbound_world(*, profile_status: str = "published",
profile_purpose: str = "outbound",
bind_profile: bool = True) -> FreightRpaOutboundReportFile:
"""出站世界种子:出站配置(绑定解析规则)+ 执行单元 + 当天可用归档文件行。
Returns:
已入库的 FreightRpaOutboundReportFile(字节由用例注入假存储)。
"""
from app.models import FreightRpaSource
source = FreightRpaSource.query.filter_by(source_code=SOURCE).one()
profile = None
if bind_profile:
profile = FreightRpaParsingProfile(
purpose=profile_purpose, profile_code=f"OUT_{SOURCE}", display_name=SOURCE,
version=1, status=profile_status, file_format="xlsx",
definition_json={
"field_mapping": factories.INBOUND_MOVEMENT_FIELD_MAPPING,
"sheet_name": "Receipt", "header_row_index": 1,
},
structure_definition_json={},
)
db.session.add(profile)
db.session.flush()
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={"report_name": "Outbound"},
query_parameters_json=[],
parsing_profile_id=profile.id if profile is not None else None,
))
unit = FreightRpaOutboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=SOURCE,
connector_type="dbs", warehouse_id="AWSDU", callback_id="outbound-sync-001",
status="success", config_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
import hashlib
digest = hashlib.sha256(b"outbound evidence workbook").hexdigest()
report = FreightRpaOutboundReportFile(
unit_run_id=unit.id, storage_provider="minio", storage_bucket="test",
storage_key=STORAGE_KEY, original_filename="outbound-sync.xlsx",
file_size=16, sha256=digest,
# 与 NOW 同刻:保证落在真实业务日新鲜度窗口内(handler/投影同窗口)。
created_at=NOW,
)
db.session.add(report)
db.session.commit()
return report
def _count_outbound_ledger(source_code: str = SOURCE) -> int:
"""该来源 outbound 档行总数。"""
return TransferMovementLedger.query.filter_by(
source_code=source_code, record_kind="outbound").count()
def test_outbound_callback_syncs_ledger_rows(outbound_storage):
# [断言意图] 正常路径:success 回调桥把出站归档按 purpose=outbound 规则解析、
# record_kind='outbound' 幂等落档;溯源(source_file_id/sha)与审计事件齐全。
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
assert ok is True # [断言意图] 落档成功
assert _count_outbound_ledger() == 1 # [断言意图] 出站行落异动档
db.session.expire_all()
row = TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").one()
assert row.doc_no == "ASN-O1" and row.material_code == "MAT-O1"
assert row.quantity == "120" and row.movement_date == "2026-10-16"
assert row.source_file_id == report.id and row.file_sha256 == report.sha256
# [断言意图] 审计事件带 record_kind=outbound(与入站同 kind、payload 区分流)。
event = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EVIDENCE_SYNCED").one()
assert event.after_json["record_kind"] == "outbound"
assert event.after_json["inserted"] == 1
def test_outbound_file_version_uses_shared_stamp(outbound_storage):
"""出站落档的 file_version 必须是 movement_file_version,不能在本路径另拼。
Why: 2026-10-21 DSV AWSFRA01/AWSBICMH01 实测——本路径自行拼接 sha256: 前缀
且未按列宽截断,71 字符整批 INSERT 失败,文件仍显示就绪但档里零记录。
"""
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O1", "1", "O", "MAT-O1", "成品", "LOT-O1", 120, "2026-10-16"],
])
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
assert ok is True # [断言意图] 落档成功(不再超长炸批)
db.session.expire_all()
row = TransferMovementLedger.query.filter_by(
source_code=SOURCE, record_kind="outbound").one()
# [断言意图] 落库版本戳等于共享函数对这份摘要的结果,且不超过列宽。
assert row.file_version == movement_file_version(report.sha256)
assert len(row.file_version) <= 64
def test_outbound_parse_failure_marks_file_and_lands_nothing(outbound_storage):
# [断言意图] 解析失败分层(出站补齐):schema 类失败 → parse_failed 三列独立
# 落到出站归档文件、零档行;状态投影随之 parse_failed(文件仍可用、供诊断)。
report = _seed_outbound_world()
# 有料号但单号为空 → missing_invoice_no → 解析必失败(料号空行 2026-10-21
# 起静默跳过放行,schema 失败路径改由仍受管控的单号缺失触发)。
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx(
[["", 100, "O", "MAT-X", "成品", "LOT-X", 30, "2026-10-16"]])
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
assert ok is False # [断言意图] 落档失败如实返回
assert _count_outbound_ledger() == 0 # [断言意图] 一行不落
db.session.expire_all()
marked = FreightRpaOutboundReportFile.query.filter_by(id=report.id).one()
assert marked.parse_failed_at is not None # [断言意图] 失败事实落到文件
assert marked.parse_error_code == "TRANSFER_FILE_SCHEMA_INVALID"
status = resolve_source_file_status(source_code=SOURCE, record_kind="outbound")
assert status["file_status"] == "parse_failed" # [断言意图] 投影不再当 ready
assert status["file_sha256"] == report.sha256
def test_outbound_without_published_outbound_profile_is_noop(outbound_storage):
# [断言意图] 规则门禁(fail-closed):无绑定规则 / 规则未发布 / purpose 不符
# → 桥 no-op(True=无事可做),零档行且不落解析失败标记——规则缺失不是文件错误。
for kwargs in (
{"bind_profile": False}, # 未绑定规则
{"profile_status": "draft"}, # 规则未发布
{"profile_purpose": "inbound"}, # purpose 不符(误绑入站规则)
):
report = _seed_outbound_world(**kwargs)
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O2", "1", "O", "MAT-O2", "成品", "LOT-O2", 30, "2026-10-16"],
])
ok = sync_and_commit_for_outbound_callback(source_code=SOURCE, now=NOW)
assert ok is True, kwargs # [断言意图] 无事可做≠失败
assert _count_outbound_ledger() == 0, kwargs
db.session.expire_all()
assert FreightRpaOutboundReportFile.query.filter_by(
id=report.id).one().parse_failed_at is None, kwargs
# 清场(三门支共用全局种子,互不污染)。
FreightRpaOutboundReportConfig.query.delete()
FreightRpaOutboundReportFile.query.delete()
FreightRpaOutboundUnitRun.query.delete()
if kwargs.get("bind_profile", True):
FreightRpaParsingProfile.query.filter(
FreightRpaParsingProfile.profile_code == f"OUT_{SOURCE}").delete()
db.session.commit()
def test_outbound_handler_success_fact_triggers_sync(outbound_storage):
# [断言意图] handler 接线:outbound success 事实(ok 且 file_id)在任务推进/
# 提交之后触发证据同步(与入站 handle_inbound_report STEP 4 对称);失败事实
# 不触发(无文件可解析,桥不得误读他源文件)。
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
report = _seed_outbound_world()
outbound_storage.objects[STORAGE_KEY] = factories.build_movement_xlsx([
["ASN-O3", "1", "O", "MAT-O3", "成品", "LOT-O3", 55, "2026-10-16"],
])
handle_outbound_report(ReportFact(
report_kind="outbound", source_code=SOURCE, file_id=report.id,
sha256=report.sha256, ok=True, error_code=None, error_message=None,
unit_run_id=report.unit_run_id,
))
assert _count_outbound_ledger() == 1 # [断言意图] 事实驱动落档
# [断言意图] 失败事实(同一世界、新归档无字节解析路径不触发):行数不增。
handle_outbound_report(ReportFact(
report_kind="outbound", source_code=SOURCE, file_id=None,
sha256=None, ok=False, error_code="RPA_OUTBOUND_CALLBACK_FAILED",
error_message="export failed", unit_run_id=report.unit_run_id,
))
assert _count_outbound_ledger() == 1
@@ -0,0 +1,316 @@
"""出站 RPA 触发服务与报表处理函数测试。
用途:验证 trigger_outbound_rpa / trigger_outbound_rpa_batch 按来源装配出站
trigger unit 并调用写者;站点停用 / 出站配置缺失 / 登录连接缺失 fail-closed;
handle_outbound_report 把等待中的 TransferSourceJob 从 waiting_rpa_callback
推进到 file_ready(无等待任务 no-op,可重入)。
依赖:app(SQLite)fixture、outbound_trigger_service、outbound_report_handler、
既有测试种子(FreightRpaProfile/FreightRpaSource)。
逻辑:对照 test_inbound_trigger_service;出站配置行挂 FreightRpaOutboundReportConfig;
写者协议与入站一致(payload= 附加字段);handler 只改调拨等待行,不写新状态。
"""
from __future__ import annotations
import pytest
from app.models import FreightRpaSource, FreightRpaOutboundReportConfig
from app.services.in_transit_transfer.outbound_trigger_service import (
trigger_outbound_rpa,
trigger_outbound_rpa_batch,
)
@pytest.fixture
def outbound_source():
"""复用种子来源并为其创建出站配置。"""
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
assert source is not None
config = FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'},
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
)
from app import db
db.session.add(config)
db.session.commit()
return source
def test_trigger_outbound_rpa_disabled_source_fails_closed(app):
"""来源停用 → ok=False,不写 trigger。"""
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
source.enabled = False
from app import db
db.session.commit()
result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_missing_config_fails_closed(app):
"""来源启用但无出站配置 → ok=False。"""
result = trigger_outbound_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
assert result['ok'] is False
assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_missing_login_fails_closed(app, outbound_source):
"""出站配置存在但登录连接停用 → ok=False,不写 trigger。"""
from app import db
outbound_source.rpa_profile.enabled = False
db.session.commit()
result = trigger_outbound_rpa(
source_code='DSV360_AWSDU', business_date='2026-08-06',
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
)
assert result['ok'] is False
assert result['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_writes_batch_trigger(app, outbound_source):
"""来源有效 → 写入 trigger 并返回 callback_id / trigger_path。"""
calls = {}
def fake_writer(run_no, units, payload=None):
calls['run_no'] = run_no
calls['units'] = units
calls['payload'] = payload or {}
return f'/tmp/trigger/{run_no}.json'
result = trigger_outbound_rpa(
source_code='DSV360_AWSDU', business_date='2026-08-06',
reason='transfer_retry_outbound', writer=fake_writer,
)
assert result['ok'] is True
assert result['callback_id']
assert result['trigger_path'].endswith('.json')
assert calls['units'][0]['source_code'] == 'DSV360_AWSDU'
assert calls['units'][0]['warehouse_id'] is None
assert calls['units'][0]['query_parameters_json'] == [
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
]
assert calls['units'][0]['credential_envelope']
assert calls['payload']['schema_version'] == 'freight_rpa.outbound.v1'
def test_trigger_outbound_rpa_creates_unit_run_before_writing_trigger(app, outbound_source):
"""触发必须先落 FreightRpaOutboundUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
from app.models import FreightRpaOutboundUnitRun
captured: dict = {}
def fake_writer(run_no, units, payload=None):
captured['units'] = units
return 'trigger.json'
outcome = trigger_outbound_rpa(
source_code=outbound_source.source_code, business_date='2026-10-19',
reason='transfer_retry_outbound', writer=fake_writer,
)
assert outcome['ok'] is True
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=outcome['callback_id']).one()
assert unit.status == 'awaiting_rpa'
assert unit.schedule_run_id is None
assert FreightRpaOutboundUnitRun.__table__.columns['schedule_run_id'].nullable is True
assert captured['units'][0]['unit_run_id'] == unit.id
assert unit.trigger_snapshot_json['callback_id'] == unit.callback_id
def test_trigger_outbound_rpa_marks_unit_failed_when_trigger_unavailable(app, outbound_source):
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
from app.models import FreightRpaOutboundUnitRun
outcome = trigger_outbound_rpa(
source_code=outbound_source.source_code, business_date='2026-10-19',
reason='transfer_retry_outbound', writer=lambda *a, **k: None,
)
assert outcome['ok'] is False
unit = FreightRpaOutboundUnitRun.query.filter_by(source_code=outbound_source.source_code).order_by(
FreightRpaOutboundUnitRun.id.desc()).first()
assert unit.status == 'failed'
assert unit.error_code == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
@pytest.fixture
def second_outbound_source(app):
"""再造一个启用来源 + 出站配置(批量用例需要多来源)。"""
from app import db
from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile, FreightRpaOutboundReportConfig
seed = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').first()
profile = FreightRpaProfile(
profile_code='DBS_SG_OUT_TEST', display_name='DBS SG Out', connector_type='dbs',
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
)
source = FreightRpaSource(
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
rpa_profile=profile,
excel_template=seed.excel_template,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
enabled=True,
)
seed_config = seed.onhand_report_config
FreightRpaOnhandReportConfig(
source=source,
parsing_profile=seed_config.parsing_profile if seed_config is not None else None,
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
query_parameters_json=[],
)
db.session.add_all([profile, source])
db.session.flush()
config = FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={'program_group': 'Bison', 'report_name': 'Outbound Details'},
query_parameters_json=[],
)
db.session.add(config)
db.session.commit()
return source
def test_trigger_outbound_rpa_batch_writes_one_trigger_for_all_units(app, outbound_source, second_outbound_source):
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
from app.models import FreightRpaOutboundUnitRun
calls: list = []
def fake_writer(run_no, units, payload=None):
calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}})
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19',
reason='transfer_retry_outbound', writer=fake_writer,
)
assert len(calls) == 1
assert outcome['ok'] is True and outcome['triggered'] is True
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
assert calls[0]['payload']['schema_version'] == 'freight_rpa.outbound.v1'
callback_ids = {u['callback_id'] for u in calls[0]['units']}
assert len(callback_ids) == 2
rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.source_code.in_(
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
assert {row.status for row in rows} == {'awaiting_rpa'}
assert all(row.schedule_run_id is None for row in rows)
assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']}
def test_trigger_outbound_rpa_batch_skips_invalid_source(app, outbound_source):
"""单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。"""
captured: dict = {}
def fake_writer(run_no, units, payload=None):
captured['units'] = units
return f'/tmp/trigger/{run_no}.json'
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-19',
writer=fake_writer,
)
assert outcome['ok'] is True and outcome['triggered'] is True
assert [u['source_code'] for u in captured['units']] == ['DSV360_AWSDU']
by_code = {item['source_code']: item for item in outcome['results']}
assert by_code['DSV360_AWSDU']['ok'] is True
assert by_code['DSV360_NOPE']['ok'] is False
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_OUTBOUND_CONFIG_MISSING'
def test_trigger_outbound_rpa_batch_all_invalid_no_trigger(app):
"""全部来源无效 → 不写 trigger,ok=False + RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE。"""
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_NOPE'], business_date='2026-10-19',
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE'
def test_trigger_outbound_rpa_batch_writer_unavailable_marks_all_failed(app, outbound_source, second_outbound_source):
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
from app.models import FreightRpaOutboundUnitRun
outcome = trigger_outbound_rpa_batch(
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-19',
writer=lambda *a, **k: None,
)
assert outcome['ok'] is False and outcome['triggered'] is False
assert outcome['error_code'] == 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
rows = FreightRpaOutboundUnitRun.query.filter(FreightRpaOutboundUnitRun.source_code.in_(
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
assert {row.status for row in rows} == {'failed'}
assert {row.error_code for row in rows} == {'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'}
def _waiting_job(source_code: str):
"""构造一个未落库的 waiting_rpa_callback 来源任务。"""
from app import db
from app.models import TransferRun, TransferSourceJob
run = TransferRun(
run_no=f'RUN-OUT-{source_code}',
business_date='2026-10-19',
status='preparing_files',
trigger_type='manual',
)
db.session.add(run)
db.session.flush()
return TransferSourceJob(run_id=run.id, source_code=source_code, status='waiting_rpa_callback')
def test_handle_outbound_report_advances_waiting_job_to_file_ready(app):
"""ok 事实把等待中的 SourceJob 从 waiting_rpa_callback 推进到 file_ready。"""
from app import db
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
job = _waiting_job('DSV')
db.session.add(job)
db.session.commit()
handle_outbound_report(ReportFact(
report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True,
))
db.session.refresh(job)
assert job.status == 'file_ready'
assert job.file_no == '42'
assert job.file_sha256 == 'abc'
def test_handle_outbound_report_noop_without_waiting_job(app):
"""无等待中的调拨任务:处理函数 no-op,不产生任何调拨来源任务行。"""
from app.models import TransferSourceJob
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
handle_outbound_report(ReportFact(
report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True,
))
assert TransferSourceJob.query.filter_by(source_code='DSV').count() == 0
def test_handle_outbound_report_is_reentrant(app):
"""第二次投递时该行已离开等待态,不再改(可重入)。"""
from app import db
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
job = _waiting_job('DSV')
db.session.add(job)
db.session.commit()
fact = ReportFact(report_kind='outbound', source_code='DSV', file_id=42, sha256='abc', ok=True)
handle_outbound_report(fact)
db.session.refresh(job)
first_finished = job.finished_at
handle_outbound_report(ReportFact(
report_kind='outbound', source_code='DSV', file_id=99, sha256='zzz', ok=True,
))
db.session.refresh(job)
assert job.status == 'file_ready'
assert job.file_no == '42'
assert job.file_sha256 == 'abc'
assert job.finished_at == first_finished
@@ -16,7 +16,7 @@ from app.services.in_transit_transfer.quantity import (
QuantityValidationError,
classify_quantity_match,
strict_quantities_equal,
validate_receipt_quantity,
validate_inbound_quantity,
)
pytestmark = pytest.mark.pure_unit
@@ -27,12 +27,12 @@ def test_equal_quantities_are_executable():
assert classify_quantity_match(Decimal("1200"), Decimal("1200")) == "executable"
def test_erp_greater_than_receipt_is_blocked():
def test_erp_greater_than_inbound_is_blocked():
"""外部系统 库存大于收料数量 → 阻断(不允许部分调拨)。"""
assert classify_quantity_match(Decimal("1200"), Decimal("1500")) == "blocked_quantity_mismatch"
def test_erp_less_than_receipt_is_blocked():
def test_erp_less_than_inbound_is_blocked():
"""外部系统 库存小于收料数量 → 阻断。"""
assert classify_quantity_match(Decimal("1200"), Decimal("800")) == "blocked_quantity_mismatch"
@@ -47,27 +47,27 @@ def test_decimal_scale_equality_is_exact():
assert strict_quantities_equal(Decimal("1.0"), Decimal("1.00"))
def test_zero_receipt_quantity_rejected():
def test_zero_movement_quantity_rejected():
"""收料数量为 0 非法。"""
with pytest.raises(QuantityValidationError):
validate_receipt_quantity(Decimal("0"))
validate_inbound_quantity(Decimal("0"))
def test_negative_receipt_quantity_rejected():
def test_negative_movement_quantity_rejected():
"""收料数量为负数非法。"""
with pytest.raises(QuantityValidationError):
validate_receipt_quantity(Decimal("-5"))
validate_inbound_quantity(Decimal("-5"))
def test_non_numeric_quantity_rejected():
"""非数字数量非法(解析层不得静默截断)。"""
with pytest.raises(QuantityValidationError):
validate_receipt_quantity("abc")
validate_inbound_quantity("abc")
def test_string_numeric_quantity_normalized():
"""字符串数字归一化为 Decimal 后参与严格比较。"""
assert validate_receipt_quantity("1200") == Decimal("1200")
assert validate_inbound_quantity("1200") == Decimal("1200")
assert strict_quantities_equal("1200", Decimal("1200"))
@@ -48,7 +48,7 @@ def _cap_deps(file, gw):
def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
"""成熟 Invoice 的库存查询经网关;严格数量匹配仍由领域控制。"""
"""圈中行的库存查询经网关;严格数量匹配仍由领域控制。"""
gw = FakeGateway(inventory={
("MAT-001", "DBS-TRANSIT", "LOT-10"): "1200",
("MAT-002", "DBS-TRANSIT", "LOT-20"): "1200",
@@ -57,7 +57,7 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
result = run_matching(
source_codes=["DBS-AWSBI"], business_date="2026-08-06",
deps=deps, run_no="RUN-T",
deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub"
)
# 网关被调用,且携带 query_inventory 能力名与 (external_org, targets) 契约
assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls)
@@ -70,17 +70,21 @@ def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
assert item.from_quantity == Decimal("1200")
def test_not_matured_not_queried(app, same_day_receipt_file):
"""当天收料(not_matured)不查外部系统——网关零调用。"""
def test_same_day_data_not_queried_before_maturity(app, same_day_inbound_file):
"""【T−2 成熟封顶 2026-10-21】当天(T)异动未成熟:不进圈档、不经网关查询。
[断言意图] 圈档封顶 movement_date ≤ T−2:当天行不出生 item,网关零调用——
日期在圈档入口即构成过滤(此前「成熟退役 2026-10-16」的免查语义随之收回)。
"""
gw = FakeGateway(inventory={})
deps = _cap_deps(same_day_receipt_file, gw)
deps = _cap_deps(same_day_inbound_file, gw)
seed_rows_from_file("DBS-AWSSG", deps, "2026-08-06")
result = run_matching(
source_codes=["DBS-AWSSG"], business_date="2026-08-06",
deps=deps, run_no="RUN-T",
deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub"
)
assert gw.calls == []
assert result.items[0].result == "not_matured"
assert result.items == ()
def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file):
@@ -111,7 +115,7 @@ def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready
seed_rows_from_file("CRANE-SZ", deps, "2026-08-06")
result = run_matching(
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06",
deps=deps, run_no="RUN-T",
deps=deps, run_no="RUN-T", transfer_type="in_transit_to_hub"
)
# [断言意图] 外部系统基础设施故障降级为逐单 blocked_external_query_failed:
# 来源保持 file_ready,发票带原因可见,其余来源(CRANE)不受影响。
@@ -0,0 +1,332 @@
"""首页队列「待匹配」桶与执行门禁改锚测试(Task 12,规格 §10,D16/D17)。
用途:锁定两块契约——
①「待匹配」桶口径:成熟未占用的出入站全量(不按类型范围过滤);
可匹配=启用类型范围并集(matchable / matchable_count)。
未封存(transfer_executed=false)、无有效 items(D17 占用判定一致)、
movement_date ≤ T−2;匹配圈定后离开、取消匹配释放后回归;无 item_id。
②file_current 门禁改锚(规格 §10):行当前性 = item → 档记录 file_sha256 ==
该来源最新可用文件 sha(档记录无变化即当前——档换版原行更新后行不再因
出生戳陈旧误判);行无档关联回退 raw_lines 出生戳(存量兼容)。
依赖:app fixture、repo_fakes、factories、models、backlog_service、matching_service。
逻辑:档记录直接 ORM 种子(与 test_requery_scope 同款);匹配走 create_matching
真链路;来源文件状态投影经 monkeypatch 注入(不触碰收料文件表)。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import TransferInvoiceItem, TransferMovementLedger, TransferRun, TransferTypeConfig
from app.services.in_transit_transfer.backlog_service import (
backlog_summary,
list_pending_match_records,
list_pending_match_records_page,
)
from app.services.in_transit_transfer.matching_service import (
_item_dto,
create_matching,
)
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
pytestmark = [pytest.mark.usefixtures("app")]
NOW = datetime(2026, 10, 14, 12, 0, 0)
def _seed_ledger(doc_no: str, *, quantity: str = "100", lot_no: str = "LOT-1",
sha: str = "a" * 64, row_no: int = 1, source_code: str = "DBS-AWSBI",
record_kind: str = "inbound", movement_date: str | None = "2026-10-13",
transfer_executed: bool = False, executed_doc_no: str | None = None,
external_doc_no: str = "", external_line_no: str = "",
material_code: str = "MAT-1", material_name: str = "物料1"):
"""种子一条档记录(缺省=默认类型范围内的收料记录,与 test_requery_scope 同款)。
external_doc_no 为空时,待匹配清单不会把该行并进其他外部单。
"""
row = TransferMovementLedger(
source_code=source_code, record_kind=record_kind,
doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="",
material_code=material_code, material_name=material_name, specification="",
external_doc_no=external_doc_no, external_line_no=external_line_no,
lot_no=lot_no, quantity=quantity, unit="PCS",
warehouse_code="", storage_code="", movement_date=movement_date,
source_file_id=None, file_version="v1", file_sha256=sha,
sheet_name="Receipt", row_no=row_no, updated_at=NOW,
transfer_executed=transfer_executed, executed_doc_no=executed_doc_no,
)
db.session.add(row)
db.session.flush()
return row
def _match_defaults():
"""构造默认 deps + 预置账面(create_matching 真链路;账面=行数量 → ready)。"""
deps, erp, _rpa = make_transfer_deps()
erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100")
return deps
def _pending_doc_nos() -> set[str]:
"""待匹配桶的单号集合(断言辅助)。"""
return {record.doc_no for record in list_pending_match_records()}
def _matchable_doc_nos() -> set[str]:
"""待匹配桶里启用类型现在圈得住的单号。"""
return {record.doc_no for record in list_pending_match_records() if record.matchable}
# ---------------------------------------------------------------------------
# ①「待匹配」桶口径(D16)
# ---------------------------------------------------------------------------
def test_pending_match_bucket_lists_unmatched_records():
"""已落档且无任何 items 的收料记录进「待匹配」桶,字段=档只读投影。"""
_seed_ledger("HOM-1", quantity="100")
_seed_ledger("HOM-2", quantity="200", row_no=2)
records = list_pending_match_records()
# [断言意图] 桶口径:范围内的未占用收料记录全部在桶(启用类型并集圈档)。
assert _pending_doc_nos() == {"HOM-1", "HOM-2"}
first = records[0]
# [断言意图] 字段=档只读投影七键(前端只读清单列:单号/料号/名称/收料日期/来源/数量)。
assert first.ledger_record_id > 0
assert first.doc_no in {"HOM-1", "HOM-2"}
assert first.material_code == "MAT-1"
assert first.material_name == "物料1"
assert first.movement_date == "2026-10-13"
assert first.source_code == "DBS-AWSBI"
assert first.quantity == "100"
# [断言意图] 不可执行的结构保证:DTO 无 item_id(未做库存核对,不可勾选)。
assert "item_id" not in type(first).__dataclass_fields__
def test_pending_match_list_rolls_up_quantity_by_external_doc():
"""同一外部单号的多项次合成一行,数量相加;没有外部单号的档行仍逐行留下。"""
_seed_ledger("HOM-1", quantity="1.50", row_no=1, external_doc_no="5975091", external_line_no="0010")
_seed_ledger(
"HOM-1", quantity="2.50", row_no=2, external_doc_no=" 5975091 ", external_line_no="0020", lot_no="LOT-2",
)
_seed_ledger(
"HOM-9", quantity="4", row_no=3, external_doc_no="5975091", external_line_no="0030",
lot_no="LOT-3", material_code="MAT-9", material_name="另一物料", movement_date="2026-10-12",
)
_seed_ledger("HOM-2", quantity="7", row_no=4, external_doc_no="5976000", external_line_no="0010", lot_no="LOT-4")
_seed_ledger("HOM-3", quantity="4", row_no=5, lot_no="LOT-5")
_seed_ledger(
"HOM-4", quantity="8", row_no=6, external_doc_no="5975091", external_line_no="0010",
lot_no="LOT-6", source_code="OTHER-SRC",
)
records = list_pending_match_records()
rolled = next(
record for record in records
if record.external_doc_no == "5975091" and record.source_code == "DBS-AWSBI"
)
# [断言意图] 同一来源、同一记录类型、同一外部单号的项次合成一行,数量相加。
assert rolled.quantity == "8"
# [断言意图] 内部单号、料号、异动日期在组内不一致时留空,避免显示成其中一笔。
assert rolled.doc_no == ""
assert rolled.material_code is None
assert rolled.material_name is None
assert rolled.movement_date is None
assert "external_line_no" not in type(rolled).__dataclass_fields__
assert next(record for record in records if record.external_doc_no == "5976000").quantity == "7"
blank = [record for record in records if not record.external_doc_no]
# [断言意图] 没有外部单号的档不并进别的单。
assert len(blank) == 1 and blank[0].doc_no == "HOM-3" and blank[0].quantity == "4"
other = next(record for record in records if record.source_code == "OTHER-SRC")
# [断言意图] 不同来源的同一外部单号分开合计。
assert other.external_doc_no == "5975091" and other.quantity == "8" and other.doc_no == "HOM-4"
assert len(records) == 4
summary = backlog_summary()
# [断言意图] 首页待匹配、可匹配数字与清单合并后的行数一致,不再按档行计数。
assert summary.pending_match_count == len(records)
assert summary.matchable_count == len(list_pending_match_records(segment="matchable"))
page = list_pending_match_records_page(page=1, page_size=2)
# [断言意图] 分页总数是合并后的行数,当前页按合并结果切片。
assert page.total == 4 and len(page.records) == 2
def test_pending_match_bucket_summary_count():
"""backlog 汇总带 pending_match 计数(首页第 4 张数字卡数据源)。"""
_seed_ledger("HOM-1")
_seed_ledger("HOM-2", row_no=2)
summary = backlog_summary()
assert summary.pending_match_count == 2
def test_pending_match_includes_mature_rows_outside_enabled_types():
"""待匹配收全部成熟未占用记录;可匹配只计启用类型范围并集。"""
_seed_ledger("HOM-1")
_seed_ledger("QQQ-1", row_no=2)
pending = list_pending_match_records()
summary = backlog_summary()
# [断言意图] 首页待匹配不再按类型范围收窄:范围外的成熟行仍在桶里。
assert {record.doc_no for record in pending} == {"HOM-1", "QQQ-1"}
# [断言意图] 库存匹配卡的可匹配数只含启用类型罩得住的行。
assert {record.doc_no for record in pending if record.matchable} == {"HOM-1"}
assert {record.doc_no for record in list_pending_match_records(segment="outside")} == {"QQQ-1"}
assert {record.doc_no for record in list_pending_match_records(segment="matchable")} == {"HOM-1"}
assert summary.pending_match_count == 2
assert summary.matchable_count == 1
def test_pending_match_bucket_leaves_once_matched():
"""匹配圈定 → 记录被 items 占用,离开待匹配桶(数字卡回落)。"""
_seed_ledger("HOM-1")
deps = _match_defaults()
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-15",
deps=deps, transfer_type="in_transit_to_hub")
# [断言意图] 记录被匹配 items 占用(D17)→ 离开待匹配桶。
assert _pending_doc_nos() == set()
def test_pending_match_bucket_returns_after_matching_cancelled():
"""取消匹配释放占用(D17)→ 记录回归待匹配桶。"""
_seed_ledger("HOM-1")
deps = _match_defaults()
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-10-15",
deps=deps, transfer_type="in_transit_to_hub")
assert _pending_doc_nos() == set()
from app.models import TransferMatching
from app.services.in_transit_transfer.cancellation import cancel_run
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).first()
run = db.session.get(TransferRun, matching.run_id)
cancel_run(run_no=run.run_no, reason="test release")
# [断言意图] 取消释放占用:记录重新可见于待匹配桶(抓到了没匹配的可见性不丢)。
assert _pending_doc_nos() == {"HOM-1"}
def test_pending_match_bucket_excludes_sealed_and_out_of_scope():
"""恒排除已封存与空异动日期;范围外仍留在待匹配,但不算可匹配。"""
_seed_ledger("HOM-1") # 在桶且可匹配
_seed_ledger("HOM-SEALED", row_no=2, transfer_executed=True,
executed_doc_no="ERP-1") # 已执行封存
_seed_ledger("HOM-SHIP", row_no=3, record_kind="outbound") # 出站,默认类型未钉记录类型
_seed_ledger("QQQ-1", row_no=4) # 范围外,仍在待匹配
_seed_ledger("HOM-NODATE", row_no=5, movement_date=None) # 异动日期空值
# [断言意图] 待匹配收成熟未占用的出入站;可匹配才按启用类型范围并集收窄。
assert _pending_doc_nos() == {"HOM-1", "HOM-SHIP", "QQQ-1"}
assert _matchable_doc_nos() == {"HOM-1", "HOM-SHIP"}
def test_pending_match_bucket_is_union_of_enabled_type_scopes():
"""可匹配=启用类型范围并集;停用类型不把已落档行移出待匹配。"""
_seed_ledger("HOM-1") # 默认类型(HOM/HOX/WTP 前缀)
_seed_ledger("ZZZ-1", row_no=2) # 第二类型范围
_seed_ledger("QQQ-1", row_no=3) # 无类型覆盖
seed_transfer_type_config("hub_repair_out", scope_rules=[
{"field": "doc_no", "match": "prefix", "values": ["ZZZ"]},
])
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"}
assert _matchable_doc_nos() == {"HOM-1", "ZZZ-1"}
# [断言意图] 停用类型即刻退出可匹配并集,待匹配全量保持不变。
row = db.session.query(TransferTypeConfig).filter_by(code="hub_repair_out").one()
row.enabled = False
db.session.commit()
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"}
assert _matchable_doc_nos() == {"HOM-1"}
# [断言意图] 无启用类型 → 可匹配为空;待匹配仍可见已落档行。
for cfg in db.session.query(TransferTypeConfig).all():
cfg.enabled = False
db.session.commit()
assert _matchable_doc_nos() == set()
assert _pending_doc_nos() == {"HOM-1", "ZZZ-1", "QQQ-1"}
# [断言意图] 可匹配段在没有启用类型时走空查询,而不是把全量当成可匹配。
assert list_pending_match_records(segment="matchable") == []
# ---------------------------------------------------------------------------
# ② file_current 门禁改锚(规格 §10)
# ---------------------------------------------------------------------------
def _patch_latest_file(monkeypatch, sha_by_source: dict[str, str]):
"""注入 matching_service 的来源文件状态投影(source_code → 最新可用文件 sha)。
record_kind 入参接受但不区分,存量断言仍按来源比对。
"""
def _resolve(*, source_code: str, record_kind: str = "inbound") -> dict:
del record_kind
sha = sha_by_source.get(source_code)
return {"file_status": "ready" if sha else "none", "has_ready_file": bool(sha),
"file_no": "REC-TEST", "file_sha256": sha}
monkeypatch.setattr(
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
_resolve,
)
def _seed_ready_item_with_ledger(sha: str = "a" * 64):
"""种子档记录 + 可执行 item(raw_lines 出生戳=sha,档记录 sha=sha)。"""
record = _seed_ledger("HOM-1", sha=sha)
item = TransferInvoiceItem(
matching_id=None, run_id=None, ledger_record_id=record.id,
source_code="DBS-AWSBI", invoice_no=record.doc_no,
material_no="MAT-1", material_name="物料1", specification="",
movement_date="2026-10-13", status="ready_to_execute", result_code=None,
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
movement_quantity="100", external_quantity="100",
lot_no="LOT-1", movement_warehouse_code="", unit="PCS",
raw_lines_json=[{"sheet": "Receipt", "row_no": 1,
"file_version": "v1", "file_sha256": sha}],
inventory_checked_at=NOW,
)
db.session.add(item)
db.session.flush()
return record, item
def test_file_current_anchors_to_ledger_record_version(monkeypatch):
"""改锚后行当前性=档记录 file_sha256 == 最新可用文件 sha(出生戳不再参与)。"""
record, item = _seed_ready_item_with_ledger(sha="a" * 64)
dto = _item_dto(item, {"file_sha256": "a" * 64}, NOW, 3600)
assert dto.file_current is True # [断言意图] 档记录持最新文件 sha → 当前
# [改锚行为变更] 档换版原行更新(file_sha256→b)而行出生戳仍是 a:
# 旧口径(出生戳 vs 最新)判 False;新口径档记录==最新 → 仍当前。
record.file_sha256 = "b" * 64
db.session.flush()
dto = _item_dto(item, {"file_sha256": "b" * 64}, NOW, 3600)
assert dto.file_current is True # [断言意图] 档记录无变化(仍在最新版)即当前
# 档记录滞后(最新文件 c,记录仍在 b)→ 行不再当前。
dto = _item_dto(item, {"file_sha256": "c" * 64}, NOW, 3600)
assert dto.file_current is False # [断言意图] 记录落后最新文件 → stale/blocked 依据
def test_file_current_falls_back_to_birth_stamp_without_ledger(monkeypatch):
"""无档关联的隔离历史行回退 raw_lines 出生戳(存量兼容口径)。"""
_record, item = _seed_ready_item_with_ledger(sha="a" * 64)
item.ledger_record_id = None
db.session.flush()
dto = _item_dto(item, {"file_sha256": "a" * 64}, NOW, 3600)
assert dto.file_current is True # [断言意图] 回退出生戳:出生版本==最新 → 当前
dto = _item_dto(item, {"file_sha256": "b" * 64}, NOW, 3600)
assert dto.file_current is False # [断言意图] 回退出生戳:版本落后 → 不当前
@@ -1,151 +0,0 @@
"""在途调拨收料文件字段/结构校验测试(L0 纯单元)。
用途:验证必填列缺失、空值、非法数量(0/负数/非数字)、非法日期与
来源身份不一致均整行阻断并抛出 ReceiptFileSchemaError。
依赖:app.services.in_transit_transfer.file_parser(纯函数)。
逻辑:解析不接触文件存储;所有错误带行号细节,供预检页展示原因。
"""
from __future__ import annotations
from datetime import date
from decimal import Decimal
import pytest
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
parse_receipt_rows,
)
pytestmark = pytest.mark.pure_unit
VALID_ROW = {
"sheet": "Receipt",
"row_no": 10,
"invoice_no": "INV-001",
"material_no": "MAT-001",
"material_name": "连接器组件",
"specification": "A 型 / 24PIN",
"receipt_date": "2026-08-05",
"receipt_quantity": "500",
"source_code": "DBS-AWSBI",
}
def _rows(**overrides) -> list[dict]:
"""以 VALID_ROW 为基底覆盖字段构造测试行。"""
base = dict(VALID_ROW)
base.update(overrides)
return [base]
def test_valid_rows_parse():
"""合法行解析出全部字段(数量 Decimal、日期 date)。"""
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows())
assert len(parsed) == 1
row = parsed[0]
assert isinstance(row, ParsedReceiptRow)
assert row.invoice_no == "INV-001"
assert row.material_no == "MAT-001"
assert row.material_name == "连接器组件"
assert row.specification == "A 型 / 24PIN"
assert row.receipt_date == date(2026, 8, 5)
assert row.receipt_quantity == Decimal("500")
assert row.sheet == "Receipt"
assert row.row_no == 10
def test_missing_invoice_no_rejected():
"""Invoice No 缺失必须整行阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(invoice_no=""))
def test_missing_material_no_rejected():
"""料号缺失必须整行阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(material_no=""))
def test_invalid_quantity_rejected():
"""非数字数量必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc"))
def test_zero_quantity_stamped_row_skipped():
"""零数量收料行(日期已盖章、数量 0)为非可用收料事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。"""
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
assert parsed == []
def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed():
"""合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。"""
rows = [
dict(VALID_ROW, row_no=788, invoice_no="WTP26082227", receipt_quantity="0",
receipt_date="2026-10-01 14:37:43"),
dict(VALID_ROW, row_no=789, invoice_no="INV-002", receipt_quantity="120"),
]
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
assert [row.row_no for row in parsed] == [789]
assert parsed[0].invoice_no == "INV-002"
def test_negative_quantity_rejected():
"""负数数量必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="-5"))
def test_invalid_date_rejected():
"""非法日期必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_date="2026/13/99"))
def test_source_identity_mismatch_rejected():
"""行内来源与任务来源不一致(Callback 身份漂移)必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
def test_missing_sheet_or_row_no_rejected():
"""Sheet/原始行号缺失无法追溯,必须阻断。"""
with pytest.raises(ReceiptFileSchemaError):
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0))
def test_material_name_and_specification_optional():
"""品名/规格允许为空(后续由明细 DTO 展示空值)。"""
parsed = parse_receipt_rows(
source_code="DBS-AWSBI",
rows=_rows(material_name="", specification=""),
)
assert parsed[0].material_name == ""
assert parsed[0].specification == ""
def test_error_carries_row_details():
"""错误细节必须携带行号与原因,供页面定位。"""
with pytest.raises(ReceiptFileSchemaError) as excinfo:
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc"))
details = excinfo.value.details
assert any(str(item.get("row_no")) == "77" for item in details.get("rows", []))
def test_schema_error_message_carries_row_details():
"""诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。"""
rows = [
dict(VALID_ROW, row_no=5, invoice_no=""),
dict(VALID_ROW, row_no=9, receipt_quantity="abc"),
]
with pytest.raises(ReceiptFileSchemaError) as exc_info:
parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
# [断言意图] 消息不再只是通用 "receipt file schema invalid",须含行号与原因;
# 明细同时保留在 details.rows 供管理端展示。
text = str(exc_info.value) or (exc_info.value.message or "")
assert "row 5" in text and "missing_invoice_no" in text
detail_rows = (exc_info.value.details or {}).get("rows") or []
assert {"row_no": 5, "reason": "missing_invoice_no"} in detail_rows
@@ -23,7 +23,7 @@ def _mixed_matching(dbs_ready_file):
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
return deps, erp, summary
@@ -3,6 +3,8 @@
用途:锁死重查外部访问形态——全部重查入口经 retry_service._recheck_items_batch
按组织分组批量 query_stock(与执行链写前复查同形态);禁止回退逐行单查
(N 行 N 次外部调用会打崩外部系统)。
【出生翻转 2026-10-14】行创建即绑定匹配,匹配号重查只触自有 items——
行种子显式挂匹配(旧「无归属行 + scope 圈行」语义已退役)。
依赖:app fixture、repo_fakes.make_transfer_deps、models。
逻辑:同组织多行 → 1 次 query_stock 且目标元组一次下传全部行;跨组织 → 每组织
各 1 次;单行路由解析失败只跳过该行(ok=False、行未被触碰、未建 Attempt),
@@ -33,8 +35,8 @@ def _seed(scope_sources, matching_no):
matching = TransferMatching(
matching_no=matching_no, run_id=run.id, business_date="2026-09-24",
status="success",
scope_json={"source_codes": scope_sources, "receipt_date_from": None,
"receipt_date_to": None, "transfer_type": "in_transit_to_hub"},
scope_json={"source_codes": scope_sources, "movement_date_from": None,
"movement_date_to": None, "transfer_type": "in_transit_to_hub"},
file_snapshot_json={}, mapping_version="v0", strategy_version="v0",
counts_json={}, estimated_transfer_quantity="0",
estimated_external_write_count=0, matching_hash="sha256:x",
@@ -45,14 +47,16 @@ def _seed(scope_sources, matching_no):
return matching
def _seed_row(source_code, invoice_no, lot_no):
def _seed_row(source_code, invoice_no, lot_no, matching=None):
"""种子一条可重查行(出生翻转后行绑匹配:默认挂当前模块用例的匹配)。"""
row = TransferInvoiceItem(
matching_id=None, source_code=source_code, invoice_no=invoice_no,
matching_id=matching.id if matching is not None else None,
source_code=source_code, invoice_no=invoice_no,
material_no="MAT-1", material_name="n", specification="",
receipt_date="2026-09-20", status="blocked_recoverable",
movement_date="2026-09-20", status="blocked_recoverable",
result_code="blocked_quantity_mismatch", result_message="strict quantity mismatch",
from_warehouse="W-FROM", to_warehouse="W-TO", receipt_quantity="36",
external_quantity="30", lot_no=lot_no, receipt_warehouse_code="W1",
from_warehouse="W-FROM", to_warehouse="W-TO", movement_quantity="36",
external_quantity="30", lot_no=lot_no, movement_warehouse_code="W1",
unit="PCS", raw_lines_json=[],
)
db.session.add(row)
@@ -64,8 +68,8 @@ def test_requery_same_org_hits_single_external_call(app):
# [断言意图] 同组织两行重查 = 1 次 query_stock,两行目标元组一次下传;
# 回退逐行单查(2 次调用)即回归。
matching = _seed(["DBS-AWSBI", "DBS-AWSSG"], "MTG-BATCH-1")
row1 = _seed_row("DBS-AWSBI", "HOX-1", "LOT-1")
row2 = _seed_row("DBS-AWSSG", "HOX-2", "LOT-2")
row1 = _seed_row("DBS-AWSBI", "HOX-1", "LOT-1", matching=matching)
row2 = _seed_row("DBS-AWSSG", "HOX-2", "LOT-2", matching=matching)
deps, erp, _ = make_transfer_deps() # 默认路由:两来源同组织 HX-CN01
erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "36")
erp.seed_stock("MAT-1", "AWSSG-TRANSIT", "LOT-2", "36")
@@ -87,8 +91,8 @@ def test_requery_same_org_hits_single_external_call(app):
def test_requery_multi_org_one_call_per_org(app):
# [断言意图] 跨组织行按组织分组各查一次:2 组织 = 2 次调用,各自只带本组目标。
matching = _seed(["DBS-AWSBI", "DBS-AWSSG"], "MTG-BATCH-2")
_seed_row("DBS-AWSBI", "HOX-3", "LOT-3")
_seed_row("DBS-AWSSG", "HOX-4", "LOT-4")
_seed_row("DBS-AWSBI", "HOX-3", "LOT-3", matching=matching)
_seed_row("DBS-AWSSG", "HOX-4", "LOT-4", matching=matching)
deps, erp, _ = make_transfer_deps(routes={
"DBS-AWSBI": RouteMapping(external_org="HX-CN01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01"),
"DBS-AWSSG": RouteMapping(external_org="HX-SG01", from_warehouse="AWSSG-TRANSIT", to_warehouse="HUB-SG"),
@@ -107,8 +111,8 @@ def test_requery_route_failure_isolates_row(app):
# [断言意图] 单行路由解析失败只跳过该行(ok=False、行未被触碰、未建 Attempt),
# 同批其他行照常批量重查。
matching = _seed(["DBS-AWSBI", "GHOST-SRC"], "MTG-BATCH-3")
good = _seed_row("DBS-AWSBI", "HOX-5", "LOT-5")
bad = _seed_row("GHOST-SRC", "HOX-6", "LOT-6")
good = _seed_row("DBS-AWSBI", "HOX-5", "LOT-5", matching=matching)
bad = _seed_row("GHOST-SRC", "HOX-6", "LOT-6", matching=matching)
deps, erp, _ = make_transfer_deps() # GHOST-SRC 未配置路由 → RouteNotResolvedError
erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-5", "36")
@@ -128,7 +132,7 @@ def test_requery_stamps_inventory_checked_at(app):
# [断言意图] 重查是真实取数:成功落 ready 的行同步刷新库存查得时刻
# (stale 判定时钟),旧时刻被覆盖。
matching = _seed(["DBS-AWSBI"], "MTG-BATCH-STALE")
row = _seed_row("DBS-AWSBI", "HOX-STALE", "LOT-1")
row = _seed_row("DBS-AWSBI", "HOX-STALE", "LOT-1", matching=matching)
row.inventory_checked_at = datetime(2026, 9, 1, 8, 0, 0)
db.session.commit()
@@ -1,12 +1,13 @@
"""重查圈行口径回归:视图(scope 圈行)能看到的行,重查必须够得着。
"""重查对档对账回归(出生翻转后语义,规格 §9)。
用途:锁死 2026-09-24 上午「点重查毫无反应」缺陷——requery_items 曾按
matching_id 圈行,而行归属解耦后行停在首次创建的匹配上(不迁移),
今天匹配卡(新 matching)重查恒命中 0 行。
依赖:app fixture、repo_fakes.make_transfer_deps、models。
逻辑:造两份同 scope 匹配;行归属旧匹配;经新匹配号重查必须命中该行;
file_removed 行即使可恢复状态也不可重查——匹配号圈行路径由 scope 谓词排除,
按 id 直取与单行重查路径由 retry_item 的 result_code 兜底拒绝(单点闭环)。
用途:锁定 requery_items 的对档 reconciliation——按匹配快照规则对档重圈:
档新增记录 → 补建 item(绑同一匹配);档证据变 → 刷新 item 证据并重置
待查;档记录消失 → item 失效隔离(blocked_file_removed 语义);
D17 占用互斥:其他匹配的有效占用不补建(本匹配自有 items 不构成占用);
file_removed 失效行不可重查(按 id 直取与单行入口由 retry_item 兜底拒绝)。
依赖:app fixture、repo_fakes.make_transfer_deps、factories、models。
逻辑:直接 ORM 种子档记录 + 匹配(scope_json 带新键快照);断言行级状态与
占用互斥;scope_item_query 退役断言在 test_matching_inplace(模块级)。
"""
from __future__ import annotations
@@ -17,28 +18,63 @@ import pytest
from app import db
from app.core.errors import ValidationError
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
from app.models import (
TransferInvoiceItem,
TransferMatching,
TransferMovementLedger,
TransferRun,
)
from app.services.in_transit_transfer.retry_service import (
requery_items,
requery_items_by_ids,
retry_item,
)
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
pytestmark = [pytest.mark.usefixtures("app")]
NOW = datetime(2026, 10, 14, 12, 0, 0)
def _seed(scope_sources, business_date, matching_no):
def _seed_ledger(doc_no: str, *, quantity: str = "100", lot_no: str = "LOT-1",
sha: str = "a" * 64, row_no: int = 1) -> TransferMovementLedger:
"""种子一条入站档记录(DBS-AWSBI / inbound / 2026-10-13)。"""
row = TransferMovementLedger(
source_code="DBS-AWSBI", record_kind="inbound",
doc_no=doc_no, line_no=str(row_no), line_seq="", in_out_flag="",
material_code="MAT-1", material_name="物料1", specification="",
lot_no=lot_no, quantity=quantity, unit="PCS",
warehouse_code="", storage_code="", movement_date="2026-10-13",
source_file_id=None, file_version="v1", file_sha256=sha,
sheet_name="Receipt", row_no=row_no, updated_at=NOW,
)
db.session.add(row)
db.session.flush()
return row
def _seed_matching(matching_no: str) -> TransferMatching:
"""种子一份匹配(scope_json 携带出生翻转新键快照 + 自有 run)。"""
seed_transfer_type_config()
run = TransferRun(run_no=f"RUN-{matching_no}", trigger_type="manual",
business_date=business_date, status="matching",
source_codes_json=scope_sources, counts_json={}, transfer_type="in_transit_to_hub")
business_date="2026-10-14", status="matching",
source_codes_json=["DBS-AWSBI"], counts_json={},
transfer_type="in_transit_to_hub")
db.session.add(run)
db.session.flush()
matching = TransferMatching(
matching_no=matching_no, run_id=run.id, business_date=business_date,
matching_no=matching_no, run_id=run.id, business_date="2026-10-14",
status="success",
scope_json={"source_codes": scope_sources, "receipt_date_from": None,
"receipt_date_to": None, "transfer_type": "in_transit_to_hub"},
scope_json={
"transfer_type": "in_transit_to_hub",
"source_codes": ["DBS-AWSBI"],
"movement_date_from": None,
"movement_date_to": None,
"scope_rules": [{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]}],
"scope_note": "doc_no prefix HOM|HOX|WTP",
"transform_rules": [],
},
file_snapshot_json={}, mapping_version="v0", strategy_version="v0",
counts_json={}, estimated_transfer_quantity="0",
estimated_external_write_count=0, matching_hash="sha256:x",
@@ -46,101 +82,228 @@ def _seed(scope_sources, business_date, matching_no):
)
db.session.add(matching)
db.session.flush()
return run, matching
return matching
def _seed_row(matching, invoice_no):
def _seed_own_item(matching: TransferMatching, ledger: TransferMovementLedger) -> TransferInvoiceItem:
"""种子匹配自有 item(blocked 可重查态,业务字段=档原值)。"""
row = TransferInvoiceItem(
matching_id=matching.id, source_code="CRANE-SZ", invoice_no=invoice_no,
material_no="MAT-1", material_name="n", specification="",
receipt_date="2026-09-20", status="blocked_recoverable",
matching_id=matching.id, run_id=matching.run_id, ledger_record_id=ledger.id,
source_code="DBS-AWSBI", invoice_no=ledger.doc_no,
material_no="MAT-1", material_name="物料1", specification="",
movement_date="2026-10-13", status="blocked_recoverable",
result_code="blocked_quantity_mismatch", result_message="strict quantity mismatch",
from_warehouse="HTP-D43", to_warehouse="HTP-D49", receipt_quantity="36",
external_quantity="30", lot_no=invoice_no, receipt_warehouse_code="W1",
unit="PCS", raw_lines_json=[],
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01", movement_quantity=ledger.quantity,
external_quantity="30", lot_no=ledger.lot_no, movement_warehouse_code="",
unit="PCS", raw_lines_json=[{"sheet": "Receipt", "row_no": ledger.row_no,
"file_version": "v1", "file_sha256": ledger.file_sha256}],
)
db.session.add(row)
db.session.flush()
return row
def test_requery_hits_row_created_under_other_matching(app):
# [断言意图] 行归属匹配 A,经匹配 B(同 scope)发起重查必须命中——scope 口径。
_, matching_a = _seed(["CRANE-SZ"], "2026-09-24", "MTG-A")
row = _seed_row(matching_a, "HOX-1")
_, matching_b = _seed(["CRANE-SZ"], "2026-09-24", "MTG-B")
def test_requery_births_item_for_new_ledger_record(app):
# [断言意图] 档新增记录 → 重查补建 item(绑同一匹配、待查态、数量=档原值)。
matching = _seed_matching("MTG-A")
existing = _seed_ledger("HOM-1")
_seed_own_item(matching, existing)
new_record = _seed_ledger("HOM-2", quantity="50", row_no=2)
deps, _, _ = make_transfer_deps()
outcome = requery_items(matching_no=matching_b.matching_no, deps=deps,
invoice_nos=["HOX-1"], actor_id="1")
requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1")
assert outcome["total"] == 1 # [断言意图] scope 圈行命中旧匹配的行
assert outcome["results"][0]["ok"] is True
assert outcome["results"][0]["item_id"] == row.id
born = TransferInvoiceItem.query.filter_by(invoice_no="HOM-2").one()
# [断言意图] 补建行创建即绑定本匹配:matching_id/run_id/ledger_record_id 齐备。
assert born.matching_id == matching.id
assert born.run_id is None # 执行 Run 关联归 orchestrator
assert born.ledger_record_id == new_record.id
assert born.movement_quantity == "50"
assert born.status == "matching" and born.result_code == "pending_stock_check" # 待查态
def test_requery_aligns_stale_source_first(app, monkeypatch):
# [断言意图] 行 sha 落后于最新文件时,重查第一步先对齐(兜底语义)。
called = {}
from app.services.in_transit_transfer import evidence_sync
def test_requery_refreshes_item_when_ledger_evidence_changed(app):
# [断言意图] 档证据变(数量)→ item 证据刷新并重置待查(旧库存作废、
# external_quantity/inventory_checked_at 置空);展示字段照常刷新。
matching = _seed_matching("MTG-B")
record = _seed_ledger("HOM-1", quantity="100")
item = _seed_own_item(matching, record)
item.inventory_checked_at = datetime(2026, 10, 14, 10, 0, 0)
db.session.flush()
def _fake_align(**kwargs):
called["sources"] = kwargs.get("source_codes")
return {code: None for code in kwargs.get("source_codes") or []}
monkeypatch.setattr(evidence_sync, "align_scope_rows", _fake_align)
monkeypatch.setattr(
"app.services.in_transit_transfer.retry_service.align_scope_rows", _fake_align)
_, matching = _seed(["CRANE"], "2026-09-25", "MTG-D")
deps, _, _ = make_transfer_deps()
requery_items(matching_no=matching.matching_no, deps=deps, invoice_nos=None, actor_id="1")
assert called.get("sources") == ["CRANE"] # [断言意图] 兜底对齐被前置调用
def test_requery_skips_file_removed_rows(app):
# [断言意图] file_removed 行不允许重查翻回可执行(消失证据不可恢复)。
_, matching_a = _seed(["CRANE-SZ"], "2026-09-24", "MTG-C")
removed = _seed_row(matching_a, "HOX-RM")
removed.result_code = "blocked_file_removed"
removed.result_message = "receipt row removed from latest file"
record.quantity = "180" # 档证据被新版本替换(原行更新)
record.material_name = "改名物料"
record.file_sha256 = "b" * 64
db.session.flush()
deps, _, _ = make_transfer_deps()
outcome = requery_items(matching_no=matching_a.matching_no, deps=deps,
invoice_nos=["HOX-RM"], actor_id="1")
requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1")
db.session.refresh(item)
assert item.movement_quantity == "180" # [断言意图] 证据刷新
assert item.material_name == "改名物料" # [断言意图] 展示字段随档换新
assert item.status == "matching" and item.result_code == "pending_stock_check" # 重置待查
assert item.external_quantity is None and item.inventory_checked_at is None # 旧库存作废
def test_requery_respects_other_matching_occupancy(app):
# [断言意图] D17 圈档互斥:档记录被「其他匹配」的有效 item 占用时,本匹配
# 重查不补建;本匹配自有 items 不构成占用(刷新路径不受互斥影响)。
matching_a = _seed_matching("MTG-A2")
matching_b = _seed_matching("MTG-B2")
record = _seed_ledger("HOM-1")
_seed_own_item(matching_a, record) # 匹配 A 占用
_seed_ledger("HOM-2", row_no=2) # 无主新记录
deps, _, _ = make_transfer_deps()
requery_items(matching_no=matching_b.matching_no, deps=deps, actor_id="1")
# [断言意图] B 的重查只补建无主记录(HOM-2),不触碰 A 的占用记录(HOM-1
# 在 B 下无行);自有占用路径由 refresh 用例覆盖。
assert TransferInvoiceItem.query.filter_by(invoice_no="HOM-1").count() == 1
born = TransferInvoiceItem.query.filter_by(invoice_no="HOM-2").one()
assert born.matching_id == matching_b.id
def test_requery_skips_file_removed_rows(app):
# [断言意图] 失效隔离行(blocked_file_removed)不允许重查翻回可执行
# (消失证据不可恢复)。
matching = _seed_matching("MTG-C")
record = _seed_ledger("HOM-1")
removed = _seed_own_item(matching, record)
removed.result_code = "blocked_file_removed"
removed.result_message = "inbound row removed from latest file"
db.session.flush()
deps, _, _ = make_transfer_deps()
outcome = requery_items(matching_no=matching.matching_no, deps=deps,
invoice_nos=["HOM-1"], actor_id="1")
assert outcome["total"] == 0 # [断言意图] 失效行被圈行排除
def test_requery_aligns_ledger_not_files(app):
# [断言意图] 重查不再对文件兜底对齐(align_scope_rows 已退役):
# 重查入口按档对账,重试模块不再持有对齐入口(属性级断言防回归)。
from app.services.in_transit_transfer import evidence_sync, retry_service
assert not hasattr(evidence_sync, "align_scope_rows")
assert not hasattr(retry_service, "align_scope_rows")
def test_retry_item_rejects_file_removed_row(app):
# [断言意图] 单行重查入口必须拒绝 file_removed 行(消失证据不可恢复,
# [断言意图] 单行重查入口必须拒绝失效隔离行(消失证据不可恢复,
# 重查只会用外部系统旧库存把行翻回可执行)。
_, matching = _seed(["CRANE-SZ"], "2026-09-25", "MTG-E")
row = _seed_row(matching, "HOX-RM2")
matching = _seed_matching("MTG-E")
record = _seed_ledger("HOM-1")
row = _seed_own_item(matching, record)
row.result_code = "blocked_file_removed"
row.result_message = "receipt row removed from latest file"
row.result_message = "inbound row removed from latest file"
db.session.flush()
deps, _, _ = make_transfer_deps()
with pytest.raises(ValidationError) as exc:
retry_item(item_id=row.id, deps=deps, kind="external_recheck")
assert exc.value.code == "TRANSFER.RETRY_NOT_ALLOWED" # [断言意图] 消失行不可重查
assert exc.value.code == "TRANSFER.RETRY_NOT_ALLOWED" # [断言意图] 隔离行不可重查
def test_requery_by_ids_rejects_file_removed_row(app):
# [断言意图] 待处理池按 id 直取的批量重查绕过了 scope 圈行谓词——其循环
# [断言意图] 待处理池按 id 直取的批量重查绕过了对账口径——其循环
# 逐行调 retry_item,单行入口拒绝后此路径必须同步闭环(该行 ok=False)。
_, matching = _seed(["CRANE-SZ"], "2026-09-25", "MTG-F")
row = _seed_row(matching, "HOX-RM3")
matching = _seed_matching("MTG-F")
record = _seed_ledger("HOM-1")
row = _seed_own_item(matching, record)
row.result_code = "blocked_file_removed"
row.result_message = "receipt row removed from latest file"
row.result_message = "inbound row removed from latest file"
db.session.flush()
deps, _, _ = make_transfer_deps()
outcome = requery_items_by_ids(item_ids=[row.id], deps=deps, actor_id="1")
assert outcome["total"] == 1
assert outcome["results"][0]["ok"] is False # [断言意图] 消失行经 by_ids 亦被拒绝
assert outcome["results"][0]["ok"] is False # [断言意图] 隔离行经 by_ids 亦被拒绝
def test_requery_never_touches_terminal_rows(app):
# [断言意图·Critical-1] 部分行已 SUCCESS 的匹配 + 档证据变化 + 重查:
# SUCCESS 行原样(status/result/updated_at/movement_quantity 均不变,防已执行
# 行被重置复活 → 二次写 ERP);非终态行照常刷新重置。
matching = _seed_matching("MTG-T1")
rec1 = _seed_ledger("HOM-1", quantity="100")
rec2 = _seed_ledger("HOM-2", quantity="200", row_no=2)
blocked = _seed_own_item(matching, rec1) # 非终态可重查行
done = _seed_own_item(matching, rec2)
done.status = "success"
done.result_code = None
done.result_message = None
db.session.flush()
frozen = (done.status, done.result_code, done.result_message,
done.updated_at, done.movement_quantity, done.external_quantity)
rec1.quantity = "150" # 档证据变化(两行同批)
rec2.quantity = "999"
db.session.flush()
deps, _, _ = make_transfer_deps()
requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1")
db.session.expire_all()
done = db.session.get(TransferInvoiceItem, done.id)
blocked = db.session.get(TransferInvoiceItem, blocked.id)
# [断言意图] 终态行零写入:含 updated_at 在内全部字段保持原值。
assert (done.status, done.result_code, done.result_message,
done.updated_at, done.movement_quantity, done.external_quantity) == frozen
assert done.status == "success"
# [断言意图] 非终态行正常对账:证据刷新 + 重置待查。
assert blocked.movement_quantity == "150"
assert blocked.status == "matching" and blocked.result_code == "pending_stock_check"
assert blocked.external_quantity is None and blocked.inventory_checked_at is None
def test_requery_does_not_rebirth_record_bound_by_terminal_row(app):
# [断言意图·Critical-1 占用面] 档记录已被本匹配终态行绑定时,重查不得补建
# 第二个 item(否则已执行记录以新待查行复活 → 二次写 ERP)。
matching = _seed_matching("MTG-T2")
record = _seed_ledger("HOM-1")
done = _seed_own_item(matching, record)
done.status = "success"
done.result_code = None
db.session.flush()
deps, _, _ = make_transfer_deps()
requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1")
# [断言意图] 该记录在匹配下恒只有一个绑定行,且仍是原终态行。
rows = TransferInvoiceItem.query.filter_by(invoice_no="HOM-1").all()
assert len(rows) == 1 and rows[0].id == done.id
assert rows[0].status == "success"
def test_requery_tolerates_missing_type_config(app):
# [断言意图·Important-4] 配置表清空后重查:不抛 NOT_CONFIGURED(整次失败),
# 行级降级——既有自有行重查 ok=False(行级错误说明,口径同 _route_for_item),
# 补建行走行级阻断(blocked_route_not_resolved + 配置缺失说明),其余行不受影响。
matching = _seed_matching("MTG-T3")
from app.models import TransferTypeConfig
db.session.query(TransferTypeConfig).delete()
db.session.commit()
record = _seed_ledger("HOM-1")
own = _seed_own_item(matching, record) # 既有可重查行
_seed_ledger("HOM-2", quantity="70", row_no=2) # 待补建的新档记录
deps, _, _ = make_transfer_deps()
outcome = requery_items(matching_no=matching.matching_no, deps=deps, actor_id="1") # 不抛
# [断言意图] 行级结果而非整体异常:既有行与补建行均 ok=False(行级路由前置
# 失败,含配置缺失说明),不影响彼此、更不炸整次重查。
assert outcome["total"] == 2
by_item = {row["item_id"]: row for row in outcome["results"]}
assert by_item[own.id]["ok"] is False
# [断言意图] 补建行走行级阻断:可解释(配置缺失)、可重查(配置修复后恢复)。
born = TransferInvoiceItem.query.filter_by(invoice_no="HOM-2").one()
assert born.matching_id == matching.id
assert born.status == "blocked_recoverable"
assert born.result_code == "blocked_route_not_resolved"
assert "transfer type config missing" in (born.result_message or "")
@@ -1,77 +0,0 @@
"""存量误标行修复脚本回归(L1,SQLite 内存库)。
用途:锁定 restore_file_removed_transfer_rows.restore_rows 的恢复语义——只动
blocked_file_removed 误标行,恢复待查态并作废旧库存;其他行绝不触碰。
依赖:app fixture、dbs_ready_file、evidence_sync(构造前置状态)。
逻辑:importlib 直载脚本模块(backend/scripts 不在包路径内),只测纯函数。
"""
import importlib.util
from datetime import datetime
from pathlib import Path
import pytest
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer.evidence_sync import sync_source_rows
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
NOW = datetime(2026, 9, 28, 10, 0, 0)
def _load_script():
"""按路径加载修复脚本模块(脚本自举 sys.path,不依赖包安装)。"""
path = Path(__file__).parents[3] / "scripts" / "restore_file_removed_transfer_rows.py"
spec = importlib.util.spec_from_file_location("restore_file_removed_transfer_rows", path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.usefixtures("app")
def test_restore_flips_only_file_removed_rows(app, dbs_ready_file):
# [断言意图] 只有 blocked_file_removed 行被恢复为待查态;正常行分毫不动。
script = _load_script()
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
good = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOM-001").first()
doomed = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOX-002").first()
doomed.status = "blocked_recoverable"
doomed.result_code = "blocked_file_removed"
doomed.result_message = "receipt row removed from latest file"
db.session.flush()
result = script.restore_rows(source_code="DBS-AWSBI", now=NOW)
assert result == {"restored": 1} # [断言意图] 只命中误标行
db.session.refresh(doomed)
assert doomed.status == "matching" # [断言意图] 恢复待查态
assert doomed.result_code == "pending_stock_check"
assert doomed.result_message is None # [断言意图] 删除解释清除
assert doomed.external_quantity is None # [断言意图] 旧库存作废待重查
db.session.refresh(good)
assert good.result_code == "pending_stock_check" # [断言意图] 正常行不触碰
@pytest.mark.usefixtures("app")
def test_restore_is_idempotent(app, dbs_ready_file):
# [断言意图] 修复后再跑一遍 restored=0(无新命中),行状态不再变化。
script = _load_script()
deps, _, _ = make_transfer_deps(dbs_ready_file)
sync_source_rows(source_code="DBS-AWSBI", deps=deps,
business_date="2026-08-06", now=NOW)
row = TransferInvoiceItem.query.filter_by(
source_code="DBS-AWSBI", invoice_no="HOX-002").first()
row.status = "blocked_recoverable"
row.result_code = "blocked_file_removed"
db.session.flush()
script.restore_rows(source_code="DBS-AWSBI", now=NOW)
second = script.restore_rows(source_code="DBS-AWSBI", now=NOW)
assert second == {"restored": 0} # [断言意图] 幂等:无新命中
@@ -1,86 +1,112 @@
"""匹配卡 scope 实时视图测试(restore 按 scope 查行 + 行装饰字段,L1)。
"""匹配卡自有 items 视图测试(restore + 行装饰字段,L1)。
用途:验证 restore_matching 不再读 matching.items 行归属,而按匹配 scope
(scope_item_query)实时圈定行集,并逐行装饰 item_id / checked_at /
stale / file_current;counts 为 scope 行实时聚合(不读 counts_json 快照)。
用途:锁定出生翻转后的 restore_matching——匹配卡=自有 items 视图(创建即绑定,
matching_id 圈行;scope_item_query 实时圈行已退役),逐行装饰 item_id /
checked_at / stale / file_current;counts 为自有行实时聚合(不读 counts_json
快照);展示不查配置表(规格 §13.1,快照自足)。
依赖:transfer_db、matching_service、repo_fakes。
逻辑:经 create_matching 真实落库构造行状态;行归属(matching_id)保持首次
创建值(原地刷新语义),重复匹配的 restore 仍能看到同一批活跃行;
收料文件状态投影按同款 monkeypatch 替身注入。
逻辑:经 create_matching 真实落库构造行状态;收料文件状态投影按 monkeypatch
替身注入;stale 时钟=inventory_checked_at(库存查得时刻,2026-09-29 换源)。
"""
from __future__ import annotations
from datetime import datetime, timedelta
import pytest
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import matching_service
from app.services.in_transit_transfer.matching_service import create_matching, restore_matching
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
pytestmark = [pytest.mark.usefixtures("transfer_db")]
def _file_ready(monkeypatch, dbs_ready_file: dict) -> None:
"""让来源文件状态投影返回 ready(sha 与 fixture 文件一致,不触碰真实文件表)。"""
monkeypatch.setattr(
matching_service, "resolve_source_file_status",
lambda *, source_code: {"file_status": "ready", "has_ready_file": True,
lambda *, source_code, record_kind="inbound": {"file_status": "ready", "has_ready_file": True,
"file_no": dbs_ready_file["file_no"],
"file_sha256": dbs_ready_file["checksum"]},
)
def test_restore_returns_scope_rows_not_owned_rows(transfer_db, dbs_ready_file, monkeypatch):
"""restore 按范围返回实时行:行属于首份匹配,但第二份匹配的 restore 也能看到(实时状态)。"""
def test_restore_returns_own_items(transfer_db, dbs_ready_file, monkeypatch):
"""restore 返回匹配自有行(创建即绑定):行装饰三要素齐备,counts 实时聚合。"""
_file_ready(monkeypatch, dbs_ready_file)
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps) # 行经证据同步落地
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
detail = restore_matching(second.matching_id, deps=deps)
detail = restore_matching(summary.matching_id, deps=deps)
assert {i.invoice_no for i in detail["items"]} == {"HOM-001", "HOX-002"}
row = next(i for i in detail["items"] if i.invoice_no == "HOX-002")
# [断言意图] 行装饰三要素:行 id 可追溯(item_id)、刚刷新不陈旧(stale)、
# [断言意图] 行装饰三要素:行 id 可追溯(item_id)、刚取数不陈旧(stale)、
# 行评估版本戳仍是该来源当前可用文件(file_current)。
assert row.item_id > 0 and row.stale is False and row.file_current is True
# [断言意图] counts 为 scope 行实时聚合(不读 counts_json 快照):
# 2 行 = 1 可执行 + 1 阻断;summary 其余字段沿用匹配记录留痕。
# [断言意图] counts 为自有行实时聚合(不读 counts_json 快照):
# 2 行 = 1 可执行 + 1 阻断。
counts = detail["summary"].counts
assert counts.file_invoice_count == 2
assert counts.executable_count == 1
assert counts.blocked_count == 1
assert counts.matched_count == 2
assert detail["summary"].matching_hash == second.matching_hash
assert detail["summary"].matching_hash == summary.matching_hash
assert detail["summary"].expires_at
def test_second_matching_restores_empty_own_view(transfer_db, dbs_ready_file, monkeypatch):
"""圈档互斥(D17)视图面:第二匹配无自有行,restore 呈现空明细而非他匹配的行。"""
_file_ready(monkeypatch, dbs_ready_file)
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
detail = restore_matching(second.matching_id, deps=deps)
# [断言意图] 出生翻转后行归属唯一:第二匹配未被圈定任何记录,restore 只见
# 自有行(空)——跨匹配共享视图会掩盖「圈档互斥」事实。
assert detail["items"] == []
assert detail["summary"].counts.file_invoice_count == 0
def test_restore_marks_stale_beyond_ttl(transfer_db, dbs_ready_file, monkeypatch):
"""行 updated_at 早于 TTL → stale=True(TTL 取 deps.strategy.confirm_ttl_seconds)。"""
"""行库存取数时刻早于展示阈值 → stale=True(stale 时钟=inventory_checked_at)。"""
_file_ready(monkeypatch, dbs_ready_file)
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
# 手工把 HOX-002 行的评估时间拨回 11 分钟前(TTL 默认 600 秒 = 10 分钟)。
stale_at = datetime.utcnow() - timedelta(minutes=11)
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
# 手工把 HOX-002 行的库存查得时刻拨回阈值之外(stale 时钟=inventory_checked_at,
# 展示阈值=strategy.inventory_stale_ttl_seconds,TestingConfig 钉 24h)。
stale_at = datetime.utcnow() - timedelta(hours=25)
hox = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
hox.updated_at = stale_at
hox.inventory_checked_at = stale_at
db.session.commit()
detail = restore_matching(summary.matching_id, deps=deps)
row = next(i for i in detail["items"] if i.invoice_no == "HOX-002")
fresh = next(i for i in detail["items"] if i.invoice_no == "HOM-001")
# [断言意图] 超过确认 TTL 未刷新的行必须标记 stale(提示用户重查后再执行),
# 未拨回的行保持新鲜;checked_at 携带行评估时间(updated_at isoformat)。
# [断言意图] 超过展示阈值未取数的行必须标记 stale(提示用户重查后再执行),
# 未拨回的行保持新鲜;checked_at 携带库存查得时刻(inventory_checked_at isoformat)。
assert row.stale is True
assert fresh.stale is False
assert row.checked_at == hox.updated_at.isoformat()
assert row.checked_at == stale_at.isoformat()
assert row.file_current is True
@@ -88,14 +114,15 @@ def test_restore_marks_file_current_false_without_ready_file(transfer_db, dbs_re
"""来源当前无可用文件 → 行 file_current=False(fail-safe,不得当作新鲜)。"""
monkeypatch.setattr(
matching_service, "resolve_source_file_status",
lambda *, source_code: {"file_status": "none", "has_ready_file": False,
lambda *, source_code, record_kind="inbound": {"file_status": "none", "has_ready_file": False,
"file_no": None, "file_sha256": None},
)
deps, erp, _ = make_transfer_deps(dbs_ready_file)
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
transfer_type="in_transit_to_hub")
detail = restore_matching(summary.matching_id, deps=deps)
@@ -25,7 +25,7 @@ def _mismatch_matching(dbs_ready_file):
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
return deps, erp, summary
@@ -197,35 +197,36 @@ def test_requery_items_invoice_filter_targets_only_given_rows(transfer_db, dbs_r
assert _item_by_invoice("HOM-001").status == "blocked_recoverable"
def test_requery_reaches_rows_created_by_older_matching(transfer_db, dbs_ready_file):
"""[回归防线 2026-09-24] 重查按 scope 圈行,行归属 matching_id 不参与。
def test_requery_reaches_only_own_matching_rows(transfer_db, dbs_ready_file):
"""[出生翻转语义] 重查只触达本匹配自有 items(创建即绑定,D17/规格 §9)。
行归属解耦后,重查只按 scope 圈行。2026-09-25 起行由证据同步落地,
matching_id 恒为 None(匹配完全不拥有行)——旧实现按 matching_id 圈行,
会导致「卡片提示重查、重查命中 0 行」的死锁(生产实测 55 行全中)。本用例
锁定:第二次同 scope 匹配后,经新匹配号重查必须触达这批无归属行。
[语义平移] 旧「scope 圈行跨匹配触达」随出生翻转退役:行由匹配创建时从档
圈定且创建即绑定,重查按 matching_id 圈自有行;其他匹配的占用行不越权
(第二份同 scope 匹配为空壳——圈档互斥,见 test_matching_service)。
"""
deps, erp, first = _mismatch_matching(dbs_ready_file)
row = _item_by_invoice("HOM-001")
# [断言意图] 落地行无匹配归属(matching_id=None):重查只能靠 scope 圈行。
assert row.matching_id is None
from app.models import TransferMatching
# 第二次同 scope 匹配:行原地刷新、归属保持为空(匹配不拥有行)。
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
assert second.matching_id != first.matching_id
db.session.expire_all()
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
row = _item_by_invoice("HOM-001")
second_matching_id = (
db.session.query(TransferMatching).filter_by(matching_no=second.matching_id).one().id
)
assert row.matching_id != second_matching_id
# [断言意图] 创建即绑定:行归属首匹配(旧「落地行 matching_id=None」已退役)。
assert row.matching_id == first_matching.id
# 第二次同 scope 匹配:圈档互斥 → 空壳(无自有行)。
second = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
assert second.matching_id != first.matching_id
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
assert row.matching_id != second_matching.id
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # ERP 侧已修正库存
result = requery_items(matching_no=second.matching_id, deps=deps)
# [断言意图] 新匹配号的重查必须触达 matching_id 指向旧匹配的行——
# 视图(scope)能看到什么,重查就作用于什么(读与操作同一圈行谓词)。
assert result["total"] == 2
rows = {r["invoice_no"]: r for r in result["results"]}
result_second = requery_items(matching_no=second.matching_id, deps=deps)
# [断言意图] 第二匹配无自有行:重查命中 0(不越权触达他匹配占用行)。
assert result_second["total"] == 0
result_first = requery_items(matching_no=first.matching_id, deps=deps)
# [断言意图] 首匹配自有行可重查:ERP 库存修正后 blocked 行翻回可执行。
assert result_first["total"] == 2
rows = {r["invoice_no"]: r for r in result_first["results"]}
assert rows["HOM-001"]["ok"] is True
assert rows["HOM-001"]["status"] == "ready_to_execute"
@@ -270,7 +271,7 @@ def _wtp_lot_matching(transfer_db):
file_dict = {
"source_code": "DBS-AWSBI",
"business_date": "2026-08-06",
"file_purpose": "receipt",
"file_purpose": "inbound",
"file_no": "REC-20260806-900",
"file_version": "v9",
"checksum": "e" * 64,
@@ -284,7 +285,7 @@ def _wtp_lot_matching(transfer_db):
}
deps, erp, _ = make_transfer_deps(file_dict)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-07", deps=deps, transfer_type="in_transit_to_hub")
return deps, erp
@@ -4,7 +4,7 @@
拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码;
inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配,
匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。
依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。
依赖:app fixture 种子站点、FreightRpaOnhandExternalMapping、DefaultRouteResolver。
逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。
"""
@@ -13,18 +13,18 @@ from __future__ import annotations
import pytest
from app.extensions import db
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.models import FreightRpaOnhandExternalMapping, FreightRpaSource
from app.services.in_transit_transfer.deps import DefaultRouteResolver
from app.services.in_transit_transfer.matching_service import RouteNotResolvedError
def _seed_mapping(
source: ShippingInventorySource, *, freight_warehouse_id: str | None,
source: FreightRpaSource, *, freight_warehouse_id: str | None,
in_transit_warehouse_code: str = 'TZT-01',
) -> ShippingInventoryExternalMapping:
) -> FreightRpaOnhandExternalMapping:
"""在既有种子来源上挂一条启用映射。"""
mapping = ShippingInventoryExternalMapping(
inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id,
mapping = FreightRpaOnhandExternalMapping(
source_id=source.id, freight_warehouse_id=freight_warehouse_id,
external_system_code='TOPGP', external_organization_code='TGHX',
external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓',
in_transit_warehouse_code=in_transit_warehouse_code, enabled=True,
@@ -34,12 +34,13 @@ def _seed_mapping(
return mapping
def _seed_inventory_match_source() -> ShippingInventorySource:
def _seed_inventory_match_source() -> FreightRpaSource:
"""以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。"""
template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = ShippingInventorySource(
template = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
# s18 起站点行不再承载 parsing_profile_id;路由解析只读外部映射,无需在手配置行。
source = FreightRpaSource(
source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane',
rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id,
rpa_profile_id=template.rpa_profile_id,
excel_template_id=template.excel_template_id,
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True,
)
@@ -51,7 +52,7 @@ def _seed_inventory_match_source() -> ShippingInventorySource:
def test_fixed_source_uses_single_mapping_in_transit_code(app):
"""fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。"""
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
# 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。
_seed_mapping(source, freight_warehouse_id='TZR2')
@@ -63,7 +64,7 @@ def test_fixed_source_uses_single_mapping_in_transit_code(app):
assert route.external_org == 'TGHX'
def test_inventory_match_prefers_receipt_warehouse_exact_mapping(app):
def test_inventory_match_prefers_inbound_warehouse_exact_mapping(app):
"""inventory_match 源:收料仓库与某行货代仓库精确匹配 → 取该行在途仓编码。"""
with app.app_context():
source = _seed_inventory_match_source()
@@ -118,7 +119,7 @@ def test_inventory_match_fails_closed_without_any_match(app):
def test_route_resolver_fails_closed_without_in_transit_code(app):
"""映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。"""
with app.app_context():
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='')
with pytest.raises(RouteNotResolvedError):
@@ -0,0 +1,51 @@
"""
tests/services/in_transit_transfer/test_rpa_sinks_ownership.py
用途:锁定入站/出站 sink 组合根归属——住在 in_transit_transfer,不在 shipping_notice;
inbound-batch-ready 直挂 freight_rpa 归档入口(无 shipping_notice Middle Man)。
"""
from __future__ import annotations
import importlib
import pytest
def test_shipping_notice_rpa_sinks_only_exposes_onhand_registration():
"""发货包只保留 onhand 注册入口,不再导出 inbound/outbound 注册。"""
sinks = importlib.import_module('app.services.shipping_notice.rpa_sinks')
assert hasattr(sinks, 'register_onhand_sinks')
assert not hasattr(sinks, 'register_inbound_sinks')
assert not hasattr(sinks, 'register_outbound_sinks')
def test_shipping_notice_inbound_report_storage_module_removed():
"""入站 Middle Man 模块已删除,生产与测试均直连 freight_rpa / 调拨处理函数。"""
with pytest.raises(ModuleNotFoundError):
importlib.import_module('app.services.shipping_notice.inbound_report_storage')
def test_register_inbound_sinks_binds_archive_and_transfer_handler(app):
"""register_inbound_sinks 把归档入口与调拨 handler 接到 inbound kinds。"""
from app.services.freight_rpa.common import callback_sinks
from app.services.freight_rpa.reports import dispatch as dispatch_module
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
from app.services.in_transit_transfer.rpa_sinks import register_inbound_sinks
dispatch_module._REPORT_HANDLERS.pop('inbound', None)
callback_sinks._SINKS.pop('inbound-batch-ready', None)
register_inbound_sinks()
assert dispatch_module._REPORT_HANDLERS.get('inbound') is handle_inbound_report
assert 'inbound-batch-ready' in callback_sinks._SINKS
def test_register_outbound_sinks_binds_outbound_handler(app):
"""register_outbound_sinks 把 handle_outbound_report 接到 outbound kind。"""
from app.services.freight_rpa.reports import dispatch as dispatch_module
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
from app.services.in_transit_transfer.rpa_sinks import register_outbound_sinks
dispatch_module._REPORT_HANDLERS.pop('outbound', None)
register_outbound_sinks()
assert dispatch_module._REPORT_HANDLERS.get('outbound') is handle_outbound_report
@@ -3,14 +3,20 @@
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
依赖:schedule.job_registry、receipt_trigger_service、in_transit_transfer_job。
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
依赖:schedule.job_registry、job_options、inbound_trigger_service、
transfer_type_config_service、in_transit_transfer_job。
逻辑:只验证注册契约与调用形态(run_auto_transfer/run_daily_recovery 打桩),
真实排程触发由 scheduler 驱动;七元组位序=(total, success, failed,
skipped, results, errors, step_logs),errors 位只放真实错误。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome
from app.services.schedule.job_options import is_known_options_source
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
@@ -22,14 +28,23 @@ def test_receipt_file_job_deregistered():
def test_transfer_job_registered_with_schedule_defaults():
"""自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。"""
"""自动调拨 job 注册且含类型/来源/恢复参数契约;描述不得硬编码时刻。"""
import re
job = get_platform_job("in-transit-transfer")
assert job is not None
assert job.enabled
keys = {field.get("key") for field in job.params_schema}
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
assert {
"transfer_types", "source_codes", "recover_history",
"receipt_from_offset_days", "receipt_to_offset_days",
} <= keys
# 断言:调拨类型=multi_select 动态选项源(启用中的类型配置),留空=全部。
types_field = next(f for f in job.params_schema if f.get("key") == "transfer_types")
assert types_field.get("type") == "multi_select"
assert types_field.get("options_source") == "transfer_types"
assert types_field.get("default") == []
assert is_known_options_source("transfer_types")
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
assert "notify_user_ids" not in keys
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
@@ -46,12 +61,12 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
"""创建可参与收料的最小库存源(rpa_profile_id 非空,须先建 Profile)。"""
from app.models import (
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingRpaProfile,
FreightRpaParsingProfile,
FreightRpaSource,
FreightRpaProfile,
)
profile = ShippingRpaProfile(
profile = FreightRpaProfile(
profile_code=f"RPA_{source_code}", display_name=source_code, connector_type="crane",
login_url="https://test.invalid/login", login_config_json={"auth_mode": "password"},
)
@@ -62,7 +77,7 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
"rpa_profile_id": profile.id, "enabled": enabled,
}
if enabled:
parsing = ShippingInventoryParsingProfile(
parsing = FreightRpaParsingProfile(
profile_code=f"PARSE_{source_code}", display_name=source_code, version=1,
status="published", file_format="xlsx",
definition_json={"field_mapping": {}, "match_keys": []},
@@ -79,31 +94,39 @@ def _make_receipt_source(db, source_code: str, *, enabled: bool):
db.session.add_all([parsing, template])
db.session.flush()
source_kwargs.update(
parsing_profile_id=parsing.id, excel_template_id=template.id,
excel_template_id=template.id,
warehouse_resolution_mode="fixed", fixed_warehouse_id="WH1",
)
else:
source_kwargs.update(warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None)
source = ShippingInventorySource(**source_kwargs)
source = FreightRpaSource(**source_kwargs)
db.session.add(source)
if enabled:
# s18 起解析方案绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行;
# 经关系级联随站点一并入库。
from app.models import FreightRpaOnhandReportConfig
FreightRpaOnhandReportConfig(
source=source, parsing_profile=parsing,
report_path_json={}, query_parameters_json=[],
)
return source
def test_list_receipt_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
def test_list_inbound_capable_source_codes_filters_by_enabled_and_config(app, transfer_db):
"""缺省来源口径:enabled 库存源且已配置收料报表才入选;停用/无配置排除。"""
from app.models import ShippingReceiptReportConfig
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
from app.models import FreightRpaInboundReportConfig
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
enabled = _make_receipt_source(transfer_db, "CRANE_SGP", enabled=True)
_make_receipt_source(transfer_db, "DBS_OFF", enabled=False)
_make_receipt_source(transfer_db, "CRANE_NOCONF", enabled=True)
transfer_db.session.flush()
transfer_db.session.add(ShippingReceiptReportConfig(
inventory_source_id=enabled.id, report_path_json={}, query_parameters_json=[],
transfer_db.session.add(FreightRpaInboundReportConfig(
source_id=enabled.id, report_path_json={}, query_parameters_json=[],
))
transfer_db.session.commit()
result = list_receipt_capable_source_codes()
result = list_inbound_capable_source_codes()
assert "CRANE_SGP" in result
assert "DBS_OFF" not in result
assert "CRANE_NOCONF" not in result
@@ -116,7 +139,7 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
from app.models import ScheduleTask
from app.services.schedule.in_transit_transfer_job import _wanted_source_codes
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP", "DBS_HUB"])
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP", "DBS_HUB"])
empty = ScheduleTask(job_params={"source_codes": []})
assert _wanted_source_codes(empty) == ["CRANE_SGP", "DBS_HUB"]
explicit = ScheduleTask(job_params={"source_codes": ["DBS_HUB"]})
@@ -125,55 +148,108 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
def test_handler_empty_data_day_stays_silent(monkeypatch):
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
def test_wanted_transfer_types_falls_back_to_all_enabled(monkeypatch):
"""调拨类型留空=全部启用类型;显式选择优先;空配置/脏配置 fail-closed 落错误。"""
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
from app.services.schedule.in_transit_transfer_job import _wanted_transfer_types
errors: list[str] = []
monkeypatch.setattr(type_mod, "get_enabled", lambda: [
SimpleNamespace(code="in_transit_to_hub"), SimpleNamespace(code="hub_repair_out"),
])
assert _wanted_transfer_types({}, errors) == ["in_transit_to_hub", "hub_repair_out"]
assert errors == []
assert _wanted_transfer_types({"transfer_types": ["in_transit_to_hub"]}, errors) == ["in_transit_to_hub"]
assert _wanted_transfer_types({"transfer_types": "hub_to_hub"}, errors) == ["hub_to_hub"]
monkeypatch.setattr(type_mod, "get_enabled", lambda: [])
assert _wanted_transfer_types({}, errors) == []
# 断言:空类型配置不静默——落错误由调用方硬失败(D8 fail-closed)。
assert errors and "调拨类型" in errors[-1]
def test_transfer_types_options_provider_lists_enabled(app, transfer_db):
"""transfer_types 选项源:仅启用类型,label 取 names zh-CN,value=类型编码。"""
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
from app.services.schedule.job_options import list_job_options
seed_transfer_type_config("in_transit_to_hub", enabled=True)
seed_transfer_type_config("hub_repair_out", enabled=False)
transfer_db.session.commit()
options = list_job_options("transfer_types")
codes = {option["value"] for option in options}
# 断言:停用类型不进选项(与排程留空=全部启用类型的口径一致)。
assert "in_transit_to_hub" in codes
assert "hub_repair_out" not in codes
label = next(o["label"] for o in options if o["value"] == "in_transit_to_hub")
assert label == "类型 in_transit_to_hub"
def _patch_schedule_env(monkeypatch, *, types=None, sources=("CRANE_SGP",)):
"""handler 单测公共打桩:来源/类型缺省口径 + 依赖与恢复隔离(不触库)。"""
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
import app.services.schedule.in_transit_transfer_job as job_mod
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: list(sources))
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
monkeypatch.setattr(
type_mod, "get_enabled",
lambda: [SimpleNamespace(code=code) for code in (types if types is not None else ["in_transit_to_hub"])],
)
return job_mod
def test_handler_empty_data_day_stays_silent(monkeypatch):
"""空数据日(全部类型均无 run 且无 errors):置静默标记抑制框架完成卡(C5)。"""
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
captured = {}
def _fake_auto_transfer(**kwargs):
captured.update(kwargs)
return job_mod.AutoTransferOutcome()
return AutoTransferOutcome()
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
run = ScheduleRun(run_no="RUNR-1", status="running")
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
total, success, failed, skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
assert "sender" not in captured
assert "recipients" not in captured
assert captured["receipt_date_from"] is None
assert captured["receipt_date_to"] is None
# 断言:恢复在循环外只跑一次;run_auto_transfer 恒收 recover_history=False。
assert captured["recover_history"] is False
assert captured["movement_date_from"] is None
assert captured["movement_date_to"] is None
assert captured["source_codes"] == ["CRANE_SGP"]
assert captured["recover_history"] is True
assert captured["transfer_type"] == "in_transit_to_hub"
assert run.response_summary_json["domain_notification_managed"] is True
assert (total, success, failed, skipped) == (0, 0, 0, 0)
assert results == []
assert any("no executable items" in w for w in warnings)
assert results == [] and errors == []
# 断言:恢复汇总与空数据说明落 step_logs(dict),errors 位不受污染。
assert step_logs[0]["step"] == "recovery"
assert any(item.get("step") == "auto_transfer" for item in step_logs)
def test_handler_converts_t_minus_offsets(monkeypatch):
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
from datetime import date
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
captured = {}
def _fake_auto_transfer(**kwargs):
captured.update(kwargs)
return job_mod.AutoTransferOutcome()
return AutoTransferOutcome()
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
run = ScheduleRun(run_no="RUNR-4", status="running")
@@ -181,85 +257,233 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
# 断言:T=2026-10-12,起4止2 换算为 T−4~T−2 的具体日期透传匹配层。
assert captured["business_date"] == "2026-10-12"
assert captured["receipt_date_from"] == "2026-10-08"
assert captured["receipt_date_to"] == "2026-10-10"
assert captured["movement_date_from"] == "2026-10-08"
assert captured["movement_date_to"] == "2026-10-10"
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
def _must_not_run(**kwargs):
raise AssertionError("run_auto_transfer must not run with invalid offsets")
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
run = ScheduleRun(run_no="RUNR-5", status="running")
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
_total, _success, _failed, _skipped, results, _warnings, errors = (
total, _success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名;
# failed_count=1 使终态为 failed(total=0+errors 会被框架误判 success,禁用)。
assert (total, failed) == (1, 1)
assert results == []
assert any("收料日期起点" in e for e in errors)
assert any("异动日期起点" in e for e in errors)
assert not (run.response_summary_json or {}).get("domain_notification_managed")
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
_total, _success, _failed, _skipped, _results, _warnings, errors = (
_total, _success, _failed, _skipped, _results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:小数偏移同样快速失败。
assert any("收料日期终点" in e for e in errors)
assert any("异动日期终点" in e for e in errors)
def test_handler_runs_each_type_once_and_recovery_once(monkeypatch):
"""多类型逐轮执行:每类型一次 run_auto_transfer(recover_history=False),恢复只跑一次。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch, types=["in_transit_to_hub", "hub_repair_out"])
recovery_calls: list[dict] = []
def _fake_recovery(**kwargs):
recovery_calls.append(kwargs)
return RecoveryOutcome(recovered_count=2)
monkeypatch.setattr(job_mod, "run_daily_recovery", _fake_recovery)
calls: list[dict] = []
def _fake_auto_transfer(**kwargs):
calls.append(kwargs)
return AutoTransferOutcome(run_no=f"TR-{len(calls)}", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
task = ScheduleTask(job_params={"transfer_types": ["in_transit_to_hub", "hub_repair_out"]})
run = ScheduleRun(run_no="RUNR-6", status="running")
total, success, failed, skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:逐类型各跑一轮且带类型编码;恢复与类型无关只跑一次。
assert [c["transfer_type"] for c in calls] == ["in_transit_to_hub", "hub_repair_out"]
assert all(c["recover_history"] is False for c in calls)
assert len(recovery_calls) == 1
# 断言:total=success+failed+recovered(2 成功 Run + 2 恢复行)。
assert (total, success, failed, skipped) == (4, 2, 0, 0)
assert [r["run_no"] for r in results] == ["TR-1", "TR-2"]
assert errors == []
# 断言:恢复汇总落 step_logs(recovered=2),errors 位只放真实错误。
assert step_logs[0]["step"] == "recovery"
assert step_logs[0]["detail"]["recovered"] == 2
def test_handler_empty_type_config_fails_hard(monkeypatch):
"""类型配置为空:fail-closed 硬失败(failed=1 → 框架 failed 终态),不执行。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch, types=[])
def _must_not_run(**kwargs):
raise AssertionError("run_auto_transfer must not run without transfer types")
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-7", status="running")
total, _success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:空配置硬失败不执行、不静默,错误信息指向类型配置缺失。
assert (total, failed) == (1, 1)
assert results == []
assert any("调拨类型" in e for e in errors)
assert not (run.response_summary_json or {}).get("domain_notification_managed")
def test_handler_run_day_uses_framework_notification(monkeypatch):
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
import app.services.schedule.in_transit_transfer_job as job_mod
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
def _fake_auto_transfer(**kwargs):
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
return AutoTransferOutcome(run_no="TR-1", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-2", status="running")
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
total, success, failed, skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
# 断言:有 run 不抑制框架通知;run_no+类型落入 results 供完成卡/留痕展示。
assert not (run.response_summary_json or {}).get("domain_notification_managed")
assert results and results[0]["run_no"] == "TR-1"
assert results[0]["transfer_type"] == "in_transit_to_hub"
assert (total, success, failed, skipped) == (1, 1, 0, 0)
assert errors == []
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
import app.services.schedule.in_transit_transfer_job as job_mod
def test_handler_recovery_failure_counts_as_failed(monkeypatch):
"""恢复复核抛异常:计一个 failed 单元——防止「恢复失败+空数据日」被框架判 success。"""
from app.models import ScheduleRun, ScheduleTask
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
job_mod = _patch_schedule_env(monkeypatch)
def _boom(**_kwargs):
raise RuntimeError("stock source offline")
monkeypatch.setattr(job_mod, "run_daily_recovery", _boom)
def _fake_auto_transfer(**kwargs):
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
return AutoTransferOutcome() # 各类型均空数据(无 Run 无错误)
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-9", status="running")
total, success, failed, _skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:恢复失败落 errors 且计 failed(终态 failed 交框架失败通知),
# 恢复 step_log 标 failed;不置静默标记。
assert (total, success, failed) == (1, 0, 1)
assert results == []
assert errors == ["recovery_failed: stock source offline"]
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "failed"
assert not (run.response_summary_json or {}).get("domain_notification_managed")
def test_handler_recovery_skipped_marks_step_log(monkeypatch):
"""recover_history=false:恢复不执行,step_log 标 skipped 且不计 failed。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch)
def _must_not_recover(**_kwargs):
raise AssertionError("run_daily_recovery must not run when recover_history is false")
monkeypatch.setattr(job_mod, "run_daily_recovery", _must_not_recover)
monkeypatch.setattr(
job_mod, "run_auto_transfer",
lambda **_kwargs: AutoTransferOutcome(run_no="TR-10", run_status="success"),
)
task = ScheduleTask(job_params={"recover_history": False})
run = ScheduleRun(run_no="RUNR-10", status="running")
total, success, failed, _skipped, results, errors, step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:恢复被跳过(step_log=skipped、无恢复错误),Run 照常产出。
assert (total, success, failed) == (1, 1, 0)
assert results and results[0]["run_no"] == "TR-10"
assert errors == []
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "skipped"
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch)
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
def _fake_auto_transfer(**kwargs):
return AutoTransferOutcome(errors=["match pipeline boom"])
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-3", status="running")
_total, _success, _failed, _skipped, results, _warnings, errors = (
_total, _success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results,
# 该类型计入 failed_count(终态 failed 交框架失败通知)。
assert not (run.response_summary_json or {}).get("domain_notification_managed")
assert results == []
assert errors == ["match pipeline boom"]
assert failed == 1
def test_handler_type_failure_isolated_per_type(monkeypatch):
"""单类型硬失败不阻断其余类型;失败类型计入 failed,成功类型照常出 Run。"""
from app.models import ScheduleRun, ScheduleTask
job_mod = _patch_schedule_env(monkeypatch, types=["bad_type", "in_transit_to_hub"])
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
def _fake_auto_transfer(**kwargs):
if kwargs["transfer_type"] == "bad_type":
return AutoTransferOutcome(errors=["type config disabled"])
return AutoTransferOutcome(run_no="TR-9", run_status="success")
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
task = ScheduleTask(job_params={})
run = ScheduleRun(run_no="RUNR-8", status="running")
total, success, failed, _skipped, results, errors, _step_logs = (
job_mod.run_in_transit_transfer_schedule(task, run)
)
# 断言:好类型照常执行出 Run;坏类型落 errors 并计入 failed(部分失败终态)。
assert (total, success, failed) == (2, 1, 1)
assert len(results) == 1 and results[0]["transfer_type"] == "in_transit_to_hub"
assert errors == ["type config disabled"]
@@ -0,0 +1,139 @@
"""范围规则引擎契约:规则间 AND、规则内多值 OR、受控词表、SQL 编译与内存求值同口径。
用途:锁定 scope_rules 引擎对外契约——受控字段白名单校验、evaluate/apply 双形态
同口径(防谓词漂移)、record_kinds_of 证据流推导、审计说明文本格式;
Task 11(圈档/重查)与 Task 5(API 校验)及证据流 UI 后续任务消费本契约。
依赖:app.core.errors.ValidationError、scope_rules 引擎、SQLAlchemy、
models/in_transit_transfer.TransferMovementLedger(SQL 编译断言与真库
行集交叉验证均以真档表为对象,2026-10-14 Task 9 回补,探针模型退役)。
逻辑:SQL 编译文本断言(pure_unit,不落库)+ 真库行集断言(请求 app/transfer_db
夹具:真档表逐条比对内存谓词命中与 SQL 实际命中行集)。
"""
from __future__ import annotations
import pytest
from sqlalchemy import select
from app import db
from app.core.errors import ValidationError
from app.models.in_transit_transfer import TransferMovementLedger
from app.services.in_transit_transfer.scope_rules import (
apply_scope_filters, evaluate_scope, parse_scope_rules, record_kinds_of, scope_rules_note,
)
pytestmark = pytest.mark.pure_unit
RULES = parse_scope_rules([
{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX"]},
{"field": "source_code", "match": "in", "values": ["SRC-A"]},
])
def test_record_kinds_of_reads_existing_scope_rule():
"""没有记录类型规则时入站和出站都要;只写 outbound 时只要出站。"""
assert record_kinds_of(parse_scope_rules([
{"field": "doc_no", "match": "prefix", "values": ["HOM"]},
])) == ("inbound", "outbound")
assert record_kinds_of(parse_scope_rules([
{"field": "record_kind", "match": "equals", "values": ["outbound"]},
])) == ("outbound",)
assert record_kinds_of(parse_scope_rules([
{"field": "record_kind", "match": "in", "values": ["outbound", "inbound"]},
])) == ("inbound", "outbound")
def test_rules_are_and_values_are_or():
"""两条规则须同时满足;同一规则内任一前缀命中即可。"""
assert evaluate_scope({"doc_no": "HOM-1", "source_code": "SRC-A"}, RULES)
assert evaluate_scope({"doc_no": "HOX-9", "source_code": "SRC-A"}, RULES)
assert not evaluate_scope({"doc_no": "HOM-1", "source_code": "SRC-B"}, RULES) # 规则间 AND:source 不中即淘汰
assert not evaluate_scope({"doc_no": "INV-1", "source_code": "SRC-A"}, RULES) # doc_no 两前缀均不中即淘汰
def test_match_modes():
"""equals 精确等值、contains 子串命中;未命中规则一票否决。
注:简报原用例字段 material_name 不在受控白名单(规格 §6 词表),经控制器
确认字段须为前端下拉受控选择,改用白名单字段 material_code(contains 断言
语义不变)。
"""
rules = parse_scope_rules([
{"field": "odm_id", "match": "equals", "values": ["HoxinRMA"]},
{"field": "material_code", "match": "contains", "values": ["轴承"]},
])
assert evaluate_scope({"odm_id": "HoxinRMA", "material_code": "精密轴承"}, rules)
assert not evaluate_scope({"odm_id": "Other", "material_code": "精密轴承"}, rules) # equals 不中
def test_unknown_field_rejected():
"""字段不在受控词表必须拒绝,且错误码固定为 TRANSFER.SCOPE_RULE_INVALID(Task 5 同步四语言 errors.json)。"""
with pytest.raises(ValidationError) as exc_info:
parse_scope_rules([{"field": "password", "match": "equals", "values": ["x"]}])
assert exc_info.value.code == "TRANSFER.SCOPE_RULE_INVALID" # 稳定错误码契约
def test_sql_compiler_literal_shape():
"""SQL 编译文本形状:prefix 编译为大写字面量 LIKE(双前缀 OR 展开)、in 编译为字面量 IN 列表。
注:Task 2 期间以临时探针模型编译占位(真档表未落地);Task 9 起改以真实
TransferMovementLedger 编译,断言不再依赖探针。原 `assert "IN" in sql` 偏弱
(任意含 IN 的 SQL 均通过),收紧为断言字面量值列表本体。
"""
assert scope_rules_note(RULES) == "doc_no prefix HOM|HOX AND source_code in SRC-A"
query = apply_scope_filters(select(TransferMovementLedger.id), TransferMovementLedger, RULES)
sql = str(query.compile(compile_kwargs={"literal_binds": True}))
assert "LIKE 'HOM%'" in sql and "LIKE 'HOX%'" in sql # prefix 字面量保持大写
assert "upper(transfer_movement_ledger.source_code) IN ('SRC-A')" in sql # in 匹配=字面量值列表
def test_sql_hits_same_rows_as_memory_predicate(app, transfer_db):
"""真档表行集交叉验证:SQL 实际命中行集与内存谓词逐条一致(Task 9 回补真库断言)。
覆盖四类边界:双前缀 OR 命中、小写命中(UPPER 同口径)、AND 淘汰、空值淘汰
(内存 _hit 空值 False ↔ SQL 空串/NULL 谓词排除,两侧必须同样不命中);
另以 movement_date(可空业务字段,规格 §4.2「空值不进日期圈定」)单独验证
NULL 边界——自然键成分 NOT NULL,NULL 只可能出现在可空业务字段。
"""
# (doc_no, source_code):前 3 条命中、后 3 条淘汰。
rows = [
{"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "HOM-1", "line_no": "1"}, # prefix 首值 + in
{"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "HOX-9", "line_no": "2"}, # prefix 次值(规则内 OR)
{"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "hom-2", "line_no": "3"}, # 小写:UPPER 后命中
{"source_code": "SRC-B", "record_kind": "receipt", "doc_no": "HOM-3", "line_no": "4"}, # 规则间 AND:source 不中
{"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "INV-1", "line_no": "5"}, # 两前缀均不中
{"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "", "line_no": "6"}, # 空串:空值不进圈定
# NULL 边界(movement_date 可空,规格 §4.2「空值不进日期圈定」;两行均满足 RULES,
# 用于下方 movement_date 专属规则的单列对照)。
{"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "HOM-NULL", "line_no": "99", "movement_date": None},
{"source_code": "SRC-A", "record_kind": "receipt", "doc_no": "HOM-DATE", "line_no": "98", "movement_date": "2026-10-14"},
]
ledgers = [TransferMovementLedger(**row) for row in rows]
db.session.add_all(ledgers)
db.session.flush()
query = apply_scope_filters(select(TransferMovementLedger.id), TransferMovementLedger, RULES)
sql_hits = {row.id for row in db.session.execute(query)}
# 行集级:SQL 命中行集恰为内存谓词判真的记录(含 2 条满足 RULES 的 NULL 边界行)。
expected = {
ledger.id for ledger, row in zip(ledgers, rows) if evaluate_scope(row, RULES)
}
assert sql_hits == expected == {
ledgers[0].id, ledgers[1].id, ledgers[2].id, ledgers[6].id, ledgers[7].id,
}
# 逐条交叉验证:每条记录「内存求值结果 ↔ 是否在 SQL 命中行集」一致。
for ledger, row in zip(ledgers, rows):
assert (ledger.id in sql_hits) is evaluate_scope(row, RULES)
# NULL 日期边界:movement_date 规则只命中有值行,NULL 行两侧(内存/SQL)同样不命中。
null_date_rules = parse_scope_rules([
{"field": "movement_date", "match": "equals", "values": ["2026-10-14"]},
])
date_query = apply_scope_filters(
select(TransferMovementLedger.id), TransferMovementLedger, null_date_rules,
)
date_hits = {row.id for row in db.session.execute(date_query)}
assert date_hits == {ledgers[7].id}
assert ledgers[6].id not in date_hits
@@ -1,12 +1,15 @@
"""来源收料文件状态投影服务测试。
"""来源证据文件状态投影服务测试。
用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile),
按来源投影 ready/fetching/failed/expired/parse_failed/none,并验证解析失败
标记 record/clear 的往返语义。调拨不维护独立抓取状态表。
依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
逻辑:有当天(业务日)抓取且未过期文件→ready(若标记解析失败→parse_failed);
有进行中单元→fetching;最新单元失败终态→failed;
保留期已到或隔日旧文件(未清理)→expired;否则→none。
用途:验证 resolve_source_file_status / resolve_source_file_statuses 只读货代入站/出站事实(UnitRun/ReportFile),
按来源与 record_kind 投影 ready/fetching/failed/expired/parse_failed/none/
unconfigured,并验证入站解析失败标记 record/clear 的往返语义。
调拨不维护独立抓取状态表。
依赖:app(SQLite)、FreightRpaSource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile;
出站用例用 monkeypatch 注入配置与可用文件视图,不连对象存储。
逻辑:入站既有用例保持:当天业务日且未过期文件→ready(解析失败→parse_failed);
进行中单元→fetching;最新单元失败终态→failed;空数据→no_data;
保留期已到或隔日旧文件→expired;否则→none。
出站无配置→unconfigured;出站有可用文件视图→ready。
"""
from __future__ import annotations
@@ -25,9 +28,9 @@ SOURCE_CODE = 'DSV360_AWSDU'
def receipt_unit_run():
"""构造一条收料执行单元(含排程/来源上下文)。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundUnitRun
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
task = ScheduleTask(
schedule_no='SCH-SOURCE-STATUS', name='Source status test', schedule_type='platform_job',
owner_user_id=1, cron_expr='0 8 * * *', job_params={},
@@ -37,8 +40,8 @@ def receipt_unit_run():
run = ScheduleRun(run_no='RUN-SOURCE-STATUS', schedule_task_id=task.id, status='awaiting_callback')
db.session.add(run)
db.session.flush()
unit = ShippingReceiptRpaUnitRun(
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
unit = FreightRpaInboundUnitRun(
schedule_run_id=run.id, source_id=source.id, source_code=source.source_code,
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-status-001',
status='awaiting_rpa', config_snapshot_json={},
)
@@ -64,7 +67,7 @@ def test_running_unit_is_fetching(app, receipt_unit_run):
def test_failed_latest_unit_is_failed(app, receipt_unit_run):
"""最新单元为失败终态且无文件 → failed。"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
receipt_unit_run.status = 'failed'
db.session.commit()
@@ -75,11 +78,11 @@ def test_failed_latest_unit_is_failed(app, receipt_unit_run):
def test_report_file_is_ready(app, receipt_unit_run):
"""有收料归档文件 → ready,且带 file_no/sha256。"""
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'receipt workbook').hexdigest()
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/test.xlsx', original_filename='receipt.xlsx',
file_size=16, sha256=digest,
@@ -96,10 +99,10 @@ def test_expired_report_is_expired(app, receipt_unit_run):
"""保留期已到但清理任务未删 → expired,不得误报 ready。"""
# [断言意图] 过期判定只看 archive_expires_at,不依赖保留期清理任务是否已落位。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
@@ -115,17 +118,17 @@ def test_newer_valid_report_wins_over_expired(app, receipt_unit_run):
"""过期文件之后又抓到未过期文件 → 以最新未过期文件为准(ready)。"""
# [断言意图] ready 查询过滤掉过期记录后仍按 created_at/id 倒序取最新一条。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'fresh workbook').hexdigest()
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
archive_expires_at=datetime.utcnow() - timedelta(days=1),
))
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/fresh.xlsx', original_filename='fresh.xlsx',
file_size=16, sha256=digest,
@@ -143,10 +146,10 @@ def test_stale_report_is_expired(app, receipt_unit_run):
# [断言意图] 新鲜度按 Asia/Shanghai 业务日窗口判定(UTC 库存时间须换算):
# 隔日抓取的文件对 D+1 预检是旧数据,投影 expired 引导重试重抓。
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/stale.xlsx', original_filename='stale.xlsx',
file_size=16, sha256=hashlib.sha256(b'stale workbook').hexdigest(),
@@ -161,11 +164,11 @@ def test_stale_report_is_expired(app, receipt_unit_run):
def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_unit_run):
"""可用归档文件若已标记 parse_failed_at → file_status=parse_failed 且不可当 ready。"""
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'bad workbook').hexdigest()
db.session.add(ShippingReceiptReportFile(
db.session.add(FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/bad.xlsx', original_filename='bad.xlsx',
file_size=16, sha256=digest,
@@ -183,28 +186,28 @@ def test_usable_file_with_parse_failed_at_projects_parse_failed(app, receipt_uni
def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
"""record 写入三列;clear 清空后投影回 ready。"""
from app import db
from app.models import ShippingReceiptReportFile
from app.models import FreightRpaInboundReportFile
from app.services.in_transit_transfer.source_file_status import (
clear_receipt_parse_failure,
record_receipt_parse_failure,
clear_inbound_parse_failure,
record_inbound_parse_failure,
resolve_source_file_status,
)
receipt_unit_run.status = 'success'
digest = hashlib.sha256(b'roundtrip').hexdigest()
report = ShippingReceiptReportFile(
report = FreightRpaInboundReportFile(
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/receipt/ok.xlsx', original_filename='ok.xlsx',
file_size=16, sha256=digest,
)
db.session.add(report)
db.session.commit()
record_receipt_parse_failure(
record_inbound_parse_failure(
report=report, error_code="TRANSFER_FILE_SCHEMA_INVALID", error_message="bad",
)
db.session.commit()
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "parse_failed"
clear_receipt_parse_failure(report=report)
clear_inbound_parse_failure(report=report)
db.session.commit()
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready"
@@ -218,3 +221,199 @@ def test_empty_unit_is_no_data(app, receipt_unit_run):
status = resolve_source_file_status(source_code=SOURCE_CODE)
assert status['file_status'] == 'no_data'
assert status['has_ready_file'] is False
def test_stale_orphan_unit_sweeps_projection_to_failed(app):
"""孤儿单元(按需触发无排程)超时回收后,投影 fetching 翻转为 failed。
网页异常关闭事故回归(2026-10-16):按需触发的单元 schedule_run_id=NULL,
回收扫描覆盖前投影永久 fetching、前端重试按钮(file_status !== 'fetching'
门禁)永久锁死;回收后必须翻转 failed 解锁重新触发 RPA。
"""
from app import db
from app.models import FreightRpaSource, FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import recover_all_stale_orphan_inbound_units
with app.app_context():
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
db.session.add(FreightRpaInboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
connector_type='dbs', callback_id='inbound-orphan-status', status='awaiting_rpa',
config_snapshot_json={}, created_at=datetime.utcnow() - timedelta(minutes=5),
))
db.session.commit()
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'fetching'
# [断言意图] 回收扫描后投影必须翻转为 failed:这是前端重试门禁
# (file_status !== 'fetching')解锁的依据,也是本测试与事故的直接回归点。
assert recover_all_stale_orphan_inbound_units() == 1
db.session.expire_all()
assert resolve_source_file_status(source_code=SOURCE_CODE)['file_status'] == 'failed'
def test_outbound_without_config_is_unconfigured(monkeypatch):
"""没有出站报表配置时,出站流是未配置,入站投影函数签名仍可只传来源。"""
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.get_outbound_config",
lambda source_code: None,
)
status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound")
assert status["file_status"] == "unconfigured"
assert status["has_ready_file"] is False
def test_outbound_usable_file_is_ready(monkeypatch):
"""出站已配置且存在可用归档时投影 ready;文件视图按入站可用文件形状注入,不读对象存储。"""
from types import SimpleNamespace
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.get_outbound_config",
lambda source_code: object(),
)
monkeypatch.setattr(
"app.services.in_transit_transfer.source_file_status.latest_usable_outbound_file",
lambda source_code: SimpleNamespace(
file_id=7,
original_filename="outbound.xlsx",
sha256="ab" * 32,
parse_failed_at=None,
),
)
status = resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="outbound")
# [断言意图] ready 必须读入站同形视图的文件名与摘要,而不是另查对象存储。
assert status["file_status"] == "ready"
assert status["has_ready_file"] is True
assert status["file_no"] == "outbound.xlsx"
assert status["file_sha256"] == "ab" * 32
def test_unknown_record_kind_is_rejected():
"""record_kind 只接受 inbound / outbound。"""
from app.core.errors import ValidationError
with pytest.raises(ValidationError):
resolve_source_file_status(source_code="DSV360_AWSBI", record_kind="onhand")
def test_outbound_report_file_projects_ready(app):
"""出站配置与当天可用归档都在库时,按出站文件表投影 ready,不读对象存储。"""
from app import db
from app.models import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
FreightRpaSource,
)
source = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
db.session.add(FreightRpaOutboundReportConfig(
source_id=source.id,
report_path_json={'report_name': 'Outbound'},
query_parameters_json=[],
))
unit = FreightRpaOutboundUnitRun(
schedule_run_id=None, source_id=source.id, source_code=source.source_code,
connector_type='dbs', warehouse_id='AWSDU', callback_id='outbound-status-ready',
status='success', config_snapshot_json={}, trigger_snapshot_json={},
)
db.session.add(unit)
db.session.flush()
digest = hashlib.sha256(b'outbound workbook').hexdigest()
db.session.add(FreightRpaOutboundReportFile(
unit_run_id=unit.id, storage_provider='minio', storage_bucket='test',
storage_key='shipping/outbound/test.xlsx', original_filename='outbound-real.xlsx',
file_size=16, sha256=digest,
))
db.session.commit()
status = resolve_source_file_status(source_code=SOURCE_CODE, record_kind='outbound')
# [断言意图] 出站 ready 走真实归档表与单元行,文件名/摘要来自行数据而非对象存储。
assert status['file_status'] == 'ready'
assert status['has_ready_file'] is True
assert status['file_no'] == 'outbound-real.xlsx'
assert status['file_sha256'] == digest
def _clone_enabled_source(source_code: str):
"""再造一个启用来源,复用种子站点的登录连接与模板,避免把查询次数测试绑在单来源上。"""
from app import db
from app.models import FreightRpaSource
existing = FreightRpaSource.query.filter_by(source_code=SOURCE_CODE).one()
source = FreightRpaSource(
source_code=source_code,
display_name=source_code,
connector_type=existing.connector_type,
rpa_profile_id=existing.rpa_profile_id,
excel_template_id=existing.excel_template_id,
warehouse_resolution_mode=existing.warehouse_resolution_mode,
fixed_warehouse_id=existing.fixed_warehouse_id,
enabled=True,
)
db.session.add(source)
db.session.commit()
return source
def test_batch_status_matches_per_source_and_prefers_running_unit(app, receipt_unit_run):
"""列表批量投影与逐来源投影一致;较新的失败单元不能盖住仍在进行的单元。"""
from app import db
from app.models import FreightRpaInboundUnitRun, FreightRpaSource
from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses
db.session.add(FreightRpaInboundUnitRun(
schedule_run_id=None,
source_id=receipt_unit_run.source_id,
source_code=SOURCE_CODE,
connector_type='dbs',
callback_id='inbound-newer-failed',
status='failed',
config_snapshot_json={},
trigger_snapshot_json={},
))
extra = _clone_enabled_source('DSV360_BATCH_EXTRA')
db.session.commit()
sources = FreightRpaSource.query.filter(
FreightRpaSource.source_code.in_([SOURCE_CODE, extra.source_code]),
).all()
batched = resolve_source_file_statuses(sources)
# [断言意图] 进行中单元优先于更新的失败单元,批量结果必须与逐条投影相同。
assert batched[SOURCE_CODE]['inbound']['file_status'] == 'fetching'
assert batched[SOURCE_CODE]['outbound']['file_status'] == 'unconfigured'
assert batched[extra.source_code]['inbound']['file_status'] == 'none'
for source in sources:
assert batched[source.source_code]['inbound'] == resolve_source_file_status(
source_code=source.source_code, record_kind='inbound',
)
assert batched[source.source_code]['outbound'] == resolve_source_file_status(
source_code=source.source_code, record_kind='outbound',
)
def test_batch_status_query_count_stays_flat_for_two_sources(app, receipt_unit_run):
"""两个来源的列表投影查询次数保持常数,不能按来源乘开。"""
from sqlalchemy import event
from app import db
from app.models import FreightRpaSource
from app.services.in_transit_transfer.source_file_status import resolve_source_file_statuses
extra = _clone_enabled_source('DSV360_BATCH_COUNT')
sources = FreightRpaSource.query.filter(
FreightRpaSource.source_code.in_([SOURCE_CODE, extra.source_code]),
).all()
assert len(sources) == 2
count = {'n': 0}
def _count_query(*_args, **_kwargs):
count['n'] += 1
event.listen(db.engine, 'before_cursor_execute', _count_query)
try:
resolve_source_file_statuses(sources)
finally:
event.remove(db.engine, 'before_cursor_execute', _count_query)
# [断言意图] 逐来源投影约 7 次/来源;两个来源仍必须落在固定的几次批量查询里。
assert count['n'] <= 8
@@ -26,7 +26,7 @@ pytestmark = pytest.mark.pure_unit
PROMPT_STATUSES = {
"file_pending", "file_ready", "matching", "ready_to_execute", "executing",
"success", "duplicate_success", "blocked_recoverable", "not_matured",
"success", "duplicate_success", "blocked_recoverable",
"result_unknown", "manually_closed", "cancelled", "notification_failed",
}
@@ -102,11 +102,6 @@ def test_unknown_status_rejected():
assert_transition_allowed("no_such_status", TransferStatus.SUCCESS.value)
def test_not_matured_has_no_outgoing_edges():
"""not_matured 无出边:当天不得查询 外部系统、不得生成调拨单。"""
assert ITEM_TRANSITIONS[TransferStatus.NOT_MATURED.value] == frozenset()
def test_run_transition_queued_to_executing_path():
"""Run 生命周期:queued → preparing_files → matching → ready_to_execute → executing。"""
assert_transition_allowed(TransferRunStatus.QUEUED.value, TransferRunStatus.PREPARING_FILES.value, transitions=RUN_TRANSITIONS)
@@ -0,0 +1,220 @@
"""transfer_movement_ledger 模型契约测试(ADR 0001 库存异动档)。
用途:锁定库存异动档表(规格 §4.2)的模型契约——表名/自然键唯一约束/
可空成分 NOT NULL + default ''/transfer_executed 默认 false/
source_file_id FK ON DELETE SET NULL(文件清理后档事实留存)。
依赖:app_ctx(根 conftest app fixture 上下文别名)、transfer_db(SQLite 内存库)、
models/in_transit_transfer、models/shipping_inbound_report。
逻辑:纯元数据断言(不落库)+ 真库往返(默认值/唯一约束/FK SET NULL 行为)。
"""
from __future__ import annotations
import pytest
from sqlalchemy import inspect, text
from sqlalchemy.exc import IntegrityError
from app import db
from app.models import FreightRpaInboundReportFile
from app.models.in_transit_transfer import TransferMovementLedger
# 自然键成分(幂等增量落地的去重键,规格 §4.2 + tt14 扩维 + 2026-10-21 外部身份
# 扩维):10 成分全部 NOT NULL,可空语义成分(line_seq/in_out_flag/carton_id/
# lot_no/external_doc_no/external_line_no)default ''(R7 终审:carton_id/lot_no
# NOT NULL + default '',防 PG NULL 逃逸唯一比对;外部身份两列同口径)。
NATURAL_KEY_COLUMNS = (
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
)
NATURAL_KEY_DIMENSION_COLUMNS = ('carton_id', 'lot_no', 'external_doc_no', 'external_line_no')
NATURAL_KEY_CONSTRAINT = 'uq_transfer_movement_ledger_natural_key'
# 规格 §4.2 全部业务/证据列(除自然键成分与回写布尔外一律 nullable)。
NULLABLE_BUSINESS_COLUMNS = (
'material_code', 'material_name', 'specification', 'quantity', 'unit',
'warehouse_code', 'storage_code', 'movement_date',
'order_type', 'odm_id', 'odm_name', 'pallet_id',
'doc_nature', 'movement_type', 'reason_code', 'source_ref_no', 'partner_code', 'remark',
'source_file_id', 'file_version', 'file_sha256', 'sheet_name', 'row_no',
'executed_doc_no',
)
@pytest.fixture
def app_ctx(app):
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
return app
def _column_map() -> dict:
return {c.name: c for c in TransferMovementLedger.__table__.columns}
def test_table_name_and_natural_key_constraint(app_ctx):
"""表名固定;自然键十成分(tt14 扩维 carton_id/lot_no + 2026-10-21 外部单据身份)构成唯一约束。"""
assert TransferMovementLedger.__tablename__ == 'transfer_movement_ledger'
constraints = {
c.name: [col.name for col in c.columns]
for c in TransferMovementLedger.__table__.constraints
if c.name
}
assert constraints[NATURAL_KEY_CONSTRAINT] == list(
NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS,
)
def test_natural_key_columns_not_null_with_empty_default(app_ctx):
"""自然键 10 成分全部 NOT NULL;可空语义成分 default ''(R7:carton_id/lot_no 同口径)。"""
cols = _column_map()
for name in NATURAL_KEY_COLUMNS + NATURAL_KEY_DIMENSION_COLUMNS:
assert cols[name].nullable is False, f"{name} 必须参与自然键即 NOT NULL"
# 与落档链路同口径:可空语义成分以空串入库(唯一约束可比,防 PG NULL 逃逸)。
for name in ('line_seq', 'in_out_flag', 'carton_id', 'lot_no',
'external_doc_no', 'external_line_no'):
assert cols[name].default.arg == ''
assert cols[name].server_default.arg == ''
def test_business_columns_nullable_and_types(app_ctx):
"""业务/证据列一律 nullable(外部系统列宽松落地);数量 String(40)、日期 String(16)。"""
cols = _column_map()
for name in NULLABLE_BUSINESS_COLUMNS:
assert cols[name].nullable is True, f"{name} 为可空业务列"
assert cols['quantity'].type.length == 40 # 数量 Decimal 文本,与 items 同约定
assert cols['movement_date'].type.length == 16 # 日期文本,与 items.movement_date 同约定
assert cols['remark'].type.python_type is str # 预留列 remark 为 Text
def test_transfer_executed_defaults_false(app_ctx):
"""平台回写封存位:NOT NULL 默认 false;executed_doc_no 可空。"""
cols = _column_map()
assert cols['transfer_executed'].nullable is False
assert cols['transfer_executed'].default.arg is False
assert cols['executed_doc_no'].nullable is True
def test_scope_indexes_declared(app_ctx):
"""圈档/封存扫描两条索引:(source_code, record_kind, movement_date) 与 (record_kind, transfer_executed)。"""
indexes = {
ix.name: [col.name for col in ix.columns]
for ix in TransferMovementLedger.__table__.indexes
if ix.name
}
assert sorted(indexes['ix_transfer_movement_ledger_source_kind_date']) == sorted(
['source_code', 'record_kind', 'movement_date'],
)
assert sorted(indexes['ix_transfer_movement_ledger_kind_executed']) == sorted(
['record_kind', 'transfer_executed'],
)
def test_source_file_fk_on_delete_set_null(app_ctx):
"""source_file_id FK 指向 freight_rpa_inbound_report_files 且 ON DELETE SET NULL(档事实留存)。"""
cols = _column_map()
fk = next(
fk for fk in TransferMovementLedger.__table__.foreign_keys
if fk.parent.name == 'source_file_id'
)
assert fk.target_fullname == 'freight_rpa_inbound_report_files.id'
assert fk.ondelete == 'SET NULL'
assert cols['source_file_id'].nullable is True
def test_ledger_roundtrip_with_defaults(transfer_db):
"""最小自然键落地:默认值生效(line_seq/in_out_flag 空串、transfer_executed false)。"""
ledger = TransferMovementLedger(
source_code='DBS-AWSBI',
record_kind='receipt',
doc_no='HOM-20261014-001',
line_no='10',
material_code='MAT-001',
quantity='12.5',
movement_date='2026-10-14',
source_file_id=None,
)
db.session.add(ledger)
db.session.flush()
loaded = db.session.get(TransferMovementLedger, ledger.id)
assert loaded.line_seq == ''
assert loaded.in_out_flag == ''
assert loaded.transfer_executed is False
assert loaded.executed_doc_no is None
assert loaded.created_at is not None and loaded.updated_at is not None
def test_duplicate_natural_key_rejected(transfer_db):
"""自然键唯一约束 DB 兜底:同八成分二次落地必须失败。
carton_id/lot_no(R7)与 line_seq/in_out_flag 同口径:ORM default '' + DB
server_default '',未传维度列的行以空串入键即可触发约束。
"""
def _make() -> TransferMovementLedger:
return TransferMovementLedger(
source_code='DBS-AWSBI',
record_kind='receipt',
doc_no='HOM-20261014-001',
line_no='10',
)
db.session.add(_make())
db.session.flush()
db.session.add(_make())
with pytest.raises(IntegrityError):
db.session.flush()
db.session.rollback()
def test_source_file_relationship_and_delete_sets_null(app, transfer_db):
"""source_file relationship 可导航;来源文件删除后档记录留存且 source_file_id 置 NULL。"""
from app.models import FreightRpaInboundUnitRun
unit_run = FreightRpaInboundUnitRun(
source_id=1, # SQLite 无 FK 强制(PRAGMA 未开),无需真实来源行
source_code='DBS-AWSBI',
connector_type='rpa',
callback_id='CB-LEDGER-001',
)
db.session.add(unit_run)
db.session.flush()
report_file = FreightRpaInboundReportFile(
unit_run_id=unit_run.id,
storage_provider='minio',
storage_bucket='receipts',
storage_key='receipts/hom-20261014.xlsx',
original_filename='hom-20261014.xlsx',
file_size=1024,
sha256='a' * 64,
)
db.session.add(report_file)
db.session.flush()
ledger = TransferMovementLedger(
source_code='DBS-AWSBI',
record_kind='receipt',
doc_no='HOM-20261014-002',
line_no='1',
source_file_id=report_file.id,
file_version='v1',
file_sha256='a' * 64,
)
db.session.add(ledger)
db.session.commit()
loaded = db.session.get(TransferMovementLedger, ledger.id)
assert loaded.source_file.id == report_file.id # relationship 目标 FreightRpaInboundReportFile
# ON DELETE SET NULL 行为:开启 SQLite FK 强制后原样删文件(文件资产保留策略)。
# PRAGMA 是连接级开关且事务内为 no-op:必须走 AUTOCOMMIT 连接执行,归还连接池
# 前关闭,否则 FK 强制残留会污染 app fixture 收尾的 drop_all(悬空 FK 拒解析)。
file_id = report_file.id
ledger_id = ledger.id
with db.engine.connect().execution_options(isolation_level='AUTOCOMMIT') as conn:
conn.execute(text('PRAGMA foreign_keys=ON'))
conn.execute(
text('DELETE FROM freight_rpa_inbound_report_files WHERE id = :id'),
{'id': file_id},
)
conn.execute(text('PRAGMA foreign_keys=OFF'))
db.session.expire_all()
survivor = db.session.get(TransferMovementLedger, ledger_id)
assert survivor is not None # 档事实不随文件消失
assert survivor.source_file_id is None # 链接仅溯源,删文件置 NULL
@@ -1,91 +1,93 @@
"""在途调拨类型契约测试(L1 纯单元)。
"""在途调拨类型门禁测试(配置化,L1)。
用途:验证调拨类型规范化/支持性门禁/类型 1 INVOICE 前缀过滤与范围说明。
依赖:transfer_type 模块、invoice_aggregator(构造汇总单)。
逻辑:纯函数测试,不创建 Flask/DB。
用途:验证 resolve_transfer_type 的三段 fail-closed 门禁——必填(None/空 →
REQUIRED)、存在性(空表/无此码 → NOT_CONFIGURED)、启停(停用 →
DISABLED;require_enabled=False 存量放行),以及正常配置解析返回 DTO。
依赖:app fixture(配置表)、factories.seed_transfer_type_config。
逻辑:类型合法值=transfer_type_configs.code(ADR 0002/D8:不做种子数据、
匹配创建必填、fail-closed)。
"""
from __future__ import annotations
from datetime import date
from decimal import Decimal
import pytest
from app.core.errors import ValidationError
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
from app.services.in_transit_transfer.transfer_type import (
HUB_REPAIR_OUT_ODM_ID,
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES,
TRANSFER_TYPE_NOT_SUPPORTED,
TransferType,
ensure_transfer_type_supported,
filter_invoices_for_type,
normalize_transfer_type,
transfer_type_scope_note,
TRANSFER_TYPE_DISABLED,
TRANSFER_TYPE_NOT_CONFIGURED,
TRANSFER_TYPE_REQUIRED,
resolve_transfer_type,
)
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
pytestmark = [pytest.mark.usefixtures("app")]
def _invoice(invoice_no: str) -> AggregatedInvoice:
"""构造最小汇总单(过滤只看 invoice_no)。"""
return AggregatedInvoice(
source_code="DBS-AWSBI", invoice_no=invoice_no, material_no="MAT-001",
material_name="连接器组件", specification="A 型",
receipt_date=date(2026, 8, 5), receipt_quantity=Decimal("100"),
raw_lines=(),
)
@pytest.fixture(autouse=True)
def _empty_transfer_type_configs():
"""类型门禁专项用例要求可控配置表:清空套件 autouse 种子后由用例自行播种。
Why: 域内 conftest 的 _seed_default_transfer_type 为全部 app 用例预置默认
类型;本模块锁定的是「空表/无此码/停用」的门禁形态,必须从空表出发。
How to apply: 每用例开始前 delete 全部配置行(conftest autouse 先于本
fixture 运行,播种被清除);需要配置的用例再调 seed_transfer_type_config。
"""
from app import db
from app.models import TransferTypeConfig
db.session.query(TransferTypeConfig).delete()
db.session.commit()
yield
def test_normalize_transfer_type_defaults_to_in_transit_to_hub():
"""缺省/空值/None 回落类型 1(存量调用方语义不变)。"""
assert normalize_transfer_type(None) == TransferType.IN_TRANSIT_TO_HUB
assert normalize_transfer_type("") == TransferType.IN_TRANSIT_TO_HUB
assert normalize_transfer_type("in_transit_to_hub") == TransferType.IN_TRANSIT_TO_HUB
assert normalize_transfer_type(TransferType.HUB_TO_HUB) == TransferType.HUB_TO_HUB
def test_resolve_returns_config_dto_when_configured():
"""配置存在 → 解析成功:DTO 携带范围规则/仓库定义/转换规则三块受控对象。"""
seed_transfer_type_config()
config = resolve_transfer_type("in_transit_to_hub")
# [断言意图] 门禁返回的是引擎解析后的配置对象(非原始 JSON):
# scope_rules/transform_rules 为规则元组,warehouse_config 可按角色解析。
assert config.code == "in_transit_to_hub"
assert config.enabled is True
assert {rule.field for rule in config.scope_rules} == {"doc_no"}
assert {rule.field for rule in config.transform_rules} == {"lot_no"}
assert config.warehouse_config.from_role.mode == "mapped"
assert config.warehouse_config.to_role.mode == "mapped"
def test_normalize_transfer_type_rejects_unknown_value():
"""非法类型值 → ValidationError(TRANSFER.TRANSFER_TYPE_INVALID)。"""
with pytest.raises(ValidationError) as exc_info:
normalize_transfer_type("not_a_type")
assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_INVALID"
def test_ensure_supported_rejects_placeholder_types():
"""类型 2/3 一期占位:进入处理链路被 fail-closed 拒绝。"""
ensure_transfer_type_supported(TransferType.IN_TRANSIT_TO_HUB)
for placeholder in (TransferType.HUB_REPAIR_OUT, TransferType.HUB_TO_HUB):
def test_resolve_requires_transfer_type():
"""必填(D8):None/空/空白 → TRANSFER_TYPE_REQUIRED,不回落默认类型。"""
for bad in (None, "", " "):
with pytest.raises(ValidationError) as exc_info:
ensure_transfer_type_supported(placeholder)
assert exc_info.value.code == TRANSFER_TYPE_NOT_SUPPORTED
resolve_transfer_type(bad)
# [断言意图] 缺失与「未配置」是两种失败:必填缺失必须独立成码。
assert exc_info.value.code == TRANSFER_TYPE_REQUIRED
def test_filter_type1_keeps_invoice_prefixes_case_insensitive():
"""类型 1 只保留 INVOICE 前缀 HOM/HOX/WTP(大小写不敏感)。"""
invoices = [
_invoice("HOM-20260801-01"),
_invoice("hox-20260801-02"),
_invoice("WTP-20260801-03"),
_invoice("INV-001"),
_invoice("RCP-9"),
_invoice("OTHER-1"),
]
kept = filter_invoices_for_type(invoices, TransferType.IN_TRANSIT_TO_HUB)
assert [invoice.invoice_no for invoice in kept] == [
"HOM-20260801-01", "hox-20260801-02", "WTP-20260801-03",
]
def test_resolve_rejects_when_config_table_empty_or_missing():
"""配置表为空或无此码 → TRANSFER_TYPE_NOT_CONFIGURED(fail-closed,D8)。"""
# [断言意图] 空配置表:不抛「必填」也不静默放行——NOT_CONFIGURED 独立成码。
with pytest.raises(ValidationError) as empty_table:
resolve_transfer_type("in_transit_to_hub")
assert empty_table.value.code == TRANSFER_TYPE_NOT_CONFIGURED
seed_transfer_type_config()
# [断言意图] 表非空但编码不存在:同一码面(存在性失败)。
with pytest.raises(ValidationError) as unknown_code:
resolve_transfer_type("no_such_type")
assert unknown_code.value.code == TRANSFER_TYPE_NOT_CONFIGURED
def test_filter_type1_empty_invoice_no_excluded():
"""空/空白 Invoice 号不匹配任何前缀 → 排除(防御性)。"""
kept = filter_invoices_for_type([_invoice("")], TransferType.IN_TRANSIT_TO_HUB)
assert kept == []
assert set(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES) == {"HOM", "HOX", "WTP"}
assert HUB_REPAIR_OUT_ODM_ID == "HoxinRMA"
def test_resolve_rejects_disabled_type_but_allows_existing_rerun():
"""停用类型:新匹配路径 DISABLED;require_enabled=False(存量重跑/重查)放行。"""
seed_transfer_type_config(enabled=False)
with pytest.raises(ValidationError) as exc_info:
resolve_transfer_type("in_transit_to_hub")
# [断言意图] 停用 ≠ 未配置:独立成码(前端可区分「请配置」与「已停用」)。
assert exc_info.value.code == TRANSFER_TYPE_DISABLED
def test_scope_note_records_type_rule():
"""范围说明写入 scope_json 的审计口径。"""
assert transfer_type_scope_note(TransferType.IN_TRANSIT_TO_HUB) == "invoice_prefix:hom+hox+wtp"
assert transfer_type_scope_note(TransferType.HUB_REPAIR_OUT) == "odm_id:HoxinRMA"
assert transfer_type_scope_note(TransferType.HUB_TO_HUB) == "pending_rule"
# [断言意图] 「停用后存量不受影响」(规格 §4.1):存量匹配的重跑/重查以
# require_enabled=False 解析同一配置,成功返回 DTO。
config = resolve_transfer_type("in_transit_to_hub", require_enabled=False)
assert config.code == "in_transit_to_hub"
assert config.enabled is False
@@ -0,0 +1,35 @@
"""transfer_type_configs 模型契约测试。
用途:锁定调拨类型配置表(ADR 0002)的模型契约——表名/列定义/唯一约束,
以及 transfer_runs.transfer_type 枚举 CHECK 已随配置化移除。
依赖:app_ctx 夹具(根 conftest app fixture 的上下文别名)、models/in_transit_transfer。
逻辑:纯元数据断言(不落库);迁移接线由 alembic 校验与域模型测试兜底。
"""
from __future__ import annotations
import pytest
from app.models.in_transit_transfer import TransferTypeConfig
@pytest.fixture
def app_ctx(app):
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
return app
def test_table_and_unique_code(app_ctx):
"""编码唯一且不可空;names_json/scope_rules_json 等为 JSON 列。"""
assert TransferTypeConfig.__tablename__ == 'transfer_type_configs'
cols = {c.name: c for c in TransferTypeConfig.__table__.columns}
assert cols['code'].nullable is False
assert cols['names_json'].type.python_type is dict
assert cols['enabled'].default.arg is False or cols['enabled'].default.arg is True
def test_transfer_runs_check_dropped():
"""transfer_runs.transfer_type 不再挂枚举 CHECK 约束(配置化取代)。"""
from app.models.in_transit_transfer import TransferRun
names = {c.name for c in TransferRun.__table__.constraints if hasattr(c, 'name') and c.name}
assert 'ck_transfer_runs_transfer_type' not in names
@@ -0,0 +1,353 @@
"""调拨类型配置服务契约:CRUD 校验门禁、读取侧 parse 拦截、仓库角色解析四场景。
用途:锁定 transfer_type_config_service 对外契约——code 格式/唯一/不可变、
names zh-CN 必填、scope_rules 默认至少一条(显式确认可豁免)、
warehouse_config 模式白名单与 fixed 必填仓库、get_enabled 只回启用且按
sort_order 排序、resolve_warehouse mapped/fixed 混合解析
(Task 5 API 与 Task 11 路由接入消费本契约)。
依赖:transfer_db 夹具(根 conftest app fixture 的 db 别名,SQLite 内存库)、
transfer_type_config_service、matching_service.RouteMapping、scope/transform 引擎。
逻辑:CRUD 与读取侧拦截用例走真实 ORM 落库;resolve_warehouse 与
_parse_warehouse_config 为纯函数用例不触 DB(模块级 pure_unit 标记:
未请求 app 的用例跳过 Flask/DB 创建,请求 transfer_db 的用例仍走 app 夹具)。
"""
from __future__ import annotations
import pytest
from app.core.errors import ValidationError
from app.models.in_transit_transfer import TransferTypeConfig
from app.services.in_transit_transfer.field_transforms import TransformRule
from app.services.in_transit_transfer.matching_service import RouteMapping
from app.services.in_transit_transfer.scope_rules import ScopeRule
from app.services.in_transit_transfer.transfer_type_config_service import (
WarehouseConfig,
WarehouseRole,
_parse_warehouse_config,
create_config,
get_by_code,
get_enabled,
list_configs,
resolve_warehouse,
update_config,
)
pytestmark = pytest.mark.pure_unit
@pytest.fixture(autouse=True)
def _drop_seeded_default_type(request):
"""本模块以 in_transit_to_hub 为夹具码:清掉域 conftest autouse 种子防撞码。
Why: 域 conftest 为全部 app 用例预置启用类型 in_transit_to_hub;本模块
create/update 用例以同一 code 构造 VALID_PAYLOAD,需从干净配置表出发。
How to apply: 仅对请求 app 的用例清表(pure_unit 用例不触 Flask/DB)。
"""
if "app" not in getattr(request, "fixturenames", []):
yield
return
from app import db
from app.models import TransferTypeConfig
db.session.query(TransferTypeConfig).delete()
db.session.commit()
yield
# [FIXTURE] 合法载荷基线:一期「在途仓至HUB仓」等价配置(双 mapped + WTP→HOW 转换)。
VALID_PAYLOAD = {
"code": "in_transit_to_hub",
"names": {"zh-CN": "在途仓至HUB仓", "en": "In-transit to Hub"},
"enabled": True,
"sort_order": 10,
"scope_rules": [
{"field": "doc_no", "match": "prefix", "values": ["HOM", "HOX", "WTP"]},
],
"warehouse_config": {
"from": {"mode": "mapped", "warehouse_code": None, "external_org": None},
"to": {"mode": "mapped", "warehouse_code": None, "external_org": None},
},
"transform_rules": [
{"field": "lot_no", "op": "prefix_replace", "source": "wtp", "target": "HOW"},
],
"description": "一期默认类型",
}
EXPECTED_SCOPE = (ScopeRule(field="doc_no", match="prefix", values=("HOM", "HOX", "WTP")),)
def _route() -> RouteMapping:
"""映射档路由样例:法人 ORG-1000 / 拨出在途仓 WH-TRANSIT / 拨入 HUB 仓 WH-HUB。"""
return RouteMapping(external_org="ORG-1000", from_warehouse="WH-TRANSIT", to_warehouse="WH-HUB")
# ---------------------------------------------------------------------------
# create_config
# ---------------------------------------------------------------------------
def test_create_roundtrip(transfer_db):
"""创建成功:字段逐一回读;scope/transform/warehouse 三块经 parse 规范化。"""
dto = create_config(VALID_PAYLOAD, operator_id=None)
assert dto.code == "in_transit_to_hub"
assert dto.names["zh-CN"] == "在途仓至HUB仓" # names 原样保留(zh-CN 必填已过门禁)
assert dto.enabled is True
assert dto.sort_order == 10
assert dto.description == "一期默认类型"
assert dto.updated_at is not None # ORM flush 填充 updated_at
# [断言] 规则块为引擎受控 dataclass;transform source/target 统一大写。
assert dto.scope_rules == EXPECTED_SCOPE
assert dto.transform_rules == (
TransformRule(field="lot_no", op="prefix_replace", source="WTP", target="HOW"),
)
assert dto.warehouse_config.from_role.mode == "mapped"
assert dto.warehouse_config.to_role.mode == "mapped"
reloaded = get_by_code("in_transit_to_hub")
assert reloaded == dto # 读回与创建产物全等(DTO dataclass eq)
def test_create_duplicate_code(transfer_db):
"""重复 code 被拒,错误码稳定为 TRANSFER.TRANSFER_TYPE_CODE_EXISTS。"""
create_config(VALID_PAYLOAD, operator_id=None)
with pytest.raises(ValidationError) as exc_info:
create_config(VALID_PAYLOAD, operator_id=None)
assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_CODE_EXISTS" # 稳定错误码契约
def test_create_invalid_code_format(transfer_db):
"""code 必须 ^[a-z][a-z0-9_]{1,63}$;非法形态走通用参数校验码。"""
for bad in ("Bad", "1abc", "-lead", "has space", "a", "x" * 65):
with pytest.raises(ValidationError) as exc_info:
create_config({**VALID_PAYLOAD, "code": bad}, operator_id=None)
# [断言] 参数形态类失败用既有通用码 VALIDATION.INVALID_PARAM(不在四语言新增清单内)。
assert exc_info.value.code == "VALIDATION.INVALID_PARAM", f"code={bad!r} 应被拒"
# 边界内合法:a 开头 + 下划线数字,长度 2..64。
create_config({**VALID_PAYLOAD, "code": "a" + "b" * 63}, operator_id=None)
def test_create_requires_zh_cn_name(transfer_db):
"""names 必填且必须含非空 zh-CN;缺 key/纯外文/空白/None 均拒。"""
no_names = {k: v for k, v in VALID_PAYLOAD.items() if k != "names"}
with pytest.raises(ValidationError) as exc_info:
create_config(no_names, operator_id=None)
assert exc_info.value.code == "VALIDATION.INVALID_PARAM" # 缺 names 整体同拒
with pytest.raises(ValidationError) as exc_info:
create_config({**VALID_PAYLOAD, "names": {"en": "English only"}}, operator_id=None)
assert exc_info.value.code == "VALIDATION.INVALID_PARAM"
with pytest.raises(ValidationError):
create_config({**VALID_PAYLOAD, "names": {"zh-CN": " "}}, operator_id=None) # 空白同拒
with pytest.raises(ValidationError):
create_config({**VALID_PAYLOAD, "names": None}, operator_id=None) # 非 dict 同拒
def test_create_empty_scope_rules_rejected_by_default(transfer_db):
"""空 scope_rules 默认拒绝(防误圈全量,规格 §6)。"""
with pytest.raises(ValidationError) as exc_info:
create_config({**VALID_PAYLOAD, "scope_rules": []}, operator_id=None)
assert exc_info.value.code == "VALIDATION.INVALID_PARAM"
with pytest.raises(ValidationError):
create_config({**VALID_PAYLOAD, "scope_rules": None}, operator_id=None)
def test_create_empty_scope_rules_with_explicit_confirm(transfer_db):
"""「空=不限」须管理页显式确认(payload 显式确认后放行,规格 §6)。"""
dto = create_config(
{**VALID_PAYLOAD, "scope_rules": [], "allow_empty_scope_rules": True}, operator_id=None,
)
assert dto.scope_rules == () # 显式确认后空规则合法(= 不限)
def test_create_warehouse_fixed_requires_code(transfer_db):
"""fixed 角色缺仓库编码在保存入口即拒(TRANSFER.WAREHOUSE_CONFIG_INVALID)。"""
payload = {
**VALID_PAYLOAD,
"warehouse_config": {"from": {"mode": "fixed"}}, # fixed 无 warehouse_code
}
with pytest.raises(ValidationError) as exc_info:
create_config(payload, operator_id=None)
assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID"
# ---------------------------------------------------------------------------
# update_config
# ---------------------------------------------------------------------------
def test_update_code_immutable(transfer_db):
"""payload 携带不同 code 即拒(TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE);同值放行。"""
create_config(VALID_PAYLOAD, operator_id=None)
with pytest.raises(ValidationError) as exc_info:
update_config("in_transit_to_hub", {"code": "renamed_type"}, operator_id=None)
assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE"
dto = update_config(
"in_transit_to_hub", {"code": "in_transit_to_hub", "sort_order": 99}, operator_id=None,
)
assert dto.sort_order == 99 # 携带相同 code 不视为改名,其余字段正常更新
def test_update_partial_keeps_unset_fields(transfer_db):
"""部分更新:未传字段保持原值;更新路径同样过 parse 门禁。"""
create_config(VALID_PAYLOAD, operator_id=None)
dto = update_config("in_transit_to_hub", {"enabled": False, "description": "停用"}, operator_id=None)
assert dto.enabled is False
assert dto.description == "停用"
assert dto.scope_rules == EXPECTED_SCOPE # 未传 scope_rules 保持不变
with pytest.raises(ValidationError) as exc_info:
update_config(
"in_transit_to_hub", {"warehouse_config": {"to": {"mode": "fixed"}}}, operator_id=None,
)
assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID" # 更新同样校验仓库定义
def test_update_rejected_payload_leaves_row_untouched(transfer_db):
"""部分更新载荷任一键非法:整单拒绝且 session 中行保持原值(无半截变更)。
评审 Finding 2 回归:update 先全量校验后统一赋值——
{"description": 新值, "transform_rules": 非法} 不得先改 description 再抛错。
"""
create_config(VALID_PAYLOAD, operator_id=None)
with pytest.raises(ValidationError) as exc_info:
update_config(
"in_transit_to_hub",
{
"description": "半截变更探测",
"transform_rules": [{"field": "lot_no", "op": "nope", "source": "A", "target": "B"}],
},
operator_id=None,
)
assert exc_info.value.code == "TRANSFER.TRANSFORM_RULE_INVALID" # 非法键抛引擎错误码
# [断言] 同一 session 内直读行:description 保持原值——校验失败不落半截变更。
row = (
transfer_db.session.query(TransferTypeConfig)
.filter(TransferTypeConfig.code == "in_transit_to_hub")
.one()
)
assert row.description == "一期默认类型"
assert row.transform_rules_json == [
{"field": "lot_no", "op": "prefix_replace", "source": "WTP", "target": "HOW"}
] # 合法键值同未被触碰(create 写入的引擎规范化原值:source/target 大写)
def test_update_not_configured(transfer_db):
"""更新不存在的类型 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED。"""
with pytest.raises(ValidationError) as exc_info:
update_config("no_such_type", {"enabled": False}, operator_id=None)
assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
# ---------------------------------------------------------------------------
# 读取侧
# ---------------------------------------------------------------------------
def test_get_enabled_only_enabled_sorted(transfer_db):
"""get_enabled 只回 enabled 且按 sort_order 升序;list_configs 回全量同序。"""
create_config(VALID_PAYLOAD, operator_id=None) # sort_order=10, enabled
create_config({**VALID_PAYLOAD, "code": "hub_repair_out", "sort_order": 5}, operator_id=None)
create_config(
{**VALID_PAYLOAD, "code": "hub_to_hub", "sort_order": 1, "enabled": False}, operator_id=None,
)
enabled = get_enabled()
assert [d.code for d in enabled] == ["hub_repair_out", "in_transit_to_hub"] # 停用不出现在 chat 列表
all_configs = list_configs()
assert [d.code for d in all_configs] == ["hub_to_hub", "hub_repair_out", "in_transit_to_hub"]
def test_get_by_code_not_configured(transfer_db):
"""不存在的 code → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED(匹配链 fail-closed 同码)。"""
with pytest.raises(ValidationError) as exc_info:
get_by_code("no_such_type")
assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
def test_read_side_parse_intercepts_dirty_rows(transfer_db):
"""库内脏数据在读取侧也被拦截:DTO 组装 scope/warehouse/transform 全走 parse。"""
# ORM 直插绕过服务校验,构造三类脏数据(模型 modeled default 使 JSON 列可省略)。
transfer_db.session.add(TransferTypeConfig(
code="dirty_scope", names_json={"zh-CN": "脏范围"},
scope_rules_json=[{"field": "password", "match": "equals", "values": ["x"]}],
))
transfer_db.session.add(TransferTypeConfig(
code="dirty_warehouse", names_json={"zh-CN": "脏仓库"},
warehouse_config_json={"from": {"mode": "bogus"}},
))
transfer_db.session.add(TransferTypeConfig(
code="dirty_transform", names_json={"zh-CN": "脏转换"},
transform_rules_json=[{"field": "lot_no", "op": "nope", "source": "A", "target": "B"}],
))
transfer_db.session.commit()
with pytest.raises(ValidationError) as exc_info:
get_by_code("dirty_scope")
assert exc_info.value.code == "TRANSFER.SCOPE_RULE_INVALID"
with pytest.raises(ValidationError) as exc_info:
get_by_code("dirty_warehouse")
assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID"
with pytest.raises(ValidationError) as exc_info:
get_by_code("dirty_transform")
assert exc_info.value.code == "TRANSFER.TRANSFORM_RULE_INVALID"
# ---------------------------------------------------------------------------
# resolve_warehouse / _parse_warehouse_config(纯函数,不触 DB)
# ---------------------------------------------------------------------------
def test_resolve_warehouse_mapped_passthrough():
"""双 mapped:仓库与法人全部透传映射档(存量 DefaultRouteResolver 行为)。"""
config = _parse_warehouse_config({}) # 缺省 warehouse_config = 双 mapped
assert resolve_warehouse(_route(), config, "from") == ("ORG-1000", "WH-TRANSIT")
assert resolve_warehouse(_route(), config, "to") == ("ORG-1000", "WH-HUB")
def test_resolve_warehouse_fixed_overrides_warehouse():
"""fixed 覆盖该角色仓库,external_org 为空沿用映射档法人。"""
config = WarehouseConfig(
from_role=WarehouseRole(mode="mapped"),
to_role=WarehouseRole(mode="fixed", warehouse_code="WH-REPAIR"),
)
assert resolve_warehouse(_route(), config, "to") == ("ORG-1000", "WH-REPAIR")
assert resolve_warehouse(_route(), config, "from") == ("ORG-1000", "WH-TRANSIT") # mapped 角色不受影响
def test_resolve_warehouse_fixed_with_org_overrides_external_org():
"""fixed + external_org 非空:法人一并覆盖(跨法人调拨场景)。"""
config = WarehouseConfig(
from_role=WarehouseRole(mode="mapped"),
to_role=WarehouseRole(mode="fixed", warehouse_code="WH-REPAIR", external_org="ORG-9000"),
)
assert resolve_warehouse(_route(), config, "to") == ("ORG-9000", "WH-REPAIR")
def test_resolve_warehouse_fixed_missing_warehouse_code_raises():
"""fixed 缺 warehouse_code(绕过 parse 直构的非法配置)在解析侧也 fail-closed。"""
config = WarehouseConfig(
from_role=WarehouseRole(mode="mapped"),
to_role=WarehouseRole(mode="fixed", warehouse_code=None),
)
with pytest.raises(ValidationError) as exc_info:
resolve_warehouse(_route(), config, "to")
assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID"
def test_resolve_warehouse_unknown_role_raises():
"""role 仅接受 from/to;未知角色 fail-closed(防调用方静默拿错仓库)。"""
config = _parse_warehouse_config({})
with pytest.raises(ValidationError) as exc_info:
resolve_warehouse(_route(), config, "middle")
assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID"
def test_parse_warehouse_config_mode_whitelist_and_normalization():
"""mode 白名单(mapped/fixed);fixed 必填非空仓库编码;缺省角色回 mapped。"""
config = _parse_warehouse_config({
"from": {"mode": "fixed", "warehouse_code": "WH-A"},
"to": {"mode": "mapped"},
})
assert config.from_role == WarehouseRole(mode="fixed", warehouse_code="WH-A")
assert config.to_role == WarehouseRole(mode="mapped")
with pytest.raises(ValidationError) as exc_info:
_parse_warehouse_config({"to": {"mode": "static"}}) # 白名单外 mode
assert exc_info.value.code == "TRANSFER.WAREHOUSE_CONFIG_INVALID"
with pytest.raises(ValidationError):
_parse_warehouse_config({"to": {"mode": "fixed", "warehouse_code": " "}}) # 空白编码同拒
@@ -43,8 +43,12 @@ def _file(*rows: dict) -> dict:
}
def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: str = "2026-08-05") -> dict:
"""构造单条 movement 行;unit=None 表示文件中该列缺失(而非空串)。"""
def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: str = "2026-08-04") -> dict:
"""构造单条 movement 行;unit=None 表示文件中该列缺失(而非空串)。
movement_date 缺省取 2026-08-04(= 业务日 08-06 的 T−2 成熟边界;更晚日期
会被圈档 T−2 封顶排除)。
"""
row = {
"sheet": "Movement", "row_no": row_no, "doc_no": doc_no,
"lot_no": f"LOT-{row_no}", "material_code": f"MAT-{row_no}",
@@ -59,8 +63,13 @@ def _row(row_no: int, doc_no: str, *, unit: str | None = None, movement_date: st
# ---- ① 契约:MOVEMENT_FIELDS 恰含 unit 且为第 11 个 ------------------------
def test_movement_fields_contract_contains_unit_as_11th_field():
"""契约定死 11 个字段且第 11 个为 unit:可选文本字段(空值由匹配阶段行级阻断,不产生解析失败)。"""
assert len(MOVEMENT_FIELDS) == 11
"""契约定死且第 11 个为 unit:可选文本字段(空值由匹配阶段行级阻断,不产生解析失败)。
2026-10-14 扩展在 unit 之后追加 7 个可选维度字段(Task 8)——只追加、不重排,
unit 的第 11 位契约不变;2026-10-21 再追加外部单据身份 2 字段(外部单号/
外部项次),总数 11+7+2=20。
"""
assert len(MOVEMENT_FIELDS) == 20
unit = MOVEMENT_FIELDS[10]
# [断言意图] unit 定死在第 11 位——movement 文件列顺序契约,解析/展示/ERP 写入共用。
assert unit.code == "unit"
@@ -69,7 +78,7 @@ def test_movement_fields_contract_contains_unit_as_11th_field():
# unit 不是幂等/匹配身份,也不是必填(解析层放行空值,阻断留给匹配层)。
assert unit.is_identity is False
assert unit.required is False
assert len({field.code for field in MOVEMENT_FIELDS}) == 11
assert len({field.code for field in MOVEMENT_FIELDS}) == 20
# ---- ② 解析:带出 unit 原值(仅 trim,不换算/不清洗) -----------------------
@@ -91,7 +100,7 @@ def test_missing_unit_still_parses():
_row(1, "HOM-901"),
_row(2, "HOM-902", unit=" "),
])
# [断言意图] 缺列与纯空白等价归一为空串,解析不抛 ReceiptFileSchemaError。
# [断言意图] 缺列与纯空白等价归一为空串,解析不抛 MovementFileSchemaError。
assert [row.unit for row in parsed] == ["", ""]
assert [row.invoice_no for row in parsed] == ["HOM-901", "HOM-902"]
@@ -107,7 +116,7 @@ def test_unit_taken_from_erp_stock_not_from_file(app):
erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100", unit="EA")
erp.seed_stock("MAT-2", "DBS-TRANSIT", "LOT-2", "100", unit="PCS")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
items = {item.invoice_no: item for item in result.items}
# [断言意图] 文件单位列(KG/缺失)对结果零影响:两行都 executable,行 unit
# 等于 ERP 返回值(EA/PCS)——单据字段只看 ERP(2026-09-24 用户拍板)。
@@ -126,7 +135,7 @@ def test_erp_missing_unit_blocked_with_route_resolved(app):
erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100")
erp.seed_stock("MAT-2", "DBS-TRANSIT", "LOT-2", "100", unit="")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
result = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
items = {item.invoice_no: item for item in result.items}
# [断言意图] ERP 缺单位只阻断本行且原因指向 ERP 侧;行已完成路由解析——
# 拨出/拨入仓库照常落列(与旧「路由前拦截仓库留空」行为的本质区别),
@@ -151,7 +160,7 @@ def test_missing_unit_difference_persisted_to_row_note(transfer_db):
erp.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100")
erp.seed_stock("MAT-2", "DBS-TRANSIT", "LOT-2", "100", unit="")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
restored = restore_matching(summary.matching_id)
items = {item.invoice_no: item for item in restored["items"]}
# [断言意图] 差异注释随行落库:restore 视图能看到 blocked_missing_unit 与原因;
@@ -176,23 +185,23 @@ def test_matching_hash_freezes_unit_value_out_of_snapshot(app):
deps_pcs, erp_pcs, _rpa = make_transfer_deps(_file(_row(1, "HOM-901", unit="PCS")))
erp_pcs.seed_stock("MAT-1", "DBS-TRANSIT", "LOT-1", "100")
seed_rows_from_file("DBS-AWSBI", deps_kg, "2026-08-06") # 行落地一次;unit 非证据字段不触发重置
hash_kg = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_kg).summary.matching_hash
hash_pcs = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_pcs).summary.matching_hash
hash_kg = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_kg, transfer_type="in_transit_to_hub").summary.matching_hash
hash_pcs = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_pcs, transfer_type="in_transit_to_hub").summary.matching_hash
# [断言意图] unit 是展示/写入字段而非匹配身份:换单位不得漂移匹配哈希(可审计复算)。
assert hash_kg == hash_pcs
def test_matching_hash_unchanged_when_unit_backfilled_on_not_matured_rows(app):
"""未成熟行补 unit 前后 Hash 不变:既有成熟过滤先行,unit 追加校验不扰动历史行结果。"""
def test_matching_hash_unchanged_when_unit_backfilled(app):
"""行补 unit 前后 Hash 不变:unit 是展示/写入列而非 Hash 入参(口径冻结)。"""
deps_before, _erp_a, _rpa = make_transfer_deps(_file(
_row(1, "HOM-901", movement_date="2026-08-06"),
_row(1, "HOM-901", movement_date="2026-08-04"),
))
deps_after, _erp_b, _rpa = make_transfer_deps(_file(
_row(1, "HOM-901", unit="KG", movement_date="2026-08-06"),
_row(1, "HOM-901", unit="KG", movement_date="2026-08-04"),
))
seed_rows_from_file("DBS-AWSBI", deps_before, "2026-08-06") # 行落地一次(当日收料 → 未成熟)
hash_before = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_before).summary.matching_hash
hash_after = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_after).summary.matching_hash
seed_rows_from_file("DBS-AWSBI", deps_before, "2026-08-06") # 行落地一次
hash_before = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_before, transfer_type="in_transit_to_hub").summary.matching_hash
hash_after = run_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps_after, transfer_type="in_transit_to_hub").summary.matching_hash
# [断言意图] 口径冻结锁定:对同一行集补 unit 列,历史预检(匹配)哈希不变。
assert hash_before == hash_after
@@ -218,10 +227,10 @@ def test_invoice_item_unit_column_roundtrip(transfer_db):
source_code="DBS-AWSBI",
invoice_no=invoice_no,
material_no="MAT-001",
receipt_date="2026-08-05",
movement_date="2026-08-05",
from_warehouse="DBS-TRANSIT",
to_warehouse="HUB-CN01",
receipt_quantity="100",
movement_quantity="100",
status="ready_to_execute",
unit=unit,
raw_lines_json=[],
@@ -29,7 +29,7 @@ def _executing_matching(dbs_ready_file):
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
summary = create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
for item in db.session.query(TransferInvoiceItem).all():
item.status = "executing"
item.updated_at = datetime.utcnow() - timedelta(hours=2) # 租约已过期
@@ -70,7 +70,7 @@ def test_finalize_stale_runs_marks_terminal(transfer_db, dbs_ready_file):
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
ready_items = (
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
.order_by(TransferInvoiceItem.id)
@@ -35,7 +35,7 @@ def _ready_items(dbs_ready_file, *seeds) -> tuple:
erp.seed_stock(*_INVOICE_TUPLES[invoice_no], quantity)
deps, erp, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
create_matching(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps, transfer_type="in_transit_to_hub")
items = (
TransferInvoiceItem.query.filter_by(status="ready_to_execute")
.order_by(TransferInvoiceItem.id)
@@ -1,5 +1,5 @@
"""
tests/services/shipping_notice/test_inventory_candidate_projection.py
tests/services/shipping_notice/test_onhand_candidate_projection.py
用途:验证正式 Task 的 active CandidateSet 读取、缺失阻断与版本化候选事实投影。
依赖:Flask app fixture、ShippingNotice / CandidateSet / CandidateLine ORM、候选 projector。
@@ -10,19 +10,19 @@ from __future__ import annotations
from app import db
from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingOnhandCandidateLine,
ShippingOnhandCandidateSet,
ShippingOnhandCandidateSource,
ShippingOrderTask,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingNoticeLineInventoryMatch,
ShippingInventoryFile,
ShippingNoticeLineOnhandMatch,
FreightRpaOnhandReportFile,
)
from app.services.shipping_notice.inventory_candidate_projection import (
from app.services.shipping_notice.onhand_candidate_projection import (
project_inventory_candidate_facts,
)
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
from app.services.shipping_notice.stp_line_onhand_match import prepare_candidate_onhand_lines
def _task(task_no: str) -> ShippingOrderTask:
@@ -36,8 +36,8 @@ def _task(task_no: str) -> ShippingOrderTask:
return task
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet:
row = ShippingInventoryCandidateSet(
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingOnhandCandidateSet:
row = ShippingOnhandCandidateSet(
task_id=int(task.id),
set_version=version,
lifecycle_status='frozen',
@@ -50,12 +50,12 @@ def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInvento
return row
def test_prepare_candidate_inventory_lines_blocks_without_active_set(app):
def test_prepare_candidate_onhand_lines_blocks_without_active_set(app):
with app.app_context():
task = _task('SN-CAND-001')
db.session.commit()
result = prepare_candidate_inventory_lines(task)
result = prepare_candidate_onhand_lines(task)
assert result['status'] == 'blocked'
assert result['error_code'] == 'inventory_candidates_missing'
@@ -66,13 +66,13 @@ def test_project_inventory_candidate_facts_reads_current_structured_set(app):
with app.app_context():
task = _task('SN-CAND-002')
candidate_set = _candidate_set(task, version=2)
source = ShippingInventoryCandidateSource(
source = ShippingOnhandCandidateSource(
candidate_set_id=int(candidate_set.id),
source_code='DBS_DUB',
candidate_order=1,
candidate_origin='rule',
)
line = ShippingInventoryCandidateLine(
line = ShippingOnhandCandidateLine(
candidate_set_id=int(candidate_set.id),
line_no=1,
source_line_no='00010',
@@ -99,14 +99,14 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
with app.app_context():
task = _task('SN-CAND-003')
old_set = _candidate_set(task, version=1)
old_line = ShippingInventoryCandidateLine(
old_line = ShippingOnhandCandidateLine(
candidate_set_id=int(old_set.id),
line_no=1,
source_codes_json=['DBS_OLD'],
)
db.session.add(old_line)
db.session.flush()
new_set = ShippingInventoryCandidateSet(
new_set = ShippingOnhandCandidateSet(
task_id=int(task.id),
set_version=2,
lifecycle_status='frozen',
@@ -116,7 +116,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
db.session.flush()
task.active_inventory_candidate_set_id = int(new_set.id)
db.session.flush()
new_line = ShippingInventoryCandidateLine(
new_line = ShippingOnhandCandidateLine(
candidate_set_id=int(new_set.id),
line_no=1,
source_codes_json=['DBS_NEW'],
@@ -132,7 +132,7 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
db.session.add(ShippingNoticeLineOnhandMatch(
task_id=int(task.id),
snapshot_line_id=int(snapshot_line.id),
line_no=1,
@@ -141,8 +141,8 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
candidate_set_version=1,
candidate_line_id=int(old_line.id),
match_result='matched',
inventory_status='ready',
inventory_source_code='DBS_OLD',
onhand_status='ready',
source_code='DBS_OLD',
is_current=True,
allowed_source_codes_snapshot=['DBS_OLD'],
detail_json={'disposition': 'ok'},
@@ -161,12 +161,12 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
with app.app_context():
task = _task('SN-CAND-EVIDENCE')
candidate_set = _candidate_set(task)
db.session.add(ShippingInventoryCandidateLine(
db.session.add(ShippingOnhandCandidateLine(
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
))
db.session.flush()
inventory_file = ShippingInventoryFile(
inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
inventory_file = FreightRpaOnhandReportFile(
onhand_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64,
)
db.session.add(inventory_file)
@@ -180,11 +180,11 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
db.session.add(ShippingNoticeLineOnhandMatch(
task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1,
candidate_set_id=int(candidate_set.id),
candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched',
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no,
candidate_set_version=1, onhand_snapshot_id=int(inventory_file.id), match_result='matched',
onhand_status='ready', source_code='DBS_DUB', matched_file_no=inventory_file.onhand_file_no,
matched_row_index=9, is_current=True, detail_json={},
))
db.session.commit()
@@ -0,0 +1,791 @@
"""tests/services/shipping_notice/test_onhand_report_handler.py
用途:阶段 B Task 7 修复轮——onhand 报表事实投递接线与处理函数契约测试:
单回调/批量 worker 在文件行 commit 后投递事实(先 commit 再投递、处理函数
失败外抛且文件行保留)、success 事实 settle 等待中的候选准备并同步门禁
(处理函数自行 commit、重放不重复候选行)、失败事实不发明候选行;
修复轮 2 补批量契约:单文件处理函数失败不跳过其余文件投递与排程收口、
Job 意外异常 requeue 可重试;修复轮 3 补:失败点回滚半途写(不被后续
commit 持久化)、drop 文件清理先于错误外抛、Job 重试「只重投失败文件」
通道(callback_id 已消费拦不住重投、未完成绝不返回 ok)。
依赖:app(SQLite)fixture、freight_rpa.reports.dispatch / facts、
freight_rpa.onhand.report_store(候选 settle 所绑文件行的唯一插入入口)、
onhand_rpa_workflow(回调入口 + 重试通道/专用异常)、onhand_recovery_service
(候选准备表)、jobs.handlers.freight_rpa_onhand_callback_process(Job 收口)。
逻辑:直接处理函数用例以 monkeypatch 替身 gate 同步记录调用(不断言 Gate 全链);
e2e 投递用例复用 test_shipping_notice_inventory_rpa_workflow 的动态订单/
客户确认/库存源种子 harness,跑通 rpa_report_inventory /
process_rpa_report_inventory_batch 全程后在注册表注入记录器断言事实字段;
批量失败用例以替身 finalize 记录收口调用(内部预存在 NameError 与本契约无关)。
"""
from __future__ import annotations
import pytest
from tests.conftest import inventory_xlsx_with_warehouse
@pytest.fixture
def db_session(app):
"""复用 app 夹具已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
@pytest.fixture(autouse=True)
def _fake_gate_sync(monkeypatch):
"""替身门禁同步:记录 (execution_id) 调用序列,不跑 Gate 全链(聚焦候选/提交契约)。"""
calls: list[int] = []
def _record(**kwargs):
calls.append(int(kwargs['execution'].id))
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
_record,
)
return calls
def _seed_waiting_preparation(db_session, *, task_no: str, execution_no: str):
"""构造「任务 + 活动执行 + 等待中候选准备轮次(waiting SourceAttempt)」。
Returns:
(task, execution, preparation, source_row) 四元组。
"""
from app.models import (
ShippingOnhandPreparationAttempt,
ShippingOnhandPreparationSourceAttempt,
ShippingOrderTask,
ShippingProcessExecution,
)
task = ShippingOrderTask(
task_no=task_no, user_id=1, source_type='direct_pdf', status='ready',
)
db_session.add(task)
db_session.flush()
execution = ShippingProcessExecution(
execution_no=execution_no, task_id=task.id, status='active',
)
db_session.add(execution)
db_session.flush()
task.active_process_execution_id = execution.id
preparation = ShippingOnhandPreparationAttempt(
task_id=task.id, attempt_no=1, status='waiting_external',
)
db_session.add(preparation)
db_session.flush()
source_row = ShippingOnhandPreparationSourceAttempt(
preparation_attempt_id=preparation.id, source_code='DSV360_AWSDU', status='waiting',
)
db_session.add(source_row)
db_session.commit()
return task, execution, preparation, source_row
def _onhand_file_id(*, source_code: str = 'DSV360_AWSDU') -> int:
"""经唯一插入入口 report_store 落一行 ready onhand 报表文件并 commit,返回 file_id。"""
from app import db
from app.services.freight_rpa.onhand.report_store import insert_onhand_report
from app.services.shipping_notice.onhand_file_store import generate_inventory_file_no
file_id = insert_onhand_report(
onhand_file_no=generate_inventory_file_no(),
storage_path='handler://onhand-report-fact.xlsx',
source_code=source_code,
snapshot_status='ready',
file_sha256='a' * 64,
)
db.session.commit()
return file_id
def test_onhand_fact_settles_waiting_candidates_and_syncs_gates(app, db_session, _fake_gate_sync):
"""success 事实:settle 等待候选(ready + 绑文件)→ 聚合准备轮次 → 门禁同步 → 自行 commit。"""
from app.models import ShippingOnhandPreparationAttempt, ShippingOnhandPreparationSourceAttempt
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
task, execution, preparation, source_row = _seed_waiting_preparation(
db_session, task_no='OT-ONHAND-FACT-SETTLE', execution_no='EX-ONHAND-FACT-SETTLE',
)
file_id = _onhand_file_id()
handle_onhand_report(ReportFact(
report_kind='onhand', source_code='DSV360_AWSDU',
file_id=file_id, sha256='a' * 64, ok=True,
))
# [断言意图] 处理函数必须自行 commit:rollback + expire_all 后 settle 仍可见。
db_session.rollback()
db_session.expire_all()
refreshed_source = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
assert refreshed_source.status == 'ready'
assert refreshed_source.onhand_file_id == file_id
refreshed_prep = db_session.get(ShippingOnhandPreparationAttempt, preparation.id)
assert refreshed_prep.status == 'succeeded'
assert refreshed_prep.completed_at is not None
# [断言意图] 门禁同步覆盖 settle 受影响的准备轮次任务(execution 绑定同任务)。
assert _fake_gate_sync == [execution.id]
# [重放] 同一事实重复投递:等待集已空——不重复 settle、不重复候选行(幂等)。
handle_onhand_report(ReportFact(
report_kind='onhand', source_code='DSV360_AWSDU',
file_id=file_id, sha256='a' * 64, ok=True,
))
db_session.rollback()
db_session.expire_all()
assert ShippingOnhandPreparationSourceAttempt.query.count() == 1
assert db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id).onhand_file_id == file_id
assert db_session.get(ShippingOnhandPreparationAttempt, preparation.id).status == 'succeeded'
def test_onhand_failure_fact_invents_no_candidate_rows(app, db_session, _fake_gate_sync):
"""失败/空事实:无文件可挂——不发明候选行(SourceAttempt 保持 waiting、不绑文件),仅重投影门禁。"""
from app.models import ShippingOnhandPreparationSourceAttempt
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
task, execution, preparation, source_row = _seed_waiting_preparation(
db_session, task_no='OT-ONHAND-FACT-FAIL', execution_no='EX-ONHAND-FACT-FAIL',
)
handle_onhand_report(ReportFact(
report_kind='onhand', source_code='DSV360_AWSDU',
file_id=None, sha256=None, ok=False,
error_code='rpa_export_failed', error_message='boom',
))
db_session.rollback()
db_session.expire_all()
# [断言意图] 失败事实没有文件身份:不得发明/改写候选行——仍是唯一一行、
# 状态保持 waiting、未绑定任何文件;门禁重投影(失败路径门禁更新归处理函数)。
assert ShippingOnhandPreparationSourceAttempt.query.count() == 1
refreshed = db_session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
assert refreshed.status == 'waiting'
assert refreshed.onhand_file_id is None
assert _fake_gate_sync == [execution.id]
def _seed_direct_rpa_task(db, *, task_no: str, run_no: str, sample) -> None:
"""复用动态订单 harness:直建 OT + 动态订单 + 客户确认 + 库存源种子 + RPA 触发种子。"""
from app.models import ShippingOrderTask
from tests.conftest import seed_rpa_inventory_trigger, seed_task_inventory_source
from tests.test_shipping_notice_inventory_rpa_workflow import (
_attach_dynamic_order,
_confirm_direct_rpa_task_customer,
)
task = ShippingOrderTask(
task_no=task_no, user_id=1, source_type='direct_pdf', status='ready',
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
seed_rpa_inventory_trigger(task, run_no=run_no)
db.session.add(task)
db.session.commit()
def _stub_structure_validation(monkeypatch):
"""替身结构校验:onhand_structure_drift 仍读已删站点列(Task 2 已记录的 deferred
minor,legacy 套件待 s18 改写)——与本修复无关;本测试聚焦 commit 后投递接线。
返回与真实 validate_production_inventory_structure 同形状的确定性解析参数:
field_mapping 用 conftest 种子字段 ID 对齐样例 xlsx 列头
(Warehouse ID / SKU / Reservation ID / Qty,表头行 1,默认 sheet)。
"""
from app.models import FreightRpaOnhandField
fields = {
row.field_code: row
for row in FreightRpaOnhandField.query.filter(
FreightRpaOnhandField.field_code.in_(
['part_number', 'reservation_id', 'available_qty', 'warehouse_id'],
)
)
}
structure_check = {
'field_mapping': {
str(fields['part_number'].id): 'SKU',
str(fields['reservation_id'].id): 'Reservation ID',
str(fields['available_qty'].id): 'Qty',
str(fields['warehouse_id'].id): 'Warehouse ID',
},
'header_row_index': 1,
'sheet_name': 'Sheet',
'level': 'exact',
'difference': {},
'warnings': [],
}
monkeypatch.setattr(
'app.services.shipping_notice.onhand_structure_drift.validate_production_inventory_structure',
lambda **_kwargs: structure_check,
)
def test_single_callback_dispatches_onhand_fact_after_file_commit(app, tmp_path, monkeypatch):
"""rpa_report_inventory:文件行 commit 后同请求投递 onhand 事实,字段与已提交行对齐。"""
from app import db
from app.models import FreightRpaOnhandReportFile
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory
from tests.conftest import rpa_callback_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'onhand-fact.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
seen: list[ReportFact] = []
register_report_handler('onhand', seen.append)
with app.app_context():
from app.models import ShippingOrderTask
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-DISPATCH', run_no='RUN-ONHAND-FACT', sample=sample)
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-DISPATCH').one()
result = rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT'))
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='RUN-ONHAND-FACT', snapshot_status='ready',
).first()
assert snap is not None
assert result.get('status') == 'ok'
# [断言意图] commit 后投递:恰好一条事实、字段与已提交文件行逐项对齐。
assert len(seen) == 1
fact = seen[0]
assert fact.report_kind == 'onhand'
assert fact.ok is True
assert fact.file_id == snap.id
assert fact.source_code == 'DSV360_AWSDU'
assert fact.sha256 == snap.file_sha256
# 文件行已提交:rollback 后重查仍在(先 commit 再投递的顺序契约)。
db.session.rollback()
db.session.expire_all()
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
def test_single_callback_handler_failure_propagates_and_keeps_file_row(app, tmp_path, monkeypatch):
"""处理函数抛错:异常原样外抛(不折进 post_commit_warnings),已提交文件行保留。"""
from app import db
from app.models import FreightRpaOnhandReportFile, ShippingOrderTask
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.shipping_notice.onhand_rpa_workflow import rpa_report_inventory
from tests.conftest import rpa_callback_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'onhand-fact-fail.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
def boom(_fact) -> None:
raise RuntimeError('onhand handler down')
register_report_handler('onhand', boom)
with app.app_context():
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-RAISE', run_no='RUN-ONHAND-FACT-RAISE', sample=sample)
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-FACT-RAISE').one()
# [断言意图] 异常必须外抛(供 Worker 重试整笔回调),绝不折进 warnings 后返回 ok。
with pytest.raises(RuntimeError, match='onhand handler down'):
rpa_report_inventory(rpa_callback_payload(task, sample, run_no='RUN-ONHAND-FACT-RAISE'))
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='RUN-ONHAND-FACT-RAISE', snapshot_status='ready',
).first()
assert snap is not None
db.session.rollback()
db.session.expire_all()
# [断言意图] 处理函数失败不回滚已提交文件行。
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
def test_batch_worker_dispatches_onhand_fact_after_commit(app, tmp_path, monkeypatch):
"""process_rpa_report_inventory_batch:整批事务 commit 后逐文件投递 onhand 事实。"""
from app import db
from app.models import FreightRpaOnhandReportFile
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'onhand-fact-batch.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
seen: list[ReportFact] = []
register_report_handler('onhand', seen.append)
with app.app_context():
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-FACT-BATCH', run_no='RUN-ONHAND-FACT-BATCH', sample=sample)
task_no = 'OT-ONHAND-FACT-BATCH'
result = process_rpa_report_inventory_batch(v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-FACT-BATCH',
'trigger_type': 'on_demand',
'results': [scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample), task_no=task_no,
)],
}))
assert result.get('status') == 'ok'
assert result.get('data', {}).get('success_count') == 1
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='RUN-ONHAND-FACT-BATCH', snapshot_status='ready',
).first()
assert snap is not None
# [断言意图] 整批 commit 后逐文件投递:恰一条 ok=True 事实,file_id 对齐已提交行。
assert [fact.file_id for fact in seen] == [snap.id]
assert all(fact.report_kind == 'onhand' and fact.ok is True for fact in seen)
db.session.rollback()
db.session.expire_all()
assert db.session.get(FreightRpaOnhandReportFile, snap.id) is not None
def test_batch_handler_failure_does_not_skip_remaining_dispatch_or_finalize(app, tmp_path, monkeypatch):
"""批量内单文件处理函数失败:其余已提交文件仍投递、排程收口仍执行、错误仍外抛、文件行保留。"""
from app import db
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample_a = drop_dir / 'onhand-fact-batch-a.xlsx'
sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
sample_b = drop_dir / 'onhand-fact-batch-b.xlsx'
sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
# [断言意图·观测点] 排程收口必须仍被调用(内部预存在 NameError 与本契约无关)。
finalize_calls: list = []
monkeypatch.setattr(
'app.services.schedule.freight_rpa_onhand_finalize.finalize_shipping_inventory_schedule_run',
lambda schedule_run_id, **_kwargs: (
finalize_calls.append(schedule_run_id)
or {'ok': True, 'schedule_finalize_status': 'finalized'}
),
)
# [断言意图·观测点] 首个文件处理函数失败,第二个必须照常收到事实。
seen: list[ReportFact] = []
calls = {'n': 0}
def flaky(fact: ReportFact) -> None:
calls['n'] += 1
seen.append(fact)
if calls['n'] == 1:
raise RuntimeError('onhand handler down mid-batch')
register_report_handler('onhand', flaky)
with app.app_context():
_stub_structure_validation(monkeypatch)
task = ScheduleTask(
schedule_no='SCH-ONHAND-BATCH-FAIL', name='Onhand batch fail', schedule_type='platform_job',
platform_api_path='freight-rpa-onhand', owner_user_id=1, cron_expr='0 8 * * *',
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no='RUN-ONHAND-BATCH-FAIL', schedule_task_id=task.id, status='running',
total_count=2, success_count=0, failed_count=0, skipped_count=0,
response_summary_json={'awaiting_rpa': True},
)
db.session.add(run)
db.session.commit()
# [断言意图] 处理函数异常必须外抛(调用方/Job 见到失败)——但不得因此跳过
# 其余文件投递与排程收口(断言在 pytest.raises 之后进行)。
with pytest.raises(RuntimeError, match='onhand handler down mid-batch'):
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-BATCH-FAIL',
'schedule_run_id': run.id,
'trigger_type': 'scheduled',
'results': [
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-BATCH-FAIL-A',
),
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-BATCH-FAIL-B',
),
],
}))
snaps = FreightRpaOnhandReportFile.query.filter(
FreightRpaOnhandReportFile.snapshot_status == 'ready',
FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B')),
).order_by(FreightRpaOnhandReportFile.id).all()
# [断言意图] 两个文件行都已落库并保留(commit 先于投递,失败不回滚)。
assert [snap.rpa_run_no for snap in snaps] == ['SR-BATCH-FAIL-A', 'SR-BATCH-FAIL-B']
# [断言意图] 两个文件的事实都投递了(首文件失败不跳过次文件投递)。
assert [fact.file_id for fact in seen] == [snap.id for snap in snaps]
# [断言意图] 排程收口仍执行(不被处理函数失败跳过)。
assert finalize_calls == [run.id]
db.session.rollback()
db.session.expire_all()
assert {db.session.get(FreightRpaOnhandReportFile, snap.id) is not None for snap in snaps} == {True}
def test_callback_process_job_requeues_on_unexpected_exception(app, monkeypatch):
"""Job 意外异常(含批量 commit 后处理函数失败重抛)必须可重试 requeue,而非终态 failed。"""
from app import db
from app.jobs.context import JobContext
from app.jobs.handlers import freight_rpa_onhand_callback_process as handler
from app.models import Job
with app.app_context():
job = Job(
domain='shipping_notice',
job_type='freight_rpa_onhand_callback_process',
status='running',
attempts=1,
max_attempts=3,
business_ref='inventory-callback:retryable-check',
payload_json={'callback_id': 'retryable-check'},
)
db.session.add(job)
db.session.commit()
def _boom(_payload):
raise RuntimeError('dispatch re-raise after commit')
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch',
_boom,
)
handler.run_shipping_inventory_callback_process(
JobContext(config={}, logger=None, extras={}), {'job_id': job.id},
)
db_session = db.session
db_session.expire_all()
# [断言意图] retryable=True → requeue(attempts 未耗尽时回到 queued 等待重试),
# 绝不落终态 failed——批量文件行已提交,重放按幂等契约补齐收口。
refreshed = db_session.get(Job, job.id)
assert refreshed.status == 'queued'
def test_batch_handler_failure_rolls_back_partial_writes_and_next_file_dispatches(app, db_session, tmp_path, monkeypatch):
"""批量内处理函数「先 bind 候选再抛错」:半途 flush 写必须回滚(不得被后续 commit 持久化),次文件照常投递。"""
from app import db
from app.models import FreightRpaOnhandReportFile, ShippingOnhandPreparationSourceAttempt
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_report_handler import handle_onhand_report
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample_a = drop_dir / 'rollback-a.xlsx'
sample_a.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
sample_b = drop_dir / 'rollback-b.xlsx'
sample_b.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
seen: list[ReportFact] = []
calls = {'n': 0}
def bind_then_raise_or_settle(fact: ReportFact) -> None:
calls['n'] += 1
seen.append(fact)
if calls['n'] == 1:
# [RED 场景] 模拟「先 bind 候选再抛错」的处理函数:半途 flush(不 commit)。
from app.models import ShippingOnhandPreparationSourceAttempt as _Row
row = (
_Row.query.filter_by(source_code='DSV360_AWSDU')
.order_by(_Row.id)
.first()
)
row.status = 'ready'
row.onhand_file_id = int(fact.file_id)
db.session.flush()
raise RuntimeError('bind then raise mid-batch')
# 次文件走真实处理函数:内部 settle(等待集)→ 门禁同步 → 自行 commit。
handle_onhand_report(fact)
register_report_handler('onhand', bind_then_raise_or_settle)
with app.app_context():
_stub_structure_validation(monkeypatch)
_task, _execution, _preparation, source_row = _seed_waiting_preparation(
db_session, task_no='OT-ONHAND-ROLLBACK', execution_no='EX-ONHAND-ROLLBACK',
)
with pytest.raises(RuntimeError, match='bind then raise mid-batch'):
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-ROLLBACK',
'trigger_type': 'on_demand',
'results': [
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample_a), source_run_no='SR-ROLLBACK-A',
),
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample_b), source_run_no='SR-ROLLBACK-B',
),
],
}))
snaps = FreightRpaOnhandReportFile.query.filter(
FreightRpaOnhandReportFile.snapshot_status == 'ready',
FreightRpaOnhandReportFile.rpa_run_no.in_(('SR-ROLLBACK-A', 'SR-ROLLBACK-B')),
).order_by(FreightRpaOnhandReportFile.id).all()
# [断言意图] 次文件照常投递:两个已提交文件的事实都送达处理函数。
assert [fact.file_id for fact in seen] == [snap.id for snap in snaps]
db.session.rollback()
db.session.expire_all()
# [断言意图] 首文件半途 bind 已回滚——不得被次文件处理函数的 commit 持久化成
# file-A 绑定;次文件真实 settle 落到 file B(等待集在回滚后原样可 settle)。
refreshed = db.session.get(ShippingOnhandPreparationSourceAttempt, source_row.id)
assert refreshed.status == 'ready'
assert refreshed.onhand_file_id == snaps[1].id
def test_batch_handler_failure_still_flushes_drop_file_cleanup_before_raise(app, tmp_path, monkeypatch):
"""处理函数抛错:drop 文件清理(消费标记+移动/入队)必须先于错误外抛完成。"""
from app import db
from app.models import FreightRpaOnhandReportFile
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.shipping_notice.onhand_rpa_workflow import process_rpa_report_inventory_batch
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'cleanup-before-raise.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
def boom(_fact) -> None:
raise RuntimeError('onhand handler down cleanup')
register_report_handler('onhand', boom)
with app.app_context():
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-CLEANUP', run_no='RUN-ONHAND-CLEANUP', sample=sample)
with pytest.raises(RuntimeError, match='onhand handler down cleanup'):
process_rpa_report_inventory_batch(v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-CLEANUP',
'trigger_type': 'on_demand',
'results': [scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-CLEANUP',
)],
}))
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='RUN-ONHAND-CLEANUP', snapshot_status='ready',
).first()
assert snap is not None
# [断言意图] 错误已外抛,但 drop 文件清理先行完成:消费标记/移动先于重抛,
# 文件离开 drop 根、落入 processed 归档(移动失败时则入持久化 cleanup 队列)。
assert not sample.exists()
assert (drop_dir / 'processed' / sample.name).exists()
def test_batch_retry_channel_redispatches_file_despite_consumed_callback_id(app, tmp_path, monkeypatch):
"""重试通道:task-linked 项 Attempt 已消费 callback_id(整批重放必被跳过)时,失败文件仍重投事实。"""
from datetime import datetime
from app import db
from app.models import FreightRpaOnhandReportFile, ShippingOrderTask, FreightRpaOnhandTaskAttempt
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.shipping_notice.onhand_rpa_workflow import (
OnhandReportDispatchAfterCommitError,
process_rpa_report_inventory_batch,
)
from tests.conftest import scheduled_rpa_batch_item, v2_inventory_batch_payload
drop_dir = tmp_path / 'drop'
drop_dir.mkdir()
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
sample = drop_dir / 'retry-callback-id.xlsx'
sample.write_bytes(inventory_xlsx_with_warehouse('AWSDU').getvalue())
seen: list[ReportFact] = []
calls = {'n': 0}
def flaky(fact: ReportFact) -> None:
calls['n'] += 1
seen.append(fact)
if calls['n'] == 1:
raise RuntimeError('onhand handler down first pass')
register_report_handler('onhand', flaky)
with app.app_context():
_stub_structure_validation(monkeypatch)
_seed_direct_rpa_task(db, task_no='OT-ONHAND-RETRY', run_no='RUN-ONHAND-RETRY', sample=sample)
task = ShippingOrderTask.query.filter_by(task_no='OT-ONHAND-RETRY').one()
candidate_set_id = int(task.active_inventory_candidate_set_id or 1)
# [RED 场景] 结构化 per-source Attempt(v2 身份字段与回调 item 对齐):
# pass 1 的回调确认会把 attempt.callback_id 写入——整批重放随即被 replay 检查跳过。
# source_run_no 用与批量 run_no 不同的 PSR 轮次号(与真实 Worker 形态一致:
# run_no=批量轮次、source_run_no=逐源轮次——run_no 消费标记按 source_run_no
# 匹配,不会误吞本 Attempt)。
attempt = FreightRpaOnhandTaskAttempt(
task_no='OT-ONHAND-RETRY',
source_code='DSV360_AWSDU',
attempt_no=1,
source_run_no='PSR-ONHAND-RETRY-1',
status='queued',
triggered_at=datetime.utcnow(),
lease_token='test-lease-token',
execution_phase='trigger_written',
extra_json={
'trigger_mode': 'test',
'candidate_set_id': candidate_set_id,
'execution_id': 1,
'gate_id': 1,
},
)
db.session.add(attempt)
db.session.commit()
batch_payload = v2_inventory_batch_payload({
'run_no': 'RUN-ONHAND-RETRY',
'trigger_type': 'on_demand',
'results': [dict(
scheduled_rpa_batch_item(
'DSV360_AWSDU', success=True, file_path=str(sample), task_no='OT-ONHAND-RETRY',
),
callback_id='test-callback:RUN-ONHAND-RETRY',
source_run_no='PSR-ONHAND-RETRY-1',
attempt_no=1,
lease_token='test-lease-token',
candidate_set_id=candidate_set_id,
execution_id=1,
gate_id=1,
)],
})
# [STEP 1] 首轮:文件落地+回调确认(写 callback_id)+投递失败 → 专用异常携带清单外抛。
with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo:
process_rpa_report_inventory_batch(batch_payload)
snap = FreightRpaOnhandReportFile.query.filter_by(
rpa_run_no='PSR-ONHAND-RETRY-1', snapshot_status='ready',
).first()
assert snap is not None
assert excinfo.value.failed_files == [{
'source_code': 'DSV360_AWSDU',
'file_id': snap.id,
'sha256': (snap.file_sha256 or None),
}]
# [断言意图·RED 场景] Attempt 已消费 callback_id——整批重放会被 replay 检查跳过。
db.session.expire(attempt)
assert str(attempt.callback_id or '').strip()
armed_callback_id = str(attempt.callback_id)
# [STEP 2] 整批重放(不带重试清单):item 被 replay 检查跳过——不落地、不投递,
# 证明整批重放无法补投(这正是「只重投失败文件」通道存在的原因)。
replay_result = process_rpa_report_inventory_batch(dict(batch_payload))
assert [fact.file_id for fact in seen] == [snap.id]
assert replay_result.get('data', {}).get('created') == []
assert armed_callback_id == str(
FreightRpaOnhandTaskAttempt.query.filter_by(
task_no='OT-ONHAND-RETRY', source_code='DSV360_AWSDU',
).order_by(FreightRpaOnhandTaskAttempt.id.desc()).first().callback_id or '',
)
# [STEP 3] 重试通道(Job 处理器写回的 retry_dispatch_files):只重投失败文件。
retry_payload = {**batch_payload, 'retry_dispatch_files': excinfo.value.failed_files}
result = process_rpa_report_inventory_batch(retry_payload)
assert result.get('status') == 'ok'
assert result.get('data', {}).get('result_status') == 'retried'
# [断言意图] 同一 file_id 的事实再次送达处理函数(callback_id 已消费拦不住重投)。
assert [fact.file_id for fact in seen] == [snap.id, snap.id]
def test_batch_retry_channel_reraises_while_handler_still_failing(app, monkeypatch):
"""重试通道:处理函数仍未成功时必须继续携带清单重抛,绝不在未完成时返回 ok。"""
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.shipping_notice.onhand_rpa_workflow import (
OnhandReportDispatchAfterCommitError,
process_rpa_report_inventory_batch,
)
def boom(_fact) -> None:
raise RuntimeError('onhand handler still down')
register_report_handler('onhand', boom)
with app.app_context():
file_id = _onhand_file_id()
marker = {'source_code': 'DSV360_AWSDU', 'file_id': file_id, 'sha256': None}
# [断言意图] 处理函数持续失败:重试通道继续抛专用异常(携带同一未成功清单,
# Job 据此继续 requeue 直至 attempts 耗尽落终态 failed)——绝不返回 ok。
with pytest.raises(OnhandReportDispatchAfterCommitError) as excinfo:
process_rpa_report_inventory_batch({'retry_dispatch_files': [marker]})
assert excinfo.value.failed_files == [marker]
def test_callback_process_job_records_failed_files_for_retry(app, monkeypatch):
"""Job 收口:投递失败重抛的清单写回 payload(retry_dispatch_files)并 requeue 可重试。"""
from app import db
from app.jobs.context import JobContext
from app.jobs.handlers import freight_rpa_onhand_callback_process as handler
from app.models import Job
from app.services.shipping_notice.onhand_rpa_workflow import OnhandReportDispatchAfterCommitError
marker = {'source_code': 'DSV360_AWSDU', 'file_id': 4242, 'sha256': 'a' * 64}
with app.app_context():
job = Job(
domain='shipping_notice',
job_type='freight_rpa_onhand_callback_process',
status='running',
attempts=1,
max_attempts=3,
business_ref='inventory-callback:dispatch-retry-check',
payload_json={'callback_id': 'dispatch-retry-check'},
)
db.session.add(job)
db.session.commit()
def _raise_dispatch_error(_payload):
raise OnhandReportDispatchAfterCommitError(
'onhand handler down after commit', failed_files=[dict(marker)],
)
monkeypatch.setattr(
'app.services.shipping_notice.onhand_rpa_workflow.process_rpa_report_inventory_batch',
_raise_dispatch_error,
)
handler.run_shipping_inventory_callback_process(
JobContext(config={}, logger=None, extras={}), {'job_id': job.id},
)
db.session.expire_all()
# [断言意图] 清单写回 payload(重试只重投这些文件)+ requeue 可重试。
refreshed = db.session.get(Job, job.id)
assert refreshed.status == 'queued'
assert refreshed.payload_json['retry_dispatch_files'] == [marker]
@@ -418,7 +418,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta
facts = _project_case_formal_gate_facts({
'current_gate': {
'gate_code': 'inventory_source_routing',
'gate_code': 'onhand_source_routing',
'status': 'pending',
'blocking_reason_code': None,
'next_action_code': None,
@@ -430,7 +430,7 @@ def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_ta
assert facts is not None
current_gate, blocking_reason, user_status = facts
assert current_gate['gate_code'] == 'inventory_source_routing'
assert current_gate['gate_code'] == 'onhand_source_routing'
assert blocking_reason['code'] is None
assert user_status == 'running'
@@ -0,0 +1,32 @@
"""
tests/services/shipping_notice/test_report_model_boundary.py
用途:阶段 B Task 5 边界门禁——禁止发货域(shipping_notice)源码直接构造
货代 RPA 报表模型行(FreightRpaOnhandReportFile / FreightRpaInboundReportFile /
FreightRpaInboundReportConfig 的构造调用)。插入必须经
freight_rpa/onhand/report_store,读取/下载必须走 freight_rpa/reports 查询面。
依赖:无运行时依赖(纯文件系统扫描);backend/app/services/shipping_notice 源码。
逻辑:rglob 全部 *.py 逐文件搜禁词构造片段;命中即失败并列出文件与片段,
保证违规时能一眼定位,而不是只报一个计数。
"""
from __future__ import annotations
from pathlib import Path
import pytest
pytestmark = pytest.mark.pure_unit
def test_shipping_notice_does_not_construct_rpa_report_rows():
root = Path(__file__).resolve().parents[3] / "app" / "services" / "shipping_notice"
banned_snippets = ("FreightRpaOnhandReportFile(", "FreightRpaInboundReportFile(", "FreightRpaInboundReportConfig(")
hits = []
for path in root.rglob("*.py"):
text = path.read_text(encoding="utf-8")
for snippet in banned_snippets:
if snippet in text:
hits.append(f"{path.name}: {snippet}")
# 关键断言:三类 RPA 报表行的构造调用必须全部消失(插入已收敛进 report_store)。
assert hits == []
@@ -0,0 +1,204 @@
"""
tests/test_admin_freight_rpa_onhand_config.py
用途:锁定 s18 后库存站点启用门禁与在手报表配置行(FreightRpaOnhandReportConfig)的服务层行为。
依赖:conftest 的 app fixture(建表并播种 TEST_RUNTIME 配置)、app.core.errors.ValidationError、
freight_rpa_source_admin_service(assert_onhand_source_can_enable / save_onhand_report_config)、
freight_rpa_report_config_service.save_inbound_report_config、
FreightRpaOnhandReportConfig / FreightRpaSource 等模型。
逻辑:验证启用中站点缺模板/缺配置行/缺解析绑定时 fail-closed;保存在手配置只写配置行、
不写站点已删除的三列,并递增配置行 config_version;在手与入站两侧解析方案 purpose 互斥。
"""
from __future__ import annotations
import itertools
import pytest
from app.core.errors import ValidationError
from app.models import (
FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaParsingProfile, FreightRpaProfile,
)
from app.services.admin.freight_rpa_report_config_service import save_inbound_report_config
from app.services.admin.freight_rpa_source_admin_service import (
assert_onhand_source_can_enable, save_onhand_report_config,
)
# 站点/连接编码自增,保证同一测试内多次构造不撞唯一约束。
_SOURCE_SEQUENCE = itertools.count(1)
@pytest.fixture
def db_session(app):
"""复用 app fixture 已建立的应用上下文会话,供测试直接落库与查询。"""
from app import db
return db.session
def _source(*, enabled: bool, excel_template_id: int | None) -> FreightRpaSource:
"""构造最小可落库的库存站点(fixed 仓库模式 + 专用连接 Profile),不自动 add 进会话。
Args:
enabled: 站点启用位;True 时调用方需自行保证模板/配置满足门禁或预期拒绝。
excel_template_id: 发货模板外键;SQLite 测试库不强制外键,允许指向不存在的模板 id。
Returns:
FreightRpaSource: 未加入会话的站点对象,由调用方决定是否落库。
"""
from app import db
sequence = next(_SOURCE_SEQUENCE)
profile = FreightRpaProfile(
profile_code=f'TASK2_PROFILE_{sequence}', display_name=f'Task2 Profile {sequence}',
connector_type='dbs', login_url='https://test.invalid/dbs',
login_config_json={'auth_mode': 'password'},
)
db.session.add(profile)
db.session.flush()
return FreightRpaSource(
source_code=f'TASK2_SOURCE_{sequence}', display_name=f'Task2 Source {sequence}',
connector_type='dbs', rpa_profile_id=profile.id, excel_template_id=excel_template_id,
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSDU',
enabled=enabled,
)
def _published_onhand_profile_id() -> int:
"""读取 conftest 播种的已发布在手解析方案(TEST_RUNTIME,purpose='onhand')。"""
profile = FreightRpaParsingProfile.query.filter_by(
profile_code='TEST_RUNTIME', status='published',
).first()
assert profile is not None and profile.purpose == 'onhand'
return profile.id
def _published_inbound_profile_id(db_session) -> int:
"""创建最小已发布入站解析方案,用于验证在手侧 fail-closed 拒绝跨 purpose 绑定。"""
profile = FreightRpaParsingProfile(
purpose='inbound', profile_code='TASK2_INBOUND', display_name='Task2 Inbound',
version=1, status='published', file_format='xlsx', definition_json={'field_mapping': {}},
)
db_session.add(profile)
db_session.commit()
return profile.id
def test_enabled_source_requires_onhand_profile_and_template(app, db_session):
"""启用中站点缺发货模板必须被服务层拒绝。
[断言意图] 该状态同时违反 ck_freight_rpa_sources_enabled_template(enabled ⇒ 模板非空),
SQLite/PG 在 INSERT 时即拦截、无法落库,故按 save_source 提交前的调用形态验证未落库对象,
与任务书原测试语义一致(服务层门禁先于数据库约束给出可解释错误码)。
"""
source = _source(enabled=True, excel_template_id=None)
with pytest.raises(ValidationError) as exc:
assert_onhand_source_can_enable(source)
assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED"
def test_enabled_source_requires_onhand_report_config_row(app, db_session):
"""启用中站点缺在手配置行时拒绝启用:配置行缺失是跨表状态,站点 CHECK 管不到。"""
source = _source(enabled=True, excel_template_id=9)
db_session.add(source)
db_session.commit()
with pytest.raises(ValidationError) as exc:
assert_onhand_source_can_enable(source)
assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED"
def test_enabled_source_requires_onhand_profile_binding(app, db_session):
"""配置行存在但未绑解析方案时同样拒绝启用。"""
source = _source(enabled=True, excel_template_id=9)
db_session.add(source)
db_session.commit()
db_session.add(FreightRpaOnhandReportConfig(source=source))
db_session.commit()
with pytest.raises(ValidationError) as exc:
assert_onhand_source_can_enable(source)
assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED"
def test_enabled_source_with_full_onhand_config_passes_gate(app, db_session):
"""配置行 + 解析绑定 + 模板齐备的启用站点通过门禁(正向路径回归)。"""
source = _source(enabled=True, excel_template_id=9)
db_session.add(source)
db_session.commit()
db_session.add(FreightRpaOnhandReportConfig(
source=source, parsing_profile_id=_published_onhand_profile_id(),
))
db_session.commit()
assert assert_onhand_source_can_enable(source) is None
def test_save_onhand_report_config_does_not_write_source_columns(app, db_session):
"""保存在手配置只写配置行,不写站点已删除的 report_path_json 等三列。"""
source = _source(enabled=False, excel_template_id=9)
db_session.add(source)
db_session.commit()
save_onhand_report_config(source.id, {
"report_path_json": {"menu": "stock"},
"query_parameters_json": [],
"parsing_profile_id": _published_onhand_profile_id(),
}, actor_id=1)
db_session.refresh(source)
assert not hasattr(source, "report_path_json")
config = FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).one()
assert config.report_path_json == {"menu": "stock"}
assert config.parsing_profile.purpose == "onhand"
def test_save_onhand_report_config_updates_row_and_bumps_config_version(app, db_session):
"""已有配置行走更新并递增 config_version,行身份保持不变。"""
source = _source(enabled=False, excel_template_id=9)
db_session.add(source)
db_session.commit()
first = save_onhand_report_config(source.id, {
"report_path_json": {"menu": "stock"},
"query_parameters_json": [],
"parsing_profile_id": _published_onhand_profile_id(),
}, actor_id=1)
second = save_onhand_report_config(source.id, {
"report_path_json": {"menu": "stock2"},
"query_parameters_json": [],
"parsing_profile_id": _published_onhand_profile_id(),
}, actor_id=1)
assert second["id"] == first["id"]
row = FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).one()
assert row.report_path_json == {"menu": "stock2"}
# [断言意图] 首次插入默认 1,第二次保存必须递增为 2(任务书:有则更新并递增 config_version)。
assert row.config_version == 2
def test_save_onhand_report_config_rejects_non_onhand_parsing_profile(app, db_session):
"""入站解析方案不得绑进在手配置;fail-closed 且不留下半写的配置行。"""
source = _source(enabled=False, excel_template_id=9)
db_session.add(source)
db_session.commit()
with pytest.raises(ValidationError) as exc:
save_onhand_report_config(source.id, {
"report_path_json": {},
"query_parameters_json": [],
"parsing_profile_id": _published_inbound_profile_id(db_session),
}, actor_id=1)
assert exc.value.code == "SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED"
assert FreightRpaOnhandReportConfig.query.filter_by(source_id=source.id).count() == 0
def test_save_inbound_report_config_keeps_inbound_only_binding(app, db_session):
"""入站配置保存继续只接受 purpose='inbound' 的解析方案(在手/入站互斥回归)。"""
source = _source(enabled=False, excel_template_id=9)
db_session.add(source)
db_session.commit()
with pytest.raises(ValidationError) as exc:
save_inbound_report_config(source.id, {
# 先给合法 DBS 四段路径,确保失败点落在解析绑定校验(purpose 互斥)而非路径校验。
"report_path_json": {
"program_group": "Bison", "program_label": "AWSBI",
"report_group": "Inbound", "report_name": "Receipt Detail",
},
"query_parameters_json": [],
"parsing_profile_id": _published_onhand_profile_id(),
}, actor_id=1)
assert exc.value.code == "SHIPPING.INBOUND_PROFILE_INVALID"
@@ -0,0 +1,87 @@
"""
tests/test_admin_freight_rpa_routes.py
用途:锁定货代 RPA 管理路由已迁到 /api/admin/freight-rpa/,旧 shipping-notice 管理路径 404。
依赖:Flask 测试客户端、admin blueprint、User。
逻辑:只断言路径注册与管理员可达;权限表存量字符串不在本测试更新。
"""
from __future__ import annotations
def _headers(username: str, role: str) -> dict[str, str]:
"""构造遗留 Header 认证上下文,匹配现有管理 API 测试方式。"""
return {'X-Username': username, 'X-Role': role}
def _rules(app) -> set[str]:
"""收集已注册的 URL 规则,用来断言旧路径没有双路由。"""
return {rule.rule for rule in app.url_map.iter_rules()}
def test_freight_rpa_admin_routes_moved_and_old_paths_404(app, client):
"""新 sources 路径对管理员成功;旧 sources 与 inventory-fields 404;onhand/fields 已注册。"""
from app import db
from app.models import User
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
db.session.add(User(
username='freight-rpa-admin',
email='freight-rpa-admin@example.com',
role='admin',
status='active',
))
db.session.commit()
headers = _headers('freight-rpa-admin', 'admin')
listed = client.get('/api/admin/freight-rpa/sources', headers=headers)
# [断言意图] 管理员读取新 sources 列表必须走统一成功 envelope。
assert listed.status_code == 200
body = listed.get_json()
assert body['success'] is True
assert isinstance(body['data'], list)
# [断言意图] 旧库存源路径无兼容路由。
assert client.get('/api/admin/shipping-notice/sources', headers=headers).status_code == 404
# [断言意图] 旧字段目录路径无兼容路由。
assert client.get('/api/admin/shipping-notice/inventory-fields', headers=headers).status_code == 404
rules = _rules(app)
# [断言意图] 字段目录已挂到 onhand/fields,且旧规则不在 url map。
assert '/api/admin/freight-rpa/onhand/fields' in rules
assert '/api/admin/shipping-notice/inventory-fields' not in rules
assert '/api/admin/shipping-notice/sources' not in rules
# [断言意图] 任务表里的旧前缀都不能再注册(含其子路径)。
retired_prefixes = (
'/api/admin/shipping-notice/sources',
'/api/admin/shipping-notice/source-validation-batches',
'/api/admin/shipping-notice/snapshots',
'/api/admin/shipping-notice/export-records',
'/api/admin/shipping-notice/routing-rules',
'/api/admin/shipping-notice/routing-fields',
'/api/admin/shipping-notice/inventory-fields',
'/api/admin/shipping-notice/configuration-catalog',
'/api/admin/shipping-notice/parsing-profiles',
'/api/admin/shipping-notice/inventory-structure-analyses',
'/api/admin/shipping-notice/external-mappings',
)
for rule in rules:
for prefix in retired_prefixes:
assert rule != prefix and not rule.startswith(prefix + '/'), rule
assert '/api/admin/freight-rpa/sources/<int:source_id>/inbound-report-config' in rules
assert '/api/admin/freight-rpa/onhand/validation-batches' in rules
fields = client.get('/api/admin/freight-rpa/onhand/fields', headers=headers)
assert fields.status_code == 200
assert fields.get_json()['success'] is True
# [断言意图] 临时会话只改词根,仍留在 shipping-notice;Excel 模板不动;异动字段归 freight-rpa。
assert '/api/admin/shipping-notice/temporary-onhand-sessions' in rules
assert '/api/admin/shipping-notice/temporary-inventory-sessions' not in rules
assert '/api/admin/shipping-notice/excel-templates' in rules
assert '/api/admin/freight-rpa/movement-fields' in rules
assert '/api/admin/shipping-notice/movement-fields' not in rules
# [断言意图] rpa-profiles 仍在 freight-rpa,不重复注册到 shipping-notice。
assert '/api/admin/freight-rpa/rpa-profiles' in rules
assert '/api/admin/shipping-notice/rpa-profiles' not in rules
+7 -4
View File
@@ -1,7 +1,7 @@
"""
标准异动字段目录接口测试。
用途:验证 GET /api/admin/shipping-notice/movement-fields 下发只读领域契约。
用途:验证 GET /api/admin/freight-rpa/movement-fields 下发只读领域契约。
依赖:Flask 管理 API、movement_contract 契约常量。
逻辑:字段目录是 immutable 常量的投影——码/类型/必填/身份标记与契约逐项一致,
不提供任何增删改入口,字段 label 由前端 i18n 渲染。
@@ -18,7 +18,8 @@ def _headers() -> dict[str, str]:
def test_movement_fields_returns_fixed_catalog(app, client):
"""标准异动字段目录:10 个定死字段、顺序稳定、必填/身份标记与契约一致。"""
"""标准异动字段目录:18 个定死字段(11 核心 + 2026-10-14 扩展 7 可选维度)、
顺序稳定、必填/身份标记与契约一致。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
from app.models import User
@@ -26,13 +27,15 @@ def test_movement_fields_returns_fixed_catalog(app, client):
db.session.add(User(username='movement-admin', email='movement-admin@example.com', role='admin', status='active'))
db.session.commit()
response = client.get('/api/admin/shipping-notice/movement-fields', headers=_headers())
response = client.get('/api/admin/freight-rpa/movement-fields', headers=_headers())
assert response.status_code == 200
data = parse_api_data(response.get_json())
# [断言意图] 字段码与顺序是前后端共同契约——后端 movement_contract 变更必须显式同步本断言。
assert [field['code'] for field in data] == [
'doc_no', 'line_no', 'in_out_flag', 'material_code', 'material_name',
'warehouse_code', 'storage_code', 'lot_no', 'quantity', 'movement_date',
'unit',
'line_seq', 'specification', 'order_type', 'odm_id', 'odm_name', 'carton_id', 'pallet_id',
]
required = {field['code'] for field in data if field['required']}
assert required == {'doc_no', 'material_code', 'quantity', 'movement_date'}
@@ -50,7 +53,7 @@ def test_movement_fields_rejects_non_admin(app, client):
db.session.add(User(username='movement-user', email='movement-user@example.com', role='user', status='active'))
db.session.commit()
response = client.get('/api/admin/shipping-notice/movement-fields', headers={
response = client.get('/api/admin/freight-rpa/movement-fields', headers={
'X-Username': 'movement-user', 'X-Role': 'user', 'Content-Type': 'application/json',
})
assert response.status_code == 403
@@ -26,7 +26,7 @@ from app.models import (
ShippingOrderExtraction,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingNoticeLineInventoryMatch,
ShippingNoticeLineOnhandMatch,
ShippingNotice,
User,
)
@@ -148,12 +148,12 @@ def _notice_with_customer(*, task_no: str, customer_id: int, business_no: str |
)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
db.session.add(ShippingNoticeLineOnhandMatch(
task_id=task.id,
snapshot_line_id=snapshot_line.id,
line_no=1,
match_result='matched',
inventory_status='ready',
onhand_status='ready',
is_current=True,
))
notice = ShippingNotice(task_no=task_no, business_no=business_no, order_task_id=task.id)
+29 -27
View File
@@ -1,9 +1,9 @@
"""
tests/test_admin_shipping_inventory.py
用途:验证货代库存后台的只读快照/导出记录接口及管理员权限。
用途:验证货代 RPA 管理端只读快照/导出记录、配置目录与站点保存接口。
依赖:Flask 测试客户端、库存文件和排程运行模型。
逻辑:库存快照来自库存文件;没有库存文件的失败 RPA 运行也必须出现在导出记录中。
逻辑:请求打到 /api/admin/freight-rpa/;快照来自在手文件,失败排程即使没有文件也出现在导出记录中。
"""
from __future__ import annotations
@@ -12,8 +12,8 @@ from datetime import datetime
from pathlib import Path
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventoryFile, User
from app.models import ShippingInventorySource, ShippingRpaProfile
from app.models import ScheduleRun, ScheduleTask, FreightRpaOnhandReportFile, User
from app.models import FreightRpaSource, FreightRpaProfile
from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import parse_api_data, parse_api_error
@@ -39,14 +39,14 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p
_create_users()
snapshot_file = Path(tmp_path) / 'snapshot.xlsx'
snapshot_file.write_bytes(b'admin-snapshot')
file_record = ShippingInventoryFile(
inventory_file_no='SIF-ADMIN-READY', storage_path=str(snapshot_file), source_code='DBS_DUB',
file_record = FreightRpaOnhandReportFile(
onhand_file_no='SIF-ADMIN-READY', storage_path=str(snapshot_file), source_code='DBS_DUB',
warehouse_id='DUB', snapshot_status='ready', identity_status='verified',
exported_at=datetime(2026, 7, 17, 10, 0, 0), rpa_run_no='RUN-READY-01',
)
schedule_task = ScheduleTask(
schedule_no='SCH-INVENTORY-FAILED', name='Inventory Export', schedule_type='platform_job',
owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='shipping-inventory-rpa',
owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='freight-rpa-onhand',
)
db.session.add_all([file_record, schedule_task])
db.session.flush()
@@ -57,23 +57,23 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p
))
db.session.commit()
for path in ('/api/admin/shipping-notice/snapshots', '/api/admin/shipping-notice/export-records'):
for path in ('/api/admin/freight-rpa/onhand/snapshots', '/api/admin/freight-rpa/onhand/export-records'):
forbidden = client.get(path, headers=_headers('inventory-user', 'user'))
assert forbidden.status_code == 403
assert parse_api_error(forbidden.get_json())['code'] == 'AUTH.FORBIDDEN'
snapshots = client.get('/api/admin/shipping-notice/snapshots', headers=_headers('inventory-admin', 'admin'))
snapshots = client.get('/api/admin/freight-rpa/onhand/snapshots', headers=_headers('inventory-admin', 'admin'))
assert snapshots.status_code == 200
snapshot_rows = parse_api_data(snapshots.get_json())
assert snapshot_rows[0]['inventory_file_no'] == 'SIF-ADMIN-READY'
assert 'storage_path' not in snapshot_rows[0]
assert snapshot_rows[0]['download_available'] is True
downloaded = client.get('/api/admin/shipping-notice/snapshots/1/download', headers=_headers('inventory-admin', 'admin'))
downloaded = client.get('/api/admin/freight-rpa/onhand/snapshots/1/download', headers=_headers('inventory-admin', 'admin'))
assert downloaded.status_code == 200
assert downloaded.data == b'admin-snapshot'
exports = client.get('/api/admin/shipping-notice/export-records', headers=_headers('inventory-admin', 'admin'))
exports = client.get('/api/admin/freight-rpa/onhand/export-records', headers=_headers('inventory-admin', 'admin'))
assert exports.status_code == 200
export_rows = parse_api_data(exports.get_json())
failed_row = next(item for item in export_rows if item['rpa_run_no'] == 'RUN-FAILED-01')
@@ -104,7 +104,7 @@ def test_inventory_configuration_catalog_is_admin_only_and_backend_controlled(ap
}], 'expected_lock_version': draft['lock_version']})
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
path = '/api/admin/shipping-notice/configuration-catalog'
path = '/api/admin/freight-rpa/onhand/configuration-catalog'
forbidden = client.get(path, headers=_headers('inventory-user', 'user'))
assert forbidden.status_code == 403
@@ -128,8 +128,8 @@ def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app
order_schema_service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
for path in (
'/api/admin/shipping-notice/routing-fields',
'/api/admin/shipping-notice/configuration-catalog',
'/api/admin/freight-rpa/onhand/routing-fields',
'/api/admin/freight-rpa/onhand/configuration-catalog',
):
response = client.get(path, headers=_headers('inventory-admin', 'admin'))
assert response.status_code == 200
@@ -139,11 +139,11 @@ def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app
def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_missing_steps(app, client):
"""管理端普通保存不允许跳过测试直接启用,独立启用接口应返回业务缺失项。"""
"""管理端普通保存不允许直接启用;独立启用接口只返回硬门槛缺失项,不含配置测试。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
profile = ShippingRpaProfile(
profile = FreightRpaProfile(
profile_code='API_ACTIVATION_LOGIN', display_name='API Activation', connector_type='dbs',
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
)
@@ -162,20 +162,22 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
},
'query_parameters_json': [],
}
created = client.post('/api/admin/shipping-notice/sources', json=payload, headers=_headers('inventory-admin', 'admin'))
created = client.post('/api/admin/freight-rpa/sources', json=payload, headers=_headers('inventory-admin', 'admin'))
assert created.status_code == 201
source = parse_api_data(created.get_json())
assert source['enabled'] is False
assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
# 关键断言:配置测试已退出启用门禁,缺失项只剩解析方案与发货模板。
assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template']
assert 'configuration_test' not in {item['code'] for item in source['activation']['checks']}
activation = client.post(
f"/api/admin/shipping-notice/sources/{source['id']}/activate",
f"/api/admin/freight-rpa/sources/{source['id']}/activate",
json={}, headers=_headers('inventory-admin', 'admin'),
)
assert activation.status_code == 409
error = parse_api_error(activation.get_json())
assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
assert error['code'] == 'SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED'
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template']
def test_latest_inventory_configuration_test_is_admin_only(app, client):
@@ -183,25 +185,25 @@ def test_latest_inventory_configuration_test_is_admin_only(app, client):
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
profile = ShippingRpaProfile(
profile = FreightRpaProfile(
profile_code='API_LATEST_TEST_LOGIN', display_name='Latest Test', connector_type='dbs',
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
)
db.session.add(profile)
source = ShippingInventorySource(
# s18 起站点行不再承载报表路径/查询条件;本用例只验证权限与空 envelope,无需配置行。
source = FreightRpaSource(
source_code='API_LATEST_TEST_SOURCE', display_name='Latest Test Source', connector_type='dbs',
rpa_profile=profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
query_parameters_json=[], enabled=False,
enabled=False,
)
db.session.add(source)
db.session.commit()
source_id = source.id
forbidden = client.get(f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest')
forbidden = client.get(f'/api/admin/freight-rpa/sources/{source_id}/test-export/latest')
assert forbidden.status_code in {401, 403}
response = client.get(
f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest',
f'/api/admin/freight-rpa/sources/{source_id}/test-export/latest',
headers=_headers('inventory-admin', 'admin'),
)
assert response.status_code == 200
@@ -1,14 +1,16 @@
"""
收料报表配置管理接口测试。
用途:验证站点内独立收料配置的权限、DBS/Crane 规则及不可影响库存配置的边界。
用途:验证站点内独立入站报表配置的权限、DBS/Crane 规则及不可影响在手配置的边界。
依赖:Flask 管理 API、库存站点测试种子、货代统一审计事件。
逻辑:配置保存只更新 shipping_receipt_report_configs,并留存前后快照审计。
逻辑:请求打到 /api/admin/freight-rpa/sources/<id>/inbound-report-config;保存只更新入站配置并留存前后快照审计。
"""
from __future__ import annotations
from app.models import ShippingAuditEvent, ShippingInventorySource, User
import pytest
from app.models import ShippingAuditEvent, FreightRpaSource, User
from tests.conftest import parse_api_data, parse_api_error
@@ -47,21 +49,23 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
# s18 起在手报表路径/查询条件归 onhand_report_config 配置行,站点行不再承载。
onhand_config = source.onhand_report_config
inventory_before = {
'path': dict(source.report_path_json), 'parameters': list(source.query_parameters_json),
'path': dict(onhand_config.report_path_json), 'parameters': list(onhand_config.query_parameters_json),
'config_version': source.config_version,
}
forbidden = client.put(
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
json=_dbs_payload(), headers=_headers('receipt-user', 'user'),
)
assert forbidden.status_code == 403
response = client.put(
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
json=_dbs_payload(), headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 200
@@ -72,13 +76,14 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
assert config['report_path_json']['report_group'] == 'Inbound'
with app.app_context():
source = ShippingInventorySource.query.get(source_id)
# 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义。
assert source.report_path_json == inventory_before['path']
assert source.query_parameters_json == inventory_before['parameters']
source = FreightRpaSource.query.get(source_id)
# 关键断言:收料配置不会借由站点抽屉保存改写库存 RPA 定义(s18 起读配置行)。
onhand_config = source.onhand_report_config
assert onhand_config.report_path_json == inventory_before['path']
assert onhand_config.query_parameters_json == inventory_before['parameters']
assert source.config_version == inventory_before['config_version']
audit = ShippingAuditEvent.query.filter_by(
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
event_type='shipping_inbound_report_config_saved', aggregate_id=str(source_id),
).one()
assert audit.before_snapshot_json is None
assert audit.after_snapshot_json['query_parameters_json'][0]['values'] == ['AWSDU', 'AWSDU-02']
@@ -89,17 +94,18 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
dbs_id = dbs.id
from app import db
crane_profile = dbs.rpa_profile.__class__(
profile_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane',
login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'},
)
crane_source = ShippingInventorySource(
# s18 起站点行不再承载报表路径/查询条件;收料配置测试无需在手配置行。
crane_source = FreightRpaSource(
source_code='CRANE_RECEIPT_CFG', display_name='Crane Receipt', connector_type='crane',
rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE',
report_path_json={}, query_parameters_json=[], enabled=False,
enabled=False,
)
db.session.add(crane_source)
db.session.commit()
@@ -108,26 +114,26 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
invalid_date = _dbs_payload()
invalid_date['query_parameters_json'] = [{'name': 'Report Date', 'mode': 'single', 'values': ['2026-08-19'], 'required': False, 'select_all': False}]
response = client.put(
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config',
json=invalid_date, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID'
invalid_selector = _dbs_payload()
invalid_selector['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': [], 'selector': '#owner'}]
response = client.put(
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config',
json=invalid_selector, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID'
# 关键断言:Warehouse 条件由管理员自行维护——缺失/空值允许保存,不再强制拦截。
missing_warehouse = _dbs_payload()
missing_warehouse['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}]
response = client.put(
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config',
json=missing_warehouse, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 200
@@ -137,7 +143,7 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
empty_warehouse = _dbs_payload()
empty_warehouse['query_parameters_json'] = [{'name': 'Warehouse', 'mode': 'multi_text', 'values': [], 'required': False, 'select_all': False}]
response = client.put(
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{dbs_id}/inbound-report-config',
json=empty_warehouse, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 200
@@ -149,19 +155,19 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
'query_parameters_json': [],
}
response = client.put(
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config',
json=invalid_crane, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID'
def _create_movement_profile(profile_code: str, *, status: str, purpose: str):
"""创建异动/库存解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
def _create_parsing_profile(profile_code: str, *, status: str, purpose: str):
"""创建入站/在手解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
from app import db
from app.models import ShippingInventoryParsingProfile
from app.models import FreightRpaParsingProfile
profile = ShippingInventoryParsingProfile(
profile = FreightRpaParsingProfile(
purpose=purpose, profile_code=profile_code, display_name=f'{profile_code} 规则',
version=1, status=status, file_format='xlsx',
definition_json={'sheet_name': 'Movement', 'header_row_index': 1,
@@ -174,19 +180,19 @@ def _create_movement_profile(profile_code: str, *, status: str, purpose: str):
return profile
def test_receipt_config_binds_published_movement_profile(app, client):
"""绑定已发布 movement 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。"""
def test_receipt_config_binds_published_inbound_profile(app, client):
"""绑定已发布 inbound 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
profile = _create_movement_profile('CRANE_MOVE_STD', status='published', purpose='movement')
profile = _create_parsing_profile('CRANE_MOVE_STD', status='published', purpose='inbound')
profile_id = profile.id
payload = {**_dbs_payload(), 'parsing_profile_id': profile_id}
response = client.put(
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
json=payload, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 200
@@ -198,31 +204,31 @@ def test_receipt_config_binds_published_movement_profile(app, client):
from app.models import ShippingAuditEvent
audit = ShippingAuditEvent.query.filter_by(
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
event_type='shipping_inbound_report_config_saved', aggregate_id=str(source_id),
).order_by(ShippingAuditEvent.id.desc()).first()
assert audit.metadata_json['parsing_profile_id'] == profile_id
def test_receipt_config_rejects_draft_or_non_movement_profile(app, client):
"""draft/库存用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。"""
def test_receipt_config_rejects_draft_or_non_inbound_profile(app, client):
"""draft/在手用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
draft = _create_movement_profile('MOVE_DRAFT', status='draft', purpose='movement')
inventory_profile = _create_movement_profile('INV_PUBLISHED', status='published', purpose='inventory')
cases = [draft.id, inventory_profile.id, 999999]
draft = _create_parsing_profile('MOVE_DRAFT', status='draft', purpose='inbound')
onhand_profile = _create_parsing_profile('INV_PUBLISHED', status='published', purpose='onhand')
cases = [draft.id, onhand_profile.id, 999999]
for profile_id in cases:
response = client.put(
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 400, f'profile_id={profile_id}'
# 关键断言:非"已发布 movement"绑定必须走统一错误码,fail-closed。
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID'
# 关键断言:非"已发布 inbound"绑定必须走统一错误码,fail-closed。
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.INBOUND_PROFILE_INVALID'
def test_receipt_config_empty_profile_id_unbinds(app, client):
@@ -230,20 +236,20 @@ def test_receipt_config_empty_profile_id_unbinds(app, client):
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
source_id = source.id
profile = _create_movement_profile('MOVE_UNBIND', status='published', purpose='movement')
profile = _create_parsing_profile('MOVE_UNBIND', status='published', purpose='inbound')
profile_id = profile.id
bound = client.put(
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
headers=_headers('receipt-admin', 'admin'),
)
assert bound.status_code == 200
unbound = client.put(
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{source_id}/inbound-report-config',
json={**_dbs_payload(), 'parsing_profile_id': None},
headers=_headers('receipt-admin', 'admin'),
)
@@ -258,15 +264,16 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
with app.app_context():
_create_users()
from app import db
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
dbs = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
crane_profile = dbs.rpa_profile.__class__(
profile_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane',
login_url='https://crane.example.invalid', login_config_json={'auth_mode': 'password'},
)
crane_source = ShippingInventorySource(
# s18 起站点行不再承载报表路径/查询条件;收料配置测试无需在手配置行。
crane_source = FreightRpaSource(
source_code='CRANE_RECEIPT_DEFAULT_CFG', display_name='Crane Receipt Defaults', connector_type='crane',
rpa_profile=crane_profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE',
report_path_json={}, query_parameters_json=[], enabled=False,
enabled=False,
)
db.session.add(crane_source)
db.session.commit()
@@ -277,7 +284,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
'query_parameters_json': [],
}
response = client.put(
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config',
json=default_query, headers=_headers('receipt-admin', 'admin'),
)
assert response.status_code == 200
@@ -287,8 +294,41 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
{'name': 'material', 'mode': 'single', 'values': ['PN-01'], 'required': False, 'select_all': False},
]}
rejected = client.put(
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
f'/api/admin/freight-rpa/sources/{crane_id}/inbound-report-config',
json=configured, headers=_headers('receipt-admin', 'admin'),
)
assert rejected.status_code == 400
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.INBOUND_REPORT_CONFIG_INVALID'
def test_retire_rejects_profile_bound_by_receipt_report_config(app):
"""绑定收料报表配置的 published 解析 Profile 退役必须被拒(退役守卫补查)。
背景:retire 此前只核查库存源(FreightRpaSource)绑定,遗漏了
收料报表配置(FreightRpaInboundReportConfig.parsing_profile_id)——入站文件
解析链会因规则退役静默失去规则。守卫补查后两者任一绑定都返回
SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED。
"""
from app import db
from app.models import FreightRpaInboundReportConfig
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
source = FreightRpaSource.query.filter_by(source_code='DSV360_AWSDU').one()
profile = _create_parsing_profile('MOVE_RETIRE_GUARD', status='published', purpose='inbound')
db.session.add(FreightRpaInboundReportConfig(
source_id=source.id, parsing_profile_id=profile.id,
report_path_json={}, query_parameters_json=[],
))
db.session.commit()
profile_id = profile.id
# 关键断言:仅绑定收料配置(无库存源绑定)也必须拒绝退役,沿用既有错误码。
with pytest.raises(Exception) as exc_info:
onhand_parsing_profile.retire(profile_id)
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED'
# 关键断言:被拒后 Profile 状态保持 published,不得被半退役。
assert FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile_id).count() == 1
+3 -2
View File
@@ -14,6 +14,7 @@ import pytest
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
from app.services.chat.router import FastRouteResult, try_fast_route
from app.services.faq_cache import FaqCacheMatch
@pytest.fixture(autouse=True)
@@ -42,11 +43,11 @@ def _user(**kwargs):
def test_try_fast_route_faq_cache(monkeypatch):
"""FAQ 命中时应返回 faq_cache 路由。"""
faq_entry = object()
faq_match = FaqCacheMatch(entry=object(), match_type='exact', match_score=1.0, matched_text='常见问题')
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.try_match',
staticmethod(lambda query, agent_id: faq_entry),
staticmethod(lambda query, agent_id: faq_match),
)
monkeypatch.setattr(
'app.services.faq_cache.FaqCacheService.stream_chat',
+1 -1
View File
@@ -197,7 +197,7 @@ def test_chat_turn_task_inventory_upload_uses_formal_inventory_handler(app, clie
}
monkeypatch.setattr(
'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_inventory_file',
'app.services.shipping_notice.chat_action_extended_handlers.shipping_tools.upload_onhand_file',
fake_upload_inventory,
)
res = client.post(
@@ -4,6 +4,7 @@ backend/tests/test_contract_payment_ledger_focus.py
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、进行中、本月应付合同后核对计数与 focus 筛选。
金额和比例都为 0 的验收款不把合同算进逾期。
"""
from __future__ import annotations
@@ -12,7 +13,7 @@ from datetime import date
from app import db
from app.models import Agent, ContractPaymentContract, ContractPaymentNode, User
from app.services.contract_payment.ledger_focus import ledger_focus_counts
from app.services.contract_payment.ledger_focus import classify_ledger_status, ledger_focus_counts
def _create_user(*, username: str) -> User:
@@ -136,3 +137,37 @@ def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
assert summary.get_json()['data']['active'] == 2
assert 'needs_completion' not in summary.get_json()['data']
assert empty.get_json()['data']['total'] == 0
def test_zero_amount_stage_does_not_mark_contract_overdue():
"""金额和比例都为 0 的阶段不参与逾期。"""
status = classify_ledger_status(
contract_status='active',
parse_status='parsed',
nodes=[
{
'status': 'paid',
'percentage': '50',
'amount': '4250.00',
'due_date': date(2026, 9, 2),
'anchor_date': date(2026, 9, 2),
},
{
'status': 'active',
'percentage': '0',
'amount': '0.00',
'due_date': date(2026, 9, 24),
'anchor_date': date(2026, 9, 24),
},
{
'status': 'active',
'percentage': '0',
'amount': '0.00',
'due_date': date(2027, 3, 23),
'anchor_date': date(2026, 9, 24),
},
],
today=date(2026, 10, 27),
)
# 关键断言:预付款已付,验收款和质保款为 0,合同应为已完成而不是已逾期。
assert status == 'completed'
+8 -1
View File
@@ -915,7 +915,14 @@ def test_erp_combined_payment_marks_prepayment_and_shipment_paid():
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
def test_oa_company_dropdown_uses_selected_option(app):
def test_erp_payment_matches_acceptance_amount_without_consuming_earlier_stages():
"""关键断言:验收款金额单独命中时只标验收款,不把预付款或出货款记成已付。"""
nodes = [
(1, "prepayment", Decimal("16740")),
(2, "shipment", Decimal("27900")),
(3, "acceptance", Decimal("11160")),
]
assert resolve_paid_node_ids(nodes, [Decimal("11160")]) == {3}
"""关键断言:公司下拉框只取 selected 项,不把全部候选项拼进公司名。"""
page = """
<table><tr>
+145 -24
View File
@@ -39,30 +39,48 @@ class _FakeLocator:
class _FakePage:
def __init__(self, *, url: str = "https://wms-portal.craneww.com/#/") -> None:
def __init__(
self,
*,
url: str = "https://wms-portal.craneww.com/#/",
visible_tokens: tuple[str, ...] = ("on-hand-details-query", "On Hand Details", "Queries", "navbar"),
visible_role_names: tuple[str, ...] = ("On Hand Details", "Queries"),
) -> None:
self.url = url
self.frames: list[_FakePage] = []
self.goto_calls: list[str] = []
self.evaluate_calls: list[tuple[str, object]] = []
self.reload_calls: list[int] = []
self.locator_selectors: list[str] = []
self._visible_tokens = visible_tokens
self._visible_role_names = visible_role_names
def locator(self, selector: str) -> _FakeLocator:
if "on-hand-details-query" in selector or "On Hand Details" in selector:
return _FakeLocator(visible=True)
if "Queries" in selector or "navbar" in selector:
return _FakeLocator(visible=True)
return _FakeLocator(visible=False)
self.locator_selectors.append(selector)
visible = any(token in selector for token in self._visible_tokens)
return _FakeLocator(visible=visible)
def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator:
if role == "link" and name in {"On Hand Details", "Queries"}:
return _FakeLocator(visible=True)
return _FakeLocator(visible=False)
return _FakeLocator(visible=name in self._visible_role_names)
def goto(self, url: str, wait_until: str = "", timeout: int = 0) -> None:
self.goto_calls.append(url)
self.url = url
def reload(self, wait_until: str = "", timeout: int = 0) -> None:
self.reload_calls.append(1)
def evaluate(self, script: str, arg: object = None) -> None:
self.evaluate_calls.append((script, arg))
if isinstance(arg, str):
self.url = f"https://wms-portal.craneww.com/#/{arg.lstrip('/')}"
def wait_for_load_state(self, state: str = "", timeout: int = 0) -> None:
return None
def test_navigate_prefers_dashboard_tile(monkeypatch):
"""应优先尝试首页 On Hand Details 卡片。"""
"""应优先尝试首页目标报表卡片。"""
module = _load_navigation()
page = _FakePage()
calls: list[str] = []
@@ -70,10 +88,10 @@ def test_navigate_prefers_dashboard_tile(monkeypatch):
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
monkeypatch.setattr(
module,
"_click_dashboard_on_hand_details",
"_click_dashboard_report_tile",
lambda *args, **kwargs: calls.append("dashboard") or True,
)
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: calls.append("navbar") or True)
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: calls.append("navbar") or True)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
mode = module.navigate_to_crane_report(
@@ -95,8 +113,8 @@ def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch):
wait_calls = {"n": 0}
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: True)
def _wait(page_arg, entry_url, *, browser_timeout_ms):
wait_calls["n"] += 1
@@ -115,22 +133,59 @@ def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch):
assert wait_calls["n"] == 2
def test_navigate_uses_direct_goto_as_last_resort(monkeypatch):
"""卡片与菜单均失败时应 goto entry_url。"""
def test_direct_goto_last_resort_assigns_hash_in_place(monkeypatch):
"""卡片与菜单均失败后:goto entry_url 未就绪时只允许就地赋 hash,禁止回根地址。"""
module = _load_navigation()
page = _FakePage()
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
entry = "https://wms-portal.craneww.com/#/outbound-details-query"
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: False)
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: False)
def _wait(page_arg, entry_url_arg, *, browser_timeout_ms):
# [断言意图] 就地赋 hash 之后表单才视为就绪;此前一律未就绪
return len(page.evaluate_calls) > 0
monkeypatch.setattr(module, "_wait_for_report_navigation", _wait)
mode = module.navigate_to_crane_report(
page,
entry,
env=lambda name, default="": default,
browser_timeout_ms=5_000,
)
assert mode == "direct_goto"
assert page.goto_calls == [entry]
assert page.reload_calls == []
assert not any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
assert page.evaluate_calls and "outbound-details-query" in str(page.evaluate_calls[0][1])
def test_navigation_never_lands_on_origin_when_form_never_ready(monkeypatch):
"""表单始终未就绪也应抛 RuntimeError,且全程不得 goto 根地址或 reload(会强制登出)。"""
module = _load_navigation()
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
entry = "https://wms-portal.craneww.com/#/outbound-details-query"
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
monkeypatch.setattr(module, "_click_dashboard_report_tile", lambda *args, **kwargs: False)
monkeypatch.setattr(module, "_click_navbar_report_item", lambda *args, **kwargs: False)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: False)
with pytest.raises(RuntimeError, match="navigation failed"):
module.navigate_to_crane_report(page, entry, env=lambda n, d="": d, browser_timeout_ms=5_000)
module.navigate_to_crane_report(
page,
entry,
env=lambda name, default="": default,
browser_timeout_ms=5_000,
)
assert page.goto_calls[0] == entry
assert any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
# [断言意图] 失败收场也只允许一次 goto(entry):根地址/reload 一旦发生即登出
assert page.goto_calls == [entry]
assert page.reload_calls == []
assert not any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
def test_is_crane_on_report_route_reads_entry_hash():
@@ -157,3 +212,69 @@ def test_report_route_without_controls_is_not_ready(monkeypatch):
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
monkeypatch.setattr(module, "_has_report_form_controls", lambda page_arg: False)
assert module.is_crane_report_form_ready(page, entry) is False
@pytest.mark.parametrize(
("route", "label"),
(
("on-hand-details-query", "On Hand Details"),
("inbound-details-query", "Inbound Details"),
("outbound-details-query", "Outbound Details"),
),
)
def test_navigate_targets_tile_by_entry_route(route, label, monkeypatch):
"""首页卡片/菜单选择器必须由 entry 路由推导,禁止硬编码 On Hand Details。"""
module = _load_navigation()
# [构造] 门户对授权用户渲染目标报表卡片:当前路由/标签的选择器可见
page = _FakePage(
url="https://wms-portal.craneww.com/#/",
visible_tokens=(route, label, "Queries"),
)
entry = f"https://wms-portal.craneww.com/#/{route}"
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
mode = module.navigate_to_crane_report(
page,
entry,
env=lambda name, default="": default,
browser_timeout_ms=5_000,
)
assert mode == "dashboard_tile"
joined = "\n".join(page.locator_selectors)
assert label in joined
# [断言意图] 出站/入站导航不得再查询 On Hand Details 选择器(2026-10-20 死循环根因之一);
# 路由推导由 test_direct_goto_last_resort(evaluate 参数)单独覆盖
for other in {"On Hand Details", "Inbound Details", "Outbound Details"} - {label}:
assert other not in joined
def test_navbar_fallback_uses_entry_route_label(monkeypatch):
"""首页卡片不可见时,经 Queries 菜单点击的路由项也须由 entry 推导。"""
module = _load_navigation()
# [构造] 卡片全部不可见(token 只含 navbar),仅 Queries 下拉项可见;
# 首页等待用短超时避免 shell 未就绪时白等 5s
page = _FakePage(
url="https://wms-portal.craneww.com/#/",
visible_tokens=("navbar",),
visible_role_names=("Queries",),
)
entry = "https://wms-portal.craneww.com/#/outbound-details-query"
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url_arg: False)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
mode = module.navigate_to_crane_report(
page,
entry,
env=lambda name, default="": default,
browser_timeout_ms=1_000,
)
assert mode == "navbar_menu"
joined = "\n".join(page.locator_selectors)
# [断言意图] 菜单回退路径同样按 entry 推导标签,禁止再查询 On Hand Details 选择器
assert '.navbar-dropdown a.navbar-item:has-text("Outbound Details")' in joined
assert "On Hand Details" not in joined
+23
View File
@@ -599,6 +599,29 @@ def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_p
assert fallback_called["value"] is False
def test_refresh_scheduled_reports_list_never_reloads_page(monkeypatch):
"""列表 goto 刷新失败时就地重赋 hash;登录态下禁止 page.reload(Crane 门户刷新即登出)。"""
module = _load_export()
page = MagicMock()
page.url = "https://wms-portal.craneww.com/#/scheduled-reports"
page.goto.side_effect = RuntimeError("net::ERR_ABORTED")
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
monkeypatch.setattr(module, "_scheduled_reports_table_visible", lambda *_a, **_k: True)
monkeypatch.setattr(module, "_wait_for_scheduled_reports_list_ready", lambda *_a, **_k: True)
module._refresh_scheduled_reports_list(
page,
env=lambda name, default="": default,
browser_timeout_ms=5_000,
entry_url="https://wms-portal.craneww.com/#/outbound-details-query",
)
# [断言意图] goto 失败的兜底是就地 hash 重赋;reload 一次都不允许发生
page.reload.assert_not_called()
assert page.evaluate.called
def test_row_matches_scheduled_report_normalizes_name_form(monkeypatch):
"""行名 InboundDetails.xlsx 与期望名 Inbound Details 应规范化后相等(收料轮询 not found 根因)。"""
module = _load_export()
+1 -1
View File
@@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
"""batch 内 session 有效时不应重复 goto + login。"""
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
assert spec and spec.loader
worker = importlib.util.module_from_spec(spec)
@@ -22,7 +22,7 @@ from app.models import (
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingExportArtifact,
ShippingInventoryParsingProfile,
FreightRpaParsingProfile,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderExtraction,
@@ -154,7 +154,7 @@ def _attach_ready_export_artifact(notice: ShippingNotice) -> None:
from app.models import ShippingOrderSchemaVersion, ShippingOrderExtraction
template = _template_row()
profile = ShippingInventoryParsingProfile(
profile = FreightRpaParsingProfile(
profile_code='REBIND_PROFILE', display_name='Rebind profile', version=1, status='published',
file_format='xlsx', definition_json={},
)
+143 -5
View File
@@ -217,6 +217,26 @@ def test_resolve_parameter_controls_receipt_detail_awsrtm_warehouse_multi_value(
assert module.resolve_parameter_controls("Receipt Detail", "Warehouse")["control"] == "select"
def test_resolve_parameter_controls_shipment_order_detail_owner_and_warehouse():
"""出站 Shipment Order Detail 的 Owner/Warehouse 应按实机 DOM 使用 multi_value,而不是库存默认 select。"""
module = _load_module()
owner = module.resolve_parameter_controls("Shipment Order Detail", "Owner")
warehouse = module.resolve_parameter_controls("Shipment Order Detail", "Warehouse")
# 关键断言:2026-10-19 AWS/Bison/AWSBI 实机——Owner ctl15、Warehouse ctl31,均为 txtValue 下拉。
assert owner == {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
}
assert warehouse == {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl31_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl31_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl31_divDropDown",
}
def test_resolve_parameter_controls_unknown_report_empty():
"""未登记报表名应返回空配置,由调用方回退参数名默认值(保持旧行为)。"""
module = _load_module()
@@ -326,10 +346,12 @@ def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value():
report_name="On Hand Inventory by Location",
)
assert payloads, "应进入多选框下拉填充路径而不是无痕失败"
# payloads 会混入结构性解析传入的 label 字符串("Warehouse"),只断言 dict 载荷。
dict_payloads = [p for p in payloads if isinstance(p, dict)]
assert dict_payloads, "应进入多选框下拉填充路径而不是无痕失败"
assert any(
payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl17_divDropDown"
for payload in payloads
for payload in dict_payloads
), f"应命中 JDA ctl17 multi_value dropdown,实际 payloads={payloads!r}"
@@ -431,10 +453,12 @@ def test_fill_dsv_filter_if_needed_receipt_awsrtm_uses_ctl29_multi_value():
program_label="AWSRTM",
)
assert payloads, "应进入 AWSRTM multi_value 填充路径"
# payloads 会混入结构性解析传入的 label 字符串,只断言 dict 载荷。
dict_payloads = [p for p in payloads if isinstance(p, dict)]
assert dict_payloads, "应进入 AWSRTM multi_value 填充路径"
assert any(
payload.get("dropdownSelector") == "#ReportViewerMain_ctl08_ctl29_divDropDown"
for payload in payloads
for payload in dict_payloads
), f"应命中 ctl29 multi_value dropdown,实际 payloads={payloads!r}"
@@ -471,14 +495,20 @@ class _RecordingPage:
_STRUCTURAL_CONTROLS = {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
}
_STRUCTURAL_SELECT = {
"control": "select",
"selector": "#ReportViewerMain_ctl08_ctl19_ddValue",
}
def test_structural_resolver_hit_returns_controls_and_trims_label():
"""命中 frame 返回三件套;label 先 trim 再传入页面脚本。"""
"""命中 frame 返回 multi_value 三件套(含 control);label 先 trim 再传入页面脚本。"""
module = _load_module()
early = _RecordingFrame(result=None)
hit = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
@@ -490,6 +520,22 @@ def test_structural_resolver_hit_returns_controls_and_trims_label():
assert hit.calls == ["Owner"]
def test_structural_resolver_select_via_label_for_returns_ddvalue():
"""Cincinnati CVG611 形态:label[for]=ctl19_ddValue 时返回 select,禁止再当 multi_value。
[断言意图] 2026-10-20 事故回归——Warehouse 是原生 select,不得落到 ctl17_txtValue
(已漂移为 Project ID)文本兜底。
"""
module = _load_module()
hit = _RecordingFrame(result=dict(_STRUCTURAL_SELECT))
page = _RecordingPage([hit])
got = module.resolve_parameter_controls_structural(page, "Warehouse")
assert got == _STRUCTURAL_SELECT
assert hit.calls == ["Warehouse"]
def test_structural_resolver_all_frames_miss_or_error_returns_none():
"""全部 frame 未命中或探测异常(跨域/销毁帧):返回 None 交调用方回退。"""
module = _load_module()
@@ -596,6 +642,98 @@ def test_fill_multi_select_structural_preferred_registry_is_fallback(monkeypatch
assert probed.calls == ["Warehouse"]
def test_fill_warehouse_uses_structural_select_not_stale_txtvalue(monkeypatch, capsys):
"""Warehouse 结构性命中 select 时走 ddValue,禁止 JDA 模板 ctl17_txtValue 文本兜底。
[断言意图] 复现 2026-10-20 Cincinnati:模板仍写 multi_value@ctl17,但页面 Warehouse
是 ctl19_ddValue;不得把 BYAWSCV611 写进漂移后的 Project ID。
"""
module = _load_module()
page = _RecordingPage([_RecordingFrame(result=dict(_STRUCTURAL_SELECT))])
selected: dict[str, str] = {}
class _FakeText:
first = None
def __init__(self) -> None:
self.first = self
def is_visible(self, timeout: int | None = None) -> bool:
return False
page.get_by_text = lambda text, exact=False: _FakeText() # type: ignore[attr-defined]
def _fake_select(page_obj, label, value, selector, *, timeout_ms):
selected["selector"] = selector
selected["value"] = value
return True
def _fake_multi(*_a, **_k):
raise AssertionError("select 形态不得走 multi_value")
monkeypatch.setattr(module, "_fill_select_parameter", _fake_select)
monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_multi)
ok = module.fill_dsv_filter_if_needed(
page,
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse",
"BYAWSCV611",
env=lambda name, default="": default,
browser_timeout_ms=lambda: 3_000,
report_name="On Hand Inventory By Location",
program_label="CVG611",
)
assert ok is True
assert selected == {
"selector": "#ReportViewerMain_ctl08_ctl19_ddValue",
"value": "BYAWSCV611",
}
captured = capsys.readouterr()
assert "ctl17_txtValue" not in captured.out + captured.err
def test_fill_warehouse_refuses_stale_txtvalue_when_structural_miss(monkeypatch, capsys):
"""结构性未命中且模板 multi_value 失败时:Warehouse 拒绝 txtValue 文本兜底并返回 False。"""
module = _load_module()
page = _RecordingPage([_RecordingFrame(result=None)])
class _FakeText:
first = None
def __init__(self) -> None:
self.first = self
def is_visible(self, timeout: int | None = None) -> bool:
return False
page.get_by_text = lambda text, exact=False: _FakeText() # type: ignore[attr-defined]
monkeypatch.setattr(module, "_fill_multi_value_parameter", lambda *_a, **_k: False)
monkeypatch.setattr(module, "_probe_report_parameter_controls", lambda *_a, **_k: {"controls": []})
filled_via_script: list[str] = []
monkeypatch.setattr(
module,
"_fill_input_via_script",
lambda root, selector, text: filled_via_script.append(selector) or True,
)
ok = module.fill_dsv_filter_if_needed(
page,
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse",
"BYAWSCV611",
env=lambda name, default="": default,
browser_timeout_ms=lambda: 3_000,
report_name="On Hand Inventory By Location",
)
assert ok is False
assert filled_via_script == []
captured = capsys.readouterr()
assert "refusing stale txtValue fallback" in captured.err
def test_multi_value_already_set_set_equality_not_substring():
"""2026-10-08 Owner@AWSRTM 事故根因回归:SSRS 多选框默认全选,txtValue 恒为全量 CSV,
目标值必为该 CSV 的子串——必须用集合相等判定,子串包含会恒误判"已设置"并跳过下拉勾选。"""
Loaded 100 of 959 files, more files were not shown because too many files have changed in this diff. Show more