feat(shipping-notice): 添加 RPA 工作者心跳告警开关,更新环境配置以支持样本证据历史记录

This commit is contained in:
hugo committed 2026-07-19 23:15:25 +08:00
1 parent 705971ad03
commit 88408490d7
34 files changed
+1697 -109

No files matched your search

@@ -16,9 +16,10 @@ from werkzeug.datastructures import FileStorage
import pytest
from app.core.errors import ValidationError
from app.extensions import db
from app.services.shipping_notice import inventory_structure_analysis
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.models import ShippingInventoryField
from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis
def _field_id(field_code: str) -> str:
@@ -75,7 +76,7 @@ def _published_part_number() -> str:
def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_path):
"""上传样本必须定位真实库存表头,并仅返回少量样例和值类型统计。"""
"""上传样本必须定位真实库存表头,只持久化脱敏样例并清理完整工作簿。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
result = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
@@ -88,6 +89,35 @@ def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_p
qty = next(column for column in columns if column['header'] == 'Qty Available')
assert qty['inferred_type'] == 'number'
assert qty['sample_values'] == ['9', '11']
assert result['sample_rows'][0] == ['P***1', '10***51', 9, 'A***U', '00***74']
analysis = db.session.get(ShippingInventoryStructureAnalysis, result['id'])
assert analysis is not None
assert analysis.storage_path is None
assert analysis.sample_rows_json == result['sample_rows']
assert not list((tmp_path / 'shipping' / 'inventory_structure_analyses').rglob('*.xlsx'))
def test_sample_analysis_prefers_populated_detail_sheet_over_same_score_summary(app, tmp_path):
"""同分候选时必须优先明细表,且只保存最终选定工作表的脱敏样例。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
stream = BytesIO()
workbook = Workbook()
summary = workbook.active
summary.title = 'Summary'
summary.append(['Summary'])
summary.append(['SECRET-SUMMARY'])
inventory = workbook.create_sheet('Inventory')
inventory.append(['Supplier SKU', 'Reservation ID', 'Qty Available'])
inventory.append(['PART-001', 'RSV-001', 7])
workbook.save(stream)
stream.seek(0)
result = inventory_structure_analysis.create_sample_upload(
FileStorage(stream=stream, filename='multi-sheet.xlsx'), actor_id=None,
)
assert result['structure']['selected_sheet_name'] == 'Inventory'
assert result['sample_rows'] == [['PA***01', 'RS***01', 7]]
assert all('_sample_rows' not in candidate for candidate in result['structure']['candidates'])
def test_sample_analysis_reads_legacy_xls(app, tmp_path):
@@ -158,6 +188,89 @@ def test_profile_draft_uses_analysis_header_selection(app, tmp_path):
assert profile['status'] == 'draft'
assert profile['definition']['sheet_name'] == 'Inventory'
assert profile['definition']['field_mapping'][_field_id('part_number')] == 'Supplier Sku'
saved = db.session.get(ShippingInventoryParsingProfile, profile['id'])
assert saved is not None
assert saved.sample_analysis_id == analysis['id']
def test_profile_sample_replacement_requires_confirmation_and_keeps_audit_history(app, tmp_path):
"""替换草稿样本必须显式确认,成功后保留旧样本 ID 的可追溯链。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
field_id = _published_part_number()
first = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
profile = inventory_structure_analysis.create_profile_draft(first['id'], {
'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
}, actor_id=None)
second = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
preview = inventory_structure_analysis.preview_profile_sample_replacement(profile['id'], second['id'])
assert preview['can_confirm'] is True
assert preview['difference']['missing_mapped_headers'] == []
with pytest.raises(ValidationError) as exc_info:
inventory_structure_analysis.create_profile_draft(second['id'], {
'profile_id': profile['id'], 'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED'
updated = inventory_structure_analysis.create_profile_draft(second['id'], {
'profile_id': profile['id'], 'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
'confirm_sample_replacement': True,
}, actor_id=None)
assert updated['sample_analysis_id'] == second['id']
assert updated['sample_evidence_history'][-1]['previous_analysis_id'] == first['id']
assert updated['sample_evidence_history'][-1]['replacement_analysis_id'] == second['id']
def test_profile_sample_replacement_rejects_file_format_change(app, tmp_path):
"""草稿不能借由替换样本改变文件格式,防止运行期解析契约被静默改写。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
field_id = _published_part_number()
first = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
profile = inventory_structure_analysis.create_profile_draft(first['id'], {
'profile_code': 'FORMAT_REPLACEMENT', 'display_name': 'Format replacement',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
}, actor_id=None)
csv_upload = FileStorage(
stream=BytesIO(b'Supplier Sku,Reservation ID,Qty Available\nPN-001,R-1,1\n'),
filename='replacement.csv',
)
csv_analysis = inventory_structure_analysis.create_sample_upload(csv_upload, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
inventory_structure_analysis.create_profile_draft(csv_analysis['id'], {
'profile_id': profile['id'], 'profile_code': 'FORMAT_REPLACEMENT', 'display_name': 'Format replacement',
'header_row_index': 1, 'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
'confirm_sample_replacement': True,
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
def test_profile_draft_requires_persisted_sample_evidence(app):
"""绕过样本分析直接保存草稿时必须被拒绝,避免来源表头脱离审计依据。"""
with app.app_context():
field_id = _published_part_number()
from app.services.shipping_notice import inventory_parsing_profile
with pytest.raises(ValidationError) as exc_info:
inventory_parsing_profile.save_draft({
'profile_code': 'NO_EVIDENCE', 'display_name': 'No evidence', 'file_format': 'xlsx',
'definition': {
'sheet_name': 'Inventory', 'header_row_index': 1, 'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
},
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED'
def test_sample_analysis_rejects_invalid_file(app, tmp_path):