Files
syops/backend/tests/test_shipping_excel_template.py
T
hugo d396371020 feat(shipping_notice): 支持客户 ODM 白名单与整单 ODM 选择收敛导出
- 客户主数据新增 odm_ids 白名单字段(含 Alembic 迁移),表单与管理端支持维护
- 导出库存命中行按客户白名单与整单 ODM 裁决收敛,新增 notice_odm_choice_service
- 工作台新增 odm-options / odm-choice 接口,投影行级候选并持久化用户选择
- 修复复核工作台跨 Run 切换时接收解析上下文残留
- 同步四语言 i18n、测试用例、funclist 与 shipping-notice 技术文档
2026-09-16 19:50:12 +08:00

1156 lines
59 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
用途:验证版本化发货 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,
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, ShippingOrderTask,
ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink,
)
from app.services.shipping_notice import excel_template
from app.services.shipping_notice.export import (
_excel_business_no,
_filename,
_mapping_value,
_system_fact,
_template_requires_system_warehouse_id,
generate_shipment_excel,
)
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
from app.services.shipping_notice.inventory_file_store import (
active_inventory_lines_for_task,
replace_task_inventory_link,
resolve_inventory_lines_for_execution,
)
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 test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fact():
"""模板将库位作为 inventory_field 消费时,不得被任务级 Warehouse ID 门禁误拦。"""
assert _template_requires_system_warehouse_id([
{
'sheet': 'PVMI Pull Request Header',
'row_mode': 'header',
'target_column': 1,
'source_kind': 'inventory_field',
'source_key': '7',
},
]) is False
assert _template_requires_system_warehouse_id([
{
'sheet': 'Header',
'row_mode': 'header',
'target_column': 2,
'source_kind': 'system_fact',
'source_key': 'warehouse_id',
},
]) is True
def test_unique_notice_warehouse_id_for_header_mapping():
"""Header 写 warehouse_id:唯一库位放行,多库位拒绝,空库位返回 None。"""
from types import SimpleNamespace
from app.services.shipping_notice.export import _unique_notice_warehouse_id
assert _unique_notice_warehouse_id([
SimpleNamespace(inventory_warehouse_id='AWSSG'),
SimpleNamespace(inventory_warehouse_id='awssg'),
]) == 'AWSSG'
assert _unique_notice_warehouse_id([
SimpleNamespace(inventory_warehouse_id=None),
SimpleNamespace(inventory_warehouse_id=''),
]) is None
with pytest.raises(ValueError, match='多库位'):
_unique_notice_warehouse_id([
SimpleNamespace(inventory_warehouse_id='AWSSG'),
SimpleNamespace(inventory_warehouse_id='MOW'),
])
def _freeze_export_snapshot(
task: ShippingOrderTask, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
customer_id: int | None = None, inventory_file_id: int | None = None,
) -> ShippingOrderSnapshot:
"""为导出测试在 OT 上建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。"""
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,
customer_id=customer_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, line_no=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=inventory_file_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()
return snapshot
def _materialize_export_notice(
*, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: ShippingInventoryFile,
source_code: str, notice_no: str,
) -> ShippingNotice:
"""从 OT 的冻结快照构造正式 Notice、NoticeLine、匹配事实与活动库存链接。
导出链路只接受已物化的正式 Notice;OT 承载订单/库存事实,Notice 通过
order_task_id 指向 OT。行级匹配事实按 OT id 落库,库存 Link 绑定 Notice 本身。
"""
notice = ShippingNotice(
task_no=notice_no, source_type='manual', order_task_id=ot.id, user_id=ot.user_id,
)
db.session.add(notice)
db.session.flush()
replace_notice_lines_from_snapshot(
notice_id=notice.id, snapshot=snapshot,
inventory_facts_by_snapshot_line_id={
int(line.id): {
'inventory_source_code': source_code,
'inventory_file_id': int(inventory_file.id),
'inventory_warehouse_id': inventory_file.warehouse_id,
}
for line in snapshot.lines
},
)
for line in snapshot.lines:
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no,
match_result='matched', inventory_status='ready',
inventory_snapshot_id=inventory_file.id, inventory_source_code=source_code,
is_current=True, detail_json={},
))
db.session.flush()
replace_task_inventory_link(notice, inventory_file, role='owner')
db.session.flush()
return notice
@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():
"""业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。"""
task = ShippingNotice(
task_no='TASK-FILENAME', business_no='WYC26060201',
business_date=date(2026, 6, 2), business_sequence_value=1,
)
template = ShippingExcelTemplate(
template_code='FILENAME', display_name='Filename',
definition_json={'filename_pattern': '{business_no}_{business_date}_{sequence}.xlsx'},
)
assert _filename(task, template) == 'WYC26060201_260602_01.xlsx'
def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cache(app, tmp_path):
"""业务执行必须使用活动库存 Link,忽略请求库存。"""
with app.app_context():
task = ShippingOrderTask(task_no='OT-INVENTORY-SOURCE', user_id=1)
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'),
inventory_lines_json=[{'part_number': 'ACTIVE'}], line_count=1,
share_mode='task_only', snapshot_status='ready',
)
db.session.add_all([task, inventory_file])
db.session.flush()
replace_task_inventory_link(task, inventory_file, role='owner')
db.session.flush()
resolved = resolve_inventory_lines_for_execution(
task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}],
)
assert resolved == [{'part_number': 'ACTIVE'}]
def test_inventory_execution_keeps_legacy_fallback_without_active_link(app):
"""无活动 Link 的历史任务仍可读取请求库存,避免升级后无法恢复。"""
with app.app_context():
task = ShippingOrderTask(task_no='OT-INVENTORY-LEGACY', user_id=1)
db.session.add(task)
db.session.flush()
assert resolve_inventory_lines_for_execution(
task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}],
) == [{'part_number': 'PAYLOAD'}]
# 既无活动 Link 也无旧缓存时返回空,不伪造或回退到其它任务库存。
assert resolve_inventory_lines_for_execution(task) == []
def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp_path, monkeypatch):
"""已有正式快照 JSON 时读取动作不得重新解析物理文件并覆盖已修复数据。"""
with app.app_context():
storage_path = tmp_path / 'stale.xlsx'
storage_path.write_bytes(b'stale-source')
task = ShippingOrderTask(task_no='OT-INVENTORY-NO-REPARSE', user_id=1)
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path),
inventory_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}],
line_count=1, share_mode='task_only', snapshot_status='ready',
)
db.session.add_all([task, inventory_file])
db.session.flush()
replace_task_inventory_link(task, inventory_file, role='owner')
db.session.flush()
reparse_calls: list[int] = []
def stale_reparse(_inventory_file):
reparse_calls.append(int(_inventory_file.id))
return ([{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-STALE'}], {})
monkeypatch.setattr(
'app.services.shipping_notice.inventory_file_store.parse_inventory_snapshot_file', stale_reparse,
)
assert active_inventory_lines_for_task(task) == [
{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'},
]
assert reparse_calls == []
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():
from tests.conftest import confirm_test_customer_resolution
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': '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=[],
)
ot = ShippingOrderTask(task_no='OT-EXPORT-1', user_id=1, status='ready', current_step='customer_review')
db.session.add(ot)
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=ot.id, 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_no=2)
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),
])
confirmed_customer = ShippingCustomer(
standard_name='Export ACME', short_code='EAC', status='active',
)
db.session.add(confirmed_customer)
db.session.flush()
confirm_test_customer_resolution(ot, customer=confirmed_customer, extraction=extraction)
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-EXPORT-1', user_id=None,
source_file_name='inventory.xlsx', storage_path=str(tmp_path / 'inventory.xlsx'),
inventory_lines_json=[{
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
}],
line_count=1, share_mode='task_only', warehouse_id='DUB', source_code='DUB', snapshot_status='ready',
)
db.session.add(inventory_file)
db.session.flush()
snapshot = _freeze_export_snapshot(
ot, extraction, version,
header={customer.id: 'acme', po_number.id: '16754796'},
lines=[(1, part.id, 'PN-1', 1, '1000000001')],
customer_id=confirmed_customer.id, inventory_file_id=inventory_file.id,
)
# 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。
task = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='DUB', notice_no='TASK-EXPORT-1',
)
assert task.business_no is None
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 == _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
assert task.business_no is not None
assert task.business_no.startswith('EAC')
# 一个 Notice 已有 Excel 后必须创建新 Notice,禁止同号追加第二个 Artifact。
with pytest.raises(ConflictError) as second_export:
generate_shipment_excel(task)
assert second_export.value.code == 'SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED'
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_excel_pull_request_number_uses_notice_business_number(app):
"""Excel Pull Request Number 直接使用 Notice business_no,不因导出日期重编号。"""
with app.app_context():
task = ShippingNotice(task_no='TASK-EXCEL-NO', business_no='IVMX26080801', business_sequence_value=1)
assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26080801'
assert task.business_no == 'IVMX26080801'
def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app):
"""正式金额必须来自 Schema FieldValue,禁止由快照或单价静默推导。"""
with app.app_context():
fields = _lookup_standard_fields('line_no', 'line_amount_with_tax')
task = ShippingNotice(task_no='TASK-MAPPING')
assert _mapping_value(
{'source_kind': 'order_field', 'source_key': fields['line_no'].id, 'formatter': 'integer', 'row_mode': 'line'},
task=task, order_values={}, inventory_values={}, notice_line_no=1,
) == 1
assert _mapping_value(
{'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'},
task=task, order_values={'__qty': Decimal('14'), '__unit_price': Decimal('941.76')}, inventory_values={},
) is None
def test_clear_template_data_rows_keeps_headers_and_removes_residual_values():
"""模板数据区从起始行起清空,表头不受影响。"""
from app.services.shipping_notice.export import _clear_template_data_rows
workbook = Workbook()
sheet = workbook.active
sheet['A3'] = 'header'
sheet['A4'] = 'current'
sheet['A5'] = 'residual-5'
sheet['B6'] = 'residual-6'
_clear_template_data_rows(sheet, 4)
assert sheet['A3'].value == 'header'
assert sheet['A4'].value is None
assert sheet['A5'].value is None
assert sheet['B6'].value is None
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():
from tests.conftest import confirm_test_customer_resolution
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=[],
))
customer = ShippingCustomer(standard_name='键控匹配客户', short_code='KEY', status='active')
db.session.add(customer); db.session.flush()
ot = ShippingOrderTask(task_no='OT-KEYED', user_id=1, status='ready', current_step='customer_review')
db.session.add(ot); db.session.flush()
extraction = ShippingOrderExtraction(
task_id=ot.id, 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_no=position + 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=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,
))
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-KEYED', user_id=None, source_file_name='keyed.xlsx',
storage_path=str(tmp_path / 'keyed.xlsx'),
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'},
],
line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='KEYED', snapshot_status='ready',
)
db.session.add(inventory_file); db.session.flush()
snapshot = _freeze_export_snapshot(
ot, extraction, version,
lines=[
(1, part.id, 'PN-A', 1, '1000000002'),
(2, part.id, 'PN-B', 1, '1000000003'),
],
customer_id=customer.id, inventory_file_id=inventory_file.id,
)
task = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='KEYED', notice_no='TASK-KEYED',
)
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_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_path):
"""导出应读取活动库存 Link;无 Link 时旧缓存冲突仍须阻断且不留半成品。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
from tests.conftest import confirm_test_customer_resolution
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=[],
))
customer = ShippingCustomer(standard_name='模糊匹配客户', short_code='AMB', status='active')
db.session.add(customer); db.session.flush()
ot = ShippingOrderTask(task_no='OT-AMBIGUOUS', user_id=1, status='ready', current_step='customer_review')
db.session.add(ot); db.session.flush()
extraction = ShippingOrderExtraction(
task_id=ot.id, 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_no=2)
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,
))
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
ambiguous_file = ShippingInventoryFile(
inventory_file_no='SIF-AMBIGUOUS', user_id=None, source_file_name='ambiguous.xlsx',
storage_path=str(tmp_path / 'ambiguous.xlsx'),
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'},
],
line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='AMBIGUOUS',
snapshot_status='ready',
)
db.session.add(ambiguous_file); db.session.flush()
snapshot = _freeze_export_snapshot(
ot, extraction, version,
lines=[(1, part.id, 'PN-A', 1, '1000000004')],
customer_id=customer.id, inventory_file_id=ambiguous_file.id,
)
task = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=ambiguous_file, source_code='AMBIGUOUS', notice_no='TASK-AMBIGUOUS',
)
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
generate_shipment_excel(task)
export_root = tmp_path / 'shipping' / 'exports'
assert not export_root.exists() or not list(export_root.rglob('*.xlsx'))
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-ACTIVE-FIXED', user_id=None,
source_file_name='fixed.xlsx', storage_path=str(tmp_path / 'fixed.xlsx'),
inventory_lines_json=[
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'},
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'},
],
line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='AMBIGUOUS',
snapshot_status='ready',
)
db.session.add(inventory_file)
db.session.flush()
replace_task_inventory_link(task, inventory_file, role='owner')
# 切换活动库存后,行级匹配事实须指向新快照;导出只读取活动 Link。
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=ot.id, is_current=True).all():
match.inventory_snapshot_id = inventory_file.id
db.session.flush()
path, _filename_value, artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-FIXED'
finally:
workbook.close()
assert artifact.inventory_snapshot_id == inventory_file.id
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()
def _build_multi_odm_notice(
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
):
"""
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
Args:
odm_values: 单订单行场景下库存行命中的 ODM 值列表。
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
Returns:
(notice, customer)。
"""
from tests.conftest import confirm_test_customer_resolution
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': 'ODMSCOPE', 'display_name': 'OdmScope',
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
{'sheet': 'Detail', 'row_mode': 'header', '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='ODMSCOPE', display_name='OdmScope', 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='ODMSCOPE', display_name='OdmScope', 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='ODMSCOPE', display_name='OdmScope', 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=[],
))
customer = ShippingCustomer(
standard_name='ODM范围客户', short_code='ODMSC', status='active',
odm_ids=list(customer_odm_ids) if customer_odm_ids is not None else None,
)
db.session.add(customer); db.session.flush()
ot = ShippingOrderTask(task_no='OT-ODMSCOPE', user_id=1, status='ready', current_step='customer_review')
db.session.add(ot); db.session.flush()
extraction = ShippingOrderExtraction(
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
)
db.session.add(extraction); db.session.flush()
specs = line_specs or [{'part': 'PN-A', 'odm_values': odm_values}]
snapshot_lines = []
for index, spec in enumerate(specs, start=1):
order_line = ShippingOrderLine(extraction_id=extraction.id, position=index, line_no=index)
db.session.add(order_line); db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
decision_status='accepted', resolved_value_json=spec['part'],
)
db.session.add(decision); db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
value_text=spec['part'], decision_id=decision.id,
))
snapshot_lines.append((index, part.id, spec['part'], 1, f'100000000{index}'))
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
inventory_rows = []
for spec in specs:
for odm in spec['odm_values']:
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
storage_path=str(tmp_path / 'odm-scope.xlsx'),
inventory_lines_json=inventory_rows,
line_count=len(inventory_rows), share_mode='task_only', warehouse_id='DUB', source_code='ODMSCOPE',
snapshot_status='ready',
)
db.session.add(inventory_file); db.session.flush()
snapshot = _freeze_export_snapshot(
ot, extraction, version,
lines=snapshot_lines,
customer_id=customer.id, inventory_file_id=inventory_file.id,
)
notice = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
)
if choice_odm is not None:
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
match.chosen_odm_id = choice_odm
db.session.flush()
return notice, customer
def test_export_narrows_odm_by_customer_range(app, tmp_path):
"""客户 ODM ID 范围非空时,导出只取范围内库存行;范围命中唯一值写入表头。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['odm-2'],
)
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
finally:
workbook.close()
def test_export_odm_range_excluding_all_raises_specific_error(app, tmp_path):
"""客户范围把全部命中排除时,必须报指向客户数据的可行动错误而非「没有匹配」。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-9'],
)
with pytest.raises(ValueError, match='不在客户数据维护的 ODM ID 范围'):
generate_shipment_excel(task)
def test_export_applies_notice_odm_choice(app, tmp_path):
"""整单用户选择优先于多值冲突;选择经 casefold 归一后命中库存行。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], choice_odm='odm-2',
)
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
finally:
workbook.close()
def test_export_auto_narrows_unique_feasible_odm_without_manual_choice(app, tmp_path):
"""无范围、无选择时,整单唯一可行 ODM(各行命中交集恰一个)自动收敛。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
{'part': 'PN-B', 'odm_values': ['ODM-2']},
])
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
finally:
workbook.close()
def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
"""无范围、无选择且多值并存时维持折叠冲突阻断,等待用户整单选择。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'])
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
generate_shipment_excel(task)
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
from app.core.errors import AppError
from app.services.shipping_notice.notice_odm_choice_service import (
notice_odm_options,
set_notice_odm_choice,
)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-2', 'ODM-3'],
)
options = notice_odm_options(task)
# [断言] 逐行候选是客户范围过滤后的集合,且保留库存行原始大小写。
assert options['whitelist_applied'] is True
assert options['customer_odm_ids'] == ['ODM-2', 'ODM-3']
assert len(options['lines']) == 1
assert options['lines'][0]['odm_values'] == ['ODM-2']
assert options['lines'][0]['chosen_odm_id'] is None
snapshot_line_id = options['lines'][0]['snapshot_line_id']
result = set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-2')
assert result['odm_id'] == 'ODM-2'
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(task.order_task_id), is_current=True,
).all()
assert matches and {m.chosen_odm_id for m in matches} == {'ODM-2'}
options = notice_odm_options(task)
assert options['lines'][0]['chosen_odm_id'] == 'ODM-2'
with pytest.raises(AppError) as exc:
set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-9')
assert getattr(exc.value, 'code', '') == 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
def test_notice_odm_choice_syncs_same_snapshot_file_lines(app, tmp_path):
"""同一快照文件的行:改任一行 ODM ID,其余行同步落库同一选择。"""
from app.services.shipping_notice.notice_odm_choice_service import (
notice_odm_options,
set_notice_odm_choice,
)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
{'part': 'PN-B', 'odm_values': ['ODM-2', 'ODM-3']},
])
options = notice_odm_options(task)
# [断言] 每行有自己的候选;同文件两行的可行集=交集。
by_sid = {str(item['snapshot_line_id']): item for item in options['lines']}
assert len(by_sid) == 2
assert options['lines'][0]['odm_values'] == ['ODM-1', 'ODM-2']
target_sid = options['lines'][0]['snapshot_line_id']
result = set_notice_odm_choice(
task, snapshot_line_id=target_sid, odm_id='ODM-2',
)
# [断言] 同步范围=同一快照文件:两行当前匹配行写同一选择。
assert result['synced_line_count'] == 2
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(task.order_task_id), is_current=True,
).all()
assert len(matches) == 2
assert {m.chosen_odm_id for m in matches} == {'ODM-2'}
options = notice_odm_options(task)
assert all(item['chosen_odm_id'] == 'ODM-2' for item in options['lines'])
def test_notice_odm_options_empty_when_template_ignores_odm(app, tmp_path):
"""模板不消费 odm 字段时投影为空候选,不产生任何选择入口。"""
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1'])
options = notice_odm_options(task)
assert options['odm_field_id'] is not None
assert options['lines'] and options['lines'][0]['odm_values'] == ['ODM-1']