""" 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.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 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'] 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' 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'