feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务

- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
This commit is contained in:
hugo committed 2026-10-19 18:45:16 +08:00
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,
@@ -1,13 +1,14 @@
"""
services/freight_rpa/common/worker_heartbeat.py
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/入站/出站就绪检查与状态查询。
依赖:Flask current_app、redis_client、同包 rpa_runtime(mock 模式)、
freight_rpa.onhand.trigger_io(onhand trigger 目录)、
freight_rpa.upload.trigger_io(上传目录)、
freight_rpa.inbound.trigger_io(inbound trigger 目录)。
逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound trigger 前强制就绪检查;
管理端 /rpa-workers/status?scope=onhand|inbound 展示对应 Worker 心跳徽标。
freight_rpa.inbound.trigger_io(inbound trigger 目录)、
freight_rpa.outbound.trigger_io(outbound trigger 目录)。
逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound/outbound trigger 前强制就绪检查;
管理端 /rpa-workers/status?scope=onhand|inbound|outbound 展示对应 Worker 心跳徽标。
"""
from __future__ import annotations
@@ -40,8 +41,11 @@ RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 W
ONHAND_EXPORT_CAPABILITY = "onhand_export"
FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload"
INBOUND_EXPORT_CAPABILITY = "inbound_export"
OUTBOUND_EXPORT_CAPABILITY = "outbound_export"
# inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。
INBOUND_WORKER_ID_SUFFIX = "-inbound"
# outbound Worker 由 start_outbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-outbound。
OUTBOUND_WORKER_ID_SUFFIX = "-outbound"
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
@@ -59,6 +63,7 @@ _REASON_USER_HINTS: dict[str, str] = {
"environment_mismatch": "Worker 环境与后端环境不一致",
"missing_onhand_export_capability": "Worker 未声明 onhand_export 能力",
"missing_inbound_export_capability": "Worker 未声明 inbound_export 能力",
"missing_outbound_export_capability": "Worker 未声明 outbound_export 能力",
"missing_freight_rpa_upload_capability": "Worker 未声明 freight_rpa_upload 能力",
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
@@ -369,7 +374,7 @@ def _verify_shared_trigger_mount(
trigger_dir: Path | None, *, require_sentinel: bool = True,
) -> tuple[bool, list[str]]:
"""
校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。
校验 trigger 目录可写;默认要求共享哨兵(库存与入站同口径)。
Args:
trigger_dir: 共享 trigger 目录。
@@ -407,7 +412,7 @@ def _verify_shared_trigger_mount(
return not reasons, reasons
def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool:
def is_inbound_rpa_worker(worker: dict[str, Any]) -> bool:
"""
判断心跳是否来自 inbound(原收料)Worker。
@@ -428,6 +433,27 @@ def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool:
return False
def is_outbound_rpa_worker(worker: dict[str, Any]) -> bool:
"""
判断心跳是否来自 outbound Worker。
优先认 <主机名>-outbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与 outbound 目录对齐判定。
"""
if str(worker.get("worker_id") or "").strip().lower().endswith(OUTBOUND_WORKER_ID_SUFFIX):
return True
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
expected = outbound_trigger_dir()
actual = str(worker.get("trigger_dir") or "").strip()
if expected is None or not actual:
return False
try:
return Path(actual).resolve() == expected.resolve()
except OSError:
return False
def _worker_scope_matches(worker: dict[str, Any]) -> tuple[bool, list[str]]:
expected_scope = shared_scope_id()
if not expected_scope:
@@ -454,7 +480,7 @@ def _worker_is_eligible(
backend_env: 后端归一环境(dev/test/prod)。
ttl_seconds: 心跳 TTL。
now: 当前 epoch 秒。
required_capability: 必选能力(onhand_export / inbound_export / freight_rpa_upload)。
required_capability: 必选能力(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。
Returns:
(是否合格, 不合格原因列表)。
@@ -482,7 +508,7 @@ def _worker_is_eligible(
def _missing_capability_reason(required_capability: str) -> str:
"""按必选能力生成缺失原因码(onhand_export / inbound_export / freight_rpa_upload)。"""
"""按必选能力生成缺失原因码(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。"""
return f"missing_{required_capability}_capability"
@@ -521,8 +547,8 @@ def _check_rpa_worker_ready_for_capability(
trigger_dir: 待校验的共享 trigger 目录。
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
extra_reasons: 调用方预检附加原因(凭据/队列等)。
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。
worker_predicate: 可选过滤(如仅入站 Worker);不匹配的心跳不进入列表。
require_sentinel: 是否要求共享哨兵(库存/入站同口径均 True)。
Returns:
RpaWorkerReadiness。
@@ -637,9 +663,9 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
)
def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
def check_inbound_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
检查入站 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求
inbound_export 能力;校验 inbound trigger 目录可写;与 onhand 同口径要求共享哨兵。
@@ -649,24 +675,24 @@ def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
return _check_rpa_worker_ready_for_capability(
trigger_dir=inbound_trigger_dir(),
required_capability=INBOUND_EXPORT_CAPABILITY,
worker_predicate=is_receipt_rpa_worker,
worker_predicate=is_inbound_rpa_worker,
require_sentinel=True,
)
def assert_receipt_rpa_worker_ready() -> None:
def assert_inbound_rpa_worker_ready() -> None:
"""
写收料 trigger 前的强制就绪检查。
写入站 trigger 前的强制就绪检查。
核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError,
排程不得进入 awaiting_receipt_rpa。
排程不得进入 awaiting_inbound_rpa。
Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
"""
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
result = check_receipt_rpa_worker_ready()
result = check_inbound_rpa_worker_ready()
if result.ready:
return
code = 'RPA.WORKER_OFFLINE'
@@ -691,6 +717,60 @@ def assert_receipt_rpa_worker_ready() -> None:
)
def check_outbound_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查出站 RPA Worker 是否在线(写 trigger 前 fail-fast)。
核心逻辑:仅看 outbound Worker 心跳(*-outbound 或 trigger_dir 对齐);要求
outbound_export 能力;校验 outbound trigger 目录可写;与 onhand/inbound 同口径要求共享哨兵。
"""
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
return _check_rpa_worker_ready_for_capability(
trigger_dir=outbound_trigger_dir(),
required_capability=OUTBOUND_EXPORT_CAPABILITY,
worker_predicate=is_outbound_rpa_worker,
require_sentinel=True,
)
def assert_outbound_rpa_worker_ready() -> None:
"""
写出站 trigger 前的强制就绪检查。
核心逻辑:镜像 assert_inbound_rpa_worker_ready;离线则抛 ServiceUnavailableError,
排程不得进入 awaiting_outbound_rpa_callback。
Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
"""
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
result = check_outbound_rpa_worker_ready()
if result.ready:
return
code = 'RPA.WORKER_OFFLINE'
if 'heartbeat_storage_unavailable' in result.reasons:
code = 'RPA.HEARTBEAT_STORAGE_UNAVAILABLE'
logger.warning(
'[rpa-heartbeat] outbound readiness blocked code=%s reasons=%s detail=%s',
code,
result.reasons,
result.detail_message,
)
raise ServiceUnavailableError(
result.message,
code=code,
details={
'reasons': result.reasons,
'detail_message': result.detail_message,
'checked_at': result.checked_at,
'shared_scope_id': shared_scope_id(),
'trigger_dir': str(outbound_trigger_dir() or ''),
},
)
def _freight_upload_config_reasons() -> list[str]:
"""
预检货代上传静态配置:凭据主密钥、上传队列目录、回调 API 基址。
@@ -852,19 +932,23 @@ def assert_inventory_rpa_worker_ready() -> None:
def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]:
"""
管理端展示:按 scope 返回在手(onhand)或入站(inbound)Worker 心跳摘要。
管理端展示:按 scope 返回在手(onhand)、入站(inbound)或出站(outbound)Worker 心跳摘要。
Args:
scope: onhand(默认,库存 RPA 工作台)或 inbound(入站 RPA 工作台);
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识(Task 12)无关。
scope: onhand(默认,库存 RPA 工作台)、inbound(入站)或 outbound(出站);
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识无关。
"""
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
normalized = str(scope or "onhand").strip().lower()
if normalized == "inbound":
readiness = check_receipt_rpa_worker_ready()
readiness = check_inbound_rpa_worker_ready()
trigger_path = str(inbound_trigger_dir() or "")
elif normalized == "outbound":
readiness = check_outbound_rpa_worker_ready()
trigger_path = str(outbound_trigger_dir() or "")
else:
readiness = check_inventory_rpa_worker_ready()
trigger_path = str(onhand_trigger_dir() or "")
@@ -2,19 +2,16 @@
services/freight_rpa/inbound/report_archive.py
用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
三年保留期、不写库存快照表)、到期对象清理(retention)、单文件企微投递与管理员
强制重发(resend)。批次 R Task 10 自 shipping_notice.receipt_report_storage /
schedule.freight_rpa_inbound_retention / shipping_notice.receipt_report_notification
平移而来(函数名 receipt 词根→inbound;模型 ShippingInboundReport* 引用不变——批次 S 才改表)。
依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun / FreightRpaInboundNotificationDelivery /
User / ScheduleRun 相关模型经行对象访问)、file_assets.storage、integrations.wecom.notify、
freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
三年保留期、不写库存快照表)与到期对象清理(retention)。per-file 企微投递与 resend
已拆除(Task 2);排程终态通知仍走 freight_rpa_inbound_finalize 统一出口。
依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun、ScheduleRun 经行对象访问)、
file_assets.storage、freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
freight_rpa.common.report_audit(本域唯一审计写入口,批次 B Task 6 起替代
shipping_notice.audit_service——freight_rpa 禁止 import shipping_notice 业务模块,
边界由 tests/services/freight_rpa/test_import_boundary.py 空白名单锁定)、
freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递,Task 6)。
逻辑:Worker 回调进入 /api/freight-rpa/inbound-batch-ready 后由组合根注册的业务 sink
(shipping_notice.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
(in_transit_transfer.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」——
commit 后构造 ReportFact(report_kind='inbound', ...) 调 dispatch_report_fact;
处理函数异常原样外抛(不吞、不回滚已提交终态),kind 未注册时 404
@@ -36,19 +33,14 @@ from flask import current_app
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
FreightRpaInboundNotificationDelivery,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
User,
)
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media
def _read_inbound_callback_file(file_path: str) -> bytes:
"""只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
@@ -59,7 +51,7 @@ def _read_inbound_callback_file(file_path: str) -> bytes:
"""
configured_root = str(inbound_drop_dir() or '').strip()
if not configured_root:
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
raise ValidationError('inbound callback file root is unavailable', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
root = Path(configured_root).resolve()
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
name = Path(str(file_path).replace('\\', '/')).name
@@ -67,12 +59,12 @@ def _read_inbound_callback_file(file_path: str) -> bytes:
try:
path.relative_to(root)
except ValueError as exc:
raise ValidationError('receipt callback file is outside receipt drop root', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') from exc
raise ValidationError('inbound callback file is outside inbound drop root', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') from exc
if path.suffix.lower() != '.xlsx' or not path.is_file():
raise ValidationError('receipt callback file must be an existing xlsx', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
raise ValidationError('inbound callback file must be an existing xlsx', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024
if path.stat().st_size > max_size:
raise ValidationError('receipt callback file exceeds configured size limit', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
raise ValidationError('inbound callback file exceeds configured size limit', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
return path.read_bytes()
@@ -96,23 +88,23 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
(供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。
"""
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID')
raise ValidationError('inbound callback schema_version is invalid', code='SHIPPING.INBOUND_CALLBACK_INVALID')
callback_id = str(payload.get('callback_id') or '').strip()
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
raise NotFoundError('Receipt RPA unit not found', code='SHIPPING.RECEIPT_UNIT_NOT_FOUND')
raise NotFoundError('Inbound RPA unit not found', code='SHIPPING.INBOUND_UNIT_NOT_FOUND')
status = str(payload.get('status') or '').strip().lower()
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
if status in {'empty', 'no_data'}:
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_inbound_data。
unit.status = 'empty'
unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64]
unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000]
unit.error_code = str(payload.get('error_code') or 'no_inbound_data')[:64]
unit.error_message = str(payload.get('error_message') or 'no_inbound_data')[:2000]
unit.finished_at = datetime.utcnow()
append_rpa_report_event(
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success',
actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success',
before=before,
after={
'status': 'empty',
@@ -127,17 +119,17 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
db.session.commit()
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False,
error_code=unit.error_code or 'no_receipt_data',
error_message=unit.error_message or 'no_receipt_data',
error_code=unit.error_code or 'no_inbound_data',
error_message=unit.error_message or 'no_inbound_data',
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': 'empty'}
if status != 'success':
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow()
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.INBOUND_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'inbound export failed')[:2000]; unit.finished_at = datetime.utcnow()
append_rpa_report_event(
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='failure',
actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='failure',
before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'callback_status': status},
)
@@ -154,7 +146,7 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
sha256 = hashlib.sha256(data).hexdigest()
claimed = str(payload.get('sha256') or '').lower()
if claimed and claimed != sha256:
raise ValidationError('receipt callback sha256 mismatch', code='SHIPPING.RECEIPT_CALLBACK_SHA_MISMATCH')
raise ValidationError('inbound callback sha256 mismatch', code='SHIPPING.INBOUND_CALLBACK_SHA_MISMATCH')
existing = FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
if existing:
# [STEP] 幂等重放:不插第二行,仍投递 ok=True 事实(同一 file_id),供处理函数重试;
@@ -171,7 +163,7 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
db.session.add(record)
unit.status = 'success'; unit.finished_at = datetime.utcnow()
db.session.flush()
append_rpa_report_event(event_type='shipping_inbound_report_archived', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
append_rpa_report_event(event_type='shipping_inbound_report_archived', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'inbound_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
# [STEP] 先 commit 归档,再投递 ok=True 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
db.session.commit()
@@ -210,7 +202,7 @@ def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='success',
before={'status': 'archived'}, after={'status': 'archive_deleted'},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
success += 1
except Exception as exc:
@@ -220,88 +212,8 @@ def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='failure',
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
failed += 1
db.session.commit()
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
def _recipient_ids(report_file: FreightRpaInboundReportFile) -> list[int]:
"""从所属排程冻结的接收人列表取目标用户;停用通知时返回空。"""
run = report_file.unit_run.schedule_run
task = run.task if run else None
if task is None or not task.notify_enabled:
return []
return sorted({int(user_id) for user_id in (task.notify_user_ids_json or []) if str(user_id).isdigit()})
def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
"""向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。
Args:
file_id: 已归档收料文件主键(FreightRpaInboundReportFile.id)。
force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。
Returns:
dict: success_count / failed_count(file_not_found 时附 reason)。
"""
report_file = db.session.get(FreightRpaInboundReportFile, file_id)
if report_file is None:
return {'success_count': 0, 'failed_count': 0, 'reason': 'file_not_found'}
success_count = failed_count = 0
for user_id in _recipient_ids(report_file):
key = f'receipt:file:{report_file.id}:user:{user_id}'
delivery = FreightRpaInboundNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
if delivery and delivery.status == 'success' and not force:
success_count += 1
continue
if delivery is None:
delivery = FreightRpaInboundNotificationDelivery(
unit_run_id=report_file.unit_run_id, report_file_id=report_file.id, recipient_user_id=user_id,
message_type='file', idempotency_key=key, status='pending',
)
db.session.add(delivery)
db.session.flush()
user = db.session.get(User, user_id)
if user is None or not user.wecom_userid:
delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding'
failed_count += 1
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
after={'delivery_status': delivery.status, 'error_code': delivery.error_code},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
)
continue
try:
media_id = upload_wecom_temp_media(file_asset_storage.get_bytes(report_file.storage_key), report_file.original_filename)
result = send_wecom_file_message(user.wecom_userid, media_id)
if int(result.get('errcode', -1)) != 0:
raise RuntimeError(str(result.get('errmsg') or result.get('errcode')))
delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.error_code = None; delivery.error_message = None
delivery.response_summary_json = {'media_uploaded': True, 'errcode': 0}
success_count += 1
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id),
actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='success',
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
)
except Exception as exc:
delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]
failed_count += 1
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
)
db.session.commit()
return {'success_count': success_count, 'failed_count': failed_count}
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'inbound_retention', 'status': 'completed'}]
@@ -0,0 +1 @@
"""outbound:出站 RPA。"""
@@ -0,0 +1,246 @@
"""
services/freight_rpa/outbound/report_archive.py
用途:outbound(出站)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
三年保留期、不写库存快照表)。
依赖:models(FreightRpaOutboundReportFile / FreightRpaOutboundUnitRun)、
file_assets.storage、freight_rpa.outbound.trigger_io(回调 SCHEMA 与 drop 根)、
freight_rpa.common.report_audit(本域唯一审计写入口)、
freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递)。
逻辑:Worker 回调进入 /api/freight-rpa/outbound-batch-ready 后由组合根(Task 10)
或测内临时 register 的 sink 调 ingest_outbound_callback 完成原样归档;
empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」——
commit 后构造 ReportFact(report_kind='outbound', ...) 调 dispatch_report_fact;
处理函数异常原样外抛(不吞、不回滚已提交终态);同一 unit_run_id + sha256
已有文件时不插第二行、仍投递 ok=True 的事实供处理函数重试。
跨机路径:file_path 只认 outbound drop 根内文件名,禁止把 Worker Windows
绝对路径当 Linux 路径打开(对照 inbound._read_inbound_callback_file)。
本模块不 import shipping_notice / in_transit_transfer,不移植入站逐文件企微投递。
"""
from __future__ import annotations
import hashlib
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from flask import current_app
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
)
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_TRIGGER_SCHEMA, outbound_drop_dir
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
from app.services.freight_rpa.reports.facts import ReportFact
def _read_outbound_callback_file(file_path: str) -> bytes:
"""只读取 outbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...)。
一律 replace('\\','/') 后取 .name,再拼本机 FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR,
relative_to(root) 防穿越。禁止把回调串当 Linux 路径直接 open。
"""
configured_root = str(outbound_drop_dir() or "").strip()
if not configured_root:
raise ValidationError(
"outbound callback file root is unavailable",
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
)
root = Path(configured_root).resolve()
# [STEP] 跨机:先归一分隔符再取末段文件名,绝不 Path(file_path).read_bytes()。
name = Path(str(file_path).replace("\\", "/")).name
path = (root / name).resolve()
try:
path.relative_to(root)
except ValueError as exc:
raise ValidationError(
"outbound callback file is outside outbound drop root",
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
) from exc
if path.suffix.lower() != ".xlsx" or not path.is_file():
raise ValidationError(
"outbound callback file must be an existing xlsx",
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
)
max_size = max(int(current_app.config.get("FILE_ASSET_MAX_SIZE_MB", 30) or 30), 1) * 1024 * 1024
if path.stat().st_size > max_size:
raise ValidationError(
"outbound callback file exceeds configured size limit",
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
)
return path.read_bytes()
def ingest_outbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
"""幂等接收单个 outbound 单元回调,原样归档三年且不写库存快照表。
Args:
payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。
Returns:
dict: unit_run_id/status[/file_id/idempotent],供 HTTP envelope 的 data 使用。
(brief 曾写 -> None;与入站 API envelope 对齐仍返回 dict。)
Raises:
ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。
NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。
AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。
业务顺序:每个终态分支先 db.session.commit() 再构造
ReportFact(report_kind='outbound', source_code=unit.source_code, ...) 调
dispatch_report_fact;事实恒带 unit_run_id=unit.id;处理函数异常原样外抛;
同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实。
"""
if payload.get("schema_version") != OUTBOUND_TRIGGER_SCHEMA:
raise ValidationError(
"outbound callback schema_version is invalid",
code="SHIPPING.OUTBOUND_CALLBACK_INVALID",
)
callback_id = str(payload.get("callback_id") or "").strip()
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
raise NotFoundError("Outbound RPA unit not found", code="SHIPPING.OUTBOUND_UNIT_NOT_FOUND")
status = str(payload.get("status") or "").strip().lower()
before = {"status": unit.status, "error_code": unit.error_code, "error_message": unit.error_message}
if status in {"empty", "no_data"}:
# [STEP] 与入站 empty / 库存 no_inventory_data 对齐:empty 是合法业务结果。
unit.status = "empty"
unit.error_code = str(payload.get("error_code") or "no_outbound_data")[:64]
unit.error_message = str(payload.get("error_message") or "no_outbound_data")[:2000]
unit.finished_at = datetime.utcnow()
append_rpa_report_event(
event_type="shipping_outbound_rpa_callback_received",
aggregate_type="shipping_outbound_unit",
aggregate_id=str(unit.id),
run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type="rpa",
actor_id="outbound-worker",
unit_id=unit.id,
result="success",
before=before,
after={
"status": "empty",
"callback_id": unit.callback_id,
"error_code": unit.error_code,
"error_message": unit.error_message,
},
metadata={"callback_status": status, "skip_reason": unit.error_code},
)
db.session.commit()
dispatch_report_fact(ReportFact(
report_kind="outbound",
source_code=unit.source_code,
file_id=None,
sha256=None,
ok=False,
error_code=unit.error_code or "no_outbound_data",
error_message=unit.error_message or "no_outbound_data",
unit_run_id=unit.id,
))
return {"unit_run_id": unit.id, "status": "empty"}
if status != "success":
unit.status = "failed"
unit.error_code = str(payload.get("error_code") or "RPA.OUTBOUND_EXPORT_FAILED")[:64]
unit.error_message = str(payload.get("error_message") or "outbound export failed")[:2000]
unit.finished_at = datetime.utcnow()
append_rpa_report_event(
event_type="shipping_outbound_rpa_callback_received",
aggregate_type="shipping_outbound_unit",
aggregate_id=str(unit.id),
run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type="rpa",
actor_id="outbound-worker",
unit_id=unit.id,
result="failure",
before=before,
after={"status": "failed", "error_code": unit.error_code, "error_message": unit.error_message},
metadata={"callback_status": status},
)
db.session.commit()
dispatch_report_fact(ReportFact(
report_kind="outbound",
source_code=unit.source_code,
file_id=None,
sha256=None,
ok=False,
error_code=unit.error_code,
error_message=unit.error_message,
unit_run_id=unit.id,
))
return {"unit_run_id": unit.id, "status": "failed"}
data = _read_outbound_callback_file(str(payload.get("file_path") or ""))
sha256 = hashlib.sha256(data).hexdigest()
claimed = str(payload.get("sha256") or "").lower()
if claimed and claimed != sha256:
raise ValidationError(
"outbound callback sha256 mismatch",
code="SHIPPING.OUTBOUND_CALLBACK_SHA_MISMATCH",
)
existing = FreightRpaOutboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
if existing:
dispatch_report_fact(ReportFact(
report_kind="outbound",
source_code=unit.source_code,
file_id=existing.id,
sha256=sha256,
ok=True,
unit_run_id=unit.id,
))
return {"unit_run_id": unit.id, "status": unit.status, "file_id": existing.id, "idempotent": True}
filename = Path(str(payload.get("original_filename") or payload.get("file_path") or "outbound.xlsx")).name
storage_key = f"shipping/outbound-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx"
file_asset_storage.upload_bytes(
storage_key=storage_key,
data=data,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
record = FreightRpaOutboundReportFile(
unit_run_id=unit.id,
storage_provider="minio",
storage_bucket=file_asset_storage.bucket_name,
storage_key=storage_key,
original_filename=filename,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
file_size=len(data),
sha256=sha256,
archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3),
)
db.session.add(record)
unit.status = "success"
unit.finished_at = datetime.utcnow()
db.session.flush()
append_rpa_report_event(
event_type="shipping_outbound_report_archived",
aggregate_type="shipping_outbound_unit",
aggregate_id=str(unit.id),
run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type="rpa",
actor_id="outbound-worker",
unit_id=unit.id,
result="success",
before=before,
after={
"status": "success",
"source_run_no": unit.callback_id,
"file_id": record.id,
"sha256": sha256,
"file_size": len(data),
},
artifact_refs=[{"kind": "outbound_report", "id": str(record.id), "sha256": sha256}],
metadata={"file_size": len(data), "retention_days": 365 * 3},
)
db.session.commit()
dispatch_report_fact(ReportFact(
report_kind="outbound",
source_code=unit.source_code,
file_id=record.id,
sha256=sha256,
ok=True,
unit_run_id=unit.id,
))
return {"unit_run_id": unit.id, "status": "success", "file_id": record.id, "idempotent": False}
@@ -0,0 +1,92 @@
"""
services/freight_rpa/outbound/trigger_io.py
用途:outbound(出站)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON
原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 schedule.freight_rpa_outbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
in_transit_transfer.outbound_trigger_service(调拨按需/批量触发)、
freight_rpa.common.worker_heartbeat(outbound trigger 目录探测/就绪检查)、
freight_rpa.outbound.report_archive(drop 目录定位与回调 SCHEMA 校验,后续任务)等调用,
与外部 RPA Worker 的文件投递目录交互;schema/action 以本文件常量为单一真相
(Worker 侧对表:freight_rpa.outbound.v1 / outbound_export_batch)。
"""
from __future__ import annotations
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
SCHEMA = "freight_rpa.outbound.v1"
ACTION_OUTBOUND_EXPORT_BATCH = "outbound_export_batch"
def _path(key: str) -> Path | None:
value = str(current_app.config.get(key) or "").strip()
if not value:
return None
return Path(value)
def outbound_trigger_dir() -> Path | None:
"""RPA outbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR);
绝不回落到 onhand/inbound trigger 目录。"""
return _path("FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR")
def outbound_drop_dir() -> Path | None:
"""RPA outbound 导出文件落盘目录(FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR)。"""
return _path("FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR")
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
try:
with open(temp_path, 'w', encoding='utf-8') as handle:
json.dump(body, handle, ensure_ascii=False, indent=2)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_path, path)
finally:
if temp_path.exists():
temp_path.unlink(missing_ok=True)
def write_outbound_export_batch_trigger(
run_no: str,
units: list[dict[str, Any]],
meta: dict[str, Any] | None = None,
) -> str | None:
"""
写入 outbound 批量 trigger 文件 outbound_export_batch_{run_no}.json
(Worker 轮询 <root>/*.json 按内容消费,schema/action 取本文件常量)。
Args:
run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。
units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。
meta: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。
Returns:
str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。
"""
trigger_dir = outbound_trigger_dir()
if not trigger_dir or not units:
return None
trigger_dir.mkdir(parents=True, exist_ok=True)
safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'outbound'
body = {
'schema_version': SCHEMA, 'action': ACTION_OUTBOUND_EXPORT_BATCH,
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
**(meta or {}),
}
path = trigger_dir / f'outbound_export_batch_{safe_run_no}.json'
_write_trigger_json_atomic(path, body)
return str(path)
@@ -1,9 +1,16 @@
"""
backend/app/services/shipping_notice/onhand_parsing_profile.py
services/freight_rpa/parsing_profile.py
用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。
依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig(s18 起站点绑定归配置行)、FreightRpaInboundReportConfig、ShippingOrderField、onhand_mapping。
逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。
用途:管理货代「报表规则」(FreightRpaParsingProfile)的草稿/发布与运行期定义读取。
purpose=onhand 走库存字段目录 + match_keys;purpose=inbound/outbound 走调拨
MOVEMENT_FIELDS 契约(与在途异动对齐)。
依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig、FreightRpaInboundReportConfig、
FreightRpaOutboundReportConfig、ShippingOrderField、
in_transit_transfer.movement_contract.MOVEMENT_FIELDS、
shipping_notice.order_schema(仅 onhand 发布时校验订单字段)。
逻辑:管理员保存草稿并发布不可变版本;来源站点 / 入站·出站报表配置只绑定 published
Profile;退役前检查 onhand/inbound/outbound 配置引用。管理端入口
/api/admin/freight-rpa/.../parsing-profiles。
"""
from __future__ import annotations
@@ -24,6 +31,7 @@ from app.models import (
FreightRpaOnhandStructureAnalysis,
ShippingOrderField,
FreightRpaInboundReportConfig,
FreightRpaOutboundReportConfig,
)
@@ -59,7 +67,7 @@ def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set
# 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
"""校验 inbound 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
"""校验 inbound/outbound 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
movement_codes = {field.code for field in MOVEMENT_FIELDS}
@@ -85,8 +93,8 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]
Args:
raw: 解析定义对象。
purpose: 'onhand'/'outbound'(沿用库存字段目录与 match_keys)或
'inbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
purpose: 'onhand'(库存字段目录 + match_keys)或
'inbound'/'outbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
"""
if not isinstance(raw, dict):
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
@@ -99,7 +107,7 @@ def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if purpose == 'inbound':
if purpose in {'inbound', 'outbound'}:
_required_movement_field_ids(raw)
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
@@ -290,13 +298,13 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
)
from app.services.shipping_notice.order_schema import service as order_schema_service
# inbound 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand/outbound 维持原约束。
# inbound/outbound 无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand 维持原约束。
referenced_field_ids = {
str(item.get('order_field_id') or '')
for item in (profile.definition_json or {}).get('match_keys', [])
if isinstance(item, dict)
}
if profile.purpose != 'inbound':
if profile.purpose == 'onhand':
published_field_ids = {
str(item.get('field_id') or '')
for item in order_schema_service.get_published_contract().get('fields', [])
@@ -316,7 +324,7 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
def retire(profile_id: int) -> dict[str, Any]:
"""退役无库存源/收料报表配置引用的 published Profile,避免使现有绑定静默失效。"""
"""退役无库存源/入站/出站报表配置引用的 published Profile,避免使现有绑定静默失效。"""
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
@@ -324,10 +332,11 @@ def retire(profile_id: int) -> dict[str, Any]:
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID')
# s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。
bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
# 收料报表配置(FreightRpaInboundReportConfig)同样绑定解析 Profile:退役前必须一并核查,
# 否则入站文件解析链(inbound purpose)会静默失去规则。
bound_receipt_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
if bound_sources or bound_receipt_configs:
# 入站/出站报表配置同样绑定解析 Profile:退役前必须一并核查,
# 否则入站/出站文件解析链会静默失去规则。
bound_inbound_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
bound_outbound_configs = FreightRpaOutboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
if bound_sources or bound_inbound_configs or bound_outbound_configs:
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED')
profile.status = 'retired'
db.session.commit()
@@ -1,7 +1,7 @@
"""freight_rpa/reports/__init__.py
用途:报表读域(阶段 B Task 3)——发货(shipping_notice 域)与在途调拨
(in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包。
用途:报表读域——发货(shipping_notice 域)与在途调拨
(in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包(含出站配置视图)。
依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。
逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice)
一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。
@@ -15,12 +15,15 @@ from app.services.freight_rpa.reports.queries import (
InboundConfigView,
InboundFileView,
OnhandConfigView,
OutboundConfigView,
SiteView,
clear_inbound_parse_failure,
get_inbound_config,
get_onhand_config,
get_outbound_config,
get_site,
latest_usable_inbound_file,
list_outbound_configured_source_codes,
mark_inbound_parse_failure,
read_inbound_file_bytes,
usable_inbound_file_condition,
@@ -31,13 +34,16 @@ __all__ = [
'InboundConfigView',
'InboundFileView',
'OnhandConfigView',
'OutboundConfigView',
'ReportFact',
'SiteView',
'clear_inbound_parse_failure',
'get_inbound_config',
'get_onhand_config',
'get_outbound_config',
'get_site',
'latest_usable_inbound_file',
'list_outbound_configured_source_codes',
'mark_inbound_parse_failure',
'read_inbound_file_bytes',
'require_report_kind',
@@ -4,8 +4,9 @@
终态、再投递事实」的第二段分发(批次 B Task 6)。
依赖:app.core.errors.AppError、freight_rpa.reports.facts(ReportFact、
require_report_kind)。
逻辑:组合根(Task 7 的 shipping_notice.rpa_sinks.register_inbound_sinks /
register_onhand_sinks 等)在应用启动时调用 register_report_handler 注入各
逻辑:组合根(shipping_notice.rpa_sinks.register_onhand_sinks /
in_transit_transfer.rpa_sinks.register_inbound_sinks /
register_outbound_sinks)在应用启动时调用 register_report_handler 注入各
kind 的业务处理函数;归档入口(如 freight_rpa.inbound.report_archive.
ingest_inbound_callback)在每个终态 db.session.commit() 之后调用
dispatch_report_fact。kind 未注册时显式 404(FREIGHT_RPA.
@@ -33,8 +34,8 @@ def register_report_handler(report_kind: str, handler: Handler) -> None:
"""
注册一个报表事实处理函数(由组合根在应用启动时调用)。
【AI 触发时机】:组合根装配(Task 7 的 register_inbound_sinks /
register_onhand_sinks)时调用;测试直接调用注入临时处理函数。
【AI 触发时机】:组合根装配(register_onhand_sinks / register_inbound_sinks /
register_outbound_sinks)时调用;测试直接调用注入临时处理函数。
核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound /
outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。
Args:
@@ -42,7 +43,7 @@ def register_report_handler(report_kind: str, handler: Handler) -> None:
handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用,
不校验其内部行为。
Raises:
ValidationError: report_kind 不在白名单(code=SHIPPING.RECEIPT_CALLBACK_INVALID)。
ValidationError: report_kind 不在白名单(code=SHIPPING.INBOUND_CALLBACK_INVALID)。
"""
kind = require_report_kind(report_kind)
_REPORT_HANDLERS[kind] = handler
@@ -4,7 +4,7 @@
依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。
逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作;
report kind 只认 onhand / inbound / outbound,非法值抛
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),
ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),
与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。
本模块不 import shipping_notice / in_transit_transfer。
【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递
@@ -23,7 +23,7 @@ REPORT_KINDS = ('onhand', 'inbound', 'outbound')
# 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码,
# 避免为同一类入参错误分裂出多个近义 code。
_INVALID_KIND_ERROR_CODE = 'SHIPPING.RECEIPT_CALLBACK_INVALID'
_INVALID_KIND_ERROR_CODE = 'SHIPPING.INBOUND_CALLBACK_INVALID'
@dataclass(frozen=True)
@@ -53,7 +53,7 @@ def require_report_kind(value: str) -> str:
用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。
核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),fail-closed。
ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),fail-closed。
Args:
value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。
@@ -2,10 +2,11 @@
用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+
解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露
freight_rpa 报表事实(站点、登录连接、在手/入站报表配置、入站解析方案、
freight_rpa 报表事实(站点、登录连接、在手/入站/出站报表配置、入站解析方案、
入站归档文件),使消费方不再直接 import freight_rpa 模型表。
依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig /
FreightRpaInboundReportConfig / FreightRpaInboundReportFile;登录连接
FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig /
FreightRpaInboundReportFile;登录连接
(RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、
app.core.errors(NotFoundError)、
file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。
@@ -23,8 +24,8 @@
config_id/config_version;新增登录连接(get_rpa_login_profile)、入站解析
方案(get_inbound_parsing_profile)、失效文件存在性(has_expired_inbound_
file)、重建通道归档清单(list_reparseable_inbound_files)、入站可用站点
编码清单(list_inbound_configured_source_codes)——供 in_transit_transfer
收敛为「只按 source_code / file_id 读取」的只读函数消费面。
编码清单(list_inbound_configured_source_codes / list_outbound_configured_source_codes)
——供 in_transit_transfer 收敛为「只按 source_code / file_id 读取」的只读函数消费面。
mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。
"""
@@ -42,6 +43,7 @@ from app.models import (
FreightRpaInboundReportConfig,
FreightRpaInboundReportFile,
FreightRpaOnhandReportConfig,
FreightRpaOutboundReportConfig,
FreightRpaSource,
)
from app.services.file_assets.storage import file_asset_storage
@@ -200,6 +202,21 @@ class InboundConfigView:
config_version: int = 1
@dataclass(frozen=True)
class OutboundConfigView:
"""出站报表配置只读视图(freight_rpa_outbound_report_configs 行),与入站同构。
config_id / config_version 供调拨出站触发落可审计单元行快照使用,
不再引用配置模型。
"""
report_path_json: dict
query_parameters_json: list
parsing_profile_id: int | None
config_id: int = 0
config_version: int = 1
@dataclass(frozen=True)
class InboundProfileView:
"""入站解析方案只读视图(freight_rpa_parsing_profiles 行)。
@@ -321,6 +338,36 @@ def get_inbound_config(source_code: str) -> InboundConfigView | None:
)
def get_outbound_config(source_code: str) -> OutboundConfigView | None:
"""按 source_code 返回出站报表配置只读视图(与入站配置同构)。
用途:调拨出站触发读路径取出站报表定义;出站不设独立启停,是否运行由站点
enabled 与本配置行是否存在决定。
核心逻辑:join 站点表按 source_code 查 freight_rpa_outbound_report_configs 行,
命中即映射视图;缺失返回 None。
Args:
source_code: 站点实例编码。
Returns:
OutboundConfigView;站点或配置不存在返回 None。
"""
config = (
FreightRpaOutboundReportConfig.query
.join(FreightRpaSource, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id)
.filter(FreightRpaSource.source_code == source_code)
.first()
)
if config is None:
return None
return OutboundConfigView(
report_path_json=dict(config.report_path_json or {}),
query_parameters_json=list(config.query_parameters_json or []),
parsing_profile_id=config.parsing_profile_id,
config_id=config.id,
config_version=int(config.config_version or 1),
)
def get_rpa_login_profile(source_code: str) -> RpaLoginProfileView | None:
"""按 source_code 返回站点绑定的 RPA 登录连接只读视图。
@@ -478,6 +525,24 @@ def list_inbound_configured_source_codes() -> list[str]:
return [str(code) for (code,) in rows]
def list_outbound_configured_source_codes() -> list[str]:
"""列出已配置出站报表的启用站点编码(调拨排程缺省执行范围)。
用途:在途自动调拨排程 source_codes 留空时的缺省范围
(outbound_trigger_service.list_outbound_capable_source_codes 委托本函数)
——出站文件只能来自已配置出站报表的启用站点。
核心逻辑:站点 join 出站配置行、仅启用站点、按 source_code 排序;只读查询。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
rows = db.session.query(FreightRpaSource.source_code).join(
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all()
return [str(code) for (code,) in rows]
def latest_usable_inbound_file(
source_code: str,
*,
@@ -8,7 +8,7 @@
避免回调迟到误推进其他阶段任务。生产调用方为调拨侧报表事实处理函数
handle_inbound_report(Task 7,inbound_report_handler.py——归档终态 commit 后
经 dispatch_report_fact 调入;返回 None 时调用方跳过提交分支);回归测试桥
(inbound_report_storage._advance_transfer_source_job)仍走本函数。
(handle_inbound_report / 历史测试桥)仍走本函数。
SourceJob 状态为字符串常量(见 models)。
"""
@@ -9,7 +9,7 @@ services/in_transit_transfer/inbound_report_handler.py
app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact /
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、
in_transit_transfer.inbound_callback_bridge / evidence_sync(同包)。
逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_inbound_sinks)
逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_inbound_sinks)
注册为 'inbound' kind 处理函数;freight_rpa.inbound.report_archive.
ingest_inbound_callback 在每个终态 db.session.commit() 之后经
dispatch_report_fact 调入本函数。处理函数只改调拨自己的行;
@@ -65,7 +65,7 @@ def handle_inbound_report(fact: ReportFact) -> None:
if kind != 'inbound':
raise ValidationError(
f"handle_inbound_report only accepts inbound facts, got: {kind!r}",
code='SHIPPING.RECEIPT_CALLBACK_INVALID',
code='SHIPPING.INBOUND_CALLBACK_INVALID',
details={'report_kind': fact.report_kind},
)
@@ -126,9 +126,9 @@ def handle_inbound_report(fact: ReportFact) -> None:
schedule_run_id = unit.schedule_run_id
if schedule_run_id:
from app.services.schedule.freight_rpa_inbound_finalize import (
finalize_receipt_schedule_run_if_complete,
refresh_receipt_schedule_run_progress,
finalize_inbound_schedule_run_if_complete,
refresh_inbound_schedule_run_progress,
)
refresh_receipt_schedule_run_progress(schedule_run_id)
finalize_receipt_schedule_run_if_complete(schedule_run_id)
refresh_inbound_schedule_run_progress(schedule_run_id)
finalize_inbound_schedule_run_if_complete(schedule_run_id)
@@ -0,0 +1,144 @@
"""
services/in_transit_transfer/outbound_report_handler.py
用途:outbound 报表事实的调拨侧业务处理函数——出站归档终态 commit 后由
dispatch_report_fact 投递的 ReportFact 只在此推进调拨自己的任务:
TransferSourceJob 等待态推进、出站排程收口。
依赖:app.db、app.models(FreightRpaOutboundUnitRun——执行单元读取)、
app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact /
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)。
逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_outbound_sinks)
注册为 'outbound' kind 处理函数;freight_rpa.outbound.report_archive.
ingest_outbound_callback 在每个终态 db.session.commit() 之后经
dispatch_report_fact 调入本函数。处理函数只改调拨自己的行;
【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚,
Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。
状态机字段与入站同一套:waiting_rpa_callback → file_ready / failed;
无等待任务则 no-op;第二次调用该行已离开等待态,不再改(可重入)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.core.errors import ValidationError
from app.models import FreightRpaOutboundUnitRun, TransferSourceJob
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
_FILE_READY = 'file_ready'
_WAITING_RPA_CALLBACK = 'waiting_rpa_callback'
_FAILED = 'failed'
def _advance_waiting_source_job(
*, source_code: str, file_no: str | None = None, file_sha256: str | None = None,
callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None,
) -> TransferSourceJob | None:
"""按来源推进最新等待回调的调拨来源任务(与入站桥同一等待态字段)。
核心逻辑:只改 status='waiting_rpa_callback' 的行;无匹配则不动作,
避免回调迟到误推进其他阶段任务。success/有文件 → file_ready;否则 → failed。
本函数只 flush 不 commit,提交归属 handle_outbound_report。
Args:
source_code: 回调所属来源实例。
file_no: 出站文件号(success 时)。
file_sha256: 出站文件 sha256(success 时)。
callback_ok / error_code / error_message: 回调终态。
Returns:
被推进的任务;无等待任务或已终态时返回 None。
"""
job = (
TransferSourceJob.query
.filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK)
.order_by(TransferSourceJob.id.desc())
.first()
)
if job is None:
return None
if callback_ok and file_no:
job.status = _FILE_READY
job.file_no = file_no
job.file_sha256 = file_sha256
job.error_code = None
job.error_message = None
job.finished_at = datetime.utcnow()
else:
job.status = _FAILED
job.error_code = error_code or 'RPA_OUTBOUND_CALLBACK_FAILED'
job.error_message = error_message or 'outbound rpa callback failed'
job.finished_at = datetime.utcnow()
db.session.flush()
return job
def handle_outbound_report(fact: ReportFact) -> None:
"""report_kind 必须是 outbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready;
ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。
核心逻辑:
[STEP 1] kind 门禁(fail-closed);[STEP 2] 推进等待中的来源任务(只改
status='waiting_rpa_callback' 的行,无等待行返回 None);[STEP 3]
推进结果必须在此提交;[STEP 4] 精确定位本次回调收尾的执行单元并回写出站
排程进度、归集终态。不调用入站 evidence_sync(record_kind=inbound 专用)。
【不捕获异常】任何一步失败原样外抛供 Worker 重试。
Args:
fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/
file_id/sha256/ok/error_code/error_message/unit_run_id)。
Returns:
None(推进/收口结果全部写库,不返回业务值)。
Raises:
ValidationError: report_kind 非 outbound(误注册/误分发,fail-closed)。
"""
# [STEP 1] kind 门禁:本函数只消费 outbound 事实。
kind = require_report_kind(fact.report_kind)
if kind != 'outbound':
raise ValidationError(
f"handle_outbound_report only accepts outbound facts, got: {kind!r}",
code='SHIPPING.OUTBOUND_CALLBACK_INVALID',
details={'report_kind': fact.report_kind},
)
# [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready;
# 否则 → failed。无等待行返回 None(调拨侧无行可改,直接结束推进分支)。
if fact.ok and fact.file_id is not None:
advanced = _advance_waiting_source_job(
source_code=fact.source_code,
file_no=str(fact.file_id),
file_sha256=fact.sha256,
callback_ok=True,
)
else:
advanced = _advance_waiting_source_job(
source_code=fact.source_code,
callback_ok=False,
error_code=fact.error_code,
error_message=fact.error_message,
)
# [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交。
if advanced is not None:
db.session.commit()
# [STEP 4] 出站排程收口:按 fact.unit_run_id 精确定位本次回调收尾的执行单元。
schedule_run_id: int | None = None
if fact.unit_run_id is not None:
unit = db.session.get(FreightRpaOutboundUnitRun, int(fact.unit_run_id))
if unit is None:
from app.core.errors import NotFoundError
raise NotFoundError(
f"Outbound RPA unit not found: {fact.unit_run_id}",
details={'unit_run_id': fact.unit_run_id},
)
schedule_run_id = unit.schedule_run_id
if schedule_run_id:
from app.services.schedule.freight_rpa_outbound_finalize import (
finalize_outbound_schedule_run_if_complete,
refresh_outbound_schedule_run_progress,
)
refresh_outbound_schedule_run_progress(schedule_run_id)
finalize_outbound_schedule_run_if_complete(schedule_run_id)
@@ -0,0 +1,261 @@
"""在途调拨出站 RPA 触发服务。
用途:为单个或多个来源触发出站 RPA 抓取(出站证据 = freight_rpa 出站 RPA 产物,
复用货代出站 trigger 链路),不创建排程。按来源取站点、出站配置与登录连接
(全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行
(awaiting_rpa,回调按 callback_id 查库可达),再装配出站 trigger unit 并
调用 write_outbound_export_batch_trigger 原子写 trigger。
依赖:write_outbound_export_batch_trigger(默认 writer,freight_rpa.outbound.trigger_io)、
freight_rpa.reports.queries(get_site / get_outbound_config / get_rpa_login_profile /
list_outbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。
逻辑:list_outbound_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/出站配置缺失/登录连接缺失时
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
trigger_outbound_rpa_batch 把多来源合并为一个 batch trigger 文件:
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
trigger unit 载荷键集与 Worker 契约(freight_rpa.outbound.v1)逐键对齐入站。
"""
from __future__ import annotations
import uuid
from typing import Any, Callable
from app.services.freight_rpa.outbound.trigger_io import (
ACTION_OUTBOUND_EXPORT_BATCH,
SCHEMA,
write_outbound_export_batch_trigger,
)
from app.services.freight_rpa.reports.queries import (
get_outbound_config,
get_rpa_login_profile,
get_site,
list_outbound_configured_source_codes,
)
RouteTriggerWriter = Callable[..., str | None]
def _write_outbound_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
"""适配出站 IO 的 meta 形参,对外保持与入站 writer 相同的 payload= 协议。"""
return write_outbound_export_batch_trigger(run_no, units, meta=payload)
def _build_trigger_unit(
*, source_code: str, business_date: str, reason: str,
) -> dict[str, Any]:
"""装配单来源出站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
站点(get_site)/ 出站配置(get_outbound_config)/ 登录连接
(get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的
unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。
"""
site = get_site(source_code)
if site is None or not site.enabled:
raise RuntimeError(f'source not enabled: {source_code}')
config = get_outbound_config(source_code)
if config is None:
raise RuntimeError(f'outbound config missing: {source_code}')
profile = get_rpa_login_profile(source_code)
if profile is None or not profile.enabled:
raise RuntimeError(f'outbound source profile unavailable: {source_code}')
query_parameters = [
dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict)
]
snapshot = {
'config_id': config.config_id, 'config_version': config.config_version,
'connector_type': site.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': query_parameters,
'warehouse_id': None, 'rpa_profile_id': profile.profile_id,
}
return {
'source_id': site.source_id,
'callback_id': f'outbound:{uuid.uuid4().hex}',
'source_code': site.source_code,
'connector_type': site.connector_type,
'warehouse_id': None,
'rpa_profile_id': profile.profile_id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(query_parameters),
'config_snapshot': snapshot,
'business_date': business_date,
'reason': reason,
}
def list_outbound_capable_source_codes() -> list[str]:
"""列出可产出出站文件的启用来源实例(已配置出站报表的启用站点)。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——出站文件
只能来自已配置出站报表的站点,与货代出站 RPA 排程的站点口径一致。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
return list_outbound_configured_source_codes()
def trigger_outbound_rpa(
*,
source_code: str,
business_date: str,
reason: str = 'transfer_retry_outbound',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源出站 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
Args:
source_code: 来源实例编码。
business_date: 业务日期。
reason: 触发原因(写入 trigger)。
writer: 触发写者;缺省复用 write_outbound_export_batch_trigger(payload= 协议)。
Returns:
{"ok": True, "callback_id": ..., "trigger_path": ...} 或
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
"""
try:
unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
except RuntimeError as exc:
return {"ok": False, "error_code": "RPA_OUTBOUND_CONFIG_MISSING", "error_message": str(exc)}
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
# 不落行则回调必然 404(与排程路径 / 入站按需触发同一模式)。
from app import db
from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun
unit = FreightRpaOutboundUnitRun(
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
source_id=unit_payload['source_id'],
source_code=unit_payload['source_code'],
connector_type=unit_payload['connector_type'],
warehouse_id=unit_payload.get('warehouse_id'),
callback_id=unit_payload['callback_id'],
status='awaiting_rpa',
config_snapshot_json=dict(unit_payload['config_snapshot']),
)
db.session.add(unit)
db.session.flush()
unit_payload['unit_run_id'] = unit.id
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or _write_outbound_trigger
path = writer_fn(run_no, [unit_payload], payload={
'schema_version': SCHEMA,
'action': ACTION_OUTBOUND_EXPORT_BATCH,
'source_code': source_code,
'business_date': business_date,
'reason': reason,
})
if not path:
unit.status = 'failed'
unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
unit.error_message = 'outbound trigger directory unavailable'
db.session.commit()
return {"ok": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE"}
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
unit.trigger_snapshot_json = unit_payload
db.session.commit()
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
def trigger_outbound_rpa_batch(
*,
source_codes: list[str],
business_date: str,
reason: str = 'transfer_retry_outbound',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""批量触发多来源出站 RPA:全部有效来源合并写**一个** batch trigger 文件。
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个出站来源编码时调用;
行级单来源重试仍走 trigger_outbound_rpa(一源一文件语义不变)。
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批);
有效 units 先各落一行 RPA 单元运行行再一次性 write_outbound_export_batch_trigger
原子落盘。Worker 对单文件按 profile 分组共享一次浏览器会话串行导出。
入站 batch 的 parse_failed 本地重解析不在此复用——来源文件状态投影仅覆盖入站归档。
Args:
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
business_date: 业务日期。
reason: 触发原因(写入 trigger payload)。
writer: 触发写者;缺省复用 write_outbound_export_batch_trigger。
Returns:
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
ok=本次请求产生了主效果(写盘成功);triggered=是否写了 batch trigger;
results 逐来源携带真实结果。
"""
from app import db
from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
results: list[dict[str, Any]] = []
units: list[FreightRpaOutboundUnitRun] = []
unit_payloads: list[dict[str, Any]] = []
# [STEP 1] 逐来源装配 unit;单源失败跳过不阻断整批。
for code in codes:
try:
unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason))
except RuntimeError as exc:
results.append({
'source_code': code, 'ok': False,
'error_code': 'RPA_OUTBOUND_CONFIG_MISSING', 'error_message': str(exc),
})
if not unit_payloads:
db.session.commit()
return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE", "results": results}
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
for payload in unit_payloads:
unit = FreightRpaOutboundUnitRun(
source_id=payload['source_id'],
source_code=payload['source_code'],
connector_type=payload['connector_type'],
warehouse_id=payload.get('warehouse_id'),
callback_id=payload['callback_id'],
status='awaiting_rpa',
config_snapshot_json=dict(payload['config_snapshot']),
)
db.session.add(unit)
units.append(unit)
db.session.flush()
for unit, payload in zip(units, unit_payloads):
payload['unit_run_id'] = unit.id
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or _write_outbound_trigger
path = writer_fn(run_no, unit_payloads, payload={
'schema_version': SCHEMA,
'action': ACTION_OUTBOUND_EXPORT_BATCH,
'business_date': business_date,
'reason': reason,
'source_codes': [payload['source_code'] for payload in unit_payloads],
})
if not path:
for unit in units:
unit.status = 'failed'
unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
unit.error_message = 'outbound trigger directory unavailable'
db.session.commit()
return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE", "results": results}
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
for unit, payload in zip(units, unit_payloads):
unit.trigger_snapshot_json = payload
results.append({'source_code': unit.source_code, 'ok': True})
db.session.commit()
return {"ok": True, "triggered": True, "trigger_path": path, "results": results}
@@ -0,0 +1,63 @@
"""
services/in_transit_transfer/rpa_sinks.py
用途:入站 / 出站 RPA 回调与报表事实的组合根注册——把 /api/freight-rpa/inbound-*、
outbound-* 接到 freight_rpa 归档入口与本包事实处理函数(调拨是唯一业务消费方)。
依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、
freight_rpa.inbound/outbound.report_archive、schedule.freight_rpa_*_finalize、
inbound_report_handler / outbound_report_handler。
逻辑:由 app.create_app 调用 register_inbound_sinks / register_outbound_sinks(幂等)。
进度类 sink 复刻 {'success':True,'data':...} envelope;文件事实经
register_report_handler 注册。不 import shipping_notice。
"""
from __future__ import annotations
from typing import Any, Callable
def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
"""旧 inbound/outbound 进度端点 envelope:{'success':True,'data':业务结果}。"""
def _sink(**payload: Any) -> dict[str, Any]:
return {'success': True, 'data': handler(payload)}
return _sink
def register_inbound_sinks() -> None:
"""注册全部 inbound 进度 sink 与 inbound 事实处理函数(幂等)。
核心逻辑:inbound-batch-ready 直挂 freight_rpa.inbound.report_archive.ingest_inbound_callback
(与 outbound 对称,无 shipping_notice 薄壳);unit/batch-progress 挂
schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report。
"""
from app.services.freight_rpa.common.callback_sinks import register_sink
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
from app.services.schedule import freight_rpa_inbound_finalize
register_sink('inbound-batch-ready', _success_data_envelope(ingest_inbound_callback))
register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_inbound_unit_processing))
register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_inbound_batch_progress))
register_report_handler('inbound', handle_inbound_report)
def register_outbound_sinks() -> None:
"""注册全部 outbound 进度 sink 与 outbound 事实处理函数(幂等)。
核心逻辑:outbound-batch-ready 直挂 freight_rpa.outbound.report_archive.ingest_outbound_callback;
unit/batch-progress 挂 schedule.freight_rpa_outbound_finalize;事实处理函数挂
handle_outbound_report。
"""
from app.services.freight_rpa.common.callback_sinks import register_sink
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
from app.services.schedule import freight_rpa_outbound_finalize
register_sink('outbound-batch-ready', _success_data_envelope(ingest_outbound_callback))
register_sink('outbound-unit-progress', _success_data_envelope(freight_rpa_outbound_finalize.mark_outbound_unit_processing))
register_sink('outbound-batch-progress', _success_data_envelope(freight_rpa_outbound_finalize.report_outbound_batch_progress))
register_report_handler('outbound', handle_outbound_report)
+4 -2
View File
@@ -344,10 +344,12 @@ def _register_headers_from_config() -> None:
if cfg.alias_order and cfg.header_labels:
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
from app.services.schedule.freight_rpa_onhand_finalize import register_inventory_rpa_excel_headers
from app.services.schedule.freight_rpa_inbound_finalize import register_receipt_rpa_excel_headers
from app.services.schedule.freight_rpa_inbound_finalize import register_inbound_rpa_excel_headers
from app.services.schedule.freight_rpa_outbound_finalize import register_outbound_rpa_excel_headers
register_inventory_rpa_excel_headers()
register_receipt_rpa_excel_headers()
register_inbound_rpa_excel_headers()
register_outbound_rpa_excel_headers()
def reload_config() -> dict[str, Any]:
@@ -1,11 +1,11 @@
"""
backend/app/services/schedule/freight_rpa_inbound_archive.py
用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
用途:货代入站 RPA 排程 run 的原始入站 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、FreightRpaInboundReportFile / FreightRpaInboundUnitRun、
file_asset_storage、timezone_util、freight_rpa_inbound_finalize.is_freight_receipt_rpa_task。
逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`;
file_asset_storage、timezone_util、freight_rpa_inbound_finalize.is_freight_inbound_rpa_task。
逻辑:finalize 调用 persist_inbound_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「入站RPA-日期-时刻-入站」;包内条目 `{序号}_{source_code}.xlsx`;
warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。
"""
@@ -23,23 +23,23 @@ from flask import current_app
from app.core.errors import NotFoundError
from app.models import ScheduleRun, FreightRpaInboundReportFile, FreightRpaInboundUnitRun
from app.services.file_assets.storage import file_asset_storage
from app.services.schedule.freight_rpa_inbound_finalize import is_freight_receipt_rpa_task
from app.services.schedule.freight_rpa_inbound_finalize import is_freight_inbound_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员'
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始入站包不存在,请重新执行或联系管理员'
_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
'raw_receipt_zip_available': False,
'raw_receipt_zip_path': None,
'raw_receipt_file_count': 0,
'raw_receipt_file_ids': [],
'raw_receipt_zip_size': 0,
'raw_inbound_zip_available': False,
'raw_inbound_zip_path': None,
'raw_inbound_file_count': 0,
'raw_inbound_file_ids': [],
'raw_inbound_zip_size': 0,
}
def get_receipt_archive_dir() -> str:
def get_inbound_archive_dir() -> str:
"""
返回收料 RPA 原始 ZIP 归档根目录(自动创建)。
返回入站 RPA 原始 ZIP 归档根目录(自动创建)。
核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径,
避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。
@@ -87,9 +87,9 @@ def _attachment_when_from_run(run: ScheduleRun) -> datetime:
return when_utc.astimezone(tz)
def receipt_rpa_attachment_stem(run: ScheduleRun) -> str:
def inbound_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
收料 RPA 企微附件共用前缀:收料RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
入站 RPA 企微附件共用前缀:入站RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
Args:
run: 排程执行记录。
@@ -98,29 +98,29 @@ def receipt_rpa_attachment_stem(run: ScheduleRun) -> str:
不含角色后缀与扩展名的展示名前缀。
"""
when = _attachment_when_from_run(run)
return f"收料RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
return f"入站RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
def receipt_raw_zip_download_name(run: ScheduleRun) -> str:
def inbound_raw_zip_download_name(run: ScheduleRun) -> str:
"""
收料 ZIP 的企微/浏览器下载展示名。
入站 ZIP 的企微/浏览器下载展示名。
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f'{receipt_rpa_attachment_stem(run)}-收料.zip'
return f'{inbound_rpa_attachment_stem(run)}-入站.zip'
def receipt_rpa_result_excel_name(run: ScheduleRun) -> str:
"""收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 onhand_rpa_result_excel_name)。"""
return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx'
def inbound_rpa_result_excel_name(run: ScheduleRun) -> str:
"""入站 RPA 结果 Excel 的企微/下载展示名(对齐库存 onhand_rpa_result_excel_name)。"""
return f'{inbound_rpa_attachment_stem(run)}-结果.xlsx'
def _receipt_raw_zip_archive_path(run_no: str) -> Path:
def _inbound_raw_zip_archive_path(run_no: str) -> Path:
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
return Path(get_receipt_archive_dir()) / f'{run_no}.zip'
return Path(get_inbound_archive_dir()) / f'{run_no}.zip'
def _iter_packable_receipt_files(run: ScheduleRun):
def _iter_packable_inbound_files(run: ScheduleRun):
"""
遍历该 run 下可打包的收料归档文件。
@@ -129,7 +129,7 @@ def _iter_packable_receipt_files(run: ScheduleRun):
Yields:
FreightRpaInboundReportFile: 可从 MinIO 读取的归档记录。
"""
if not is_freight_receipt_rpa_task(getattr(run, 'task', None)):
if not is_freight_inbound_rpa_task(getattr(run, 'task', None)):
return
rows = (
FreightRpaInboundReportFile.query.join(
@@ -147,35 +147,35 @@ def _iter_packable_receipt_files(run: ScheduleRun):
yield report_file
def receipt_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
def inbound_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
"""
从 response_summary_json 读取原始收料 ZIP 是否可下载。
从 response_summary_json 读取原始入站 ZIP 是否可下载。
核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。
"""
if not isinstance(summary, dict):
return False
return bool(summary.get('raw_receipt_zip_available'))
return bool(summary.get('raw_inbound_zip_available'))
def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
def persist_inbound_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
"""
finalize 阶段预生成原始收料 ZIP 归档并返回 summary 字段。
finalize 阶段预生成原始入站 ZIP 归档并返回 summary 字段。
核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 <archive_dir>/<run_no>.zip
(含 manifest.json);无可用文件时返回 raw_receipt_zip_available=false。
(含 manifest.json);无可用文件时返回 raw_inbound_zip_available=false。
Args:
run: 收料 RPA ScheduleRun。
run: 入站 RPA ScheduleRun。
Returns:
dict: raw_receipt_zip_available / path / file_count / file_ids / zip_size。
dict: raw_inbound_zip_available / path / file_count / file_ids / zip_size。
"""
packable_files = list(_iter_packable_receipt_files(run))
packable_files = list(_iter_packable_inbound_files(run))
if not packable_files:
return dict(_EMPTY_ARCHIVE_SUMMARY)
archive_path = _receipt_raw_zip_archive_path(run.run_no)
archive_path = _inbound_raw_zip_archive_path(run.run_no)
files_manifest: list[dict[str, Any]] = []
with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
@@ -217,15 +217,15 @@ def persist_receipt_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
)
return {
'raw_receipt_zip_available': True,
'raw_receipt_zip_path': str(archive_path.resolve()),
'raw_receipt_file_count': len(files_manifest),
'raw_receipt_file_ids': [item['file_id'] for item in files_manifest],
'raw_receipt_zip_size': int(archive_path.stat().st_size),
'raw_inbound_zip_available': True,
'raw_inbound_zip_path': str(archive_path.resolve()),
'raw_inbound_file_count': len(files_manifest),
'raw_inbound_file_ids': [item['file_id'] for item in files_manifest],
'raw_inbound_zip_size': int(archive_path.stat().st_size),
}
def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
def _is_allowed_inbound_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
@@ -237,7 +237,7 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
if not resolved.is_file():
return False
archive_dir = Path(get_receipt_archive_dir()).resolve()
archive_dir = Path(get_inbound_archive_dir()).resolve()
try:
resolved.relative_to(archive_dir)
except ValueError:
@@ -245,11 +245,11 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
return True
def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
def resolve_inbound_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
"""
解析 run 已归档的原始收料 ZIP 路径供下载接口 send_file。
解析 run 已归档的原始入站 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_receipt_zip_path,校验文件存在、后缀为 .zip、
核心逻辑:读取 summary.raw_inbound_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
@@ -259,18 +259,18 @@ def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not receipt_raw_zip_available_from_summary(summary):
if not inbound_raw_zip_available_from_summary(summary):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path_raw = str(summary.get('raw_receipt_zip_path') or '').strip()
zip_path_raw = str(summary.get('raw_inbound_zip_path') or '').strip()
if not zip_path_raw:
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path = Path(zip_path_raw)
if not _is_allowed_receipt_archive_path(zip_path):
if not _is_allowed_inbound_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), receipt_raw_zip_download_name(run)
return zip_path.resolve(), inbound_raw_zip_download_name(run)
def _sanitize_zip_segment(value: str) -> str:
@@ -1,7 +1,7 @@
"""
backend/app/services/schedule/freight_rpa_inbound_finalize.py
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
用途:独立入站 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。
依赖:FreightRpaInboundUnitRun、freight_rpa_inbound_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom;
@@ -21,7 +21,7 @@ from app.models import ScheduleRun, ScheduleTask
from app.models import FreightRpaInboundUnitRun
from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.freight_rpa_inbound_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY
from app.services.schedule.freight_rpa_inbound_job import AWAITING_INBOUND_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA
from app.services.shipping_notice.audit_service import append_shipping_audit_event
@@ -29,25 +29,25 @@ _RECEIPT_RPA_HEADER_ORDER = [
"source_code",
"warehouse_id",
"connector_type",
"receipt_file_count",
"inbound_file_count",
"export_status",
"skip_reason",
"error_message",
]
_RECEIPT_RPA_HEADER_LABELS = {
"source_code": "收料源",
"source_code": "入站源",
"warehouse_id": "仓库",
"connector_type": "连接器",
"receipt_file_count": "归档文件数",
"inbound_file_count": "归档文件数",
"export_status": "导出状态",
"skip_reason": "跳过原因",
"error_message": "错误原因",
}
def register_receipt_rpa_excel_headers() -> None:
def register_inbound_rpa_excel_headers() -> None:
"""
注册货代收料 RPA 排程 Excel 列头(幂等)。
注册货代入站 RPA 排程 Excel 列头(幂等)。
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
@@ -57,15 +57,15 @@ def register_receipt_rpa_excel_headers() -> None:
)
def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> list[dict[str, Any]]:
def _build_inbound_finalize_details(units: list[FreightRpaInboundUnitRun]) -> list[dict[str, Any]]:
"""
收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。
入站单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。
核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片 计数口径一致;
归档文件数便于与原始收料包内 {序号}_{source_code}.xlsx 条目对账。
归档文件数便于与原始入站包内 {序号}_{source_code}.xlsx 条目对账。
Args:
units: 该 run 的全部收料单元(已全部终态)。
units: 该 run 的全部入站单元(已全部终态)。
Returns:
list[dict]: 按 unit.id 升序的明细行。
@@ -83,7 +83,7 @@ def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> li
'source_code': unit.source_code,
'warehouse_id': unit.warehouse_id or '',
'connector_type': unit.connector_type or '',
'receipt_file_count': len(unit.files or []),
'inbound_file_count': len(unit.files or []),
'export_status': export_status,
'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '',
'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '',
@@ -91,25 +91,25 @@ def _build_receipt_finalize_details(units: list[FreightRpaInboundUnitRun]) -> li
return rows
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
def should_defer_inbound_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
"""仅当独立入站 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
return bool(
task.schedule_type == 'platform_job'
and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY
and any(isinstance(row, dict) and row.get('status') == AWAITING_RECEIPT_RPA_CALLBACK_STATUS for row in step_logs or [])
and any(isinstance(row, dict) and row.get('status') == AWAITING_INBOUND_RPA_CALLBACK_STATUS for row in step_logs or [])
)
def is_awaiting_receipt_rpa_schedule_run(run: ScheduleRun | None) -> bool:
"""判断 run 是否为独立收料 callback 等待态,供 worker 启动恢复时保护。"""
def is_awaiting_inbound_rpa_schedule_run(run: ScheduleRun | None) -> bool:
"""判断 run 是否为独立入站 callback 等待态,供 worker 启动恢复时保护。"""
summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {}
return bool(run is not None and run.status == 'running' and summary.get('awaiting_receipt_rpa'))
return bool(run is not None and run.status == 'running' and summary.get('awaiting_inbound_rpa'))
def apply_deferred_receipt_schedule_run_state(
def apply_deferred_inbound_schedule_run_state(
run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict],
) -> ScheduleRun:
"""将收料 run 保持为 awaiting callback,终态由所有收料单元回调完成后专用服务写入。"""
"""将收料 run 保持为 awaiting callback,终态由所有入站单元回调完成后专用服务写入。"""
run.status = 'running'
run.started_at = run.started_at or datetime.utcnow()
run.total_count = total_count
@@ -118,18 +118,18 @@ def apply_deferred_receipt_schedule_run_state(
run.skipped_count = 0
run.finished_at = None
run.step_logs = step_logs
run.response_summary_json = {'awaiting_receipt_rpa': True, 'pending_details': details, 'errors': errors[:20]}
run.response_summary_json = {'awaiting_inbound_rpa': True, 'pending_details': details, 'errors': errors[:20]}
db.session.commit()
return run
def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict:
def refresh_inbound_schedule_run_progress(schedule_run_id: int) -> dict:
"""
收料单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。
入站单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。
核心逻辑:仅在 awaiting_receipt_rpa 时,按已终态单元聚合 success/empty/failed 写入
核心逻辑:仅在 awaiting_inbound_rpa 时,按已终态单元聚合 success/empty/failed 写入
ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at,
终态仍由 finalize_receipt_schedule_run_if_complete 负责。
终态仍由 finalize_inbound_schedule_run_if_complete 负责。
Args:
schedule_run_id: 排程执行记录主键。
@@ -141,8 +141,8 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict:
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_receipt_rpa'):
return {'updated': False, 'reason': 'not_awaiting_receipt_callback'}
if run.status != 'running' or not summary.get('awaiting_inbound_rpa'):
return {'updated': False, 'reason': 'not_awaiting_inbound_callback'}
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
success_count = sum(unit.status == 'success' for unit in units)
@@ -173,11 +173,11 @@ def refresh_receipt_schedule_run_progress(schedule_run_id: int) -> dict:
}
def report_receipt_batch_progress(payload: dict) -> dict:
def report_inbound_batch_progress(payload: dict) -> dict:
"""
Worker 每完成一笔收料导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。
Worker 每完成一笔入站导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。
核心逻辑:校验 schema + schedule_run_id;仅 awaiting_receipt_rpa 时抬升
核心逻辑:校验 schema + schedule_run_id;仅 awaiting_inbound_rpa 时抬升
ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。
Args:
@@ -199,8 +199,8 @@ def report_receipt_batch_progress(payload: dict) -> dict:
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_receipt_rpa'):
return {'updated': False, 'reason': 'not_awaiting_receipt_callback'}
if run.status != 'running' or not summary.get('awaiting_inbound_rpa'):
return {'updated': False, 'reason': 'not_awaiting_inbound_callback'}
incoming = {
'success_count': max(0, int(payload.get('success_count') or 0)),
@@ -228,9 +228,9 @@ def report_receipt_batch_progress(payload: dict) -> dict:
}
def mark_receipt_unit_processing(payload: dict) -> dict:
def mark_inbound_unit_processing(payload: dict) -> dict:
"""
Worker 开始导出某收料单元时标记 processing(对齐库存 claimed / rpa_exporting)。
Worker 开始导出某入站单元时标记 processing(对齐库存 claimed / rpa_exporting)。
核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。
"""
@@ -247,27 +247,27 @@ def mark_receipt_unit_processing(payload: dict) -> dict:
if unit.status == 'processing':
return {'updated': True, 'status': 'processing', 'idempotent': True}
unit.status = 'processing'
# started_at 是收料超时对账的活动锚(_receipt_last_activity):在飞单元必须有
# started_at 是入站超时对账的活动锚(_inbound_last_activity):在飞单元必须有
# 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。
unit.started_at = datetime.utcnow()
db.session.commit()
if unit.schedule_run_id:
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
refresh_inbound_schedule_run_progress(unit.schedule_run_id)
return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id}
def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
def finalize_inbound_schedule_run_if_complete(schedule_run_id: int) -> dict:
"""
当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。
核心逻辑:聚合单元计数 → 预生成原始收料 ZIP 写入 summary → 企微发 textcard+单 ZIP。
核心逻辑:聚合单元计数 → 预生成原始入站 ZIP 写入 summary → 企微发 textcard+单 ZIP。
"""
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'finalized': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_receipt_rpa'):
return {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
if not summary.get('awaiting_inbound_rpa'):
return {'finalized': False, 'reason': 'not_awaiting_inbound_callback'}
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
terminal = {'success', 'empty', 'failed', 'cancelled'}
if any(unit.status not in terminal for unit in units):
@@ -284,8 +284,8 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
# [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
register_receipt_rpa_excel_headers()
# [STEP] 对齐库存 finalize:终态前生成入站汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
register_inbound_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(INBOUND_RPA_JOB_KEY)
excel_export_ok = True
excel_data, excel_name, excel_size = None, None, 0
@@ -300,49 +300,49 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
'failed_count': failed_count,
'duration_ms': run.duration_ms,
},
details=_build_receipt_finalize_details(units),
details=_build_inbound_finalize_details(units),
header_order=header_order,
header_labels=header_labels,
)
except Exception as excel_exc:
excel_export_ok = False
current_app.logger.error(
'[schedule-run] receipt RPA excel export failed for run %s: %s', run.run_no, excel_exc,
'[schedule-run] inbound RPA excel export failed for run %s: %s', run.run_no, excel_exc,
)
# 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。
if run.status == 'success':
run.status = 'partial_failed'
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
else:
# 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.freight_rpa_inbound_archive import receipt_rpa_result_excel_name
# 企微/下载展示名:入站RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.freight_rpa_inbound_archive import inbound_rpa_result_excel_name
excel_name = receipt_rpa_result_excel_name(run)
excel_name = inbound_rpa_result_excel_name(run)
run.excel_file_data = excel_data
run.excel_file_name = excel_name if excel_data else None
run.excel_file_size = excel_size or 0
# [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。
# [STEP] 对齐库存:终态前预生成原始入站 ZIP,企微只发一个包。
archive_summary = {
'raw_receipt_zip_available': False,
'raw_receipt_zip_path': None,
'raw_receipt_file_count': 0,
'raw_receipt_file_ids': [],
'raw_receipt_zip_size': 0,
'raw_inbound_zip_available': False,
'raw_inbound_zip_path': None,
'raw_inbound_file_count': 0,
'raw_inbound_file_ids': [],
'raw_inbound_zip_size': 0,
}
try:
from app.services.schedule.freight_rpa_inbound_archive import persist_receipt_rpa_raw_zip_archive
from app.services.schedule.freight_rpa_inbound_archive import persist_inbound_rpa_raw_zip_archive
archive_summary = persist_receipt_rpa_raw_zip_archive(run)
archive_summary = persist_inbound_rpa_raw_zip_archive(run)
except Exception as archive_exc:
current_app.logger.error(
'[schedule-run] receipt RPA zip archive failed for run %s: %s',
'[schedule-run] inbound RPA zip archive failed for run %s: %s',
run.run_no, archive_exc,
)
run.response_summary_json = {
**summary,
'awaiting_receipt_rpa': False,
'awaiting_inbound_rpa': False,
'success_count': success_count,
'empty_count': skipped_count,
'failed_count': failed_count,
@@ -351,7 +351,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
**archive_summary,
}
db.session.commit()
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+收料 ZIP。
# 通知与库存 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+入站 ZIP。
try:
task = run.task
if task is not None and task.notify_enabled:
@@ -360,20 +360,20 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
_notify_schedule_run_wecom(task, run)
db.session.commit()
except Exception as wecom_exc:
current_app.logger.error('[schedule-run] receipt RPA wecom notify failed: %s', wecom_exc)
current_app.logger.error('[schedule-run] inbound RPA wecom notify failed: %s', wecom_exc)
return {'finalized': True, 'status': run.status}
def _receipt_timeout_seconds() -> int:
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
def _inbound_timeout_seconds() -> int:
"""读取入站回调等待上限;超时只标记失败,不会自动重试或重发。"""
try:
return max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
return 900
def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
"""识别独立收料 RPA 排程,避免超时回收影响库存或其他平台任务。"""
def is_freight_inbound_rpa_task(task: ScheduleTask | None) -> bool:
"""识别独立入站 RPA 排程,避免超时回收影响库存或其他平台任务。"""
return bool(
task
and task.schedule_type == 'platform_job'
@@ -381,7 +381,7 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
)
def _receipt_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime:
def _inbound_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime:
"""收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
@@ -398,18 +398,18 @@ def _receipt_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRu
return max(stamps)
def _fail_receipt_unit_with_timeout(
def _fail_inbound_unit_with_timeout(
unit: FreightRpaInboundUnitRun, *, now: datetime, timeout_seconds: int,
run_no: str | None = None,
) -> None:
"""单个收料单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。
"""单个入站单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。
核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——run 级扫描与孤儿
单元扫描共用本函数收口单元,防止两条路径语义漂移。只改单元不 commit,
事务归属调用方。
Args:
unit: 待收口的非终态收料单元。
unit: 待收口的非终态入站单元。
now: 收口时刻(同批单元共享同一时间戳)。
timeout_seconds: 超时窗(写入错误文案与审计 metadata)。
run_no: 所属排程 run 号(run 级回收传实;孤儿单元无排程,保持 None)。
@@ -418,8 +418,8 @@ def _fail_receipt_unit_with_timeout(
"""
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
unit.status = 'failed'
unit.error_code = 'RPA.RECEIPT_CALLBACK_TIMEOUT'
unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds'
unit.error_code = 'RPA.INBOUND_CALLBACK_TIMEOUT'
unit.error_message = f'Inbound RPA callback timed out after {timeout_seconds} seconds'
unit.finished_at = now
append_shipping_audit_event(
event_type='shipping_inbound_rpa_callback_timeout', aggregate_type='shipping_inbound_unit',
@@ -430,46 +430,46 @@ def _fail_receipt_unit_with_timeout(
)
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。
def _recover_stale_inbound_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立入站运行收口为失败,保留其单元与触发审计事实。
截止判据为最后活动锚(_receipt_last_activity)而非 run.started_at——
截止判据为最后活动锚(_inbound_last_activity)而非 run.started_at——
串行长批次(>timeout)只要仍有笔间活动就不得被误杀。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at:
if not summary.get('awaiting_inbound_rpa') or run.status != 'running' or not run.started_at:
return False
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not is_freight_receipt_rpa_task(task):
if not is_freight_inbound_rpa_task(task):
return False
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
if _receipt_last_activity(run, units) > cutoff:
if _inbound_last_activity(run, units) > cutoff:
return False
now = datetime.utcnow()
pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}]
for unit in pending:
_fail_receipt_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no)
_fail_inbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no)
run.status = 'failed'
run.finished_at = now
run.duration_ms = int((now - run.started_at).total_seconds() * 1000)
run.failed_count = len(pending) or max(1, int(run.failed_count or 0))
run.error_message = f'收料 RPA 回调等待超时({timeout_seconds} 秒)'
run.error_message = f'入站 RPA 回调等待超时({timeout_seconds} 秒)'
run.step_logs = [*(run.step_logs or []), {
'step': 'freight_receipt_rpa', 'status': 'failed',
'step': 'freight_inbound_rpa', 'status': 'failed',
'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds},
}]
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'recovered_reason': 'receipt_rpa_callback_timeout'}
run.response_summary_json = {**summary, 'awaiting_inbound_rpa': False, 'recovered_reason': 'inbound_rpa_callback_timeout'}
return True
def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int:
"""在同一收料排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。"""
if not is_freight_receipt_rpa_task(task):
def recover_stale_inbound_rpa_schedule_runs(task: ScheduleTask) -> int:
"""在同一入站排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。"""
if not is_freight_inbound_rpa_task(task):
return 0
timeout_seconds = _receipt_timeout_seconds()
timeout_seconds = _inbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
_recover_stale_inbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all()
)
if recovered:
@@ -477,12 +477,12 @@ def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int:
return recovered
def recover_all_stale_receipt_rpa_schedule_runs() -> int:
"""Worker 启动时扫描全部超时收料回调,避免重启后运行永久卡住。"""
timeout_seconds = _receipt_timeout_seconds()
def recover_all_stale_inbound_rpa_schedule_runs() -> int:
"""Worker 启动时扫描全部超时入站回调,避免重启后运行永久卡住。"""
timeout_seconds = _inbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
_recover_stale_inbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(status='running').all()
)
if recovered:
@@ -490,30 +490,30 @@ def recover_all_stale_receipt_rpa_schedule_runs() -> int:
return recovered
def recover_all_stale_orphan_receipt_units() -> int:
"""回收按需触发(无排程绑定)的超时收料单元,解除来源投影永久 fetching。
def recover_all_stale_orphan_inbound_units() -> int:
"""回收按需触发(无排程绑定)的超时入站单元,解除来源投影永久 fetching。
【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台
重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 inbound_trigger_service),
不在 run 级扫描(recover_all_stale_receipt_rpa_schedule_runs 按 run 遍历)范围内;
不在 run 级扫描(recover_all_stale_inbound_rpa_schedule_runs 按 run 遍历)范围内;
Worker 网页异常关闭后回调永不到达,若不回收则来源投影(source_file_status)
永久 fetching、前端重试按钮永久锁死(2026-10-16 事故根因)。
核心逻辑:[STEP 1] 扫 schedule_run_id IS NULL、状态非终态、活动锚
(coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取
无 started_at 时以 created_at 兜底;注意 run 级 _receipt_last_activity 是
无 started_at 时以 created_at 兜底;注意 run 级 _inbound_last_activity 是
笔间静默口径、刻意不含 created_at,两者语义不同)超过
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_receipt_rpa_unit)
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_inbound_rpa_unit)
原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。
[STEP 2] 逐单元经 _fail_receipt_unit_with_timeout 收口(failed +
RPA.RECEIPT_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
[STEP 2] 逐单元经 _fail_inbound_unit_with_timeout 收口(failed +
RPA.INBOUND_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」
(与 recover_stale_waiting_source_jobs 口径一致)。
Returns:
本次回收的单元数。
"""
timeout_seconds = _receipt_timeout_seconds()
timeout_seconds = _inbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
orphans = (
FreightRpaInboundUnitRun.query
@@ -528,6 +528,6 @@ def recover_all_stale_orphan_receipt_units() -> int:
return 0
now = datetime.utcnow()
for unit in orphans:
_fail_receipt_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds)
_fail_inbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds)
db.session.commit()
return len(orphans)
@@ -1,12 +1,12 @@
"""
backend/app/services/schedule/freight_rpa_inbound_job.py
用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。
依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_receipt_rpa_worker_ready、
用途:独立入站 RPA 排程——按勾选来源站点一对一冻结执行单元并写 inbound trigger。
依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_inbound_rpa_worker_ready、
FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaInboundUnitRun、
ScheduleTask/Run。
逻辑:job_registry 的 freight-rpa-inbound 调用本 handler;写 trigger 前 fail-fast;
口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。
口径与 onhand 排程一致(选中 N 源 → N unit),query_parameters 原样下发。
"""
from __future__ import annotations
@@ -20,16 +20,16 @@ from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaIn
from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_receipt_rpa_worker_ready,
assert_inbound_rpa_worker_ready,
)
INBOUND_RPA_JOB_KEY = 'freight-rpa-inbound'
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
AWAITING_INBOUND_RPA_CALLBACK_STATUS = 'awaiting_inbound_rpa_callback'
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _wanted_source_codes(task: ScheduleTask) -> set[str]:
"""提取结构化 source_codes;留空代表全部具备有效收料配置的站点。"""
"""提取结构化 source_codes;留空代表全部具备有效入站配置的站点。"""
params = task.job_params if isinstance(task.job_params, dict) else {}
values = params.get('source_codes') or []
if isinstance(values, str):
@@ -38,7 +38,7 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]:
def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaInboundReportConfig]]:
"""读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
"""读取已启用且已配置入站报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
wanted = _wanted_source_codes(task)
rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join(
FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id,
@@ -47,7 +47,7 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, Freigh
def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[str, Any]]:
"""浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
"""浅拷贝入站查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
return [
dict(item) for item in (config.query_parameters_json or [])
if isinstance(item, dict)
@@ -57,8 +57,8 @@ def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[s
def _build_unit(
source: FreightRpaSource, config: FreightRpaInboundReportConfig, schedule_run_id: int,
) -> FreightRpaInboundUnitRun:
"""冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
callback_id = f'receipt:{uuid.uuid4().hex}'
"""冻结可审计的入站执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
callback_id = f'inbound:{uuid.uuid4().hex}'
snapshot = {
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config),
@@ -98,27 +98,27 @@ def _serialize_trigger_unit(unit: FreightRpaInboundUnitRun) -> dict[str, Any]:
}
def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
def run_freight_rpa_inbound_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
写独立收料 trigger;每个勾选站点对应一个执行单元(与库存 RPA 同口径)。
写独立入站 trigger;每个勾选站点对应一个执行单元(与 onhand RPA 同口径)。
核心逻辑:写 trigger 前 assert_receipt_rpa_worker_ready;离线立即 failed,
不创建 unit、不进入 awaiting_receipt_rpa。
核心逻辑:写 trigger 前 assert_inbound_rpa_worker_ready;离线立即 failed,
不创建 unit、不进入 awaiting_inbound_rpa。
"""
units: list[FreightRpaInboundUnitRun] = [
_build_unit(source, config, run.id) for source, config in _eligible_sources(task)
]
if not units:
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
return 0, 0, 0, 1, [], ['no enabled inbound report sources'], [{'step': 'freight_inbound_rpa', 'status': 'skipped'}]
# [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。
try:
assert_receipt_rpa_worker_ready()
assert_inbound_rpa_worker_ready()
except ServiceUnavailableError as exc:
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
detail_message = str((exc.details or {}).get('detail_message') or message)
return len(units), 0, len(units), 0, [], [detail_message], [{
'step': 'freight_receipt_rpa',
'step': 'freight_inbound_rpa',
'status': 'failed',
'detail': {
'message': message,
@@ -134,9 +134,9 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
trigger_units = [_serialize_trigger_unit(unit) for unit in units]
except RuntimeError as exc:
for unit in units:
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_PROFILE_UNAVAILABLE'; unit.error_message = str(exc)
unit.status = 'failed'; unit.error_code = 'RPA.INBOUND_PROFILE_UNAVAILABLE'; unit.error_message = str(exc)
db.session.commit()
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_inbound_rpa', 'status': 'failed'}]
for unit, trigger_unit in zip(units, trigger_units):
unit.trigger_snapshot_json = trigger_unit
trigger_path = write_inbound_export_batch_trigger(run.run_no, trigger_units, {
@@ -144,13 +144,13 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
})
if not trigger_path:
for unit in units:
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_TRIGGER_UNAVAILABLE'; unit.error_message = 'receipt trigger directory unavailable'
unit.status = 'failed'; unit.error_code = 'RPA.INBOUND_TRIGGER_UNAVAILABLE'; unit.error_message = 'inbound trigger directory unavailable'
db.session.commit()
return len(units), 0, len(units), 0, [], ['receipt trigger directory unavailable'], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
return len(units), 0, len(units), 0, [], ['inbound trigger directory unavailable'], [{'step': 'freight_inbound_rpa', 'status': 'failed'}]
details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units]
run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})}
db.session.commit()
return len(units), 0, 0, 0, details, [], [{
'step': 'freight_receipt_rpa', 'status': AWAITING_RECEIPT_RPA_CALLBACK_STATUS,
'step': 'freight_inbound_rpa', 'status': AWAITING_INBOUND_RPA_CALLBACK_STATUS,
'detail': {'trigger_path': trigger_path, 'unit_count': len(units)},
}]
@@ -11,8 +11,13 @@ from __future__ import annotations
from typing import Any
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""排程壳:委托 freight_rpa.inbound.report_archive 执行三年保留清理(行为不变)。"""
from app.services.freight_rpa.inbound.report_archive import run_freight_rpa_inbound_retention_schedule
def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""排程壳:委托 freight_rpa.inbound.report_archive 执行三年保留清理(行为不变)。
return run_freight_rpa_inbound_retention_schedule(task, run)
核心逻辑:本函数与 archive 同名;必须 as 别名导入,避免递归调用自身。
"""
from app.services.freight_rpa.inbound.report_archive import (
run_freight_rpa_inbound_retention_schedule as _run_inbound_archive_retention,
)
return _run_inbound_archive_retention(task, run)
@@ -0,0 +1,311 @@
"""
backend/app/services/schedule/freight_rpa_outbound_archive.py
用途:货代出站 RPA 排程 run 的原始出站 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、FreightRpaOutboundReportFile / FreightRpaOutboundUnitRun、
file_asset_storage、timezone_util、freight_rpa_outbound_finalize.is_freight_outbound_rpa_task。
逻辑:finalize 调用 persist_outbound_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「出站RPA-日期-时刻-出站」;包内条目 `{序号}_{source_code}.xlsx`;
warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。
"""
from __future__ import annotations
import json
import re
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from flask import current_app
from app.core.errors import NotFoundError
from app.models import ScheduleRun, FreightRpaOutboundReportFile, FreightRpaOutboundUnitRun
from app.services.file_assets.storage import file_asset_storage
from app.services.schedule.freight_rpa_outbound_finalize import is_freight_outbound_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始出站包不存在,请重新执行或联系管理员'
_EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
'raw_outbound_zip_available': False,
'raw_outbound_zip_path': None,
'raw_outbound_file_count': 0,
'raw_outbound_file_ids': [],
'raw_outbound_zip_size': 0,
}
def get_outbound_archive_dir() -> str:
"""
返回出站 RPA 原始 ZIP 归档根目录(自动创建)。
核心逻辑:优先读 Flask config;值为 None/空时回落到 Config 默认路径,
避免 Path(None) 在 finalize 阶段把整次 ZIP 归档打成空 summary。
"""
configured = ''
if current_app:
raw = current_app.config.get('FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR')
configured = str(raw).strip() if raw is not None else ''
if not configured:
from app.core.config.settings import Config
configured = str(Config.FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR or '').strip()
archive_dir = Path(configured)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
"""
推导企微/下载展示名中的当地时刻。
核心逻辑:与库存归档同构——started_at → created_at → finished_at →
解析 RUN{yyyyMMddHHmmss}* → utcnow;再转到任务 schedule_timezone。
"""
when_utc: datetime | None = None
for value in (run.started_at, run.created_at, run.finished_at):
if isinstance(value, datetime):
when_utc = value
break
if when_utc is None:
match = re.match(r'^RUN(\d{14})', str(run.run_no or '').strip())
if match:
try:
when_utc = datetime.strptime(match.group(1), '%Y%m%d%H%M%S')
except ValueError:
when_utc = None
if when_utc is None:
when_utc = datetime.now(timezone.utc).replace(tzinfo=None)
task = getattr(run, 'task', None)
tz_name = getattr(task, 'schedule_timezone', None) if task is not None else None
tz = resolve_schedule_tzinfo(tz_name)
if when_utc.tzinfo is None:
when_utc = when_utc.replace(tzinfo=timezone.utc)
return when_utc.astimezone(tz)
def outbound_rpa_attachment_stem(run: ScheduleRun) -> str:
"""
出站 RPA 企微附件共用前缀:出站RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
Args:
run: 排程执行记录。
Returns:
不含角色后缀与扩展名的展示名前缀。
"""
when = _attachment_when_from_run(run)
return f"出站RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
def outbound_raw_zip_download_name(run: ScheduleRun) -> str:
"""
出站 ZIP 的企微/浏览器下载展示名。
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
"""
return f'{outbound_rpa_attachment_stem(run)}-出站.zip'
def outbound_rpa_result_excel_name(run: ScheduleRun) -> str:
"""出站 RPA 结果 Excel 的企微/下载展示名(对齐入站 inbound_rpa_result_excel_name)。"""
return f'{outbound_rpa_attachment_stem(run)}-结果.xlsx'
def _outbound_raw_zip_archive_path(run_no: str) -> Path:
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
return Path(get_outbound_archive_dir()) / f'{run_no}.zip'
def _iter_packable_outbound_files(run: ScheduleRun):
"""
遍历该 run 下可打包的出站归档文件。
核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。
Yields:
FreightRpaOutboundReportFile: 可从 MinIO 读取的归档记录。
"""
if not is_freight_outbound_rpa_task(getattr(run, 'task', None)):
return
rows = (
FreightRpaOutboundReportFile.query.join(
FreightRpaOutboundUnitRun,
FreightRpaOutboundReportFile.unit_run_id == FreightRpaOutboundUnitRun.id,
)
.filter(
FreightRpaOutboundUnitRun.schedule_run_id == run.id,
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
)
.order_by(FreightRpaOutboundReportFile.id.asc())
.all()
)
for report_file in rows:
yield report_file
def outbound_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
"""
从 response_summary_json 读取原始出站 ZIP 是否可下载。
核心逻辑:列表序列化只读 summary,不查库、不访问磁盘。
"""
if not isinstance(summary, dict):
return False
return bool(summary.get('raw_outbound_zip_available'))
def persist_outbound_rpa_raw_zip_archive(run: ScheduleRun) -> dict[str, Any]:
"""
finalize 阶段预生成原始出站 ZIP 归档并返回 summary 字段。
核心逻辑:从 MinIO 拉取各单元归档字节 → 写入 <archive_dir>/<run_no>.zip
(含 manifest.json);无可用文件时返回 raw_outbound_zip_available=false。
Args:
run: 出站 RPA ScheduleRun。
Returns:
dict: raw_outbound_zip_available / path / file_count / file_ids / zip_size。
"""
packable_files = list(_iter_packable_outbound_files(run))
if not packable_files:
return dict(_EMPTY_ARCHIVE_SUMMARY)
archive_path = _outbound_raw_zip_archive_path(run.run_no)
files_manifest: list[dict[str, Any]] = []
with zipfile.ZipFile(archive_path, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
for zip_index, report_file in enumerate(packable_files, start=1):
unit = report_file.unit_run
source_code = str(getattr(unit, 'source_code', None) or '').strip()
warehouse_id = str(getattr(unit, 'warehouse_id', None) or '').strip()
original_name = str(report_file.original_filename or '').strip() or 'outbound.xlsx'
suffix = Path(original_name).suffix or '.xlsx'
entry_name = _build_zip_entry_name(
index=zip_index,
source_code=source_code,
warehouse_id=warehouse_id,
original_suffix=suffix,
)
# [STEP] 出站归档在 MinIO:读字节后 writestr,不依赖本地 storage_path。
data = file_asset_storage.get_bytes(report_file.storage_key)
archive.writestr(entry_name, data)
files_manifest.append({
'file_id': report_file.id,
'source_code': source_code,
'warehouse_id': warehouse_id,
'file_name': entry_name,
'original_file_name': original_name,
'sha256': report_file.sha256,
})
manifest = {
'run_no': run.run_no,
'total_count': int(run.total_count or 0),
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'files': files_manifest,
}
archive.writestr(
'manifest.json',
json.dumps(manifest, ensure_ascii=False, indent=2),
)
return {
'raw_outbound_zip_available': True,
'raw_outbound_zip_path': str(archive_path.resolve()),
'raw_outbound_file_count': len(files_manifest),
'raw_outbound_file_ids': [item['file_id'] for item in files_manifest],
'raw_outbound_zip_size': int(archive_path.stat().st_size),
}
def _is_allowed_outbound_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != '.zip':
return False
if not resolved.is_file():
return False
archive_dir = Path(get_outbound_archive_dir()).resolve()
try:
resolved.relative_to(archive_dir)
except ValueError:
return False
return True
def resolve_outbound_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
"""
解析 run 已归档的原始出站 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_outbound_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
Raises:
NotFoundError: summary 未标记可用、路径非法或归档文件已丢失。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not outbound_raw_zip_available_from_summary(summary):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path_raw = str(summary.get('raw_outbound_zip_path') or '').strip()
if not zip_path_raw:
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
zip_path = Path(zip_path_raw)
if not _is_allowed_outbound_archive_path(zip_path):
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
return zip_path.resolve(), outbound_raw_zip_download_name(run)
def _sanitize_zip_segment(value: str) -> str:
"""ZIP 内文件名片段安全化,避免路径穿越与非法字符。"""
cleaned = re.sub(r'[^\w\-.]+', '_', str(value or '').strip())
return cleaned or 'unknown'
def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str:
"""
包内短标签:优先 source_code;无则回退仓码;再否则 outbound。
warehouse_id / file_id 已写入 manifest.json;条目名不必再叠仓码。
"""
source = str(source_code or '').strip()
if source:
return source
warehouse = str(warehouse_id or '').strip()
if warehouse and warehouse.lower() not in {'unknown', 'na'}:
return warehouse
return 'outbound'
def _build_zip_entry_name(
*,
index: int,
source_code: str,
warehouse_id: str,
original_suffix: str,
) -> str:
"""
生成 ZIP 内单文件条目名(不含目录)。
核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。
"""
label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id))
suffix = original_suffix if original_suffix.startswith('.') else f'.{original_suffix}'
return f'{index:03d}_{label}{suffix}'
@@ -0,0 +1,532 @@
"""
backend/app/services/schedule/freight_rpa_outbound_finalize.py
用途:独立出站 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。
依赖:FreightRpaOutboundUnitRun、freight_rpa_outbound_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom;
超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from sqlalchemy import func
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.models import FreightRpaOutboundUnitRun
from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.freight_rpa_outbound_job import AWAITING_OUTBOUND_RPA_CALLBACK_STATUS, OUTBOUND_RPA_JOB_KEY
from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_TRIGGER_SCHEMA
from app.services.shipping_notice.audit_service import append_shipping_audit_event
_OUTBOUND_RPA_HEADER_ORDER = [
"source_code",
"warehouse_id",
"connector_type",
"outbound_file_count",
"export_status",
"skip_reason",
"error_message",
]
_OUTBOUND_RPA_HEADER_LABELS = {
"source_code": "出站源",
"warehouse_id": "仓库",
"connector_type": "连接器",
"outbound_file_count": "归档文件数",
"export_status": "导出状态",
"skip_reason": "跳过原因",
"error_message": "错误原因",
}
def register_outbound_rpa_excel_headers() -> None:
"""
注册货代出站 RPA 排程 Excel 列头(幂等)。
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
OUTBOUND_RPA_JOB_KEY,
_OUTBOUND_RPA_HEADER_ORDER,
_OUTBOUND_RPA_HEADER_LABELS,
)
def _build_outbound_finalize_details(units: list[FreightRpaOutboundUnitRun]) -> list[dict[str, Any]]:
"""
出站单元 → 排程 Excel 明细行(对齐入站 finalize 的行结构)。
核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片计数口径一致;
归档文件数便于与原始出站包内 {序号}_{source_code}.xlsx 条目对账。
Args:
units: 该 run 的全部出站单元(已全部终态)。
Returns:
list[dict]: 按 unit.id 升序的明细行。
"""
rows: list[dict[str, Any]] = []
for unit in sorted(units, key=lambda item: item.id):
status = unit.status
if status == 'empty':
export_status = 'skipped'
elif status == 'cancelled':
export_status = 'failed'
else:
export_status = status
rows.append({
'source_code': unit.source_code,
'warehouse_id': unit.warehouse_id or '',
'connector_type': unit.connector_type or '',
'outbound_file_count': len(unit.files or []),
'export_status': export_status,
'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '',
'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '',
})
return rows
def should_defer_outbound_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
"""仅当独立出站 job 成功写入 trigger 后延后终态,避免影响库存/入站 job 判断。"""
return bool(
task.schedule_type == 'platform_job'
and normalize_platform_api_path(task.platform_api_path) == OUTBOUND_RPA_JOB_KEY
and any(isinstance(row, dict) and row.get('status') == AWAITING_OUTBOUND_RPA_CALLBACK_STATUS for row in step_logs or [])
)
def is_awaiting_outbound_rpa_schedule_run(run: ScheduleRun | None) -> bool:
"""判断 run 是否为独立出站 callback 等待态,供 worker 启动恢复时保护。"""
summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {}
return bool(run is not None and run.status == 'running' and summary.get('awaiting_outbound_rpa'))
def apply_deferred_outbound_schedule_run_state(
run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict],
) -> ScheduleRun:
"""将出站 run 保持为 awaiting callback,终态由所有出站单元回调完成后专用服务写入。"""
run.status = 'running'
run.started_at = run.started_at or datetime.utcnow()
run.total_count = total_count
run.success_count = 0
run.failed_count = 0
run.skipped_count = 0
run.finished_at = None
run.step_logs = step_logs
run.response_summary_json = {'awaiting_outbound_rpa': True, 'pending_details': details, 'errors': errors[:20]}
db.session.commit()
return run
def refresh_outbound_schedule_run_progress(schedule_run_id: int) -> dict:
"""
出站单元每笔回调后回写排程 run 进度计数(非终态,对齐库存 inventory-batch-progress)。
核心逻辑:仅在 awaiting_outbound_rpa 时,按已终态单元聚合 success/empty/failed 写入
ScheduleRun 计数与 response_summary_json.progress;不改 status/finished_at,
终态仍由 finalize_outbound_schedule_run_if_complete 负责。
Args:
schedule_run_id: 排程执行记录主键。
Returns:
dict: updated=True/False 及当前计数;非等待态返回 reason。
"""
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_outbound_rpa'):
return {'updated': False, 'reason': 'not_awaiting_outbound_callback'}
units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
success_count = sum(unit.status == 'success' for unit in units)
skipped_count = sum(unit.status == 'empty' for unit in units)
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
# [STEP] 与库存进度同口径:只抬升计数,防乱序回调把笔数打回去。
run.success_count = max(int(run.success_count or 0), success_count)
run.skipped_count = max(int(run.skipped_count or 0), skipped_count)
run.failed_count = max(int(run.failed_count or 0), failed_count)
if run.total_count is None or int(run.total_count or 0) < len(units):
run.total_count = len(units)
summary = dict(summary)
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'processing_count': sum(unit.status == 'processing' for unit in units),
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
db.session.commit()
return {
'updated': True,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
}
def report_outbound_batch_progress(payload: dict) -> dict:
"""
Worker 每完成一笔出站导出后的实时进度回写(非终态,对齐 inventory-batch-progress)。
核心逻辑:校验 schema + schedule_run_id;仅 awaiting_outbound_rpa 时抬升
ScheduleRun 计数;最终以 unit 终态回调 + finalize 为准。
Args:
payload: Worker 上报的累计 success/skipped/failed 与 schedule_run_id。
Returns:
dict: updated / rejected 及当前计数。
"""
if payload.get('schema_version') != OUTBOUND_TRIGGER_SCHEMA:
return {'updated': False, 'reason': 'callback_schema_invalid'}
try:
schedule_run_id = int(payload.get('schedule_run_id')) if payload.get('schedule_run_id') is not None else None
except (TypeError, ValueError):
schedule_run_id = None
if not schedule_run_id:
return {'updated': False, 'reason': 'schedule_run_id_required'}
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'updated': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != 'running' or not summary.get('awaiting_outbound_rpa'):
return {'updated': False, 'reason': 'not_awaiting_outbound_callback'}
incoming = {
'success_count': max(0, int(payload.get('success_count') or 0)),
'skipped_count': max(0, int(payload.get('skipped_count') or 0)),
'failed_count': max(0, int(payload.get('failed_count') or 0)),
}
run.success_count = max(int(run.success_count or 0), incoming['success_count'])
run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count'])
run.failed_count = max(int(run.failed_count or 0), incoming['failed_count'])
summary = dict(summary)
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'batch_run_no': str(payload.get('batch_run_no') or payload.get('run_no') or ''),
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
db.session.commit()
return {
'updated': True,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
}
def mark_outbound_unit_processing(payload: dict) -> dict:
"""
Worker 开始导出某出站单元时标记 processing(对齐库存 claimed / rpa_exporting)。
核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。
"""
if payload.get('schema_version') != OUTBOUND_TRIGGER_SCHEMA:
return {'updated': False, 'reason': 'callback_schema_invalid'}
callback_id = str(payload.get('callback_id') or '').strip()
if not callback_id:
return {'updated': False, 'reason': 'callback_id_required'}
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
return {'updated': False, 'reason': 'unit_not_found'}
if unit.status in {'success', 'empty', 'failed', 'cancelled'}:
return {'updated': False, 'reason': 'already_terminal', 'status': unit.status}
if unit.status == 'processing':
return {'updated': True, 'status': 'processing', 'idempotent': True}
unit.status = 'processing'
# started_at 是出站超时对账的活动锚(_outbound_last_activity):在飞单元必须有
# 开始时间,否则长静默批次无法区分"在跑"与"worker 已死"。
unit.started_at = datetime.utcnow()
db.session.commit()
if unit.schedule_run_id:
refresh_outbound_schedule_run_progress(unit.schedule_run_id)
return {'updated': True, 'status': 'processing', 'unit_run_id': unit.id}
def finalize_outbound_schedule_run_if_complete(schedule_run_id: int) -> dict:
"""
当出站 run 的全部单元已回调后写入独立排程终态,不读取库存/入站回调结果。
核心逻辑:聚合单元计数 → 预生成原始出站 ZIP 写入 summary → 企微发 textcard+单 ZIP。
"""
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return {'finalized': False, 'reason': 'schedule_run_not_found'}
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_outbound_rpa'):
return {'finalized': False, 'reason': 'not_awaiting_outbound_callback'}
units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
terminal = {'success', 'empty', 'failed', 'cancelled'}
if any(unit.status not in terminal for unit in units):
return {'finalized': False, 'reason': 'units_pending'}
success_count = sum(unit.status == 'success' for unit in units)
skipped_count = sum(unit.status == 'empty' for unit in units)
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
run.total_count = len(units)
run.success_count = success_count
run.skipped_count = skipped_count
run.failed_count = failed_count
run.finished_at = datetime.utcnow()
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) if run.started_at else 0
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
# [STEP] 对齐入站 finalize:终态前生成出站汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
register_outbound_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(OUTBOUND_RPA_JOB_KEY)
excel_export_ok = True
excel_data, excel_name, excel_size = None, None, 0
try:
excel_data, _excel_name, excel_size = export_schedule_result_excel(
run_no=run.run_no,
summary={
'status': run.status,
'total_count': len(units),
'success_count': success_count,
'skipped_count': skipped_count,
'failed_count': failed_count,
'duration_ms': run.duration_ms,
},
details=_build_outbound_finalize_details(units),
header_order=header_order,
header_labels=header_labels,
)
except Exception as excel_exc:
excel_export_ok = False
current_app.logger.error(
'[schedule-run] outbound RPA excel export failed for run %s: %s', run.run_no, excel_exc,
)
# 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。
if run.status == 'success':
run.status = 'partial_failed'
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
else:
# 企微/下载展示名:出站RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.freight_rpa_outbound_archive import outbound_rpa_result_excel_name
excel_name = outbound_rpa_result_excel_name(run)
run.excel_file_data = excel_data
run.excel_file_name = excel_name if excel_data else None
run.excel_file_size = excel_size or 0
# [STEP] 对齐入站:终态前预生成原始出站 ZIP,企微只发一个包。
archive_summary = {
'raw_outbound_zip_available': False,
'raw_outbound_zip_path': None,
'raw_outbound_file_count': 0,
'raw_outbound_file_ids': [],
'raw_outbound_zip_size': 0,
}
try:
from app.services.schedule.freight_rpa_outbound_archive import persist_outbound_rpa_raw_zip_archive
archive_summary = persist_outbound_rpa_raw_zip_archive(run)
except Exception as archive_exc:
current_app.logger.error(
'[schedule-run] outbound RPA zip archive failed for run %s: %s',
run.run_no, archive_exc,
)
run.response_summary_json = {
**summary,
'awaiting_outbound_rpa': False,
'success_count': success_count,
'empty_count': skipped_count,
'failed_count': failed_count,
'excel_export_status': 'ok' if excel_export_ok else 'failed',
'excel_failed': not excel_export_ok,
**archive_summary,
}
db.session.commit()
# 通知与入站 RPA 完全同构:run 终态后走通用排程出口一次性发 textcard+出站 ZIP。
try:
task = run.task
if task is not None and task.notify_enabled:
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
_notify_schedule_run_wecom(task, run)
db.session.commit()
except Exception as wecom_exc:
current_app.logger.error('[schedule-run] outbound RPA wecom notify failed: %s', wecom_exc)
return {'finalized': True, 'status': run.status}
def _outbound_timeout_seconds() -> int:
"""读取出站回调等待上限;超时只标记失败,不会自动重试或重发。"""
try:
return max(60, int(current_app.config.get('FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
return 900
def is_freight_outbound_rpa_task(task: ScheduleTask | None) -> bool:
"""识别独立出站 RPA 排程,避免超时回收影响库存或其他平台任务。"""
return bool(
task
and task.schedule_type == 'platform_job'
and normalize_platform_api_path(task.platform_api_path) == OUTBOUND_RPA_JOB_KEY
)
def _outbound_last_activity(run: ScheduleRun, units: list[FreightRpaOutboundUnitRun]) -> datetime:
"""出站 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。
极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。
"""
stamps = [run.started_at] if run.started_at else []
for unit in units:
if unit.started_at:
stamps.append(unit.started_at)
if unit.finished_at:
stamps.append(unit.finished_at)
return max(stamps)
def _fail_outbound_unit_with_timeout(
unit: FreightRpaOutboundUnitRun, *, now: datetime, timeout_seconds: int,
run_no: str | None = None,
) -> None:
"""单个出站单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。
核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——run 级扫描与孤儿
单元扫描共用本函数收口单元,防止两条路径语义漂移。只改单元不 commit,
事务归属调用方。
Args:
unit: 待收口的非终态出站单元。
now: 收口时刻(同批单元共享同一时间戳)。
timeout_seconds: 超时窗(写入错误文案与审计 metadata)。
run_no: 所属排程 run 号(run 级回收传实;孤儿单元无排程,保持 None)。
Returns:
None。
"""
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
unit.status = 'failed'
unit.error_code = 'RPA.OUTBOUND_CALLBACK_TIMEOUT'
unit.error_message = f'Outbound RPA callback timed out after {timeout_seconds} seconds'
unit.finished_at = now
append_shipping_audit_event(
event_type='shipping_outbound_rpa_callback_timeout', aggregate_type='shipping_outbound_unit',
aggregate_id=str(unit.id), run_no=run_no, actor_type='worker', actor_id='schedule-recovery',
unit_id=unit.id, result='failure', before=before,
after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'timeout_seconds': timeout_seconds},
)
def _recover_stale_outbound_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立出站运行收口为失败,保留其单元与触发审计事实。
截止判据为最后活动锚(_outbound_last_activity)而非 run.started_at——
串行长批次(>timeout)只要仍有笔间活动就不得被误杀。
"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if not summary.get('awaiting_outbound_rpa') or run.status != 'running' or not run.started_at:
return False
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
if not is_freight_outbound_rpa_task(task):
return False
units = FreightRpaOutboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
if _outbound_last_activity(run, units) > cutoff:
return False
now = datetime.utcnow()
pending = [unit for unit in units if unit.status in {'queued', 'awaiting_rpa', 'processing'}]
for unit in pending:
_fail_outbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds, run_no=run.run_no)
run.status = 'failed'
run.finished_at = now
run.duration_ms = int((now - run.started_at).total_seconds() * 1000)
run.failed_count = len(pending) or max(1, int(run.failed_count or 0))
run.error_message = f'出站 RPA 回调等待超时({timeout_seconds} 秒)'
run.step_logs = [*(run.step_logs or []), {
'step': 'freight_outbound_rpa', 'status': 'failed',
'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds},
}]
run.response_summary_json = {**summary, 'awaiting_outbound_rpa': False, 'recovered_reason': 'outbound_rpa_callback_timeout'}
return True
def recover_stale_outbound_rpa_schedule_runs(task: ScheduleTask) -> int:
"""在同一出站排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。"""
if not is_freight_outbound_rpa_task(task):
return 0
timeout_seconds = _outbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_outbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all()
)
if recovered:
db.session.commit()
return recovered
def recover_all_stale_outbound_rpa_schedule_runs() -> int:
"""Worker 启动时扫描全部超时出站回调,避免重启后运行永久卡住。"""
timeout_seconds = _outbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
recovered = sum(
_recover_stale_outbound_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
for run in ScheduleRun.query.filter_by(status='running').all()
)
if recovered:
db.session.commit()
return recovered
def recover_all_stale_orphan_outbound_units() -> int:
"""回收按需触发(无排程绑定)的超时出站单元,解除来源投影永久 fetching。
【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台
重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 outbound_trigger_service),
不在 run 级扫描(recover_all_stale_outbound_rpa_schedule_runs 按 run 遍历)范围内;
Worker 网页异常关闭后回调永不到达,若不回收则来源投影(source_file_status)
永久 fetching、前端重试按钮永久锁死。
核心逻辑:[STEP 1] 扫 schedule_run_id IS NULL、状态非终态、活动锚
(coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取
无 started_at 时以 created_at 兜底;注意 run 级 _outbound_last_activity 是
笔间静默口径、刻意不含 created_at,两者语义不同)超过
FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试
原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。
[STEP 2] 逐单元经 _fail_outbound_unit_with_timeout 收口(failed +
RPA.OUTBOUND_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」。
Returns:
本次回收的单元数。
"""
timeout_seconds = _outbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
orphans = (
FreightRpaOutboundUnitRun.query
.filter(
FreightRpaOutboundUnitRun.schedule_run_id.is_(None),
FreightRpaOutboundUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')),
func.coalesce(FreightRpaOutboundUnitRun.started_at, FreightRpaOutboundUnitRun.created_at) < cutoff,
)
.all()
)
if not orphans:
return 0
now = datetime.utcnow()
for unit in orphans:
_fail_outbound_unit_with_timeout(unit, now=now, timeout_seconds=timeout_seconds)
db.session.commit()
return len(orphans)
@@ -0,0 +1,156 @@
"""
backend/app/services/schedule/freight_rpa_outbound_job.py
用途:独立出站 RPA 排程——按勾选库存源一对一冻结执行单元并写 outbound trigger。
依赖:freight_rpa.outbound.trigger_io.write_outbound_export_batch_trigger、assert_outbound_rpa_worker_ready、
FreightRpaSource / FreightRpaOutboundReportConfig / FreightRpaOutboundUnitRun、
ScheduleTask/Run。
逻辑:job_registry 的 freight-rpa-outbound 调用本 handler;写 trigger 前 fail-fast;
口径与入站排程一致(选中 N 源 → N unit),query_parameters 原样下发。
"""
from __future__ import annotations
import uuid
from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaOutboundReportConfig, FreightRpaOutboundUnitRun
from app.services.freight_rpa.outbound.trigger_io import SCHEMA, write_outbound_export_batch_trigger
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_outbound_rpa_worker_ready,
)
OUTBOUND_RPA_JOB_KEY = 'freight-rpa-outbound'
AWAITING_OUTBOUND_RPA_CALLBACK_STATUS = 'awaiting_outbound_rpa_callback'
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _wanted_source_codes(task: ScheduleTask) -> set[str]:
"""提取结构化 source_codes;留空代表全部具备有效出站配置的站点。"""
params = task.job_params if isinstance(task.job_params, dict) else {}
values = params.get('source_codes') or []
if isinstance(values, str):
values = [values]
return {str(value).strip().upper() for value in values if str(value).strip()}
def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaOutboundReportConfig]]:
"""读取已启用且已配置出站报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
wanted = _wanted_source_codes(task)
rows = db.session.query(FreightRpaSource, FreightRpaOutboundReportConfig).join(
FreightRpaOutboundReportConfig, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).all()
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
def _copy_query_parameters(config: FreightRpaOutboundReportConfig) -> list[dict[str, Any]]:
"""浅拷贝出站查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
return [
dict(item) for item in (config.query_parameters_json or [])
if isinstance(item, dict)
]
def _build_unit(
source: FreightRpaSource, config: FreightRpaOutboundReportConfig, schedule_run_id: int,
) -> FreightRpaOutboundUnitRun:
"""冻结可审计的出站执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
callback_id = f'outbound:{uuid.uuid4().hex}'
snapshot = {
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': _copy_query_parameters(config),
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
}
return FreightRpaOutboundUnitRun(
schedule_run_id=schedule_run_id, source_id=source.id, source_code=source.source_code,
connector_type=source.connector_type, warehouse_id=None, callback_id=callback_id,
status='awaiting_rpa', config_snapshot_json=snapshot,
)
def _serialize_trigger_unit(unit: FreightRpaOutboundUnitRun) -> dict[str, Any]:
"""生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 outbound trigger 下发。"""
source = unit.source
profile = source.rpa_profile if source is not None else None
if source is None or profile is None or not profile.enabled:
raise RuntimeError(f'outbound source profile unavailable: {unit.source_code}')
snapshot = dict(unit.config_snapshot_json or {})
return {
'unit_run_id': unit.id,
'callback_id': unit.callback_id,
'source_code': unit.source_code,
'connector_type': unit.connector_type,
'warehouse_id': unit.warehouse_id,
'rpa_profile_id': profile.id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
},
'report_path_json': dict(snapshot.get('report_path_json') or {}),
'query_parameters_json': list(snapshot.get('query_parameters_json') or []),
'config_snapshot': snapshot,
}
def run_freight_rpa_outbound_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
写独立出站 trigger;每个勾选站点对应一个执行单元(与入站 RPA 同口径)。
核心逻辑:写 trigger 前 assert_outbound_rpa_worker_ready;离线立即 failed,
不创建 unit、不进入 awaiting_outbound_rpa_callback。
"""
units: list[FreightRpaOutboundUnitRun] = [
_build_unit(source, config, run.id) for source, config in _eligible_sources(task)
]
if not units:
return 0, 0, 0, 1, [], ['no enabled outbound report sources'], [{'step': 'freight_outbound_rpa', 'status': 'skipped'}]
# [STEP] 写 trigger / 入库 unit 前 fail-fast,避免 Worker 离线干等到超时。
try:
assert_outbound_rpa_worker_ready()
except ServiceUnavailableError as exc:
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
detail_message = str((exc.details or {}).get('detail_message') or message)
return len(units), 0, len(units), 0, [], [detail_message], [{
'step': 'freight_outbound_rpa',
'status': 'failed',
'detail': {
'message': message,
'detail_message': detail_message,
'error_code': exc.code,
'reasons': (exc.details or {}).get('reasons') or [],
},
}]
db.session.add_all(units)
db.session.flush()
try:
trigger_units = [_serialize_trigger_unit(unit) for unit in units]
except RuntimeError as exc:
for unit in units:
unit.status = 'failed'; unit.error_code = 'RPA.OUTBOUND_PROFILE_UNAVAILABLE'; unit.error_message = str(exc)
db.session.commit()
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_outbound_rpa', 'status': 'failed'}]
for unit, trigger_unit in zip(units, trigger_units):
unit.trigger_snapshot_json = trigger_unit
trigger_path = write_outbound_export_batch_trigger(run.run_no, trigger_units, {
'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': SCHEMA,
})
if not trigger_path:
for unit in units:
unit.status = 'failed'; unit.error_code = 'RPA.OUTBOUND_TRIGGER_UNAVAILABLE'; unit.error_message = 'outbound trigger directory unavailable'
db.session.commit()
return len(units), 0, len(units), 0, [], ['outbound trigger directory unavailable'], [{'step': 'freight_outbound_rpa', 'status': 'failed'}]
details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units]
run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})}
db.session.commit()
return len(units), 0, 0, 0, details, [], [{
'step': 'freight_outbound_rpa', 'status': AWAITING_OUTBOUND_RPA_CALLBACK_STATUS,
'detail': {'trigger_path': trigger_path, 'unit_count': len(units)},
}]
@@ -0,0 +1,66 @@
"""
backend/app/services/schedule/freight_rpa_outbound_retention.py
用途:出站原样归档三年到期对象清理(排程壳 + 本阶段清理本体)。
依赖:FreightRpaOutboundReportFile、file_asset_storage、freight_rpa.common.report_audit。
逻辑:job_registry 的 freight-rpa-outbound-retention 调用本 handler;仅删除已过保留期的
MinIO 对象,保留运行、文件事实和审计记录。Task 9 可将本体下沉 outbound.report_archive,
本文件届时改回薄接缝(对照 inbound_retention)。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import FreightRpaOutboundReportFile
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
OUTBOUND_RETENTION_JOB_KEY = 'freight-rpa-outbound-retention'
def run_freight_rpa_outbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。
Args:
task: 排程任务行(job_params.limit 提供单批上限,1..1000)。
run: 排程执行记录(本函数不改写 run,仅按排程协议返回计数/明细/日志)。
Returns:
排程平台 Job 协议七元组(总查得数、成功、失败、跳过 0、明细、错误、step_logs)。
"""
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
now = datetime.utcnow()
rows = FreightRpaOutboundReportFile.query.filter(
FreightRpaOutboundReportFile.archive_expires_at.is_not(None),
FreightRpaOutboundReportFile.archive_expires_at <= now,
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
).order_by(FreightRpaOutboundReportFile.id).limit(limit).all()
success = failed = 0
errors: list[str] = []
for report_file in rows:
try:
file_asset_storage.delete_object(report_file.storage_key)
report_file.archive_deleted_at = now
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
append_rpa_report_event(
event_type='shipping_outbound_report_archive_deleted', aggregate_type='shipping_outbound_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='outbound-retention',
unit_id=report_file.unit_run_id, result='success',
before={'status': 'archived'}, after={'status': 'archive_deleted'},
artifact_refs=[{'kind': 'outbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
success += 1
except Exception as exc:
errors.append(f'{report_file.id}: {exc}')
append_rpa_report_event(
event_type='shipping_outbound_report_archive_delete_attempted', aggregate_type='shipping_outbound_file',
aggregate_id=str(report_file.id), actor_type='worker', actor_id='outbound-retention',
unit_id=report_file.unit_run_id, result='failure',
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
artifact_refs=[{'kind': 'outbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
failed += 1
db.session.commit()
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'outbound_retention', 'status': 'completed'}]
+22 -8
View File
@@ -5,7 +5,7 @@ backend/app/services/schedule/job_options.py
依赖:models.Agent、shipping_notice.onhand_source_repository。
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
货代 RPA 注册键为 freight_rpa_sources 与 freight_rpa_inbound_sources。
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。
"""
from __future__ import annotations
@@ -34,8 +34,8 @@ def _agent_apps_options() -> list[dict[str, Any]]:
]
def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
"""启用中的货代库存源(value=source_code,来自数据库主数据)。"""
def _freight_rpa_sources_options() -> list[dict[str, Any]]:
"""启用中的货代来源站点(value=source_code,来自数据库主数据;供 onhand 排程选源)。"""
from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources
return [
@@ -52,8 +52,8 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
]
def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置收料报表的站点,供独立收料排程选择。"""
def _freight_rpa_inbound_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置入站报表的站点,供独立入站排程选择。"""
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join(
@@ -61,7 +61,20 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
).filter(FreightRpaSource.enabled.is_(True)).all()
return [{
'label': source.display_name or source.source_code, 'value': source.source_code,
'description': f'{source.connector_type} · 收料已配置',
'description': f'{source.connector_type} · 入站已配置',
} for source, _config in rows]
def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置出站报表的站点,供独立出站排程选择。"""
from app.models import FreightRpaSource, FreightRpaOutboundReportConfig
rows = db.session.query(FreightRpaSource, FreightRpaOutboundReportConfig).join(
FreightRpaOutboundReportConfig, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).all()
return [{
'label': source.display_name or source.source_code, 'value': source.source_code,
'description': f'{source.connector_type} · 出站已配置',
} for source, _config in rows]
@@ -102,8 +115,9 @@ def _users_options() -> list[dict[str, Any]]:
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
"agent_apps": _agent_apps_options,
"freight_rpa_sources": _shipping_inventory_sources_options,
"freight_rpa_inbound_sources": _shipping_receipt_sources_options,
"freight_rpa_sources": _freight_rpa_sources_options,
"freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options,
"freight_rpa_outbound_sources": _freight_rpa_outbound_sources_options,
"hxops_users": _hxops_users_options,
"users": _users_options,
}
+28 -7
View File
@@ -2,7 +2,7 @@
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:freight_rpa_onhand_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
依赖:freight_rpa_onhand_job、freight_rpa_inbound_job、freight_rpa_outbound_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
"""
@@ -133,8 +133,10 @@ def _register_builtin_platform_jobs() -> None:
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
from app.services.schedule.freight_rpa_onhand_job import run_freight_rpa_onhand_schedule
from app.services.schedule.freight_rpa_inbound_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_rpa_inbound_retention import run_freight_receipt_rpa_retention_schedule
from app.services.schedule.freight_rpa_inbound_job import run_freight_rpa_inbound_schedule
from app.services.schedule.freight_rpa_inbound_retention import run_freight_rpa_inbound_retention_schedule
from app.services.schedule.freight_rpa_outbound_job import run_freight_rpa_outbound_schedule
from app.services.schedule.freight_rpa_outbound_retention import run_freight_rpa_outbound_retention_schedule
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
run_shipping_post_ot_auto_fulfill_compensation_schedule,
@@ -399,22 +401,41 @@ def _register_builtin_platform_jobs() -> None:
register_platform_job(PlatformJobDefinition(
key="freight-rpa-inbound",
label="货代入站 RPA",
handler=run_freight_receipt_rpa_schedule,
handler=run_freight_rpa_inbound_schedule,
description="按计划从已配置入站报表的站点导出并归档入站文件。",
category="shipping",
params_schema=({
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
"key": "source_codes", "type": "multi_select", "label": "入站站点", "required": False,
"default": [], "options_source": "freight_rpa_inbound_sources",
"help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。",
"help": "选择需要执行的入站站点;留空则执行所有已启用入站配置。",
},),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key='freight-rpa-inbound-retention', label='货代入站归档到期清理',
handler=run_freight_receipt_rpa_retention_schedule,
handler=run_freight_rpa_inbound_retention_schedule,
description='仅删除已过三年保留期的入站对象,保留运行、文件事实和审计记录。', category='shipping',
params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100},
))
register_platform_job(PlatformJobDefinition(
key="freight-rpa-outbound",
label="货代出站 RPA",
handler=run_freight_rpa_outbound_schedule,
description="按计划从已配置出站报表的站点导出并归档出站文件。",
category="shipping",
params_schema=({
"key": "source_codes", "type": "multi_select", "label": "出站站点", "required": False,
"default": [], "options_source": "freight_rpa_outbound_sources",
"help": "选择需要执行的出站站点;留空则执行所有已启用出站配置。",
},),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key='freight-rpa-outbound-retention', label='货代出站归档到期清理',
handler=run_freight_rpa_outbound_retention_schedule,
description='仅删除已过三年保留期的出站对象,保留运行、文件事实和审计记录。', category='shipping',
params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100},
))
register_platform_job(PlatformJobDefinition(
key="faq-aggregate-hot",
label="FAQ 热点聚合",
+12 -2
View File
@@ -1,3 +1,10 @@
"""
backend/app/services/schedule/query_service.py
用途:排程任务与运行记录的查询/序列化。
依赖:ScheduleRun / ScheduleTask、库存/入站/出站 raw-zip 可用性判定。
逻辑:list_tasks / get_run / serialize_run 供管理端排程工作台与下载按钮读取。
"""
from __future__ import annotations
from datetime import datetime, timezone
@@ -10,7 +17,8 @@ from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary
from app.services.schedule.timezone_util import (
DEFAULT_SCHEDULE_TIMEZONE,
compute_next_run_at,
@@ -61,6 +69,7 @@ def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dic
def serialize_run(run: ScheduleRun) -> dict:
"""序列化单条运行记录;附带库存/入站/出站 raw-zip 是否可下载。"""
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
return {
'id': run.id,
@@ -86,7 +95,8 @@ def serialize_run(run: ScheduleRun) -> dict:
'excel_file_name': run.excel_file_name,
'excel_file_size': run.excel_file_size,
'inventory_raw_zip_available': inventory_raw_zip_available_from_summary(summary),
'receipt_raw_zip_available': receipt_raw_zip_available_from_summary(summary),
'inbound_raw_zip_available': inbound_raw_zip_available_from_summary(summary),
'outbound_raw_zip_available': outbound_raw_zip_available_from_summary(summary),
'kb_sync_status': run.kb_sync_status,
'kb_group_id': run.kb_group_id,
'kb_document_id': run.kb_document_id,
+29 -13
View File
@@ -2,7 +2,8 @@
backend/app/services/schedule/queue_service.py
用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务
(onhand / inbound / outbound finalize 超时回收)。
逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。
domain/job_type 固定 schedule/schedule_run 供 worker 认领;业务身份写入
business_ref(schedule_run:{id}:{platform_api_path})、payload 与 message。
@@ -24,10 +25,15 @@ from app.services.schedule.freight_rpa_onhand_finalize import (
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.freight_rpa_inbound_finalize import (
recover_all_stale_orphan_receipt_units,
recover_all_stale_receipt_rpa_schedule_runs,
recover_stale_receipt_rpa_schedule_runs,
is_awaiting_receipt_rpa_schedule_run,
recover_all_stale_orphan_inbound_units,
recover_all_stale_inbound_rpa_schedule_runs,
recover_stale_inbound_rpa_schedule_runs,
is_awaiting_inbound_rpa_schedule_run,
)
from app.services.schedule.freight_rpa_outbound_finalize import (
recover_all_stale_orphan_outbound_units,
recover_all_stale_outbound_rpa_schedule_runs,
recover_stale_outbound_rpa_schedule_runs,
)
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
@@ -233,7 +239,8 @@ def enqueue_manual_schedule_run(
if task is None:
raise LookupError(f"schedule task {task_id} not found")
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
recover_stale_inbound_rpa_schedule_runs(task)
recover_stale_outbound_rpa_schedule_runs(task)
active = _active_run(task.id)
if active is not None:
job = (
@@ -287,7 +294,8 @@ def enqueue_due_schedule_runs(*, limit: int = 5) -> int:
# 每轮都回收当前任务已超时的外部 RPA 回调,不能仅依赖 worker 启动时扫一次;
# 这只是终态化失败,不会自动重新导出。
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
recover_stale_inbound_rpa_schedule_runs(task)
recover_stale_outbound_rpa_schedule_runs(task)
if _active_run(task.id) is None:
_create_queued_run(task, trigger_type="cron", triggered_by_user_id=None)
_advance_next_run(task)
@@ -337,7 +345,7 @@ def prepare_schedule_queue() -> int:
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
interrupted = 0
for run in legacy_running:
if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run):
if is_awaiting_rpa_schedule_run(run) or is_awaiting_inbound_rpa_schedule_run(run):
continue
active_job = (
query_jobs_for_schedule_run(run.id)
@@ -380,16 +388,24 @@ def prepare_schedule_queue() -> int:
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_rpa_inbound_finalize。
receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()
if receipt_stale:
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale)
inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()
if inbound_stale:
current_app.logger.info("[schedule-worker] recovered %d stale inbound RPA runs", inbound_stale)
# 按需触发(无排程)孤儿单元同口径回收(2026-10-16):调拨工作台重试/自动调拨
# 补抓创建的单元 schedule_run_id 为 NULL,上方 run 级扫描按 run 遍历覆盖不到;
# 网页异常关闭后回调永不到达,不回收则来源投影永久 fetching、重试按钮永久锁死。
orphan_stale = recover_all_stale_orphan_receipt_units()
orphan_stale = recover_all_stale_orphan_inbound_units()
if orphan_stale:
current_app.logger.info("[schedule-worker] recovered %d stale orphan receipt RPA units", orphan_stale)
current_app.logger.info("[schedule-worker] recovered %d stale orphan inbound RPA units", orphan_stale)
# 出站 run / 孤儿单元超时对账与入站同属每轮领取维护,不得挂启动一次性分支。
outbound_stale = recover_all_stale_outbound_rpa_schedule_runs()
if outbound_stale:
current_app.logger.info("[schedule-worker] recovered %d stale outbound RPA runs", outbound_stale)
outbound_orphan_stale = recover_all_stale_orphan_outbound_units()
if outbound_orphan_stale:
current_app.logger.info("[schedule-worker] recovered %d stale orphan outbound RPA units", outbound_orphan_stale)
try:
from app.services.freight_rpa.common.worker_heartbeat_alert import maybe_alert_rpa_worker_status
@@ -2,7 +2,9 @@
backend/app/services/schedule/scheduler_service.py
用途:排程任务生命周期(创建/更新)与单次运行执行器。
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync、
freight_rpa_onhand_finalize / inbound_finalize / outbound_finalize(awaiting 延后终态与超时回收)、
onhand / inbound / outbound archive raw-zip 可用性(企微深链 download 意图)。
逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task;
job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path
未传参时重置默认值);schedule worker 调用 run_task_now 并经 resolve_schedule_executor 分发 handler;
@@ -31,9 +33,14 @@ from app.services.schedule.freight_rpa_onhand_finalize import (
should_defer_schedule_run_finalization,
)
from app.services.schedule.freight_rpa_inbound_finalize import (
apply_deferred_receipt_schedule_run_state,
recover_stale_receipt_rpa_schedule_runs,
should_defer_receipt_schedule_run,
apply_deferred_inbound_schedule_run_state,
recover_stale_inbound_rpa_schedule_runs,
should_defer_inbound_schedule_run,
)
from app.services.schedule.freight_rpa_outbound_finalize import (
apply_deferred_outbound_schedule_run_state,
recover_stale_outbound_rpa_schedule_runs,
should_defer_outbound_schedule_run,
)
from app.services.schedule.job_params import normalize_job_params_for_contract
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
@@ -103,11 +110,12 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
"""
构造排程企微 textcard 跳转 query 参数。
核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1
核心逻辑:指向管理端 /admin/schedules;有原始库存/入站/出站归档时附加 raw_zip=1
与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。
"""
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
params: dict[str, Any] = {
@@ -117,17 +125,20 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
if inventory_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'inventory_raw_zip'
elif receipt_raw_zip_available_from_summary(summary):
elif inbound_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'receipt_raw_zip'
params['download'] = 'inbound_raw_zip'
elif outbound_raw_zip_available_from_summary(summary):
params['raw_zip'] = '1'
params['download'] = 'outbound_raw_zip'
return params
def _receipt_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]:
def _inbound_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]:
"""
收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。
收集入站排程 run 名下可投递的入站报表文件;非收料任务返回空列表。
核心逻辑:按 platform_api_path 识别收料排程,返回该 run 全部单元已归档且
核心逻辑:按 platform_api_path 识别入站排程,返回该 run 全部单元已归档且
未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP,
本函数保留给管理员单文件重发等旁路读取。
"""
@@ -158,7 +169,7 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
组装排程完成企微 textcard 正文。
核心逻辑:与管理端统计口径一致,展示 total/success/skipped/failed 四列计数;
有原始库存/收料归档时提示包已随通知发送或可点击下载。
有原始库存/入站/出站归档时提示包已随通知发送或可点击下载。
"""
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
skipped_count = int(run.skipped_count or 0)
@@ -172,12 +183,15 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
from app.services.schedule.freight_rpa_onhand_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_inbound_archive import inbound_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_outbound_archive import outbound_raw_zip_available_from_summary
if inventory_raw_zip_available_from_summary(summary):
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
if receipt_raw_zip_available_from_summary(summary):
description += '\n原始收料包:已随本通知发送;亦可点击本通知登录后下载'
if inbound_raw_zip_available_from_summary(summary):
description += '\n原始入站包:已随本通知发送;亦可点击本通知登录后下载'
if outbound_raw_zip_available_from_summary(summary):
description += '\n原始出站包:已随本通知发送;亦可点击本通知登录后下载'
return description
@@ -186,8 +200,8 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
排程完成后的通用企微通知。
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
则跳过以免与领域缺件/失败告警重复。
库存与收料 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包;
收料附加该 run 的原始收料 ZIP(不再逐文件推送)。
库存、入站、出站 RPA 共用本出口与同一套门禁:库存附加排程 Excel 与原始库存包;
入站/出站附加该 run 的原始 ZIP(不再逐文件推送)。
"""
from app.services.integrations.wecom.notify import (
upload_wecom_temp_media,
@@ -248,18 +262,33 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
run.run_no, exc,
)
receipt_zip_media_id = None
receipt_zip_file_name = None
inbound_zip_media_id = None
inbound_zip_file_name = None
try:
from app.services.schedule.freight_rpa_inbound_archive import resolve_receipt_raw_zip_download
from app.services.schedule.freight_rpa_inbound_archive import resolve_inbound_raw_zip_download
receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run)
receipt_zip_media_id = upload_wecom_temp_media(
receipt_zip_path.read_bytes(), receipt_zip_file_name,
inbound_zip_path, inbound_zip_file_name = resolve_inbound_raw_zip_download(run)
inbound_zip_media_id = upload_wecom_temp_media(
inbound_zip_path.read_bytes(), inbound_zip_file_name,
)
except Exception as exc:
current_app.logger.info(
'[wecom-schedule] raw receipt zip media skipped for run %s: %s',
'[wecom-schedule] raw inbound zip media skipped for run %s: %s',
run.run_no, exc,
)
outbound_zip_media_id = None
outbound_zip_file_name = None
try:
from app.services.schedule.freight_rpa_outbound_archive import resolve_outbound_raw_zip_download
outbound_zip_path, outbound_zip_file_name = resolve_outbound_raw_zip_download(run)
outbound_zip_media_id = upload_wecom_temp_media(
outbound_zip_path.read_bytes(), outbound_zip_file_name,
)
except Exception as exc:
current_app.logger.info(
'[wecom-schedule] raw outbound zip media skipped for run %s: %s',
run.run_no, exc,
)
@@ -318,23 +347,41 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
except Exception as exc:
errors.append(f'{u.real_name or u.username}: raw zip exception={exc}')
if receipt_zip_media_id:
if inbound_zip_media_id:
try:
receipt_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_receipt_raw_zip', u,
title, f'[原始收料包] {receipt_zip_file_name}', uuid.uuid4().hex,
inbound_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_inbound_raw_zip', u,
title, f'[原始入站包] {inbound_zip_file_name}', uuid.uuid4().hex,
)
receipt_zip_data = send_wecom_file_message(u.wecom_userid, receipt_zip_media_id)
if receipt_zip_data.get('errcode') == 0:
receipt_zip_audit.status = 'sent'
inbound_zip_data = send_wecom_file_message(u.wecom_userid, inbound_zip_media_id)
if inbound_zip_data.get('errcode') == 0:
inbound_zip_audit.status = 'sent'
else:
receipt_zip_audit.error_code = str(receipt_zip_data.get('errcode'))
receipt_zip_audit.error_message = str(receipt_zip_data.get('errmsg', 'unknown'))[:255]
inbound_zip_audit.error_code = str(inbound_zip_data.get('errcode'))
inbound_zip_audit.error_message = str(inbound_zip_data.get('errmsg', 'unknown'))[:255]
errors.append(
f'{u.real_name or u.username}: receipt zip errcode={receipt_zip_data.get("errcode")}'
f'{u.real_name or u.username}: inbound zip errcode={inbound_zip_data.get("errcode")}'
)
except Exception as exc:
errors.append(f'{u.real_name or u.username}: receipt zip exception={exc}')
errors.append(f'{u.real_name or u.username}: inbound zip exception={exc}')
if outbound_zip_media_id:
try:
outbound_zip_audit = _create_audit(
f'{_WECOM_EVENT_TYPE}_outbound_raw_zip', u,
title, f'[原始出站包] {outbound_zip_file_name}', uuid.uuid4().hex,
)
outbound_zip_data = send_wecom_file_message(u.wecom_userid, outbound_zip_media_id)
if outbound_zip_data.get('errcode') == 0:
outbound_zip_audit.status = 'sent'
else:
outbound_zip_audit.error_code = str(outbound_zip_data.get('errcode'))
outbound_zip_audit.error_message = str(outbound_zip_data.get('errmsg', 'unknown'))[:255]
errors.append(
f'{u.real_name or u.username}: outbound zip errcode={outbound_zip_data.get("errcode")}'
)
except Exception as exc:
errors.append(f'{u.real_name or u.username}: outbound zip exception={exc}')
if textcard_ok_count > 0:
run.wecom_notified = True
@@ -570,7 +617,8 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
该路径原先只写库不打日志,worker 汇总行看不到失败原因。
"""
recover_stale_awaiting_rpa_schedule_runs(task)
recover_stale_receipt_rpa_schedule_runs(task)
recover_stale_inbound_rpa_schedule_runs(task)
recover_stale_outbound_rpa_schedule_runs(task)
if run is None:
existing = db.session.query(ScheduleRun).filter(
@@ -640,8 +688,12 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
errors=errors,
step_logs=step_logs,
)
if should_defer_receipt_schedule_run(task, step_logs):
return apply_deferred_receipt_schedule_run_state(
if should_defer_inbound_schedule_run(task, step_logs):
return apply_deferred_inbound_schedule_run_state(
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
)
if should_defer_outbound_schedule_run(task, step_logs):
return apply_deferred_outbound_schedule_run_state(
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
)
@@ -1,100 +0,0 @@
"""
services/shipping_notice/inbound_report_access.py
用途:收料归档文件的授权列表与受控下载。
依赖:FreightRpaInboundReportFile(仅查询/取回行,供授权与审计)、当前用户、
freight_rpa/reports.read_inbound_file_bytes(归档字节唯一读取入口)。
逻辑:工作台 /api/workspace/inbound-report-files 调用本模块;下载地址只返回受控 API 路径。
阶段 B Task 5 起下载字节改经 freight_rpa/reports 只读函数取得,禁止本模块
自持模型 + 对象存储双跳读字节。
"""
from __future__ import annotations
from io import BytesIO
from typing import Any
from app import db
from app.core.errors import ForbiddenError, NotFoundError
from app.models import FreightRpaInboundReportFile, User
from app.services.freight_rpa.reports import read_inbound_file_bytes
from app.services.shipping_notice.audit_service import append_shipping_audit_event
def _is_admin(user: User) -> bool:
"""判断用户是否为收料报表管理角色。"""
return bool(user.is_platform_admin())
def can_download_receipt_report_file(report_file: FreightRpaInboundReportFile, user: User) -> bool:
"""仅允许管理员或所属排程通知接收人读取收料归档。"""
if _is_admin(user):
return True
run = report_file.unit_run.schedule_run
task = run.task if run is not None else None
return task is not None and int(user.id) in {
int(value) for value in (task.notify_user_ids_json or []) if str(value).isdigit()
}
def _serialize_receipt_report_file(report_file: FreightRpaInboundReportFile) -> dict[str, Any]:
"""输出可下载收料文件的脱敏列表投影,永不暴露对象存储 bucket 或 key。"""
unit = report_file.unit_run
run = unit.schedule_run if unit is not None else None
return {
'id': report_file.id,
'original_filename': report_file.original_filename,
'content_type': report_file.content_type,
'file_size': report_file.file_size,
'sha256': report_file.sha256,
'source_code': unit.source_code if unit is not None else None,
'warehouse_id': unit.warehouse_id if unit is not None else None,
'schedule_run_no': run.run_no if run is not None else None,
'archive_expires_at': report_file.archive_expires_at.isoformat() if report_file.archive_expires_at else None,
'created_at': report_file.created_at.isoformat() if report_file.created_at else None,
'download_url': f'/api/workspace/inbound-report-files/{report_file.id}/download',
}
def list_receipt_report_files(user: User, *, limit: int = 100) -> list[dict[str, Any]]:
"""列出管理员或当前排程接收人可见的未清理收料归档,并留存读取审计。"""
bounded_limit = max(1, min(int(limit), 200))
rows = FreightRpaInboundReportFile.query.filter(
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
).order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc()).all()
# 先按授权过滤再截断:不能因为前 100 条属于其他排程而遗漏当前接收人的历史文件。
visible = [item for item in rows if can_download_receipt_report_file(item, user)][:bounded_limit]
append_shipping_audit_event(
event_type='shipping_inbound_report_files_listed', aggregate_type='shipping_inbound_file_collection',
aggregate_id=str(user.id), actor_type='user', actor_id=user.id, owner_user_id=user.id,
result='success', after={'visible_count': len(visible), 'limit': bounded_limit},
metadata={'surface': 'workspace_receipt_report_files'},
)
db.session.commit()
return [_serialize_receipt_report_file(item) for item in visible]
def resolve_receipt_report_download(file_id: int, user: User) -> tuple[BytesIO, str, str | None]:
"""授权读取私有对象并记录允许或拒绝的下载审计。"""
report_file = db.session.get(FreightRpaInboundReportFile, file_id)
if report_file is None or report_file.archive_deleted_at is not None:
raise NotFoundError('Receipt report file not found', code='SHIPPING.RECEIPT_REPORT_FILE_NOT_FOUND')
if not can_download_receipt_report_file(report_file, user):
append_shipping_audit_event(
event_type='shipping_inbound_report_download_rejected', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id,
unit_id=report_file.unit_run_id, result='rejected', reason_code='recipient_not_authorized',
after={'status': 'rejected', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
db.session.commit()
raise ForbiddenError('You are not authorized to download this receipt report')
# [STEP] 阶段 B Task 5:归档字节统一经 freight_rpa/reports 只读函数读取(对象存储 key 不外泄、不双跳)。
data = read_inbound_file_bytes(file_id)
append_shipping_audit_event(
event_type='shipping_inbound_report_downloaded', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='user', actor_id=user.id, owner_user_id=user.id,
unit_id=report_file.unit_run_id, result='success',
after={'status': 'downloaded', 'owner_user_id': user.id}, artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
db.session.commit()
return BytesIO(data), report_file.original_filename, report_file.content_type
@@ -1,122 +0,0 @@
"""
services/shipping_notice/inbound_report_storage.py
收料 RPA callback 的域内业务桥与终态收尾(shipping_notice 留守侧)。
用途:批次 R Task 10 拆分后,本模块只留守「业务桥」——收料终态落库后推进在途调拨的
waiting_rpa_callback 来源任务(B3 接线)、success 终态的调拨证据同步,以及排程
终态归集(finalize)调用;原样归档/三年保留/resend/通知投递等 RPA 产物事实能力
已下沉 freight_rpa.inbound.report_archive(函数名 receipt 词根→inbound)。
依赖:freight_rpa.inbound.report_archive(归档能力,经 ingest_receipt_callback 委托)、
in_transit_transfer.inbound_callback_bridge / evidence_sync(惰性导入,仅桥),
schedule.freight_rpa_inbound_finalize(惰性导入,仅 finalize)。
逻辑:ingest_receipt_callback 仍是本域回调入口(rpa_sinks 以 {'success':True,'data':...}
envelope 注册为 inbound-batch-ready sink):委托 report_archive.ingest_inbound_callback
归档(各终态分支各自 commit 后投递 ReportFact——批次 B Task 6 起归档入口不再收
on_terminal 钩子)。生产链路的终态收尾自 Task 7 起由调拨侧处理函数
in_transit_transfer.inbound_report_handler.handle_inbound_report 承担(rpa_sinks 经
register_report_handler 注册);本模块的 _finish_inbound_callback_terminal +
_advance_transfer_source_job 留守为回归测试桥(tests/test_freight_receipt_rpa_callback.
py 经 register_report_handler 注入复刻拆分前终态收尾),其中桥推进失败
【不再吞异常】(Task 7 移除 except Exception: logger.warning——失败必须外抛,
避免把调拨推进失败再次吞掉;吞异常仅保留在证据同步双保险分支)。
"""
from __future__ import annotations
from typing import Any
from flask import current_app
from app.models import FreightRpaInboundUnitRun
def _advance_transfer_source_job(
unit: 'FreightRpaInboundUnitRun', *, ok: bool,
file_no: str | None = None, file_sha256: str | None = None,
error_code: str | None = None, error_message: str | None = None,
) -> None:
"""收料回调终态推进调拨来源任务并提交;失败外抛(Task 7 起不再吞异常)。
Args:
unit: 已落终态的收料单元行(用其 source_code 定位调拨任务)。
ok: 回调是否成功(True 仅在 success 且带 file_no 时推进 file_ready)。
file_no / file_sha256: success 时绑定的归档文件号与指纹。
error_code / error_message: 失败时的错误码与描述。
Raises:
Exception: 桥推进/提交失败原样外抛(Task 7 移除 except 吞异常——
生产链路的推进失败改由调拨侧处理函数承担并外抛供 Worker 重试;
本函数留守为回归测试桥,同样不再吞失败)。
"""
from app import db
from app.services.in_transit_transfer.inbound_callback_bridge import advance_source_job_from_inbound_callback
advanced = advance_source_job_from_inbound_callback(
source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256,
callback_ok=ok, error_code=error_code, error_message=error_message,
)
if advanced is not None:
# 桥内只 flush 不 commit;empty/failed 且 finalize 提前返回时无人提交,
# 必须在此 commit,否则请求结束回滚会丢掉已推进的任务(B3 持久性)。
db.session.commit()
def _finish_inbound_callback_terminal(
unit: 'FreightRpaInboundUnitRun', *, ok: bool,
file_no: str | None = None, file_sha256: str | None = None,
error_code: str | None = None, error_message: str | None = None,
) -> None:
"""终态归档 commit 之后的业务收尾(留守测试桥),顺序与拆分前逐点一致。
定位(Task 7 起):生产链路的终态收尾已由调拨侧处理函数
in_transit_transfer.inbound_report_handler.handle_inbound_report 承担
(rpa_sinks 经 register_report_handler 注册);本函数留守为回归测试桥
(tests/test_freight_receipt_rpa_callback.py 经 register_report_handler 注入),
复刻拆分前的桥推进(不再吞异常)+ 证据同步 + 排程收口三段语义。
核心逻辑:[STEP 1] 推进在途调拨来源任务(_advance_transfer_source_job,原 B3 接线);
[STEP 2] 仅 success 终态触发调拨证据同步(桥模式失败仅日志,绝不影响收料归档主链路,
语义见 in_transit_transfer/evidence_sync.sync_and_commit_for_callback);[STEP 3] 有排程
run 时回写进度并归集终态(按需触发单元 schedule_run_id 为 NULL,跳过排程终态归集;
文件通知不在此逐文件发送:统一由排程终态归集后一次性推送,与库存 RPA 同构)。
"""
_advance_transfer_source_job(
unit, ok=ok, file_no=file_no, file_sha256=file_sha256,
error_code=error_code, error_message=error_message,
)
if ok:
# [调拨证据同步·主链路] success 终态文件落地即解析写调拨待办(本分支专属;
# empty/failed 分支不触发同步)。
try:
from datetime import datetime as _dt
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
sync_and_commit_for_callback(
source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(),
)
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
from app.services.schedule.freight_rpa_inbound_finalize import (
finalize_receipt_schedule_run_if_complete,
refresh_receipt_schedule_run_progress,
)
if unit.schedule_run_id:
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
"""幂等接收单个收料单元回调:委托 report_archive 原样归档(终态后投递事实)。
Args:
payload: Worker 回调载荷;schema_version 必须等于 freight_rpa.inbound.v1。
Returns:
dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。
业务顺序(Task 6 起):归档各终态 commit 后由 report_archive 直接投递
ReportFact(dispatch_report_fact);本域桥/finalize 收尾改经
register_report_handler 注册的处理函数承担(Task 7 接线),不再走
on_terminal 钩子。
"""
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
return ingest_inbound_callback(payload)
@@ -514,7 +514,7 @@ def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_
adopt_published_profile(run.analysis_id, profile_id)
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键;
# 与 shipping_onhand_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。
# 与 freight_rpa_source_admin_service.bind_source_parsing_profile 的批量绑定写序保持同构。
config = source.onhand_report_config
if config is None:
config = FreightRpaOnhandReportConfig(source=source)
@@ -689,7 +689,7 @@ def parse_inventory_snapshot_file(inv_file: FreightRpaOnhandReportFile) -> tuple
if not path.is_file():
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.onhand_file_no}")
from app.models import FreightRpaSource
from app.services.shipping_notice.onhand_parsing_profile import require_source_profile
from app.services.freight_rpa.parsing_profile import require_source_profile
from app.core.errors import ValidationError
source = FreightRpaSource.query.filter_by(source_code=inv_file.source_code).first()
@@ -10,7 +10,8 @@ services/shipping_notice/onhand_report_handler.py
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、
onhand_recovery_service(候选准备 settle/聚合/等待任务反查)、
process_gate_bridge(门禁同步)。
逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks)
逻辑:由组合根(app.create_app → shipping_notice.rpa_sinks.register_onhand_sinks;
入站/出站另见 in_transit_transfer.rpa_sinks)
注册为 'onhand' kind 处理函数;onhand_rpa_workflow 的单回调
(rpa_report_inventory)与批量 worker(process_rpa_report_inventory_batch)
在文件行 commit 后逐文件投递 ok=True 事实(先 commit 再投递——Task 7 修复轮
@@ -100,7 +101,7 @@ def handle_onhand_report(fact: ReportFact) -> None:
if kind != 'onhand':
raise ValidationError(
f"handle_onhand_report only accepts onhand facts, got: {kind!r}",
code='SHIPPING.RECEIPT_CALLBACK_INVALID',
code='SHIPPING.INBOUND_CALLBACK_INVALID',
details={'report_kind': fact.report_kind},
)
@@ -448,7 +448,7 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
}
if any(str(value or '').strip() in duplicates for value in mapping.values()):
raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.ONHAND_STRUCTURE_ANALYSIS_SELECTION_INVALID')
from app.services.shipping_notice import onhand_parsing_profile
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
saved = onhand_parsing_profile.save_draft({
'profile_code': data.get('profile_code'),
@@ -525,7 +525,7 @@ def create_parsing_profile_draft_from_temporary_session(
if existing_draft_id:
existing_draft = db.session.get(FreightRpaParsingProfile, existing_draft_id)
if existing_draft is not None:
from app.services.shipping_notice.onhand_parsing_profile import payload as profile_payload
from app.services.freight_rpa.parsing_profile import payload as profile_payload
return profile_payload(existing_draft)
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, item.analysis_id) if item.analysis_id else None
@@ -1,23 +1,14 @@
"""
services/shipping_notice/rpa_sinks.py
用途:onhand(在手库存)与 inbound(入站,原收料)RPA 回调的业务 sink 注册适配层——把
/api/freight-rpa/* 蓝图的 dispatch_sink kind 接到真实业务处理器,并把文件/报表
事实 kind 接到 reports.dispatch 的处理函数(阶段 B Task 7)。
依赖:freight_rpa.common.callback_sinks(register_sink——进度类回调注册表)、
freight_rpa.reports.dispatch(register_report_handler——文件/报表事实处理函数注册表)、
onhand_rpa_workflow(快照落盘/批量 ingest)、per_source_rpa_service(Attempt 认领)、
onhand_configuration_test(配置测试)、inbound_report_storage(inbound 归档入口 +
业务桥留守)、in_transit_transfer.inbound_report_handler / onhand_report_handler
(Task 7 的两个文件事实处理函数)、schedule.freight_rpa_inbound_finalize
(inbound 进度/领取处理器,Task 11 已随排程壳平移改名)。
逻辑:由组合根(app.create_app)调用 register_onhand_sinks() / register_inbound_sinks() 完成
注册(幂等,重复注册覆盖)。进度类 sink 仅做两件事:① 复刻旧 shipping-notice rpa
回调端点的响应 envelope(逐 kind 对齐,禁止统一 envelope);② 对 onhand-repair 注入
旧路由等价的 payload['repair']=True。文件事实处理函数经 register_report_handler 注册
(Task 7:inbound→handle_inbound_report、onhand→handle_onhand_report)——归档入口
终态 commit 后经 dispatch_report_fact 投递 ReportFact 调入;业务事务边界完全由被
包装的域内函数保持,本层只做接线,不碰 db。
用途:onhand(在手库存)RPA 回调与报表事实的组合根注册——把 /api/freight-rpa/onhand-*
接到发货域业务处理器。入站 / 出站注册见 in_transit_transfer.rpa_sinks。
依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、
onhand_rpa_workflow、per_source_rpa_service、onhand_configuration_test、
onhand_report_handler。
逻辑:由 app.create_app 调用 register_onhand_sinks()(幂等)。进度类 sink 复刻旧
shipping-notice rpa 回调 envelope;onhand-repair 注入 payload['repair']=True;
文件事实经 register_report_handler('onhand', handle_onhand_report) 注册。
"""
from __future__ import annotations
@@ -64,11 +55,9 @@ def register_onhand_sinks() -> None:
"""组合根入口:注册全部 onhand 回调 sink 与 onhand 事实处理函数(幂等;create_app 每次启动调用)。
核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀,被包装函数全部住在
shipping_notice(业务落盘留守域),与 Task 4 裁定一致——认领(claim_inventory_batch)
与批量编排留 per_source_rpa_service,本层只做 envelope 复刻与分发接线;
文件事实处理函数走 reports.dispatch(Task 7):'onhand' kind 经
register_report_handler 注册 handle_onhand_report(在手文件归档终态 commit 后由
dispatch_report_fact 调入),进度类 sink 仍走 register_sink、envelope 不变。
shipping_notice(业务落盘留守域)——认领(claim_inventory_batch)与批量编排留
per_source_rpa_service,本层只做 envelope 复刻与分发接线;文件事实处理函数走
reports.dispatch:'onhand' kind 注册 handle_onhand_report。
"""
from app.services.freight_rpa.common.callback_sinks import register_sink
from app.services.freight_rpa.reports.dispatch import register_report_handler
@@ -93,35 +82,4 @@ def register_onhand_sinks() -> None:
_ok_data_envelope(onhand_configuration_test.report_batch_test_exports),
)
register_sink('onhand-repair', _onhand_repair_sink)
# [STEP Task 7] 文件事实处理函数注册:onhand 归档终态 commit 后经
# dispatch_report_fact 投递 ReportFact(report_kind='onhand')到本处理函数。
register_report_handler('onhand', handle_onhand_report)
def register_inbound_sinks() -> None:
"""组合根入口:注册全部 inbound(收料)回调 sink 与 inbound 事实处理函数(幂等;create_app 每次启动调用)。
核心逻辑:进度类 kind 命名 = /api/freight-rpa/* 回调路由名去前缀。inbound-batch-ready 的
业务处理器 = inbound_report_storage.ingest_receipt_callback(归档能力下沉
freight_rpa.inbound.report_archive 后的域内入口;批次 B Task 6 起归档入口不再收
on_terminal 钩子——终态 commit 后由 report_archive 直接投递 ReportFact);
unit/batch-progress 处理器仍住排程壳
(Task 11 已平移改名为 schedule.freight_rpa_inbound_finalize),按「处理函数住在哪个包」
由本层接注册表。三个进度类 kind 旧端点 envelope 均为 {'success':True,'data':...},逐字复刻。
文件事实处理函数走 reports.dispatch(Task 7):'inbound' kind 经 register_report_handler
注册 in_transit_transfer.handle_inbound_report(调拨推进/证据同步/排程收口均由该
处理函数承担,freight_rpa 不 import 桥与 finalize),进度类 sink 仍走 register_sink、
envelope 不变。
"""
from app.services.freight_rpa.common.callback_sinks import register_sink
from app.services.freight_rpa.reports.dispatch import register_report_handler
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
from app.services.schedule import freight_rpa_inbound_finalize
from app.services.shipping_notice import inbound_report_storage
register_sink('inbound-batch-ready', _success_data_envelope(inbound_report_storage.ingest_receipt_callback))
register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_receipt_unit_processing))
register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_receipt_batch_progress))
# [STEP Task 7] 文件事实处理函数注册:inbound 归档各终态 commit 后经
# dispatch_report_fact 投递 ReportFact(report_kind='inbound')到调拨侧处理函数。
register_report_handler('inbound', handle_inbound_report)