Files
syops/backend/tests/test_shipping_excel_template.py
hugo f5611d6783 fix(shipping-notice): 打通短缺放行链路的证据读点、决策码迁移与整单放行导出
生产实证(OT-20261027-4BD4CEFF):料号兜底自动放行不触发的根因是 s18 改名
漏迁移放行证据读点,getattr(source,'parsing_profile') 恒 None,致自动/人工
放行全部静默失败。三段修复:

1. 放行证据解析改读 source.onhand_report_config.parsing_profile
   (与 require_source_profile 同口径)。
2. 补批次 S 漏网迁移 s20a1b2c3d4e:复核行决策码 inventory→onhand 值替换,
   重建 ck_shipping_review_line_decisions_code(dev 往返验证后已应用 prod)。
3. 导出链回链 OT:_notice_source_code/_notice_inventory_file_id 纳入已审计
   放行行事实(整单放行不再报「库存源不存在」/丢证据快照);
   prepare_export_match_inputs 放行/结案决定 join 按 confirmed_task_id(OT) 回链。

回归:test_export_released_shortage_only_notice_resolves_source_and_rows
(先红后绿)等 117 项全绿。
2026-10-27 16:07:41 +08:00

1281 lines
65 KiB
Python
Raw Permalink 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, FreightRpaOnhandReportConfig, FreightRpaParsingProfile, FreightRpaSource, ShippingOrderExtraction,
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingCustomer, FreightRpaOnhandField, FreightRpaOnhandReportFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, FreightRpaProfile, ShippingNotice, ShippingOrderTask,
ShippingNoticeLineOnhandMatch, ShippingTaskOnhandLink,
)
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.onhand_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(FreightRpaOnhandField.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: FreightRpaOnhandReportFile,
source_code: str, notice_no: str, match_result: str = 'matched',
) -> 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(ShippingNoticeLineOnhandMatch(
task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no,
line_index=int(line.line_no) - 1,
match_result=match_result, onhand_status='ready',
onhand_snapshot_id=inventory_file.id, 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 = FreightRpaOnhandReportFile(
onhand_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'),
onhand_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 = FreightRpaOnhandReportFile(
onhand_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path),
onhand_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.onhand_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 = FreightRpaParsingProfile(
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 = FreightRpaProfile(
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 = FreightRpaSource(
source_code='DUB', display_name='Dublin', connector_type='dbs', rpa_profile_id=login.id,
excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB',
)
# s18 起解析绑定/报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行,随站点级联入库。
FreightRpaOnhandReportConfig(
source=source, parsing_profile_id=parsing.id,
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 = FreightRpaOnhandReportFile(
onhand_file_no='SIF-EXPORT-1', user_id=None,
source_file_name='inventory.xlsx', storage_path=str(tmp_path / 'inventory.xlsx'),
onhand_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 = FreightRpaParsingProfile(
profile_code='SHARED_INV', display_name='Shared Inventory', version=1, status='published',
file_format='xlsx', definition_json={}, checksum='p' * 64,
)
login = FreightRpaProfile(
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'):
shared_source = FreightRpaSource(
source_code=code, display_name=code, connector_type='dbs', rpa_profile_id=login.id,
excel_template_id=published['id'],
warehouse_resolution_mode='fixed', fixed_warehouse_id=code,
)
# s18 起解析绑定/报表路径/查询条件归配置行,随站点级联入库。
FreightRpaOnhandReportConfig(
source=shared_source, parsing_profile_id=parsing.id,
report_path_json={}, query_parameters_json=[],
)
db.session.add(shared_source)
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 = FreightRpaProfile(
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()
# s18 起站点行不再承载报表路径/查询条件;停用站点退役守卫只读模板绑定。
db.session.add(FreightRpaSource(
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',
))
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 = FreightRpaParsingProfile(
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 = FreightRpaProfile(
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()
keyed_source = FreightRpaSource(
source_code='KEYED', display_name='Keyed', connector_type='dbs', rpa_profile_id=login.id,
excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB',
)
# s18 起解析绑定/报表路径/查询条件归配置行,随站点级联入库。
FreightRpaOnhandReportConfig(
source=keyed_source, parsing_profile_id=parsing.id,
report_path_json={}, query_parameters_json=[],
)
db.session.add(keyed_source)
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 = FreightRpaOnhandReportFile(
onhand_file_no='SIF-KEYED', user_id=None, source_file_name='keyed.xlsx',
storage_path=str(tmp_path / 'keyed.xlsx'),
onhand_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 = FreightRpaParsingProfile(
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 = FreightRpaProfile(
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()
ambiguous_source = FreightRpaSource(
source_code='AMBIGUOUS', display_name='Ambiguous', connector_type='dbs', rpa_profile_id=login.id,
excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB',
)
# s18 起解析绑定/报表路径/查询条件归配置行,随站点级联入库。
FreightRpaOnhandReportConfig(
source=ambiguous_source, parsing_profile_id=parsing.id,
report_path_json={}, query_parameters_json=[],
)
db.session.add(ambiguous_source)
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 = FreightRpaOnhandReportFile(
onhand_file_no='SIF-AMBIGUOUS', user_id=None, source_file_name='ambiguous.xlsx',
storage_path=str(tmp_path / 'ambiguous.xlsx'),
onhand_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 = FreightRpaOnhandReportFile(
onhand_file_no='SIF-ACTIVE-FIXED', user_id=None,
source_file_name='fixed.xlsx', storage_path=str(tmp_path / 'fixed.xlsx'),
onhand_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 ShippingNoticeLineOnhandMatch.query.filter_by(task_id=ot.id, is_current=True).all():
match.onhand_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,
released_shortage: bool = False, unreleased_shortage: bool = False,
order_part: str = 'PN-A', inventory_part: str | None = 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)
released_shortage: True 时唯一行构造为短缺放行场景——订单料号不在库存行
(匹配键 0 命中)、事实落 not_found、并落已确认复核 Case 的系统放行决定
(release_field_values 携带 ODM 证据值),整单无任何 matched 事实。
unreleased_shortage: True 时事实落 not_found 但不落放行决定(未放行短缺)。
order_part / inventory_part: 订单行与库存行的料号(放行场景两者必须不同)。
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 = FreightRpaParsingProfile(
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 = FreightRpaProfile(
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()
odm_source = FreightRpaSource(
source_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', rpa_profile_id=login.id,
excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB',
)
# s18 起解析绑定/报表路径/查询条件归配置行,随站点级联入库。
FreightRpaOnhandReportConfig(
source=odm_source, parsing_profile_id=parsing.id,
report_path_json={}, query_parameters_json=[],
)
db.session.add(odm_source)
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': order_part, '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'): inventory_part or spec['part'], _inventory_field_id('odm_id'): odm})
inventory_file = FreightRpaOnhandReportFile(
onhand_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
storage_path=str(tmp_path / 'odm-scope.xlsx'),
onhand_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',
match_result='not_found' if (released_shortage or unreleased_shortage) else 'matched',
)
if released_shortage:
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
case = ShippingOrderReviewCase(
case_no='CASE-ODMSCOPE-RELEASE', run_id=931, unit_id=932, document_id=933,
owner_user_id=1, status='confirmed', confirmed_task_id=int(ot.id),
)
db.session.add(case); db.session.flush()
db.session.add(ShippingOrderReviewLineDecision(
review_case_id=case.id, draft_line_id='line-1', line_index=0,
decision_code='release_onhand_shortage', decision_source='system',
line_status='released_shortage', is_active=True,
snapshot_json={
'release_field_values': {str(_inventory_field_id('odm_id')): 'ODM-1'},
'release_evidence_scope': 'part_fallback',
},
))
db.session.flush()
if choice_odm is not None:
for match in ShippingNoticeLineOnhandMatch.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_unique_hit_odm_bypasses_customer_range(app, tmp_path):
"""唯一命中 ODM 免白名单:Excel 里只有一个 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, odm_values=['ODM-1'], customer_odm_ids=['ODM-9'],
)
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-1'
finally:
workbook.close()
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_export_released_shortage_only_notice_resolves_source_and_rows(app, tmp_path):
"""整单短缺放行(0 条 matched 事实)也能解析库存源并按放行证据导出。
回归 OT-20261027-4BD4CEFF:预约键 0 命中→料号兜底自动放行后,行事实恒为
not_found;_notice_source_code 只认 matched 会让整单放行的单报
「库存源不存在或已停用」;prepare_export_match_inputs 的放行决定 join 须按
confirmed_task_id(OT) 回链,Notice 身份调用不得丢放行行。
"""
from app.services.shipping_notice.export import _notice_source_code, prepare_export_match_inputs
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
notice, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, released_shortage=True,
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
)
# 断言意图 1:源解析把放行行事实与 matched 行同票,整单放行也能拿到唯一源。
assert _notice_source_code(notice) == 'ODMSCOPE'
# 断言意图 2:以 Notice 身份准备导出输入,放行决定经 OT 回链可查到,
# 放行行进入导出行集并携带审计补录值(无 matched 事实也不报「没有匹配」)。
inputs = prepare_export_match_inputs(notice)
assert inputs['released_snapshot_line_ids']
assert inputs['released_export_line_indexes'] == {0}
assert list(inputs['release_overrides_by_line'][0].values()) == ['ODM-1']
assert [row['__order_line_index'] for row in inputs['line_values']] == [0]
# 断言意图 3:整单放行时证据快照仍落 Artifact 审计(matched-only 不再断证据链)。
assert inputs['verification'] is not None
path, _filename_value, _artifact = generate_shipment_excel(notice)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-1'
finally:
workbook.close()
def test_unreleased_shortage_notice_still_lacks_source(app, tmp_path):
"""未放行的短缺行不得参与源解析:matched-only 语义对未放行场景保持不变。"""
from app.services.shipping_notice.export import _notice_source_code
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
notice, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, unreleased_shortage=True,
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
)
# 断言意图:not_found 且无放行决定的事实不充当导出源依据(fail-closed 不变)。
assert _notice_source_code(notice) is None
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 = ShippingNoticeLineOnhandMatch.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 = ShippingNoticeLineOnhandMatch.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']