615 lines
34 KiB
Python
615 lines
34 KiB
Python
"""
|
|
用途:验证版本化发货 Excel 模板发布、库存源共享绑定及动态字段导出产物审计。
|
|
依赖:excel_template/export 服务、openpyxl、订单动态 Schema 与库存配置模型。
|
|
逻辑:创建真实 xlsx 草稿并发布,生成任务产物后断言 Header/Line 写入及版本锁定字段。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date
|
|
from decimal import Decimal
|
|
from io import BytesIO
|
|
from unittest.mock import patch
|
|
|
|
from openpyxl import Workbook, load_workbook
|
|
from werkzeug.datastructures import FileStorage
|
|
import pytest
|
|
|
|
from app import db
|
|
from app.models import (
|
|
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
|
|
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
|
ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
|
|
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
|
|
)
|
|
from app.services.shipping_notice import excel_template
|
|
from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel
|
|
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
|
|
from app.services.shipping_notice.reservation_service import record_inventory_verification
|
|
from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE
|
|
from app.core.errors import ConflictError, ValidationError
|
|
|
|
|
|
def _lookup_standard_fields(*codes: str) -> dict[str, ShippingOrderField]:
|
|
"""从全局标准资产目录取字段,供模板测试引用稳定 field_id。"""
|
|
from app.services.shipping_notice import field_asset_service
|
|
field_asset_service.ensure_standard_assets_seeded()
|
|
return {code: ShippingOrderField.query.filter_by(field_code=code).one() for code in codes}
|
|
|
|
|
|
def _inventory_field_id(field_code: str) -> str:
|
|
"""返回库存字段目录 ID,使模板测试覆盖当前发布契约。"""
|
|
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
|
|
|
|
|
|
def _freeze_export_snapshot(
|
|
task: ShippingNotice, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
|
|
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
|
|
) -> None:
|
|
"""为导出测试建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。"""
|
|
field_codes = {
|
|
str(item.get('field_id')): str(item.get('field_code') or '')
|
|
for item in (version.definition_json or {}).get('fields') or []
|
|
}
|
|
po_number = next(
|
|
(str(value) for field_id, value in (header or {}).items() if field_codes.get(str(field_id)) == 'po_number'),
|
|
'TEST-PO-001',
|
|
)
|
|
snapshot = ShippingOrderSnapshot(
|
|
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
|
|
order_data_version=1, rule_versions_json={},
|
|
header_values_json={str(key): value for key, value in (header or {}).items()},
|
|
customer_po_number=po_number,
|
|
)
|
|
db.session.add(snapshot)
|
|
db.session.flush()
|
|
for position, field_id, part_number, qty, reservation_id in lines or []:
|
|
db.session.add(ShippingOrderSnapshotLine(
|
|
snapshot_id=snapshot.id, position=position, part_number=part_number,
|
|
reservation_id=reservation_id, qty=Decimal(str(qty)),
|
|
field_values_json={str(field_id): part_number},
|
|
))
|
|
db.session.flush()
|
|
task.order_snapshot_id = snapshot.id
|
|
record_inventory_verification(
|
|
task, inventory_snapshot_id=task.inventory_snapshot_id, source_config_version='test-v1',
|
|
line_results=[{
|
|
'reservation_id': line.reservation_id, 'part_number': line.part_number,
|
|
'required_qty': line.qty, 'available_qty': line.qty, 'line_status': 'ok',
|
|
} for line in snapshot.lines],
|
|
)
|
|
db.session.flush()
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _template_object_storage(monkeypatch):
|
|
"""使用内存私有对象存储替身,验证模板不依赖本机文件系统。"""
|
|
objects: dict[str, bytes] = {}
|
|
|
|
def upload_bytes(*, storage_key: str, data: bytes, content_type: str) -> None:
|
|
objects[storage_key] = bytes(data)
|
|
|
|
def get_bytes(storage_key: str) -> bytes:
|
|
if storage_key not in objects:
|
|
raise RuntimeError(f'missing test object: {storage_key}')
|
|
return objects[storage_key]
|
|
|
|
def delete_object(storage_key: str) -> None:
|
|
objects.pop(storage_key, None)
|
|
|
|
for module in ('app.services.shipping_notice.excel_template', 'app.services.shipping_notice.export'):
|
|
monkeypatch.setattr(f'{module}.file_asset_storage.upload_bytes', upload_bytes)
|
|
monkeypatch.setattr(f'{module}.file_asset_storage.get_bytes', get_bytes)
|
|
monkeypatch.setattr(f'{module}.file_asset_storage.delete_object', delete_object)
|
|
monkeypatch.setattr(f'{module}.file_asset_storage.bucket_name', 'test-template-bucket')
|
|
return objects
|
|
|
|
|
|
def _workbook_upload() -> FileStorage:
|
|
"""构造含 Header/Detail 工作表的内存 xlsx 上传对象。"""
|
|
stream = BytesIO()
|
|
wb = Workbook()
|
|
wb.active.title = 'Header'
|
|
wb.create_sheet('Detail')
|
|
wb.save(stream)
|
|
stream.seek(0)
|
|
return FileStorage(stream=stream, filename='shipping.xlsx', content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
|
|
|
|
|
def test_filename_pattern_supports_business_number_and_split_business_variables():
|
|
"""业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。"""
|
|
shipping_case = ShippingCase(
|
|
case_no='CASE-FILENAME', business_no='WYC26060201', customer_short_code_snapshot='WYC',
|
|
business_date=date(2026, 6, 2), sequence_value=1,
|
|
)
|
|
task = ShippingNotice(task_no='TASK-FILENAME', inventory_source_code='DBS')
|
|
task.shipping_case = shipping_case
|
|
template = ShippingExcelTemplate(
|
|
template_code='FILENAME', display_name='Filename',
|
|
definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'},
|
|
)
|
|
|
|
assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx'
|
|
|
|
|
|
def test_filename_pattern_falls_back_to_controlled_environment_configuration(app):
|
|
"""模板未提供规则时可使用受控环境变量,调用方仍不能提交任意文件名。"""
|
|
with app.app_context():
|
|
app.config['SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN'] = 'default_{task_no}.xlsx'
|
|
task = ShippingNotice(task_no='TASK-FILENAME-DEFAULT')
|
|
template = ShippingExcelTemplate(template_code='DEFAULT', display_name='Default', definition_json={})
|
|
assert _filename(task, template) == 'default_TASK-FILENAME-DEFAULT.xlsx'
|
|
|
|
|
|
def test_publish_allows_empty_template_filename_pattern_for_environment_fallback(app, tmp_path):
|
|
"""空模板规则代表显式采用环境变量回退,发布时仍须完整校验 Excel 映射。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'ENV_FALLBACK',
|
|
'display_name': 'Environment fallback',
|
|
'definition': {
|
|
'filename_pattern': '',
|
|
'mappings': [{
|
|
'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1,
|
|
'source_kind': 'constant', 'source_key': 'fallback', 'formatter': 'text',
|
|
}],
|
|
},
|
|
}, actor_id=None)
|
|
|
|
published = excel_template.publish(draft['id'], actor_id=None)
|
|
|
|
assert published['status'] == 'published'
|
|
assert published['definition']['filename_pattern'] == ''
|
|
|
|
|
|
def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
|
"""发布模板后按稳定 field_id 写入订单值,并锁定模板、Schema、Profile 与库存快照。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
|
db.session.add(schema)
|
|
db.session.flush()
|
|
fields = _lookup_standard_fields('customer_code', 'customer_po_number', 'part_number')
|
|
customer = fields['customer_code']
|
|
po_number = fields['customer_po_number']
|
|
part = fields['part_number']
|
|
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={
|
|
'fields': [{'field_id': customer.id}, {'field_id': po_number.id}, {'field_id': part.id}],
|
|
}, checksum='s' * 64)
|
|
db.session.add(version)
|
|
db.session.flush()
|
|
|
|
definition = {
|
|
'filename_pattern': 'shipment_{task_no}_{date}.xlsx',
|
|
'mappings': [
|
|
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'order_field', 'source_key': customer.id, 'formatter': 'upper'},
|
|
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 2, 'source_kind': 'system_fact', 'source_key': 'warehouse_id', 'formatter': 'text'},
|
|
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 3, 'source_kind': 'system_fact', 'source_key': 'export_date', 'formatter': 'date_mmddyyyy'},
|
|
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 1, 'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text'},
|
|
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 2, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
|
|
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 3, 'target_column': 3, 'source_kind': 'order_field', 'source_key': po_number.id, 'formatter': 'text'},
|
|
],
|
|
}
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'COMMON_SHIPMENT', 'display_name': 'Common Shipment', 'definition': definition,
|
|
}, actor_id=None)
|
|
published = excel_template.publish(draft['id'], actor_id=None)
|
|
|
|
parsing = ShippingInventoryParsingProfile(
|
|
profile_code='COMMON_INV', display_name='Common Inventory', version=1, status='published',
|
|
file_format='xlsx', definition_json={
|
|
'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'},
|
|
'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}],
|
|
}, checksum='p' * 64,
|
|
)
|
|
login = ShippingRpaProfile(
|
|
profile_code='LOGIN', display_name='Login', connector_type='dbs', login_url='https://invalid',
|
|
login_config_json={'auth_mode': 'password'},
|
|
)
|
|
db.session.add_all([parsing, login])
|
|
db.session.flush()
|
|
source = ShippingInventorySource(
|
|
source_code='DUB', display_name='Dublin', connector_type='dbs', rpa_profile_id=login.id,
|
|
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
|
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
|
)
|
|
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
|
db.session.add_all([source, extraction])
|
|
db.session.flush()
|
|
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
|
|
db.session.add(order_line)
|
|
db.session.flush()
|
|
header_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=customer.id, decision_status='accepted', resolved_value_json='acme')
|
|
po_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=po_number.id, decision_status='accepted', resolved_value_json='16754796')
|
|
line_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, decision_status='accepted', resolved_value_json='PN-1')
|
|
db.session.add_all([header_decision, po_decision, line_decision])
|
|
db.session.flush()
|
|
db.session.add_all([
|
|
ShippingOrderFieldValue(extraction_id=extraction.id, field_id=customer.id, value_text='acme', decision_id=header_decision.id),
|
|
ShippingOrderFieldValue(extraction_id=extraction.id, field_id=po_number.id, value_text='16754796', decision_id=po_decision.id),
|
|
ShippingOrderFieldValue(extraction_id=extraction.id, line_id=order_line.id, field_id=part.id, value_text='PN-1', decision_id=line_decision.id),
|
|
])
|
|
task = ShippingNotice(
|
|
task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB',
|
|
inventory_warehouse_id='DUB', inventory_lines_json=[{
|
|
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
|
|
}], inventory_snapshot_id=None,
|
|
)
|
|
db.session.add(task)
|
|
db.session.flush()
|
|
_freeze_export_snapshot(
|
|
task, extraction, version,
|
|
header={customer.id: 'acme', po_number.id: '16754796'},
|
|
lines=[(1, part.id, 'PN-1', 1, '1000000001')],
|
|
)
|
|
|
|
path, filename, artifact = generate_shipment_excel(task)
|
|
db.session.commit()
|
|
|
|
wb = load_workbook(path, read_only=True)
|
|
assert wb['Header'].cell(2, 1).value == 'ACME' # Header 动态字段及 formatter 生效。
|
|
assert wb['Header'].cell(2, 2).value == 'DUB' # 受控系统事实写入目标列。
|
|
assert wb['Header'].cell(2, 3).value == _system_fact(task, 'export_date').strftime('%m/%d/%Y')
|
|
assert wb['Detail'].cell(3, 1).value == 'PN-1' # Line 字段按订单行写入。
|
|
assert wb['Detail'].cell(3, 2).value == 'ODM-9' # 标准库存字段无需 LLM 判断。
|
|
assert wb['Detail'].cell(3, 3).value == '16754796' # Header 字段按业务要求重复到每条明细。
|
|
wb.close()
|
|
assert filename.startswith('shipment_TASK-EXPORT-1_')
|
|
assert artifact.template_id == published['id']
|
|
assert artifact.order_schema_version_id == version.id
|
|
assert artifact.inventory_parsing_profile_id == parsing.id
|
|
assert artifact.file_checksum and artifact.input_checksum and artifact.file_size > 0
|
|
|
|
# Dynamic inventory sources must resolve Warehouse before any export can be created.
|
|
task.inventory_warehouse_id = None
|
|
with pytest.raises(ValueError, match='缺少已解析的 Warehouse ID'):
|
|
generate_shipment_excel(task)
|
|
|
|
|
|
def test_header_mapping_rejects_line_order_field(app):
|
|
"""订单头区域不得引用明细字段,避免把多行值错误压缩为单个表头值。"""
|
|
with app.app_context():
|
|
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
|
db.session.add(schema)
|
|
db.session.flush()
|
|
part = _lookup_standard_fields('part_number')['part_number']
|
|
db.session.add(ShippingOrderSchemaVersion(
|
|
schema_id=schema.id, version=1, status='published',
|
|
definition_json={'fields': [{'field_id': part.id}]}, checksum='s' * 64,
|
|
))
|
|
db.session.flush()
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'INVALID_HEADER_LINE', 'display_name': 'Invalid Header Line',
|
|
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [{
|
|
'sheet': 'Header', 'row_mode': 'header', 'start_row': 2, 'target_column': 1,
|
|
'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text',
|
|
}]},
|
|
}, actor_id=None)
|
|
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
excel_template.publish(draft['id'], actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID'
|
|
|
|
|
|
def test_export_date_system_fact_uses_business_timezone(app):
|
|
"""导出日期必须返回上海业务时区的日期对象,供模板统一格式化。"""
|
|
with app.app_context():
|
|
value = _system_fact(ShippingNotice(task_no='TASK-DATE'), 'export_date')
|
|
assert isinstance(value, date)
|
|
|
|
|
|
def test_two_sources_can_share_one_published_excel_template(app, tmp_path):
|
|
"""同结构库存源绑定同一 published 模板,避免复制维护映射规则。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'SHARED', 'display_name': 'Shared',
|
|
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
|
|
{'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1, 'source_kind': 'constant', 'source_key': 'n', 'formatter': 'text'},
|
|
]},
|
|
}, actor_id=None)
|
|
published = excel_template.publish(draft['id'], actor_id=None)
|
|
parsing = ShippingInventoryParsingProfile(
|
|
profile_code='SHARED_INV', display_name='Shared Inventory', version=1, status='published',
|
|
file_format='xlsx', definition_json={}, checksum='p' * 64,
|
|
)
|
|
login = ShippingRpaProfile(
|
|
profile_code='SHARED_LOGIN', display_name='Shared Login', connector_type='dbs',
|
|
login_url='https://invalid', login_config_json={'auth_mode': 'password'},
|
|
)
|
|
db.session.add_all([parsing, login])
|
|
db.session.flush()
|
|
for code in ('DUB', 'RTM'):
|
|
db.session.add(ShippingInventorySource(
|
|
source_code=code, display_name=code, connector_type='dbs', rpa_profile_id=login.id,
|
|
parsing_profile_id=parsing.id, excel_template_id=published['id'],
|
|
warehouse_resolution_mode='fixed', fixed_warehouse_id=code,
|
|
report_path_json={}, query_parameters_json=[],
|
|
))
|
|
db.session.commit()
|
|
|
|
template = db.session.get(ShippingExcelTemplate, published['id'])
|
|
assert template is not None
|
|
assert {source.source_code for source in template.sources} == {'DUB', 'RTM'} # 一个发布版本供多个 Source 共享。
|
|
|
|
|
|
def test_disabled_source_still_blocks_template_retirement(app):
|
|
"""禁用库存源仍保留模板配置引用,迁移前不得退役其模板版本。"""
|
|
with app.app_context():
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'DISABLED_REF', 'display_name': 'Disabled Ref',
|
|
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [{
|
|
'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1,
|
|
'source_kind': 'constant', 'source_key': 'x', 'formatter': 'text',
|
|
}]},
|
|
}, actor_id=None)
|
|
published = excel_template.publish(draft['id'], actor_id=None)
|
|
login = ShippingRpaProfile(
|
|
profile_code='DISABLED_REF', display_name='Disabled Ref', connector_type='dbs',
|
|
login_url='https://invalid', login_config_json={'auth_mode': 'password'},
|
|
)
|
|
db.session.add(login)
|
|
db.session.flush()
|
|
db.session.add(ShippingInventorySource(
|
|
source_code='DISABLED_REF', display_name='Disabled Ref', connector_type='dbs', enabled=False,
|
|
rpa_profile_id=login.id, excel_template_id=published['id'],
|
|
warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
|
|
report_path_json={}, query_parameters_json=[],
|
|
))
|
|
db.session.commit()
|
|
|
|
with pytest.raises(Exception) as exc_info:
|
|
excel_template.retire(published['id'])
|
|
assert getattr(exc_info.value, 'code', '') == 'SHIPPING.EXCEL_TEMPLATE_RETIRE_BLOCKED'
|
|
|
|
|
|
def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path):
|
|
"""库存行顺序与订单相反时仍须按稳定 match_keys 写入正确 ODM,禁止按数组下标配对。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
|
db.session.add(schema); db.session.flush()
|
|
part = _lookup_standard_fields('part_number')['part_number']
|
|
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={
|
|
'fields': [{'field_id': part.id}],
|
|
})
|
|
db.session.add(version); db.session.flush()
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'KEYED', 'display_name': 'Keyed',
|
|
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
|
|
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 1, 'source_kind': 'order_field', 'source_key': part.id, 'formatter': 'text'},
|
|
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 2, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
|
|
]},
|
|
}, actor_id=None)
|
|
published = excel_template.publish(draft['id'], actor_id=None)
|
|
parsing = ShippingInventoryParsingProfile(
|
|
profile_code='KEYED', display_name='Keyed', version=1, status='published', file_format='xlsx',
|
|
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
|
|
)
|
|
login = ShippingRpaProfile(
|
|
profile_code='KEYED', display_name='Keyed', connector_type='dbs', login_url='https://invalid',
|
|
login_config_json={'auth_mode': 'password'},
|
|
)
|
|
db.session.add_all([parsing, login]); db.session.flush()
|
|
db.session.add(ShippingInventorySource(
|
|
source_code='KEYED', display_name='Keyed', connector_type='dbs', rpa_profile_id=login.id,
|
|
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
|
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
|
))
|
|
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
|
db.session.add(extraction); db.session.flush()
|
|
for position, value in enumerate(('PN-A', 'PN-B'), start=1):
|
|
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_key=str(position))
|
|
db.session.add(line); db.session.flush()
|
|
decision = ShippingOrderFieldDecision(
|
|
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
|
|
decision_status='accepted', resolved_value_json=value,
|
|
)
|
|
db.session.add(decision); db.session.flush()
|
|
db.session.add(ShippingOrderFieldValue(
|
|
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
|
|
value_text=value, decision_id=decision.id,
|
|
))
|
|
task = ShippingNotice(
|
|
task_no='TASK-KEYED', current_order_extraction_id=extraction.id, inventory_source_code='KEYED',
|
|
inventory_warehouse_id='DUB', inventory_lines_json=[
|
|
{_inventory_field_id('part_number'): 'PN-B', _inventory_field_id('odm_id'): 'ODM-B'},
|
|
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-A'},
|
|
],
|
|
)
|
|
db.session.add(task); db.session.flush()
|
|
_freeze_export_snapshot(
|
|
task, extraction, version,
|
|
lines=[
|
|
(1, part.id, 'PN-A', 1, '1000000002'),
|
|
(2, part.id, 'PN-B', 1, '1000000003'),
|
|
],
|
|
)
|
|
|
|
path, _filename, _artifact = generate_shipment_excel(task)
|
|
workbook = load_workbook(path, read_only=True)
|
|
assert workbook['Detail'].cell(2, 2).value == 'ODM-A'
|
|
assert workbook['Detail'].cell(3, 2).value == 'ODM-B'
|
|
workbook.close()
|
|
|
|
|
|
def test_template_upload_rejects_fake_xlsx_without_leaving_file(app, tmp_path, _template_object_storage):
|
|
"""扩展名伪装的无效工作簿必须在创建草稿前拒绝,模板目录不得产生孤立文件。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
fake = FileStorage(stream=BytesIO(b'not-a-workbook'), filename='fake.xlsx')
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
excel_template.create_draft(fake, {
|
|
'template_code': 'FAKE', 'display_name': 'Fake', 'definition': {},
|
|
}, actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_INVALID'
|
|
assert not _template_object_storage
|
|
|
|
|
|
def test_existing_template_can_create_new_draft_version_without_reupload(app):
|
|
"""新版本直接复制受管文件和映射定义,用户无需再次选择本地 Excel。"""
|
|
with app.app_context():
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'COPY_VERSION', 'display_name': 'Copy Version',
|
|
'definition': {'filename_pattern': '{business_no}.xlsx', 'mappings': [{
|
|
'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1,
|
|
'source_kind': 'constant', 'source_key': 'x', 'formatter': 'text',
|
|
}]},
|
|
}, actor_id=None)
|
|
published = excel_template.publish(draft['id'], actor_id=None)
|
|
copied = excel_template.create_draft_from_existing(published['id'], actor_id=None)
|
|
assert copied['version'] == 2
|
|
assert copied['status'] == 'draft'
|
|
assert copied['definition'] == draft['definition']
|
|
layout = excel_template.get_layout(copied['id'])
|
|
assert set(layout['sheets']) == {'Header', 'Detail'}
|
|
|
|
|
|
def test_existing_template_can_clone_as_independent_v1_without_reupload(app):
|
|
"""复制为新模板必须复用文件和定义,但采用新编码且不加入原模板版本链。"""
|
|
with app.app_context():
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'SOURCE_TEMPLATE', 'display_name': 'Source Template',
|
|
'definition': {'filename_pattern': '{business_no}.xlsx', 'mappings': [{
|
|
'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1,
|
|
'source_kind': 'constant', 'source_key': 'copy', 'formatter': 'text',
|
|
}]},
|
|
}, actor_id=None)
|
|
published = excel_template.publish(draft['id'], actor_id=None)
|
|
copied = excel_template.clone_as_new_template(published['id'], {
|
|
'template_code': 'COPIED_TEMPLATE', 'display_name': 'Copied Template',
|
|
}, actor_id=None)
|
|
|
|
assert copied['template_code'] == 'COPIED_TEMPLATE'
|
|
assert copied['display_name'] == 'Copied Template'
|
|
assert copied['version'] == 1
|
|
assert copied['status'] == 'draft'
|
|
assert copied['definition'] == draft['definition']
|
|
assert copied['file_checksum'] == draft['file_checksum']
|
|
|
|
with pytest.raises(ConflictError) as exc_info:
|
|
excel_template.clone_as_new_template(published['id'], {
|
|
'template_code': 'COPIED_TEMPLATE', 'display_name': 'Another Copy',
|
|
}, actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_CODE_EXISTS'
|
|
|
|
|
|
def test_template_publish_rejects_order_field_removed_from_current_schema(app):
|
|
"""模板草稿不得在订单字段移出当前 published Schema 后继续发布。"""
|
|
from app.services.shipping_notice.order_schema import service as order_schema_service
|
|
|
|
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',
|
|
'display_name': '旧料号',
|
|
}, actor_id=None)
|
|
new_field = order_schema_service.save_field({
|
|
'field_code': 'new_part', 'scope': 'line', 'value_type': 'string',
|
|
'display_name': '新料号',
|
|
}, actor_id=None)
|
|
|
|
def 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': '提取内部料号',
|
|
}
|
|
|
|
first = order_schema_service.create_draft({}, actor_id=None)
|
|
saved_schema = order_schema_service.save_draft(first['id'], {
|
|
'fields': [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'],
|
|
)
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'STALE_FIELD', 'display_name': 'Stale Field',
|
|
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [{
|
|
'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 1,
|
|
'source_kind': 'order_field', 'source_key': old_field['id'], 'formatter': 'text',
|
|
}]},
|
|
}, actor_id=None)
|
|
with pytest.raises(ValidationError) as exc_info:
|
|
excel_template.publish(draft['id'], actor_id=None)
|
|
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID'
|
|
|
|
|
|
def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app, tmp_path):
|
|
"""同一匹配键对应多个不同 ODM 时必须阻断,且不得留下半成品 Excel。"""
|
|
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
|
with app.app_context():
|
|
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
|
db.session.add(schema); db.session.flush()
|
|
part = _lookup_standard_fields('part_number')['part_number']
|
|
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
|
|
db.session.add(version); db.session.flush()
|
|
draft = excel_template.create_draft(_workbook_upload(), {
|
|
'template_code': 'AMBIGUOUS', 'display_name': 'Ambiguous',
|
|
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
|
|
{'sheet': 'Detail', 'row_mode': 'line', 'start_row': 2, 'target_column': 1, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
|
|
]},
|
|
}, actor_id=None)
|
|
published = excel_template.publish(draft['id'], actor_id=None)
|
|
parsing = ShippingInventoryParsingProfile(
|
|
profile_code='AMBIGUOUS', display_name='Ambiguous', version=1, status='published', file_format='xlsx',
|
|
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
|
|
)
|
|
login = ShippingRpaProfile(
|
|
profile_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', login_url='https://invalid',
|
|
login_config_json={'auth_mode': 'password'},
|
|
)
|
|
db.session.add_all([parsing, login]); db.session.flush()
|
|
db.session.add(ShippingInventorySource(
|
|
source_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', rpa_profile_id=login.id,
|
|
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
|
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
|
))
|
|
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
|
db.session.add(extraction); db.session.flush()
|
|
line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
|
|
db.session.add(line); db.session.flush()
|
|
decision = ShippingOrderFieldDecision(
|
|
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
|
|
decision_status='accepted', resolved_value_json='PN-A',
|
|
)
|
|
db.session.add(decision); db.session.flush()
|
|
db.session.add(ShippingOrderFieldValue(
|
|
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
|
|
value_text='PN-A', decision_id=decision.id,
|
|
))
|
|
task = ShippingNotice(
|
|
task_no='TASK-AMBIGUOUS', current_order_extraction_id=extraction.id,
|
|
inventory_source_code='AMBIGUOUS', inventory_warehouse_id='DUB', inventory_lines_json=[
|
|
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-1'},
|
|
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-2'},
|
|
],
|
|
)
|
|
db.session.add(task); db.session.flush()
|
|
_freeze_export_snapshot(
|
|
task, extraction, version,
|
|
lines=[(1, part.id, 'PN-A', 1, '1000000004')],
|
|
)
|
|
|
|
with pytest.raises(ValueError, match='值不一致'):
|
|
generate_shipment_excel(task)
|
|
export_root = tmp_path / 'shipping' / 'exports'
|
|
assert not export_root.exists() or not list(export_root.rglob('*.xlsx'))
|
|
|
|
|
|
def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch):
|
|
"""Artifact/任务事务提交失败时必须删除已生成文件,避免孤立 ready-looking 产物。"""
|
|
path = tmp_path / 'orphan.xlsx'
|
|
path.write_bytes(b'orphan')
|
|
with app.app_context():
|
|
monkeypatch.setattr(db.session, 'commit', lambda: (_ for _ in ()).throw(RuntimeError('commit failed')))
|
|
with pytest.raises(RuntimeError, match='commit failed'):
|
|
_commit_generated_export(str(path))
|
|
assert not path.exists()
|