feat(in-transit-transfer): 调拨类型配置化与库存异动档原子切换

调拨类型从四处硬编码升级为管理页可配置:范围规则(受控字段白名单,规则间且/值间或)、
仓库定义(映射档/固定仓双模式角色解析)、字段转换(批号前缀替换,匹配时快照固化到 scope_json)。

新建 transfer_movement_ledger 库存异动档(参照 ERP inaj_t):自然键幂等增量落档
(插入/换证更新/跳过/缺席不删/执行封存永不触碰),圈档互斥保证一条档记录一生只绑一次明细;
收料证据落地改写档、停写 items。transfer_invoice_items 出生翻转为匹配时从档圈定创建
(一次匹配永久写入 matching_id+ledger_record_id),回查对账/取消释放/执行门禁/待匹配桶全链路适配。

迁移 tt10→tt13 单 head:类型配置表、异动档、items 档外键、transfer_runs.transfer_type 放宽 String(64)。

随行披露:设计文档与实施计划、ADR 0001/0002、in-transit-transfer 术语表、
demand/funclist/technical 文档更新同批入库。
This commit is contained in:
hugo committed 2026-10-15 13:02:17 +08:00
1 parent 28d6085d07
commit 52c71ee46a
78 files changed
+7423 -1702

No files matched your search

@@ -25,6 +25,14 @@ def _jwt_headers(user: User) -> dict:
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
@pytest.fixture(autouse=True)
def _seed_transfer_type(app):
"""类型配置化(Task 11/D8):API 域用例预置默认启用类型(匹配创建必填)。"""
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)。
@@ -114,7 +122,7 @@ def test_create_matching_returns_envelope_with_matching_id(app, client, admin_he
"""POST /matchings → 201 envelope,data 含 matching_id/hash/计数。"""
response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"
})
assert response.status_code == 201
body = response.get_json()
@@ -129,7 +137,7 @@ def test_create_matching_returns_envelope_with_matching_id(app, client, admin_he
def test_create_matching_requires_authentication(client):
"""未认证 → 401(envelope error)。"""
response = client.post(f"{API_PREFIX}/matchings", json={"source_codes": ["DBS-AWSBI"]})
response = client.post(f"{API_PREFIX}/matchings", json={"source_codes": ["DBS-AWSBI"], "transfer_type": "in_transit_to_hub"})
assert response.status_code == 401
assert response.get_json()["success"] is False
@@ -137,7 +145,7 @@ def test_create_matching_requires_authentication(client):
def test_create_matching_forbidden_without_agent_permission(client, unauthorized_headers):
"""无 in_transit_transfer Agent 权限 → 403。"""
response = client.post(f"{API_PREFIX}/matchings", headers=unauthorized_headers, json={
"source_codes": ["DBS-AWSBI"],
"source_codes": ["DBS-AWSBI"], "transfer_type": "in_transit_to_hub"
})
assert response.status_code == 403
assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN"
@@ -147,7 +155,7 @@ def test_create_matching_warehouse_manager_allowed(app, client, warehouse_header
"""持有 Agent 权限的仓库管理员可创建匹配。"""
response = client.post(f"{API_PREFIX}/matchings", headers=warehouse_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"
})
assert response.status_code == 201
assert response.get_json()["data"]["matching_id"]
@@ -155,13 +163,13 @@ def test_create_matching_warehouse_manager_allowed(app, client, warehouse_header
def test_create_matching_validates_source_codes(app, client, admin_headers, transfer_deps):
"""缺少 source_codes → 400 参数错误。"""
response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={"business_date": "2026-08-06"})
response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"})
assert response.status_code == 400
assert response.get_json()["success"] is False
def test_create_matching_accepts_transfer_type_and_rejects_placeholder(app, client, admin_headers, transfer_deps):
"""transfer_type 合法值放行;占位类型(类型2/3)与非法值 → 400 fail-closed。"""
"""transfer_type 合法值放行;未配置编码 → 422 NOT_CONFIGURED(D8/规格 §11)。"""
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
@@ -169,21 +177,38 @@ def test_create_matching_accepts_transfer_type_and_rejects_placeholder(app, clie
})
assert created.status_code == 201
# [语义平移] 旧「占位类型/非法值 NOT_SUPPORTED/INVALID」随配置化退役:
# 类型合法值=配置表 code,无此码统一 NOT_CONFIGURED(启用/停用门禁见服务用例)。
for bad_type in ("hub_repair_out", "hub_to_hub", "bogus_type"):
response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
"transfer_type": bad_type,
})
assert response.status_code == 400, bad_type
assert response.get_json()["success"] is False
assert response.status_code == 422, bad_type # [规格 §11] 类型门禁统一 422
body = response.get_json()
assert body["success"] is False
assert body["error"]["code"] == "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
def test_create_matching_requires_transfer_type(app, client, admin_headers, transfer_deps):
"""transfer_type 缺失 → 422 TRANSFER_TYPE_REQUIRED(D8 必填,规格 §11)。"""
response = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
})
assert response.status_code == 422 # [规格 §11] 类型门禁统一 422
body = response.get_json()
# [断言意图] 必填缺失独立成码(与 NOT_CONFIGURED 区分),前端可精确提示。
assert body["success"] is False
assert body["error"]["code"] == "TRANSFER.TRANSFER_TYPE_REQUIRED"
def test_restore_matching_progress(app, client, admin_headers, transfer_deps):
"""GET /matchings/{id} 恢复匹配进度(Hash/明细一致)。"""
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"
}).get_json()["data"]
restored = client.get(f"{API_PREFIX}/matchings/{created['matching_id']}", headers=admin_headers)
assert restored.status_code == 200
@@ -230,7 +255,7 @@ def _create_matching(client, admin_headers) -> str:
"""创建匹配并返回 matching_no。"""
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"
})
assert created.status_code == 201
return created.get_json()["data"]["matching_id"]
@@ -346,7 +371,7 @@ def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_
"""人工关闭缺少原因 → 400。"""
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"
}).get_json()["data"]
with app.app_context():
from app.models import TransferInvoiceItem
@@ -364,7 +389,7 @@ def test_manual_close_item_success(app, client, admin_headers, transfer_deps):
"""人工关闭成功 → 状态 manually_closed。"""
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"
}).get_json()["data"]
with app.app_context():
from app.models import TransferInvoiceItem
@@ -458,7 +483,7 @@ def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, trans
# 匹配含 1 个数量不一致(blocked)项
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"
}).get_json()["data"]
with app.app_context():
from app.models import TransferInvoiceItem
@@ -685,7 +710,7 @@ def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch,
created = client.post(f"{API_PREFIX}/matchings", headers=admin_headers, json={
"source_codes": ["DBS-AWSBI"],
"business_date": "2026-08-06",
"business_date": "2026-08-06", "transfer_type": "in_transit_to_hub"
})
matching_no = created.get_json()["data"]["matching_id"]
+326
View File
@@ -0,0 +1,326 @@
"""调拨类型 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 升序、最小暴露(不含范围规则/仓库定义等)。"""
_seed_type(sort_order=20)
_seed_type(code="hub_to_line", sort_order=10)
_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:
# [断言意图] 最小暴露硬契约:响应 key 集合恰为四键——scope_rules/
# warehouse_config/description 属管理端配置资产,禁止泄露。
assert set(item.keys()) == {"code", "names", "sort_order", "transform_rules"}
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"