Merge branch 'dev' into common-problems-fuzzy-query
This commit is contained in:
commit
d3204f1db8
790 files changed
+71443
-26080
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)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,391 @@
|
||||
"""
|
||||
services/admin/shipping_onhand_admin_service.py
|
||||
|
||||
用途:在手域管理——库存快照只读、导出运行记录、路由规则、外部仓库映射。
|
||||
依赖: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 typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaOnhandExternalMapping,
|
||||
FreightRpaOnhandReportFile,
|
||||
FreightRpaOnhandRoutingRule,
|
||||
FreightRpaOnhandRoutingRuleCondition,
|
||||
FreightRpaOnhandRoutingRuleVersion,
|
||||
FreightRpaSource,
|
||||
ScheduleRun,
|
||||
ScheduleTask,
|
||||
ShippingOrderField,
|
||||
)
|
||||
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.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})
|
||||
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 _snapshot_payload(snapshot: FreightRpaOnhandReportFile) -> dict[str, Any]:
|
||||
"""投影库存快照的管理端只读行,不暴露存储路径或库存明细。"""
|
||||
return {
|
||||
'id': snapshot.id, 'inventory_file_no': snapshot.onhand_file_no,
|
||||
'source_code': snapshot.source_code, 'warehouse_id': snapshot.warehouse_id,
|
||||
'snapshot_status': snapshot.snapshot_status, 'identity_status': snapshot.identity_status,
|
||||
'line_count': snapshot.line_count, 'share_mode': snapshot.share_mode,
|
||||
'exported_at': _iso(snapshot.exported_at), 'expires_at': _iso(snapshot.expires_at),
|
||||
'rpa_run_no': snapshot.rpa_run_no, 'schedule_run_id': snapshot.schedule_run_id,
|
||||
'source_file_name': snapshot.source_file_name, 'created_at': _iso(snapshot.created_at),
|
||||
'download_available': bool(snapshot.storage_path and not str(snapshot.storage_path).startswith('failed://')),
|
||||
'error_message': (snapshot.schema_preview_json or {}).get('error') if snapshot.snapshot_status == 'failed' else None,
|
||||
}
|
||||
|
||||
|
||||
def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""列出最新库存快照,供管理员确认当前可用的库存文件。"""
|
||||
rows = FreightRpaOnhandReportFile.query.order_by(
|
||||
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
|
||||
).limit(max(1, min(limit, 200))).all()
|
||||
return [_snapshot_payload(row) for row in rows]
|
||||
|
||||
|
||||
def get_snapshot_download(snapshot_id: int) -> tuple[str, str]:
|
||||
"""返回管理员可下载的库存快照路径及安全文件名。
|
||||
|
||||
Args:
|
||||
snapshot_id: 库存快照主键。
|
||||
|
||||
Returns:
|
||||
本地托管文件绝对路径和面向下载的文件名。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 快照不存在或托管文件已不存在。
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
snapshot = db.session.get(FreightRpaOnhandReportFile, snapshot_id)
|
||||
if snapshot is None:
|
||||
raise NotFoundError('Inventory snapshot not found', code='SHIPPING.ONHAND_SNAPSHOT_NOT_FOUND')
|
||||
path = Path(str(snapshot.storage_path or '')).resolve()
|
||||
if not str(snapshot.storage_path or '') or str(snapshot.storage_path).startswith('failed://') or not path.is_file():
|
||||
raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.ONHAND_SNAPSHOT_FILE_NOT_FOUND')
|
||||
filename = str(snapshot.source_file_name or f'{snapshot.onhand_file_no}{path.suffix or ".xlsx"}')
|
||||
return str(path), filename
|
||||
|
||||
|
||||
def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""列出 RPA 导出记录,合并已归档文件与排程失败/跳过结果。"""
|
||||
file_rows = FreightRpaOnhandReportFile.query.filter(
|
||||
FreightRpaOnhandReportFile.rpa_run_no.is_not(None),
|
||||
).order_by(
|
||||
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
|
||||
).limit(max(1, min(limit, 200))).all()
|
||||
records = [_snapshot_payload(row) for row in file_rows]
|
||||
known_identities = {
|
||||
(str(item.get('rpa_run_no') or ''), str(item.get('source_code') or ''), str(item.get('warehouse_id') or ''))
|
||||
for item in records
|
||||
}
|
||||
|
||||
# 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。
|
||||
schedule_runs = ScheduleRun.query.join(ScheduleTask).filter(
|
||||
ScheduleTask.platform_api_path == 'freight-rpa-onhand',
|
||||
).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all()
|
||||
for run in schedule_runs:
|
||||
response = run.api_response_json if isinstance(run.api_response_json, dict) else {}
|
||||
request_data = run.api_request_json if isinstance(run.api_request_json, dict) else {}
|
||||
run_no = str(response.get('run_no') or request_data.get('run_no') or run.run_no or '').strip()
|
||||
items: list[tuple[str, dict[str, Any]]] = []
|
||||
for status, key in (('skipped', 'skipped'), ('failed', 'failed')):
|
||||
for item in response.get(key) if isinstance(response.get(key), list) else []:
|
||||
if isinstance(item, dict):
|
||||
items.append((status, item))
|
||||
if not items and run.status in {'queued', 'running'}:
|
||||
pending = (run.response_summary_json or {}).get('pending_details', [])
|
||||
for item in pending if isinstance(pending, list) else []:
|
||||
if isinstance(item, dict):
|
||||
items.append(('awaiting_rpa', item))
|
||||
if not items and run.status in {'failed', 'partial_failed'}:
|
||||
for source_code in request_data.get('source_codes') if isinstance(request_data.get('source_codes'), list) else []:
|
||||
items.append(('failed', {'source_code': source_code, 'error_message': run.error_message}))
|
||||
for status, item in items:
|
||||
source_code = str(item.get('source_code') or '').strip()
|
||||
warehouse_id = str(item.get('warehouse_id') or '').strip()
|
||||
identity = (run_no, source_code, warehouse_id)
|
||||
if identity in known_identities:
|
||||
continue
|
||||
known_identities.add(identity)
|
||||
records.append({
|
||||
'id': f'schedule-{run.id}-{status}-{source_code}-{warehouse_id}',
|
||||
'inventory_file_no': None,
|
||||
'source_code': source_code or None,
|
||||
'warehouse_id': warehouse_id or None,
|
||||
'snapshot_status': status,
|
||||
'export_status': status,
|
||||
'identity_status': None,
|
||||
'line_count': 0,
|
||||
'share_mode': None,
|
||||
'exported_at': _iso(run.finished_at or run.created_at),
|
||||
'expires_at': None,
|
||||
'rpa_run_no': run_no or None,
|
||||
'schedule_run_id': run.id,
|
||||
'source_file_name': None,
|
||||
'created_at': _iso(run.created_at),
|
||||
'error_message': str(item.get('error_message') or item.get('error') or run.error_message or '')[:500] or None,
|
||||
})
|
||||
records.sort(key=lambda item: str(item.get('exported_at') or item.get('created_at') or ''), reverse=True)
|
||||
return records[:max(1, min(limit, 200))]
|
||||
|
||||
|
||||
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,
|
||||
'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status,
|
||||
'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version,
|
||||
'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id,
|
||||
'operator': c.operator, 'expected_value_json': c.expected_value_json,
|
||||
'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions],
|
||||
}
|
||||
|
||||
|
||||
def _validate_rule_condition_expected(operator: str, value: Any) -> Any:
|
||||
"""按匹配符号规范化期望值,避免自由 JSON 在运行期才暴露配置错误。"""
|
||||
if operator in {'is_empty', 'is_not_empty'}:
|
||||
return None
|
||||
if operator in {'in', 'not_in'}:
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError('List operator requires a string list', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
normalized = [str(item).strip() for item in value if str(item).strip()]
|
||||
if not normalized:
|
||||
raise ValidationError('List operator requires at least one value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
return normalized
|
||||
if operator in {'numeric_length', 'string_length'}:
|
||||
try:
|
||||
length = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Length operator requires an integer', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') from exc
|
||||
if length < 0:
|
||||
raise ValidationError('Length must not be negative', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
return length
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValidationError('Routing condition requires an expected value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
return value.strip()
|
||||
|
||||
|
||||
def list_rules() -> list[dict[str, Any]]:
|
||||
"""列出规则及条件,用于草稿编辑和已发布规则查看。"""
|
||||
return [_rule_payload(item) for item in FreightRpaOnhandRoutingRule.query.order_by(FreightRpaOnhandRoutingRule.priority.desc()).all()]
|
||||
|
||||
|
||||
def delete_draft_rule(rule_id: int) -> None:
|
||||
"""删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。"""
|
||||
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
|
||||
if rule.status != 'draft':
|
||||
raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.ONHAND_RULE_DELETE_BLOCKED')
|
||||
db.session.delete(rule)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""归档已发布规则,使其不再参与新路由,同时保留已发布版本。"""
|
||||
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
|
||||
if rule.status != 'published':
|
||||
raise ConflictError('Only published routing rules can be retired', code='SHIPPING.ONHAND_RULE_RETIRE_INVALID')
|
||||
rule.status = 'retired'
|
||||
rule.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _rule_payload(rule)
|
||||
|
||||
|
||||
def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None = None) -> dict[str, Any]:
|
||||
"""保存草稿规则;发布规则必须以新版本创建,避免篡改历史定义。"""
|
||||
if rule_id:
|
||||
current = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
|
||||
if current is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
|
||||
if current.status != 'draft':
|
||||
raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.ONHAND_RULE_IMMUTABLE')
|
||||
rule = current if rule_id else FreightRpaOnhandRoutingRule(
|
||||
rule_code='', rule_name='', scope='', action_type='', action_payload_json={}
|
||||
)
|
||||
rule.rule_code = str(_text(data, 'rule_code', required=True)).upper()
|
||||
rule.rule_name = str(_text(data, 'rule_name', required=True))
|
||||
rule.scope = str(_text(data, 'scope', required=True)).lower()
|
||||
rule.priority = int(data.get('priority') or 0)
|
||||
rule.match_mode = str(data.get('match_mode') or 'all').lower()
|
||||
rule.status = 'draft'
|
||||
rule.action_type = str(_text(data, 'action_type', required=True)).lower()
|
||||
rule.action_payload_json = data.get('action_payload_json') if isinstance(data.get('action_payload_json'), dict) else {}
|
||||
rule.version = int(data.get('version') or 1)
|
||||
if not rule_id:
|
||||
rule.created_by = actor_id
|
||||
rule.updated_by = actor_id
|
||||
if rule.action_type not in ALLOWED_ACTIONS or rule.scope not in {'task', 'line'} or rule.match_mode not in {'all', 'any'}:
|
||||
raise ValidationError('Invalid routing rule metadata', code='SHIPPING.ONHAND_RULE_INVALID')
|
||||
conditions = data.get('conditions')
|
||||
if not isinstance(conditions, list) or not conditions:
|
||||
raise ValidationError('Routing rule requires conditions', code='SHIPPING.ONHAND_RULE_CONDITIONS_REQUIRED')
|
||||
# 草稿更新在同一版本内替换条件;发布后不可原地修改。
|
||||
if rule_id:
|
||||
db.session.query(FreightRpaOnhandRoutingRuleCondition).filter_by(rule_id=rule.id).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
db.session.flush()
|
||||
db.session.expire(rule, ['conditions'])
|
||||
for index, item in enumerate(conditions, start=1):
|
||||
if not isinstance(item, dict) or item.get('operator') not in ALLOWED_OPERATORS:
|
||||
raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
source_kind = str(item.get('source_kind') or 'order_field')
|
||||
order_field_id = str(item.get('order_field_id') or '') or None
|
||||
field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None
|
||||
if source_kind == 'order_field':
|
||||
if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'):
|
||||
raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
published_fields = {
|
||||
str(config.get('field_id'))
|
||||
for config in order_schema_service.get_published_contract()['fields']
|
||||
if config.get('scope') == field.scope
|
||||
}
|
||||
if field.id not in published_fields:
|
||||
raise ValidationError('Routing order field is not published', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
else:
|
||||
raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
operator = str(item['operator'])
|
||||
rule.conditions.append(FreightRpaOnhandRoutingRuleCondition(
|
||||
condition_group=int(item.get('condition_group') or 1), source_kind=source_kind,
|
||||
order_field_id=order_field_id,
|
||||
operator=operator, expected_value_json=_validate_rule_condition_expected(
|
||||
operator, item.get('expected_value_json'),
|
||||
), sequence=index,
|
||||
))
|
||||
if not rule_id:
|
||||
db.session.add(rule)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Routing rule code and version already exist', code='SHIPPING.ONHAND_RULE_CONFLICT') from exc
|
||||
return _rule_payload(rule)
|
||||
|
||||
|
||||
def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""发布草稿并写入不可变规则定义快照。
|
||||
|
||||
路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际
|
||||
库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。
|
||||
"""
|
||||
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
|
||||
if rule.status != 'draft':
|
||||
raise ConflictError('Only draft routing rules can be published', code='SHIPPING.ONHAND_RULE_PUBLISH_INVALID')
|
||||
if rule.action_type in {'add_source_candidates', 'exclude_source_candidates'}:
|
||||
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
|
||||
source_codes = {
|
||||
str(code or '').strip().upper()
|
||||
for code in payload.get('source_codes', [])
|
||||
if str(code or '').strip()
|
||||
}
|
||||
existing_codes = {
|
||||
str(code).strip().upper()
|
||||
for (code,) in db.session.query(FreightRpaSource.source_code).all()
|
||||
}
|
||||
missing_codes = sorted(source_codes - existing_codes)
|
||||
if missing_codes:
|
||||
raise ValidationError(
|
||||
'Routing rule references unavailable inventory sources',
|
||||
code='SHIPPING.ONHAND_RULE_SOURCE_INVALID',
|
||||
details={'source_codes': missing_codes},
|
||||
)
|
||||
rule.status = 'published'
|
||||
rule.updated_by = actor_id
|
||||
db.session.add(FreightRpaOnhandRoutingRuleVersion(
|
||||
rule_id=rule.id, version=rule.version, definition_json=_rule_payload(rule), published_by=actor_id,
|
||||
))
|
||||
db.session.commit()
|
||||
return _rule_payload(rule)
|
||||
|
||||
|
||||
def _external_payload(mapping: FreightRpaOnhandExternalMapping) -> dict[str, Any]:
|
||||
return {
|
||||
'id': mapping.id, 'source_id': mapping.source_id,
|
||||
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
|
||||
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
|
||||
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
|
||||
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
|
||||
'enabled': bool(mapping.enabled), 'version': mapping.version,
|
||||
}
|
||||
|
||||
|
||||
def list_external_mappings() -> list[dict[str, Any]]:
|
||||
"""列出库存源到外部系统仓库的映射,不执行调拨判断。"""
|
||||
return [_external_payload(item) for item in FreightRpaOnhandExternalMapping.query.order_by(FreightRpaOnhandExternalMapping.id).all()]
|
||||
|
||||
|
||||
def delete_external_mapping(mapping_id: int) -> None:
|
||||
"""删除错误的外部仓库映射;历史文件和任务不回写此实时配置。"""
|
||||
record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id)
|
||||
if record is None:
|
||||
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND')
|
||||
db.session.delete(record)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新精确/默认外部系统映射。"""
|
||||
record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id) if mapping_id else None
|
||||
if mapping_id and record is None:
|
||||
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND')
|
||||
try:
|
||||
source_id = int(data.get('source_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('source_id is required') from exc
|
||||
if db.session.get(FreightRpaSource, source_id) is None:
|
||||
raise ValidationError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
record = record or FreightRpaOnhandExternalMapping(source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
|
||||
record.source_id = source_id
|
||||
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
|
||||
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
|
||||
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
|
||||
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
|
||||
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
|
||||
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
|
||||
record.external_organization_code = _text(data, 'external_organization_code')
|
||||
record.external_site_code = _text(data, 'external_site_code')
|
||||
record.external_warehouse_code = str(_text(data, 'external_warehouse_code', required=True)).upper()
|
||||
record.external_warehouse_name = str(_text(data, 'external_warehouse_name', required=True))
|
||||
record.enabled = _bool(data, 'enabled', bool(record.enabled) if mapping_id else True)
|
||||
record.updated_by = actor_id
|
||||
if not mapping_id:
|
||||
record.created_by = actor_id
|
||||
db.session.add(record)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_CONFLICT') from exc
|
||||
return _external_payload(record)
|
||||
Reference in new issue
Block a user