- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。 - 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。 - 更新 ORM 模型,增加出站报表相关的持久化模型。 - 统一命名规范,确保在手、入站与出站的概念一致性。
247 lines
13 KiB
Python
247 lines
13 KiB
Python
"""
|
|
用途:验证可复用库存解析 Profile 的版本、共享绑定和订单字段匹配键门禁。
|
|
依赖:freight_rpa.parsing_profile、freight_rpa_source_admin_service、订单 Schema 服务。
|
|
逻辑:发布一个 Profile 后绑定多个 Source;新版本并存且旧绑定稳定,非法字段、退役引用或非发布绑定被拒绝。
|
|
"""
|
|
|
|
from cryptography.fernet import Fernet
|
|
import pytest
|
|
|
|
from app.core.errors import ValidationError
|
|
from app.services.admin import freight_rpa_source_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, FreightRpaOnhandField, FreightRpaOnhandStructureAnalysis
|
|
|
|
|
|
def _inventory_mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]:
|
|
"""以库存字段目录 ID 构造解析映射,禁止测试继续模拟旧字段编码配置。"""
|
|
rows = {item.field_code: item for item in FreightRpaOnhandField.query.filter_by(status='active').all()}
|
|
return {
|
|
str(rows['part_number'].id): part,
|
|
str(rows['reservation_id'].id): reservation,
|
|
str(rows['available_qty'].id): quantity,
|
|
}
|
|
|
|
|
|
def _part_number_field_id() -> str:
|
|
"""返回内部料号目录 ID,作为订单明细匹配键的库存端引用。"""
|
|
return str(FreightRpaOnhandField.query.filter_by(field_code='part_number').one().id)
|
|
|
|
|
|
def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_format: str = 'xlsx') -> int:
|
|
"""构造最小化样本结构证据,使 Profile 测试遵循生产环境的表头绑定门禁。"""
|
|
item = FreightRpaOnhandStructureAnalysis(
|
|
source_kind='sample_upload', source_file_name='sample.xlsx', storage_path=None,
|
|
file_checksum='a' * 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 _published_profile() -> dict:
|
|
"""创建含 part_number 匹配键的 published 解析 Profile。"""
|
|
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
|
|
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
|
schema_draft = order_schema_service.create_draft({}, actor_id=None)
|
|
saved_schema = order_schema_service.save_draft(schema_draft['id'], {
|
|
'fields': [_schema_field_config(field['id'])],
|
|
'expected_lock_version': schema_draft['lock_version'],
|
|
})
|
|
order_schema_service.publish(
|
|
schema_draft['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
|
|
)
|
|
draft = onhand_parsing_profile.save_draft({
|
|
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common', 'file_format': 'xlsx',
|
|
'sample_analysis_id': _sample_evidence(headers=['Supplier Sku', 'Reservation ID', 'Qty Available']),
|
|
'definition': {
|
|
'header_row_index': 1,
|
|
'field_mapping': _inventory_mapping(),
|
|
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
|
|
},
|
|
}, actor_id=None)
|
|
return onhand_parsing_profile.publish(draft['id'], actor_id=None)
|
|
|
|
|
|
def _schema_field_config(field_id: str) -> dict:
|
|
"""构造库存匹配测试使用的最小可发布订单行字段规则。"""
|
|
return {
|
|
'field_id': field_id, 'display_name': '内部料号', 'required': True, 'aliases': [],
|
|
'normalizer_key': 'trim', 'validator_keys': [], 'enum_options': [],
|
|
'evidence_policy': {
|
|
'required': True, 'source_precedence': ['attachment_table'],
|
|
'conflict_policy': 'block', 'allow_single_source': True,
|
|
},
|
|
'relation_role': None, 'comparator_key': 'normalized_text',
|
|
'extraction_instruction': '提取订单行内部料号',
|
|
}
|
|
|
|
|
|
def _source(profile_id: int, parsing_id: int, code: str) -> dict:
|
|
"""构造绑定共享解析 Profile 的 DBS 库存源(s18:解析绑定走 onhand_report_config)。"""
|
|
return {
|
|
'source_code': code, 'display_name': code, 'connector_type': 'dbs',
|
|
'rpa_profile_id': profile_id,
|
|
'excel_template_id': _excel_template_id(),
|
|
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': code,
|
|
'snapshot_ttl_seconds': 3600, 'enabled': True,
|
|
'onhand_report_config': {
|
|
'parsing_profile_id': parsing_id,
|
|
'report_path_json': {
|
|
'program_group': 'Bison', 'program_label': 'AWSBI',
|
|
'report_group': 'Inventory', 'report_name': 'On Hand',
|
|
},
|
|
'query_parameters_json': [],
|
|
},
|
|
}
|
|
|
|
|
|
def _excel_template_id() -> int:
|
|
"""创建本组 Source 绑定共享的最小已发布发货模板。"""
|
|
item = ShippingExcelTemplate.query.filter_by(template_code='COMMON_EXPORT').first()
|
|
if item:
|
|
return item.id
|
|
item = ShippingExcelTemplate(
|
|
template_code='COMMON_EXPORT', display_name='Common Export', version=1, status='published',
|
|
storage_provider='minio', storage_bucket='test', storage_key='test/common-export.xlsx',
|
|
original_filename='template.xlsx',
|
|
file_checksum='0' * 64, definition_json={'filename_pattern': 'shipment_{task_no}.xlsx', 'mappings': []},
|
|
definition_checksum='1' * 64,
|
|
)
|
|
db.session.add(item)
|
|
db.session.flush()
|
|
return item.id
|
|
|
|
|
|
def test_published_parsing_profile_can_be_shared_by_sources(app):
|
|
"""同一 published Profile 应可绑定多个库存源,避免重复维护相同模板。"""
|
|
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
|
with app.app_context():
|
|
parsing = _published_profile()
|
|
login = freight_rpa_source_admin_service.save_profile({
|
|
'profile_code': 'DBS_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs',
|
|
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
|
|
'username': 'u', 'password': 'p', 'enabled': True,
|
|
}, actor_id=None)
|
|
first = freight_rpa_source_admin_service.save_source(_source(login['id'], parsing['id'], 'DUB'), actor_id=None)
|
|
second = freight_rpa_source_admin_service.save_source(_source(login['id'], parsing['id'], 'RTM'), actor_id=None)
|
|
|
|
assert first['onhand_report_config']['parsing_profile_id'] == parsing['id']
|
|
assert second['onhand_report_config']['parsing_profile_id'] == parsing['id']
|
|
assert onhand_parsing_profile.list_profiles()[0]['source_count'] == 2
|
|
|
|
|
|
def test_source_rejects_draft_parsing_profile(app):
|
|
"""库存源只能绑定 published Profile,避免运行期读取可变草稿。"""
|
|
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
|
with app.app_context():
|
|
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
|
|
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
|
draft = onhand_parsing_profile.save_draft({
|
|
'profile_code': 'DRAFT_ONLY', 'display_name': 'Draft', 'definition': {
|
|
'sheet_name': None, 'header_row_index': 1,
|
|
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
|
|
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
|
|
},
|
|
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
|
|
}, actor_id=None)
|
|
login = freight_rpa_source_admin_service.save_profile({
|
|
'profile_code': 'LOGIN', 'display_name': 'Login', 'connector_type': 'dbs',
|
|
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
|
|
'username': 'u', 'password': 'p', 'enabled': True,
|
|
}, actor_id=None)
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
freight_rpa_source_admin_service.save_source(_source(login['id'], draft['id'], 'DUB'), actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'
|
|
|
|
|
|
def test_csv_parsing_profile_rejects_worksheet_configuration(app):
|
|
"""CSV 没有工作表语义,保存 Profile 时不得接受会被运行期忽略的 sheet_name。"""
|
|
with app.app_context():
|
|
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
|
|
field = order_schema_service.save_field({
|
|
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
|
|
}, actor_id=None)
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
onhand_parsing_profile.save_draft({
|
|
'profile_code': 'CSV_SHEET', 'display_name': 'CSV Sheet', 'file_format': 'csv',
|
|
'definition': {
|
|
'sheet_name': 'Inventory', 'header_row_index': 1,
|
|
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
|
|
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
|
|
},
|
|
}, actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_INVALID'
|
|
|
|
|
|
def test_new_published_version_does_not_retire_bound_version(app):
|
|
"""发布新版本不得使现有库存源绑定的旧 published 版本失效。"""
|
|
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
|
with app.app_context():
|
|
first = _published_profile()
|
|
field_id = next(
|
|
item['field_id'] for item in order_schema_service.get_published_contract()['fields']
|
|
if item.get('field_code') == 'part_number' and item.get('scope') == 'line'
|
|
)
|
|
second_draft = onhand_parsing_profile.save_draft({
|
|
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx',
|
|
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
|
|
'definition': {
|
|
'header_row_index': 1,
|
|
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_field_id()}],
|
|
},
|
|
}, actor_id=None)
|
|
second = onhand_parsing_profile.publish(second_draft['id'], actor_id=None)
|
|
assert first['id'] != second['id']
|
|
assert {item['status'] for item in onhand_parsing_profile.list_profiles()} == {'published'}
|
|
|
|
|
|
def test_referenced_published_profile_cannot_be_retired(app):
|
|
"""已绑定库存源的解析 Profile 必须先迁移 Source,不能直接退役。"""
|
|
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
|
with app.app_context():
|
|
parsing = _published_profile()
|
|
login = freight_rpa_source_admin_service.save_profile({
|
|
'profile_code': 'RETIRE_LOGIN', 'display_name': 'DBS', 'connector_type': 'dbs',
|
|
'login_url': 'https://example.invalid', 'login_config_json': {'auth_mode': 'password'},
|
|
'username': 'u', 'password': 'p', 'enabled': True,
|
|
}, actor_id=None)
|
|
freight_rpa_source_admin_service.save_source(_source(login['id'], parsing['id'], 'RETIRE'), actor_id=None)
|
|
with pytest.raises(Exception) as exc_info:
|
|
onhand_parsing_profile.retire(parsing['id'])
|
|
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED'
|
|
|
|
|
|
def test_parsing_profile_publish_rejects_field_removed_from_current_schema(app):
|
|
"""解析 Profile 不得发布仍引用旧 Schema 字段的匹配键。"""
|
|
with app.app_context():
|
|
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
|
|
old_field = order_schema_service.save_field({'field_code': 'old_part', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
|
new_field = order_schema_service.save_field({'field_code': 'new_part', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
|
first = order_schema_service.create_draft({}, actor_id=None)
|
|
saved_schema = order_schema_service.save_draft(first['id'], {
|
|
'fields': [_schema_field_config(new_field['id'])], 'expected_lock_version': first['lock_version'],
|
|
})
|
|
order_schema_service.publish(
|
|
first['id'], actor_id=None, expected_lock_version=saved_schema['lock_version'],
|
|
)
|
|
profile = onhand_parsing_profile.save_draft({
|
|
'profile_code': 'STALE_FIELD', 'display_name': 'Stale Field',
|
|
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
|
|
'definition': {
|
|
'sheet_name': None, 'header_row_index': 1,
|
|
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
|
|
'match_keys': [{'order_field_id': old_field['id'], 'inventory_field_id': _part_number_field_id()}],
|
|
},
|
|
}, actor_id=None)
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
onhand_parsing_profile.publish(profile['id'], actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID'
|