feat(in-transit-transfer): inbound/outbound 幂等重命名与解析用途分层

- receipt→inbound 三件套改名(回调桥/文件门禁/触发服务),回调链幂等去重,迁移 tt14 同步台账键与测试基建
- 库存解析用途分层 onhand/inbound/outbound(迁移 tt15):解析档案、文件存储与下载名按用途隔离,管理端表单同步
- 「成熟」概念退役(迁移 tt16):数据无成熟属性,日期边界由调用方入参严格判定
- backlog 新增重解析服务,在途重识别投影 processing,EML 父项不再停留处理中
- 收料 RPA 回调/归档/排程链路同步改名挂点,运维脚本复位假完成状态
- 文档随批:ADR 0003 模块边界决策、10-15/10-16 计划与设计、调拨文档族与 demand/tec/funclist
- 同步 chat/errors 文案四语言、调拨前端卡片与 e2e、测试全家
This commit is contained in:
hugo committed 2026-10-16 19:43:49 +08:00
1 parent 43dceaf027
commit 8102a1fe44
151 files changed
+8057 -2382

No files matched your search

+274 -23
View File
@@ -1,26 +1,46 @@
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验)。
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验 + 迁移往返)。
用途:验证 inventory_parsing_profile._validate_definition(purpose=...) 分支——
movement 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
不查库存字段目录、无 match_keys);inventory 维持既有 match_keys 校验。
并用 app fixture 校验模型 purpose 列默认 'inventory'。
依赖:inventory_parsing_profile._validate_definition(纯)、app(SQLite)。
逻辑:_required_movement_field_ids 纯函数校验;模型列默认值经 app fixture 校验。
inbound 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
不查库存字段目录、无 match_keys);onhand/outbound 维持既有库存字段目录 + match_keys
校验(outbound 出站文件结构就位,暂无运行时消费方)。并用 app fixture 校验模型
purpose 列默认 'onhand'、CHECK 约束三元枚举,以及 tt15 迁移 SQLite 真实往返。
依赖:inventory_parsing_profile._validate_definition / save_draft(纯 + app SQLite)、
migrations/versions/tt15(batch_alter_table 改枚举)、app_ctx(根 conftest app
fixture 上下文别名)。
逻辑:_required_movement_field_ids 纯函数校验;模型列默认值/约束经 app fixture 校验;
迁移往返按 tt13/tt14 同款模式(手工复刻前置表结构 + upgrade→downgrade→upgrade)。
"""
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.core.errors import ValidationError
from app.services.shipping_notice.inventory_parsing_profile import _validate_definition
from app.services.shipping_notice.inventory_parsing_profile import _validate_definition, save_draft
pytestmark = pytest.mark.pure_unit
REVISION = "tt15b6a7b8c9d0"
DOWN_REVISION = "tt14a5f6a7b8c9"
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" / "versions"
def _movement_definition() -> dict:
@pytest.fixture
def app_ctx(app):
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
return app
def _inbound_definition() -> dict:
return {
'sheet_name': 'Movement',
'sheet_name': 'Inbound',
'header_row_index': 1,
'field_mapping': {
'doc_no': '单据编号',
@@ -37,33 +57,264 @@ def _movement_definition() -> dict:
}
def test_movement_definition_validates_fixed_fields():
"""movement 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。"""
definition = _validate_definition(_movement_definition(), purpose='movement')
def test_inbound_definition_validates_fixed_fields():
"""inbound 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。"""
definition = _validate_definition(_inbound_definition(), purpose='inbound')
assert definition['field_mapping']['doc_no'] == '单据编号'
assert definition['field_mapping']['quantity'] == '数量'
assert definition['match_keys'] == []
def test_movement_definition_missing_fixed_field_rejected():
"""movement 缺 movement_date → 阻断。"""
raw = dict(_movement_definition())
def test_inbound_definition_missing_fixed_field_rejected():
"""inbound 缺 movement_date → 阻断。"""
raw = dict(_inbound_definition())
raw['field_mapping'] = {k: v for k, v in raw['field_mapping'].items() if k != 'movement_date'}
with pytest.raises(ValidationError):
_validate_definition(raw, purpose='movement')
_validate_definition(raw, purpose='inbound')
def test_movement_definition_rejects_unknown_field():
"""movement 引用非定死领域字段 → 阻断。"""
raw = dict(_movement_definition())
def test_inbound_definition_rejects_unknown_field():
"""inbound 引用非定死领域字段 → 阻断。"""
raw = dict(_inbound_definition())
raw['field_mapping'] = {**raw['field_mapping'], 'free_text': '随意列'}
with pytest.raises(ValidationError):
_validate_definition(raw, purpose='movement')
_validate_definition(raw, purpose='inbound')
def test_model_purpose_column_defaults_to_inventory(app):
"""模型 purpose 列默认 'inventory'(既有行不回填)。"""
def test_purpose_enum_values():
"""模型 purpose 列:default/server_default 均为 'onhand',CHECK 枚举恰为三元新枚举。"""
from app.models.shipping_inventory_config import ShippingInventoryParsingProfile
col = ShippingInventoryParsingProfile.__table__.columns["purpose"]
assert col.default.arg == "onhand" and col.server_default.arg == "onhand"
check = next(c for c in ShippingInventoryParsingProfile.__table__.constraints
if getattr(c, "name", "") == "ck_shipping_inventory_parsing_profiles_purpose")
sql = str(getattr(check, "sqltext", check))
for value in ("onhand", "inbound", "outbound"):
assert value in sql
for legacy in ("'inventory'", "'movement'"):
assert legacy not in sql
def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_format: str = 'xlsx') -> int:
"""构造最小化样本结构证据,使 save_draft 遵循生产环境的表头绑定门禁。"""
from app import db
from app.models import ShippingInventoryStructureAnalysis
item = ShippingInventoryStructureAnalysis(
source_kind='sample_upload', source_file_name='sample.xlsx', storage_path=None,
file_checksum='c' * 64, file_format=file_format, analysis_status='ready',
structure_json={'candidates': [{
'sheet_name': sheet_name, 'header_row_index': 1, 'headers': headers,
'columns': [{'header': header, 'duplicate': False} for header in headers],
}]},
suggested_mapping_json={}, validation_summary_json={}, sample_rows_json=[], warning_json=[],
)
db.session.add(item)
db.session.flush()
return item.id
def _catalog_mapping() -> dict[str, str]:
"""以库存字段目录 ID 构造 onhand/outbound 用解析映射(目录分支端点)。"""
from app.models import ShippingInventoryField
rows = {item.field_code: item for item in ShippingInventoryField.query.filter_by(status='active').all()}
return {
str(rows['part_number'].id): 'Supplier Sku',
str(rows['reservation_id'].id): 'Reservation ID',
str(rows['available_qty'].id): 'Qty Available',
}
def test_draft_accepts_outbound_and_rejects_legacy(app_ctx):
"""save_draft purpose='outbound' 通过校验;purpose='movement' 报 SHIPPING.INVENTORY_PARSING_PROFILE_INVALID。"""
from app import db
from app.models import ShippingOrderField
# 出站文件结构就位:outbound 走库存字段目录分支(与 onhand 同构),需行级订单匹配键。
order_field = ShippingOrderField(field_code='part_number', scope='line', value_type='string')
db.session.add(order_field)
db.session.flush()
headers = ['Supplier Sku', 'Reservation ID', 'Qty Available']
outbound = save_draft({
'profile_code': 'OUT_STD', 'display_name': '出站结构就位', 'purpose': 'outbound',
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers),
'definition': {
'header_row_index': 1,
'field_mapping': _catalog_mapping(),
'match_keys': [{'order_field_id': order_field.id, 'inventory_field_id': next(iter(_catalog_mapping()))}],
},
}, actor_id=None)
assert outbound['purpose'] == 'outbound'
with pytest.raises(ValidationError) as exc_info:
save_draft({
'profile_code': 'LEGACY_MOVE', 'display_name': '旧异动用途', 'purpose': 'movement',
'file_format': 'xlsx', 'sample_analysis_id': _sample_evidence(headers=headers),
'definition': {'header_row_index': 1, 'field_mapping': _catalog_mapping(), 'match_keys': []},
}, actor_id=None)
# 关键断言:旧枚举 movement 已从白名单移除,fail-closed 报统一错误码。
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
def test_model_purpose_column_defaults_to_onhand(app):
"""模型 purpose 列默认 'onhand'(存量 inventory 行由 tt15 数据迁移回填)。"""
from app.models import ShippingInventoryParsingProfile
existing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first()
assert existing is not None and existing.purpose == 'inventory'
assert existing is not None and existing.purpose == 'onhand'
def _load_migration(revision: str):
"""按 revision 加载迁移模块(test_migration_widen_transfer_run_type 同款,不加载 Flask 应用)。"""
for path in MIGRATIONS_DIR.glob("*.py"):
if path.name.startswith(f"{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
raise AssertionError(f"migration file for revision {revision} not found")
def test_tt15_revision_chains_from_tt14_head():
"""tt15 必须存在且挂在 tt14a5f6a7b8c9(实施时实际单 head)之后,且用 batch 模式保 SQLite 往返。"""
for path in MIGRATIONS_DIR.glob("*.py"):
if path.name.startswith(f"{REVISION}_"):
text = path.read_text(encoding="utf-8")
assert f"revision = '{REVISION}'" in text or f'revision = "{REVISION}"' in text
assert f"down_revision = '{DOWN_REVISION}'" in text or f'down_revision = "{DOWN_REVISION}"' in text
# SQLite 不支持裸 DROP CONSTRAINT / ALTER COLUMN SET DEFAULT:必须走 batch_alter_table。
assert "batch_alter_table" in text
return
raise AssertionError(f"migration file for revision {REVISION} not found")
def _prestate_metadata() -> sa.MetaData:
"""复刻 tt15 前置(tt14 末态)的 shipping_inventory_parsing_profiles 表结构。
按建表迁移 b17e3d4c5a60 与后续加列迁移(fc1d2e3f4a5b/f83d9e0f1a2b/a4c7e9f1b2d3/
if1b2c3d4e5g)汇总列集,purpose 保持旧枚举(default 'inventory' + 旧 CHECK),
作为 tt15 往返的真实前置。历史链祖先众多(a0b1c2d3e4f6…),整链重放不成比例,
手工复刻与 tt13 前置基线做法一致。
"""
md = sa.MetaData()
sa.Table("users", md, sa.Column("id", sa.Integer(), primary_key=True))
sa.Table(
"shipping_inventory_structure_analyses", md,
sa.Column("id", sa.Integer(), primary_key=True),
)
sa.Table(
"shipping_inventory_parsing_profiles", md,
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("purpose", sa.String(length=16), nullable=False, server_default="inventory"),
sa.Column("profile_code", sa.String(length=64), nullable=False),
sa.Column("display_name", sa.String(length=128), nullable=False),
sa.Column("version", sa.Integer(), server_default="1", nullable=False),
sa.Column("status", sa.String(length=16), server_default="draft", nullable=False),
sa.Column("file_format", sa.String(length=16), server_default="xlsx", nullable=False),
sa.Column("definition_json", sa.JSON(), nullable=False),
sa.Column("checksum", sa.String(length=64), nullable=True),
sa.Column("structure_definition_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False),
sa.Column("exact_structure_fingerprint", sa.String(length=64), nullable=True),
sa.Column("compatibility_fingerprint", sa.String(length=64), nullable=True),
sa.Column("fingerprint_version", sa.String(length=32), nullable=True),
sa.Column("sample_analysis_id", sa.Integer(), nullable=True),
sa.Column("sample_evidence_history_json", sa.JSON(), server_default=sa.text("'[]'"), nullable=False),
sa.Column("created_by", sa.Integer(), nullable=True),
sa.Column("published_by", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("published_at", sa.DateTime(), nullable=True),
sa.UniqueConstraint("profile_code", "version", name="uq_inventory_parsing_profiles_code_version"),
sa.CheckConstraint(
"purpose IN ('inventory', 'movement')",
name="ck_shipping_inventory_parsing_profiles_purpose",
),
sa.ForeignKeyConstraint(["sample_analysis_id"], ["shipping_inventory_structure_analyses.id"]),
sa.ForeignKeyConstraint(["created_by"], ["users.id"]),
sa.ForeignKeyConstraint(["published_by"], ["users.id"]),
)
return md
_LEGACY_ROW_COLUMNS = (
"purpose, profile_code, display_name, version, status, file_format, "
"definition_json, structure_definition_json, sample_evidence_history_json, created_at"
)
def _insert_profile(connection, *, purpose: str, profile_code: str) -> None:
"""按旧枚举直接插入一条解析规则行(旧 CHECK 放行 inventory/movement)。"""
connection.execute(sa.text(
f"INSERT INTO shipping_inventory_parsing_profiles ({_LEGACY_ROW_COLUMNS}) "
f"VALUES ('{purpose}', '{profile_code}', '{profile_code} 规则', 1, 'published', 'xlsx', "
f"'{{}}', '{{}}', '[]', '2026-01-01 00:00:00')"
))
def _purpose_by_code(connection) -> dict[str, str]:
rows = connection.execute(sa.text(
"SELECT profile_code, purpose FROM shipping_inventory_parsing_profiles"
)).fetchall()
return {code: purpose for code, purpose in rows}
def _column_default(connection, column: str) -> str:
columns = {c["name"]: c for c in sa.inspect(connection).get_columns("shipping_inventory_parsing_profiles")}
return str(columns[column].get("default") or "")
def test_tt15_sqlite_roundtrip_upgrade_downgrade_upgrade():
"""SQLite 真实往返:upgrade 换枚举并迁数据 / downgrade 对称还原 / 再 upgrade。
[断言意图] 前置表(旧枚举 default 'inventory' + 旧 CHECK)就位后,tt15 的
batch DROP CHECK → 数据 UPDATE → ADD CHECK → SET DEFAULT 不丢列、不丢数据;
存量 inventory→onhand、movement→inbound 精确映射;新 CHECK 真实生效
(outbound 放行、旧值拒写);downgrade 对称(outbound/inbound→movement 结构就位
语义最接近),default/CHECK 翻转可回滚。
"""
engine = sa.create_engine("sqlite:///:memory:")
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
_prestate_metadata().create_all(connection)
_insert_profile(connection, purpose='inventory', profile_code='LEG_INV')
_insert_profile(connection, purpose='movement', profile_code='LEG_MOVE')
# 前置基线:旧 CHECK 放行 inventory/movement、拒新枚举。
_insert_profile(connection, purpose='movement', profile_code='BASE_MOVE')
assert "inventory" in _column_default(connection, "purpose")
migration = _load_migration(REVISION)
migration.op = operations
migration.upgrade()
# [断言意图] 数据迁移:inventory→onhand、movement→inbound。
assert _purpose_by_code(connection) == {
'LEG_INV': 'onhand', 'LEG_MOVE': 'inbound', 'BASE_MOVE': 'inbound',
}
# [断言意图] 列默认值翻转为 'onhand'。
assert "onhand" in _column_default(connection, "purpose")
# [断言意图] 新 CHECK 真实生效:outbound 放行、旧值 inventory 拒写。
_insert_profile(connection, purpose='outbound', profile_code='NEW_OUT')
with pytest.raises(sa.exc.IntegrityError):
_insert_profile(connection, purpose='inventory', profile_code='REJECT_OLD')
migration.downgrade()
# [断言意图] downgrade 对称:onhand→inventory,inbound/outbound→movement。
assert _purpose_by_code(connection) == {
'LEG_INV': 'inventory', 'LEG_MOVE': 'movement', 'BASE_MOVE': 'movement', 'NEW_OUT': 'movement',
}
assert "inventory" in _column_default(connection, "purpose")
# [断言意图] 旧 CHECK 还原:inventory 放行、新值 onhand 拒写。
_insert_profile(connection, purpose='inventory', profile_code='BACK_INV')
with pytest.raises(sa.exc.IntegrityError):
_insert_profile(connection, purpose='onhand', profile_code='REJECT_NEW')
migration.upgrade()
assert _purpose_by_code(connection) == {
'LEG_INV': 'onhand', 'LEG_MOVE': 'inbound', 'BASE_MOVE': 'inbound',
'NEW_OUT': 'inbound', 'BACK_INV': 'onhand',
}
assert "onhand" in _column_default(connection, "purpose")