feat(shipping-notice): 添加 RPA 工作者心跳告警开关,更新环境配置以支持样本证据历史记录
This commit is contained in:
1 parent
705971ad03
commit
88408490d7
34 files changed
+1697
-109
No files matched your search
@@ -187,6 +187,15 @@ def start_shipping_inventory_configuration_test(source_id: int):
|
||||
return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/latest', methods=['GET'])
|
||||
@require_admin
|
||||
def get_latest_shipping_inventory_configuration_test(source_id: int):
|
||||
"""读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.get_latest_test_run(source_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
|
||||
@@ -350,6 +359,15 @@ def update_shipping_inventory_parsing_profile(profile_id: int):
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int):
|
||||
"""比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。"""
|
||||
return _ok(inventory_structure_analysis.preview_profile_sample_replacement(
|
||||
profile_id, analysis_id, request.get_json(silent=True) or {},
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_inventory_parsing_profile(profile_id: int):
|
||||
|
||||
@@ -266,7 +266,7 @@ class Config:
|
||||
or '.hxops_rpa_shared_mount'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'true').lower() == 'true'
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
|
||||
|
||||
@@ -126,7 +126,7 @@ class ShippingInventorySource(Base):
|
||||
|
||||
|
||||
class ShippingInventoryParsingProfile(Base):
|
||||
"""可跨库存源复用的库存文件结构与订单匹配配置。"""
|
||||
"""可跨库存源复用的库存文件结构、样本证据与订单匹配配置。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_parsing_profiles'
|
||||
__table_args__ = (
|
||||
@@ -147,16 +147,27 @@ class ShippingInventoryParsingProfile(Base):
|
||||
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
|
||||
sample_analysis_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
|
||||
)
|
||||
# Preserve every confirmed evidence switch so a draft remains explainable after samples change.
|
||||
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
JSON, nullable=False, default=list, server_default=text("'[]'"),
|
||||
)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile')
|
||||
sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship(
|
||||
foreign_keys=[sample_analysis_id],
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryStructureAnalysis(Base):
|
||||
"""库存文件结构分析记录;保存受控样例与建议,不承载正式库存快照。"""
|
||||
"""库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_structure_analyses'
|
||||
__table_args__ = (
|
||||
@@ -169,13 +180,15 @@ class ShippingInventoryStructureAnalysis(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
source_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='sample_upload', server_default='sample_upload')
|
||||
source_file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
# Only temporary conversation sessions retain a short-lived source file for confirmation.
|
||||
storage_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
file_format: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
analysis_status: Mapped[str] = mapped_column(String(32), nullable=False, default='ready', server_default='ready')
|
||||
structure_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
suggested_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
validation_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
sample_rows_json: Mapped[list[list[Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
warning_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
|
||||
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -185,7 +198,7 @@ class ShippingInventoryStructureAnalysis(Base):
|
||||
|
||||
|
||||
class ShippingInventoryConfigurationTestRun(Base):
|
||||
"""库存站点配置测试的异步 RPA 运行;测试文件不能进入生产库存池。"""
|
||||
"""库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_configuration_test_runs'
|
||||
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),)
|
||||
@@ -194,6 +207,7 @@ class ShippingInventoryConfigurationTestRun(Base):
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
||||
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
|
||||
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
|
||||
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True)
|
||||
|
||||
@@ -406,7 +406,12 @@ def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str
|
||||
source_config_version=source.config_version,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {}
|
||||
if not confirmed_test or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0):
|
||||
if (
|
||||
not confirmed_test
|
||||
or source.rpa_profile is None
|
||||
or confirmed_test.rpa_profile_config_version != source.rpa_profile.config_version
|
||||
or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0)
|
||||
):
|
||||
return ['configuration_test'], details
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id)
|
||||
profile = source.parsing_profile
|
||||
@@ -503,29 +508,118 @@ def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
|
||||
return ['template_validation'] if not mappings or invalid else []
|
||||
|
||||
|
||||
def _activation_missing_requirements(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]:
|
||||
"""计算库存站点进入正式运行前尚未完成的业务步骤和测试验证详情。"""
|
||||
missing: list[str] = []
|
||||
if source.rpa_profile is None or not source.rpa_profile.enabled:
|
||||
missing.append('rpa_profile')
|
||||
if source.parsing_profile is None or source.parsing_profile.status != 'published':
|
||||
missing.append('parsing_profile')
|
||||
if source.excel_template is None or source.excel_template.status != 'published':
|
||||
missing.append('excel_template')
|
||||
else:
|
||||
missing.extend(_template_validation_missing(source))
|
||||
def _latest_test_run_evidence(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""提取最近一次配置测试的非敏感证据,供上线检查说明测试是否过期或失败。"""
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source.id,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
if run is None:
|
||||
return {'state': 'not_started'}
|
||||
profile_version = source.rpa_profile.config_version if source.rpa_profile is not None else None
|
||||
if (
|
||||
run.source_config_version != source.config_version
|
||||
or run.rpa_profile_config_version != profile_version
|
||||
):
|
||||
return {
|
||||
'state': 'stale', 'run_no': run.run_no, 'status': run.status,
|
||||
'source_config_version': run.source_config_version,
|
||||
'rpa_profile_config_version': run.rpa_profile_config_version,
|
||||
}
|
||||
if run.status == 'failed':
|
||||
return {'state': 'failed', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
return {'state': 'current', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
|
||||
|
||||
|
||||
def _activation_check(
|
||||
code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None,
|
||||
blocking: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造单项上线门禁结果,确保管理端只展示服务端已判定的业务事实。"""
|
||||
return {
|
||||
'code': code,
|
||||
'status': status or ('passed' if passed else 'pending'),
|
||||
'blocking': not passed if blocking is None else blocking,
|
||||
'action': action,
|
||||
'evidence': evidence,
|
||||
}
|
||||
|
||||
|
||||
def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]:
|
||||
"""构建库存站点正式运行的权威检查清单。
|
||||
|
||||
检查项按管理员完成配置的业务顺序返回。测试、解析、模板和仓库映射均以当前
|
||||
``config_version`` 的持久化事实为准,避免管理端依据本地表单状态猜测启用资格。
|
||||
"""
|
||||
validation_missing, validation_details = _test_analysis_validation(source)
|
||||
missing.extend(validation_missing)
|
||||
return missing, validation_details
|
||||
missing = set(validation_missing)
|
||||
test_evidence = _latest_test_run_evidence(source)
|
||||
test_complete = 'configuration_test' not in missing
|
||||
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
|
||||
parsing_ready = source.parsing_profile is not None and source.parsing_profile.status == 'published'
|
||||
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
|
||||
template_valid = template_ready and 'template_validation' not in missing
|
||||
checks = [
|
||||
_activation_check(
|
||||
'rpa_profile', passed=profile_ready, action='configure_connection',
|
||||
evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready},
|
||||
),
|
||||
_activation_check(
|
||||
'parsing_profile', passed=parsing_ready, action='configure_parsing_profile',
|
||||
evidence={'profile_id': source.parsing_profile_id, 'published': parsing_ready},
|
||||
),
|
||||
_activation_check(
|
||||
'excel_template', passed=template_ready, action='configure_excel_template',
|
||||
evidence={'template_id': source.excel_template_id, 'published': template_ready},
|
||||
),
|
||||
_activation_check(
|
||||
'template_validation', passed=not template_ready or template_valid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_ready and not template_valid,
|
||||
),
|
||||
_activation_check(
|
||||
'configuration_test', passed=test_complete,
|
||||
action='run_configuration_test', evidence=test_evidence,
|
||||
status=test_evidence['state'] if test_evidence['state'] in {'stale', 'failed'} else None,
|
||||
),
|
||||
_activation_check(
|
||||
'parsing_validation', passed=test_complete and 'parsing_validation' not in missing,
|
||||
action='run_configuration_test', evidence={'sample_warehouses': validation_details['sample_warehouses']},
|
||||
status='pending' if not test_complete else None, blocking='parsing_validation' in missing,
|
||||
),
|
||||
]
|
||||
if source.warehouse_resolution_mode == 'inventory_match':
|
||||
checks.append(_activation_check(
|
||||
'warehouse_identification', passed=test_complete and 'warehouse_identification' not in missing,
|
||||
action='configure_parsing_profile', evidence={'sample_warehouses': validation_details['sample_warehouses']},
|
||||
status='pending' if not test_complete else None, blocking='warehouse_identification' in missing,
|
||||
))
|
||||
checks.append(_activation_check(
|
||||
'warehouse_mapping', passed=test_complete and 'warehouse_mapping' not in missing, action='configure_warehouse_mapping',
|
||||
evidence={
|
||||
'mode': source.warehouse_resolution_mode,
|
||||
'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'sample_warehouses': validation_details['sample_warehouses'],
|
||||
},
|
||||
status='pending' if not test_complete else None, blocking='warehouse_mapping' in missing,
|
||||
))
|
||||
return checks
|
||||
|
||||
|
||||
def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""返回库存站点启用检查结果,供管理端展示下一步操作。"""
|
||||
missing, validation = _activation_missing_requirements(source)
|
||||
"""返回库存站点正式运行的结构化门禁结果。
|
||||
|
||||
Args:
|
||||
source: 已持久化的库存站点,关联配置由当前数据库事务提供。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: ``checks`` 为前端唯一的检查真相;``ready`` 为启用结论;
|
||||
``missing_requirements`` 是由 checks 派生的紧凑摘要,供现有调用方读取。
|
||||
"""
|
||||
checks = _source_activation_checks(source)
|
||||
missing = [item['code'] for item in checks if item['blocking']]
|
||||
return {
|
||||
'ready': not missing,
|
||||
'checks': checks,
|
||||
'missing_requirements': missing,
|
||||
'validation': validation,
|
||||
}
|
||||
|
||||
|
||||
@@ -543,7 +637,6 @@ def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
)
|
||||
source.enabled = True
|
||||
source.updated_by = actor_id
|
||||
source.config_version += 1
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
@@ -555,7 +648,6 @@ def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
source.enabled = False
|
||||
source.updated_by = actor_id
|
||||
source.config_version += 1
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
@@ -8,11 +8,11 @@ services/shipping_notice/inventory_configuration_test.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
@@ -26,15 +26,56 @@ def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
|
||||
"""投影测试运行状态,避免暴露 RPA 文件的服务器路径。"""
|
||||
return {
|
||||
'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id,
|
||||
'source_config_version': run.source_config_version, 'status': run.status, 'stage': run.stage,
|
||||
'source_config_version': run.source_config_version, 'rpa_profile_config_version': run.rpa_profile_config_version,
|
||||
'status': run.status, 'stage': run.stage,
|
||||
'analysis_id': run.analysis_id, 'result': run.result_json or {}, 'error_message': run.error_message,
|
||||
'created_at': run.created_at.isoformat() if run.created_at else None,
|
||||
'completed_at': run.completed_at.isoformat() if run.completed_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, source: ShippingInventorySource) -> bool:
|
||||
"""判断测试运行是否仍对应当前站点与 RPA 连接配置,避免旧任务阻塞新配置测试。"""
|
||||
return bool(
|
||||
source.rpa_profile
|
||||
and run.source_config_version == source.config_version
|
||||
and run.rpa_profile_config_version == source.rpa_profile.config_version
|
||||
)
|
||||
|
||||
|
||||
def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
|
||||
"""将超出库存 RPA 等待窗口的当前测试标记为失败,避免管理端无限轮询。"""
|
||||
timeout = max(1, int(current_app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS']))
|
||||
deadline = datetime.utcnow() - timedelta(seconds=timeout)
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
ShippingInventoryConfigurationTestRun.created_at < deadline,
|
||||
).all()
|
||||
for run in runs:
|
||||
run.status = 'failed'
|
||||
run.stage = 'failed'
|
||||
run.error_message = '测试导出等待 RPA Worker 超时,请重新测试'
|
||||
run.completed_at = datetime.utcnow()
|
||||
|
||||
|
||||
def get_latest_test_run(source_id: int) -> dict[str, Any] | None:
|
||||
"""返回站点当前配置对应的最近测试运行,供管理端刷新或重开抽屉后恢复真实状态。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
_expire_timed_out_runs(source)
|
||||
db.session.commit()
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source.id,
|
||||
source_config_version=source.config_version,
|
||||
rpa_profile_config_version=source.rpa_profile.config_version if source.rpa_profile else -1,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
return _payload(run) if run else None
|
||||
|
||||
|
||||
def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""为停用库存站点写入专用测试 trigger;重复点击复用等待中的运行。"""
|
||||
"""为停用库存站点写入专用测试 trigger;仅复用同一配置版本仍在运行的任务。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
@@ -42,8 +83,11 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
|
||||
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID')
|
||||
if source.rpa_profile is None or not source.rpa_profile.enabled:
|
||||
raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED')
|
||||
_expire_timed_out_runs(source)
|
||||
active = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.source_config_version == source.config_version,
|
||||
ShippingInventoryConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
if active:
|
||||
@@ -54,6 +98,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
|
||||
run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||
run = ShippingInventoryConfigurationTestRun(
|
||||
run_no=run_no, inventory_source_id=source.id, source_config_version=source.config_version,
|
||||
rpa_profile_config_version=source.rpa_profile.config_version,
|
||||
status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id,
|
||||
)
|
||||
db.session.add(run)
|
||||
@@ -83,6 +128,10 @@ def get_test_run(source_id: int, run_no: str) -> dict[str, Any]:
|
||||
).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is not None:
|
||||
_expire_timed_out_runs(source)
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
|
||||
|
||||
@@ -92,10 +141,10 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
|
||||
if run.status == 'completed':
|
||||
if run.status in {'completed', 'failed'}:
|
||||
return _payload(run)
|
||||
source = db.session.get(ShippingInventorySource, run.inventory_source_id)
|
||||
if source is None or source.config_version != run.source_config_version:
|
||||
if source is None or not _matches_current_configuration(run, source):
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
@@ -109,28 +158,24 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, _analysis_root, serialize_analysis
|
||||
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, serialize_analysis
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
|
||||
from app.models import ShippingInventoryStructureAnalysis
|
||||
import hashlib
|
||||
import uuid
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition
|
||||
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
|
||||
|
||||
run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush()
|
||||
suffix = resolve_inventory_upload_suffix(path.name)
|
||||
raw = path.read_bytes()
|
||||
target_dir = _analysis_root() / uuid.uuid4().hex
|
||||
target_dir.mkdir(parents=True, exist_ok=False)
|
||||
target = target_dir / f'test{suffix}'
|
||||
try:
|
||||
shutil.copy2(path, target)
|
||||
structure, suggested, summary, warnings = _analyse_path(target, suffix)
|
||||
# The RPA download is only read for analysis; configuration evidence never retains a second full workbook copy.
|
||||
structure, suggested, summary, warnings = _analyse_path(path, suffix)
|
||||
definition = structure_definition(file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', []))
|
||||
analysis = ShippingInventoryStructureAnalysis(
|
||||
source_kind='configuration_test', source_file_name=path.name, storage_path=str(target), file_checksum=hashlib.sha256(raw).hexdigest(),
|
||||
source_kind='configuration_test', source_file_name=path.name, storage_path=None, file_checksum=hashlib.sha256(raw).hexdigest(),
|
||||
file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
|
||||
validation_summary_json=summary, warning_json=warnings, created_by=run.created_by,
|
||||
validation_summary_json=summary, sample_rows_json=list(structure.get('selected_sample_rows') or []), warning_json=warnings, created_by=run.created_by,
|
||||
exact_structure_fingerprint=exact_fingerprint(definition), compatibility_fingerprint=compatibility_fingerprint(definition=definition, field_mapping=suggested, match_keys=[]),
|
||||
)
|
||||
db.session.add(analysis); db.session.flush()
|
||||
@@ -138,7 +183,6 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
run.analysis_id = analysis.id; run.status = 'completed'; run.stage = 'ready_for_confirmation'; run.result_json = {'analysis': serialize_analysis(analysis)}; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
shutil.rmtree(target_dir, ignore_errors=True)
|
||||
db.session.rollback()
|
||||
raise
|
||||
return _payload(run)
|
||||
@@ -153,7 +197,12 @@ def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
if source is None or profile is None or profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
if source.enabled or source.config_version != run.source_config_version:
|
||||
if (
|
||||
source.enabled
|
||||
or source.config_version != run.source_config_version
|
||||
or source.rpa_profile is None
|
||||
or source.rpa_profile.config_version != run.rpa_profile_config_version
|
||||
):
|
||||
raise ConflictError('Inventory Source configuration changed', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE')
|
||||
from app.services.shipping_notice.inventory_structure_analysis import adopt_published_profile
|
||||
|
||||
@@ -162,6 +211,7 @@ def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_
|
||||
source.updated_by = actor_id
|
||||
source.config_version += 1
|
||||
run.source_config_version = source.config_version
|
||||
run.rpa_profile_config_version = source.rpa_profile.config_version
|
||||
run.result_json = {**(run.result_json or {}), 'confirmed_profile_id': profile.id, 'confirmed_profile_checksum': profile.checksum}
|
||||
db.session.commit()
|
||||
return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id}
|
||||
@@ -21,6 +21,7 @@ from app.models import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryStructureAnalysis,
|
||||
ShippingOrderField,
|
||||
)
|
||||
|
||||
@@ -97,14 +98,75 @@ def _validate_definition(raw: Any) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _require_sample_evidence(
|
||||
sample_analysis_id: Any,
|
||||
definition: dict[str, Any],
|
||||
*,
|
||||
file_format: str,
|
||||
) -> ShippingInventoryStructureAnalysis:
|
||||
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
|
||||
try:
|
||||
analysis_id = int(sample_analysis_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Parsing profile requires sample analysis evidence',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
|
||||
) from exc
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format:
|
||||
raise ValidationError(
|
||||
'Parsing profile sample analysis evidence is unavailable',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
|
||||
selected = next((candidate for candidate in candidates if isinstance(candidate, dict)
|
||||
and candidate.get('sheet_name') == definition.get('sheet_name')
|
||||
and candidate.get('header_row_index') == definition.get('header_row_index')), None)
|
||||
if not isinstance(selected, dict):
|
||||
raise ValidationError(
|
||||
'Parsing profile worksheet or header row is not present in sample evidence',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()}
|
||||
if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()):
|
||||
raise ValidationError(
|
||||
'Parsing profile mapping is not present in sample evidence',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
duplicates = {
|
||||
str(column.get('header') or '').strip()
|
||||
for column in selected.get('columns', []) if isinstance(column, dict) and column.get('duplicate')
|
||||
}
|
||||
if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()):
|
||||
raise ValidationError(
|
||||
'Parsing profile mapping uses duplicate sample headers',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
return analysis
|
||||
|
||||
|
||||
def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
|
||||
"""序列化解析 Profile 管理 DTO。"""
|
||||
sample_analysis = profile.sample_analysis
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
|
||||
'definition': profile.definition_json or {}, 'checksum': profile.checksum,
|
||||
'published_at': profile.published_at.isoformat() if profile.published_at else None,
|
||||
'source_count': len(profile.sources),
|
||||
'sample_analysis_id': profile.sample_analysis_id,
|
||||
'sample_evidence_history': profile.sample_evidence_history_json or [],
|
||||
'sample_evidence': {
|
||||
'id': sample_analysis.id,
|
||||
'source_file_name': sample_analysis.source_file_name,
|
||||
'file_checksum': sample_analysis.file_checksum,
|
||||
'file_format': sample_analysis.file_format,
|
||||
'structure': sample_analysis.structure_json or {},
|
||||
'sample_rows': sample_analysis.sample_rows_json or [],
|
||||
'validation_summary': sample_analysis.validation_summary_json or {},
|
||||
'created_at': sample_analysis.created_at.isoformat() if sample_analysis.created_at else None,
|
||||
} if sample_analysis is not None else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -116,7 +178,7 @@ def list_profiles() -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新解析 Profile 草稿;published 版本不可原地修改。"""
|
||||
"""创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
@@ -132,13 +194,37 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
|
||||
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
||||
db.session.add(profile)
|
||||
profile.display_name = str(data.get('display_name') or code).strip()
|
||||
profile.file_format = str(data.get('file_format') or 'xlsx').lower()
|
||||
if profile.file_format not in {'xls', 'xlsx', 'csv'}:
|
||||
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
|
||||
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
|
||||
raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
if profile_id and requested_file_format != profile.file_format:
|
||||
raise ValidationError(
|
||||
'Draft parsing profile file format is immutable',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
profile.file_format = requested_file_format
|
||||
definition = _validate_definition(data.get('definition'))
|
||||
if profile.file_format == 'csv' and definition.get('sheet_name'):
|
||||
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
sample_analysis = _require_sample_evidence(
|
||||
data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format,
|
||||
)
|
||||
if profile.sample_analysis_id and profile.sample_analysis_id != sample_analysis.id:
|
||||
if not bool(data.get('confirm_sample_replacement')):
|
||||
raise ValidationError(
|
||||
'Replacing inventory sample evidence requires confirmation',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
|
||||
)
|
||||
history = list(profile.sample_evidence_history_json or [])
|
||||
history.append({
|
||||
'previous_analysis_id': profile.sample_analysis_id,
|
||||
'replacement_analysis_id': sample_analysis.id,
|
||||
'replaced_at': datetime.utcnow().isoformat(),
|
||||
'replaced_by': actor_id,
|
||||
})
|
||||
profile.sample_evidence_history_json = history
|
||||
profile.definition_json = definition
|
||||
profile.sample_analysis = sample_analysis
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
@@ -150,6 +236,9 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID')
|
||||
_require_sample_evidence(
|
||||
profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
published_field_ids = {
|
||||
|
||||
@@ -14,7 +14,7 @@ import re
|
||||
import shutil
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -31,6 +31,7 @@ from app.services.shipping_notice.inventory_snapshot import find_inventory_heade
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import (
|
||||
compatibility_fingerprint,
|
||||
exact_fingerprint,
|
||||
normalise_header,
|
||||
structure_definition,
|
||||
)
|
||||
|
||||
@@ -92,6 +93,27 @@ def _value_type(values: list[Any]) -> str:
|
||||
return 'text'
|
||||
|
||||
|
||||
def _evidence_value(value: Any) -> Any:
|
||||
"""将样本单元格转换为可审计但不暴露业务标识的最小化证据值。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
if isinstance(value, (int, float, bool)):
|
||||
return value
|
||||
if isinstance(value, (date, datetime)):
|
||||
return value.isoformat()
|
||||
text = str(value).strip()
|
||||
if len(text) <= 2:
|
||||
return '*' * len(text)
|
||||
if len(text) <= 6:
|
||||
return f'{text[:1]}***{text[-1:]}'
|
||||
return f'{text[:2]}***{text[-2:]}'
|
||||
|
||||
|
||||
def _sample_evidence_rows(sample_rows: list[list[Any]]) -> list[list[Any]]:
|
||||
"""保留最多五行已脱敏样例,供映射审计和页面预览而非库存运行。"""
|
||||
return [[_evidence_value(value) for value in row] for row in sample_rows[:MAX_SAMPLE_ROWS]]
|
||||
|
||||
|
||||
def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[dict[str, Any]]:
|
||||
"""生成来源栏位的业务预览,包括样例、空值率和建议字段。"""
|
||||
suggestions = suggest_field_mapping(headers, as_catalog=True)
|
||||
@@ -108,7 +130,7 @@ def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[di
|
||||
columns.append({
|
||||
'index': index,
|
||||
'header': header,
|
||||
'sample_values': [str(value)[:120] for value in non_empty[:MAX_SAMPLE_ROWS]],
|
||||
'sample_values': [str(_evidence_value(value))[:120] for value in non_empty[:MAX_SAMPLE_ROWS]],
|
||||
'sample_empty_rate': round((rows_total - len(non_empty)) / rows_total, 4) if rows_total else 1,
|
||||
'inferred_type': _value_type(non_empty),
|
||||
'duplicate': bool(header and duplicates[header] > 1),
|
||||
@@ -175,6 +197,7 @@ def _build_workbook_structure(
|
||||
'header_row_index': header_index + 1,
|
||||
'headers': headers,
|
||||
'columns': _column_summary(headers, samples),
|
||||
'_sample_rows': _sample_evidence_rows(samples),
|
||||
'sample_row_count': len(samples),
|
||||
'row_count_hint': row_count,
|
||||
'score': score,
|
||||
@@ -184,14 +207,18 @@ def _build_workbook_structure(
|
||||
candidates.append(candidate)
|
||||
if not candidates:
|
||||
raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
|
||||
selected = max(candidates, key=lambda item: (item['score'], item['sample_row_count']))
|
||||
# Prefer a populated detail sheet over a same-score cover/summary sheet.
|
||||
selected = max(candidates, key=lambda item: (
|
||||
item['score'], item['sample_row_count'], sum(1 for header in item['headers'] if header),
|
||||
))
|
||||
structure = {
|
||||
'sheets': sheets,
|
||||
'candidates': candidates,
|
||||
'candidates': [{key: value for key, value in candidate.items() if key != '_sample_rows'} for candidate in candidates],
|
||||
'selected_sheet_name': selected['sheet_name'],
|
||||
'selected_header_row_index': selected['header_row_index'],
|
||||
'selected_headers': selected['headers'],
|
||||
'selected_columns': selected['columns'],
|
||||
'selected_sample_rows': selected['_sample_rows'],
|
||||
}
|
||||
mapping = suggest_field_mapping(selected['headers'], as_catalog=True)
|
||||
summary = {
|
||||
@@ -251,7 +278,7 @@ def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str
|
||||
return {
|
||||
'sheets': [], 'candidates': [candidate], 'selected_sheet_name': None,
|
||||
'selected_header_row_index': header_index + 1, 'selected_headers': headers,
|
||||
'selected_columns': candidate['columns'],
|
||||
'selected_columns': candidate['columns'], 'selected_sample_rows': _sample_evidence_rows(samples),
|
||||
}, mapping, {
|
||||
'candidate_count': 1, 'sample_row_count': len(samples),
|
||||
'valid_inventory_field_suggestions': len(mapping),
|
||||
@@ -282,6 +309,7 @@ def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, An
|
||||
'structure': item.structure_json or {},
|
||||
'suggested_mapping': item.suggested_mapping_json or {},
|
||||
'validation_summary': item.validation_summary_json or {},
|
||||
'sample_rows': item.sample_rows_json or [],
|
||||
'warnings': item.warning_json or [],
|
||||
'match_result': item.match_result_json or {},
|
||||
'created_at': item.created_at.isoformat() if item.created_at else None,
|
||||
@@ -289,7 +317,7 @@ def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, An
|
||||
|
||||
|
||||
def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""上传并分析管理员选择的库存样本文件,创建后端权威分析记录。"""
|
||||
"""上传并分析管理员库存样本,只持久化脱敏结构证据且立即清理完整原件。"""
|
||||
if upload is None or not str(upload.filename or '').strip():
|
||||
raise ValidationError('Inventory sample file is required', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_REQUIRED')
|
||||
suffix = resolve_inventory_upload_suffix(str(upload.filename))
|
||||
@@ -316,10 +344,10 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
|
||||
header_row_index=structure.get('selected_header_row_index') or 1, headers=selected_headers,
|
||||
)
|
||||
item = ShippingInventoryStructureAnalysis(
|
||||
source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=str(path),
|
||||
source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=None,
|
||||
file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready',
|
||||
structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary,
|
||||
warning_json=warnings, created_by=actor_id,
|
||||
sample_rows_json=list(structure.get('selected_sample_rows') or []), warning_json=warnings, created_by=actor_id,
|
||||
exact_structure_fingerprint=exact_fingerprint(selected_definition),
|
||||
compatibility_fingerprint=compatibility_fingerprint(
|
||||
definition=selected_definition, field_mapping=suggested, match_keys=[],
|
||||
@@ -335,8 +363,12 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
|
||||
'exact_structure_fingerprint': item.exact_structure_fingerprint,
|
||||
'compatibility_fingerprint': item.compatibility_fingerprint,
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_analysis(item)
|
||||
try:
|
||||
db.session.commit()
|
||||
return serialize_analysis(item)
|
||||
finally:
|
||||
# The sample workbook is only a parsing input. Long-term audit relies on minimised structure evidence.
|
||||
shutil.rmtree(analysis_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def get_analysis(analysis_id: int) -> dict[str, Any]:
|
||||
@@ -347,11 +379,55 @@ def get_analysis(analysis_id: int) -> dict[str, Any]:
|
||||
return serialize_analysis(item)
|
||||
|
||||
|
||||
def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""比较草稿当前样本和候选样本,明确列出需要管理员确认的结构变化。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
|
||||
if analysis is None or analysis.analysis_status != 'ready':
|
||||
raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED')
|
||||
previous = profile.sample_analysis
|
||||
old_headers = list((previous.structure_json or {}).get('selected_headers') or []) if previous else []
|
||||
new_headers = list((analysis.structure_json or {}).get('selected_headers') or [])
|
||||
old_normalised = {normalise_header(value): str(value) for value in old_headers if normalise_header(value)}
|
||||
new_normalised = {normalise_header(value): str(value) for value in new_headers if normalise_header(value)}
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
proposed = data if isinstance(data, dict) else {}
|
||||
mapping = proposed.get('field_mapping') if isinstance(proposed.get('field_mapping'), dict) else definition.get('field_mapping')
|
||||
mapping = mapping if isinstance(mapping, dict) else {}
|
||||
missing_mapped_headers = [
|
||||
str(header) for header in mapping.values()
|
||||
if normalise_header(header) not in new_normalised
|
||||
]
|
||||
return {
|
||||
'profile_id': profile.id,
|
||||
'previous_analysis_id': profile.sample_analysis_id,
|
||||
'replacement_analysis_id': analysis.id,
|
||||
'difference': {
|
||||
'added_columns': [new_normalised[key] for key in new_normalised if key not in old_normalised],
|
||||
'missing_columns': [old_normalised[key] for key in old_normalised if key not in new_normalised],
|
||||
'column_order_changed': old_normalised.keys() == new_normalised.keys() and old_headers != new_headers,
|
||||
'missing_mapped_headers': missing_mapped_headers,
|
||||
'file_format_changed': profile.file_format != analysis.file_format,
|
||||
},
|
||||
'can_confirm': not missing_mapped_headers and profile.file_format == analysis.file_format,
|
||||
}
|
||||
|
||||
|
||||
def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""用已分析的真实栏位创建库存文件解析方案草稿,禁止前端编造来源栏位。"""
|
||||
"""用已分析样本证据创建或更新草稿,禁止前端编造来源栏位或脱离样本保存。"""
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
if analysis is None:
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
existing_profile = db.session.get(ShippingInventoryParsingProfile, data.get('profile_id')) if data.get('profile_id') else None
|
||||
if existing_profile is not None and existing_profile.file_format != analysis.file_format:
|
||||
raise ValidationError(
|
||||
'Draft parsing profile file format is immutable',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
sheet_name = str(data.get('sheet_name') or structure.get('selected_sheet_name') or '').strip() or None
|
||||
header_row_index = data.get('header_row_index') or structure.get('selected_header_row_index')
|
||||
@@ -378,6 +454,8 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
|
||||
'profile_code': data.get('profile_code'),
|
||||
'display_name': data.get('display_name'),
|
||||
'file_format': analysis.file_format,
|
||||
'sample_analysis_id': analysis.id,
|
||||
'confirm_sample_replacement': bool(data.get('confirm_sample_replacement')),
|
||||
'definition': {
|
||||
'sheet_name': sheet_name,
|
||||
'header_row_index': header_row_index,
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/rpa_worker_heartbeat_alert.py
|
||||
|
||||
用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
|
||||
依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
|
||||
逻辑:由 schedule worker 每轮循环调用;DB 为告警状态权威源,Redis 仅作缓存同步。
|
||||
逻辑:由 schedule worker 每轮循环调用;默认 ALERT_ENABLED=false 不发送;DB 为告警状态权威源,Redis 仅作缓存同步。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -46,7 +46,7 @@ def _config_bool(key: str, default: bool) -> bool:
|
||||
def _alert_enabled() -> bool:
|
||||
if not _heartbeat_check_required():
|
||||
return False
|
||||
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED", True)
|
||||
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED", False)
|
||||
|
||||
|
||||
def _alert_cooldown_seconds() -> int:
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""记录库存映射草稿的样本替换审计。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'a4c7e9f1b2d3'
|
||||
down_revision = 'fd2e3f4a5b6c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""保留样本证据的替换链,避免草稿更新后丢失配置依据。"""
|
||||
op.add_column(
|
||||
'shipping_inventory_parsing_profiles',
|
||||
sa.Column('sample_evidence_history_json', sa.JSON(), server_default=sa.text("'[]'"), nullable=False),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除样本替换历史字段。"""
|
||||
op.drop_column('shipping_inventory_parsing_profiles', 'sample_evidence_history_json')
|
||||
@@ -0,0 +1,35 @@
|
||||
"""将库存映射样本改为最小化结构证据。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'fc1d2e3f4a5b'
|
||||
down_revision = 'fb1c2d3e4f5a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""保存脱敏样例和 Profile 样本引用,不再要求分析记录持有完整 Excel 路径。"""
|
||||
with op.batch_alter_table('shipping_inventory_structure_analyses') as batch:
|
||||
batch.alter_column('storage_path', existing_type=sa.String(length=500), nullable=True)
|
||||
batch.add_column(sa.Column('sample_rows_json', sa.JSON(), server_default=sa.text("'[]'"), nullable=False))
|
||||
with op.batch_alter_table('shipping_inventory_parsing_profiles') as batch:
|
||||
batch.add_column(sa.Column('sample_analysis_id', sa.Integer(), nullable=True))
|
||||
batch.create_index('ix_shipping_inventory_parsing_profiles_sample_analysis_id', ['sample_analysis_id'])
|
||||
batch.create_foreign_key(
|
||||
'fk_inventory_parsing_profiles_sample_analysis',
|
||||
'shipping_inventory_structure_analyses', ['sample_analysis_id'], ['id'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除样本证据引用;旧版重新要求结构分析记录保存来源路径。"""
|
||||
with op.batch_alter_table('shipping_inventory_parsing_profiles') as batch:
|
||||
batch.drop_constraint('fk_inventory_parsing_profiles_sample_analysis', type_='foreignkey')
|
||||
batch.drop_index('ix_shipping_inventory_parsing_profiles_sample_analysis_id')
|
||||
batch.drop_column('sample_analysis_id')
|
||||
with op.batch_alter_table('shipping_inventory_structure_analyses') as batch:
|
||||
batch.drop_column('sample_rows_json')
|
||||
batch.alter_column('storage_path', existing_type=sa.String(length=500), nullable=False)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""锁定库存站点测试使用的 RPA Profile 配置版本。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'fd2e3f4a5b6c'
|
||||
down_revision = 'fc1d2e3f4a5b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为既有测试运行补充连接版本快照,使凭据或登录配置变更能够使测试失效。"""
|
||||
with op.batch_alter_table('shipping_inventory_configuration_test_runs') as batch:
|
||||
batch.add_column(sa.Column(
|
||||
'rpa_profile_config_version', sa.Integer(), nullable=False, server_default=sa.text('1'),
|
||||
))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除 RPA Profile 配置版本快照。"""
|
||||
with op.batch_alter_table('shipping_inventory_configuration_test_runs') as batch:
|
||||
batch.drop_column('rpa_profile_config_version')
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user