feat(shipping-notice): 收料异动解析配置闭环与按需触发FK违例修复
- 收料单元 schedule_run_id 改可空,修复按需触发 FK 违例 - 收料配置绑定已发布异动解析规则(校验/回显/审计快照) - 预检未绑异动规则 fail-closed,不再徒劳触发 RPA - 标准异动字段目录只读接口;解析规则用途切换与批号映射表单(四语言) - movement 解析规则可发布(跳过订单匹配键校验);站点启停门禁仅限库存站点页签 - 只读映射卡三列布局修复
This commit is contained in:
1 parent
ab57ab3b1f
commit
20835dcfc0
28 files changed
+987
-73
No files matched your search
@@ -95,15 +95,42 @@ def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receip
|
||||
assert outcome["ok"] is True
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
|
||||
assert unit.status == "awaiting_rpa"
|
||||
assert unit.schedule_run_id == 0 # 调拨触发无排程 run,沿用 0 占位约定
|
||||
# [断言意图] 按需触发无排程 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 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 规则(仅满足守卫校验,不参与解析)。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
purpose='movement', 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': '料号',
|
||||
'quantity': '数量', 'movement_date': '异动日期'},
|
||||
'match_keys': []},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
config.parsing_profile_id = profile.id
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""deps 默认触发器必须真写 trigger 文件,不得只查配置就返回 ok=True(B1 断线根因)。"""
|
||||
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)
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
|
||||
@@ -113,6 +140,20 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
|
||||
assert list(tmp_path.glob("receipt_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(防徒劳抓取)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
|
||||
)
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
|
||||
assert outcome["ok"] is False
|
||||
assert outcome["error_code"] == "RPA_RECEIPT_MOVEMENT_PROFILE_MISSING"
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")) == []
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
标准异动字段目录接口测试。
|
||||
|
||||
用途:验证 GET /api/admin/shipping-notice/movement-fields 下发只读领域契约。
|
||||
依赖:Flask 管理 API、movement_contract 契约常量。
|
||||
逻辑:字段目录是 immutable 常量的投影——码/类型/必填/身份标记与契约逐项一致,
|
||||
不提供任何增删改入口,字段 label 由前端 i18n 渲染。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.conftest import parse_api_data
|
||||
|
||||
|
||||
def _headers() -> dict[str, str]:
|
||||
"""构造管理 API 身份 Header(与收料配置接口测试同款)。"""
|
||||
return {'X-Username': 'movement-admin', 'X-Role': 'admin', 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def test_movement_fields_returns_fixed_catalog(app, client):
|
||||
"""标准异动字段目录:10 个定死字段、顺序稳定、必填/身份标记与契约一致。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
from app.models import User
|
||||
from app import db
|
||||
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())
|
||||
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',
|
||||
]
|
||||
required = {field['code'] for field in data if field['required']}
|
||||
assert required == {'doc_no', 'material_code', 'quantity', 'movement_date'}
|
||||
identity = {field['code'] for field in data if field['is_identity']}
|
||||
assert identity == {'doc_no', 'material_code', 'movement_date'}
|
||||
assert {field['value_type'] for field in data} <= {'text', 'decimal', 'date'}
|
||||
|
||||
|
||||
def test_movement_fields_rejects_non_admin(app, client):
|
||||
"""字段目录是管理端配置资产,非 admin 角色 403。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import User
|
||||
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={
|
||||
'X-Username': 'movement-user', 'X-Role': 'user', 'Content-Type': 'application/json',
|
||||
})
|
||||
assert response.status_code == 403
|
||||
@@ -166,6 +166,102 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
|
||||
def _create_movement_profile(profile_code: str, *, status: str, purpose: str):
|
||||
"""创建异动/库存解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
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,
|
||||
'field_mapping': {'doc_no': '单据编号', 'material_code': '料号',
|
||||
'quantity': '数量', 'movement_date': '异动日期'},
|
||||
'match_keys': []},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.commit()
|
||||
return profile
|
||||
|
||||
|
||||
def test_receipt_config_binds_published_movement_profile(app, client):
|
||||
"""绑定已发布 movement 规则 → 保存成功,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_id = source.id
|
||||
profile = _create_movement_profile('CRANE_MOVE_STD', status='published', purpose='movement')
|
||||
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',
|
||||
json=payload, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
config = parse_api_data(response.get_json())
|
||||
# 关键断言:绑定 id 与规则摘要(码/版本/状态)必须回显,供抽屉展示当前绑定。
|
||||
assert config['parsing_profile_id'] == profile_id
|
||||
assert config['parsing_profile']['profile_code'] == 'CRANE_MOVE_STD'
|
||||
assert config['parsing_profile']['status'] == 'published'
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_receipt_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/库存用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.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]
|
||||
|
||||
for profile_id in cases:
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-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'
|
||||
|
||||
|
||||
def test_receipt_config_empty_profile_id_unbinds(app, client):
|
||||
"""parsing_profile_id 传 None → 解绑(置空),不做校验也不报错。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
profile = _create_movement_profile('MOVE_UNBIND', status='published', purpose='movement')
|
||||
profile_id = profile.id
|
||||
|
||||
bound = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-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',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': None},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert unbound.status_code == 200
|
||||
# 关键断言:None 表示显式解绑,payload 的绑定字段回到空值。
|
||||
assert parse_api_data(unbound.get_json())['parsing_profile_id'] is None
|
||||
|
||||
|
||||
def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
"""Crane 固定使用页面默认值直接 Run Report,管理员不能维护查询条件。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
|
||||
@@ -281,3 +281,42 @@ def test_sample_analysis_rejects_invalid_file(app, tmp_path):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_structure_analysis.create_sample_upload(upload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID'
|
||||
|
||||
|
||||
def test_profile_draft_purpose_passthrough_creates_movement_profile(app, tmp_path):
|
||||
"""purpose='movement' 必须透传到解析规则:异动草稿不依赖库存字段目录与匹配键。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
# 关键断言:movement 映射直接用定死领域字段码作键,不需要订单匹配键。
|
||||
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'MOVE_STD', 'display_name': '收料异动标准', 'purpose': 'movement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
|
||||
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
|
||||
'match_keys': None,
|
||||
}, actor_id=None)
|
||||
assert profile['purpose'] == 'movement'
|
||||
assert profile['definition']['match_keys'] == []
|
||||
assert set(profile['definition']['field_mapping']) == {'doc_no', 'material_code', 'quantity', 'movement_date'}
|
||||
|
||||
|
||||
def test_publish_movement_profile_skips_order_match_key_contract(app, tmp_path):
|
||||
"""发布 movement 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。"""
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'MOVE_PUB', 'display_name': '收料异动发布', 'purpose': 'movement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
|
||||
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
|
||||
'match_keys': None,
|
||||
}, actor_id=None)
|
||||
# 关键断言:movement 草稿必须能直接发布(有样本证据即可),match_keys 为空是合法契约。
|
||||
published = inventory_parsing_profile.publish(profile['id'], actor_id=None)
|
||||
assert published['status'] == 'published'
|
||||
assert published['checksum']
|
||||
assert published['definition']['match_keys'] == []
|
||||
Reference in new issue
Block a user