174 lines
8.5 KiB
Python
174 lines
8.5 KiB
Python
"""验证正式库存文件结构漂移必须在入库前受控处理。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from openpyxl import Workbook
|
|
|
|
from app import db
|
|
from app.core.errors import ConflictError
|
|
from app.models import (
|
|
ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryFile,
|
|
ShippingInventoryParsingProfile, ShippingInventorySource, ShippingRpaProfile,
|
|
)
|
|
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
|
|
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path
|
|
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
|
|
from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition
|
|
|
|
|
|
def _workbook(path: Path, headers: list[str]) -> None:
|
|
"""创建可控表头的库存文件,用于模拟货代导出格式变化。"""
|
|
workbook = Workbook()
|
|
sheet = workbook.active
|
|
sheet.append(headers)
|
|
values = {
|
|
'Supplier Sku': 'PN-1', 'Reservation ID': '1000140351', 'Qty Available': 9,
|
|
'Custom Part': 'PN-CUSTOM', 'Custom Reservation': '1000140999', 'Custom Quantity': 7,
|
|
'Export Time': '2026-07-17',
|
|
}
|
|
sheet.append([values.get(header, 'value') for header in headers])
|
|
workbook.save(path)
|
|
|
|
|
|
def _multi_sheet_workbook(path: Path) -> None:
|
|
"""创建含相似工作表的文件,验证正式校验不会选错已确认工作表。"""
|
|
workbook = Workbook()
|
|
summary = workbook.active
|
|
summary.title = 'Summary'
|
|
# Summary 表刻意缺少关键栏位,不能影响已配置 Inventory 表的正式校验。
|
|
summary.append(['Changed Part', 'Reservation ID', 'Qty Available'])
|
|
summary.append(['SUMMARY-PN', '1000140351', 99])
|
|
inventory = workbook.create_sheet('Inventory')
|
|
inventory.append(['Supplier Sku', 'Reservation ID', 'Qty Available'])
|
|
inventory.append(['PN-1', '1000140351', 9])
|
|
workbook.save(path)
|
|
|
|
|
|
def _source_with_profile(path: Path) -> ShippingInventorySource:
|
|
"""从基准文件建立已启用站点和已发布方案,模拟完成全部启用前校验后的状态。"""
|
|
structure, _suggested, _summary, _warnings = _analyse_path(path, '.xlsx')
|
|
definition = structure_definition(
|
|
file_format='xlsx', sheet_name='Sheet', header_row_index=1,
|
|
headers=structure['selected_headers'],
|
|
)
|
|
inventory_fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.filter_by(status='active').all()}
|
|
profile = ShippingInventoryParsingProfile(
|
|
profile_code='DRIFT_PROFILE', display_name='Drift Profile', version=1, status='published', file_format='xlsx',
|
|
definition_json={'sheet_name': 'Sheet', 'header_row_index': 1, 'field_mapping': {
|
|
inventory_fields['part_number']: 'Supplier Sku', inventory_fields['reservation_id']: 'Reservation ID',
|
|
inventory_fields['available_qty']: 'Qty Available',
|
|
}, 'match_keys': []}, structure_definition_json=definition,
|
|
exact_structure_fingerprint=exact_fingerprint(definition), checksum='1' * 64,
|
|
)
|
|
rpa = ShippingRpaProfile(
|
|
profile_code='DRIFT_LOGIN', display_name='Drift Login', connector_type='dbs',
|
|
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
|
|
)
|
|
template = ShippingExcelTemplate(
|
|
template_code='DRIFT_TEMPLATE', display_name='Drift Template', version=1, status='published',
|
|
storage_bucket='test', storage_key='drift.xlsx', original_filename='drift.xlsx', file_checksum='0' * 64,
|
|
definition_json={'mappings': [{'source_kind': 'inventory_field', 'source_key': 'part_number'}]},
|
|
definition_checksum='2' * 64,
|
|
)
|
|
source = ShippingInventorySource(
|
|
source_code='DRIFT_SOURCE', display_name='Drift Source', connector_type='dbs', rpa_profile=rpa,
|
|
parsing_profile=profile, excel_template=template, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
|
|
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
|
|
query_parameters_json=[], match_aliases_json=[], enabled=True,
|
|
)
|
|
db.session.add(source)
|
|
db.session.commit()
|
|
return source
|
|
|
|
|
|
def test_production_structure_accepts_exact_and_noncritical_column_change(app, tmp_path):
|
|
"""同结构和仅新增无关栏位可入库,但结果需明确标注一致性等级。"""
|
|
with app.app_context():
|
|
baseline = tmp_path / 'baseline.xlsx'
|
|
_workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available'])
|
|
_source_with_profile(baseline)
|
|
|
|
exact = validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=baseline)
|
|
assert exact['level'] == 'exact'
|
|
|
|
compatible = tmp_path / 'compatible.xlsx'
|
|
_workbook(compatible, ['Supplier Sku', 'Reservation ID', 'Qty Available', 'Export Time'])
|
|
result = validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=compatible)
|
|
assert result['level'] == 'compatible'
|
|
assert 'export time' in result['difference']['added_columns']
|
|
|
|
|
|
def test_production_structure_blocks_core_column_drift(app, tmp_path):
|
|
"""关键库存栏位改名后必须阻断,禁止运行期自动猜测新来源列。"""
|
|
with app.app_context():
|
|
baseline = tmp_path / 'baseline.xlsx'
|
|
_workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available'])
|
|
_source_with_profile(baseline)
|
|
drifted = tmp_path / 'drifted.xlsx'
|
|
_workbook(drifted, ['Changed Part', 'Reservation ID', 'Qty Available'])
|
|
|
|
with pytest.raises(ConflictError) as blocked:
|
|
validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=drifted)
|
|
assert blocked.value.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED'
|
|
|
|
|
|
def test_production_structure_uses_configured_worksheet_not_best_guess(app, tmp_path):
|
|
"""多工作表文件必须依赖方案指定工作表,不能被其他错误工作表影响。"""
|
|
with app.app_context():
|
|
baseline = tmp_path / 'baseline.xlsx'
|
|
_workbook(baseline, ['Supplier Sku', 'Reservation ID', 'Qty Available'])
|
|
source = _source_with_profile(baseline)
|
|
source.parsing_profile.definition_json = {
|
|
**source.parsing_profile.definition_json,
|
|
'sheet_name': 'Inventory',
|
|
}
|
|
source.parsing_profile.structure_definition_json = structure_definition(
|
|
file_format='xlsx', sheet_name='Inventory', header_row_index=1,
|
|
headers=['Supplier Sku', 'Reservation ID', 'Qty Available'],
|
|
)
|
|
source.parsing_profile.exact_structure_fingerprint = exact_fingerprint(
|
|
source.parsing_profile.structure_definition_json,
|
|
)
|
|
db.session.commit()
|
|
|
|
_multi_sheet_workbook(tmp_path / 'multi-sheet.xlsx')
|
|
result = validate_production_inventory_structure(source_code='DRIFT_SOURCE', path=tmp_path / 'multi-sheet.xlsx')
|
|
assert result['level'] == 'exact'
|
|
assert result['sheet_name'] == 'Inventory'
|
|
|
|
|
|
def test_snapshot_reread_uses_published_profile_not_header_guess(app, tmp_path):
|
|
"""正式快照丢失缓存行后仍按绑定方案重读,不能回退自动表头猜测。"""
|
|
with app.app_context():
|
|
path = tmp_path / 'configured-only.xlsx'
|
|
_workbook(path, ['Custom Part', 'Custom Reservation', 'Custom Quantity'])
|
|
source = _source_with_profile(path)
|
|
fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()}
|
|
source.parsing_profile.definition_json = {
|
|
'sheet_name': 'Sheet', 'header_row_index': 1,
|
|
'field_mapping': {
|
|
fields['part_number']: 'Custom Part',
|
|
fields['reservation_id']: 'Custom Reservation',
|
|
fields['available_qty']: 'Custom Quantity',
|
|
},
|
|
'match_keys': [],
|
|
}
|
|
snapshot = ShippingInventoryFile(
|
|
inventory_file_no='INV-REREAD-001', storage_path=str(path), source_code=source.source_code,
|
|
warehouse_id='DUB', snapshot_status='ready', inventory_lines_json=None,
|
|
)
|
|
db.session.add(snapshot)
|
|
db.session.commit()
|
|
|
|
lines, meta = parse_inventory_snapshot_file(snapshot)
|
|
assert lines == [{
|
|
fields['part_number']: 'PN-CUSTOM',
|
|
fields['reservation_id']: '1000140999',
|
|
fields['available_qty']: 7.0,
|
|
}]
|
|
assert 'part_number' not in lines[0]
|
|
assert str(meta['mapping_source']).startswith('parsing_profile:DRIFT_PROFILE:v1')
|