feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。 - 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。 - 更新 ORM 模型,增加出站报表相关的持久化模型。 - 统一命名规范,确保在手、入站与出站的概念一致性。
This commit is contained in:
1 parent
39fe3c05f2
commit
911afa0f73
152 files changed
+9861
-2984
No files matched your search
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
services/admin/freight_rpa_form_utils.py
|
||||
|
||||
用途:货代 RPA 管理端表单校验共用件(JSON 对象、报表路径、查询条件、时间序列化)。
|
||||
依赖:app.core.errors.ValidationError。
|
||||
逻辑:freight_rpa_source_admin_service(站点/连接)与 freight_rpa_report_config_service
|
||||
(入站/出站报表配置)共用;错误码沿用历史 SHIPPING.ONHAND_SOURCE_CONFIG_INVALID,
|
||||
调用方可按域 remap。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
def json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
|
||||
"""读取并复制对象型 JSON 配置。
|
||||
|
||||
Args:
|
||||
data: 管理 API 的请求载荷。
|
||||
field: 只允许 JSON object 的字段名。
|
||||
|
||||
Returns:
|
||||
空值规范化为空对象后的可写入配置。
|
||||
|
||||
Raises:
|
||||
ValidationError: 字段不是 JSON object。
|
||||
"""
|
||||
value = data.get(field, {})
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
return dict(value)
|
||||
|
||||
|
||||
def validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]:
|
||||
"""校验 DBS 四级报表路径,防止技术选择器混入业务配置。"""
|
||||
allowed = {'program_group', 'program_label', 'report_group', 'report_name'}
|
||||
if set(report_path) - allowed:
|
||||
raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
normalized = {key: str(value or '').strip() for key, value in report_path.items()}
|
||||
if connector_type == 'dbs':
|
||||
missing = [key for key in allowed if not normalized.get(key)]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'DBS inventory source requires a complete report path',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)},
|
||||
)
|
||||
elif normalized:
|
||||
raise ValidationError(
|
||||
'Only DBS inventory sources can define report_path_json',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
|
||||
)
|
||||
return {key: normalized[key] for key in allowed if normalized.get(key)}
|
||||
|
||||
|
||||
def validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。"""
|
||||
raw = data.get('query_parameters_json', [])
|
||||
if not isinstance(raw, list):
|
||||
raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
result: list[dict[str, Any]] = []
|
||||
seen_names: set[str] = set()
|
||||
allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'}
|
||||
for index, item in enumerate(raw):
|
||||
if not isinstance(item, dict) or set(item) - allowed:
|
||||
raise ValidationError(
|
||||
'query parameter contains unsupported fields',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index},
|
||||
)
|
||||
name = str(item.get('name') or '').strip()
|
||||
mode = str(item.get('mode') or 'single').strip().lower()
|
||||
values = item.get('values', [])
|
||||
required = item.get('required', False)
|
||||
select_all = item.get('select_all', False)
|
||||
if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}:
|
||||
raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
if not isinstance(values, list) or any(not isinstance(value, str) for value in values):
|
||||
raise ValidationError('query parameter values must be a string list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
if not isinstance(required, bool) or not isinstance(select_all, bool):
|
||||
raise ValidationError('query parameter flags must be boolean', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
normalized_values = [value.strip() for value in values if value.strip()]
|
||||
if required and not normalized_values and not select_all:
|
||||
raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
if select_all and mode != 'multi_select':
|
||||
raise ValidationError('select_all only applies to multi_select', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
parameter: dict[str, Any] = {
|
||||
'name': name, 'mode': mode, 'values': normalized_values,
|
||||
'required': required, 'select_all': select_all,
|
||||
}
|
||||
if mode == 'multi_text':
|
||||
joiner = str(item.get('joiner') or ',').strip()
|
||||
if not joiner:
|
||||
raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
parameter['joiner'] = joiner
|
||||
seen_names.add(name.lower())
|
||||
result.append(parameter)
|
||||
return result
|
||||
|
||||
|
||||
def iso(value: datetime | None) -> str | None:
|
||||
"""datetime → ISO 字符串;None 保持 None。"""
|
||||
return value.isoformat() if value else None
|
||||
@@ -0,0 +1,224 @@
|
||||
"""
|
||||
services/admin/freight_rpa_report_config_service.py
|
||||
|
||||
用途:货代 RPA 入站 / 出站报表配置管理(GET/PUT),与在手配置解耦。
|
||||
依赖:db、FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig /
|
||||
FreightRpaParsingProfile、freight_rpa_form_utils、shipping_notice.audit_service。
|
||||
逻辑:admin_freight_rpa 蓝图委托本服务;不进入来源站点启用硬门槛;
|
||||
解析绑定须 published 且 purpose 匹配 inbound/outbound。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaSource,
|
||||
)
|
||||
from app.services.admin.freight_rpa_form_utils import iso, json_object, validate_query_parameters, validate_report_path
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _inbound_report_config_payload(config: FreightRpaInboundReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立入站配置,禁止把库存路径或凭据透传至管理端。"""
|
||||
profile = config.parsing_profile
|
||||
return {
|
||||
'id': config.id, 'source_id': config.source_id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
'parsing_profile': ({
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'status': profile.status,
|
||||
} if profile else None),
|
||||
'config_version': config.config_version,
|
||||
'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _outbound_report_config_payload(config: FreightRpaOutboundReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立出站配置,禁止把库存/入站路径或凭据透传至管理端。"""
|
||||
profile = config.parsing_profile
|
||||
return {
|
||||
'id': config.id, 'source_id': config.source_id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
'parsing_profile': ({
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'status': profile.status,
|
||||
} if profile else None),
|
||||
'config_version': config.config_version,
|
||||
'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _validate_inbound_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验入站配置绑定的解析规则:必须已发布且 purpose='inbound';空值表示解绑。"""
|
||||
if profile_id is None or str(profile_id).strip() == '':
|
||||
return None
|
||||
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
|
||||
raise ValidationError(
|
||||
'Inbound parsing profile must be published with purpose inbound',
|
||||
code='SHIPPING.INBOUND_PROFILE_INVALID',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _validate_outbound_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验出站配置绑定的解析规则:必须已发布且 purpose='outbound';空值表示解绑。"""
|
||||
if profile_id is None or str(profile_id).strip() == '':
|
||||
return None
|
||||
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'outbound':
|
||||
raise ValidationError(
|
||||
'Outbound parsing profile must be published with purpose outbound',
|
||||
code='SHIPPING.OUTBOUND_PROFILE_INVALID',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _validate_inbound_report_config(
|
||||
source: FreightRpaSource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范入站配置:路径+查询条件;日期禁填。"""
|
||||
try:
|
||||
parameters = validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc
|
||||
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
|
||||
raise ValidationError('Inbound report date filtering is not supported', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
|
||||
raw_path = json_object(data, 'report_path_json')
|
||||
if source.connector_type == 'dbs':
|
||||
try:
|
||||
path = validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
raise ValidationError('Crane inbound report is fixed to Inbound Details', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
|
||||
if parameters:
|
||||
raise ValidationError(
|
||||
'Crane inbound report does not support query parameters',
|
||||
code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return {'report_name': 'Inbound Details'}, []
|
||||
raise ValidationError('Unsupported inbound connector type', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
|
||||
|
||||
|
||||
def _validate_outbound_report_config(
|
||||
source: FreightRpaSource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范出站配置:路径+查询条件;日期禁填;Crane 固定 Outbound Details。"""
|
||||
try:
|
||||
parameters = validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc
|
||||
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
|
||||
raise ValidationError('Outbound report date filtering is not supported', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
|
||||
raw_path = json_object(data, 'report_path_json')
|
||||
if source.connector_type == 'dbs':
|
||||
try:
|
||||
path = validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Outbound Details'):
|
||||
raise ValidationError('Crane outbound report is fixed to Outbound Details', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
|
||||
if parameters:
|
||||
raise ValidationError(
|
||||
'Crane outbound report does not support query parameters',
|
||||
code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return {'report_name': 'Outbound Details'}, []
|
||||
raise ValidationError('Unsupported outbound connector type', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
|
||||
|
||||
|
||||
def get_inbound_report_config(source_id: int) -> dict[str, Any] | None:
|
||||
"""读取站点的入站配置;不存在时返回空。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
return _inbound_report_config_payload(config) if config else None
|
||||
|
||||
|
||||
def save_inbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点内独立入站配置并追加配置前后快照审计。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
path, parameters = _validate_inbound_report_config(source, data)
|
||||
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
before = _inbound_report_config_payload(config) if config else None
|
||||
is_new = config is None
|
||||
if config is None:
|
||||
config = FreightRpaInboundReportConfig(source_id=source.id)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = _validate_inbound_profile_binding(data.get('parsing_profile_id'))
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _inbound_report_config_payload(config)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_inbound_report_config_saved', aggregate_type='shipping_inbound_report_config',
|
||||
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
|
||||
result='success', before=before, after=after,
|
||||
metadata={'source_id': source.id, 'connector_type': source.connector_type,
|
||||
'parsing_profile_id': config.parsing_profile_id},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def get_outbound_report_config(source_id: int) -> dict[str, Any] | None:
|
||||
"""读取站点的出站配置;不存在时返回空。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
return _outbound_report_config_payload(config) if config else None
|
||||
|
||||
|
||||
def save_outbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点内独立出站配置并追加配置前后快照审计。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
path, parameters = _validate_outbound_report_config(source, data)
|
||||
config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
before = _outbound_report_config_payload(config) if config else None
|
||||
is_new = config is None
|
||||
if config is None:
|
||||
config = FreightRpaOutboundReportConfig(source_id=source.id)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = _validate_outbound_profile_binding(data.get('parsing_profile_id'))
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _outbound_report_config_payload(config)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_outbound_report_config_saved', aggregate_type='shipping_outbound_report_config',
|
||||
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
|
||||
result='success', before=before, after=after,
|
||||
metadata={'source_id': source.id, 'connector_type': source.connector_type,
|
||||
'parsing_profile_id': config.parsing_profile_id},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
@@ -0,0 +1,702 @@
|
||||
"""
|
||||
services/admin/freight_rpa_source_admin_service.py
|
||||
|
||||
用途:货代 RPA 共用主数据管理——登录连接(FreightRpaProfile)与来源站点(FreightRpaSource),
|
||||
含站点启用门禁、在手配置行写入、解析绑定审计。
|
||||
依赖:db、FreightRpaProfile / FreightRpaSource / FreightRpaOnhandReportConfig、
|
||||
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
|
||||
onhand_source_repository.validate_source_profile、audit_service。
|
||||
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
|
||||
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaOnhandExternalMapping,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaOnhandReportFile,
|
||||
FreightRpaOnhandRoutingRule,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaProfile,
|
||||
FreightRpaSource,
|
||||
FreightRpaSourceParsingBindingAudit,
|
||||
ScheduleRun,
|
||||
ShippingExcelTemplate,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
)
|
||||
from app.services.admin.freight_rpa_form_utils import (
|
||||
iso as _iso,
|
||||
json_object as _json_object,
|
||||
validate_query_parameters as _validate_query_parameters,
|
||||
validate_report_path as _validate_report_path,
|
||||
)
|
||||
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
|
||||
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
||||
|
||||
|
||||
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
|
||||
"""读取并清洗字符串表单字段。"""
|
||||
value = str(data.get(field) or '').strip()
|
||||
if required and not value:
|
||||
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
|
||||
return value or None
|
||||
|
||||
|
||||
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
|
||||
"""读取布尔表单字段。"""
|
||||
value = data.get(field, default)
|
||||
if not isinstance(value, bool):
|
||||
raise ValidationError(f'{field} must be a boolean', details={'field': field})
|
||||
return value
|
||||
|
||||
|
||||
|
||||
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
|
||||
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
|
||||
value = data.get('login_config_json', {})
|
||||
if not isinstance(value, dict) or set(value) - {'auth_mode'}:
|
||||
raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID')
|
||||
auth_mode = str(value.get('auth_mode') or 'password').strip().lower()
|
||||
if auth_mode != 'password':
|
||||
raise ValidationError(
|
||||
'Only password authentication is currently supported',
|
||||
code='SHIPPING.RPA_PROFILE_CONFIG_INVALID',
|
||||
)
|
||||
return {'auth_mode': auth_mode}
|
||||
|
||||
|
||||
|
||||
|
||||
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'connector_type': profile.connector_type, 'login_url': profile.login_url,
|
||||
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
|
||||
'upload_config_json': profile.upload_config_json,
|
||||
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
|
||||
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
|
||||
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _mask(ciphertext: str | None) -> str | None:
|
||||
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
|
||||
return 'configured' if ciphertext else None
|
||||
|
||||
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出 Profile 元数据,不返回可恢复的凭据。"""
|
||||
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
|
||||
|
||||
|
||||
def delete_profile(profile_id: int) -> None:
|
||||
"""删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。"""
|
||||
profile = db.session.get(FreightRpaProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
if FreightRpaSource.query.filter_by(rpa_profile_id=profile.id).count():
|
||||
raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED')
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
|
||||
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
profile = profile or FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
|
||||
# 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version,
|
||||
# upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。
|
||||
prev_non_upload = (
|
||||
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
|
||||
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
|
||||
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
|
||||
) if profile_id else None
|
||||
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
|
||||
profile.display_name = str(_text(data, 'display_name', required=True))
|
||||
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
|
||||
profile.login_url = str(_text(data, 'login_url', required=True))
|
||||
profile.login_config_json = _validate_profile_login_config(data)
|
||||
profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True)
|
||||
if not profile.enabled and any(source.enabled for source in profile.sources):
|
||||
raise ConflictError(
|
||||
'Disable inventory sources before disabling their RPA Profile',
|
||||
code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED',
|
||||
)
|
||||
username = _text(data, 'username')
|
||||
password = _text(data, 'password')
|
||||
if username is not None:
|
||||
profile.username_ciphertext = encrypt_credential(username)
|
||||
if password is not None:
|
||||
profile.password_ciphertext = encrypt_credential(password)
|
||||
if username is not None or password is not None:
|
||||
profile.credential_updated_at = datetime.utcnow()
|
||||
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
|
||||
if 'upload_config_json' in data:
|
||||
profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json'))
|
||||
profile.updated_by = actor_id
|
||||
if profile_id:
|
||||
now_non_upload = (
|
||||
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
|
||||
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
|
||||
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
|
||||
)
|
||||
if now_non_upload != prev_non_upload:
|
||||
profile.config_version += 1
|
||||
if not profile_id:
|
||||
profile.created_by = actor_id
|
||||
db.session.add(profile)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc
|
||||
return _profile_payload(profile)
|
||||
|
||||
|
||||
def _onhand_report_config_payload(config: FreightRpaOnhandReportConfig) -> dict[str, Any]:
|
||||
"""序列化站点一对一在手报表配置行,不透传解析方案定义。"""
|
||||
return {
|
||||
'id': config.id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
}
|
||||
|
||||
|
||||
def _source_payload(source: FreightRpaSource) -> dict[str, Any]:
|
||||
"""序列化库存站点及其是否满足正式启用前置条件。
|
||||
|
||||
s18 起报表路径/查询条件/解析方案绑定不再随站点 DTO 平铺,
|
||||
改挂在 ``onhand_report_config`` 嵌套对象(配置行不存在时为 null)。
|
||||
"""
|
||||
return {
|
||||
'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name,
|
||||
'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id,
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'onhand_report_config': (
|
||||
_onhand_report_config_payload(source.onhand_report_config)
|
||||
if source.onhand_report_config is not None else None
|
||||
),
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled),
|
||||
'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at),
|
||||
'activation': get_source_activation_status(source),
|
||||
}
|
||||
|
||||
|
||||
def _validate_onhand_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验在手配置绑定的解析方案:必须已发布且 purpose='onhand';空值/0 表示解绑。
|
||||
|
||||
Args:
|
||||
profile_id: 请求载荷中的 parsing_profile_id;None/空串/0 视为解绑(与旧站点保存语义一致)。
|
||||
|
||||
Returns:
|
||||
int | None: 规整后的方案 id 或 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 方案 id 非法、不存在、未发布或用途不是 onhand
|
||||
(fail-closed,防误绑入站/出站方案,统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
|
||||
"""
|
||||
raw = str(profile_id).strip() if profile_id is not None else ''
|
||||
if raw in {'', '0'}:
|
||||
return None
|
||||
if not raw.isdigit():
|
||||
raise ValidationError(
|
||||
'Onhand parsing profile must be published with purpose onhand',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
profile = db.session.get(FreightRpaParsingProfile, int(raw))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'onhand':
|
||||
raise ValidationError(
|
||||
'Onhand parsing profile must be published with purpose onhand',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _apply_onhand_report_config(
|
||||
source: FreightRpaSource, data: dict[str, Any], *, actor_id: int | None,
|
||||
) -> FreightRpaOnhandReportConfig:
|
||||
"""把手报表三字段写入手配置行(无则插入),不触碰站点行已删除的三列。
|
||||
|
||||
核心逻辑:先全量校验路径对象/查询条件/解析绑定,失败时不留脏会话;
|
||||
校验通过后无配置行则插入(created_by=actor),有则更新并递增 config_version。
|
||||
报表路径按原样 JSON object 存取(Driver selector 等实现细节归 Worker/模板域,
|
||||
管理端 DBS 四段路径由前端 normaliseInventoryReportPath 规整后提交)。
|
||||
|
||||
Args:
|
||||
source: 已存在的库存站点(新配置行经 inventory_source 关系级联挂载)。
|
||||
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
|
||||
actor_id: 当前管理员主键,仅写审计字段。
|
||||
|
||||
Returns:
|
||||
FreightRpaOnhandReportConfig: 已写入(尚未提交)的配置行。
|
||||
"""
|
||||
# [STEP 1] 全量校验先行,任何失败都不会留下半写的配置行。
|
||||
report_path = _json_object(data, 'report_path_json')
|
||||
# DBS 四段路径按原样 JSON object 存取(前端 normaliseInventoryReportPath 规整);
|
||||
# 非 DBS(Crane)站点不得误填 DBS 报表路径(fail-closed,与列搬迁前契约一致)。
|
||||
if source.connector_type != 'dbs' and report_path:
|
||||
raise ValidationError(
|
||||
'Only DBS inventory sources can define report_path_json',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
|
||||
)
|
||||
parameters = _validate_query_parameters(data)
|
||||
parsing_profile_id = _validate_onhand_profile_binding(data.get('parsing_profile_id'))
|
||||
# [STEP 2] 校验通过后写配置行:无则插入,有则更新并递增 config_version。
|
||||
config = source.onhand_report_config
|
||||
if config is None:
|
||||
config = FreightRpaOnhandReportConfig(source=source)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.report_path_json = report_path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = parsing_profile_id
|
||||
config.updated_by = actor_id
|
||||
return config
|
||||
|
||||
|
||||
def save_onhand_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点一对一在手报表配置:没有配置行时插入,有则更新并递增该行 config_version。
|
||||
|
||||
核心逻辑:委托 _apply_onhand_report_config 校验并写行;启用中的站点借保存拆掉
|
||||
启用门禁(缺解析绑定/模板)时由 assert_onhand_source_can_enable fail-closed 拒绝。
|
||||
|
||||
Args:
|
||||
source_id: 库存站点主键,必须已存在。
|
||||
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
|
||||
actor_id: 当前管理员主键,仅写审计字段。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: 配置行 DTO(id / report_path_json / query_parameters_json / parsing_profile_id)。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 站点不存在。
|
||||
ValidationError: 解析方案不存在/未发布/purpose 不是 onhand,或启用中站点门禁被拆。
|
||||
"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
config = _apply_onhand_report_config(source, data, actor_id=actor_id)
|
||||
# 启用中的站点不得借配置保存解绑解析方案(excel_template 缺失同样拒绝)。
|
||||
assert_onhand_source_can_enable(source)
|
||||
db.session.commit()
|
||||
return _onhand_report_config_payload(config)
|
||||
|
||||
|
||||
def assert_onhand_source_can_enable(source: FreightRpaSource) -> None:
|
||||
"""启用中的库存站点必须已有在手配置行(含解析方案绑定)与发货模板。
|
||||
|
||||
【AI 触发时机】:保存站点(save_source 载荷含 enabled=true 或保留启用态)、
|
||||
保存在手配置(save_onhand_report_config 拆绑定前)时调用;
|
||||
PostgreSQL CHECK 不能跨表,解析方案存在性只能由服务层执行。
|
||||
|
||||
Args:
|
||||
source: 站点对象(可为未提交的暂态行,配置行经 onhand_report_config 关系读取)。
|
||||
|
||||
Returns:
|
||||
None: 门禁通过(站点未启用时恒通过)。
|
||||
|
||||
Raises:
|
||||
ValidationError: enabled 为真但缺配置行、配置行未绑解析方案或站点未绑模板,
|
||||
统一 code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'。
|
||||
"""
|
||||
if not source.enabled:
|
||||
return
|
||||
config = source.onhand_report_config
|
||||
if config is None or not config.parsing_profile_id or not source.excel_template_id:
|
||||
raise ValidationError(
|
||||
'Enabled inventory source requires onhand report config, parsing profile and excel template',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
|
||||
|
||||
def _binding_snapshot(source: FreightRpaSource) -> dict[str, Any]:
|
||||
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。
|
||||
|
||||
s18 起解析绑定挂在 onhand_report_config 配置行上,快照同样取自配置行。
|
||||
"""
|
||||
config = source.onhand_report_config
|
||||
return {
|
||||
'source_id': source.id,
|
||||
'source_code': source.source_code,
|
||||
'enabled': bool(source.enabled),
|
||||
'parsing_profile_id': config.parsing_profile_id if config is not None else None,
|
||||
'parsing_profile_checksum': (
|
||||
config.parsing_profile.checksum
|
||||
if config is not None and config.parsing_profile is not None else None
|
||||
),
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'config_version': source.config_version,
|
||||
}
|
||||
|
||||
|
||||
def _validate_source_parsing_binding(source: FreightRpaSource, profile: FreightRpaParsingProfile) -> None:
|
||||
"""校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。"""
|
||||
if profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
|
||||
if not mapping:
|
||||
raise ValidationError('Published parsing profile is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
template = source.excel_template
|
||||
if template is None:
|
||||
return
|
||||
if template.status != 'published':
|
||||
raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
|
||||
template_definition = template.definition_json if isinstance(template.definition_json, dict) else {}
|
||||
template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else []
|
||||
missing_fields = sorted({
|
||||
str(item.get('source_key') or '')
|
||||
for item in template_mappings
|
||||
if isinstance(item, dict)
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '') not in mapping
|
||||
})
|
||||
if missing_fields:
|
||||
raise ValidationError(
|
||||
'Parsing profile does not provide all inventory fields required by the excel template',
|
||||
code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields},
|
||||
)
|
||||
|
||||
|
||||
def bind_source_parsing_profile(
|
||||
source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。
|
||||
|
||||
Args:
|
||||
source_ids: 待绑定的库存站点主键,不能为空且不得重复。
|
||||
profile_id: 必须为已发布解析方案主键。
|
||||
actor_id: 当前管理员主键,仅写入审计。
|
||||
reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。
|
||||
operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。
|
||||
|
||||
Returns:
|
||||
list[dict[str, Any]]: 已更新站点的管理端 DTO。
|
||||
|
||||
Raises:
|
||||
ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。
|
||||
ConflictError: 试图变更已启用站点的正式解析方案。
|
||||
"""
|
||||
try:
|
||||
normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0})
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc
|
||||
if not normalized_ids or len(normalized_ids) != len(source_ids):
|
||||
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM')
|
||||
if operation not in {'direct', 'bulk'}:
|
||||
raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM')
|
||||
normalized_reason = str(reason or '').strip()
|
||||
if len(normalized_reason) > 500:
|
||||
raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM')
|
||||
# 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。
|
||||
if not normalized_reason:
|
||||
normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案'
|
||||
try:
|
||||
normalized_profile_id = int(profile_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc
|
||||
profile = db.session.get(FreightRpaParsingProfile, normalized_profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
sources = [db.session.get(FreightRpaSource, source_id) for source_id in normalized_ids]
|
||||
if any(source is None for source in sources):
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
typed_sources = [source for source in sources if source is not None]
|
||||
# [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。
|
||||
for source in typed_sources:
|
||||
_validate_source_parsing_binding(source, profile)
|
||||
for source in typed_sources:
|
||||
before = _binding_snapshot(source)
|
||||
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键。
|
||||
config = source.onhand_report_config
|
||||
previous_profile_id = config.parsing_profile_id if config is not None else None
|
||||
if config is None:
|
||||
config = FreightRpaOnhandReportConfig(source=source)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.parsing_profile_id = profile.id
|
||||
config.updated_by = actor_id
|
||||
source.updated_by = actor_id
|
||||
# 站点 config_version 仍随绑定递增:配置测试锁定版本与运行期失效判断依赖它。
|
||||
source.config_version += 1
|
||||
db.session.flush()
|
||||
db.session.add(FreightRpaSourceParsingBindingAudit(
|
||||
source_id=source.id, previous_parsing_profile_id=previous_profile_id,
|
||||
parsing_profile_id=config.parsing_profile_id, operation=operation, reason=normalized_reason, actor_id=actor_id,
|
||||
source_config_version_before=before['config_version'], source_config_version_after=source.config_version,
|
||||
before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source),
|
||||
))
|
||||
db.session.commit()
|
||||
return [_source_payload(source) for source in typed_sources]
|
||||
|
||||
|
||||
def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]:
|
||||
"""读取库存站点解析绑定审计,仅返回配置快照和操作者标识。"""
|
||||
if db.session.get(FreightRpaSource, source_id) is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
rows = FreightRpaSourceParsingBindingAudit.query.filter_by(
|
||||
source_id=source_id,
|
||||
).order_by(FreightRpaSourceParsingBindingAudit.id.desc()).all()
|
||||
return [{
|
||||
'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id,
|
||||
'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id,
|
||||
'source_config_version_before': row.source_config_version_before,
|
||||
'source_config_version_after': row.source_config_version_after,
|
||||
'before': row.before_snapshot_json, 'after': row.after_snapshot_json,
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
} for row in rows]
|
||||
|
||||
|
||||
def list_sources() -> list[dict[str, Any]]:
|
||||
"""列出库存源及其稳定业务配置。"""
|
||||
return [_source_payload(item) for item in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all()]
|
||||
|
||||
|
||||
def delete_source(source_id: int) -> None:
|
||||
"""删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
source_code = str(source.source_code or '').strip().upper()
|
||||
has_mapping = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id).count() > 0
|
||||
has_snapshot = FreightRpaOnhandReportFile.query.filter_by(source_code=source_code).count() > 0
|
||||
has_rule = any(
|
||||
source_code in {str(code).strip().upper() for code in candidates}
|
||||
for rule in FreightRpaOnhandRoutingRule.query.all()
|
||||
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
|
||||
if isinstance(candidates, list)
|
||||
)
|
||||
has_task = db.session.query(ShippingNoticeLine.id).filter(
|
||||
ShippingNoticeLine.inventory_source_code == source_code,
|
||||
).first() is not None or db.session.query(ShippingNoticeLineOnhandMatch.id).filter(
|
||||
ShippingNoticeLineOnhandMatch.source_code == source_code,
|
||||
).first() is not None
|
||||
has_export_run = any(
|
||||
source_code in {str(code).strip().upper() for code in source_codes}
|
||||
for run in ScheduleRun.query.all()
|
||||
for source_codes in [(run.api_request_json or {}).get('source_codes', [])]
|
||||
if isinstance(source_codes, list)
|
||||
)
|
||||
if has_mapping or has_snapshot or has_rule or has_task or has_export_run:
|
||||
raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED')
|
||||
db.session.delete(source)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _template_validation_missing(source: FreightRpaSource) -> list[str]:
|
||||
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
|
||||
template = source.excel_template
|
||||
# s18 起解析方案绑定取自 onhand_report_config 配置行。
|
||||
config = source.onhand_report_config
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if template is None or profile is None:
|
||||
return []
|
||||
definition = template.definition_json if isinstance(template.definition_json, dict) else {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()}
|
||||
invalid = any(
|
||||
isinstance(item, dict)
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '') not in inventory_fields
|
||||
for item in mappings
|
||||
)
|
||||
return ['template_validation'] if not mappings or invalid else []
|
||||
|
||||
|
||||
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: FreightRpaSource) -> list[dict[str, Any]]:
|
||||
"""构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。
|
||||
|
||||
测试导出不再参与启用门禁;启停由管理员显式开关完成。
|
||||
"""
|
||||
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
|
||||
# s18 起解析方案绑定取自 onhand_report_config 配置行;配置行缺失即解析门禁未就绪。
|
||||
config = source.onhand_report_config
|
||||
parsing_profile = config.parsing_profile if config is not None else None
|
||||
parsing_ready = parsing_profile is not None and parsing_profile.status == 'published'
|
||||
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
|
||||
template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False
|
||||
return [
|
||||
_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': parsing_profile.id if parsing_profile is not None else None, '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_invalid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_invalid,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]:
|
||||
"""返回库存站点启用硬门槛的结构化结果。
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
status = get_source_activation_status(source)
|
||||
if not status['ready']:
|
||||
raise ConflictError(
|
||||
'Inventory Source is not ready for activation',
|
||||
code='SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED',
|
||||
details=status,
|
||||
)
|
||||
source.enabled = True
|
||||
source.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""停用库存站点,保留其解析方案和历史运行审计。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
source.enabled = False
|
||||
source.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def save_source(
|
||||
data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None,
|
||||
allow_enable_transition: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。
|
||||
|
||||
s18 起站点头部仅编辑 source_code / display_name / connector_type / rpa_profile_id /
|
||||
excel_template_id / 仓库模式 / snapshot_ttl_seconds;报表路径、查询条件与解析方案
|
||||
绑定经载荷内嵌的 ``onhand_report_config`` 对象写入配置行(与独立保存同一校验路径)。
|
||||
"""
|
||||
source = db.session.get(FreightRpaSource, source_id) if source_id else None
|
||||
if source_id and source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
try:
|
||||
profile_id = int(data.get('rpa_profile_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('rpa_profile_id is required') from exc
|
||||
profile = db.session.get(FreightRpaProfile, profile_id)
|
||||
if profile is None:
|
||||
raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False)
|
||||
if not allow_enable_transition:
|
||||
# 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。
|
||||
enabled = bool(source.enabled) if source is not None else False
|
||||
else:
|
||||
enabled = requested_enabled
|
||||
if enabled and not profile.enabled:
|
||||
raise ValidationError(
|
||||
'Enabled Inventory Source requires an enabled RPA Profile',
|
||||
code='SHIPPING.RPA_PROFILE_DISABLED',
|
||||
)
|
||||
excel_template_id = data.get('excel_template_id')
|
||||
excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None
|
||||
if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'):
|
||||
raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
|
||||
is_new = source is None
|
||||
source = source or FreightRpaSource(
|
||||
source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed',
|
||||
)
|
||||
source.source_code = str(_text(data, 'source_code', required=True)).upper()
|
||||
source.display_name = str(_text(data, 'display_name', required=True))
|
||||
source.connector_type = str(_text(data, 'connector_type', required=True)).lower()
|
||||
source.rpa_profile = profile
|
||||
source.excel_template = excel_template
|
||||
source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower()
|
||||
source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id')
|
||||
source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400)
|
||||
source.enabled = enabled
|
||||
source.updated_by = actor_id
|
||||
if source_id:
|
||||
source.config_version += 1
|
||||
if is_new:
|
||||
source.created_by = actor_id
|
||||
db.session.add(source)
|
||||
# [STEP 1] 启用门禁先行:缺模板在写库前给出可解释错误,避免撞站点行 CHECK 的 IntegrityError
|
||||
# (模板缺失复用 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED,不新造码)。
|
||||
if enabled and excel_template is None:
|
||||
raise ValidationError(
|
||||
'published excel_template_id is required',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
try:
|
||||
# flush 让 excel_template_id / 新行主键先行落位,后续门禁读取规整后的外键。
|
||||
db.session.flush()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
|
||||
# [STEP 2] 载荷内嵌 onhand_report_config 时与独立保存走同一校验/写行路径(无则插入配置行)。
|
||||
config_data = data.get('onhand_report_config')
|
||||
if isinstance(config_data, dict):
|
||||
_apply_onhand_report_config(source, config_data, actor_id=actor_id)
|
||||
# [STEP 3] 启用门禁复核(缺配置行/解析绑定/模板统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
|
||||
if enabled:
|
||||
assert_onhand_source_can_enable(source)
|
||||
validate_source_profile(source, profile)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
|
||||
return _source_payload(source)
|
||||
|
||||
@@ -1,44 +1,38 @@
|
||||
"""
|
||||
services/admin/shipping_onhand_admin_service.py
|
||||
|
||||
用途:管理库存源、RPA Profile、在手报表配置、路由规则和外部系统映射主数据。
|
||||
依赖:db、库存配置模型(含 s18 起的 FreightRpaOnhandReportConfig 配置行)、凭据加密、
|
||||
Source/Profile 校验、统一 AppError。
|
||||
逻辑:管理 API 委托本服务完成校验和事务;运行期库存匹配不从本服务读取明文凭据。
|
||||
s18 起在手报表路径/查询条件/解析方案绑定归 FreightRpaOnhandReportConfig 一对一配置行
|
||||
(save_source 载荷内嵌 onhand_report_config 时经 _apply_onhand_report_config 写行),
|
||||
站点行只保留连接、模板绑定、仓库模式与启停;启用门禁由
|
||||
assert_onhand_source_can_enable 在服务层执行(PostgreSQL CHECK 不能跨表)。
|
||||
用途:在手域管理——库存快照只读、导出运行记录、路由规则、外部仓库映射。
|
||||
依赖:db、FreightRpaOnhandReportFile / FreightRpaOnhandRoutingRule /
|
||||
FreightRpaOnhandExternalMapping、order_schema、routing_operators、ALLOWED_ACTIONS。
|
||||
逻辑:admin_freight_rpa 的 snapshots / export-records / rules / external-mappings 委托本服务;
|
||||
登录连接与来源站点见 freight_rpa_source_admin_service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaOnhandExternalMapping, FreightRpaOnhandReportFile, FreightRpaOnhandRoutingRule, FreightRpaOnhandRoutingRuleCondition,
|
||||
FreightRpaOnhandRoutingRuleVersion, FreightRpaSource, FreightRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice,
|
||||
FreightRpaOnhandExternalMapping,
|
||||
FreightRpaOnhandReportFile,
|
||||
FreightRpaOnhandRoutingRule,
|
||||
FreightRpaOnhandRoutingRuleCondition,
|
||||
FreightRpaOnhandRoutingRuleVersion,
|
||||
FreightRpaSource,
|
||||
ScheduleRun,
|
||||
ScheduleTask,
|
||||
ShippingOrderField,
|
||||
FreightRpaParsingProfile,
|
||||
ShippingNoticeLine, ShippingNoticeLineOnhandMatch,
|
||||
ShippingExcelTemplate,
|
||||
FreightRpaSourceParsingBindingAudit,
|
||||
FreightRpaInboundReportConfig, FreightRpaOnhandReportConfig,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
|
||||
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
||||
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
|
||||
from app.services.admin.freight_rpa_form_utils import iso as _iso
|
||||
from app.services.shipping_notice.onhand_routing_engine import ALLOWED_ACTIONS
|
||||
from app.services.shipping_notice import onhand_parsing_profile
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
|
||||
|
||||
|
||||
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
|
||||
"""读取并清洗字符串表单字段。"""
|
||||
value = str(data.get(field) or '').strip()
|
||||
if required and not value:
|
||||
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
|
||||
@@ -46,653 +40,13 @@ def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str |
|
||||
|
||||
|
||||
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
|
||||
"""读取布尔表单字段。"""
|
||||
value = data.get(field, default)
|
||||
if not isinstance(value, bool):
|
||||
raise ValidationError(f'{field} must be a boolean', details={'field': field})
|
||||
return value
|
||||
|
||||
|
||||
def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
|
||||
"""读取并复制对象型 JSON 配置。
|
||||
|
||||
Args:
|
||||
data: 管理 API 的请求载荷。
|
||||
field: 只允许 JSON object 的字段名。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: 空值规范化为空对象后的可写入配置。
|
||||
|
||||
Raises:
|
||||
ValidationError: 字段不是 JSON object。
|
||||
"""
|
||||
value = data.get(field, {})
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
return dict(value)
|
||||
|
||||
|
||||
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
|
||||
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
|
||||
value = data.get('login_config_json', {})
|
||||
if not isinstance(value, dict) or set(value) - {'auth_mode'}:
|
||||
raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID')
|
||||
auth_mode = str(value.get('auth_mode') or 'password').strip().lower()
|
||||
if auth_mode != 'password':
|
||||
raise ValidationError(
|
||||
'Only password authentication is currently supported',
|
||||
code='SHIPPING.RPA_PROFILE_CONFIG_INVALID',
|
||||
)
|
||||
return {'auth_mode': auth_mode}
|
||||
|
||||
|
||||
def _validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]:
|
||||
"""校验 DBS 四级报表路径,防止技术选择器混入业务配置。"""
|
||||
allowed = {'program_group', 'program_label', 'report_group', 'report_name'}
|
||||
if set(report_path) - allowed:
|
||||
raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
normalized = {key: str(value or '').strip() for key, value in report_path.items()}
|
||||
if connector_type == 'dbs':
|
||||
missing = [key for key in allowed if not normalized.get(key)]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'DBS inventory source requires a complete report path',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)},
|
||||
)
|
||||
elif normalized:
|
||||
raise ValidationError(
|
||||
'Only DBS inventory sources can define report_path_json',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
|
||||
)
|
||||
return {key: normalized[key] for key in allowed if normalized.get(key)}
|
||||
|
||||
|
||||
def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。"""
|
||||
raw = data.get('query_parameters_json', [])
|
||||
if not isinstance(raw, list):
|
||||
raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
result: list[dict[str, Any]] = []
|
||||
seen_names: set[str] = set()
|
||||
allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'}
|
||||
for index, item in enumerate(raw):
|
||||
if not isinstance(item, dict) or set(item) - allowed:
|
||||
raise ValidationError(
|
||||
'query parameter contains unsupported fields',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index},
|
||||
)
|
||||
name = str(item.get('name') or '').strip()
|
||||
mode = str(item.get('mode') or 'single').strip().lower()
|
||||
values = item.get('values', [])
|
||||
required = item.get('required', False)
|
||||
select_all = item.get('select_all', False)
|
||||
if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}:
|
||||
raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
if not isinstance(values, list) or any(not isinstance(value, str) for value in values):
|
||||
raise ValidationError('query parameter values must be a string list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
if not isinstance(required, bool) or not isinstance(select_all, bool):
|
||||
raise ValidationError('query parameter flags must be boolean', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
normalized_values = [value.strip() for value in values if value.strip()]
|
||||
if required and not normalized_values and not select_all:
|
||||
raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
if select_all and mode != 'multi_select':
|
||||
raise ValidationError('select_all only applies to multi_select', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
parameter: dict[str, Any] = {
|
||||
'name': name, 'mode': mode, 'values': normalized_values,
|
||||
'required': required, 'select_all': select_all,
|
||||
}
|
||||
if mode == 'multi_text':
|
||||
joiner = str(item.get('joiner') or ',').strip()
|
||||
if not joiner:
|
||||
raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
parameter['joiner'] = joiner
|
||||
seen_names.add(name.lower())
|
||||
result.append(parameter)
|
||||
return result
|
||||
|
||||
|
||||
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'connector_type': profile.connector_type, 'login_url': profile.login_url,
|
||||
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
|
||||
'upload_config_json': profile.upload_config_json,
|
||||
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
|
||||
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
|
||||
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _mask(ciphertext: str | None) -> str | None:
|
||||
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
|
||||
return 'configured' if ciphertext else None
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
return value.isoformat() if value else None
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出 Profile 元数据,不返回可恢复的凭据。"""
|
||||
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
|
||||
|
||||
|
||||
def delete_profile(profile_id: int) -> None:
|
||||
"""删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。"""
|
||||
profile = db.session.get(FreightRpaProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
if FreightRpaSource.query.filter_by(rpa_profile_id=profile.id).count():
|
||||
raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED')
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
|
||||
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
profile = profile or FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
|
||||
# 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version,
|
||||
# upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。
|
||||
prev_non_upload = (
|
||||
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
|
||||
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
|
||||
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
|
||||
) if profile_id else None
|
||||
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
|
||||
profile.display_name = str(_text(data, 'display_name', required=True))
|
||||
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
|
||||
profile.login_url = str(_text(data, 'login_url', required=True))
|
||||
profile.login_config_json = _validate_profile_login_config(data)
|
||||
profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True)
|
||||
if not profile.enabled and any(source.enabled for source in profile.sources):
|
||||
raise ConflictError(
|
||||
'Disable inventory sources before disabling their RPA Profile',
|
||||
code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED',
|
||||
)
|
||||
username = _text(data, 'username')
|
||||
password = _text(data, 'password')
|
||||
if username is not None:
|
||||
profile.username_ciphertext = encrypt_credential(username)
|
||||
if password is not None:
|
||||
profile.password_ciphertext = encrypt_credential(password)
|
||||
if username is not None or password is not None:
|
||||
profile.credential_updated_at = datetime.utcnow()
|
||||
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
|
||||
if 'upload_config_json' in data:
|
||||
profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json'))
|
||||
profile.updated_by = actor_id
|
||||
if profile_id:
|
||||
now_non_upload = (
|
||||
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
|
||||
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
|
||||
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
|
||||
)
|
||||
if now_non_upload != prev_non_upload:
|
||||
profile.config_version += 1
|
||||
if not profile_id:
|
||||
profile.created_by = actor_id
|
||||
db.session.add(profile)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc
|
||||
return _profile_payload(profile)
|
||||
|
||||
|
||||
def _onhand_report_config_payload(config: FreightRpaOnhandReportConfig) -> dict[str, Any]:
|
||||
"""序列化站点一对一在手报表配置行,不透传解析方案定义。"""
|
||||
return {
|
||||
'id': config.id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
}
|
||||
|
||||
|
||||
def _source_payload(source: FreightRpaSource) -> dict[str, Any]:
|
||||
"""序列化库存站点及其是否满足正式启用前置条件。
|
||||
|
||||
s18 起报表路径/查询条件/解析方案绑定不再随站点 DTO 平铺,
|
||||
改挂在 ``onhand_report_config`` 嵌套对象(配置行不存在时为 null)。
|
||||
"""
|
||||
return {
|
||||
'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name,
|
||||
'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id,
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'onhand_report_config': (
|
||||
_onhand_report_config_payload(source.onhand_report_config)
|
||||
if source.onhand_report_config is not None else None
|
||||
),
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled),
|
||||
'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at),
|
||||
'activation': get_source_activation_status(source),
|
||||
}
|
||||
|
||||
|
||||
def _receipt_report_config_payload(config: FreightRpaInboundReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
|
||||
profile = config.parsing_profile
|
||||
return {
|
||||
'id': config.id, 'source_id': config.source_id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
# 入站解析绑定:供抽屉回显当前规则;摘要只取展示字段,不透传定义。
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
'parsing_profile': ({
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'status': profile.status,
|
||||
} if profile else None),
|
||||
'config_version': config.config_version,
|
||||
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _validate_inbound_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验收料配置绑定的入站解析规则:必须已发布且 purpose='inbound';空值表示解绑。
|
||||
|
||||
Args:
|
||||
profile_id: 请求中的 parsing_profile_id;None/空串表示解绑。
|
||||
Returns:
|
||||
规整后的规则 id 或 None。
|
||||
Raises:
|
||||
ValidationError: 规则不存在/未发布/用途不是 inbound(fail-closed,防误绑在手/出站规则)。
|
||||
"""
|
||||
if profile_id is None or str(profile_id).strip() == '':
|
||||
return None
|
||||
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
|
||||
raise ValidationError(
|
||||
'Inbound parsing profile must be published with purpose inbound',
|
||||
code='SHIPPING.INBOUND_PROFILE_INVALID',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _validate_receipt_report_config(
|
||||
source: FreightRpaSource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范收料配置,与库存同构:路径+查询条件;日期禁填。
|
||||
|
||||
DBS 的 Warehouse 等查询条件均为可选报表筛选:空条件表示 Worker 使用页面默认;
|
||||
不作为排程是否产出执行单元的门禁(一源一单元)。
|
||||
"""
|
||||
try:
|
||||
parameters = _validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
|
||||
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
|
||||
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
raw_path = _json_object(data, 'report_path_json')
|
||||
if source.connector_type == 'dbs':
|
||||
try:
|
||||
path = _validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
# Warehouse 等条件可选;缺失/空值允许保存,运行期原样下发或走页面默认。
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
if parameters:
|
||||
raise ValidationError(
|
||||
'Crane receipt report does not support query parameters',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return {'report_name': 'Inbound Details'}, []
|
||||
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
|
||||
|
||||
def get_receipt_report_config(source_id: int) -> dict[str, Any] | None:
|
||||
"""读取站点的收料配置;不存在时返回空,供抽屉初始化而非创建库存配置。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
return _receipt_report_config_payload(config) if config else None
|
||||
|
||||
|
||||
def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点内独立收料配置并追加配置前后快照审计,不写入库存 Source 字段。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
path, parameters = _validate_receipt_report_config(source, data)
|
||||
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
before = _receipt_report_config_payload(config) if config else None
|
||||
is_new = config is None
|
||||
if config is None:
|
||||
config = FreightRpaInboundReportConfig(source_id=source.id)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = _validate_inbound_profile_binding(data.get('parsing_profile_id'))
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _receipt_report_config_payload(config)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_inbound_report_config_saved', aggregate_type='shipping_inbound_report_config',
|
||||
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
|
||||
result='success', before=before, after=after,
|
||||
metadata={'source_id': source.id, 'connector_type': source.connector_type,
|
||||
'parsing_profile_id': config.parsing_profile_id},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def _validate_onhand_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验在手配置绑定的解析方案:必须已发布且 purpose='onhand';空值/0 表示解绑。
|
||||
|
||||
Args:
|
||||
profile_id: 请求载荷中的 parsing_profile_id;None/空串/0 视为解绑(与旧站点保存语义一致)。
|
||||
|
||||
Returns:
|
||||
int | None: 规整后的方案 id 或 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 方案 id 非法、不存在、未发布或用途不是 onhand
|
||||
(fail-closed,防误绑入站/出站方案,统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
|
||||
"""
|
||||
raw = str(profile_id).strip() if profile_id is not None else ''
|
||||
if raw in {'', '0'}:
|
||||
return None
|
||||
if not raw.isdigit():
|
||||
raise ValidationError(
|
||||
'Onhand parsing profile must be published with purpose onhand',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
profile = db.session.get(FreightRpaParsingProfile, int(raw))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'onhand':
|
||||
raise ValidationError(
|
||||
'Onhand parsing profile must be published with purpose onhand',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _apply_onhand_report_config(
|
||||
source: FreightRpaSource, data: dict[str, Any], *, actor_id: int | None,
|
||||
) -> FreightRpaOnhandReportConfig:
|
||||
"""把手报表三字段写入手配置行(无则插入),不触碰站点行已删除的三列。
|
||||
|
||||
核心逻辑:先全量校验路径对象/查询条件/解析绑定,失败时不留脏会话;
|
||||
校验通过后无配置行则插入(created_by=actor),有则更新并递增 config_version。
|
||||
报表路径按原样 JSON object 存取(Driver selector 等实现细节归 Worker/模板域,
|
||||
管理端 DBS 四段路径由前端 normaliseInventoryReportPath 规整后提交)。
|
||||
|
||||
Args:
|
||||
source: 已存在的库存站点(新配置行经 inventory_source 关系级联挂载)。
|
||||
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
|
||||
actor_id: 当前管理员主键,仅写审计字段。
|
||||
|
||||
Returns:
|
||||
FreightRpaOnhandReportConfig: 已写入(尚未提交)的配置行。
|
||||
"""
|
||||
# [STEP 1] 全量校验先行,任何失败都不会留下半写的配置行。
|
||||
report_path = _json_object(data, 'report_path_json')
|
||||
# DBS 四段路径按原样 JSON object 存取(前端 normaliseInventoryReportPath 规整);
|
||||
# 非 DBS(Crane)站点不得误填 DBS 报表路径(fail-closed,与列搬迁前契约一致)。
|
||||
if source.connector_type != 'dbs' and report_path:
|
||||
raise ValidationError(
|
||||
'Only DBS inventory sources can define report_path_json',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
|
||||
)
|
||||
parameters = _validate_query_parameters(data)
|
||||
parsing_profile_id = _validate_onhand_profile_binding(data.get('parsing_profile_id'))
|
||||
# [STEP 2] 校验通过后写配置行:无则插入,有则更新并递增 config_version。
|
||||
config = source.onhand_report_config
|
||||
if config is None:
|
||||
config = FreightRpaOnhandReportConfig(source=source)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.report_path_json = report_path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = parsing_profile_id
|
||||
config.updated_by = actor_id
|
||||
return config
|
||||
|
||||
|
||||
def save_onhand_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点一对一在手报表配置:没有配置行时插入,有则更新并递增该行 config_version。
|
||||
|
||||
核心逻辑:委托 _apply_onhand_report_config 校验并写行;启用中的站点借保存拆掉
|
||||
启用门禁(缺解析绑定/模板)时由 assert_onhand_source_can_enable fail-closed 拒绝。
|
||||
|
||||
Args:
|
||||
source_id: 库存站点主键,必须已存在。
|
||||
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
|
||||
actor_id: 当前管理员主键,仅写审计字段。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: 配置行 DTO(id / report_path_json / query_parameters_json / parsing_profile_id)。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 站点不存在。
|
||||
ValidationError: 解析方案不存在/未发布/purpose 不是 onhand,或启用中站点门禁被拆。
|
||||
"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
config = _apply_onhand_report_config(source, data, actor_id=actor_id)
|
||||
# 启用中的站点不得借配置保存解绑解析方案(excel_template 缺失同样拒绝)。
|
||||
assert_onhand_source_can_enable(source)
|
||||
db.session.commit()
|
||||
return _onhand_report_config_payload(config)
|
||||
|
||||
|
||||
def assert_onhand_source_can_enable(source: FreightRpaSource) -> None:
|
||||
"""启用中的库存站点必须已有在手配置行(含解析方案绑定)与发货模板。
|
||||
|
||||
【AI 触发时机】:保存站点(save_source 载荷含 enabled=true 或保留启用态)、
|
||||
保存在手配置(save_onhand_report_config 拆绑定前)时调用;
|
||||
PostgreSQL CHECK 不能跨表,解析方案存在性只能由服务层执行。
|
||||
|
||||
Args:
|
||||
source: 站点对象(可为未提交的暂态行,配置行经 onhand_report_config 关系读取)。
|
||||
|
||||
Returns:
|
||||
None: 门禁通过(站点未启用时恒通过)。
|
||||
|
||||
Raises:
|
||||
ValidationError: enabled 为真但缺配置行、配置行未绑解析方案或站点未绑模板,
|
||||
统一 code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'。
|
||||
"""
|
||||
if not source.enabled:
|
||||
return
|
||||
config = source.onhand_report_config
|
||||
if config is None or not config.parsing_profile_id or not source.excel_template_id:
|
||||
raise ValidationError(
|
||||
'Enabled inventory source requires onhand report config, parsing profile and excel template',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
|
||||
|
||||
def _binding_snapshot(source: FreightRpaSource) -> dict[str, Any]:
|
||||
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。
|
||||
|
||||
s18 起解析绑定挂在 onhand_report_config 配置行上,快照同样取自配置行。
|
||||
"""
|
||||
config = source.onhand_report_config
|
||||
return {
|
||||
'source_id': source.id,
|
||||
'source_code': source.source_code,
|
||||
'enabled': bool(source.enabled),
|
||||
'parsing_profile_id': config.parsing_profile_id if config is not None else None,
|
||||
'parsing_profile_checksum': (
|
||||
config.parsing_profile.checksum
|
||||
if config is not None and config.parsing_profile is not None else None
|
||||
),
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'config_version': source.config_version,
|
||||
}
|
||||
|
||||
|
||||
def _validate_source_parsing_binding(source: FreightRpaSource, profile: FreightRpaParsingProfile) -> None:
|
||||
"""校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。"""
|
||||
if profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
|
||||
if not mapping:
|
||||
raise ValidationError('Published parsing profile is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
template = source.excel_template
|
||||
if template is None:
|
||||
return
|
||||
if template.status != 'published':
|
||||
raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
|
||||
template_definition = template.definition_json if isinstance(template.definition_json, dict) else {}
|
||||
template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else []
|
||||
missing_fields = sorted({
|
||||
str(item.get('source_key') or '')
|
||||
for item in template_mappings
|
||||
if isinstance(item, dict)
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '') not in mapping
|
||||
})
|
||||
if missing_fields:
|
||||
raise ValidationError(
|
||||
'Parsing profile does not provide all inventory fields required by the excel template',
|
||||
code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields},
|
||||
)
|
||||
|
||||
|
||||
def bind_source_parsing_profile(
|
||||
source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。
|
||||
|
||||
Args:
|
||||
source_ids: 待绑定的库存站点主键,不能为空且不得重复。
|
||||
profile_id: 必须为已发布解析方案主键。
|
||||
actor_id: 当前管理员主键,仅写入审计。
|
||||
reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。
|
||||
operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。
|
||||
|
||||
Returns:
|
||||
list[dict[str, Any]]: 已更新站点的管理端 DTO。
|
||||
|
||||
Raises:
|
||||
ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。
|
||||
ConflictError: 试图变更已启用站点的正式解析方案。
|
||||
"""
|
||||
try:
|
||||
normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0})
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc
|
||||
if not normalized_ids or len(normalized_ids) != len(source_ids):
|
||||
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM')
|
||||
if operation not in {'direct', 'bulk'}:
|
||||
raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM')
|
||||
normalized_reason = str(reason or '').strip()
|
||||
if len(normalized_reason) > 500:
|
||||
raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM')
|
||||
# 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。
|
||||
if not normalized_reason:
|
||||
normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案'
|
||||
try:
|
||||
normalized_profile_id = int(profile_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc
|
||||
profile = db.session.get(FreightRpaParsingProfile, normalized_profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
sources = [db.session.get(FreightRpaSource, source_id) for source_id in normalized_ids]
|
||||
if any(source is None for source in sources):
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
typed_sources = [source for source in sources if source is not None]
|
||||
# [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。
|
||||
for source in typed_sources:
|
||||
_validate_source_parsing_binding(source, profile)
|
||||
for source in typed_sources:
|
||||
before = _binding_snapshot(source)
|
||||
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键。
|
||||
config = source.onhand_report_config
|
||||
previous_profile_id = config.parsing_profile_id if config is not None else None
|
||||
if config is None:
|
||||
config = FreightRpaOnhandReportConfig(source=source)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.parsing_profile_id = profile.id
|
||||
config.updated_by = actor_id
|
||||
source.updated_by = actor_id
|
||||
# 站点 config_version 仍随绑定递增:配置测试锁定版本与运行期失效判断依赖它。
|
||||
source.config_version += 1
|
||||
db.session.flush()
|
||||
db.session.add(FreightRpaSourceParsingBindingAudit(
|
||||
source_id=source.id, previous_parsing_profile_id=previous_profile_id,
|
||||
parsing_profile_id=config.parsing_profile_id, operation=operation, reason=normalized_reason, actor_id=actor_id,
|
||||
source_config_version_before=before['config_version'], source_config_version_after=source.config_version,
|
||||
before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source),
|
||||
))
|
||||
db.session.commit()
|
||||
return [_source_payload(source) for source in typed_sources]
|
||||
|
||||
|
||||
def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]:
|
||||
"""读取库存站点解析绑定审计,仅返回配置快照和操作者标识。"""
|
||||
if db.session.get(FreightRpaSource, source_id) is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
rows = FreightRpaSourceParsingBindingAudit.query.filter_by(
|
||||
source_id=source_id,
|
||||
).order_by(FreightRpaSourceParsingBindingAudit.id.desc()).all()
|
||||
return [{
|
||||
'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id,
|
||||
'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id,
|
||||
'source_config_version_before': row.source_config_version_before,
|
||||
'source_config_version_after': row.source_config_version_after,
|
||||
'before': row.before_snapshot_json, 'after': row.after_snapshot_json,
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
} for row in rows]
|
||||
|
||||
|
||||
def list_sources() -> list[dict[str, Any]]:
|
||||
"""列出库存源及其稳定业务配置。"""
|
||||
return [_source_payload(item) for item in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all()]
|
||||
|
||||
|
||||
def delete_source(source_id: int) -> None:
|
||||
"""删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
source_code = str(source.source_code or '').strip().upper()
|
||||
has_mapping = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id).count() > 0
|
||||
has_snapshot = FreightRpaOnhandReportFile.query.filter_by(source_code=source_code).count() > 0
|
||||
has_rule = any(
|
||||
source_code in {str(code).strip().upper() for code in candidates}
|
||||
for rule in FreightRpaOnhandRoutingRule.query.all()
|
||||
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
|
||||
if isinstance(candidates, list)
|
||||
)
|
||||
has_task = db.session.query(ShippingNoticeLine.id).filter(
|
||||
ShippingNoticeLine.inventory_source_code == source_code,
|
||||
).first() is not None or db.session.query(ShippingNoticeLineOnhandMatch.id).filter(
|
||||
ShippingNoticeLineOnhandMatch.source_code == source_code,
|
||||
).first() is not None
|
||||
has_export_run = any(
|
||||
source_code in {str(code).strip().upper() for code in source_codes}
|
||||
for run in ScheduleRun.query.all()
|
||||
for source_codes in [(run.api_request_json or {}).get('source_codes', [])]
|
||||
if isinstance(source_codes, list)
|
||||
)
|
||||
if has_mapping or has_snapshot or has_rule or has_task or has_export_run:
|
||||
raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED')
|
||||
db.session.delete(source)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _snapshot_payload(snapshot: FreightRpaOnhandReportFile) -> dict[str, Any]:
|
||||
"""投影库存快照的管理端只读行,不暴露存储路径或库存明细。"""
|
||||
return {
|
||||
@@ -803,204 +157,6 @@ def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
return records[:max(1, min(limit, 200))]
|
||||
|
||||
|
||||
def _template_validation_missing(source: FreightRpaSource) -> list[str]:
|
||||
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
|
||||
template = source.excel_template
|
||||
# s18 起解析方案绑定取自 onhand_report_config 配置行。
|
||||
config = source.onhand_report_config
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if template is None or profile is None:
|
||||
return []
|
||||
definition = template.definition_json if isinstance(template.definition_json, dict) else {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()}
|
||||
invalid = any(
|
||||
isinstance(item, dict)
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '') not in inventory_fields
|
||||
for item in mappings
|
||||
)
|
||||
return ['template_validation'] if not mappings or invalid else []
|
||||
|
||||
|
||||
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: FreightRpaSource) -> list[dict[str, Any]]:
|
||||
"""构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。
|
||||
|
||||
测试导出不再参与启用门禁;启停由管理员显式开关完成。
|
||||
"""
|
||||
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
|
||||
# s18 起解析方案绑定取自 onhand_report_config 配置行;配置行缺失即解析门禁未就绪。
|
||||
config = source.onhand_report_config
|
||||
parsing_profile = config.parsing_profile if config is not None else None
|
||||
parsing_ready = parsing_profile is not None and parsing_profile.status == 'published'
|
||||
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
|
||||
template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False
|
||||
return [
|
||||
_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': parsing_profile.id if parsing_profile is not None else None, '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_invalid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_invalid,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]:
|
||||
"""返回库存站点启用硬门槛的结构化结果。
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
status = get_source_activation_status(source)
|
||||
if not status['ready']:
|
||||
raise ConflictError(
|
||||
'Inventory Source is not ready for activation',
|
||||
code='SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED',
|
||||
details=status,
|
||||
)
|
||||
source.enabled = True
|
||||
source.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""停用库存站点,保留其解析方案和历史运行审计。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
source.enabled = False
|
||||
source.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def save_source(
|
||||
data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None,
|
||||
allow_enable_transition: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。
|
||||
|
||||
s18 起站点头部仅编辑 source_code / display_name / connector_type / rpa_profile_id /
|
||||
excel_template_id / 仓库模式 / snapshot_ttl_seconds;报表路径、查询条件与解析方案
|
||||
绑定经载荷内嵌的 ``onhand_report_config`` 对象写入配置行(与独立保存同一校验路径)。
|
||||
"""
|
||||
source = db.session.get(FreightRpaSource, source_id) if source_id else None
|
||||
if source_id and source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
try:
|
||||
profile_id = int(data.get('rpa_profile_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('rpa_profile_id is required') from exc
|
||||
profile = db.session.get(FreightRpaProfile, profile_id)
|
||||
if profile is None:
|
||||
raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False)
|
||||
if not allow_enable_transition:
|
||||
# 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。
|
||||
enabled = bool(source.enabled) if source is not None else False
|
||||
else:
|
||||
enabled = requested_enabled
|
||||
if enabled and not profile.enabled:
|
||||
raise ValidationError(
|
||||
'Enabled Inventory Source requires an enabled RPA Profile',
|
||||
code='SHIPPING.RPA_PROFILE_DISABLED',
|
||||
)
|
||||
excel_template_id = data.get('excel_template_id')
|
||||
excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None
|
||||
if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'):
|
||||
raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
|
||||
is_new = source is None
|
||||
source = source or FreightRpaSource(
|
||||
source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed',
|
||||
)
|
||||
source.source_code = str(_text(data, 'source_code', required=True)).upper()
|
||||
source.display_name = str(_text(data, 'display_name', required=True))
|
||||
source.connector_type = str(_text(data, 'connector_type', required=True)).lower()
|
||||
source.rpa_profile = profile
|
||||
source.excel_template = excel_template
|
||||
source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower()
|
||||
source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id')
|
||||
source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400)
|
||||
source.enabled = enabled
|
||||
source.updated_by = actor_id
|
||||
if source_id:
|
||||
source.config_version += 1
|
||||
if is_new:
|
||||
source.created_by = actor_id
|
||||
db.session.add(source)
|
||||
# [STEP 1] 启用门禁先行:缺模板在写库前给出可解释错误,避免撞站点行 CHECK 的 IntegrityError
|
||||
# (模板缺失复用 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED,不新造码)。
|
||||
if enabled and excel_template is None:
|
||||
raise ValidationError(
|
||||
'published excel_template_id is required',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
try:
|
||||
# flush 让 excel_template_id / 新行主键先行落位,后续门禁读取规整后的外键。
|
||||
db.session.flush()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
|
||||
# [STEP 2] 载荷内嵌 onhand_report_config 时与独立保存走同一校验/写行路径(无则插入配置行)。
|
||||
config_data = data.get('onhand_report_config')
|
||||
if isinstance(config_data, dict):
|
||||
_apply_onhand_report_config(source, config_data, actor_id=actor_id)
|
||||
# [STEP 3] 启用门禁复核(缺配置行/解析绑定/模板统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
|
||||
if enabled:
|
||||
assert_onhand_source_can_enable(source)
|
||||
validate_source_profile(source, profile)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def _rule_payload(rule: FreightRpaOnhandRoutingRule) -> dict[str, Any]:
|
||||
return {
|
||||
'id': rule.id, 'rule_code': rule.rule_code, 'rule_name': rule.rule_name, 'scope': rule.scope,
|
||||
|
||||
Reference in new issue
Block a user