- 收料单元 schedule_run_id 改可空,修复按需触发 FK 违例 - 收料配置绑定已发布异动解析规则(校验/回显/审计快照) - 预检未绑异动规则 fail-closed,不再徒劳触发 RPA - 标准异动字段目录只读接口;解析规则用途切换与批号映射表单(四语言) - movement 解析规则可发布(跳过订单匹配键校验);站点启停门禁仅限库存站点页签 - 只读映射卡三列布局修复
323 lines
18 KiB
Python
323 lines
18 KiB
Python
"""
|
|
tests/test_inventory_structure_analysis.py
|
|
|
|
用途:验证库存样本的后端结构分析、真实表头约束和解析方案草稿创建。
|
|
依赖:openpyxl、inventory_structure_analysis、订单字段 Schema 服务。
|
|
逻辑:管理端上传样本后必须由后端决定工作表和来源栏位;草稿创建只能引用分析出的真实栏位。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from io import BytesIO
|
|
from pathlib import Path
|
|
|
|
from openpyxl import Workbook
|
|
from werkzeug.datastructures import FileStorage
|
|
import pytest
|
|
|
|
from app.core.errors import ValidationError
|
|
from app.extensions import db
|
|
from app.services.shipping_notice import inventory_structure_analysis
|
|
from app.services.shipping_notice.order_schema import service as order_schema_service
|
|
from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis
|
|
|
|
|
|
def _field_id(field_code: str) -> str:
|
|
"""返回测试显式创建的用户库存字段 ID。"""
|
|
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
|
|
|
|
|
|
def _mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]:
|
|
"""使用字段目录 ID 构造样本解析映射。"""
|
|
return {
|
|
_field_id('part_number'): part,
|
|
_field_id('reservation_id'): reservation,
|
|
_field_id('available_qty'): quantity,
|
|
}
|
|
|
|
|
|
def _inventory_upload() -> FileStorage:
|
|
"""构造带标题行和库存表头的 xlsx 样本,覆盖候选表头识别。"""
|
|
stream = BytesIO()
|
|
workbook = Workbook()
|
|
cover = workbook.active
|
|
cover.title = 'Cover'
|
|
cover['A1'] = 'Inventory report'
|
|
sheet = workbook.create_sheet('Inventory')
|
|
sheet.append(['AWS Inventory Report'])
|
|
sheet.append([])
|
|
sheet.append(['Supplier Sku', 'Reservation ID', 'Qty Available', 'Warehouse ID', 'ODM ID'])
|
|
sheet.append(['PN-001', '1000140351', 9, 'AWSDU', '0000000574'])
|
|
sheet.append(['PN-002', '1000140352', 11, 'AWSDU', '0000000574'])
|
|
workbook.save(stream)
|
|
stream.seek(0)
|
|
return FileStorage(stream=stream, filename='inventory-sample.xlsx')
|
|
|
|
|
|
def _published_part_number() -> str:
|
|
"""建立草稿创建所需的已发布订单明细字段并返回稳定字段 ID。"""
|
|
order_schema_service.initialize_schema({'display_name': 'Inventory Analysis'}, actor_id=None)
|
|
field = order_schema_service.save_field({
|
|
'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
|
|
}, actor_id=None)
|
|
draft = order_schema_service.create_draft({}, actor_id=None)
|
|
saved = order_schema_service.save_draft(draft['id'], {'fields': [{
|
|
'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': '提取内部料号',
|
|
}], 'expected_lock_version': draft['lock_version']})
|
|
order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
|
return field['id']
|
|
|
|
|
|
def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_path):
|
|
"""上传样本必须定位真实库存表头,只持久化脱敏样例并清理完整工作簿。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
result = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
|
assert result['file_format'] == 'xlsx'
|
|
assert result['structure']['selected_sheet_name'] == 'Inventory'
|
|
assert result['structure']['selected_header_row_index'] == 3
|
|
# 用户字段名称与来源表头不同,后端不得通过内置业务词典擅自猜测。
|
|
assert result['suggested_mapping'] == {}
|
|
columns = result['structure']['selected_columns']
|
|
qty = next(column for column in columns if column['header'] == 'Qty Available')
|
|
assert qty['inferred_type'] == 'number'
|
|
assert qty['sample_values'] == ['9', '11']
|
|
assert result['sample_rows'][0] == ['P***1', '10***51', 9, 'A***U', '00***74']
|
|
analysis = db.session.get(ShippingInventoryStructureAnalysis, result['id'])
|
|
assert analysis is not None
|
|
assert analysis.storage_path is None
|
|
assert analysis.sample_rows_json == result['sample_rows']
|
|
assert not list((tmp_path / 'shipping' / 'inventory_structure_analyses').rglob('*.xlsx'))
|
|
|
|
|
|
def test_sample_analysis_prefers_populated_detail_sheet_over_same_score_summary(app, tmp_path):
|
|
"""同分候选时必须优先明细表,且只保存最终选定工作表的脱敏样例。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
stream = BytesIO()
|
|
workbook = Workbook()
|
|
summary = workbook.active
|
|
summary.title = 'Summary'
|
|
summary.append(['Summary'])
|
|
summary.append(['SECRET-SUMMARY'])
|
|
inventory = workbook.create_sheet('Inventory')
|
|
inventory.append(['Supplier SKU', 'Reservation ID', 'Qty Available'])
|
|
inventory.append(['PART-001', 'RSV-001', 7])
|
|
workbook.save(stream)
|
|
stream.seek(0)
|
|
result = inventory_structure_analysis.create_sample_upload(
|
|
FileStorage(stream=stream, filename='multi-sheet.xlsx'), actor_id=None,
|
|
)
|
|
assert result['structure']['selected_sheet_name'] == 'Inventory'
|
|
assert result['sample_rows'] == [['PA***01', 'RS***01', 7]]
|
|
assert all('_sample_rows' not in candidate for candidate in result['structure']['candidates'])
|
|
|
|
|
|
def test_sample_analysis_reads_legacy_xls(app, tmp_path):
|
|
"""旧 xls 样本必须走 xlrd 分析并保留其真实文件格式,不能要求用户先转换。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
template = Path(__file__).resolve().parents[1] / 'templates' / 'maintenance_record_history_template.xls'
|
|
with app.app_context():
|
|
upload = FileStorage(stream=BytesIO(template.read_bytes()), filename='legacy-inventory.xls')
|
|
result = inventory_structure_analysis.create_sample_upload(upload, actor_id=None)
|
|
|
|
assert result['file_format'] == 'xls'
|
|
assert result['structure']['selected_headers']
|
|
|
|
|
|
def test_profile_draft_rejects_source_header_not_present_in_analysis(app, tmp_path):
|
|
"""草稿不能提交浏览器伪造的来源栏位,必须只使用分析结果中的真实表头。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
field_id = _published_part_number()
|
|
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
|
'profile_code': 'INVALID_HEADERS', 'display_name': 'Invalid',
|
|
'sheet_name': 'Inventory', 'header_row_index': 3,
|
|
'field_mapping': _mapping(part='Made Up'),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
|
}, actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID'
|
|
|
|
|
|
def test_profile_draft_rejects_duplicate_source_header(app, tmp_path):
|
|
"""同名来源栏位不能作为映射目标,避免运行期按第一列静默解析。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
field_id = _published_part_number()
|
|
stream = BytesIO()
|
|
workbook = Workbook()
|
|
sheet = workbook.active
|
|
sheet.append(['Supplier Sku', 'Supplier Sku', 'Reservation ID', 'Qty Available'])
|
|
sheet.append(['PN-1', 'PN-OTHER', '1000140351', 9])
|
|
workbook.save(stream)
|
|
stream.seek(0)
|
|
analysis = inventory_structure_analysis.create_sample_upload(
|
|
FileStorage(stream=stream, filename='duplicate.xlsx'), actor_id=None,
|
|
)
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
|
'profile_code': 'DUPLICATE_HEADERS', 'display_name': 'Duplicate',
|
|
'sheet_name': 'Sheet', 'header_row_index': 1,
|
|
'field_mapping': _mapping(),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
|
}, actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID'
|
|
|
|
|
|
def test_profile_draft_uses_analysis_header_selection(app, tmp_path):
|
|
"""确认的工作表、表头和来源栏位能创建可继续编辑的库存文件解析方案草稿。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
field_id = _published_part_number()
|
|
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
|
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
|
'profile_code': 'AWS_INVENTORY', 'display_name': 'AWS 库存文件',
|
|
'sheet_name': 'Inventory', 'header_row_index': 3,
|
|
'field_mapping': _mapping(),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
|
}, actor_id=None)
|
|
assert profile['status'] == 'draft'
|
|
assert profile['definition']['sheet_name'] == 'Inventory'
|
|
assert profile['definition']['field_mapping'][_field_id('part_number')] == 'Supplier Sku'
|
|
saved = db.session.get(ShippingInventoryParsingProfile, profile['id'])
|
|
assert saved is not None
|
|
assert saved.sample_analysis_id == analysis['id']
|
|
|
|
|
|
def test_profile_sample_replacement_requires_confirmation_and_keeps_audit_history(app, tmp_path):
|
|
"""替换草稿样本必须显式确认,成功后保留旧样本 ID 的可追溯链。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
field_id = _published_part_number()
|
|
first = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
|
profile = inventory_structure_analysis.create_profile_draft(first['id'], {
|
|
'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
|
|
'sheet_name': 'Inventory', 'header_row_index': 3,
|
|
'field_mapping': _mapping(),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
|
}, actor_id=None)
|
|
second = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
|
preview = inventory_structure_analysis.preview_profile_sample_replacement(profile['id'], second['id'])
|
|
assert preview['can_confirm'] is True
|
|
assert preview['difference']['missing_mapped_headers'] == []
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
inventory_structure_analysis.create_profile_draft(second['id'], {
|
|
'profile_id': profile['id'], 'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
|
|
'sheet_name': 'Inventory', 'header_row_index': 3,
|
|
'field_mapping': _mapping(),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
|
}, actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED'
|
|
updated = inventory_structure_analysis.create_profile_draft(second['id'], {
|
|
'profile_id': profile['id'], 'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
|
|
'sheet_name': 'Inventory', 'header_row_index': 3,
|
|
'field_mapping': _mapping(),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
|
'confirm_sample_replacement': True,
|
|
}, actor_id=None)
|
|
assert updated['sample_analysis_id'] == second['id']
|
|
assert updated['sample_evidence_history'][-1]['previous_analysis_id'] == first['id']
|
|
assert updated['sample_evidence_history'][-1]['replacement_analysis_id'] == second['id']
|
|
|
|
|
|
def test_profile_sample_replacement_rejects_file_format_change(app, tmp_path):
|
|
"""草稿不能借由替换样本改变文件格式,防止运行期解析契约被静默改写。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
field_id = _published_part_number()
|
|
first = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
|
profile = inventory_structure_analysis.create_profile_draft(first['id'], {
|
|
'profile_code': 'FORMAT_REPLACEMENT', 'display_name': 'Format replacement',
|
|
'sheet_name': 'Inventory', 'header_row_index': 3,
|
|
'field_mapping': _mapping(),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
|
}, actor_id=None)
|
|
csv_upload = FileStorage(
|
|
stream=BytesIO(b'Supplier Sku,Reservation ID,Qty Available\nPN-001,R-1,1\n'),
|
|
filename='replacement.csv',
|
|
)
|
|
csv_analysis = inventory_structure_analysis.create_sample_upload(csv_upload, actor_id=None)
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
inventory_structure_analysis.create_profile_draft(csv_analysis['id'], {
|
|
'profile_id': profile['id'], 'profile_code': 'FORMAT_REPLACEMENT', 'display_name': 'Format replacement',
|
|
'header_row_index': 1, 'field_mapping': _mapping(),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
|
'confirm_sample_replacement': True,
|
|
}, actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
|
|
|
|
|
|
def test_profile_draft_requires_persisted_sample_evidence(app):
|
|
"""绕过样本分析直接保存草稿时必须被拒绝,避免来源表头脱离审计依据。"""
|
|
with app.app_context():
|
|
field_id = _published_part_number()
|
|
from app.services.shipping_notice import inventory_parsing_profile
|
|
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
inventory_parsing_profile.save_draft({
|
|
'profile_code': 'NO_EVIDENCE', 'display_name': 'No evidence', 'file_format': 'xlsx',
|
|
'definition': {
|
|
'sheet_name': 'Inventory', 'header_row_index': 1, 'field_mapping': _mapping(),
|
|
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
|
|
},
|
|
}, actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED'
|
|
|
|
|
|
def test_sample_analysis_rejects_invalid_file(app, tmp_path):
|
|
"""伪装为 xlsx 的非工作簿必须被拒绝,且不留下分析记录。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
upload = FileStorage(stream=BytesIO(b'not a workbook'), filename='invalid.xlsx')
|
|
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'] == []
|