feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口

完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
This commit is contained in:
hugo committed 2026-08-11 14:04:39 +08:00
1 parent 8e0bbf7a81
commit c94d173f92
181 files changed
+12947 -1724

No files matched your search

+155 -6
View File
@@ -19,12 +19,17 @@ from app import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
ShippingCase, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
)
from app.services.shipping_notice import excel_template
from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel
from app.services.shipping_notice.export import _excel_business_no, _filename, _mapping_value, _system_fact, generate_shipment_excel
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
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
@@ -132,6 +137,76 @@ def test_filename_pattern_supports_business_number_and_split_business_variables(
assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx'
def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cache(app, tmp_path):
"""业务执行必须使用活动库存 Link,忽略请求库存和旧任务缓存。"""
with app.app_context():
task = ShippingNotice(
task_no='TASK-INVENTORY-SOURCE', inventory_lines_json=[{'part_number': 'STALE'}],
)
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'}]
assert task.inventory_lines_json == [{'part_number': 'STALE'}]
def test_inventory_execution_keeps_legacy_fallback_without_active_link(app):
"""无活动 Link 的历史任务仍可读取请求库存或旧缓存,避免升级后无法恢复。"""
with app.app_context():
task = ShippingNotice(
task_no='TASK-INVENTORY-LEGACY', inventory_lines_json=[{'part_number': 'CACHE'}],
)
db.session.add(task)
db.session.flush()
assert resolve_inventory_lines_for_execution(
task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}],
) == [{'part_number': 'PAYLOAD'}]
assert resolve_inventory_lines_for_execution(task) == [{'part_number': 'CACHE'}]
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 = ShippingNotice(task_no='TASK-INVENTORY-NO-REPARSE')
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():
@@ -299,6 +374,54 @@ def test_export_date_system_fact_uses_business_timezone(app):
assert isinstance(value, date)
def test_excel_pull_request_number_uses_export_date_without_changing_case_number(app):
"""Excel Pull Request Number 必须采用导出日期,且业务单主编号保持原值。"""
with app.app_context():
shipping_case = ShippingCase(
case_no='CASE-EXCEL-NO', business_no='IVMX26080801', sequence_value=1,
)
task = ShippingNotice(task_no='TASK-EXCEL-NO')
task.shipping_case = shipping_case
assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26081101'
assert shipping_case.business_no == 'IVMX26080801'
def test_export_mapping_falls_back_to_export_sequence_and_derived_line_amount(app):
"""LineNumber 缺失时用导出行序号,Shipment Value 缺失时用数量乘单价。"""
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={}, export_sequence=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={},
) == 13184.64
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')
@@ -541,8 +664,8 @@ def test_template_publish_rejects_order_field_removed_from_current_schema(app):
assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID'
def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app, tmp_path):
"""同一匹配键对应多个不同 ODM 时必须阻断,且不得留下半成品 Excel。"""
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():
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
@@ -597,11 +720,37 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app,
lines=[(1, part.id, 'PN-A', 1, '1000000004')],
)
with pytest.raises(ValueError, match='值不一致'):
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')
task.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
assert task.inventory_lines_json[0][_inventory_field_id('odm_id')] == 'ODM-1'
def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch):
"""Artifact/任务事务提交失败时必须删除已生成文件,避免孤立 ready-looking 产物。"""