- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。 - 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。 - 更新 ORM 模型,增加出站报表相关的持久化模型。 - 统一命名规范,确保在手、入站与出站的概念一致性。
365 lines
20 KiB
Python
365 lines
20 KiB
Python
"""
|
||
services/freight_rpa/parsing_profile.py
|
||
|
||
用途:管理货代「报表规则」(FreightRpaParsingProfile)的草稿/发布与运行期定义读取。
|
||
purpose=onhand 走库存字段目录 + match_keys;purpose=inbound/outbound 走调拨
|
||
MOVEMENT_FIELDS 契约(与在途异动对齐)。
|
||
依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig、FreightRpaInboundReportConfig、
|
||
FreightRpaOutboundReportConfig、ShippingOrderField、
|
||
in_transit_transfer.movement_contract.MOVEMENT_FIELDS、
|
||
shipping_notice.order_schema(仅 onhand 发布时校验订单字段)。
|
||
逻辑:管理员保存草稿并发布不可变版本;来源站点 / 入站·出站报表配置只绑定 published
|
||
Profile;退役前检查 onhand/inbound/outbound 配置引用。管理端入口
|
||
/api/admin/freight-rpa/.../parsing-profiles。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
from datetime import datetime
|
||
from typing import Any
|
||
|
||
from sqlalchemy import func
|
||
|
||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||
from app.extensions import db
|
||
from app.models import (
|
||
FreightRpaOnhandField,
|
||
FreightRpaOnhandReportConfig,
|
||
FreightRpaParsingProfile,
|
||
FreightRpaOnhandStructureAnalysis,
|
||
ShippingOrderField,
|
||
FreightRpaInboundReportConfig,
|
||
FreightRpaOutboundReportConfig,
|
||
)
|
||
|
||
|
||
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
|
||
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
|
||
field_ids: list[int] = []
|
||
for raw_id in field_mapping:
|
||
try:
|
||
field_id = int(raw_id)
|
||
except (TypeError, ValueError) as exc:
|
||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') from exc
|
||
if field_id <= 0:
|
||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
field_ids.append(field_id)
|
||
rows = FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(set(field_ids))).all() if field_ids else []
|
||
fields = {str(row.id): row for row in rows if row.status == 'active'}
|
||
if len(fields) != len(set(str(item) for item in field_ids)):
|
||
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
return fields
|
||
|
||
|
||
def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set[str]:
|
||
"""校验解析方案具备匹配与库存数量能力,不限定字段名称。"""
|
||
match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'}
|
||
quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'}
|
||
if not match_ids or len(quantity_ids) != 1:
|
||
raise ValidationError(
|
||
'Parsing profile requires at least one match field and exactly one inventory quantity field',
|
||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||
)
|
||
return match_ids | quantity_ids
|
||
|
||
|
||
# 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
|
||
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
|
||
"""校验 inbound/outbound 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
|
||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||
|
||
movement_codes = {field.code for field in MOVEMENT_FIELDS}
|
||
mapping = definition.get('field_mapping') or {}
|
||
mapped_codes = {str(code) for code in mapping.keys() if str(code).strip()}
|
||
unknown = mapped_codes - movement_codes
|
||
if unknown:
|
||
raise ValidationError(
|
||
f'Movement parsing profile references unknown field: {sorted(unknown)}',
|
||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||
)
|
||
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
|
||
if missing:
|
||
raise ValidationError(
|
||
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
|
||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||
)
|
||
return mapped_codes
|
||
|
||
|
||
def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]:
|
||
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。
|
||
|
||
Args:
|
||
raw: 解析定义对象。
|
||
purpose: 'onhand'(库存字段目录 + match_keys)或
|
||
'inbound'/'outbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
|
||
"""
|
||
if not isinstance(raw, dict):
|
||
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
field_mapping = raw.get('field_mapping')
|
||
if not isinstance(field_mapping, dict) or not field_mapping:
|
||
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
if any(not str(value or '').strip() for value in field_mapping.values()):
|
||
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
header_row_index = raw.get('header_row_index')
|
||
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
|
||
raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
|
||
if purpose in {'inbound', 'outbound'}:
|
||
_required_movement_field_ids(raw)
|
||
return {
|
||
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
|
||
'header_row_index': header_row_index,
|
||
'field_mapping': {str(key).strip(): str(value).strip() for key, value in field_mapping.items()},
|
||
'match_keys': [],
|
||
}
|
||
|
||
catalog_fields = _catalog_fields(field_mapping)
|
||
_required_catalog_field_ids(catalog_fields)
|
||
match_keys = raw.get('match_keys')
|
||
if not isinstance(match_keys, list) or not match_keys:
|
||
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
normalized_keys: list[dict[str, str]] = []
|
||
seen_order_fields: set[str] = set()
|
||
seen_inventory_fields: set[str] = set()
|
||
for item in match_keys:
|
||
field = db.session.get(ShippingOrderField, str(item.get('order_field_id') or '')) if isinstance(item, dict) else None
|
||
inventory_field = str(item.get('inventory_field_id') or item.get('inventory_field') or '') if isinstance(item, dict) else ''
|
||
inventory = catalog_fields.get(inventory_field)
|
||
if (
|
||
field is None or field.status != 'active' or field.scope != 'line'
|
||
or inventory is None or inventory.usage_type != 'match_identity'
|
||
):
|
||
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
if field.id in seen_order_fields or inventory_field in seen_inventory_fields:
|
||
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
seen_order_fields.add(field.id)
|
||
seen_inventory_fields.add(inventory_field)
|
||
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
|
||
return {
|
||
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
|
||
'header_row_index': header_row_index,
|
||
'field_mapping': {str(int(key)): str(value).strip() for key, value in field_mapping.items()},
|
||
'match_keys': normalized_keys,
|
||
}
|
||
|
||
|
||
def _require_sample_evidence(
|
||
sample_analysis_id: Any,
|
||
definition: dict[str, Any],
|
||
*,
|
||
file_format: str,
|
||
) -> FreightRpaOnhandStructureAnalysis:
|
||
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
|
||
try:
|
||
analysis_id = int(sample_analysis_id)
|
||
except (TypeError, ValueError) as exc:
|
||
raise ValidationError(
|
||
'Parsing profile requires sample analysis evidence',
|
||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
|
||
) from exc
|
||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, 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.ONHAND_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.ONHAND_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.ONHAND_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.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||
)
|
||
return analysis
|
||
|
||
|
||
def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]:
|
||
"""序列化解析 Profile 管理 DTO。"""
|
||
sample_analysis = profile.sample_analysis
|
||
return {
|
||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||
'purpose': profile.purpose, '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,
|
||
}
|
||
|
||
|
||
def list_profiles() -> list[dict[str, Any]]:
|
||
"""列出全部解析 Profile 版本。"""
|
||
return [payload(item) for item in FreightRpaParsingProfile.query.order_by(
|
||
FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.version.desc(),
|
||
).all()]
|
||
|
||
|
||
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||
"""创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
|
||
profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile_id else None
|
||
if profile_id and profile is None:
|
||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||
if profile is not None and profile.status != 'draft':
|
||
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
|
||
code = str(data.get('profile_code') or '').strip().upper()
|
||
if not code:
|
||
raise ValidationError('profile_code is required', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
if profile is not None and code != profile.profile_code:
|
||
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
|
||
if profile is None:
|
||
next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
|
||
profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
||
db.session.add(profile)
|
||
purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower()
|
||
if purpose not in {'onhand', 'inbound', 'outbound'}:
|
||
raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||
if profile_id and purpose != profile.purpose:
|
||
raise ValidationError(
|
||
'Draft parsing profile purpose is immutable',
|
||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||
)
|
||
profile.purpose = purpose
|
||
profile.display_name = str(data.get('display_name') or code).strip()
|
||
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.ONHAND_PARSING_PROFILE_INVALID')
|
||
if profile_id and requested_file_format != profile.file_format:
|
||
raise ValidationError(
|
||
'Draft parsing profile file format is immutable',
|
||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||
)
|
||
profile.file_format = requested_file_format
|
||
definition = _validate_definition(data.get('definition'), purpose=purpose)
|
||
if profile.file_format == 'csv' and definition.get('sheet_name'):
|
||
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.ONHAND_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.ONHAND_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)
|
||
|
||
|
||
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
|
||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||
if profile is None:
|
||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||
if profile.status != 'draft':
|
||
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.ONHAND_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
|
||
|
||
# inbound/outbound 无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand 维持原约束。
|
||
referenced_field_ids = {
|
||
str(item.get('order_field_id') or '')
|
||
for item in (profile.definition_json or {}).get('match_keys', [])
|
||
if isinstance(item, dict)
|
||
}
|
||
if profile.purpose == 'onhand':
|
||
published_field_ids = {
|
||
str(item.get('field_id') or '')
|
||
for item in order_schema_service.get_published_contract().get('fields', [])
|
||
}
|
||
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
|
||
raise ValidationError(
|
||
'Parsing profile match keys must reference the current published order schema',
|
||
code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID',
|
||
)
|
||
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
||
profile.status = 'published'
|
||
profile.published_by = actor_id
|
||
profile.published_at = datetime.utcnow()
|
||
db.session.commit()
|
||
return payload(profile)
|
||
|
||
|
||
def retire(profile_id: int) -> dict[str, Any]:
|
||
"""退役无库存源/入站/出站报表配置引用的 published Profile,避免使现有绑定静默失效。"""
|
||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||
if profile is None:
|
||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||
if profile.status != 'published':
|
||
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID')
|
||
# s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。
|
||
bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||
# 入站/出站报表配置同样绑定解析 Profile:退役前必须一并核查,
|
||
# 否则入站/出站文件解析链会静默失去规则。
|
||
bound_inbound_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||
bound_outbound_configs = FreightRpaOutboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||
if bound_sources or bound_inbound_configs or bound_outbound_configs:
|
||
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED')
|
||
profile.status = 'retired'
|
||
db.session.commit()
|
||
return payload(profile)
|
||
|
||
|
||
def delete_draft(profile_id: int) -> None:
|
||
"""删除从未发布的解析 Profile 草稿。"""
|
||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||
if profile is None:
|
||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||
if profile.status != 'draft':
|
||
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.ONHAND_PARSING_PROFILE_DELETE_BLOCKED')
|
||
db.session.delete(profile)
|
||
db.session.commit()
|
||
|
||
|
||
def require_source_profile(source: Any) -> FreightRpaParsingProfile:
|
||
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
|
||
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
|
||
config = getattr(source, 'onhand_report_config', None)
|
||
profile = config.parsing_profile if config is not None else None
|
||
if profile is None or profile.status != 'published':
|
||
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||
return profile
|