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,7 +16,7 @@ from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import inventory_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service
from app import db
from app.models import ShippingExcelTemplate, ShippingInventoryField
from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryStructureAnalysis
def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict:
@@ -27,6 +27,26 @@ def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict:
}
def _sample_evidence() -> int:
"""创建最小表头证据,确保库存源服务测试不绕过解析方案样本门禁。"""
item = ShippingInventoryStructureAnalysis(
source_kind='sample_upload', source_file_name='service-sample.xlsx', storage_path=None,
file_checksum='b' * 64, file_format='xlsx', analysis_status='ready',
structure_json={'candidates': [{
'sheet_name': None, 'header_row_index': 1,
'headers': ['Supplier Sku', 'Reservation ID', 'Qty Available'],
'columns': [
{'header': 'Supplier Sku', 'duplicate': False},
{'header': 'Reservation ID', 'duplicate': False},
{'header': 'Qty Available', 'duplicate': False},
],
}]}, suggested_mapping_json={}, validation_summary_json={}, sample_rows_json=[], warning_json=[],
)
db.session.add(item)
db.session.flush()
return item.id
def _parsing_profile() -> dict:
"""发布可由多个库存源共享的最小库存解析 Profile。"""
state = order_schema_service.get_state()
@@ -63,6 +83,7 @@ def _parsing_profile() -> dict:
assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'}
draft = inventory_parsing_profile.save_draft({
'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx',
'sample_analysis_id': _sample_evidence(),
'definition': {
'header_row_index': 1,
'field_mapping': {
@@ -206,6 +227,35 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
def test_activation_status_exposes_structured_checks_without_duplicate_test_blocks(app):
"""未测试站点应显示后续验证步骤,但只由测试门禁阻断,避免管理员面对重复待办。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
payload = {
'source_code': 'CHECKS_SOURCE', 'display_name': 'Checks Source', 'connector_type': 'dbs',
'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None,
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand',
},
'query_parameters_json': [], 'match_aliases_json': [], 'enabled': False,
}
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
checks = {item['code']: item for item in draft['activation']['checks']}
# 关键断言:未进行测试时,解析/仓库验证被展示为待测试而非额外阻断门禁。
assert checks['configuration_test']['blocking'] is True
assert checks['configuration_test']['evidence'] == {'state': 'not_started'}
assert checks['parsing_validation']['status'] == 'pending'
assert checks['parsing_validation']['blocking'] is False
assert checks['warehouse_mapping']['status'] == 'pending'
assert checks['warehouse_mapping']['blocking'] is False
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
def test_enabled_source_rejects_disabled_rpa_profile(app):
"""启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
@@ -176,3 +176,33 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
error = parse_api_error(activation.get_json())
assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
def test_latest_inventory_configuration_test_is_admin_only(app, client):
"""最近测试状态仅允许管理员读取,且没有测试记录时仍返回标准空数据 envelope。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
profile = ShippingRpaProfile(
profile_code='API_LATEST_TEST_LOGIN', display_name='Latest Test', connector_type='dbs',
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
)
db.session.add(profile)
source = ShippingInventorySource(
source_code='API_LATEST_TEST_SOURCE', display_name='Latest Test Source', connector_type='dbs',
rpa_profile=profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
query_parameters_json=[], match_aliases_json=[], enabled=False,
)
db.session.add(source)
db.session.commit()
source_id = source.id
forbidden = client.get(f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest')
assert forbidden.status_code in {401, 403}
response = client.get(
f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest',
headers=_headers('inventory-admin', 'admin'),
)
assert response.status_code == 200
assert parse_api_data(response.get_json()) is None
@@ -2,6 +2,7 @@
from __future__ import annotations
from datetime import datetime, timedelta
from pathlib import Path
from unittest.mock import patch
@@ -18,6 +19,7 @@ from app.models import (
ShippingExcelTemplate,
ShippingInventoryFile,
ShippingInventoryField,
ShippingRpaProfile,
ShippingInventorySource,
)
from app.services.admin import shipping_inventory_service
@@ -125,6 +127,57 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp
assert ShippingInventoryConfigurationTestRun.query.count() == 1
def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_path):
"""重开配置抽屉只能恢复当前版本测试;站点改动后可发起独立新测试而不复用旧运行。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
first = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
assert inventory_configuration_test.get_latest_test_run(source['id'])['run_no'] == first['run_no']
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
shipping_inventory_service.save_source({**current, 'display_name': 'Changed before callback'}, actor_id=None, source_id=source['id'])
# 关键断言:旧运行不再属于当前配置,重新测试必须创建新运行而不是误复用。
assert inventory_configuration_test.get_latest_test_run(source['id']) is None
second = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
assert second['run_no'] != first['run_no']
assert inventory_configuration_test.get_latest_test_run(source['id'])['run_no'] == second['run_no']
def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
"""RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one()
run.created_at = datetime.utcnow() - timedelta(seconds=2)
db.session.commit()
recovered = inventory_configuration_test.get_latest_test_run(source['id'])
# 关键断言:超时是明确失败终态,客户端无需自行推断或继续轮询。
assert recovered['status'] == 'failed'
assert recovered['stage'] == 'failed'
assert '超时' in recovered['error_message']
result_file = tmp_path / 'late-rpa-result.xlsx'
_workbook(result_file)
late_callback = inventory_configuration_test.report_test_export({
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
})
# 关键断言:超时后的迟到回调不能将失败任务重新写成完成,也不能生成结构分析证据。
assert late_callback['status'] == 'failed'
assert ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one().analysis_id is None
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
"""确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
@@ -165,6 +218,40 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
db.session.commit()
assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True
assert shipping_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True
assert next(
item for item in shipping_inventory_service.get_source_activation_status(source_model)['checks']
if item['code'] == 'configuration_test'
)['status'] == 'passed'
def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path):
"""连接凭据或登录配置变更后,旧测试不得继续作为当前库存站点的启用证据。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
completed = _complete_test_run(source, tmp_path)
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='PROFILE_STALE')
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
rpa_profile = db.session.get(ShippingRpaProfile, source['rpa_profile_id'])
shipping_inventory_service.save_profile({
'profile_code': rpa_profile.profile_code, 'display_name': rpa_profile.display_name,
'connector_type': rpa_profile.connector_type, 'login_url': rpa_profile.login_url,
'login_config_json': rpa_profile.login_config_json, 'enabled': True,
'username': 'updated-user', 'password': 'updated-password',
}, actor_id=None, profile_id=rpa_profile.id)
source_model = db.session.get(ShippingInventorySource, source['id'])
test_check = next(
item for item in shipping_inventory_service.get_source_activation_status(source_model)['checks']
if item['code'] == 'configuration_test'
)
# 关键断言:连接配置版本变更使已完成测试失效,不能继续放行正式运行。
assert test_check['status'] == 'stale'
assert test_check['blocking'] is True
def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path):
@@ -184,6 +271,15 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
assert stale.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE'
# 关键断言:旧配置版本的测试只能作为过期证据展示,不能被误判为当前测试通过。
stale_status = shipping_inventory_service.get_source_activation_status(
db.session.get(ShippingInventorySource, source['id']),
)
test_check = next(item for item in stale_status['checks'] if item['code'] == 'configuration_test')
assert test_check['status'] == 'stale'
assert test_check['blocking'] is True
assert test_check['evidence']['run_no'] == completed['run_no']
source_model = db.session.get(ShippingInventorySource, source['id'])
source_model.parsing_profile_id = profile['id']
template = ShippingExcelTemplate(
@@ -221,12 +317,13 @@ def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
_publish_profile_from_analysis(completed['analysis_id'], field_id, code='TEST_MATCHED')
unrelated = inventory_parsing_profile.save_draft({
'profile_code': 'TEST_UNRELATED', 'display_name': 'Unrelated', 'file_format': 'xlsx',
'sample_analysis_id': completed['analysis_id'],
'definition': {
'sheet_name': 'Other', 'header_row_index': 1,
'sheet_name': 'Sheet', 'header_row_index': 1,
'field_mapping': {
_inventory_field_id('part_number'): 'Other Part',
_inventory_field_id('reservation_id'): 'Other Reservation',
_inventory_field_id('available_qty'): 'Other Qty',
_inventory_field_id('part_number'): 'Supplier Sku',
_inventory_field_id('reservation_id'): 'Reservation ID',
_inventory_field_id('available_qty'): 'Qty Available',
},
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}],
},
@@ -12,7 +12,7 @@ from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import inventory_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service
from app import db
from app.models import ShippingExcelTemplate, ShippingInventoryField
from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryStructureAnalysis
def _inventory_mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]:
@@ -30,6 +30,21 @@ def _part_number_field_id() -> str:
return str(ShippingInventoryField.query.filter_by(field_code='part_number').one().id)
def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_format: str = 'xlsx') -> int:
"""构造最小化样本结构证据,使 Profile 测试遵循生产环境的表头绑定门禁。"""
item = ShippingInventoryStructureAnalysis(
source_kind='sample_upload', source_file_name='sample.xlsx', storage_path=None,
file_checksum='a' * 64, file_format=file_format, analysis_status='ready',
structure_json={'candidates': [{
'sheet_name': sheet_name, 'header_row_index': 1, 'headers': headers,
'columns': [{'header': header, 'duplicate': False} for header in headers],
}]}, suggested_mapping_json={}, validation_summary_json={}, sample_rows_json=[], warning_json=[],
)
db.session.add(item)
db.session.flush()
return item.id
def _published_profile() -> dict:
"""创建含 part_number 匹配键的 published 解析 Profile。"""
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
@@ -44,6 +59,7 @@ def _published_profile() -> dict:
)
draft = inventory_parsing_profile.save_draft({
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common', 'file_format': 'xlsx',
'sample_analysis_id': _sample_evidence(headers=['Supplier Sku', 'Reservation ID', 'Qty Available']),
'definition': {
'header_row_index': 1,
'field_mapping': _inventory_mapping(),
@@ -122,9 +138,11 @@ def test_source_rejects_draft_parsing_profile(app):
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
draft = inventory_parsing_profile.save_draft({
'profile_code': 'DRAFT_ONLY', 'display_name': 'Draft', 'definition': {
'sheet_name': None, 'header_row_index': 1,
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
},
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
}, actor_id=None)
login = shipping_inventory_service.save_profile({
'profile_code': 'LOGIN', 'display_name': 'Login', 'connector_type': 'dbs',
@@ -163,7 +181,9 @@ def test_new_published_version_does_not_retire_bound_version(app):
field_id = order_schema_service.get_state()['fields'][0]['id']
second_draft = inventory_parsing_profile.save_draft({
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx',
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
'definition': {
'header_row_index': 1,
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_field_id()}],
},
@@ -204,7 +224,9 @@ def test_parsing_profile_publish_rejects_field_removed_from_current_schema(app):
)
profile = inventory_parsing_profile.save_draft({
'profile_code': 'STALE_FIELD', 'display_name': 'Stale Field',
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
'definition': {
'sheet_name': None, 'header_row_index': 1,
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': old_field['id'], 'inventory_field_id': _part_number_field_id()}],
},
@@ -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):