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

@@ -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: