Merge branch 'dev' into common-problems-fuzzy-query

This commit is contained in:
HTEWJ\26070045 committed 2026-10-23 09:41:26 +08:00
commit d3204f1db8
790 files changed
+71443 -26080

No files matched your search

@@ -0,0 +1,105 @@
"""
services/admin/freight_rpa_form_utils.py
用途:货代 RPA 管理端表单校验共用件(JSON 对象、报表路径、查询条件、时间序列化)。
依赖:app.core.errors.ValidationError。
逻辑:freight_rpa_source_admin_service(站点/连接)与 freight_rpa_report_config_service
(入站/出站报表配置)共用;错误码沿用历史 SHIPPING.ONHAND_SOURCE_CONFIG_INVALID,
调用方可按域 remap。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.core.errors import ValidationError
def json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
"""读取并复制对象型 JSON 配置。
Args:
data: 管理 API 的请求载荷。
field: 只允许 JSON object 的字段名。
Returns:
空值规范化为空对象后的可写入配置。
Raises:
ValidationError: 字段不是 JSON object。
"""
value = data.get(field, {})
if not isinstance(value, dict):
raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
return dict(value)
def validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]:
"""校验 DBS 四级报表路径,防止技术选择器混入业务配置。"""
allowed = {'program_group', 'program_label', 'report_group', 'report_name'}
if set(report_path) - allowed:
raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
normalized = {key: str(value or '').strip() for key, value in report_path.items()}
if connector_type == 'dbs':
missing = [key for key in allowed if not normalized.get(key)]
if missing:
raise ValidationError(
'DBS inventory source requires a complete report path',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)},
)
elif normalized:
raise ValidationError(
'Only DBS inventory sources can define report_path_json',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
)
return {key: normalized[key] for key in allowed if normalized.get(key)}
def validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
"""校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。"""
raw = data.get('query_parameters_json', [])
if not isinstance(raw, list):
raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
result: list[dict[str, Any]] = []
seen_names: set[str] = set()
allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'}
for index, item in enumerate(raw):
if not isinstance(item, dict) or set(item) - allowed:
raise ValidationError(
'query parameter contains unsupported fields',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index},
)
name = str(item.get('name') or '').strip()
mode = str(item.get('mode') or 'single').strip().lower()
values = item.get('values', [])
required = item.get('required', False)
select_all = item.get('select_all', False)
if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}:
raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
if not isinstance(values, list) or any(not isinstance(value, str) for value in values):
raise ValidationError('query parameter values must be a string list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
if not isinstance(required, bool) or not isinstance(select_all, bool):
raise ValidationError('query parameter flags must be boolean', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
normalized_values = [value.strip() for value in values if value.strip()]
if required and not normalized_values and not select_all:
raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
if select_all and mode != 'multi_select':
raise ValidationError('select_all only applies to multi_select', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
parameter: dict[str, Any] = {
'name': name, 'mode': mode, 'values': normalized_values,
'required': required, 'select_all': select_all,
}
if mode == 'multi_text':
joiner = str(item.get('joiner') or ',').strip()
if not joiner:
raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
parameter['joiner'] = joiner
seen_names.add(name.lower())
result.append(parameter)
return result
def iso(value: datetime | None) -> str | None:
"""datetime → ISO 字符串;None 保持 None。"""
return value.isoformat() if value else None
@@ -0,0 +1,224 @@
"""
services/admin/freight_rpa_report_config_service.py
用途:货代 RPA 入站 / 出站报表配置管理(GET/PUT),与在手配置解耦。
依赖:db、FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig /
FreightRpaParsingProfile、freight_rpa_form_utils、shipping_notice.audit_service。
逻辑:admin_freight_rpa 蓝图委托本服务;不进入来源站点启用硬门槛;
解析绑定须 published 且 purpose 匹配 inbound/outbound。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import NotFoundError, ValidationError
from app.extensions import db
from app.models import (
FreightRpaInboundReportConfig,
FreightRpaOutboundReportConfig,
FreightRpaParsingProfile,
FreightRpaSource,
)
from app.services.admin.freight_rpa_form_utils import iso, json_object, validate_query_parameters, validate_report_path
from app.services.shipping_notice.audit_service import append_shipping_audit_event
def _inbound_report_config_payload(config: FreightRpaInboundReportConfig) -> dict[str, Any]:
"""序列化独立入站配置,禁止把库存路径或凭据透传至管理端。"""
profile = config.parsing_profile
return {
'id': config.id, 'source_id': config.source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'parsing_profile_id': config.parsing_profile_id,
'parsing_profile': ({
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status,
} if profile else None),
'config_version': config.config_version,
'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at),
}
def _outbound_report_config_payload(config: FreightRpaOutboundReportConfig) -> dict[str, Any]:
"""序列化独立出站配置,禁止把库存/入站路径或凭据透传至管理端。"""
profile = config.parsing_profile
return {
'id': config.id, 'source_id': config.source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'parsing_profile_id': config.parsing_profile_id,
'parsing_profile': ({
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status,
} if profile else None),
'config_version': config.config_version,
'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at),
}
def _validate_inbound_profile_binding(profile_id: Any) -> int | None:
"""校验入站配置绑定的解析规则:必须已发布且 purpose='inbound';空值表示解绑。"""
if profile_id is None or str(profile_id).strip() == '':
return None
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
raise ValidationError(
'Inbound parsing profile must be published with purpose inbound',
code='SHIPPING.INBOUND_PROFILE_INVALID',
)
return profile.id
def _validate_outbound_profile_binding(profile_id: Any) -> int | None:
"""校验出站配置绑定的解析规则:必须已发布且 purpose='outbound';空值表示解绑。"""
if profile_id is None or str(profile_id).strip() == '':
return None
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
if profile is None or profile.status != 'published' or profile.purpose != 'outbound':
raise ValidationError(
'Outbound parsing profile must be published with purpose outbound',
code='SHIPPING.OUTBOUND_PROFILE_INVALID',
)
return profile.id
def _validate_inbound_report_config(
source: FreightRpaSource, data: dict[str, Any],
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范入站配置:路径+查询条件;日期禁填。"""
try:
parameters = validate_query_parameters(data)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
raise ValidationError('Inbound report date filtering is not supported', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
raw_path = json_object(data, 'report_path_json')
if source.connector_type == 'dbs':
try:
path = validate_report_path('dbs', raw_path)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc
return path, parameters
if source.connector_type == 'crane':
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
raise ValidationError('Crane inbound report is fixed to Inbound Details', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
if parameters:
raise ValidationError(
'Crane inbound report does not support query parameters',
code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID',
)
return {'report_name': 'Inbound Details'}, []
raise ValidationError('Unsupported inbound connector type', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
def _validate_outbound_report_config(
source: FreightRpaSource, data: dict[str, Any],
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范出站配置:路径+查询条件;日期禁填;Crane 固定 Outbound Details。"""
try:
parameters = validate_query_parameters(data)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
raise ValidationError('Outbound report date filtering is not supported', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
raw_path = json_object(data, 'report_path_json')
if source.connector_type == 'dbs':
try:
path = validate_report_path('dbs', raw_path)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc
return path, parameters
if source.connector_type == 'crane':
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Outbound Details'):
raise ValidationError('Crane outbound report is fixed to Outbound Details', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
if parameters:
raise ValidationError(
'Crane outbound report does not support query parameters',
code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID',
)
return {'report_name': 'Outbound Details'}, []
raise ValidationError('Unsupported outbound connector type', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
def get_inbound_report_config(source_id: int) -> dict[str, Any] | None:
"""读取站点的入站配置;不存在时返回空。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
return _inbound_report_config_payload(config) if config else None
def save_inbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""保存站点内独立入站配置并追加配置前后快照审计。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
path, parameters = _validate_inbound_report_config(source, data)
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
before = _inbound_report_config_payload(config) if config else None
is_new = config is None
if config is None:
config = FreightRpaInboundReportConfig(source_id=source.id)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.report_path_json = path
config.query_parameters_json = parameters
config.parsing_profile_id = _validate_inbound_profile_binding(data.get('parsing_profile_id'))
config.updated_by = actor_id
db.session.flush()
after = _inbound_report_config_payload(config)
append_shipping_audit_event(
event_type='shipping_inbound_report_config_saved', aggregate_type='shipping_inbound_report_config',
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
result='success', before=before, after=after,
metadata={'source_id': source.id, 'connector_type': source.connector_type,
'parsing_profile_id': config.parsing_profile_id},
)
db.session.commit()
return after
def get_outbound_report_config(source_id: int) -> dict[str, Any] | None:
"""读取站点的出站配置;不存在时返回空。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
return _outbound_report_config_payload(config) if config else None
def save_outbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""保存站点内独立出站配置并追加配置前后快照审计。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
path, parameters = _validate_outbound_report_config(source, data)
config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
before = _outbound_report_config_payload(config) if config else None
is_new = config is None
if config is None:
config = FreightRpaOutboundReportConfig(source_id=source.id)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.report_path_json = path
config.query_parameters_json = parameters
config.parsing_profile_id = _validate_outbound_profile_binding(data.get('parsing_profile_id'))
config.updated_by = actor_id
db.session.flush()
after = _outbound_report_config_payload(config)
append_shipping_audit_event(
event_type='shipping_outbound_report_config_saved', aggregate_type='shipping_outbound_report_config',
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
result='success', before=before, after=after,
metadata={'source_id': source.id, 'connector_type': source.connector_type,
'parsing_profile_id': config.parsing_profile_id},
)
db.session.commit()
return after
@@ -0,0 +1,702 @@
"""
services/admin/freight_rpa_source_admin_service.py
用途:货代 RPA 共用主数据管理——登录连接(FreightRpaProfile)与来源站点(FreightRpaSource),
含站点启用门禁、在手配置行写入、解析绑定审计。
依赖:db、FreightRpaProfile / FreightRpaSource / FreightRpaOnhandReportConfig、
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
onhand_source_repository.validate_source_profile、audit_service。
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
FreightRpaOnhandExternalMapping,
FreightRpaOnhandReportConfig,
FreightRpaOnhandReportFile,
FreightRpaOnhandRoutingRule,
FreightRpaParsingProfile,
FreightRpaProfile,
FreightRpaSource,
FreightRpaSourceParsingBindingAudit,
ScheduleRun,
ShippingExcelTemplate,
ShippingNoticeLine,
ShippingNoticeLineOnhandMatch,
)
from app.services.admin.freight_rpa_form_utils import (
iso as _iso,
json_object as _json_object,
validate_query_parameters as _validate_query_parameters,
validate_report_path as _validate_report_path,
)
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
from app.services.shipping_notice.upload_config_validation import validate_upload_config
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
"""读取并清洗字符串表单字段。"""
value = str(data.get(field) or '').strip()
if required and not value:
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
return value or None
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
"""读取布尔表单字段。"""
value = data.get(field, default)
if not isinstance(value, bool):
raise ValidationError(f'{field} must be a boolean', details={'field': field})
return value
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
value = data.get('login_config_json', {})
if not isinstance(value, dict) or set(value) - {'auth_mode'}:
raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID')
auth_mode = str(value.get('auth_mode') or 'password').strip().lower()
if auth_mode != 'password':
raise ValidationError(
'Only password authentication is currently supported',
code='SHIPPING.RPA_PROFILE_CONFIG_INVALID',
)
return {'auth_mode': auth_mode}
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
return {
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'connector_type': profile.connector_type, 'login_url': profile.login_url,
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
'upload_config_json': profile.upload_config_json,
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
}
def _mask(ciphertext: str | None) -> str | None:
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
return 'configured' if ciphertext else None
def list_profiles() -> list[dict[str, Any]]:
"""列出 Profile 元数据,不返回可恢复的凭据。"""
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
def delete_profile(profile_id: int) -> None:
"""删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。"""
profile = db.session.get(FreightRpaProfile, profile_id)
if profile is None:
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
if FreightRpaSource.query.filter_by(rpa_profile_id=profile.id).count():
raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED')
db.session.delete(profile)
db.session.commit()
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
if profile_id and profile is None:
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
profile = profile or FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
# 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version,
# upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。
prev_non_upload = (
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
) if profile_id else None
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
profile.display_name = str(_text(data, 'display_name', required=True))
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
profile.login_url = str(_text(data, 'login_url', required=True))
profile.login_config_json = _validate_profile_login_config(data)
profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True)
if not profile.enabled and any(source.enabled for source in profile.sources):
raise ConflictError(
'Disable inventory sources before disabling their RPA Profile',
code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED',
)
username = _text(data, 'username')
password = _text(data, 'password')
if username is not None:
profile.username_ciphertext = encrypt_credential(username)
if password is not None:
profile.password_ciphertext = encrypt_credential(password)
if username is not None or password is not None:
profile.credential_updated_at = datetime.utcnow()
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
if 'upload_config_json' in data:
profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json'))
profile.updated_by = actor_id
if profile_id:
now_non_upload = (
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
)
if now_non_upload != prev_non_upload:
profile.config_version += 1
if not profile_id:
profile.created_by = actor_id
db.session.add(profile)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc
return _profile_payload(profile)
def _onhand_report_config_payload(config: FreightRpaOnhandReportConfig) -> dict[str, Any]:
"""序列化站点一对一在手报表配置行,不透传解析方案定义。"""
return {
'id': config.id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'parsing_profile_id': config.parsing_profile_id,
}
def _source_payload(source: FreightRpaSource) -> dict[str, Any]:
"""序列化库存站点及其是否满足正式启用前置条件。
s18 起报表路径/查询条件/解析方案绑定不再随站点 DTO 平铺,
改挂在 ``onhand_report_config`` 嵌套对象(配置行不存在时为 null)。
"""
return {
'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name,
'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id,
'excel_template_id': source.excel_template_id,
'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id,
'onhand_report_config': (
_onhand_report_config_payload(source.onhand_report_config)
if source.onhand_report_config is not None else None
),
'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled),
'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at),
'activation': get_source_activation_status(source),
}
def _validate_onhand_profile_binding(profile_id: Any) -> int | None:
"""校验在手配置绑定的解析方案:必须已发布且 purpose='onhand';空值/0 表示解绑。
Args:
profile_id: 请求载荷中的 parsing_profile_id;None/空串/0 视为解绑(与旧站点保存语义一致)。
Returns:
int | None: 规整后的方案 id 或 None。
Raises:
ValidationError: 方案 id 非法、不存在、未发布或用途不是 onhand
(fail-closed,防误绑入站/出站方案,统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
"""
raw = str(profile_id).strip() if profile_id is not None else ''
if raw in {'', '0'}:
return None
if not raw.isdigit():
raise ValidationError(
'Onhand parsing profile must be published with purpose onhand',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
profile = db.session.get(FreightRpaParsingProfile, int(raw))
if profile is None or profile.status != 'published' or profile.purpose != 'onhand':
raise ValidationError(
'Onhand parsing profile must be published with purpose onhand',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
return profile.id
def _apply_onhand_report_config(
source: FreightRpaSource, data: dict[str, Any], *, actor_id: int | None,
) -> FreightRpaOnhandReportConfig:
"""把手报表三字段写入手配置行(无则插入),不触碰站点行已删除的三列。
核心逻辑:先全量校验路径对象/查询条件/解析绑定,失败时不留脏会话;
校验通过后无配置行则插入(created_by=actor),有则更新并递增 config_version。
报表路径按原样 JSON object 存取(Driver selector 等实现细节归 Worker/模板域,
管理端 DBS 四段路径由前端 normaliseInventoryReportPath 规整后提交)。
Args:
source: 已存在的库存站点(新配置行经 inventory_source 关系级联挂载)。
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
actor_id: 当前管理员主键,仅写审计字段。
Returns:
FreightRpaOnhandReportConfig: 已写入(尚未提交)的配置行。
"""
# [STEP 1] 全量校验先行,任何失败都不会留下半写的配置行。
report_path = _json_object(data, 'report_path_json')
# DBS 四段路径按原样 JSON object 存取(前端 normaliseInventoryReportPath 规整);
# 非 DBS(Crane)站点不得误填 DBS 报表路径(fail-closed,与列搬迁前契约一致)。
if source.connector_type != 'dbs' and report_path:
raise ValidationError(
'Only DBS inventory sources can define report_path_json',
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
)
parameters = _validate_query_parameters(data)
parsing_profile_id = _validate_onhand_profile_binding(data.get('parsing_profile_id'))
# [STEP 2] 校验通过后写配置行:无则插入,有则更新并递增 config_version。
config = source.onhand_report_config
if config is None:
config = FreightRpaOnhandReportConfig(source=source)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.report_path_json = report_path
config.query_parameters_json = parameters
config.parsing_profile_id = parsing_profile_id
config.updated_by = actor_id
return config
def save_onhand_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""保存站点一对一在手报表配置:没有配置行时插入,有则更新并递增该行 config_version。
核心逻辑:委托 _apply_onhand_report_config 校验并写行;启用中的站点借保存拆掉
启用门禁(缺解析绑定/模板)时由 assert_onhand_source_can_enable fail-closed 拒绝。
Args:
source_id: 库存站点主键,必须已存在。
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
actor_id: 当前管理员主键,仅写审计字段。
Returns:
dict[str, Any]: 配置行 DTO(id / report_path_json / query_parameters_json / parsing_profile_id)。
Raises:
NotFoundError: 站点不存在。
ValidationError: 解析方案不存在/未发布/purpose 不是 onhand,或启用中站点门禁被拆。
"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
config = _apply_onhand_report_config(source, data, actor_id=actor_id)
# 启用中的站点不得借配置保存解绑解析方案(excel_template 缺失同样拒绝)。
assert_onhand_source_can_enable(source)
db.session.commit()
return _onhand_report_config_payload(config)
def assert_onhand_source_can_enable(source: FreightRpaSource) -> None:
"""启用中的库存站点必须已有在手配置行(含解析方案绑定)与发货模板。
【AI 触发时机】:保存站点(save_source 载荷含 enabled=true 或保留启用态)、
保存在手配置(save_onhand_report_config 拆绑定前)时调用;
PostgreSQL CHECK 不能跨表,解析方案存在性只能由服务层执行。
Args:
source: 站点对象(可为未提交的暂态行,配置行经 onhand_report_config 关系读取)。
Returns:
None: 门禁通过(站点未启用时恒通过)。
Raises:
ValidationError: enabled 为真但缺配置行、配置行未绑解析方案或站点未绑模板,
统一 code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'。
"""
if not source.enabled:
return
config = source.onhand_report_config
if config is None or not config.parsing_profile_id or not source.excel_template_id:
raise ValidationError(
'Enabled inventory source requires onhand report config, parsing profile and excel template',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
def _binding_snapshot(source: FreightRpaSource) -> dict[str, Any]:
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。
s18 起解析绑定挂在 onhand_report_config 配置行上,快照同样取自配置行。
"""
config = source.onhand_report_config
return {
'source_id': source.id,
'source_code': source.source_code,
'enabled': bool(source.enabled),
'parsing_profile_id': config.parsing_profile_id if config is not None else None,
'parsing_profile_checksum': (
config.parsing_profile.checksum
if config is not None and config.parsing_profile is not None else None
),
'excel_template_id': source.excel_template_id,
'config_version': source.config_version,
}
def _validate_source_parsing_binding(source: FreightRpaSource, profile: FreightRpaParsingProfile) -> None:
"""校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。"""
if profile.status != 'published':
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
if not mapping:
raise ValidationError('Published parsing profile is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
template = source.excel_template
if template is None:
return
if template.status != 'published':
raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
template_definition = template.definition_json if isinstance(template.definition_json, dict) else {}
template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else []
missing_fields = sorted({
str(item.get('source_key') or '')
for item in template_mappings
if isinstance(item, dict)
and item.get('source_kind') == 'inventory_field'
and str(item.get('source_key') or '') not in mapping
})
if missing_fields:
raise ValidationError(
'Parsing profile does not provide all inventory fields required by the excel template',
code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields},
)
def bind_source_parsing_profile(
source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str,
) -> list[dict[str, Any]]:
"""为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。
Args:
source_ids: 待绑定的库存站点主键,不能为空且不得重复。
profile_id: 必须为已发布解析方案主键。
actor_id: 当前管理员主键,仅写入审计。
reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。
operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。
Returns:
list[dict[str, Any]]: 已更新站点的管理端 DTO。
Raises:
ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。
ConflictError: 试图变更已启用站点的正式解析方案。
"""
try:
normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0})
except (TypeError, ValueError) as exc:
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc
if not normalized_ids or len(normalized_ids) != len(source_ids):
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM')
if operation not in {'direct', 'bulk'}:
raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM')
normalized_reason = str(reason or '').strip()
if len(normalized_reason) > 500:
raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM')
# 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。
if not normalized_reason:
normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案'
try:
normalized_profile_id = int(profile_id)
except (TypeError, ValueError) as exc:
raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc
profile = db.session.get(FreightRpaParsingProfile, normalized_profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
sources = [db.session.get(FreightRpaSource, source_id) for source_id in normalized_ids]
if any(source is None for source in sources):
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
typed_sources = [source for source in sources if source is not None]
# [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。
for source in typed_sources:
_validate_source_parsing_binding(source, profile)
for source in typed_sources:
before = _binding_snapshot(source)
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键。
config = source.onhand_report_config
previous_profile_id = config.parsing_profile_id if config is not None else None
if config is None:
config = FreightRpaOnhandReportConfig(source=source)
config.created_by = actor_id
db.session.add(config)
else:
config.config_version += 1
config.parsing_profile_id = profile.id
config.updated_by = actor_id
source.updated_by = actor_id
# 站点 config_version 仍随绑定递增:配置测试锁定版本与运行期失效判断依赖它。
source.config_version += 1
db.session.flush()
db.session.add(FreightRpaSourceParsingBindingAudit(
source_id=source.id, previous_parsing_profile_id=previous_profile_id,
parsing_profile_id=config.parsing_profile_id, operation=operation, reason=normalized_reason, actor_id=actor_id,
source_config_version_before=before['config_version'], source_config_version_after=source.config_version,
before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source),
))
db.session.commit()
return [_source_payload(source) for source in typed_sources]
def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]:
"""读取库存站点解析绑定审计,仅返回配置快照和操作者标识。"""
if db.session.get(FreightRpaSource, source_id) is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
rows = FreightRpaSourceParsingBindingAudit.query.filter_by(
source_id=source_id,
).order_by(FreightRpaSourceParsingBindingAudit.id.desc()).all()
return [{
'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id,
'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id,
'source_config_version_before': row.source_config_version_before,
'source_config_version_after': row.source_config_version_after,
'before': row.before_snapshot_json, 'after': row.after_snapshot_json,
'created_at': row.created_at.isoformat() if row.created_at else None,
} for row in rows]
def list_sources() -> list[dict[str, Any]]:
"""列出库存源及其稳定业务配置。"""
return [_source_payload(item) for item in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all()]
def delete_source(source_id: int) -> None:
"""删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
source_code = str(source.source_code or '').strip().upper()
has_mapping = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id).count() > 0
has_snapshot = FreightRpaOnhandReportFile.query.filter_by(source_code=source_code).count() > 0
has_rule = any(
source_code in {str(code).strip().upper() for code in candidates}
for rule in FreightRpaOnhandRoutingRule.query.all()
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
if isinstance(candidates, list)
)
has_task = db.session.query(ShippingNoticeLine.id).filter(
ShippingNoticeLine.inventory_source_code == source_code,
).first() is not None or db.session.query(ShippingNoticeLineOnhandMatch.id).filter(
ShippingNoticeLineOnhandMatch.source_code == source_code,
).first() is not None
has_export_run = any(
source_code in {str(code).strip().upper() for code in source_codes}
for run in ScheduleRun.query.all()
for source_codes in [(run.api_request_json or {}).get('source_codes', [])]
if isinstance(source_codes, list)
)
if has_mapping or has_snapshot or has_rule or has_task or has_export_run:
raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED')
db.session.delete(source)
db.session.commit()
def _template_validation_missing(source: FreightRpaSource) -> list[str]:
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
template = source.excel_template
# s18 起解析方案绑定取自 onhand_report_config 配置行。
config = source.onhand_report_config
profile = config.parsing_profile if config is not None else None
if template is None or profile is None:
return []
definition = template.definition_json if isinstance(template.definition_json, dict) else {}
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()}
invalid = any(
isinstance(item, dict)
and item.get('source_kind') == 'inventory_field'
and str(item.get('source_key') or '') not in inventory_fields
for item in mappings
)
return ['template_validation'] if not mappings or invalid else []
def _activation_check(
code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None,
blocking: bool | None = None,
) -> dict[str, Any]:
"""构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。"""
return {
'code': code,
'status': status or ('passed' if passed else 'pending'),
'blocking': not passed if blocking is None else blocking,
'action': action,
'evidence': evidence,
}
def _source_activation_checks(source: FreightRpaSource) -> list[dict[str, Any]]:
"""构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。
测试导出不再参与启用门禁;启停由管理员显式开关完成。
"""
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
# s18 起解析方案绑定取自 onhand_report_config 配置行;配置行缺失即解析门禁未就绪。
config = source.onhand_report_config
parsing_profile = config.parsing_profile if config is not None else None
parsing_ready = parsing_profile is not None and parsing_profile.status == 'published'
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False
return [
_activation_check(
'rpa_profile', passed=profile_ready, action='configure_connection',
evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready},
),
_activation_check(
'parsing_profile', passed=parsing_ready, action='configure_parsing_profile',
evidence={'profile_id': parsing_profile.id if parsing_profile is not None else None, 'published': parsing_ready},
),
_activation_check(
'excel_template', passed=template_ready, action='configure_excel_template',
evidence={'template_id': source.excel_template_id, 'published': template_ready},
),
_activation_check(
'template_validation', passed=not template_invalid,
action='configure_excel_template', evidence={}, blocking=template_invalid,
),
]
def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]:
"""返回库存站点启用硬门槛的结构化结果。
Args:
source: 已持久化的库存站点,关联配置由当前数据库事务提供。
Returns:
dict[str, Any]: ``checks`` 为前端唯一的检查真相;``ready`` 为启用结论;
``missing_requirements`` 是由 checks 派生的紧凑摘要,供现有调用方读取。
"""
checks = _source_activation_checks(source)
missing = [item['code'] for item in checks if item['blocking']]
return {
'ready': not missing,
'checks': checks,
'missing_requirements': missing,
}
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
status = get_source_activation_status(source)
if not status['ready']:
raise ConflictError(
'Inventory Source is not ready for activation',
code='SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED',
details=status,
)
source.enabled = True
source.updated_by = actor_id
db.session.commit()
return _source_payload(source)
def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""停用库存站点,保留其解析方案和历史运行审计。"""
source = db.session.get(FreightRpaSource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
source.enabled = False
source.updated_by = actor_id
db.session.commit()
return _source_payload(source)
def save_source(
data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None,
allow_enable_transition: bool = True,
) -> dict[str, Any]:
"""保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。
s18 起站点头部仅编辑 source_code / display_name / connector_type / rpa_profile_id /
excel_template_id / 仓库模式 / snapshot_ttl_seconds;报表路径、查询条件与解析方案
绑定经载荷内嵌的 ``onhand_report_config`` 对象写入配置行(与独立保存同一校验路径)。
"""
source = db.session.get(FreightRpaSource, source_id) if source_id else None
if source_id and source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
try:
profile_id = int(data.get('rpa_profile_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('rpa_profile_id is required') from exc
profile = db.session.get(FreightRpaProfile, profile_id)
if profile is None:
raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False)
if not allow_enable_transition:
# 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。
enabled = bool(source.enabled) if source is not None else False
else:
enabled = requested_enabled
if enabled and not profile.enabled:
raise ValidationError(
'Enabled Inventory Source requires an enabled RPA Profile',
code='SHIPPING.RPA_PROFILE_DISABLED',
)
excel_template_id = data.get('excel_template_id')
excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None
if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'):
raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
is_new = source is None
source = source or FreightRpaSource(
source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed',
)
source.source_code = str(_text(data, 'source_code', required=True)).upper()
source.display_name = str(_text(data, 'display_name', required=True))
source.connector_type = str(_text(data, 'connector_type', required=True)).lower()
source.rpa_profile = profile
source.excel_template = excel_template
source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower()
source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id')
source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400)
source.enabled = enabled
source.updated_by = actor_id
if source_id:
source.config_version += 1
if is_new:
source.created_by = actor_id
db.session.add(source)
# [STEP 1] 启用门禁先行:缺模板在写库前给出可解释错误,避免撞站点行 CHECK 的 IntegrityError
# (模板缺失复用 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED,不新造码)。
if enabled and excel_template is None:
raise ValidationError(
'published excel_template_id is required',
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
)
try:
# flush 让 excel_template_id / 新行主键先行落位,后续门禁读取规整后的外键。
db.session.flush()
except Exception as exc:
db.session.rollback()
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
# [STEP 2] 载荷内嵌 onhand_report_config 时与独立保存走同一校验/写行路径(无则插入配置行)。
config_data = data.get('onhand_report_config')
if isinstance(config_data, dict):
_apply_onhand_report_config(source, config_data, actor_id=actor_id)
# [STEP 3] 启用门禁复核(缺配置行/解析绑定/模板统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
if enabled:
assert_onhand_source_can_enable(source)
validate_source_profile(source, profile)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
return _source_payload(source)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,391 @@
"""
services/admin/shipping_onhand_admin_service.py
用途:在手域管理——库存快照只读、导出运行记录、路由规则、外部仓库映射。
依赖:db、FreightRpaOnhandReportFile / FreightRpaOnhandRoutingRule /
FreightRpaOnhandExternalMapping、order_schema、routing_operators、ALLOWED_ACTIONS。
逻辑:admin_freight_rpa 的 snapshots / export-records / rules / external-mappings 委托本服务;
登录连接与来源站点见 freight_rpa_source_admin_service。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
FreightRpaOnhandExternalMapping,
FreightRpaOnhandReportFile,
FreightRpaOnhandRoutingRule,
FreightRpaOnhandRoutingRuleCondition,
FreightRpaOnhandRoutingRuleVersion,
FreightRpaSource,
ScheduleRun,
ScheduleTask,
ShippingOrderField,
)
from app.services.admin.freight_rpa_form_utils import iso as _iso
from app.services.shipping_notice.onhand_routing_engine import ALLOWED_ACTIONS
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
"""读取并清洗字符串表单字段。"""
value = str(data.get(field) or '').strip()
if required and not value:
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
return value or None
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
"""读取布尔表单字段。"""
value = data.get(field, default)
if not isinstance(value, bool):
raise ValidationError(f'{field} must be a boolean', details={'field': field})
return value
def _snapshot_payload(snapshot: FreightRpaOnhandReportFile) -> dict[str, Any]:
"""投影库存快照的管理端只读行,不暴露存储路径或库存明细。"""
return {
'id': snapshot.id, 'inventory_file_no': snapshot.onhand_file_no,
'source_code': snapshot.source_code, 'warehouse_id': snapshot.warehouse_id,
'snapshot_status': snapshot.snapshot_status, 'identity_status': snapshot.identity_status,
'line_count': snapshot.line_count, 'share_mode': snapshot.share_mode,
'exported_at': _iso(snapshot.exported_at), 'expires_at': _iso(snapshot.expires_at),
'rpa_run_no': snapshot.rpa_run_no, 'schedule_run_id': snapshot.schedule_run_id,
'source_file_name': snapshot.source_file_name, 'created_at': _iso(snapshot.created_at),
'download_available': bool(snapshot.storage_path and not str(snapshot.storage_path).startswith('failed://')),
'error_message': (snapshot.schema_preview_json or {}).get('error') if snapshot.snapshot_status == 'failed' else None,
}
def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]:
"""列出最新库存快照,供管理员确认当前可用的库存文件。"""
rows = FreightRpaOnhandReportFile.query.order_by(
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
).limit(max(1, min(limit, 200))).all()
return [_snapshot_payload(row) for row in rows]
def get_snapshot_download(snapshot_id: int) -> tuple[str, str]:
"""返回管理员可下载的库存快照路径及安全文件名。
Args:
snapshot_id: 库存快照主键。
Returns:
本地托管文件绝对路径和面向下载的文件名。
Raises:
NotFoundError: 快照不存在或托管文件已不存在。
"""
from pathlib import Path
snapshot = db.session.get(FreightRpaOnhandReportFile, snapshot_id)
if snapshot is None:
raise NotFoundError('Inventory snapshot not found', code='SHIPPING.ONHAND_SNAPSHOT_NOT_FOUND')
path = Path(str(snapshot.storage_path or '')).resolve()
if not str(snapshot.storage_path or '') or str(snapshot.storage_path).startswith('failed://') or not path.is_file():
raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.ONHAND_SNAPSHOT_FILE_NOT_FOUND')
filename = str(snapshot.source_file_name or f'{snapshot.onhand_file_no}{path.suffix or ".xlsx"}')
return str(path), filename
def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
"""列出 RPA 导出记录,合并已归档文件与排程失败/跳过结果。"""
file_rows = FreightRpaOnhandReportFile.query.filter(
FreightRpaOnhandReportFile.rpa_run_no.is_not(None),
).order_by(
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
).limit(max(1, min(limit, 200))).all()
records = [_snapshot_payload(row) for row in file_rows]
known_identities = {
(str(item.get('rpa_run_no') or ''), str(item.get('source_code') or ''), str(item.get('warehouse_id') or ''))
for item in records
}
# 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。
schedule_runs = ScheduleRun.query.join(ScheduleTask).filter(
ScheduleTask.platform_api_path == 'freight-rpa-onhand',
).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all()
for run in schedule_runs:
response = run.api_response_json if isinstance(run.api_response_json, dict) else {}
request_data = run.api_request_json if isinstance(run.api_request_json, dict) else {}
run_no = str(response.get('run_no') or request_data.get('run_no') or run.run_no or '').strip()
items: list[tuple[str, dict[str, Any]]] = []
for status, key in (('skipped', 'skipped'), ('failed', 'failed')):
for item in response.get(key) if isinstance(response.get(key), list) else []:
if isinstance(item, dict):
items.append((status, item))
if not items and run.status in {'queued', 'running'}:
pending = (run.response_summary_json or {}).get('pending_details', [])
for item in pending if isinstance(pending, list) else []:
if isinstance(item, dict):
items.append(('awaiting_rpa', item))
if not items and run.status in {'failed', 'partial_failed'}:
for source_code in request_data.get('source_codes') if isinstance(request_data.get('source_codes'), list) else []:
items.append(('failed', {'source_code': source_code, 'error_message': run.error_message}))
for status, item in items:
source_code = str(item.get('source_code') or '').strip()
warehouse_id = str(item.get('warehouse_id') or '').strip()
identity = (run_no, source_code, warehouse_id)
if identity in known_identities:
continue
known_identities.add(identity)
records.append({
'id': f'schedule-{run.id}-{status}-{source_code}-{warehouse_id}',
'inventory_file_no': None,
'source_code': source_code or None,
'warehouse_id': warehouse_id or None,
'snapshot_status': status,
'export_status': status,
'identity_status': None,
'line_count': 0,
'share_mode': None,
'exported_at': _iso(run.finished_at or run.created_at),
'expires_at': None,
'rpa_run_no': run_no or None,
'schedule_run_id': run.id,
'source_file_name': None,
'created_at': _iso(run.created_at),
'error_message': str(item.get('error_message') or item.get('error') or run.error_message or '')[:500] or None,
})
records.sort(key=lambda item: str(item.get('exported_at') or item.get('created_at') or ''), reverse=True)
return records[:max(1, min(limit, 200))]
def _rule_payload(rule: FreightRpaOnhandRoutingRule) -> dict[str, Any]:
return {
'id': rule.id, 'rule_code': rule.rule_code, 'rule_name': rule.rule_name, 'scope': rule.scope,
'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status,
'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version,
'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id,
'operator': c.operator, 'expected_value_json': c.expected_value_json,
'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions],
}
def _validate_rule_condition_expected(operator: str, value: Any) -> Any:
"""按匹配符号规范化期望值,避免自由 JSON 在运行期才暴露配置错误。"""
if operator in {'is_empty', 'is_not_empty'}:
return None
if operator in {'in', 'not_in'}:
if not isinstance(value, list):
raise ValidationError('List operator requires a string list', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
normalized = [str(item).strip() for item in value if str(item).strip()]
if not normalized:
raise ValidationError('List operator requires at least one value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
return normalized
if operator in {'numeric_length', 'string_length'}:
try:
length = int(value)
except (TypeError, ValueError) as exc:
raise ValidationError('Length operator requires an integer', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') from exc
if length < 0:
raise ValidationError('Length must not be negative', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
return length
if not isinstance(value, str) or not value.strip():
raise ValidationError('Routing condition requires an expected value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
return value.strip()
def list_rules() -> list[dict[str, Any]]:
"""列出规则及条件,用于草稿编辑和已发布规则查看。"""
return [_rule_payload(item) for item in FreightRpaOnhandRoutingRule.query.order_by(FreightRpaOnhandRoutingRule.priority.desc()).all()]
def delete_draft_rule(rule_id: int) -> None:
"""删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。"""
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if rule.status != 'draft':
raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.ONHAND_RULE_DELETE_BLOCKED')
db.session.delete(rule)
db.session.commit()
def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""归档已发布规则,使其不再参与新路由,同时保留已发布版本。"""
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if rule.status != 'published':
raise ConflictError('Only published routing rules can be retired', code='SHIPPING.ONHAND_RULE_RETIRE_INVALID')
rule.status = 'retired'
rule.updated_by = actor_id
db.session.commit()
return _rule_payload(rule)
def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None = None) -> dict[str, Any]:
"""保存草稿规则;发布规则必须以新版本创建,避免篡改历史定义。"""
if rule_id:
current = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if current is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if current.status != 'draft':
raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.ONHAND_RULE_IMMUTABLE')
rule = current if rule_id else FreightRpaOnhandRoutingRule(
rule_code='', rule_name='', scope='', action_type='', action_payload_json={}
)
rule.rule_code = str(_text(data, 'rule_code', required=True)).upper()
rule.rule_name = str(_text(data, 'rule_name', required=True))
rule.scope = str(_text(data, 'scope', required=True)).lower()
rule.priority = int(data.get('priority') or 0)
rule.match_mode = str(data.get('match_mode') or 'all').lower()
rule.status = 'draft'
rule.action_type = str(_text(data, 'action_type', required=True)).lower()
rule.action_payload_json = data.get('action_payload_json') if isinstance(data.get('action_payload_json'), dict) else {}
rule.version = int(data.get('version') or 1)
if not rule_id:
rule.created_by = actor_id
rule.updated_by = actor_id
if rule.action_type not in ALLOWED_ACTIONS or rule.scope not in {'task', 'line'} or rule.match_mode not in {'all', 'any'}:
raise ValidationError('Invalid routing rule metadata', code='SHIPPING.ONHAND_RULE_INVALID')
conditions = data.get('conditions')
if not isinstance(conditions, list) or not conditions:
raise ValidationError('Routing rule requires conditions', code='SHIPPING.ONHAND_RULE_CONDITIONS_REQUIRED')
# 草稿更新在同一版本内替换条件;发布后不可原地修改。
if rule_id:
db.session.query(FreightRpaOnhandRoutingRuleCondition).filter_by(rule_id=rule.id).delete(
synchronize_session=False
)
db.session.flush()
db.session.expire(rule, ['conditions'])
for index, item in enumerate(conditions, start=1):
if not isinstance(item, dict) or item.get('operator') not in ALLOWED_OPERATORS:
raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
source_kind = str(item.get('source_kind') or 'order_field')
order_field_id = str(item.get('order_field_id') or '') or None
field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None
if source_kind == 'order_field':
if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'):
raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
published_fields = {
str(config.get('field_id'))
for config in order_schema_service.get_published_contract()['fields']
if config.get('scope') == field.scope
}
if field.id not in published_fields:
raise ValidationError('Routing order field is not published', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
else:
raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
operator = str(item['operator'])
rule.conditions.append(FreightRpaOnhandRoutingRuleCondition(
condition_group=int(item.get('condition_group') or 1), source_kind=source_kind,
order_field_id=order_field_id,
operator=operator, expected_value_json=_validate_rule_condition_expected(
operator, item.get('expected_value_json'),
), sequence=index,
))
if not rule_id:
db.session.add(rule)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('Routing rule code and version already exist', code='SHIPPING.ONHAND_RULE_CONFLICT') from exc
return _rule_payload(rule)
def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""发布草稿并写入不可变规则定义快照。
路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际
库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。
"""
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
if rule is None:
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
if rule.status != 'draft':
raise ConflictError('Only draft routing rules can be published', code='SHIPPING.ONHAND_RULE_PUBLISH_INVALID')
if rule.action_type in {'add_source_candidates', 'exclude_source_candidates'}:
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
source_codes = {
str(code or '').strip().upper()
for code in payload.get('source_codes', [])
if str(code or '').strip()
}
existing_codes = {
str(code).strip().upper()
for (code,) in db.session.query(FreightRpaSource.source_code).all()
}
missing_codes = sorted(source_codes - existing_codes)
if missing_codes:
raise ValidationError(
'Routing rule references unavailable inventory sources',
code='SHIPPING.ONHAND_RULE_SOURCE_INVALID',
details={'source_codes': missing_codes},
)
rule.status = 'published'
rule.updated_by = actor_id
db.session.add(FreightRpaOnhandRoutingRuleVersion(
rule_id=rule.id, version=rule.version, definition_json=_rule_payload(rule), published_by=actor_id,
))
db.session.commit()
return _rule_payload(rule)
def _external_payload(mapping: FreightRpaOnhandExternalMapping) -> dict[str, Any]:
return {
'id': mapping.id, 'source_id': mapping.source_id,
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
'enabled': bool(mapping.enabled), 'version': mapping.version,
}
def list_external_mappings() -> list[dict[str, Any]]:
"""列出库存源到外部系统仓库的映射,不执行调拨判断。"""
return [_external_payload(item) for item in FreightRpaOnhandExternalMapping.query.order_by(FreightRpaOnhandExternalMapping.id).all()]
def delete_external_mapping(mapping_id: int) -> None:
"""删除错误的外部仓库映射;历史文件和任务不回写此实时配置。"""
record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id)
if record is None:
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND')
db.session.delete(record)
db.session.commit()
def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping_id: int | None = None) -> dict[str, Any]:
"""创建或更新精确/默认外部系统映射。"""
record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id) if mapping_id else None
if mapping_id and record is None:
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND')
try:
source_id = int(data.get('source_id'))
except (TypeError, ValueError) as exc:
raise ValidationError('source_id is required') from exc
if db.session.get(FreightRpaSource, source_id) is None:
raise ValidationError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
record = record or FreightRpaOnhandExternalMapping(source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
record.source_id = source_id
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
record.external_organization_code = _text(data, 'external_organization_code')
record.external_site_code = _text(data, 'external_site_code')
record.external_warehouse_code = str(_text(data, 'external_warehouse_code', required=True)).upper()
record.external_warehouse_name = str(_text(data, 'external_warehouse_name', required=True))
record.enabled = _bool(data, 'enabled', bool(record.enabled) if mapping_id else True)
record.updated_by = actor_id
if not mapping_id:
record.created_by = actor_id
db.session.add(record)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_CONFLICT') from exc
return _external_payload(record)
@@ -162,6 +162,8 @@ agent_types:
handler_config_schema: {}
in_transit_transfer:
label: 在途仓自动调拨
# 调拨类型来自平台配置(管理端「在途调拨类型」维护,GET /transfer-types 下发),
# 本清单与提示词不硬编码类型列表;Dify 平台侧如有副本需人工同步。
conversation_mode_default: task_chat
runtime_provider_default: hybrid
models:
@@ -6,6 +6,9 @@
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
Dify Chatflow 生命周期。
【调拨类型语义 2026-10-14】调拨类型来自平台配置(管理端「在途调拨类型」
维护,`GET /api/in-transit-transfer/transfer-types` 下发);提示词与本
Handler 一律不硬编码类型列表,Dify 平台侧如有副本需人工同步。
"""
from __future__ import annotations
+30 -3
View File
@@ -3,7 +3,8 @@ backend/app/services/file_assets/storage.py
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。
逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退;
读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。
"""
from __future__ import annotations
@@ -119,13 +120,39 @@ class FileAssetStorage:
except S3Error:
return False
def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str:
"""生成短期受控下载 URL。"""
def presigned_get_url(
self,
storage_key: str,
*,
expires_seconds: int,
download_name: str | None = None,
) -> str:
"""生成短期受控下载 URL。
核心逻辑:对象键常为内容哈希,浏览器会把它当成保存名。
download_name 非空时把 response-content-disposition 签进 URL,
让保存对话框使用业务文件名。预览地址不要传这个参数。
Args:
storage_key: MinIO 对象键。
expires_seconds: 链接有效秒数,短于 60 秒时抬到 60。
download_name: 附件保存名;只接受调用方已洗净的文件名。
Returns:
带过期签名的 GET URL。
"""
self._ensure_bucket_exists()
response_headers = None
if download_name:
safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '')
response_headers = {
'response-content-disposition': f'attachment; filename="{safe}"',
}
return self.client.presigned_get_object(
self.bucket_name,
storage_key,
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
response_headers=response_headers,
)
@@ -0,0 +1 @@
"""货代 RPA 模块根:承载 freight_rpa 域代码(common/onhand/inbound/upload)。"""
@@ -0,0 +1 @@
"""common:域中立件(跨 RPA Worker 共用、不依赖具体业务域)。"""
@@ -0,0 +1,58 @@
"""
services/freight_rpa/common/callback_sinks.py
用途:RPA 回调「进度类」sink 注册表——freight_rpa 侧的回调分发缝(批次 B Task 6 起
与文件事实分发分工:文件/报表就绪类回调走 freight_rpa.reports.dispatch.
dispatch_report_fact——归档入口先 db.session.commit() 再投递 ReportFact,
kind 未注册同样 404 FREIGHT_RPA.SINK_NOT_REGISTERED;进度类 kind
(inbound-unit-progress / inbound-batch-progress / onhand-batch-claimed 等)
仍走本模块的 register_sink / dispatch_sink,不改 envelope)。
依赖:app.core.errors.AppError。
逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,进度类端点按 kind 分发到
组合根(create_app / api 层)注册的业务处理器;未注册的 kind 显式 404,
绝不静默吞回调。Task 9/10 落地 workflow_protocol / report_archive 时由
组合根调用 register_sink 注入真实业务持久化处理器。
"""
from __future__ import annotations
from typing import Any, Callable
from app.core.errors import AppError
_SINKS: dict[str, Callable[..., Any]] = {}
def register_sink(kind: str, handler: Callable[..., Any]) -> None:
"""
注册一个回调 sink 处理器(由组合根在应用启动时调用)。
Args:
kind: 回调种类,命名 = 回调路由名去前缀(如 "onhand-ready"、
"onhand-configuration-test-complete");同一 kind 重复注册为覆盖。
handler: 业务处理器;契约:接收回调载荷的关键字参数并返回可 jsonify 的业务结果。
"""
_SINKS[kind] = handler
def dispatch_sink(kind: str, **payload: Any) -> Any:
"""
按 kind 分发回调载荷到已注册 sink。
Args:
kind: register_sink 注册过的回调种类。
payload: 回调载荷键值对;键必须为合法 Python 标识符(回调 schema 均为 snake_case)。
Returns:
handler 的返回值(业务结果 dict,由蓝图 jsonify)。
Raises:
AppError: code=FREIGHT_RPA.SINK_NOT_REGISTERED、http_status=404——kind 未注册时
显式失败(Task 9/10 注册真实 sink 前的既定语义)。
"""
handler = _SINKS.get(kind)
if handler is None:
raise AppError(
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
message=f'No callback sink registered for kind: {kind}',
http_status=404,
)
return handler(**payload)
@@ -1,5 +1,5 @@
"""
services/shipping_notice/credential_crypto.py
services/freight_rpa/common/credential_crypto.py
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
@@ -0,0 +1,384 @@
"""freight_rpa/common/report_audit.py
用途:货代 RPA 域(inbound 回调归档、保留期清理、通知投递)写入
ShippingAuditEvent 统一审计账本的唯一入口(批次 B Task 6)。
依赖:app.models.ShippingAuditEvent(允许 import 模型)、app.core.errors.
ValidationError、SQLAlchemy 会话(app.db)。
逻辑:替代此前对 app.services.shipping_notice.audit_service 的依赖——freight_rpa
包禁止 import app.services.shipping_notice.*(import 边界由 tests/services/
freight_rpa/test_import_boundary.py 的空白名单锁定),故本模块以与
append_shipping_audit_event 相同的关键字面直接写同一个 ShippingAuditEvent
模型,事件名(shipping_inbound_rpa_callback_received /
shipping_inbound_report_archived 等)与聚合键保持不变,避免审计查询断档。
与 audit_service 的有意差异(均为本域受控场景):
(1)before/after 快照不做白名单投影——本域快照键均为受控诊断键
(status/error_code/sha256/file_size 等),原样入 snapshot 列;
(2)不做 XFA 加密完整快照(本域无敏感完整载荷);
(3)保留期恒为 None(货代统一审计账本永久保留);
(4)event_hash 以本地稳定哈希对核心字段集合计算,previous_event_hash
取同聚合最新一条已 flush 事件的 event_hash(链结构与 audit_service 同构)。
本模块不提交事务,由调用方与业务写入同一事务提交;写入失败时业务不得 commit。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ShippingAuditEvent
# 与 audit_service 同源的 actor/result 白名单(模型 CHECK 约束同集)。
_ALLOWED_ACTOR_TYPES = frozenset({'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'})
_ALLOWED_RESULTS = frozenset({'success', 'failure', 'rejected', 'ignored'})
# 审计元数据/快照禁止键本地冻结子集(凭据 / 正文 / URL 类;自
# shipping_notice.progress_audit_contract.AUDIT_FORBIDDEN_KEYS 裁剪,仅供本域防呆)。
_FORBIDDEN_AUDIT_KEYS = frozenset({
'api_key',
'api_base_url',
'authorization',
'body',
'content',
'document_text',
'email_body',
'minio',
'object_key',
'object_url',
'password',
'prompt',
'provider_config',
'quote',
'raw_content',
'raw_output',
'secret',
'token',
'url',
'user_agent',
})
def _is_forbidden_audit_key(key: str) -> bool:
"""键名大小写不敏感命中本地禁止键集合(与 audit_service 判定同构)。"""
return str(key or '').strip().lower() in _FORBIDDEN_AUDIT_KEYS
def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]:
"""
递归收集命中敏感黑名单的键路径(dict/list 均遍历,嵌套路径稳定拼接)。
Returns:
命中键路径列表(调用方排序后入 ValidationError.details)。
"""
found: list[str] = []
if isinstance(payload, dict):
for key, child in payload.items():
key_text = str(key)
child_path = f'{path}.{key_text}' if path else key_text
if _is_forbidden_audit_key(key_text):
found.append(child_path)
found.extend(_collect_forbidden_keys(child, path=child_path))
elif isinstance(payload, list):
for index, child in enumerate(payload):
found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]'))
return found
def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
"""验证元数据仅含脱敏诊断事实,阻断凭据、正文与 URL 进入审计账本。"""
safe = dict(metadata or {})
forbidden = _collect_forbidden_keys(safe)
if forbidden:
raise ValidationError(
'RPA report audit metadata contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return safe
def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None:
"""校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。"""
if refs is None:
return None
if not isinstance(refs, list):
raise ValidationError(
f'RPA report audit {field_name} must be a list',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
)
forbidden = _collect_forbidden_keys(refs)
if forbidden:
raise ValidationError(
f'RPA report audit {field_name} contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(forbidden))},
)
return refs
def _stable_hash(value: Any) -> str:
"""对受控状态对象生成 SHA-256(排序键 + 紧凑分隔符,与 audit_service 同构)。"""
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
def _snapshot_diff(before: Any, after: Any) -> dict[str, Any] | None:
"""
计算前后快照顶层差异(changed/added/removed 三段;无变化返回 None)。
核心逻辑:值均为受控诊断键原样比较(本域快照不做白名单投影,见模块 docstring)。
"""
left = before if isinstance(before, dict) else {}
right = after if isinstance(after, dict) else {}
changed: dict[str, Any] = {}
added: dict[str, Any] = {}
removed: dict[str, Any] = {}
for key in sorted(set(left) | set(right)):
if key in left and key in right:
if left[key] != right[key]:
changed[key] = {'from': left[key], 'to': right[key]}
elif key in right:
added[key] = right[key]
else:
removed[key] = left[key]
if not changed and not added and not removed:
return None
return {'changed': changed, 'added': added, 'removed': removed}
def _resolve_previous_event_hash(*, aggregate_type: str, aggregate_id: str) -> str | None:
"""
读取同聚合最新一条事件的 event_hash 作为哈希链前驱。
核心逻辑:按 id 倒序取一条;缺失或旧数据无 hash 时返回 None(链从本条起锚)。
调用方须先 flush 保证同事务先前事件可查(与 audit_service 顺序一致)。
"""
previous = (
ShippingAuditEvent.query
.filter_by(aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128])
.order_by(ShippingAuditEvent.id.desc())
.first()
)
if previous is None:
return None
return str(previous.event_hash) if previous.event_hash else None
def _event_hash_payload(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
action: str | None,
result: str | None,
reason_code: str | None,
run_no: str | None,
task_no: str | None,
operation_id: str | None,
request_id: str | None,
actor_type: str,
actor_id: str | None,
before_snapshot: dict[str, Any] | None,
after_snapshot: dict[str, Any] | None,
diff_json: dict[str, Any] | None,
previous_event_hash: str | None,
sensitivity_level: str | None,
) -> dict[str, Any]:
"""组装参与 event_hash 计算的稳定字段集合(字段集与 audit_snapshot_service 同构)。"""
return {
'event_type': event_type,
'aggregate_type': aggregate_type,
'aggregate_id': aggregate_id,
'action': action,
'result': result,
'reason_code': reason_code,
'workflow_id': None,
'workflow_item_id': None,
'workflow_item_version_id': None,
'version_no': None,
'run_no': run_no,
'document_id': None,
'review_case_no': None,
'task_no': task_no,
'operation_id': operation_id,
'request_id': request_id,
'actor_type': actor_type,
'actor_id': actor_id,
'before_snapshot': before_snapshot,
'after_snapshot': after_snapshot,
'diff': diff_json,
'previous_event_hash': previous_event_hash,
'sensitivity_level': sensitivity_level,
}
def append_rpa_report_event(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
run_no: str | None = None,
task_no: str | None = None,
intake_no: str | None = None,
actor_type: str = 'system',
actor_id: str | int | None = None,
actor_role: str | None = None,
actor_display: str | None = None,
request_id: str | None = None,
operation_id: str | None = None,
correlation_id: str | None = None,
source: str | None = None,
result: str | None = None,
error_code: str | None = None,
conversation_id: str | None = None,
unit_id: str | int | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
owner_user_id: str | int | None = None,
attempt_no: int | None = None,
action: str | None = None,
reason_code: str | None = None,
reason: str | None = None,
before: Any = None,
after: Any = None,
evidence_refs: list[dict[str, Any]] | None = None,
artifact_refs: list[dict[str, Any]] | None = None,
context_refs: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
sensitivity_level: str | None = None,
) -> ShippingAuditEvent:
"""
追加一条货代 RPA 审计事实(freight_rpa 域唯一审计写入口)。
用途:与 shipping_notice.audit_service.append_shipping_audit_event 关键字兼容的
RPA 域替代品——调用方(report_archive 等)自 audit_service 迁移时仅改函数名,
事件名与聚合键原样保持,避免审计查询断档(见模块 docstring 的四处有意差异)。
核心逻辑:[STEP 1] 校验 actor_type/result 白名单 + 元数据/引用脱敏;
[STEP 2] 计算 before/after 稳定哈希与顶层 diff;
[STEP 3] flush 后取同聚合前驱 event_hash,对核心字段集合计算 event_hash;
[STEP 4] 写入 ShippingAuditEvent(保留期恒 None=永久)并 flush,不 commit。
Args:
event_type: 稳定业务事件名(如 shipping_inbound_rpa_callback_received);
禁止传入用户自由文本。
aggregate_type/aggregate_id: 业务聚合类型与稳定编号(软引用,不使用外键)。
run_no/task_no: 排程 run / task 软引用(截断 64)。
actor_type/actor_id/actor_role/actor_display: 操作主体四元组
(actor_type 必须在 user/system/rpa/chatflow/admin/worker 内)。
result: success / failure / rejected / ignored(白名单外抛 ValidationError)。
before/after: 受控状态快照(本域不做白名单投影,键须为诊断类,禁敏感键)。
evidence_refs/artifact_refs: FileAsset ID、SHA-256 等标识引用;禁止 URL/正文。
metadata: 仅允许原因码、计数等脱敏诊断事实(禁止键见 _FORBIDDEN_AUDIT_KEYS)。
unit_id/document_id/review_case_no/owner_user_id/attempt_no: 业务关联软引用。
action/reason_code/reason/error_code/conversation_id/correlation_id/source/
request_id/operation_id/intake_no/sensitivity_level: 追溯与分级补充字段。
Returns:
尚未提交的 ShippingAuditEvent,由调用方与业务写入在同一事务提交。
Raises:
ValidationError: actor/result 非法,或元数据/快照引用包含正文、凭据等敏感键。
"""
# [STEP 1] 校验与脱敏(错误码与 audit_service 共用,避免同义分裂)。
if actor_type not in _ALLOWED_ACTOR_TYPES:
raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID')
if result is not None and result not in _ALLOWED_RESULTS:
raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID')
safe_metadata = _sanitize_metadata(metadata)
if before is not None and _collect_forbidden_keys(before):
raise ValidationError(
'RPA report audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(before)))},
)
if after is not None and _collect_forbidden_keys(after):
raise ValidationError(
'RPA report audit snapshot contains forbidden keys',
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(after)))},
)
# [STEP 2] 快照哈希与顶层差异。
before_snapshot = before if isinstance(before, dict) else None
after_snapshot = after if isinstance(after, dict) else None
diff_json = _snapshot_diff(before, after)
# [STEP 3] 哈希链:flush 保证同事务先前事件可查,再取前驱并计算本条 event_hash。
db.session.flush()
previous_event_hash = _resolve_previous_event_hash(
aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128],
)
resolved_run_no = str(run_no)[:64] if run_no else None
resolved_task_no = str(task_no)[:64] if task_no else None
resolved_actor_id = str(actor_id)[:128] if actor_id is not None else None
resolved_operation_id = str(operation_id)[:64] if operation_id else None
resolved_request_id = str(request_id)[:64] if request_id else None
resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None
event_hash = _stable_hash(_event_hash_payload(
event_type=str(event_type)[:64],
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
action=str(action)[:64] if action else None,
result=result,
reason_code=str(reason_code)[:128] if reason_code else None,
run_no=resolved_run_no,
task_no=resolved_task_no,
operation_id=resolved_operation_id,
request_id=resolved_request_id,
actor_type=actor_type,
actor_id=resolved_actor_id,
before_snapshot=before_snapshot,
after_snapshot=after_snapshot,
diff_json=diff_json,
previous_event_hash=previous_event_hash,
sensitivity_level=resolved_sensitivity,
))
# [STEP 4] 写入事件(保留期恒 None=永久保留;不 commit,由调用方保证原子性)。
event = ShippingAuditEvent(
event_type=str(event_type)[:64],
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
run_no=resolved_run_no,
task_no=resolved_task_no,
intake_no=str(intake_no)[:64] if intake_no else None,
actor_type=actor_type,
actor_id=resolved_actor_id,
actor_role=str(actor_role)[:64] if actor_role else None,
actor_display=str(actor_display)[:128] if actor_display else None,
request_id=resolved_request_id,
operation_id=resolved_operation_id,
correlation_id=str(correlation_id)[:64] if correlation_id else None,
source=str(source)[:32] if source else None,
result=result,
error_code=str(error_code)[:64] if error_code else None,
conversation_id=str(conversation_id)[:100] if conversation_id else None,
unit_id=str(unit_id)[:64] if unit_id is not None else None,
document_id=str(document_id)[:64] if document_id is not None else None,
review_case_no=str(review_case_no)[:64] if review_case_no else None,
owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None,
attempt_no=int(attempt_no) if attempt_no is not None else None,
action=str(action)[:64] if action else None,
reason_code=str(reason_code)[:128] if reason_code else None,
reason=str(reason)[:2000] if reason else None,
before_hash=_stable_hash(before_snapshot) if before_snapshot is not None else None,
after_hash=_stable_hash(after_snapshot) if after_snapshot is not None else None,
before_snapshot_json=before_snapshot,
after_snapshot_json=after_snapshot,
diff_json=diff_json,
previous_event_hash=previous_event_hash,
event_hash=event_hash,
sensitivity_level=resolved_sensitivity,
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
context_refs_json=dict(context_refs or {}) if context_refs else None,
metadata_json=safe_metadata,
retention_expires_at=None,
)
db.session.add(event)
db.session.flush()
return event
# 供测试与契约引用的冻结黑名单导出(与 audit_service.FORBIDDEN_AUDIT_METADATA_KEYS 对应的本地子集)。
RPA_FORBIDDEN_AUDIT_KEYS = _FORBIDDEN_AUDIT_KEYS
@@ -0,0 +1,36 @@
"""
services/freight_rpa/common/rpa_runtime.py
用途:RPA 运行模式(browser/mock)的展示助手——把任务回调记录或后端配置规范化为前端安全摘要。
依赖:Flask current_app 配置(FREIGHT_RPA_WORKER_MOCK);不依赖目录 IO 与 Worker 文件契约。
逻辑:由 shipping_notice.query_service(任务序列化注入 rpa_runtime 摘要)、
同包 worker_heartbeat(mock 模式下跳过真实 Worker 在线探测)消费;
仅做展示归一,不承载触发/回调逻辑。
"""
from __future__ import annotations
from typing import Any
from flask import current_app
def _runtime_summary(mode: str) -> dict[str, str | bool]:
"""将 browser/mock 规范化为前端安全展示摘要。"""
normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser"
mock_enabled = normalized == "mock"
return {
"mode": normalized,
"label": "Mock RPA" if mock_enabled else "真实 RPA",
"mock": mock_enabled,
}
def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]:
"""返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。"""
if isinstance(runtime, dict):
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
if mode in {"browser", "mock"}:
return _runtime_summary(mode)
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower()
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
@@ -1,11 +1,14 @@
"""
services/shipping_notice/rpa_worker_heartbeat.py
services/freight_rpa/common/worker_heartbeat.py
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)、
shipping_notice.receipt_rpa(收料 trigger 目录)。
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload/receipt trigger 前强制就绪检查;
管理端 /rpa-workers/status?scope=inventory|receipt 展示对应 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 目录)、
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
@@ -24,18 +27,25 @@ from flask import current_app
from app.core.config.settings import _normalize_env_name
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.rpa import inventory_trigger_dir, rpa_runtime_mode
from app.services.freight_rpa.onhand.trigger_io import onhand_trigger_dir
from .rpa_runtime import rpa_runtime_mode
logger = logging.getLogger(__name__)
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
INVENTORY_EXPORT_CAPABILITY = "inventory_export"
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
RECEIPT_EXPORT_CAPABILITY = "receipt_export"
# 收料 Worker 由 start_receipt_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-receipt。
RECEIPT_WORKER_ID_SUFFIX = "-receipt"
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换——
# inventory_export→onhand_export、receipt_export→inbound_export;上传能力为 freight_rpa_upload;
# worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。
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]] = {}
@@ -51,8 +61,10 @@ _REASON_USER_HINTS: dict[str, str] = {
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
"trigger_dir_not_writable": "trigger 目录不可写",
"environment_mismatch": "Worker 环境与后端环境不一致",
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力",
"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": "未配置货代上传队列目录",
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
@@ -139,7 +151,7 @@ def shared_scope_id() -> str:
explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "")
if explicit:
return explicit
trigger_dir = inventory_trigger_dir()
trigger_dir = onhand_trigger_dir()
if not trigger_dir:
return ""
for part in Path(trigger_dir).parts:
@@ -362,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 目录。
@@ -400,18 +412,39 @@ 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:
"""
判断心跳是否来自收料 Worker。
判断心跳是否来自 inbound(原收料)Worker。
优先认 <主机名>-receipt(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与收料目录对齐判定。
优先认 <主机名>-inbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与 inbound 目录对齐判定。
"""
if str(worker.get("worker_id") or "").strip().lower().endswith(RECEIPT_WORKER_ID_SUFFIX):
if str(worker.get("worker_id") or "").strip().lower().endswith(INBOUND_WORKER_ID_SUFFIX):
return True
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
expected = receipt_trigger_dir()
expected = inbound_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 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
@@ -437,7 +470,7 @@ def _worker_is_eligible(
backend_env: str,
ttl_seconds: int,
now: float,
required_capability: str = INVENTORY_EXPORT_CAPABILITY,
required_capability: str = ONHAND_EXPORT_CAPABILITY,
) -> tuple[bool, list[str]]:
"""
判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。
@@ -447,7 +480,7 @@ def _worker_is_eligible(
backend_env: 后端归一环境(dev/test/prod)。
ttl_seconds: 心跳 TTL。
now: 当前 epoch 秒。
required_capability: 必选能力(inventory_export / freight_upload)。
required_capability: 必选能力(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。
Returns:
(是否合格, 不合格原因列表)。
@@ -461,10 +494,7 @@ def _worker_is_eligible(
capabilities = _parse_capabilities(worker.get("capabilities"))
if required_capability and required_capability not in capabilities:
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
reasons.append("missing_freight_upload_capability")
else:
reasons.append("missing_inventory_export_capability")
reasons.append(_missing_capability_reason(required_capability))
worker_env = str(worker.get("environment") or "").strip().lower()
if worker_env and worker_env != backend_env:
@@ -477,6 +507,11 @@ def _worker_is_eligible(
return not reasons, reasons
def _missing_capability_reason(required_capability: str) -> str:
"""按必选能力生成缺失原因码(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。"""
return f"missing_{required_capability}_capability"
def _summarize_reasons(reasons: list[str]) -> str:
hints: list[str] = []
for reason in reasons:
@@ -512,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。
@@ -601,7 +636,7 @@ def _check_rpa_worker_ready_for_capability(
message, detail_message = "ready", "ready"
else:
failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
if required_capability == FREIGHT_RPA_UPLOAD_CAPABILITY:
detail = _summarize_reasons(failure.reasons)
message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
detail_message = f"{message}({detail})" if detail else message
@@ -623,41 +658,41 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
"""
return _check_rpa_worker_ready_for_capability(
trigger_dir=inventory_trigger_dir(),
required_capability=INVENTORY_EXPORT_CAPABILITY,
trigger_dir=onhand_trigger_dir(),
required_capability=ONHAND_EXPORT_CAPABILITY,
)
def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
def check_inbound_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
检查入站 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
核心逻辑:仅看收料 Worker 心跳(*-receipt 或 trigger_dir 对齐);要求
receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。
核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求
inbound_export 能力;校验 inbound trigger 目录可写;与 onhand 同口径要求共享哨兵。
"""
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
return _check_rpa_worker_ready_for_capability(
trigger_dir=receipt_trigger_dir(),
required_capability=RECEIPT_EXPORT_CAPABILITY,
worker_predicate=is_receipt_rpa_worker,
trigger_dir=inbound_trigger_dir(),
required_capability=INBOUND_EXPORT_CAPABILITY,
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.shipping_notice.receipt_rpa import receipt_trigger_dir
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'
@@ -677,7 +712,61 @@ def assert_receipt_rpa_worker_ready() -> None:
'detail_message': result.detail_message,
'checked_at': result.checked_at,
'shared_scope_id': shared_scope_id(),
'trigger_dir': str(receipt_trigger_dir() or ''),
'trigger_dir': str(inbound_trigger_dir() or ''),
},
)
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 ''),
},
)
@@ -689,7 +778,7 @@ def _freight_upload_config_reasons() -> list[str]:
Returns:
不合规原因码列表(空表示静态配置通过)。
"""
from app.services.shipping_notice.rpa import upload_queue_dir, upload_trigger_dir
from app.services.freight_rpa.upload.trigger_io import upload_queue_dir, upload_trigger_dir
reasons: list[str] = []
credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "")
@@ -722,16 +811,16 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
检查货代上传 RPA 是否可安全自动触发。
核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与
freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
freight_rpa_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
Returns:
RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。
"""
from app.services.shipping_notice.rpa import upload_trigger_dir
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
return _check_rpa_worker_ready_for_capability(
trigger_dir=upload_trigger_dir(),
required_capability=FREIGHT_UPLOAD_CAPABILITY,
required_capability=FREIGHT_RPA_UPLOAD_CAPABILITY,
extra_reasons=_freight_upload_config_reasons(),
)
@@ -757,7 +846,7 @@ def assert_freight_upload_rpa_ready() -> None:
result.reasons,
result.detail_message,
)
from app.services.shipping_notice.rpa import upload_trigger_dir
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
raise ServiceUnavailableError(
result.message,
@@ -768,7 +857,7 @@ def assert_freight_upload_rpa_ready() -> None:
"checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(),
"trigger_dir": str(upload_trigger_dir() or ""),
"capability": FREIGHT_UPLOAD_CAPABILITY,
"capability": FREIGHT_RPA_UPLOAD_CAPABILITY,
},
)
@@ -836,29 +925,34 @@ def assert_inventory_rpa_worker_ready() -> None:
"detail_message": result.detail_message,
"checked_at": result.checked_at,
"shared_scope_id": shared_scope_id(),
"trigger_dir": str(inventory_trigger_dir() or ""),
"trigger_dir": str(onhand_trigger_dir() or ""),
},
)
def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]:
def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]:
"""
管理端展示:按 scope 返回库存或收料 Worker 心跳摘要。
管理端展示:按 scope 返回在手(onhand)、入站(inbound)或出站(outbound)Worker 心跳摘要。
Args:
scope: inventory(默认)或 receipt。
scope: onhand(默认,库存 RPA 工作台)、inbound(入站)或 outbound(出站);
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识无关。
"""
from app.services.shipping_notice.rpa import upload_trigger_dir
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
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 "inventory").strip().lower()
if normalized == "receipt":
readiness = check_receipt_rpa_worker_ready()
trigger_path = str(receipt_trigger_dir() or "")
normalized = str(scope or "onhand").strip().lower()
if normalized == "inbound":
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(inventory_trigger_dir() or "")
normalized = "inventory"
trigger_path = str(onhand_trigger_dir() or "")
normalized = "onhand"
freight_readiness = check_freight_upload_rpa_ready()
ttl_seconds = _heartbeat_ttl_seconds()
@@ -896,7 +990,7 @@ def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]:
"upload_trigger_dir": str(upload_trigger_dir() or ""),
"reasons": readiness.reasons,
"workers": workers,
"freight_upload": {
"freight_rpa_upload": {
"ready": freight_readiness.ready,
"message": freight_readiness.message,
"detail_message": freight_readiness.detail_message,
@@ -1,8 +1,8 @@
"""
services/shipping_notice/rpa_worker_heartbeat_alert.py
services/freight_rpa/common/worker_heartbeat_alert.py
用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
依赖:同包 worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
逻辑:由 schedule worker 每轮循环调用;默认 ALERT_ENABLED=false 不发送;DB 为告警状态权威源,Redis 仅作缓存同步。
"""
@@ -21,7 +21,7 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.models import AppSetting, User
from app.services.permission_roles.service import list_platform_admin_users
from app.services.shipping_notice.rpa_worker_heartbeat import (
from .worker_heartbeat import (
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
RPA_WORKER_OFFLINE_MESSAGE,
_heartbeat_check_required,
@@ -0,0 +1 @@
"""inbound:入站 RPA。"""
@@ -0,0 +1,219 @@
"""
services/freight_rpa/inbound/report_archive.py
用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
三年保留期、不写库存快照表)与到期对象清理(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
(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
FREIGHT_RPA.SINK_NOT_REGISTERED;同一 unit_run_id + sha256 已有文件时不插第二行、
仍投递 ok=True 的事实供处理函数重试。业务收尾(推进在途调拨来源任务、调拨证据
同步、排程终态归集)改由 Task 7 的处理函数(handle_inbound_report 等)承担,
本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa。
"""
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 (
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
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
def _read_inbound_callback_file(file_path: str) -> bytes:
"""只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...),
Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史
载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。
"""
configured_root = str(inbound_drop_dir() or '').strip()
if not configured_root:
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
path = (root / name).resolve()
try:
path.relative_to(root)
except ValueError as 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('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('inbound callback file exceeds configured size limit', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
return path.read_bytes()
def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
"""幂等接收单个 inbound 单元回调,原样归档三年且不写库存快照表。
Args:
payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。
Returns:
dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。
Raises:
ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。
NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。
AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。
业务顺序(Task 6 契约):每个终态分支先 db.session.commit() 再构造
ReportFact(report_kind='inbound', source_code=unit.source_code, ...) 调
dispatch_report_fact;事实恒带 unit_run_id=unit.id(Task 7 修复轮 2——
含 failure/empty 与幂等重放,处理函数据此精确定位本单元的排程 run);
处理函数异常原样外抛(不吞、不回滚已提交终态);
同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实
(供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。
"""
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
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('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_inbound_data。
unit.status = 'empty'
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='inbound-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},
)
# [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
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_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.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='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},
)
# [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
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, error_message=unit.error_message,
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': 'failed'}
data = _read_inbound_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('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),供处理函数重试;
# unit_run_id 自单元行回填(Task 7 修复轮 2)。
dispatch_report_fact(ReportFact(
report_kind='inbound', 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 'receipt.xlsx')).name
storage_key = f'shipping/receipt-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 = FreightRpaInboundReportFile(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_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()
dispatch_report_fact(ReportFact(
report_kind='inbound', 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}
def run_freight_rpa_inbound_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 = FreightRpaInboundReportFile.query.filter(
FreightRpaInboundReportFile.archive_expires_at.is_not(None),
FreightRpaInboundReportFile.archive_expires_at <= now,
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
).order_by(FreightRpaInboundReportFile.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_inbound_report_archive_deleted', aggregate_type='shipping_inbound_file',
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': 'inbound_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_inbound_report_archive_delete_attempted', aggregate_type='shipping_inbound_file',
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': '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': 'inbound_retention', 'status': 'completed'}]
@@ -0,0 +1,93 @@
"""
services/freight_rpa/inbound/trigger_io.py
用途:inbound(入站,原收料)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_inbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
in_transit_transfer.inbound_trigger_service(调拨按需/批量触发)、
freight_rpa.common.worker_heartbeat(inbound trigger 目录探测/就绪检查)、
freight_rpa.inbound.report_archive(drop 目录定位与回调 SCHEMA 校验,Task 10 下沉)等调用,
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
(Worker 侧 Task 12 对表:freight_rpa.inbound.v1 / inbound_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 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
# (旧 receipt 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
SCHEMA = "freight_rpa.inbound.v1"
ACTION_INBOUND_EXPORT_BATCH = "inbound_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 inbound_trigger_dir() -> Path | None:
"""RPA inbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR);
绝不回落到 onhand trigger 目录。"""
return _path("FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR")
def inbound_drop_dir() -> Path | None:
"""RPA inbound 导出文件落盘目录(FREIGHT_RPA_SHARED_INBOUND_DROP_DIR)。"""
return _path("FREIGHT_RPA_SHARED_INBOUND_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_inbound_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
"""
写入 inbound 批量 trigger 文件 inbound_export_batch_{run_no}.json
([PROMPT_UPDATE] 2026-10-16 批次 R:文件名前缀随 Worker 侧 Task 12 一起由
receipt_export_batch_* 切换为 inbound_export_batch_*;Worker 轮询 <root>/*.json
按内容消费,schema/action 取本文件常量新值)。
Args:
run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。
units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。
payload: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。
Returns:
str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。
"""
trigger_dir = inbound_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 'inbound'
body = {
'schema_version': SCHEMA, 'action': ACTION_INBOUND_EXPORT_BATCH,
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
**(payload or {}),
}
path = trigger_dir / f'inbound_export_batch_{safe_run_no}.json'
_write_trigger_json_atomic(path, body)
return str(path)
@@ -0,0 +1 @@
"""onhand:在手库存 RPA。"""
@@ -1,9 +1,11 @@
"""
services/shipping_notice/rpa_attempts.py
services/freight_rpa/onhand/attempts.py
用途:统计任务的 RPA 库存导出与货代上传重试次数,并返回统一上限。
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑。
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,决定是否还能继续触发 RPA 重试。
用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。
逻辑:由 shipping_notice 的 onhand_rpa_workflow、fulfillment_workflow 等模块调用本文件,
决定是否还能继续触发 RPA 重试;事件类型字符串(onhand_rpa_* 等)是落库数据值,
随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。
"""
from __future__ import annotations
@@ -15,15 +17,15 @@ from app.models import ShippingNotice, ShippingTaskEvent
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
_INVENTORY_SUCCESS_EVENTS = {
_ONHAND_SUCCESS_EVENTS = {
"inventory_uploaded",
"inventory_parsed",
"inventory_rpa_drop_ingested",
"inventory_rpa_ready",
"onhand_rpa_drop_ingested",
"onhand_rpa_ready",
"inventory_template_mapping_used",
}
_INVENTORY_ATTEMPT_RESET_EVENTS = _INVENTORY_SUCCESS_EVENTS | {
_ONHAND_ATTEMPT_RESET_EVENTS = _ONHAND_SUCCESS_EVENTS | {
"decision_retry_rpa",
}
@@ -33,24 +35,24 @@ _UPLOAD_SUCCESS_EVENTS = {
}
def inventory_rpa_attempts(task: ShippingNotice | None) -> int:
def onhand_rpa_attempts(task: ShippingNotice | None) -> int:
"""统计自上次库存成功事件以来的 RPA 库存导出触发/失败次数。"""
if not task or task.id is None:
return 0
last_reset = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_ATTEMPT_RESET_EVENTS))
.filter(ShippingTaskEvent.event_type.in_(_ONHAND_ATTEMPT_RESET_EVENTS))
.order_by(ShippingTaskEvent.id.desc())
.first()
)
since: datetime | None = last_reset.created_at if last_reset else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
ShippingTaskEvent.event_type == "onhand_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_failed"
ShippingTaskEvent.event_type == "onhand_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
@@ -1,9 +1,11 @@
"""
services/shipping_notice/inventory_rpa_callback_cleanup.py
services/freight_rpa/onhand/callback_cleanup.py
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。
依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。
逻辑:commit 后尝试归档;失败则移入 .hxops_quarantine 并入队;scheduler/worker 启动时定期消费队列。
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记
(Task 9 自 shipping_notice.onhand_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
依赖:freight_rpa.onhand.trigger_io(onhand_drop_dir / onhand_processed_dir)、json、uuid、Flask current_app。
逻辑:commit 后由 shipping_notice 业务 sink 调用尝试归档;失败则移入 .hxops_quarantine 并入队;
scheduler/worker 启动时定期消费队列。
"""
from __future__ import annotations
@@ -18,7 +20,7 @@ from typing import Any
from flask import current_app
from app.services.shipping_notice.rpa import inventory_drop_dir, inventory_processed_dir
from app.services.freight_rpa.onhand.trigger_io import onhand_drop_dir, onhand_processed_dir
_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed"
_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
@@ -30,7 +32,7 @@ _LOGGER = logging.getLogger(__name__)
def callback_cleanup_queue_dir() -> Path | None:
"""drop 目录下 callback 归档重试队列路径。"""
drop = inventory_drop_dir()
drop = onhand_drop_dir()
if not drop:
return None
return drop / _CLEANUP_QUEUE_DIRNAME
@@ -38,7 +40,7 @@ def callback_cleanup_queue_dir() -> Path | None:
def callback_cleanup_failed_dir() -> Path | None:
"""超过最大重试次数的 cleanup job 隔离目录。"""
drop = inventory_drop_dir()
drop = onhand_drop_dir()
if not drop:
return None
return drop / _CLEANUP_FAILED_DIRNAME
@@ -49,7 +51,7 @@ def callback_quarantine_dir() -> Path | None:
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
"""
drop = inventory_drop_dir()
drop = onhand_drop_dir()
if not drop:
return None
return drop / _QUARANTINE_DIRNAME
@@ -243,7 +245,7 @@ def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]:
callback_raw = str(payload.get("callback_path") or "").strip()
processed_raw = str(payload.get("processed_dir") or "").strip()
callback_path = Path(callback_raw) if callback_raw else None
processed_dir = Path(processed_raw) if processed_raw else inventory_processed_dir()
processed_dir = Path(processed_raw) if processed_raw else onhand_processed_dir()
if callback_path is None or processed_dir is None:
try:
job_path.unlink()
@@ -0,0 +1,84 @@
"""freight_rpa/onhand/report_store.py
用途:freight_rpa_onhand_report_files 的写入唯一入口(阶段 B Task 5)——发货域
(shipping_notice)与调度等其他消费方不得自行构造 FreightRpaOnhandReportFile 行,
插入/按主键更新统一经本模块收敛,保证报表事实写入只发生在货代 RPA 域。
依赖:app.db、app.models.FreightRpaOnhandReportFile、app.core.errors.NotFoundError。
逻辑:insert_onhand_report 接收与 FreightRpaOnhandReportFile 列同名的关键字参数
(storage_path、file_sha256、onhand_lines_json、field_mapping_json、
snapshot_status、warehouse_id、source_code、rpa_run_no 等),flush 后
返回 file_id;update_onhand_report 按主键更新给定列。两者都【只 flush 不
commit】——事务提交时机归属调用方;两者都【不创建任务关联】——
shipping_task_onhand_links 等 link 表归发货域,由调用方自行维护。
【禁止】import app.services.shipping_notice / in_transit_transfer(import
方向只能反过来,边界由 tests/services/shipping_notice/
test_report_model_boundary.py 锁定)。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import NotFoundError
from app.models import FreightRpaOnhandReportFile
def insert_onhand_report(**columns: Any) -> int:
"""插入 freight_rpa_onhand_report_files 一行并 flush。返回 file_id。不创建任务关联,不 commit。
【AI 触发时机】:任何需要新增在手/库存快照文件记录的场景
(RPA 回调入快照、人工上传保存、空快照记录)须调用本函数,禁止在
shipping_notice 域内直接构造 FreightRpaOnhandReportFile 行。
核心逻辑:[STEP 1] 以与模型列同名的关键字参数构造行;
[STEP 2] db.session.add + flush(拿到自增主键且同事务内可见);
[STEP 3] 返回 int 主键,供调用方按需经 db.session.get 取回 ORM 对象。
Args:
**columns: FreightRpaOnhandReportFile 的任意合法列关键字(禁止传入不存在的
列名,非法列名会在构造时抛 TypeError)。无默认值语义变化——
列默认值仍由模型定义(default=)承担。
Returns:
新插入行的 file_id(int)。
Raises:
TypeError: 传入了模型不存在的列关键字。
sqlalchemy.exc.IntegrityError: 唯一约束(如 onhand_file_no / RPA 幂等索引)
冲突,由调用方决定 savepoint 回滚或复用既有行。
"""
row = FreightRpaOnhandReportFile(**columns)
db.session.add(row)
db.session.flush()
return int(row.id)
def update_onhand_report(file_id: int, **columns: Any) -> None:
"""按 file_id 更新该行的给定列并 flush。不 commit。
【AI 触发时机】:快照过期(snapshot_status→expired)、批次同身份改写
share_mode、identity_status 回填等针对既有在手报表行的列更新场景。
核心逻辑:[STEP 1] 按主键取行(命中身份缓存即为同一 ORM 对象,调用方
持有的引用会同步可见更新),缺失抛 NotFoundError(fail-closed,禁止静默
吞掉错配);[STEP 2] 逐列 setattr;[STEP 3] flush。【不 commit】——
事务归属调用方;【不动任务关联】——link 表更新归发货域。
Args:
file_id: freight_rpa_onhand_report_files 主键(int;禁止传入非整数 ID)。
**columns: 要更新的列名与取值(禁止传入模型不存在的列名)。
Raises:
NotFoundError: file_id 对应的行不存在。
TypeError: 传入了模型不存在的列关键字。
"""
row = db.session.get(FreightRpaOnhandReportFile, file_id)
if row is None:
raise NotFoundError(
f"Onhand report file not found: {file_id}",
details={'file_id': file_id},
)
for key, value in columns.items():
setattr(row, key, value)
db.session.flush()
@@ -0,0 +1,108 @@
"""
services/freight_rpa/onhand/trigger_io.py
用途:onhand(在手库存)RPA 的纯文件 IO——trigger/落盘目录解析、trigger JSON 原子写、
单任务导出 trigger 写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、onhand_rpa_workflow(回调 schema 校验)、
per_source_rpa_service(回调 schema 校验)、freight_rpa.common.worker_heartbeat(目录探测)等调用,
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
(Worker 侧 Task 12 对表:freight_rpa.onhand.v1 / onhand_export / onhand_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 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
# (旧 inventory 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
SCHEMA = "freight_rpa.onhand.v1"
ACTION_ONHAND_EXPORT = "onhand_export"
ACTION_ONHAND_EXPORT_BATCH = "onhand_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 onhand_drop_dir() -> Path | None:
"""RPA onhand 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_ONHAND_DROP_DIR)。"""
return _path("FREIGHT_RPA_SHARED_ONHAND_DROP_DIR")
def onhand_processed_dir() -> Path | None:
"""已处理 onhand 文件归档子目录(drop_dir/processed)。"""
base = onhand_drop_dir()
if not base:
return None
return base / "processed"
def onhand_trigger_dir() -> Path | None:
"""RPA onhand 导出触发 JSON 目录(FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR)。"""
return _path("FREIGHT_RPA_SHARED_ONHAND_TRIGGER_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_onhand_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
"""
写入 RPA onhand 导出触发文件 inventory_export_{task_no}.json
(文件名沿用既有 Worker 契约,仅 action 取新值 ACTION_ONHAND_EXPORT)。
Returns:
str | None: 触发文件绝对路径;目录未配置时返回 None。
"""
trigger_dir = onhand_trigger_dir()
if not trigger_dir:
return None
trigger_dir.mkdir(parents=True, exist_ok=True)
body = {
"action": ACTION_ONHAND_EXPORT,
"task_no": task_no,
"run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}",
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
path = trigger_dir / f"inventory_export_{task_no}.json"
_write_trigger_json_atomic(path, body)
return str(path)
# TODO(批次S): 全仓零调用,死代码候选,收敛时删除
def find_latest_inventory_file() -> Path | None:
"""在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。"""
drop = onhand_drop_dir()
if not drop or not drop.is_dir():
return None
candidates = [
p for p in drop.iterdir()
if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"}
]
if not candidates:
return None
return max(candidates, key=lambda p: p.stat().st_mtime)
@@ -0,0 +1,349 @@
"""
services/freight_rpa/onhand/workflow_protocol.py
用途:onhand(在手库存)RPA 回调协议态——attempt 行记账、run_no 幂等键、轮次校验、
排程进度记账与超时窗口判定的纯协议层。
依赖:app.models(ShippingTaskEvent / FreightRpaOnhandTaskAttempt / ScheduleRun)、
app.extensions.db、freight_rpa.onhand 包内模块;**禁止 import 任何
shipping_notice 业务模块**(import 边界由 tests/services/freight_rpa/test_import_boundary.py
AST 全包扫描锁死,含函数内延迟 import)。
逻辑:Task 9 拆分自 shipping_notice.onhand_rpa_workflow——回调进入
/api/freight-rpa/* 蓝图后,业务 sink(shipping_notice.rpa_sinks 注册)在原事务内
调用本模块完成协议记账(不改变 commit 时机),再由域内业务函数做快照落盘/
门禁推进/审计投影;快照、Gate、状态机等业务终态一律留在 shipping_notice。
"""
from __future__ import annotations
import json
from datetime import datetime
from pathlib import Path
from typing import Any
from app.extensions import db
from app.models import ScheduleRun, ShippingTaskEvent, FreightRpaOnhandTaskAttempt
def latest_task_event(task: Any, event_type: str) -> ShippingTaskEvent | None:
"""返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试/轮次校验用)。"""
if task.id is None:
return None
return (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
.order_by(ShippingTaskEvent.id.desc())
.first()
)
def extract_run_no_from_trigger(trigger_path: str | None) -> str:
"""从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 单票均支持)。"""
path = Path(str(trigger_path or ""))
name = path.name
prefix = "inventory_export_batch_"
if name.startswith(prefix) and name.endswith(".json"):
return name[len(prefix) : -len(".json")]
if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file():
try:
payload = json.loads(path.read_text(encoding="utf-8"))
if isinstance(payload, dict):
run_no = str(payload.get("run_no") or "").strip()
if run_no:
return run_no
except (OSError, json.JSONDecodeError, TypeError, ValueError):
pass
return ""
def is_legacy_trigger_run_no(run_no: str) -> bool:
"""判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传 run_no)。"""
return str(run_no or "").strip().upper().startswith("LEGACY-")
def expected_rpa_callback_run_no(task: Any) -> str:
"""读取任务最近一次 RPA 触发记录的 run_no(事件 detail 优先,缺失回退 trigger 文件)。"""
last_trigger = latest_task_event(task, "onhand_rpa_triggered")
if not last_trigger:
return ""
detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {}
run_no = str(detail.get("run_no") or "").strip()
if run_no:
return run_no
return extract_run_no_from_trigger(str(detail.get("trigger") or ""))
def validate_rpa_callback_run_no(task: Any, callback_run_no: str) -> str | None:
"""校验回调 run_no 属于当前任务最近一次有效触发轮次。
Returns:
None 校验通过;否则返回拒绝原因码(no_active_trigger / run_no_missing / run_no_mismatch)。
"""
provided = str(callback_run_no or "").strip()
expected = expected_rpa_callback_run_no(task)
if not expected:
return "no_active_trigger"
if not provided:
if is_legacy_trigger_run_no(expected):
return None
return "run_no_missing"
if provided != expected:
return "run_no_mismatch"
return None
def resolve_effective_callback_run_no(task: Any, payload: dict[str, Any]) -> str:
"""解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。"""
provided = str(payload.get("run_no") or "").strip()
if provided:
return provided
return expected_rpa_callback_run_no(task)
def get_consumed_inventory_rpa_run_no(task: Any) -> str:
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
attempt = (
FreightRpaOnhandTaskAttempt.query
.filter_by(task_no=str(task.task_no or ''), status='consumed')
.order_by(FreightRpaOnhandTaskAttempt.consumed_at.desc(), FreightRpaOnhandTaskAttempt.id.desc())
.first()
)
return str(getattr(attempt, 'source_run_no', '') or '').strip()
def mark_inventory_rpa_run_no_consumed(task: Any, run_no: str) -> None:
"""[协议记账] 标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。
核心逻辑:只改 Attempt 行(status/consumed_at),不 commit——commit 时机由调用方
业务事务决定,与拆分前行为一致。
"""
effective = str(run_no or "").strip()
if not effective:
return
attempt = (
FreightRpaOnhandTaskAttempt.query
.filter_by(task_no=str(task.task_no or ''), source_run_no=effective)
.one_or_none()
)
if attempt is not None:
attempt.status = 'consumed'
attempt.consumed_at = datetime.utcnow()
def validate_rpa_callback_not_replayed(task: Any, run_no: str) -> str | None:
"""拒绝同一 run_no 的重复成功/失败/跳过回调。
Returns:
None 允许处理;"run_no_already_consumed" 表示重放,应拒绝。
"""
effective = str(run_no or "").strip()
consumed = get_consumed_inventory_rpa_run_no(task)
if effective and consumed and effective == consumed:
return "run_no_already_consumed"
return None
def validate_schedule_batch_callback_run_no(
schedule_run_id: int | None,
callback_run_no: str,
*,
require_awaiting: bool = True,
) -> str | None:
"""校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。
Args:
schedule_run_id: 排程 run 主键;None 表示非排程回调,直接通过。
callback_run_no: Worker 上报的 batch_run_no / run_no。
require_awaiting: True(进度/收件终态)要求仍处于 awaiting_rpa;
False(解析 Job)只校验身份,允许排程已按「文件返回」终态化。
Returns:
None 校验通过;否则返回拒绝原因码(schedule_run_not_found / schedule_run_no_missing /
schedule_run_no_mismatch / schedule_run_not_awaiting)。
"""
if schedule_run_id is None:
return None
run = db.session.get(ScheduleRun, schedule_run_id)
if not run:
return "schedule_run_not_found"
expected = str(run.run_no or "").strip()
provided = str(callback_run_no or "").strip()
if not expected:
return "schedule_run_no_missing"
if provided != expected:
return "schedule_run_no_mismatch"
if not require_awaiting:
return None
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if run.status != "running" or not summary.get("awaiting_rpa"):
return "schedule_run_not_awaiting"
return None
def record_onhand_batch_progress(
run: ScheduleRun,
run_no: str,
*,
success_count: int,
skipped_count: int,
failed_count: int,
) -> dict[str, Any]:
"""[协议记账] 排程批量导出进度回写:max(现有, 上报) 防乱序回退,写后即 commit。
【AI 触发时机】:onhand-batch-progress 业务 sink 已完成 schema/run 校验后调用;
非终态记账(不修改 status/started_at/finished_at,终态仍以 batch-ready 为准)。
Args:
run: 已确认存在且处于 awaiting_rpa 的 ScheduleRun 行。
run_no: 批次 run_no,写入 response_summary_json.progress 供审计。
success_count / skipped_count / failed_count: 已按 max(0, int(x)) 归一的非负计数。
Returns:
dict: 提交后的最终计数 {'success_count','skipped_count','failed_count','run_no'};
供业务层拼装响应,键值与拆分前响应逐字一致。
"""
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)
summary = dict(run.response_summary_json or {})
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': run_no,
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
# commit 时机与拆分前 onhand_rpa_workflow.report_inventory_batch_progress 完全一致:
# 校验通过、计数写完后立即提交,再由业务层构造响应。
db.session.commit()
return {
'run_no': run_no,
'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 compute_rpa_wait_window(
triggered_at: datetime,
timeout_seconds: int,
*,
now: datetime | None = None,
) -> tuple[int, int, int]:
"""计算库存 RPA 等待窗口(elapsed / timeout / remaining 秒)。
【AI 触发时机】:业务层已确认任务处于 RPA 等待态、需要判断是否超时或调度复查时调用。
Args:
triggered_at: 最近一次 onhand_rpa_triggered 事件的 created_at。
timeout_seconds: 超时阈值秒数(由业务层 tool_common 读取配置)。
now: 可注入当前时间(测试用);缺省 utcnow。
Returns:
tuple[int, int, int]: (elapsed_seconds, timeout_seconds, remaining_seconds);
elapsed 向下取整且不为负,remaining 不为负。
"""
current = now or datetime.utcnow()
elapsed = max(int((current - triggered_at).total_seconds()), 0)
remaining = max(int(timeout_seconds) - elapsed, 0)
return elapsed, int(timeout_seconds), remaining
def resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None:
"""将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。
Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``,
Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。
安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。
Returns:
Path | None: 解析成功且确为 allowed_root 下存在文件时返回绝对路径;否则 None。
"""
text = str(raw_path or '').strip()
if not text:
return None
try:
root = allowed_root.resolve()
except OSError:
return None
candidate = Path(text)
try:
resolved = candidate.resolve()
if resolved.is_file():
resolved.relative_to(root)
return resolved
except (OSError, ValueError, RuntimeError):
pass
name = Path(text.replace('\\', '/')).name.strip()
if not name or name in {'.', '..'} or '/' in name or '\\' in name:
return None
mapped = (root / name).resolve()
try:
mapped.relative_to(root)
except ValueError:
return None
if mapped.is_file():
return mapped
return None
def normalize_inventory_result_status(payload: dict[str, Any]) -> str:
"""归一化单任务 RPA 库存回调结果。
核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段;
缺省 success 视为 true(历史单任务回调兼容)。
Returns:
str: success | skipped | failed
"""
raw_status = str(payload.get("status") or "").strip().lower()
if raw_status in {"success", "skipped", "failed"}:
return raw_status
if payload.get("skipped"):
return "skipped"
if bool(payload.get("success", True)):
return "success"
return "failed"
def normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
"""归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。
核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或
缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。
Returns:
str: success | skipped | failed
"""
raw_status = str(item.get("status") or "").strip().lower()
if raw_status in {"success", "skipped", "failed"}:
return raw_status
if item.get("skipped"):
return "skipped"
if item.get("success") is True:
return "success"
return "failed"
def merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
"""合并 batch 顶层契约字段到 result item。
核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由
Worker item 显式返回,禁止后端从任务或数据库补齐。
Returns:
dict: 合并后的 item 副本(不修改入参)。
"""
merged = dict(item)
top_schema_version = str(payload.get('schema_version') or '').strip()
if top_schema_version and not str(merged.get('schema_version') or '').strip():
merged['schema_version'] = top_schema_version
top_run_no = str(payload.get("run_no") or "").strip()
if top_run_no and not str(merged.get("run_no") or "").strip():
merged["run_no"] = top_run_no
task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip()
if task_no and not str(merged.get("task_no") or "").strip():
merged["task_no"] = task_no
return merged
@@ -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/inventory_parsing_profile.py
services/freight_rpa/parsing_profile.py
用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。
依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_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
@@ -18,47 +25,49 @@ from sqlalchemy import func
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
ShippingInventoryField,
ShippingInventoryParsingProfile,
ShippingInventorySource,
ShippingInventoryStructureAnalysis,
FreightRpaOnhandField,
FreightRpaOnhandReportConfig,
FreightRpaParsingProfile,
FreightRpaOnhandStructureAnalysis,
ShippingOrderField,
FreightRpaInboundReportConfig,
FreightRpaOutboundReportConfig,
)
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
field_ids: list[int] = []
for raw_id in field_mapping:
try:
field_id = int(raw_id)
except (TypeError, ValueError) as exc:
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') from exc
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') from exc
if field_id <= 0:
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
field_ids.append(field_id)
rows = ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(set(field_ids))).all() if field_ids else []
rows = FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(set(field_ids))).all() if field_ids else []
fields = {str(row.id): row for row in rows if row.status == 'active'}
if len(fields) != len(set(str(item) for item in field_ids)):
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
return fields
def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> set[str]:
def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set[str]:
"""校验解析方案具备匹配与库存数量能力,不限定字段名称。"""
match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'}
quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'}
if not match_ids or len(quantity_ids) != 1:
raise ValidationError(
'Parsing profile requires at least one match field and exactly one inventory quantity field',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
return match_ids | quantity_ids
# 异动(movement)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
# 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
"""校验 movement 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
"""校验 inbound/outbound 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
movement_codes = {field.code for field in MOVEMENT_FIELDS}
@@ -68,37 +77,37 @@ def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
if unknown:
raise ValidationError(
f'Movement parsing profile references unknown field: {sorted(unknown)}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
if missing:
raise ValidationError(
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
return mapped_codes
def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, Any]:
def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]:
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。
Args:
raw: 解析定义对象。
purpose: 'inventory'(沿用库存字段目录与 match_keys)或
'movement'(端点用定死 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.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
field_mapping = raw.get('field_mapping')
if not isinstance(field_mapping, dict) or not field_mapping:
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if any(not str(value or '').strip() for value in field_mapping.values()):
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
header_row_index = raw.get('header_row_index')
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if purpose == 'movement':
if purpose in {'inbound', 'outbound'}:
_required_movement_field_ids(raw)
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
@@ -111,7 +120,7 @@ def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, A
_required_catalog_field_ids(catalog_fields)
match_keys = raw.get('match_keys')
if not isinstance(match_keys, list) or not match_keys:
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
normalized_keys: list[dict[str, str]] = []
seen_order_fields: set[str] = set()
seen_inventory_fields: set[str] = set()
@@ -123,9 +132,9 @@ def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, A
field is None or field.status != 'active' or field.scope != 'line'
or inventory is None or inventory.usage_type != 'match_identity'
):
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if field.id in seen_order_fields or inventory_field in seen_inventory_fields:
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
seen_order_fields.add(field.id)
seen_inventory_fields.add(inventory_field)
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
@@ -142,20 +151,20 @@ def _require_sample_evidence(
definition: dict[str, Any],
*,
file_format: str,
) -> ShippingInventoryStructureAnalysis:
) -> FreightRpaOnhandStructureAnalysis:
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
try:
analysis_id = int(sample_analysis_id)
except (TypeError, ValueError) as exc:
raise ValidationError(
'Parsing profile requires sample analysis evidence',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
) from exc
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format:
raise ValidationError(
'Parsing profile sample analysis evidence is unavailable',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
)
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
@@ -165,13 +174,13 @@ def _require_sample_evidence(
if not isinstance(selected, dict):
raise ValidationError(
'Parsing profile worksheet or header row is not present in sample evidence',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
)
headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()}
if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()):
raise ValidationError(
'Parsing profile mapping is not present in sample evidence',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
)
duplicates = {
str(column.get('header') or '').strip()
@@ -180,12 +189,12 @@ def _require_sample_evidence(
if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()):
raise ValidationError(
'Parsing profile mapping uses duplicate sample headers',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
)
return analysis
def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]:
"""序列化解析 Profile 管理 DTO。"""
sample_analysis = profile.sample_analysis
return {
@@ -211,49 +220,49 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
def list_profiles() -> list[dict[str, Any]]:
"""列出全部解析 Profile 版本。"""
return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by(
ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(),
return [payload(item) for item in FreightRpaParsingProfile.query.order_by(
FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.version.desc(),
).all()]
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
"""创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None
profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile_id else None
if profile_id and profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile is not None and profile.status != 'draft':
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
code = str(data.get('profile_code') or '').strip().upper()
if not code:
raise ValidationError('profile_code is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('profile_code is required', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if profile is not None and code != profile.profile_code:
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
if profile is None:
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
db.session.add(profile)
purpose = str(data.get('purpose') or profile.purpose or 'inventory').strip().lower()
if purpose not in {'inventory', 'movement'}:
raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower()
if purpose not in {'onhand', 'inbound', 'outbound'}:
raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if profile_id and purpose != profile.purpose:
raise ValidationError(
'Draft parsing profile purpose is immutable',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
profile.purpose = purpose
profile.display_name = str(data.get('display_name') or code).strip()
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('file_format is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if profile_id and requested_file_format != profile.file_format:
raise ValidationError(
'Draft parsing profile file format is immutable',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
profile.file_format = requested_file_format
definition = _validate_definition(data.get('definition'), purpose=purpose)
if profile.file_format == 'csv' and definition.get('sheet_name'):
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
sample_analysis = _require_sample_evidence(
data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format,
)
@@ -261,7 +270,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
if not bool(data.get('confirm_sample_replacement')):
raise ValidationError(
'Replacing inventory sample evidence requires confirmation',
code='SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
code='SHIPPING.ONHAND_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
)
history = list(profile.sample_evidence_history_json or [])
history.append({
@@ -279,23 +288,23 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID')
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID')
_require_sample_evidence(
profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
# movement 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;inventory 维持原约束。
# 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 != 'movement':
if profile.purpose == 'onhand':
published_field_ids = {
str(item.get('field_id') or '')
for item in order_schema_service.get_published_contract().get('fields', [])
@@ -303,7 +312,7 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
raise ValidationError(
'Parsing profile match keys must reference the current published order schema',
code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID',
code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID',
)
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
profile.checksum = hashlib.sha256(encoded).hexdigest()
@@ -315,14 +324,20 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
def retire(profile_id: int) -> dict[str, Any]:
"""退役无库存源引用的 published Profile,避免使现有 Source 静默失效。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
"""退役无库存源/入站/出站报表配置引用的 published Profile,避免使现有绑定静默失效。"""
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'published':
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID')
if ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count():
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED')
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID')
# s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。
bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
# 入站/出站报表配置同样绑定解析 Profile:退役前必须一并核查,
# 否则入站/出站文件解析链会静默失去规则。
bound_inbound_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
bound_outbound_configs = FreightRpaOutboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
if bound_sources or bound_inbound_configs or bound_outbound_configs:
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED')
profile.status = 'retired'
db.session.commit()
return payload(profile)
@@ -330,18 +345,20 @@ def retire(profile_id: int) -> dict[str, Any]:
def delete_draft(profile_id: int) -> None:
"""删除从未发布的解析 Profile 草稿。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.INVENTORY_PARSING_PROFILE_DELETE_BLOCKED')
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.ONHAND_PARSING_PROFILE_DELETE_BLOCKED')
db.session.delete(profile)
db.session.commit()
def require_source_profile(source: Any) -> ShippingInventoryParsingProfile:
def require_source_profile(source: Any) -> FreightRpaParsingProfile:
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
profile = getattr(source, 'parsing_profile', None)
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
config = getattr(source, 'onhand_report_config', None)
profile = config.parsing_profile if config is not None else None
if profile is None or profile.status != 'published':
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
return profile
@@ -0,0 +1,51 @@
"""freight_rpa/reports/__init__.py
用途:报表读域——发货(shipping_notice 域)与在途调拨
(in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包(含出站配置视图)。
依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。
逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice)
一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。
本包不得 import app.services.shipping_notice 或 app.services.in_transit_transfer
(import 边界由 tests/services/freight_rpa/test_report_queries.py 与
test_import_boundary.py 锁定)。
"""
from app.services.freight_rpa.reports.facts import REPORT_KINDS, ReportFact, require_report_kind
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,
)
__all__ = [
'REPORT_KINDS',
'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',
'usable_inbound_file_condition',
]
@@ -0,0 +1,79 @@
"""freight_rpa/reports/dispatch.py
用途:报表事实(ReportFact)处理函数注册表与分发缝——RPA 回调「先 commit
终态、再投递事实」的第二段分发(批次 B Task 6)。
依赖:app.core.errors.AppError、freight_rpa.reports.facts(ReportFact、
require_report_kind)。
逻辑:组合根(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.
SINK_NOT_REGISTERED,与 common.callback_sinks.dispatch_sink 同码),
绝不静默吞事实;处理函数异常原样向外抛(供 Worker/上层重试整笔回调)。
本模块不 commit、不 rollback。
"""
from __future__ import annotations
from typing import Callable
from app.core.errors import AppError
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
# 报表事实处理函数契约:接收单个 ReportFact,返回 None;
# 异常由调用方外抛重试,处理函数内部禁止自行吞异常。
Handler = Callable[[ReportFact], None]
# kind → 处理函数注册表(模块级单例;同 kind 重复注册为覆盖)。
_REPORT_HANDLERS: dict[str, Handler] = {}
def register_report_handler(report_kind: str, handler: Handler) -> None:
"""
注册一个报表事实处理函数(由组合根在应用启动时调用)。
【AI 触发时机】:组合根装配(register_onhand_sinks / register_inbound_sinks /
register_outbound_sinks)时调用;测试直接调用注入临时处理函数。
核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound /
outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。
Args:
report_kind: 报表种类字符串(必须在 REPORT_KINDS 白名单内)。
handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用,
不校验其内部行为。
Raises:
ValidationError: report_kind 不在白名单(code=SHIPPING.INBOUND_CALLBACK_INVALID)。
"""
kind = require_report_kind(report_kind)
_REPORT_HANDLERS[kind] = handler
def dispatch_report_fact(fact: ReportFact) -> None:
"""
把已随终态 commit 的报表事实投递给对应 kind 的处理函数。
【AI 触发时机】:归档入口(如 ingest_inbound_callback)在每个终态
db.session.commit() 之后调用;禁止用于 commit 之前的路径(非法载荷 /
单元不存在 / 落库失败均不得投递)。
核心逻辑:kind 经 require_report_kind 校验后查注册表;命中即调用处理函数,
其异常原样向外抛(不包日志、不吞);未注册抛
AppError(code='FREIGHT_RPA.SINK_NOT_REGISTERED', http_status=404)。
本函数不 commit、不 rollback。
Args:
fact: 终态已落库后构造好的报表事实(report_kind/source_code/file_id/
sha256/ok/error_code/error_message)。
Raises:
ValidationError: fact.report_kind 不在白名单。
AppError: kind 未注册处理函数(404;归档终态已提交不回滚,
Worker 重试整笔回调即可补投递)。
"""
kind = require_report_kind(fact.report_kind)
handler = _REPORT_HANDLERS.get(kind)
if handler is None:
raise AppError(
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
message=f'No report handler registered for kind: {kind}',
http_status=404,
)
handler(fact)
@@ -0,0 +1,71 @@
"""freight_rpa/reports/facts.py
用途:定义跨域报表「事实」的传输契约——report kind 白名单与 ReportFact。
依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。
逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作;
report kind 只认 onhand / inbound / outbound,非法值抛
ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),
与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。
本模块不 import shipping_notice / in_transit_transfer。
【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递
必从单元行回填,供消费方处理函数精确定位本次回调收尾的执行单元。
"""
from __future__ import annotations
from dataclasses import dataclass
from app.core.errors import ValidationError
# 【AI 触发时机】AI 或调用方在构造 ReportFact / 分发报表回调前必须先用
# require_report_kind 归一化校验 kind;白名单之外的取值一律拒绝。
REPORT_KINDS = ('onhand', 'inbound', 'outbound')
# 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码,
# 避免为同一类入参错误分裂出多个近义 code。
_INVALID_KIND_ERROR_CODE = 'SHIPPING.INBOUND_CALLBACK_INVALID'
@dataclass(frozen=True)
class ReportFact:
"""一份回报表的事实行(跨域只读传输对象)。
用途:RPA 回调归档后,由 freight_rpa 域产生、发货/调拨域消费的最小事实快照;
ok=False 时 error_code/error_message 描述失败原因。
约束:frozen 不可变;file_id/sha256 允许 None(抓取失败时无产物可指);
unit_run_id 为归档入口回填的执行单元主键(Task 7 修复轮 2 起每次投递
必带——处理函数据此精确定位「本次回调收尾的单元」,禁止按来源猜最新),
允许 None 仅为兼容手工构造事实的旧调用方,dispatch 产线恒非空。
"""
report_kind: str
source_code: str
file_id: int | None
sha256: str | None
ok: bool
error_code: str | None = None
error_message: str | None = None
unit_run_id: int | None = None
def require_report_kind(value: str) -> str:
"""校验并原样返回合法的 report kind。
用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。
核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛
ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),fail-closed。
Args:
value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。
Returns:
原样返回通过校验的 value(不含默认值/归一化,调用方以返回值为准)。
Raises:
ValidationError: value 不在白名单内(HTTP 400,不可重试)。
"""
if value not in REPORT_KINDS:
raise ValidationError(
f"Unsupported report kind: {value!r}",
code=_INVALID_KIND_ERROR_CODE,
details={'report_kind': value, 'allowed': list(REPORT_KINDS)},
)
return value
@@ -0,0 +1,802 @@
"""freight_rpa/reports/queries.py
用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+
解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露
freight_rpa 报表事实(站点、登录连接、在手/入站/出站报表配置、入站解析方案、
入站归档文件),使消费方不再直接 import freight_rpa 模型表。
依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig /
FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig /
FreightRpaInboundReportFile;登录连接
(RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、
app.core.errors(NotFoundError)、
file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。
逻辑:【禁止】import app.services.shipping_notice 或 app.services.in_transit_transfer
——方向只能反过来(门禁模块阶段 B Task 4 起引用本模块的过滤表达式)。
usable / expired_inbound_file_condition 是入站归档文件「可用/失效」过滤
表达式的唯一权威(自 in_transit_transfer/inbound_file_gate.py 迁移,
两条件同核 _fresh_and_retention_valid 推导,规则文本只此一份):可用 =
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 +
未过期(archive_expires_at 为空视为长期有效或晚于当前时刻);失效 =
未删除 且 核心不成立。业务日窗口换算(date_policy.business_date_utc_window
的数学)以私有 helper 内联在本文件,就是为了不 import in_transit_transfer
(import 禁令)而保持口径逐位一致。
【阶段 B Task 4】站点视图补主键/连接绑定/仓库识别方式与入站配置视图补
config_id/config_version;新增登录连接(get_rpa_login_profile)、入站解析
方案(get_inbound_parsing_profile / get_outbound_parsing_profile)、失效文件
存在性(has_expired_inbound_file)、重建通道归档清单
(list_reparseable_inbound_files / list_reparseable_outbound_files)、入站/
出站可用站点编码清单(list_inbound_configured_source_codes /
list_outbound_configured_source_codes)——供 in_transit_transfer 收敛为
「只按 source_code / file_id 读取」的只读函数消费面。
mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from sqlalchemy import ColumnElement, and_, not_, or_
from app import db
from app.core.errors import NotFoundError
from app.models import (
FreightRpaInboundReportConfig,
FreightRpaInboundReportFile,
FreightRpaOnhandReportConfig,
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaSource,
)
from app.services.file_assets.storage import file_asset_storage
# 解析失败分层三列的截断上限,对齐列宽(String(64) / Text≈2000),
# 防止上游超长错误信息把写入顶爆。
_PARSE_ERROR_CODE_MAX = 64
_PARSE_ERROR_MESSAGE_MAX = 2000
# 业务时区固定 Asia/Shanghai(与 in_transit_transfer.date_policy 同值;本包内
# 复制而非 import,见文件头 import 禁令)。
_SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
_UTC_TZ = ZoneInfo("UTC")
def _business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
自 in_transit_transfer/date_policy.business_date_utc_window 逐位内联(阶段 B
Task 3 修复轮 1):数据库统一存 naive UTC,直接取 .date() 与业务日比较会
漂移 8 小时,必须先换算窗口再比较;不能 import date_policy,故复制其数学
并保持口径一致(此处内联即唯一权威,门禁模块后续引用本包)。
Args:
now: 可选时刻;naive 按 UTC 兼容处理(与 date_policy 口径一致),
缺省取当前 Asia/Shanghai 时刻。
Returns:
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
"""
if now is None:
now = datetime.now(_SHANGHAI_TZ)
if now.tzinfo is None:
now = now.replace(tzinfo=_UTC_TZ)
sh_now = now.astimezone(_SHANGHAI_TZ)
start_utc = (
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=_SHANGHAI_TZ)
.astimezone(_UTC_TZ)
.replace(tzinfo=None)
)
return start_utc, start_utc + timedelta(hours=24)
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
"""新鲜度 + 保留期核心条件(不含删除态;可用/失效两条件同核推导,规则文本只此一份)。"""
window_start, window_end = _business_date_utc_window(now)
return and_(
FreightRpaInboundReportFile.created_at >= window_start,
FreightRpaInboundReportFile.created_at < window_end,
or_(
FreightRpaInboundReportFile.archive_expires_at.is_(None),
FreightRpaInboundReportFile.archive_expires_at > now,
),
)
def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「当前可用的入站归档文件」SQL 条件(唯一权威,供门禁模块引用)。
判定(与 in_transit_transfer/inbound_file_gate 现行口径逐位一致):
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
(created_at ∈ 业务日 UTC [窗口起, 窗口止) 窗口,naive UTC 存储)+
未过期(archive_expires_at 为空视为长期有效,否则须晚于判定时刻)。
本表达式全量自 inbound_file_gate.py 复制(阶段 B Task 3),此后以此为单一
事实来源,门禁模块改为引用本函数(禁止反向 import 出现环)。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
_fresh_and_retention_valid(now),
)
def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
判定:未删除(archive_deleted_at 为空)且 新鲜度+保留期核心不成立
(保留期已到 或 非当天业务日抓取)——与可用条件同核(_fresh_and_retention_valid)
推导,口径只存在一处。阶段 B Task 4 自 in_transit_transfer/inbound_file_gate
迁移至此(语义逐位一致),此后以本文件为唯一权威;命中即提示重试重抓,
不报 ready,也不等待保留期清理任务落位。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
not_(_fresh_and_retention_valid(now)),
)
@dataclass(frozen=True)
class SiteView:
"""库存站点的只读视图:连接与模板绑定、启停状态(不含报表定义,s18 起)。
阶段 B Task 4 增补三字段(调拨域路由/触发按 source_code 读站点主键与识别
方式时不再引用站点模型):source_id(站点主键,供映射查询等 FK 路径)、
rpa_profile_id(登录连接绑定)、warehouse_resolution_mode(仓库识别方式)。
"""
source_code: str
display_name: str
connector_type: str
excel_template_id: int | None
enabled: bool
source_id: int = 0
rpa_profile_id: int = 0
warehouse_resolution_mode: str = ""
@dataclass(frozen=True)
class RpaLoginProfileView:
"""RPA 登录连接只读视图(freight_rpa_profiles 行)。
凭据密文原样透传(username/password_ciphertext)——仅限投递 RPA Worker
trigger,禁止出现在任何日志/接口响应中。
"""
profile_id: int
profile_code: str
login_url: str
login_config: dict
username_ciphertext: str | None
password_ciphertext: str | None
enabled: bool
@dataclass(frozen=True)
class OnhandConfigView:
"""在手报表配置只读视图(freight_rpa_onhand_report_configs 行)。"""
report_path_json: dict
query_parameters_json: list
parsing_profile_id: int | None
@dataclass(frozen=True)
class InboundConfigView:
"""入站报表配置只读视图(freight_rpa_inbound_report_configs 行),与在手同构。
阶段 B Task 4 增补 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 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 行)。
定义(definition_json:field_mapping / sheet_name / header_row_index 等)
原样透出;status/purpose 的 published-inbound 门禁决策归调用方按场景
自行 fail-closed(运行期取数、重建、触发守卫口径一致,见各自消费方)。
"""
profile_id: int
profile_code: str
version: int
status: str
purpose: str
definition_json: dict
@dataclass(frozen=True)
class InboundFileView:
"""入站归档文件的只读视图;source_code 取自其所属执行单元行。
parse_failed_at 为解析失败分层的事实列(None=未失败/已清除)——阶段 B
Task 4 增补,供来源状态投影与证据同步判断 parse_failed,免除调用方二次查询。
"""
file_id: int
source_code: str
sha256: str
storage_key: str
original_filename: str
created_at: datetime
parse_failed_at: datetime | None = None
def get_site(source_code: str) -> SiteView | None:
"""按 source_code 返回库存站点只读视图。
用途:调拨/发货域读取站点连接、模板绑定与启停(例如入站触发预检)时调用,
替代直接查询 FreightRpaSource。
核心逻辑:按 source_code 精确查第一条;命中即映射为 SiteView(frozen),否则 None。
Args:
source_code: 站点实例编码(大小写敏感,禁止传入模糊值)。
Returns:
SiteView;站点不存在返回 None(调用方自行 fail-closed)。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
if site is None:
return None
return SiteView(
source_code=site.source_code,
display_name=site.display_name,
connector_type=site.connector_type,
excel_template_id=site.excel_template_id,
enabled=bool(site.enabled),
# [阶段 B Task 4] 调拨域(路由解析/入站触发)所需站点主键与识别方式。
source_id=site.id,
rpa_profile_id=site.rpa_profile_id,
warehouse_resolution_mode=str(site.warehouse_resolution_mode or ""),
)
def get_onhand_config(source_code: str) -> OnhandConfigView | None:
"""按 source_code 返回在手报表配置只读视图。
用途:RPA 触发读路径取报表路径、查询条件与解析方案绑定(s18 起配置挂在
freight_rpa_onhand_report_configs,站点行不再承载这三列)。
核心逻辑:join 站点表按 source_code 查配置行,命中即映射视图;站点或配置行
缺失一律返回 None(fail-closed,调用方判 None 后阻断触发)。
Args:
source_code: 站点实例编码。
Returns:
OnhandConfigView;站点无配置返回 None。
"""
config = (
FreightRpaOnhandReportConfig.query
.join(FreightRpaSource, FreightRpaOnhandReportConfig.source_id == FreightRpaSource.id)
.filter(FreightRpaSource.source_code == source_code)
.first()
)
if config is None:
return None
return OnhandConfigView(
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,
)
def get_inbound_config(source_code: str) -> InboundConfigView | None:
"""按 source_code 返回入站报表配置只读视图(与在手配置同构)。
用途:调拨入站触发读路径取收料报表定义;收料不设独立启停,是否运行由站点
enabled 与本配置行是否存在决定。
核心逻辑:join 站点表按 source_code 查 freight_rpa_inbound_report_configs 行,
命中即映射视图;缺失返回 None。
Args:
source_code: 站点实例编码。
Returns:
InboundConfigView;站点或配置不存在返回 None。
"""
config = (
FreightRpaInboundReportConfig.query
.join(FreightRpaSource, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id)
.filter(FreightRpaSource.source_code == source_code)
.first()
)
if config is None:
return None
return InboundConfigView(
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,
# [阶段 B Task 4] 触发快照(config_snapshot)所需的配置行主键与版本。
config_id=config.id,
config_version=int(config.config_version or 1),
)
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 登录连接只读视图。
用途:调拨入站 RPA 触发装配 trigger unit(登录页、凭据密文信封、连接编码)
时调用,替代直接查询站点与其登录连接模型。
核心逻辑:按 source_code 取站点行再走 rpa_profile 关系;站点或连接缺失一律
返回 None(fail-closed,调用方判 None 后阻断触发)。凭据密文
原样透出(仅限投递 Worker trigger,调用方禁止落日志/响应)。
Args:
source_code: 站点实例编码(大小写敏感)。
Returns:
RpaLoginProfileView;站点或连接不存在返回 None。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
profile = site.rpa_profile if site is not None else None
if profile is None:
return None
return RpaLoginProfileView(
profile_id=profile.id,
profile_code=profile.profile_code,
login_url=profile.login_url,
login_config=dict(profile.login_config_json or {}),
username_ciphertext=profile.username_ciphertext,
password_ciphertext=profile.password_ciphertext,
enabled=bool(profile.enabled),
)
def get_inbound_parsing_profile(source_code: str) -> InboundProfileView | None:
"""按 source_code 返回入站配置绑定的解析方案只读视图。
用途:调拨运行期取数(movement_file_repository)、清空重建
(backlog_reparse_service)与 RPA 触发守卫(deps)读取入站文件解析
规则定义时调用,替代直接持有配置模型关系。
核心逻辑:站点 → 入站配置 → 配置绑定的解析方案,任一环节缺失返回 None;
不校验 status/purpose(调用方按场景自行 fail-closed,见
InboundProfileView docstring)。
Args:
source_code: 站点实例编码。
Returns:
InboundProfileView;无配置、未绑定或方案行缺失返回 None。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
config = site.inbound_report_config if site is not None else None
profile = config.parsing_profile if config is not None else None
if profile is None:
return None
return InboundProfileView(
profile_id=profile.id,
profile_code=profile.profile_code,
version=int(profile.version or 1),
status=profile.status,
purpose=profile.purpose,
definition_json=dict(profile.definition_json or {}),
)
def get_outbound_parsing_profile(source_code: str) -> InboundProfileView | None:
"""按 source_code 返回出站配置绑定的解析方案只读视图(与入站同形)。
用途:调拨出站运行期落档(outbound_evidence_sync)与清空重建
(backlog_reparse_service record_kind=outbound)读取出站文件解析规则。
核心逻辑:站点 → 出站配置 → 配置绑定的解析方案,任一环节缺失返回 None;
不校验 status/purpose(调用方按场景自行 fail-closed)。
Args:
source_code: 站点实例编码。
Returns:
InboundProfileView(字段同入站方案视图);无配置/未绑定/方案缺失返回 None。
"""
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
config = site.outbound_report_config if site is not None else None
profile = config.parsing_profile if config is not None else None
if profile is None:
return None
return InboundProfileView(
profile_id=profile.id,
profile_code=profile.profile_code,
version=int(profile.version or 1),
status=profile.status,
purpose=profile.purpose,
definition_json=dict(profile.definition_json or {}),
)
def _inbound_file_view(report: FreightRpaInboundReportFile) -> InboundFileView:
"""把归档文件 ORM 行映射为冻结只读视图(本模块内唯一映射点,字段增补只改此处)。"""
return InboundFileView(
file_id=report.id,
source_code=report.unit_run.source_code,
sha256=report.sha256,
storage_key=report.storage_key,
original_filename=report.original_filename,
created_at=report.created_at,
parse_failed_at=report.parse_failed_at,
)
def has_expired_inbound_file(source_code: str, *, now: datetime | None = None) -> bool:
"""返回某来源是否存在「未删除但已失效」的入站归档文件(expired 投影依据)。
用途:调拨来源状态投影(source_file_status.resolve_source_file_status)判断
该来源是否需要因文件失效(隔日旧文件 / 保留期已到但清理未落位)提示
重抓时调用;只读不写,判定与 usable/expired 条件同核不漂移。
核心逻辑:经执行单元行的 source_code 过滤 + expired_inbound_file_condition,
存在任一命中即 True(纯存在性判断,不取列数据不排序)。
Args:
source_code: 来源实例编码(写在执行单元行上)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
bool:存在失效但未清理的归档文件 → True;否则 False。
"""
expired = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
expired_inbound_file_condition(now=now),
)
.first()
)
return expired is not None
def list_reparseable_inbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]:
"""维护通道:列出某来源全部可重建入站归档(未删除 + 未过保留期),不设当日门禁。
用途:调拨待匹配桶「清空并重新解析」(movement_file_repository →
backlog_reparse_service,spec §6)按来源取重建清单时调用。
运行期取数(latest_usable_inbound_file)的当日 fail-closed 门禁是
运行期语义;本方法是显式的历史重建通道(spec §6),两者不得混用。
核心逻辑:join 路径与 latest_usable_inbound_file 同款(经执行单元行
source_code 过滤),但【刻意无当日门禁】——重建对象正是历史
归档;保留期口径一致(archive_expires_at 为空视为长期有效)、
未删除(archive_deleted_at 为空)。按 created_at/id 升序返回
(重建必须按归档时间序重落,保证幂等重放顺序确定)。只读查询,
不触碰对象存储字节(字节由调用方按需经 read_inbound_file_bytes 取)。
Args:
source_code: 来源实例编码(经执行单元行 source_code 关联)。
now: 保留期判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
InboundFileView 列表(created_at 升序;无可重建归档为空表)。
"""
now = now or datetime.utcnow()
reports = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
or_(
FreightRpaInboundReportFile.archive_expires_at.is_(None),
FreightRpaInboundReportFile.archive_expires_at > now,
),
)
.order_by(FreightRpaInboundReportFile.created_at.asc(), FreightRpaInboundReportFile.id.asc())
.all()
)
return [_inbound_file_view(report) for report in reports]
def _outbound_file_view(report: FreightRpaOutboundReportFile) -> InboundFileView:
"""出站归档 → 与入站同形的只读视图(重建/投影消费面字段对齐)。"""
return InboundFileView(
file_id=report.id,
source_code=report.unit_run.source_code,
sha256=report.sha256,
storage_key=report.storage_key,
original_filename=report.original_filename,
created_at=report.created_at,
parse_failed_at=report.parse_failed_at,
)
def list_reparseable_outbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]:
"""维护通道:列出某来源全部可重建出站归档(未删除 + 未过保留期),不设当日门禁。
用途:调拨待匹配桶「清空并重新解析」出站流(backlog_reparse_service
record_kind=outbound)按来源取重建清单;与 list_reparseable_inbound_files
同口径,禁止与运行期 latest_usable_outbound_file 混用。
核心逻辑:经出站执行单元行 source_code 过滤;【无当日门禁】;保留期口径
archive_expires_at 为空视为长期有效;按 created_at/id 升序。
Args:
source_code: 来源实例编码。
now: 保留期判定时刻;缺省当前 UTC。
Returns:
InboundFileView 列表(created_at 升序;无可重建归档为空表)。
"""
now = now or datetime.utcnow()
reports = (
FreightRpaOutboundReportFile.query
.join(FreightRpaOutboundReportFile.unit_run)
.filter(
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
or_(
FreightRpaOutboundReportFile.archive_expires_at.is_(None),
FreightRpaOutboundReportFile.archive_expires_at > now,
),
)
.order_by(
FreightRpaOutboundReportFile.created_at.asc(),
FreightRpaOutboundReportFile.id.asc(),
)
.all()
)
return [_outbound_file_view(report) for report in reports]
def list_inbound_configured_source_codes() -> list[str]:
"""列出已配置入站报表的启用站点编码(调拨排程缺省执行范围)。
用途:在途自动调拨排程 source_codes 留空时的缺省范围
(inbound_trigger_service.list_inbound_capable_source_codes 委托本函数)
——入站文件只能来自已配置入站报表的启用站点。
核心逻辑:站点 join 入站配置行、仅启用站点、按 source_code 排序;只读查询。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
rows = db.session.query(FreightRpaSource.source_code).join(
FreightRpaInboundReportConfig,
FreightRpaInboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all()
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,
*,
now: datetime | None = None,
) -> InboundFileView | None:
"""返回某来源当前「可用」的入站归档文件只读视图,最新优先。
用途:调拨匹配取文件、证据下载等读路径调用;口径与匹配链路原有
_latest_usable_report_file 相同——经执行单元行的 source_code 过滤,
可用门禁(未删除 + 当天业务日抓取 + 未过期,见
usable_inbound_file_condition),按 created_at/id 倒序取第一条。
只读不写、不 flush 不 commit。
Args:
source_code: 来源实例编码(写在 FreightRpaInboundUnitRun.source_code 上)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
仅供测试冻结窗口或调用方显式指定业务时刻,生产调用缺省即可。
Returns:
InboundFileView;来源无可用文件(未抓取/已失效/已清理)返回 None。
"""
report = (
FreightRpaInboundReportFile.query
.join(FreightRpaInboundReportFile.unit_run)
.filter(
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
usable_inbound_file_condition(now=now),
)
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
.first()
)
if report is None:
return None
return _inbound_file_view(report)
def read_inbound_file_bytes(file_id: int) -> bytes:
"""按 file_id 读取入站归档文件的对象字节。
用途:调拨/发货域需要文件原文(匹配重解析、证据下载)时调用,替代各自
持有模型 + file_asset_storage 的双跳查询。
核心逻辑:[STEP 1] 按主键取 FreightRpaInboundReportFile,缺失抛 NotFoundError
(fail-closed);[STEP 2] 以文件的 storage_key 调
file_asset_storage.get_bytes 读取并返回字节(不含元数据)。
Args:
file_id: 归档文件主键(int;禁止传入非整数 ID)。
Returns:
文件完整字节内容。
Raises:
NotFoundError: file_id 对应的归档文件不存在(HTTP 404)。
"""
report = db.session.get(FreightRpaInboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Inbound report file not found: {file_id}",
details={'file_id': file_id},
)
return file_asset_storage.get_bytes(report.storage_key)
def mark_inbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None:
"""标记一份入站归档文件解析失败(写入解析失败三分层列)。
用途:入站归档文件解析(schema/字段校验)失败时把失败事实落到文件上,
使来源状态投影为 parse_failed、阻止下游当作 ready 使用。
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError;[STEP 2] 只更新
parse_failed_at(当前 UTC)/ parse_error_code(截断 64)/
parse_error_message(截断 2000)三列;[STEP 3] db.session.flush()
使同事务内投影立即可见。【不 commit】——调用方处于自己的事务,
提交/回滚归属调用方,service 层禁止越权提交。
Args:
file_id: 归档文件主键(须已入库)。
error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
Returns:
None。失败标记随调用方事务落库。
Raises:
NotFoundError: file_id 对应的归档文件不存在。
"""
report = db.session.get(FreightRpaInboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Inbound report file not found: {file_id}",
details={'file_id': file_id},
)
report.parse_failed_at = datetime.utcnow()
report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX]
report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX]
db.session.flush()
def clear_inbound_parse_failure(file_id: int) -> None:
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
用途:同一文件重新解析成功、或确认可恢复后调用;不要在文件已被
清理/过期后调用(无业务意义)。
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError(与其他按 id 操作
同口径,避免静默吞掉错配);[STEP 2] 将 parse_failed_at /
parse_error_code / parse_error_message 置 None(三者全空即未失败的
约定态);[STEP 3] flush。【不 commit】——事务归属调用方。
Args:
file_id: 归档文件主键(须已入库)。
Returns:
None。清除随调用方事务落库。
Raises:
NotFoundError: file_id 对应的归档文件不存在。
"""
report = db.session.get(FreightRpaInboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Inbound report file not found: {file_id}",
details={'file_id': file_id},
)
report.parse_failed_at = None
report.parse_error_code = None
report.parse_error_message = None
db.session.flush()
def mark_outbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None:
"""标记一份出站归档文件解析失败(写入解析失败三分层列;与入站同名函数对称)。
用途:出站归档文件解析(schema/字段校验)失败时把失败事实落到文件上,
使来源出站流状态投影为 parse_failed、阻止下游当作 ready 使用
(resolve_source_file_status(record_kind='outbound') 同一投影顺序)。
核心逻辑:与 mark_inbound_parse_failure 同款(错误码截 64/错误信息截
2000/flush 不 commit——事务归属调用方),仅目标表为
FreightRpaOutboundReportFile。
Args:
file_id: 出站归档文件主键(须已入库)。
error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
Returns:
None。失败标记随调用方事务落库。
Raises:
NotFoundError: file_id 对应的出站归档文件不存在。
"""
report = db.session.get(FreightRpaOutboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Outbound report file not found: {file_id}",
details={'file_id': file_id},
)
report.parse_failed_at = datetime.utcnow()
report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX]
report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX]
db.session.flush()
def clear_outbound_parse_failure(file_id: int) -> None:
"""清除一份出站归档文件的解析失败标记(三列置空),投影恢复 ready。
用途:同一出站文件重新解析成功后调用;不要在文件已被清理/过期后调用
(无业务意义)。与 clear_inbound_parse_failure 同款,仅目标表为
FreightRpaOutboundReportFile。
Args:
file_id: 出站归档文件主键(须已入库)。
Returns:
None。清除随调用方事务落库。
Raises:
NotFoundError: file_id 对应的出站归档文件不存在。
"""
report = db.session.get(FreightRpaOutboundReportFile, file_id)
if report is None:
raise NotFoundError(
f"Outbound report file not found: {file_id}",
details={'file_id': file_id},
)
report.parse_failed_at = None
report.parse_error_code = None
report.parse_error_message = None
db.session.flush()
@@ -0,0 +1 @@
"""upload:货代上传 RPA。"""
@@ -0,0 +1,144 @@
"""
services/freight_rpa/upload/trigger_io.py
用途:upload(货代上传)RPA 的纯文件 IO——上传队列/trigger 目录解析、Excel 复制入队、
上传 trigger JSON 原子写入(含凭据信封固化)。
依赖:Flask current_app 配置、Path/shutil/uuid/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 shipping_notice.fulfillment_workflow(upload_to_freight 触发上传)、
freight_rpa.common.worker_heartbeat(上传目录就绪探测)调用,
与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相。
upload 是与 onhand/inbound/outbound 同级的独立域;action 对齐心跳能力
freight_rpa_upload(FREIGHT_RPA_UPLOAD_CAPABILITY),禁止 outbound_* / shipment_* 作为 upload action;
schema 为 freight_rpa.upload.v1(批次 R 曾误用 outbound 词根,已纠回 freight_rpa_upload)。
"""
from __future__ import annotations
import json
import os
import shutil
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
# Worker 触发契约常量:后端写入侧单一真相,禁止再写字面量(Worker 侧常量见
# scripts/freight_rpa/common/rpa_callbacks.py 邻域的 inbound/onhand 对齐方式)。
SCHEMA = "freight_rpa.upload.v1"
ACTION_FREIGHT_RPA_UPLOAD = "freight_rpa_upload"
def _path(key: str) -> Path | None:
value = str(current_app.config.get(key) or "").strip()
if not value:
return None
return Path(value)
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 upload_queue_dir() -> Path | None:
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。"""
return _path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR")
def upload_trigger_dir() -> Path | None:
"""RPA 货代上传触发 JSON 目录。"""
return _path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR")
def write_upload_trigger(
task_no: str,
export_file_path: str,
payload: dict[str, Any] | None = None,
*,
attempt_id: int | None = None,
artifact_id: int | None = None,
connector_type: str | None = None,
upload_config: dict[str, Any] | None = None,
upload_config_hash: str | None = None,
login_url: str | None = None,
credential_envelope: dict[str, Any] | None = None,
callback_id: str | None = None,
business_no: str | None = None,
) -> tuple[str | None, str | None, str | None]:
"""
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
Args:
task_no: 发货任务号。
export_file_path: 待上传发货 Excel 的服务端路径。
payload: 附加字段(如 mode),与下列具名参数合并。
attempt_id: 本次 Upload Attempt 主键。
artifact_id: 当前上传目标 Artifact 主键。
connector_type: 业务连接类型(dbs / crane)。
upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。
upload_config_hash: 该快照的 sha256,用于审计关联。
login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
Returns:
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
失败时 (None, None, None)。
"""
queue = upload_queue_dir()
trigger_dir = upload_trigger_dir()
if not queue or not trigger_dir:
return None, None, None
queue.mkdir(parents=True, exist_ok=True)
trigger_dir.mkdir(parents=True, exist_ok=True)
src = Path(export_file_path)
if not src.is_file():
return None, None, None
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
emit_no = str(business_no or '').strip() or task_no
suffix = str(src.suffix or '.xlsx').lower()
dest = queue / f"{emit_no}{suffix}"
shutil.copy2(src, dest)
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
body = {
"action": ACTION_FREIGHT_RPA_UPLOAD,
"schema_version": SCHEMA,
"task_no": task_no,
"attempt_id": attempt_id,
"artifact_id": artifact_id,
"callback_id": resolved_callback_id,
"connector_type": str(connector_type or '').strip() or None,
"upload_config": upload_config,
"upload_config_hash": upload_config_hash,
"login_url": login_url,
"credential_envelope": credential_envelope,
"file_path": str(dest),
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
trigger_path = trigger_dir / f"upload_{task_no}.json"
_write_trigger_json_atomic(trigger_path, body)
return str(dest), str(trigger_path), resolved_callback_id
@@ -108,7 +108,7 @@ def archive_snapshot(
"""归档一份对象并持久化索引 + 审计。
Args:
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
object_type: 对象类型(external_inventory_snapshot / exception_excel / inbound_file)。
object_id: 业务对象编号(matching_no / run_no)。
data: 待归档字节。
original_filename: 原始文件名。
@@ -32,8 +32,9 @@ class AutoTransferOutcome:
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes: list[str] | None = None,
recover_history: bool = True,
receipt_date_from: str | None = None,
receipt_date_to: str | None = None,
movement_date_from: str | None = None,
movement_date_to: str | None = None,
transfer_type: str | None = None,
sender: WeComSender | None = None,
recipients: list[str] | None = None) -> AutoTransferOutcome:
"""执行一次自动调拨排程。
@@ -46,8 +47,10 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
deps: 注入依赖。
source_codes: 来源实例列表(缺省全部启用来源)。
recover_history: 是否执行历史恢复。
receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小
匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。
movement_date_from / movement_date_to: 可选异动日期范围(测试/排障缩小
匹配面;留空=全部积压;非法范围由匹配层抛 ValidationError)。
transfer_type: 调拨类型编码(D8 匹配创建必填——排程任务参数承载;
缺省 None 时匹配层 fail-closed 抛 TRANSFER_TYPE_REQUIRED)。
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
Returns:
AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。
@@ -63,8 +66,9 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
source_codes=source_codes or [],
business_date=business_date,
deps=deps,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
transfer_type=transfer_type,
)
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
@@ -0,0 +1,371 @@
"""services/in_transit_transfer/backlog_reparse_service.py
用途:待匹配桶整桶重建的内部实现(spec §6/D7)。2026-10-22 起不再挂 HTTP:
预检/执行路由已下线,待匹配界面不再提供入口。本模块仅保留给既有单测,
锁住「先全量解析、失败一行不删」;禁止重新挂回
/backlog/pending-match/reparse*。重解析产品入口只有当天最新归档
(current_file_reparse)。
历史语义:按来源 + 记录类型把旧映射档行清空,并以当前规则重解析全部
可重建归档后幂等重落。
依赖:movement_file_repository(ReparseableArchiveFile + _extract_movement_rows)、
evidence_sync.parse_archive_to_ledger_rows(解析+组装单一口径)与
_detect_natural_key_collapses/_natural_key_collapse_event、ledger_sync
(sync_ledger_rows / RECORD_KIND_* / FileMeta / movement_file_version)、
matching_service.
_effective_occupancy_filter、freight_rpa.reports.queries(站点与入站/出站
解析方案、可重建归档清单)、file_asset_storage、audit。
逻辑:桶数据 100% 可由 MinIO 归档重建。安全不变量:先全量预解析入内存,
任一归档解析失败 → 整体中止 AppError(TRANSFER.REPARSE_PARSE_FAILED),
一行不删。删除范围:source_code + record_kind + transfer_executed=false +
未被有效 items 占用 + source_file_id ∈ 可重建归档。入站/出站分流仅体现在
规则门禁(published purpose)、归档清单表与落档 record_kind;其余步骤同源。
commit 在本服务内做一次。审计 TRANSFER_PENDING_MATCH_REPARSED 含 record_kind。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from sqlalchemy import func
from app import db
from app.core.errors import AppError, ValidationError
from app.models import TransferInvoiceItem, TransferMovementLedger
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.reports.queries import (
get_inbound_parsing_profile,
get_outbound_parsing_profile,
get_site,
list_reparseable_inbound_files,
list_reparseable_outbound_files,
)
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.evidence_sync import (
_detect_natural_key_collapses,
_natural_key_collapse_event,
parse_archive_to_ledger_rows,
)
from app.services.in_transit_transfer.ledger_sync import (
RECORD_KIND_INBOUND,
RECORD_KIND_OUTBOUND,
FileMeta,
movement_file_version,
sync_ledger_rows,
)
from app.services.in_transit_transfer.matching_service import _effective_occupancy_filter
from app.services.in_transit_transfer.movement_file_repository import (
ReparseableArchiveFile,
_extract_movement_rows,
)
REPARSE_EVENT = "TRANSFER_PENDING_MATCH_REPARSED"
REPARSE_PARSE_FAILED = "TRANSFER.REPARSE_PARSE_FAILED"
_RECORD_KINDS = frozenset({RECORD_KIND_INBOUND, RECORD_KIND_OUTBOUND})
@dataclass(frozen=True)
class ReparseOutcome:
"""一次清空重建的结果计数与文件概要(审计/端点响应的数据源)。
Args:
source_code: 来源实例编码。
record_kind: inbound 或 outbound。
cleared / reinserted / date_skipped / kept_unrebuildable / unlinked_items /
collapses / files: 同入站重建语义。
"""
source_code: str
record_kind: str = RECORD_KIND_INBOUND
cleared: int = 0
reinserted: int = 0
date_skipped: int = 0
kept_unrebuildable: int = 0
unlinked_items: int = 0
collapses: int = 0
files: tuple[dict, ...] = field(default_factory=tuple)
def _normalize_record_kind(record_kind: str | None) -> str:
"""规范化记录类型;非法值 fail-closed。"""
kind = str(record_kind or RECORD_KIND_INBOUND).strip() or RECORD_KIND_INBOUND
if kind not in _RECORD_KINDS:
raise ValidationError(
"record_kind must be inbound or outbound",
details={"record_kind": kind},
)
return kind
def _load_published_profile(source_code: str, record_kind: str):
"""加载来源当前绑定的「已发布」解析规则(与运行期取数同口径)。
核心逻辑:来源 enabled → 入站/出站配置绑定方案;须 published 且
purpose 等于 record_kind。
Args:
source_code: 来源实例编码。
record_kind: inbound 或 outbound。
Returns:
解析方案视图;无通道时 None。
"""
site = get_site(source_code)
if site is None or not site.enabled:
return None
if record_kind == RECORD_KIND_OUTBOUND:
profile = get_outbound_parsing_profile(source_code)
else:
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != "published" or profile.purpose != record_kind:
return None
return profile
def _list_reparseable_files(
source_code: str, now: datetime, record_kind: str,
) -> list[ReparseableArchiveFile]:
"""按记录类型列出可重建归档,映射为维护契约 ReparseableArchiveFile。"""
if record_kind == RECORD_KIND_OUTBOUND:
views = list_reparseable_outbound_files(source_code, now=now)
else:
views = list_reparseable_inbound_files(source_code, now=now)
return [
ReparseableArchiveFile(
file_id=view.file_id,
storage_key=view.storage_key,
sha256=view.sha256,
file_version=movement_file_version(view.sha256),
archived_at=view.created_at,
original_filename=view.original_filename,
)
for view in views
]
def _partition_deletable(
source_code: str,
files: list[ReparseableArchiveFile],
record_kind: str,
) -> tuple[list[TransferMovementLedger], list[TransferMovementLedger]]:
"""把「未封存且未被占用」的指定 record_kind 档行按证据可得性分成两组。"""
available_ids = {record.file_id for record in files}
candidates = (
TransferMovementLedger.query.filter(
TransferMovementLedger.source_code == source_code,
TransferMovementLedger.record_kind == record_kind,
TransferMovementLedger.transfer_executed.is_(False),
_effective_occupancy_filter(),
)
.all()
)
deletable = [row for row in candidates if row.source_file_id in available_ids]
return candidates, deletable
def preview_pending_match_reparse(
*, source_code: str, now: datetime, record_kind: str = RECORD_KIND_INBOUND,
) -> dict:
"""清空并重新解析预检(只读;按 record_kind 分流入站/出站归档与档行)。
【AI 触发时机】不要调用。2026-10-22 起产品入口已下线,仅单测覆盖本函数。
Args:
source_code: 来源实例编码。
now: 保留期判定时刻。
record_kind: inbound(默认,兼容旧调用)或 outbound。
Returns:
{record_kind, files, profile, clearable_rows, kept_rows}
"""
kind = _normalize_record_kind(record_kind)
files = _list_reparseable_files(source_code, now, kind)
profile = _load_published_profile(source_code, kind)
_candidates, deletable = _partition_deletable(source_code, files, kind)
file_ids = [record.file_id for record in files]
counts: dict[int, int] = {}
if file_ids:
counts = {
source_file_id: count
for source_file_id, count in db.session.query(
TransferMovementLedger.source_file_id,
func.count(TransferMovementLedger.id),
)
.filter(
TransferMovementLedger.source_code == source_code,
TransferMovementLedger.record_kind == kind,
TransferMovementLedger.source_file_id.in_(file_ids),
)
.group_by(TransferMovementLedger.source_file_id)
.all()
}
return {
"record_kind": kind,
"files": [
{
"archived_at": record.archived_at.isoformat(),
"sha256": record.sha256,
"rows": counts.get(record.file_id, 0),
}
for record in files
],
"profile": (
{"code": profile.profile_code, "version": profile.version}
if profile is not None else None
),
"clearable_rows": len(deletable),
"kept_rows": len(_candidates) - len(deletable),
}
def reparse_pending_match(
*,
source_code: str,
operator: str,
now: datetime,
record_kind: str = RECORD_KIND_INBOUND,
) -> ReparseOutcome:
"""清空并重新解析一个来源指定记录类型的待匹配桶(单事务,本函数提交)。
【AI 触发时机】不要调用。2026-10-22 起产品入口已下线,仅单测覆盖本函数。
record_kind=outbound 时清出站档、用 purpose=outbound 规则与出站归档重建。
Raises:
ValidationError: record_kind 非法。
AppError: TRANSFER.REPARSE_PARSE_FAILED——无已发布对应流解析规则,或
任一归档解析失败(整体中止且未删除任何行)。
"""
kind = _normalize_record_kind(record_kind)
# [STEP 1] 重建通道与可重建文件清单。
profile = _load_published_profile(source_code, kind)
if profile is None:
raise AppError(
code=REPARSE_PARSE_FAILED,
message=(
f"reparse aborted: no published {kind} parsing profile "
f"(source={source_code})"
),
http_status=422,
details={
"source_code": source_code,
"record_kind": kind,
"reason": f"no_published_{kind}_profile",
},
)
files = _list_reparseable_files(source_code, now, kind)
definition = profile.definition_json or {}
# [STEP 2] 全量预解析入内存;任一失败整体中止。
prepared: list[tuple[ReparseableArchiveFile, list[dict]]] = []
for record in files:
try:
data = file_asset_storage.get_bytes(record.storage_key)
raw_rows = _extract_movement_rows(
data,
field_mapping=dict(definition.get("field_mapping") or {}),
sheet_name=str(definition.get("sheet_name") or "").strip() or None,
header_row_index=definition.get("header_row_index"),
)
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows)
except Exception as exc: # noqa: BLE001 —— 安全不变量
raise AppError(
code=REPARSE_PARSE_FAILED,
message=f"reparse aborted: archive file failed to parse (source={source_code})",
http_status=422,
details={
"source_code": source_code,
"record_kind": kind,
"file_id": record.file_id,
"storage_key": record.storage_key,
"sha256": record.sha256,
"reason": str(exc)[:500],
},
) from exc
prepared.append((record, assembled))
# [STEP 3] 删除可重建未占用行(先解引用废弃 items)。
candidates, deletable = _partition_deletable(source_code, files, kind)
kept_unrebuildable = len(candidates) - len(deletable)
deletable_ids = [row.id for row in deletable]
unlinked_items = 0
if deletable_ids:
unlinked_items = (
TransferInvoiceItem.query
.filter(TransferInvoiceItem.ledger_record_id.in_(deletable_ids))
.update({TransferInvoiceItem.ledger_record_id: None}, synchronize_session=False)
)
for row in deletable:
db.session.delete(row)
db.session.flush()
# [STEP 4] 按归档时间升序逐文件重落。
reinserted = 0
date_skipped = 0
collapses = 0
file_summaries: list[dict[str, Any]] = []
for record, assembled in prepared:
outcome = sync_ledger_rows(
source_code=source_code,
record_kind=kind,
parsed_rows=assembled,
file_meta=FileMeta(
source_file_id=record.file_id,
file_version=record.file_version,
file_sha256=record.sha256,
),
now=now,
)
reinserted += outcome.inserted
date_skipped += outcome.date_skipped
if outcome.inserted or outcome.updated:
file_collapses = _detect_natural_key_collapses(assembled)
for collapse in file_collapses:
db.session.add(_natural_key_collapse_event(
source_code=source_code, collapse=collapse, record_kind=kind,
))
collapses += len(file_collapses)
file_summaries.append({
"file_id": record.file_id,
"sha256": record.sha256,
"archived_at": record.archived_at.isoformat(),
"inserted": outcome.inserted,
})
# [STEP 5] 审计 + commit。
db.session.add(build_transfer_audit_event(
event_type=REPARSE_EVENT,
aggregate_type="transfer_source",
aggregate_id=source_code,
actor_type="user",
actor_id=operator,
actor_display=operator,
result="success",
after={
"operator": operator,
"source_code": source_code,
"record_kind": kind,
"files": [
{"file_id": record.file_id, "sha256": record.sha256}
for record, _assembled in prepared
],
"profile_code": profile.profile_code,
"profile_version": profile.version,
"cleared": len(deletable),
"reinserted": reinserted,
"date_skipped": date_skipped,
"kept": kept_unrebuildable,
"unlinked_items": unlinked_items,
"collapses": collapses,
},
))
db.session.commit()
return ReparseOutcome(
source_code=source_code,
record_kind=kind,
cleared=len(deletable),
reinserted=reinserted,
date_skipped=date_skipped,
kept_unrebuildable=kept_unrebuildable,
unlinked_items=unlinked_items,
collapses=collapses,
files=tuple(file_summaries),
)
@@ -1,22 +1,43 @@
"""在途调拨历史待处理池与老化分级。
"""services/in_transit_transfer/backlog_service.py
在途调拨历史待处理池与老化分级 + 首页「待匹配」桶(D16)。
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。
依赖:models、status。
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘;
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部出入站记录,
规格 §10/D16:只读清单 + 计数,不可勾选执行)。
依赖:models、status、matching_service(待匹配全量圈档 + 启用类型范围并集)。
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
manually_closed / success / duplicate_success 永久排除。
待匹配桶=成熟未占用的出入站全量(pending_ledger_query:未封存/有异动日期/
未被有效 items 占用/T−2,不按调拨类型范围过滤)。清单再按来源+记录类型+
外部单号合计数量,不再展开外部项次;没有外部单号的档行仍逐行返回。
首页待匹配、可匹配计数与清单行数同一合并口径。【2026-10-22 SQL 下推】
计数=合并键 GROUP BY 计数、清单分页=组首行锚点 OFFSET/LIMIT 后只召回
本页档行、行桶汇总=轻量元组单条查询;口径不变,禁止再整段装载内存切片。池行带出生匹配的
transfer_type,供待恢复/已关闭/结果未知表展示调拨类别。可匹配=启用类型范围并集,
供库存匹配卡计数,并给清单行打 matchable。无 item_id 不可执行;
匹配圈定后记录离开本桶,
取消匹配释放后回归。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Optional
from decimal import Decimal, InvalidOperation
from typing import Any, Optional
from sqlalchemy import func
from sqlalchemy import String, and_, case, cast, func, literal, or_
from sqlalchemy.orm import joinedload
from app import db
from app.models import TransferAttempt, TransferInvoiceItem
from app.models import TransferAttempt, TransferInvoiceItem, TransferMovementLedger
from app.services.in_transit_transfer.matching_service import (
circle_ledger_record_ids_scope_union,
pending_ledger_query,
transfer_type_code_of,
)
from app.services.in_transit_transfer.status import TransferStatus
AGING_NORMAL = "normal"
@@ -28,6 +49,32 @@ AGING_CLOSED = "closed"
_BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
# 结果筛选切片(前端首页计数卡切片与池内筛选同口径);all=三态并集。
RESULT_FILTER_RECOVERABLE = "recoverable"
RESULT_FILTER_CLOSED = "closed"
RESULT_FILTER_UNKNOWN = "unknown"
RESULT_FILTER_ALL = "all"
_ALL_BACKLOG_STATUSES = (
_BACKLOG_RECOVERABLE,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
)
_RESULT_FILTER_STATUSES: dict[str, tuple[str, ...]] = {
RESULT_FILTER_ALL: _ALL_BACKLOG_STATUSES,
RESULT_FILTER_RECOVERABLE: (_BACKLOG_RECOVERABLE,),
RESULT_FILTER_CLOSED: (TransferStatus.MANUALLY_CLOSED.value,),
RESULT_FILTER_UNKNOWN: (TransferStatus.RESULT_UNKNOWN.value,),
}
RESULT_FILTER_CHOICES = (RESULT_FILTER_ALL, *_RESULT_FILTER_STATUSES.keys())
# 服务端分页默认值/上限(与已执行单 /documents 接口同口径:默认 20、上限 100)。
BACKLOG_PAGE_DEFAULT = 1
BACKLOG_PAGE_SIZE_DEFAULT = 20
BACKLOG_PAGE_SIZE_MAX = 100
# 跨页全选 id 上限(2026-10-22):防误拉超大规模池;超出截断并由 API 透出
# truncated 标记(千行级池单次全量 id 拉取成本可忽略,上限为防御性兜底)。
BACKLOG_SELECT_ALL_MAX = 5000
@dataclass(frozen=True)
class BacklogItemDTO:
@@ -42,20 +89,47 @@ class BacklogItemDTO:
age_days: int
aging_level: str
last_attempt_at: Optional[str] = None
receipt_date: Optional[str] = None
movement_date: Optional[str] = None
material_name: Optional[str] = None
from_warehouse: Optional[str] = None
to_warehouse: Optional[str] = None
lot_no: Optional[str] = None
receipt_quantity: Optional[str] = None
movement_quantity: Optional[str] = None
external_quantity: Optional[str] = None
# 最近一次结果码(如 blocked_file_removed);供前端区分「文件已移除」徽标
result_code: Optional[str] = None
# 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。
transfer_type: str = ""
@dataclass(frozen=True)
class PendingMatchRecordDTO:
"""「待匹配」桶单项(D16):按外部单号收口后的只读投影——无 item_id,不可勾选执行。
有外部单号时,同一来源、同一记录类型下的多项次合成一行。quantity 为这些档行
数量之和(Decimal 文本,与 items.movement_quantity 同约定)。没有外部单号的
档行仍逐行返回。单号/料号/品名/异动日期在组内不一致时为空,前端显示占位。
ledger_record_id 是组内最小档 id,只作行键,不代表整组只有这一条档。
"""
ledger_record_id: int
doc_no: str
material_code: Optional[str] = None
material_name: Optional[str] = None
movement_date: Optional[str] = None
source_code: str = ""
# 档记录类型(inbound/outbound)。
record_kind: str = "inbound"
# 外部单号(WMS Order #)。空串=该行没有外部单号,未与其他行合并。
external_doc_no: str = ""
quantity: Optional[str] = None
# 当前启用类型范围并集罩得住。分段查询里同一组的标记一致。
matchable: bool = False
@dataclass
class BacklogSummaryDTO:
"""待处理池汇总(含老化分级计数)。"""
"""待处理池汇总(含老化分级计数 + 待匹配桶计数)。"""
recoverable_count: int = 0
closed_count: int = 0
@@ -63,6 +137,36 @@ class BacklogSummaryDTO:
warn_3d: int = 0
escalate_5d: int = 0
critical_7d: int = 0
# 首页「待匹配」卡:与待匹配清单同一合并口径的行数(不含类型范围)。
pending_match_count: int = 0
# 首页「匹配可调拨库存」卡:与清单「当前可匹配」同一合并口径的行数。
matchable_count: int = 0
@dataclass(frozen=True)
class BacklogPageDTO:
"""待处理池分页结果(2026-10-16 服务端分页:池为无界增长集合,
全量拉取在千行级放大网络载荷与老化批量查询规模;items=当前页切片,
total=筛选后全量计数供前端分页器)。"""
items: list[BacklogItemDTO]
total: int
page: int
page_size: int
_PENDING_SEGMENTS = ("all", "matchable", "outside")
@dataclass(frozen=True)
class PendingMatchPageDTO:
"""「待匹配」桶分页结果。total 与 records 都是外部单号合并后的行,
不是档行数。没有外部单号的档行仍各占一行。"""
records: list[PendingMatchRecordDTO]
total: int
page: int
page_size: int
def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str:
@@ -100,40 +204,55 @@ def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
return {item_id: latest for item_id, latest in rows}
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None):
"""待处理池基础查询(状态集合 + 可选来源/关键字过滤)。
排序:收料日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键,
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
以此排序会让正在处理的行在列表中跳位。
keyword 与前端池内筛选同字段集(Invoice/料号/品名/来源,2026-10-16 随
服务端分页下推),大小写不敏感子串匹配(ilike)。
Args:
now: 判定时刻(默认当前时间)。
statuses: 池内状态白名单(result_filter 切片或三态并集)。
source_code: 可选来源过滤。
keyword: 可选关键字(子串大小写不敏感)。
Returns:
BacklogItemDTO 列表。
未排序的 SQLAlchemy Query(排序由调用方统一拼 _BACKLOG_ORDER_BY)。
"""
current = now or datetime.utcnow()
query = TransferInvoiceItem.query.filter(
TransferInvoiceItem.status.in_([
_BACKLOG_RECOVERABLE,
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
]),
)
query = TransferInvoiceItem.query.filter(TransferInvoiceItem.status.in_(statuses))
if source_code:
query = query.filter_by(source_code=source_code)
pool_rows = query.order_by(
TransferInvoiceItem.receipt_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
TransferInvoiceItem.id.asc(),
).all()
latest_map = _latest_attempt_times([row.id for row in pool_rows])
if keyword:
like = f"%{keyword}%"
query = query.filter(or_(
TransferInvoiceItem.invoice_no.ilike(like),
TransferInvoiceItem.material_no.ilike(like),
TransferInvoiceItem.material_name.ilike(like),
TransferInvoiceItem.source_code.ilike(like),
))
return query
# 全链路统一业务稳定键排序(异动日期→数据源→Invoice→创建时间→id 兜底)。
_BACKLOG_ORDER_BY = (
TransferInvoiceItem.movement_date.asc().nulls_last(),
TransferInvoiceItem.source_code.asc(),
TransferInvoiceItem.invoice_no.asc(),
TransferInvoiceItem.created_at.asc(),
TransferInvoiceItem.id.asc(),
)
def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[BacklogItemDTO]:
"""池行 → DTO 组装(老化判定需 Attempt 最近时间,批量单条 GROUP BY 查询)。
Args:
rows: 当前页(或全量)池行,须已按业务稳定键排序。
current: 老化判定的当前时刻。
Returns:
BacklogItemDTO 列表(与输入同序)。
"""
latest_map = _latest_attempt_times([row.id for row in rows])
output: list[BacklogItemDTO] = []
for item in pool_rows:
for item in rows:
latest = latest_map.get(item.id)
base = latest if latest is not None else item.updated_at
age = max(0, int((current - base).total_seconds() // 86400))
@@ -153,33 +272,599 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
age_days=age,
aging_level=level,
last_attempt_at=latest.isoformat() if latest is not None else None,
receipt_date=item.receipt_date,
movement_date=item.movement_date,
material_name=item.material_name,
from_warehouse=item.from_warehouse,
to_warehouse=item.to_warehouse,
lot_no=item.lot_no,
receipt_quantity=str(item.receipt_quantity) if item.receipt_quantity is not None else None,
movement_quantity=str(item.movement_quantity) if item.movement_quantity is not None else None,
external_quantity=str(item.external_quantity) if item.external_quantity is not None else None,
result_code=item.result_code,
transfer_type=transfer_type_code_of(item),
))
return output
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
"""计算待处理池汇总计数与老化分级。"""
items = list_backlog(now=now)
summary = BacklogSummaryDTO()
for item in items:
if item.status == TransferStatus.MANUALLY_CLOSED.value:
summary.closed_count += 1
elif item.status == TransferStatus.RESULT_UNKNOWN.value:
summary.unknown_count += 1
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)——全量(兼容口径,未分页)。
排序:异动日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键,
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
以此排序会让正在处理的行在列表中跳位。
分页场景请用 list_backlog_page(2026-10-16),本函数保留供无参兼容调用。
Args:
now: 判定时刻(默认当前时间)。
source_code: 可选来源过滤。
Returns:
BacklogItemDTO 列表。
"""
current = now or datetime.utcnow()
rows = (
_backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code)
.options(joinedload(TransferInvoiceItem.matching))
.order_by(*_BACKLOG_ORDER_BY)
.all()
)
return _backlog_dtos(rows, current)
def list_backlog_page(
*,
now: datetime | None = None,
source_code: str | None = None,
keyword: str | None = None,
result_filter: str = RESULT_FILTER_ALL,
page: int = BACKLOG_PAGE_DEFAULT,
page_size: int = BACKLOG_PAGE_SIZE_DEFAULT,
) -> BacklogPageDTO:
"""待处理池分页查询(2026-10-16 服务端分页 + 筛选下推)。
【AI 触发时机】前端待处理池视图按页/筛选拉取时经 API 调用;禁止绕过
result_filter 白名单(fail-closed,非 all/recoverable/closed/unknown 由
API 层 400)。筛选(result_filter/keyword)与计数口径一致:total 为
筛选后全量计数,供前端分页器展示;老化批量查询只对当前页行执行
(千行级池的响应规模从 O(池) 降到 O(页))。
Args:
now: 判定时刻(默认当前时间)。
source_code: 可选来源过滤。
keyword: 可选关键字(Invoice/料号/品名/来源,子串大小写不敏感)。
result_filter: 结果切片(all/recoverable/closed/unknown)。
page: 页码(1 起)。
page_size: 每页行数(1..100)。
Returns:
BacklogPageDTO(items=当前页切片,total=筛选后全量计数)。
"""
current = now or datetime.utcnow()
statuses = _RESULT_FILTER_STATUSES.get(result_filter)
if statuses is None:
# 防御:API 层已做白名单 400,这里兜底回三态并集(service 直调场景不炸)
statuses = _ALL_BACKLOG_STATUSES
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
total = base.count()
rows = (
base.options(joinedload(TransferInvoiceItem.matching))
.order_by(*_BACKLOG_ORDER_BY)
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return BacklogPageDTO(items=_backlog_dtos(rows, current), total=total, page=page, page_size=page_size)
def list_backlog_item_ids(
*,
source_code: str | None = None,
keyword: str | None = None,
result_filter: str = RESULT_FILTER_ALL,
limit: int = BACKLOG_SELECT_ALL_MAX,
) -> tuple[list[int], int]:
"""跨页全选支持(2026-10-22):当前筛选下全部待处理明细 id(轻量 id 列表)。
【AI 触发时机】前端待处理池「选择全部 N 行」时经 API 调用——服务端分页下
勾选集合只能覆盖当前页,本函数按同一筛选口径取全量 id 供批量操作
(重查/恢复/关闭端点本就按 item_ids 列表逐行隔离,无需新批量契约)。
Args:
source_code: 可选来源过滤。
keyword: 可选关键字(与 list_backlog_page 同字段集)。
result_filter: 结果切片(all/recoverable/closed/unknown)。
limit: id 上限(防误拉超大规模池;超出截断,truncated 标记随 API 透出)。
Returns:
(ids, total):ids=item_id 升序列表(≤limit),total=筛选后全量计数
(含未返回部分,供前端提示截断)。
"""
statuses = _RESULT_FILTER_STATUSES.get(result_filter)
if statuses is None:
# 防御:API 层已做白名单 400,这里兜底回三态并集(service 直调场景不炸)
statuses = _ALL_BACKLOG_STATUSES
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
total = base.count()
rows = (
base.order_by(TransferInvoiceItem.id.asc())
.limit(limit)
.with_entities(TransferInvoiceItem.id)
.all()
)
return [int(row[0]) for row in rows], total
def _pending_match_dto(record, *, matchable_ids: set[int]) -> PendingMatchRecordDTO:
"""把单条档行投影成待匹配清单项,并标出是否落在启用类型范围并集内。
本函数不做外部单号合并。合并在 _aggregate_pending_match_records。
Args:
record: TransferMovementLedger 或带同名字段的行。
matchable_ids: circle_ledger_record_ids_scope_union 的 id 集合。
Returns:
只读 PendingMatchRecordDTO。无 item_id。
"""
return PendingMatchRecordDTO(
ledger_record_id=record.id,
doc_no=record.doc_no,
material_code=record.material_code,
material_name=record.material_name,
movement_date=record.movement_date,
source_code=record.source_code,
record_kind=str(getattr(record, "record_kind", None) or "inbound"),
external_doc_no=str(getattr(record, "external_doc_no", None) or ""),
quantity=record.quantity,
matchable=record.id in matchable_ids,
)
def _uniform_text(values: list[object]) -> str | None:
"""组内去掉空白后只有一个取值时返回它。
核心逻辑:空串不参与比较;出现第二个不同取值即视为不一致。
Args:
values: 档行上的文本字段。None 与空白视为没有值。
Returns:
唯一非空文本;没有值或取值不一致时返回 None。
"""
seen: list[str] = []
for raw in values:
text = str(raw or "").strip()
if not text or text in seen:
continue
seen.append(text)
if len(seen) > 1:
return None
return seen[0] if seen else None
def _sum_quantity_text(values: list[object]) -> str | None:
"""把一组数量文本相加,输出不带多余尾零的十进制文本。
核心逻辑:能解析的按 Decimal 相加;全组都无法解析时保留第一条非空原文,
避免把脏数据收成空白。
Args:
values: 档上的 quantity 文本。
Returns:
合计文本;全空时返回 None。
"""
total = Decimal(0)
seen = False
fallback: str | None = None
for raw in values:
text = str(raw or "").strip()
if not text:
continue
if fallback is None:
fallback = text
try:
total += Decimal(text)
except InvalidOperation:
continue
seen = True
if not seen:
return fallback
rendered = format(total, "f")
if "." in rendered:
rendered = rendered.rstrip("0").rstrip(".")
return rendered or "0"
def _pending_match_group_key(record: PendingMatchRecordDTO) -> tuple:
"""待匹配清单的合并键。
有外部单号时按来源、记录类型、外部单号合并,项次不进键。
没有外部单号时每条档单独成组,避免把互无关的行加成一笔。
Args:
record: 尚未合并的单条档投影。
Returns:
可哈希分组键。
"""
external_doc_no = record.external_doc_no.strip()
if external_doc_no:
return ("external", record.source_code, record.record_kind, external_doc_no)
return ("line", record.ledger_record_id)
def _collapse_pending_match_group(rows: list[PendingMatchRecordDTO]) -> PendingMatchRecordDTO:
"""把同一合并键下的档行收成清单上的一行。
核心逻辑:数量相加;单号、料号、品名、异动日期只在组内一致时保留。
行键用最小档 id,保证翻页和表格行键稳定。
Args:
rows: 同一组合并键下的档投影,至少一条。
Returns:
合并后的 PendingMatchRecordDTO。
"""
head = rows[0]
external_doc_no = head.external_doc_no.strip()
return PendingMatchRecordDTO(
ledger_record_id=min(row.ledger_record_id for row in rows),
doc_no=_uniform_text([row.doc_no for row in rows]) or "",
material_code=_uniform_text([row.material_code for row in rows]),
material_name=_uniform_text([row.material_name for row in rows]),
movement_date=_uniform_text([row.movement_date for row in rows]),
source_code=head.source_code,
record_kind=head.record_kind,
external_doc_no=external_doc_no,
quantity=_sum_quantity_text([row.quantity for row in rows]),
matchable=all(row.matchable for row in rows),
)
def _aggregate_pending_match_records(records: list[PendingMatchRecordDTO]) -> list[PendingMatchRecordDTO]:
"""按外部单号合并待匹配清单,并保持档查询的先后顺序。
核心逻辑:沿用 pending_ledger_query 的排序(异动日期 → 来源 → 单号 → id)。
一组的位置取该组第一条档的位置,这样同一外部单号不会被分页切开后再加总。
Args:
records: 未合并的档投影,已按圈档稳定排序。
Returns:
合并后的清单。没有外部单号的行原样留下。
"""
grouped: dict[tuple, list[PendingMatchRecordDTO]] = {}
order: list[tuple] = []
for record in records:
key = _pending_match_group_key(record)
bucket = grouped.get(key)
if bucket is None:
grouped[key] = [record]
order.append(key)
else:
summary.recoverable_count += 1
if item.aging_level == AGING_WARN_3D:
bucket.append(record)
return [_collapse_pending_match_group(grouped[key]) for key in order]
def _load_pending_match_records(*, segment: str, matchable_ids: set[int]) -> list[PendingMatchRecordDTO]:
"""读取一段待匹配档并按外部单号合并。
分页单位是合并后的外部单,所以这里先取整段再合并,不能先按档行 limit。
Args:
segment: all、matchable 或 outside。调用方已校验。
matchable_ids: 启用类型范围并集的档 id。
Returns:
该段合并后的全量清单。
"""
rows = pending_ledger_query(matchable_ids=matchable_ids, segment=segment).all()
return _aggregate_pending_match_records([
_pending_match_dto(record, matchable_ids=matchable_ids) for record in rows
])
def _count_pending_match_groups(query) -> int:
"""按清单合并键计数,不把档行装进内存。
核心逻辑:有外部单号(去掉首尾空白后非空)时按来源、记录类型、外部单号分组;
没有外部单号时一行一组。分组键与 _pending_match_group_key 一致。
查询上的排序会拿掉,否则数据库拒绝按非分组列排序。
Args:
query: pending_ledger_query 的某一段。
Returns:
合并后的行数。
"""
external = func.trim(func.coalesce(TransferMovementLedger.external_doc_no, ""))
grouped_kind = case((external != "", literal("external")), else_=literal("line"))
grouped_source = case((external != "", TransferMovementLedger.source_code), else_=literal(""))
grouped_record_kind = case((external != "", TransferMovementLedger.record_kind), else_=literal(""))
grouped_doc = case((external != "", external), else_=cast(TransferMovementLedger.id, String))
grouped = (
query.order_by(None)
.with_entities(grouped_kind, grouped_source, grouped_record_kind, grouped_doc)
.group_by(grouped_kind, grouped_source, grouped_record_kind, grouped_doc)
.subquery()
)
return int(db.session.query(func.count()).select_from(grouped).scalar() or 0)
def _matchable_ids() -> set[int]:
"""启用类型现在圈得住的档 id。无启用类型时为空集。只取 id,不装载整行。"""
return circle_ledger_record_ids_scope_union()
def list_pending_match_records(*, segment: str = "all") -> list[PendingMatchRecordDTO]:
"""首页待办看板「待匹配」桶清单(已抓取尚未匹配的外部异动记录,只读)。
数据源=pending_ledger_query:未封存、有异动日期、未被有效 items 占用、
movement_date ≤ T−2 的出入站记录,不按调拨类型范围过滤。
segment=matchable 只留启用类型范围并集;segment=outside 是其余已落档。
每行 matchable 标记并集成员,供清单把「当前可匹配」和其余行分开。
【2026-10-22 清单收口】返回前按来源 + 记录类型 + 外部单号合并,quantity
为组内数量之和;没有外部单号的档行不合并。首页计数走同一合并。
数字变化口径:文件落地→涨;被匹配圈定→离开(占用);取消匹配→回归;
执行成功→封存恒排除。停用类型只减少可匹配行,不把其余行移出本桶。
不可执行:记录尚未经匹配/库存核对(无 items),本桶仅提供只读清单与
「去匹配」引导,禁止任何勾选执行入口。
Args:
segment: all、matchable 或 outside。
Returns:
合并后的 PendingMatchRecordDTO 列表。一组的位置取其最早一条档
(异动日期 → 来源 → 单号 → id)。
Raises:
ValidationError: segment 不是上述三值。
"""
from app.core.errors import ValidationError
if segment not in _PENDING_SEGMENTS:
raise ValidationError("segment must be all, matchable, or outside")
return _load_pending_match_records(segment=segment, matchable_ids=_matchable_ids())
def list_pending_match_records_page(
*,
page: int = BACKLOG_PAGE_DEFAULT,
page_size: int = BACKLOG_PAGE_SIZE_DEFAULT,
segment: str = "all",
) -> PendingMatchPageDTO:
"""「待匹配」桶分页清单(服务端分页;只读语义与全量版一致)。
【2026-10-22 分页下推】总数与页圈定都在 SQL 完成:total=合并键 GROUP BY
计数(_count_pending_match_groups);本页组经 row_number 组首行锚点
OFFSET/LIMIT 圈定(_pending_group_anchor_rows),再只召回本页组的档行做
合并投影(_load_page_group_records)——分页单位仍是外部单,但不能先按档行
limit(同一外部单号会被切进两页),也不能整段装载后内存切片(千行级池上
每页都 O(全池))。
Args:
page: 页码(1 起)。
page_size: 每页行数(1..100)。
segment: all、matchable 或 outside。
Returns:
PendingMatchPageDTO(records=当前页切片,total=该段合并后的行数)。
Raises:
ValidationError: segment 不是上述三值。
"""
from app.core.errors import ValidationError
if segment not in _PENDING_SEGMENTS:
raise ValidationError("segment must be all, matchable, or outside")
matchable_ids = _matchable_ids()
base = pending_ledger_query(matchable_ids=matchable_ids, segment=segment)
total = _count_pending_match_groups(base)
start = (page - 1) * page_size
anchors = _pending_group_anchor_rows(base, offset=start, limit=page_size) if total > start else []
records = _load_page_group_records(base, anchors, matchable_ids=matchable_ids) if anchors else []
return PendingMatchPageDTO(
records=records,
total=total,
page=page,
page_size=page_size,
)
def _pending_group_anchor_rows(base, *, offset: int, limit: int) -> list[Any]:
"""按合并键取一页「组首行」锚点(row_number 窗口下推,不装载整段档行)。
核心逻辑:分区键与 _count_pending_match_groups / _pending_match_group_key
同一口径(外部单号去空白非空=来源+记录类型+外部单号一组;否则每行一组);
分区排序与 pending_ledger_query 的圈档稳定排序一致(异动日期→来源→单号→
id),rn=1 即该组在清单上的第一条档——组位置语义与
_aggregate_pending_match_records「一组的位置取其第一条档」完全一致,
翻页顺序与全量版逐行相同。
Args:
base: pending_ledger_query 的某一段(已含固定条件与分段过滤)。
offset: 起始组数((page-1)*page_size)。
limit: 本页组数(page_size)。
Returns:
锚点行列表(属性 id/movement_date/source_code/doc_no/group_kind/
group_source/group_record_kind/group_doc),按组首行位置排序。
"""
external = func.trim(func.coalesce(TransferMovementLedger.external_doc_no, ""))
group_kind = case((external != "", literal("external")), else_=literal("line"))
group_source = case((external != "", TransferMovementLedger.source_code), else_=literal(""))
group_record_kind = case((external != "", TransferMovementLedger.record_kind), else_=literal(""))
group_doc = case((external != "", external), else_=cast(TransferMovementLedger.id, String))
ledger_order = (
TransferMovementLedger.movement_date.asc(),
TransferMovementLedger.source_code.asc(),
TransferMovementLedger.doc_no.asc(),
TransferMovementLedger.id.asc(),
)
ranked = (
base.order_by(None)
.with_entities(
TransferMovementLedger.id.label("id"),
TransferMovementLedger.movement_date.label("movement_date"),
TransferMovementLedger.source_code.label("source_code"),
TransferMovementLedger.doc_no.label("doc_no"),
group_kind.label("group_kind"),
group_source.label("group_source"),
group_record_kind.label("group_record_kind"),
group_doc.label("group_doc"),
func.row_number().over(
partition_by=(group_kind, group_source, group_record_kind, group_doc),
order_by=ledger_order,
).label("rn"),
)
.subquery()
)
return (
db.session.query(
ranked.c.id,
ranked.c.movement_date,
ranked.c.source_code,
ranked.c.doc_no,
ranked.c.group_kind,
ranked.c.group_source,
ranked.c.group_record_kind,
ranked.c.group_doc,
)
.filter(ranked.c.rn == 1)
.order_by(
ranked.c.movement_date.asc(),
ranked.c.source_code.asc(),
ranked.c.doc_no.asc(),
ranked.c.id.asc(),
)
.offset(offset)
.limit(limit)
.all()
)
def _load_page_group_records(
base,
anchors: list[Any],
*,
matchable_ids: set[int],
) -> list[PendingMatchRecordDTO]:
"""只召回本页各组涉及的档行,复用 Python 合并投影出页内清单。
核心逻辑:外部单号组按 (来源, 记录类型, trim(外部单号)) 条件召回兄弟行,
行组按锚点 id 召回;装载量只随本页组数与组内项次数增长,不受池规模影响。
召回行沿用 _pending_match_dto + _aggregate_pending_match_records 收口,
口径与全量版完全一致(含 matchable=组内全部行可匹配);最后按锚点顺序
还原页序(召回顺序是档序,不是组序)。
Args:
base: pending_ledger_query 的某一段(与锚点同一查询,口径天然一致)。
anchors: _pending_group_anchor_rows 的本页锚点,非空。
matchable_ids: 启用类型范围并集的档 id(matchable 标记用)。
Returns:
本页合并后的清单,顺序与锚点(组首行位置)一致。
"""
external_keys: list[tuple[str, str, str]] = []
line_ids: list[int] = []
for anchor in anchors:
if anchor.group_kind == "external":
external_keys.append((anchor.group_source, str(anchor.group_record_kind or "inbound"), anchor.group_doc))
else:
line_ids.append(anchor.id)
conds = []
if external_keys:
conds.append(or_(*[
and_(
TransferMovementLedger.source_code == source,
TransferMovementLedger.record_kind == record_kind,
func.trim(func.coalesce(TransferMovementLedger.external_doc_no, "")) == doc,
)
for source, record_kind, doc in external_keys
]))
if line_ids:
conds.append(TransferMovementLedger.id.in_(line_ids))
rows = (
base.filter(or_(*conds))
.order_by(
TransferMovementLedger.movement_date.asc(),
TransferMovementLedger.source_code.asc(),
TransferMovementLedger.doc_no.asc(),
TransferMovementLedger.id.asc(),
)
.all()
)
merged = _aggregate_pending_match_records([
_pending_match_dto(row, matchable_ids=matchable_ids) for row in rows
])
# 页序还原:合并键与锚点分区键同构(record_kind 与 DTO 投影同样取
# 「空回退 inbound」),据此把组序从档序纠正回组首行位置序。
position = {
(("external", anchor.group_source, str(anchor.group_record_kind or "inbound"), anchor.group_doc)
if anchor.group_kind == "external" else ("line", anchor.id)): index
for index, anchor in enumerate(anchors)
}
return sorted(merged, key=lambda record: position[_pending_match_group_key(record)])
def _pending_match_counts() -> tuple[int, int]:
"""首页待匹配、可匹配计数,与清单合并后的行数一致。
核心逻辑:在数据库里按外部单号合并键计数,不把整段档行装进 Python。
可匹配 id 为空时直接记 0,不再扫一遍全量。
Returns:
(pending_match_count, matchable_count)。
"""
matchable_ids = _matchable_ids()
pending_count = _count_pending_match_groups(
pending_ledger_query(matchable_ids=matchable_ids, segment="all"),
)
if not matchable_ids:
return pending_count, 0
matchable_count = _count_pending_match_groups(
pending_ledger_query(matchable_ids=matchable_ids, segment="matchable"),
)
return pending_count, matchable_count
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
"""计算待处理池汇总计数、老化分级与待匹配桶计数。
【2026-10-22 汇总下推】行桶汇总单条查询取 (status, 老化基准时刻) 轻量元组:
老化基准=最近 Attempt 时刻(LEFT JOIN GROUP BY 子查询,与
_latest_attempt_times 同口径),无 Attempt 回退 updated_at;三态计数与
老化分级在 Python 单趟折叠。不再经 list_backlog 整池装载 ORM 实体(含
matching joinedload)——千行级池上 summary 的行桶部分从 O(池) 实体 +
Attempt 批查降到 1 条轻量查询。待匹配/可匹配计数走 _pending_match_counts
(SQL 按外部单号合并键计数),与清单合并后的行数一致。
Args:
now: 老化判定的当前时刻(默认当前时间;测试注入用)。
Returns:
BacklogSummaryDTO(三态计数 + warn_3d/escalate_5d/critical_7d +
pending_match_count/matchable_count)。
"""
current = now or datetime.utcnow()
summary = BacklogSummaryDTO()
latest_attempt = (
db.session.query(TransferAttempt.item_id, func.max(TransferAttempt.created_at).label("latest"))
.group_by(TransferAttempt.item_id)
.subquery()
)
rows = (
db.session.query(
TransferInvoiceItem.status,
func.coalesce(latest_attempt.c.latest, TransferInvoiceItem.updated_at),
)
.outerjoin(latest_attempt, latest_attempt.c.item_id == TransferInvoiceItem.id)
.filter(TransferInvoiceItem.status.in_(_ALL_BACKLOG_STATUSES))
.all()
)
for status, base_time in rows:
# [STEP 1] 三态计数:closed/unknown 单独计数且不进老化桶(与
# _backlog_dtos 的 AGING_CLOSED/AGING_UNKNOWN 口径一致)。
if status == TransferStatus.MANUALLY_CLOSED.value:
summary.closed_count += 1
continue
if status == TransferStatus.RESULT_UNKNOWN.value:
summary.unknown_count += 1
continue
# [STEP 2] 可恢复行的老化分级(天数算法与 _backlog_dtos 一致)。
summary.recoverable_count += 1
age = max(0, int((current - base_time).total_seconds() // 86400))
level = aging_level_for(age)
if level == AGING_WARN_3D:
summary.warn_3d += 1
elif item.aging_level == AGING_ESCALATE_5D:
elif level == AGING_ESCALATE_5D:
summary.escalate_5d += 1
elif item.aging_level == AGING_CRITICAL_7D:
elif level == AGING_CRITICAL_7D:
summary.critical_7d += 1
# [待匹配桶计数] 与行桶相互独立,并与清单外部单号合并后的行数一致。
summary.pending_match_count, summary.matchable_count = _pending_match_counts()
return summary
@@ -3,7 +3,13 @@
用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销;
原因必填;取消前后状态进入审计。
依赖:models、status、core.errors。
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消;
Run 转取消时其名下匹配(TransferMatching)同步转 cancelled,并按
matching_id 圈定名下 ready 未建单行退役为 cancelled——
【出生翻转/D17 占用释放出口(规格 §9)】出生行 run_id=None,必须按匹配
圈定才能命中:ready 行退役(队列不再可见、执行门禁拒绝)+ 匹配→cancelled
(阻断行不再占用其圈定的档记录),档记录随即释放、可被后续匹配
重新圈定;取消路径不写档(占用释放由状态判定自然达成)。
"""
from __future__ import annotations
@@ -12,7 +18,7 @@ from datetime import datetime
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import TransferInvoiceItem, TransferRun
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
from app.services.in_transit_transfer import status as status_machine
@@ -60,6 +66,28 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
).count()
if active == 0:
run.status = status_machine.TransferRunStatus.CANCELLED.value
# [D17 占用释放 + 可执行行退役(规格 §9)] Run 取消时名下未终态匹配同步
# 转 cancelled,并按 matching_id 圈定其名下 items 退役:
# - ready 且未建单的行 → cancelled(出生行 run_id=None,必须按匹配圈定
# 才能命中——否则取消后行仍 ready,队列双份可见、可与重圈匹配双双
# 执行=同批档记录二次写 ERP);
# - blocked 行保留阻断解释(不占执行面),其占用
# 随匹配状态=cancelled 释放(占用判定见 matching_service);
# - executing/result_unknown 行不触碰(在飞/结果裁决中,既有取消语义)。
# 取消路径不写档(占用释放由状态判定自然达成)。
for matching in db.session.query(TransferMatching).filter_by(run_id=run.id).all():
if matching.status in {"success", "failed", "cancelled", "expired"}:
continue
matching.status = status_machine.TransferRunStatus.CANCELLED.value
for item in db.session.query(TransferInvoiceItem).filter_by(matching_id=matching.id).all():
if (
item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value
and not item.external_document_no
):
item.status = status_machine.TransferStatus.CANCELLED.value
item.result_code = "cancelled"
item.result_message = reason_value
cancelled += 1
run.completed_at = run.completed_at or datetime.utcnow()
db.session.commit()
return {"run_no": run.run_no, "cancelled_count": cancelled}
@@ -14,8 +14,9 @@ from decimal import Decimal
from typing import Iterable
# ---- 一期冻结错误码(TDD §7.3)-------------------------------------------
# 【TRANSFER_INBOUND_NOT_MATURED 已退役 2026-10-16】成熟概念删除(未上线期不设
# 兼容层);前端四语言 errors.json 同键一并移除。
TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED"
TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED"
TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
@@ -32,7 +33,6 @@ TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED"
KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
TRANSFER_PERMISSION_DENIED,
TRANSFER_RECEIPT_NOT_MATURED,
TRANSFER_FILE_NOT_READY,
TRANSFER_FILE_SCHEMA_INVALID,
TRANSFER_INVOICE_CONFLICT,
@@ -67,7 +67,6 @@ class MatchingCountsDTO:
"""匹配计数。"""
file_invoice_count: int = 0
not_matured_count: int = 0
matched_count: int = 0
executable_count: int = 0
blocked_count: int = 0
@@ -101,13 +100,13 @@ class MatchingItemDTO:
to_warehouse: str
to_quantity: Decimal
result: str
receipt_date: str | None = None
movement_date: str | None = None
reason: str = ""
external_document_no: str | None = None
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
lot_no: str = ""
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
receipt_warehouse_code: str = ""
# 入站文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
movement_warehouse_code: str = ""
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):展示与 ERP 写入行输入,
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
unit: str = ""
@@ -122,6 +121,9 @@ class MatchingItemDTO:
# (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐,
# 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。
external_org: str = ""
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
# 无匹配或快照未写类型时为空串。
transfer_type: str = ""
@dataclass(frozen=True)
@@ -129,14 +131,13 @@ class MatchingSummaryDTO:
"""匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。
estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单
五元组 (external_org, source_code, receipt_date, from_warehouse, to_warehouse)
五元组 (external_org, source_code, movement_date, from_warehouse, to_warehouse)
去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。
"""
matching_id: str
status: str
business_date: str
eligible_receipt_date_to: str
expires_at: str
counts: MatchingCountsDTO
estimated_transfer_quantity: str
@@ -0,0 +1,171 @@
"""services/in_transit_transfer/current_file_reparse.py
用途:对当前最新可用入站/出站归档做一次本地重解析并落档(不触发 RPA)。
依赖:evidence_sync.sync_source_rows、outbound_evidence_sync.sync_outbound_source_rows、
source_file_status(latest_usable_outbound_file、resolve_source_file_status)、
freight_rpa.reports.queries(latest_usable_inbound_file、mark_inbound_parse_failure、
mark_outbound_parse_failure)、date_policy.business_date_now、deps.get_transfer_dependencies、
file_parser.MovementFileSchemaError、core.errors、flask.current_app(非 schema 失败记日志)。
逻辑:先确认可用归档与已发布规则门禁,再委托既有 sync_*_source_rows 落档并 commit;
schema 失败 rollback 后 mark 解析失败并单独 commit;无规则/无文件 fail-closed;
其他异常(含非 NO_PROFILE 的 AppError)rollback、记日志、不标 parse_failed,返回 ok=False。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from flask import current_app
from app import db
from app.core.errors import AppError, ValidationError
from app.services.freight_rpa.reports.queries import (
latest_usable_inbound_file,
mark_inbound_parse_failure,
mark_outbound_parse_failure,
)
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.deps import get_transfer_dependencies
from app.services.in_transit_transfer.evidence_sync import sync_source_rows
from app.services.in_transit_transfer.file_parser import MovementFileSchemaError
from app.services.in_transit_transfer.outbound_evidence_sync import sync_outbound_source_rows
from app.services.in_transit_transfer.source_file_status import (
latest_usable_outbound_file,
resolve_source_file_status,
)
_RECORD_KINDS = frozenset({"inbound", "outbound"})
@dataclass(frozen=True)
class CurrentReparseResult:
"""一次当前归档重解析的返回。"""
source_code: str
record_kind: str
ok: bool
file_status: str
file_id: int | None
inserted: int = 0
updated: int = 0
skipped: int = 0
sealed_skipped: int = 0
error_code: str | None = None
error_message: str | None = None
def reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult:
"""重解析该来源当前最新可用归档并提交。
核心逻辑:先取 latest usable 文件。没有文件抛 CURRENT_REPARSE_NO_FILE。
有文件则调用既有 sync_*_source_rows。返回 None 表示没有已发布规则,抛
CURRENT_REPARSE_NO_PROFILE,不写 parse_failed。结构错误回滚后 mark_*_parse_failure
并单独提交。其他异常(含非 NO_PROFILE 的 AppError,如存储不可用)只回滚、
记 TRANSFER_CURRENT_REPARSE_FAILED 日志,不标解析失败,返回 ok=False。
error_message 取异常 message,为空再退回 str(exc)。成功路径由 sync 函数里的
movement_file_version 写版本戳,本函数不拼 sha256: 前缀。
Args:
source_code: 来源实例编码。
record_kind: inbound 或 outbound。
now: 落档与新鲜度判定时刻。
Returns:
CurrentReparseResult。结构错误和其他落档异常(含非 NO_PROFILE 的 AppError)时 ok 为 False。
Raises:
ValidationError: record_kind 不是 inbound 或 outbound。
AppError: 仅 TRANSFER.CURRENT_REPARSE_NO_FILE 或 TRANSFER.CURRENT_REPARSE_NO_PROFILE,HTTP 422。
"""
kind = record_kind.strip()
if kind not in _RECORD_KINDS:
raise ValidationError("record_kind must be inbound or outbound")
if kind == "outbound":
file_view = latest_usable_outbound_file(source_code, now=now)
else:
file_view = latest_usable_inbound_file(source_code, now=now)
if file_view is None:
raise AppError(
code="TRANSFER.CURRENT_REPARSE_NO_FILE",
message="no usable archive file",
http_status=422,
details={"source_code": source_code, "record_kind": kind},
)
file_id = file_view.file_id
try:
if kind == "outbound":
outcome = sync_outbound_source_rows(source_code=source_code, now=now)
else:
outcome = sync_source_rows(
source_code=source_code,
deps=get_transfer_dependencies(),
business_date=business_date_now(),
now=now,
)
if outcome is None:
raise AppError(
code="TRANSFER.CURRENT_REPARSE_NO_PROFILE",
message="no published parsing profile",
http_status=422,
details={"source_code": source_code, "record_kind": kind},
)
db.session.commit()
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
return CurrentReparseResult(
source_code=source_code,
record_kind=kind,
ok=True,
file_status=str(status["file_status"]),
file_id=file_id,
inserted=outcome.inserted,
updated=outcome.updated,
skipped=outcome.skipped,
sealed_skipped=outcome.sealed_skipped,
)
except MovementFileSchemaError as exc:
db.session.rollback()
error_message = (getattr(exc, "message", "") or str(exc))[:2000]
error_code = exc.code
if kind == "outbound":
mark_outbound_parse_failure(
file_id, error_code=error_code, error_message=error_message)
else:
mark_inbound_parse_failure(
file_id, error_code=error_code, error_message=error_message)
db.session.commit()
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
return CurrentReparseResult(
source_code=source_code,
record_kind=kind,
ok=False,
file_status=str(status["file_status"]),
file_id=file_id,
error_code=error_code,
error_message=error_message,
)
except Exception as exc:
# 无已发布规则仍是 422;其余 AppError(存储不可用等)与普通异常同一失败分支。
if isinstance(exc, AppError) and exc.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE":
raise
db.session.rollback()
current_app.logger.exception(
"TRANSFER_CURRENT_REPARSE_FAILED source=%s kind=%s",
source_code,
kind,
)
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
error_message = (getattr(exc, "message", "") or str(exc))[:500]
return CurrentReparseResult(
source_code=source_code,
record_kind=kind,
ok=False,
file_status=str(status["file_status"]),
file_id=file_id,
error_code="TRANSFER.CURRENT_REPARSE_FAILED",
error_message=error_message,
)
@@ -1,11 +1,15 @@
"""在途调拨业务日期与成熟度策略。
"""在途调拨业务日期与日期解析。
用途:固定业务时区 Asia/Shanghai,实现 T+lag 成熟规则(默认 T+2:收料日期 ≤ T-2
可匹配,T-1/当天 not_matured,未来日期阻断);统一 parse_date 归一化收料日期
(ISO + DSV SSRS 美式 MM/DD/YYYY[ HH:MM:SS])。
依赖:标准库 zoneinfo / datetime;可选 Flask current_app(读成熟滞后配置)。
用途:固定业务时区 Asia/Shanghai,统一 parse_date 归一化异动日期(ISO + DSV SSRS
美式 MM/DD/YYYY[ HH:MM:SS]);提供业务日换算、UTC 存储窗口换算与可匹配
截止日(T−2)换算。
依赖:标准库 zoneinfo / datetime。
逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync
复用,避免各服务各自计算导致口径漂移。
【T−2 管控恢复 2026-10-21】T−2 之前的数据全部成熟,T−2 之后(T−1/当天/
未来)无成熟数据不可进入异动日期范围——matching_service 以
eligible_movement_date_to 卡控范围截止;未来日期阻断(数据错误)保留。
(2026-10-16 曾随成熟规则退役放开到「截止 ≤ 业务日期」,本次按业务口径收回。)
"""
from __future__ import annotations
@@ -15,14 +19,9 @@ from zoneinfo import ZoneInfo
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
# 成熟度结果
MATURITY_ELIGIBLE = "eligible"
MATURITY_NOT_MATURED = "not_matured"
MATURITY_FUTURE = "future"
# 成熟滞后天数默认值(T+2:收料日期 ≤ T-2 才可匹配;与海外的时差余量)。
# 可经环境变量 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS 覆盖(settings 装载)。
DEFAULT_MATURITY_LAG_DAYS = 2
# 可匹配截止滞后天数:T−2 之前数据全部成熟(与前端 transferDate.ts
# DEFAULT_LOOKBACK_DAYS 同口径,两侧须同步调整)。
MOVEMENT_DATE_MAX_LAG_DAYS = 2
# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。
_US_DATE_FORMATS = (
@@ -35,7 +34,7 @@ _US_DATE_FORMATS = (
def parse_date(value: date | datetime | str) -> date:
"""将 date/datetime 或日期字符串归一化为 date。
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 收料);
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 入站文件);
均失败则 ValueError(fail-closed)。
Args:
@@ -59,7 +58,7 @@ def parse_date(value: date | datetime | str) -> date:
return datetime.fromisoformat(text).date()
except ValueError:
pass
# [STEP] DSV SSRS 收料 Date Received:美式月/日/年(可带时分秒)。
# [STEP] DSV SSRS 入站 Date Received:美式月/日/年(可带时分秒)。
for fmt in _US_DATE_FORMATS:
try:
return datetime.strptime(text, fmt).date()
@@ -84,6 +83,22 @@ def business_date_now(moment: datetime | None = None) -> date:
return moment.astimezone(SHANGHAI_TZ).date()
def eligible_movement_date_to(business_date: date | str,
lag_days: int = MOVEMENT_DATE_MAX_LAG_DAYS) -> date:
"""返回可进入异动日期范围的截止日(业务日期 T − lag 天,默认 T−2)。
【AI 触发时机】matching_service 校验异动日期范围、或任何需要「最远可选到
哪天」的场景;与前端 transferDate.ts defaultMovementDate 同口径。
Args:
business_date: 当前业务日期 T。
lag_days: 截止滞后天数;缺省 MOVEMENT_DATE_MAX_LAG_DAYS。
Returns:
T − lag 天。
"""
return parse_date(business_date) - timedelta(days=lag_days)
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
@@ -105,53 +120,3 @@ def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, dat
.replace(tzinfo=None)
)
return start_utc, start_utc + timedelta(hours=24)
def maturity_lag_days() -> int:
"""读取成熟滞后天数(app 配置优先,缺省回退 DEFAULT_MATURITY_LAG_DAYS)。
Returns:
成熟滞后天数 lag;无 Flask app 上下文(纯单元测试/脚本)时回退默认值,
保持策略函数可纯调用。
"""
try:
from flask import current_app
return int(current_app.config.get(
"IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS") or DEFAULT_MATURITY_LAG_DAYS)
except RuntimeError: # 无 app 上下文
return DEFAULT_MATURITY_LAG_DAYS
def maturity_status(receipt_date: date | str, business_date: date | str,
lag_days: int | None = None) -> str:
"""按 T+lag 规则判定收料日期成熟度(默认 lag=2)。
Args:
receipt_date: 收料日期。
business_date: 当前业务日期 T。
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
Returns:
'eligible'(receipt ≤ T-lag)、'not_matured'(T-lag < receipt ≤ T)或
'future'(receipt > T,结构化阻断)。
"""
receipt = parse_date(receipt_date)
business = parse_date(business_date)
lag = maturity_lag_days() if lag_days is None else int(lag_days)
if receipt > business:
return MATURITY_FUTURE
if receipt > business - timedelta(days=lag):
return MATURITY_NOT_MATURED
return MATURITY_ELIGIBLE
def eligible_receipt_date_to(business_date: date | str, lag_days: int | None = None) -> date:
"""返回可进入匹配的收料截止日期(业务日期 T - lag 天,默认 T-2)。
Args:
business_date: 当前业务日期。
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
Returns:
T - lag 天。
"""
lag = maturity_lag_days() if lag_days is None else int(lag_days)
return parse_date(business_date) - timedelta(days=lag)
@@ -2,8 +2,8 @@
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:movement_file_repository / capability_client / matching_service / models / Flask config。
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
逻辑:默认实现直接接线真实链路 —— 入站文件行读取走 movement_file_repository
(复用 ShippingInboundReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed);
策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_
@@ -18,9 +18,14 @@ from typing import Any
from flask import current_app
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.models import FreightRpaOnhandExternalMapping
from app.services.freight_rpa.reports.queries import (
get_inbound_config,
get_inbound_parsing_profile,
get_site,
)
from app.services.in_transit_transfer.capability_client import CapabilityClient
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
from app.services.in_transit_transfer.movement_file_repository import ShippingInboundFileRepository
from app.services.in_transit_transfer.matching_service import (
RouteMapping,
RouteNotResolvedError,
@@ -39,7 +44,7 @@ class DefaultRouteResolver:
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
inventory_match 源优先「入站文件仓库列 == 货代仓库」精确匹配,匹配不到回退
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
"""
@@ -47,24 +52,29 @@ class DefaultRouteResolver:
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
【阶段 B Task 4】站点行(主键/启停/识别方式)读取改经
freight_rpa.reports.queries.get_site 只读视图,不再引用站点模型;
外部仓库映射仍为调拨域自有表(freight_rpa_onhand_external_mappings
不改归属,见计划 Global Constraints),按站点主键直查。
Args:
source_code: 来源实例编码(须启用)。
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
warehouse_code: 入站文件「仓库」列原值(inventory_match 源的映射匹配键)。
Returns:
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
Raises:
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
"""
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
raise RouteNotResolvedError(source_code=source_code)
mappings = ShippingInventoryExternalMapping.query.filter_by(
inventory_source_id=source.id, enabled=True,
mappings = FreightRpaOnhandExternalMapping.query.filter_by(
source_id=site.source_id, enabled=True,
).all()
selected = None
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
if site.warehouse_resolution_mode == 'inventory_match':
# [匹配] 入站仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
key = str(warehouse_code or '').strip().upper()
if key:
@@ -147,7 +157,7 @@ def get_transfer_dependencies() -> TransferDeps:
if _override is not None:
return _override
return TransferDeps(
file_repository=ShippingReceiptFileRepository(),
file_repository=ShippingInboundFileRepository(),
rpa_trigger=_DefaultRpaTrigger(),
route_resolver=DefaultRouteResolver(),
capabilities=_build_capability_client(),
@@ -156,30 +166,30 @@ def get_transfer_dependencies() -> TransferDeps:
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
"""默认入站 RPA 触发器:委托真实触发服务(trigger_inbound_rpa)。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
真实链路 = 落单元行 + 原子写 trigger 文件;站点/入站配置缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时
直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。
另在本类前置守卫:入站配置存在但未绑定已发布 inbound 解析规则时
直接返回 RPA_INBOUND_PROFILE_MISSING,不触发徒劳抓取。
【阶段 B Task 4】守卫读取改经 freight_rpa.reports.queries 只读入口
(get_site / get_inbound_config / get_inbound_parsing_profile)。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
# [守卫] 入站配置存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳:
# 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is not None:
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
site = get_site(source_code)
if site is not None and site.enabled:
config = get_inbound_config(source_code)
if config is not None:
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'}
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
return {'ok': False, 'error_code': 'RPA_INBOUND_PROFILE_MISSING'}
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
outcome = trigger_inbound_rpa(source_code=source_code, business_date=business_date, reason=reason)
return {
"ok": bool(outcome.get("ok")),
"callback_id": outcome.get("callback_id"),
@@ -1,94 +1,331 @@
"""services/in_transit_transfer/evidence_sync.py
用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写,
主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。
依赖:file_parser / invoice_aggregator / transfer_type / source_file_status /
matching_service(_item_evaluated_sha、_latest_usable_report_file 复用)/
contracts / models / audit。
逻辑:一次解析写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
整行跳过(幂等,不续新鲜度);sha 变了证据没变 → 刷新名称/规格展示值并只换
版本戳;证据变了(数量/批号/仓库)→ 刷新证据并重置回待查(旧库存是对旧数量
查的,作废);历史残留 blocked_file_removed 行复现 → 无论证据变化与否无条件
恢复待查(防御路径,2026-09-28 起同步不再新产生该码);缺席存续(只换版本戳
到最新文件 sha,状态与结果码原样保留——收料 RPA 非全量导出,缺席≠删除;行
复现时经 STEP 2 正常刷新)。全程零外部调用(不查 ERP、不触发 RPA);终态行
绝不触碰,终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨);
不 commit 只 flush(提交归调用方:落地桥自行 commit,匹配/重查随主事务)。
13 状态冻结契约内表达待查态:status='matching' + result_code='pending_stock_check'。
【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析失败
标记(parse_failed 三列置空,投影恢复 ready);桥入口同步失败先 rollback
(保持桥隔离),仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID /
ReceiptFileSchemaError)把失败事实独立 commit 落到当前可用文件上。
用途:入站证据同步——把来源最新可用入站文件(freight_rpa 入站 RPA 产物)解析并镜像落档(库存异动档
transfer_movement_ledger,主链路),一次解析、写档不写明细。
依赖:file_parser / ledger_sync / freight_rpa.reports.queries(最新可用归档视图
latest_usable_inbound_file 与解析失败标记 mark/clear——只读只写入口唯一权威)/
source_file_status(状态投影)/ contracts / audit。
【阶段 B Task 4】文件取数不再经 matching_service._latest_usable_report_file
(该函数已删除),改按 source_code 直调 freight_rpa.reports.queries;解析失败
标记改按 file_id 调 mark_inbound_parse_failure / clear_inbound_parse_failure。
逻辑:【2026-10-14 出生翻转(ADR 0001/D3/D4)】本模块不再写 transfer_invoice_items
——items 改为匹配创建时从档圈定(见 matching_service);落地产物=档行:
①按自然键查档不存在 → 插入(record_kind/溯源五列随行);
②同文件重落(sha 一致)→ 幂等跳过(档无 TTL,完全不动行);
③证据变化 → 原行更新业务镜像列 + 换溯源(ledger_sync 六分类语义);
④文件缺席的档行保留不删(入站 RPA 非全量导出,缺席≠删除);
⑤已执行封存行(transfer_executed=true)永不更新永不复活。
组装口径:解析行按调拨明细粒度 (doc_no, material_code, movement_date)
聚合为领域行(数量相加、其余取组内首行、sheet/row_no 取首行)——与旧
items 汇总粒度一致(档断言等价于原 items 断言),保证「档 → 匹配圈定 →
严格数量比对」的数量语义不因翻转漂移。
全程零外部调用(不查 ERP、不触发 RPA);不 commit 只 flush(提交归调用
方:落地桥自行 commit,匹配/重查随主事务)。
【档自然键坍缩守卫 终审 I3】组装产物按档自然键行级六成分 (doc_no, line_no,
line_seq, in_out_flag, carton_id, lot_no) 复检:同键批内 ≥2 行且 material_code
不同(同单号多料号且
行级项次全空的输入)→ 每个坍缩键写一条 ledger_natural_key_collapse 审计
事件(结果=第二料号行被幂等吞掉,首见为准,数据行为不变)——把静默丢行
变显式可观测;事件只在批内实际落档(inserted/updated>0)时打,幂等重落
不重复打(防只追加审计表被同文件重落刷爆,与 ledger_sync 交叉校验事件
同款防刷口径)。
【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析
失败标记(parse_failed 三列置空);桥入口同步失败先 rollback(保持桥隔离),
仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID / MovementFileSchemaError)
把失败事实独立 commit 落到当前可用文件上。
【对齐入口退役 2026-10-14】align_scope_rows 已删除:匹配/重查不再对文件
兜底重解析,改为对档对账(重查见 retry_service.requery_items 对档 reconciliation)。
【解析口径单一化 2026-10-15(spec §6)】「原始行→档行」的解析+组装抽为模块级
纯函数 parse_archive_to_ledger_rows:运行期本模块与维护重建
(backlog_reparse_service 清空并重解析)共用同一实现,杜绝两套解析漂移;
归档字节→原始行的提取段仍在 movement_file_repository._extract_movement_rows。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import Any, Mapping
from app import db
from app.models import TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.freight_rpa.reports.queries import (
clear_inbound_parse_failure,
latest_usable_inbound_file,
mark_inbound_parse_failure,
)
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.file_parser import ReceiptFileSchemaError, parse_movement_rows
from app.services.in_transit_transfer.invoice_aggregator import aggregate_invoices
from app.services.in_transit_transfer.matching_service import (
RESULT_FILE_REMOVED,
RouteNotResolvedError,
_item_evaluated_sha,
_latest_usable_report_file,
from app.services.in_transit_transfer.file_parser import (
MovementFileSchemaError,
ParsedMovementRow,
parse_movement_rows,
)
from app.services.in_transit_transfer.source_file_status import (
clear_receipt_parse_failure,
record_receipt_parse_failure,
resolve_source_file_status,
)
from app.services.in_transit_transfer.transfer_type import (
TransferType,
filter_invoices_for_type,
from app.services.in_transit_transfer.ledger_sync import (
RECORD_KIND_INBOUND,
FileMeta,
sync_ledger_rows,
)
# 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码),
# 表示「收料文件已落地、库存侧尚未核对」;禁用新状态值。
# 表示「已出生/已重置、库存侧尚未核对」;禁用新状态值。出生翻转后该态出现在
# 匹配创建的出生行(评估前置)与重查对账的证据刷新行(重置待查)。
SYNC_RESULT_PENDING = "pending_stock_check"
# 终态集合与 matching_service 原地刷新口径一致:同步永不触碰既定事实。
_TERMINAL_ITEM_STATUSES = frozenset({
status_machine.TransferStatus.SUCCESS.value,
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
status_machine.TransferStatus.MANUALLY_CLOSED.value,
status_machine.TransferStatus.CANCELLED.value,
status_machine.TransferStatus.EXECUTING.value,
status_machine.TransferStatus.RESULT_UNKNOWN.value,
})
# 档自然键坍缩审计事件 kind(终审 I3 冻结字面量;仓库事件 kind 无集中常量表,
# 行内常量惯例——ledger_sync.LEDGER_CROSS_CHECK_EVENT 同款)。与交叉校验矛盾
# (in_out_flag 错位)分 kind:修复动作不同(前者查导出模板项次列,后者查进出
# 库别映射),运维按 kind 检索互不干扰。
LEDGER_NATURAL_KEY_COLLAPSE_EVENT = "ledger_natural_key_collapse"
@dataclass(frozen=True)
class SyncOutcome:
"""一次来源同步的结果计数(审计与兜底日志的数据源)。"""
"""一次来源落档的结果计数(审计与兜底日志的数据源;计数随 ledger_sync 同源,
date_skipped(异动日期空值)在 ledger_sync 落档过滤阶段消化,不透传本层)。"""
source_code: str
file_sha256: str
inserted: int = 0 # 文件有、本地无 → 插入待查行
refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留
reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废)
absent_kept: int = 0 # 文件里缺席 → 换戳保留状态(存续:缺席≠删除,2026-09-28)
skipped: int = 0 # sha 未变的幂等跳过;终态四元组重落地亦计入(不复活)
inserted: int = 0 # 自然键不存在 → 插入新档行
updated: int = 0 # 证据变化 → 原行更新业务镜像列 + 换溯源
skipped: int = 0 # sha 未变的幂等跳过;封存行命中亦计入(sealed_skipped 另计)
sealed_skipped: int = 0 # 封存行(transfer_executed=true):永不更新永不复活
cross_flagged: int = 0 # record_kind 与 in_out_flag 矛盾且本次实际落档的行数
def _assemble_ledger_rows(
parsed: list[ParsedMovementRow],
raw_rows: list[Any],
) -> list[dict]:
"""把解析行组装为落档领域行 dict(档断言等价于原 items 断言的粒度桥)。
核心逻辑:[STEP 1] 原始行按 (sheet, row_no) 建索引——ParsedMovementRow 无扩展
字段槽位(Task 8 事实),扩展 7 字段(line_no/line_seq/in_out_flag/order_type/
odm_*/carton_id/pallet_id 及 🔖预留)与外部单据身份(external_doc_no/
external_line_no,2026-10-21 扩展)从原始领域行 dict 取。[STEP 2] 按调拨明细
粒度 (doc_no, material_code, movement_date, 外部单号, 外部项次) 聚合:数量
Decimal 相加,其余字段取组内首行,sheet_name/row_no 取首行——与旧 aggregate_
invoices 汇总键一致,保证翻转后严格数量比对(ASN 合计 vs ERP 账面)语义不变;
外部单据身份入聚合键(2026-10-21):不同 WMS 单号/项次的行不得数量相加折叠
(外部身份是档自然键成分,折叠即丢行)。
注意:原始行无「项次」且同单号多料号时,自然键 (doc_no, line_no='', ...,
carton_id 等值, lot_no 等值) 会折叠多料号行为一条档记录(档自然键不含料号,
规格 §4.2;carton_id/lot_no 为键成分,批内等值才折叠)——真实 WMS 导出
携带项次列,不命中该形态;该坍缩形态由 _detect_natural_key_collapses 检测并
落 ledger_natural_key_collapse 审计事件(终审 I3,静默丢行 → 显式可观测)。
Args:
parsed: 已校验解析行(parse_movement_rows 产物)。
raw_rows: 原始领域行 dict 列表(ReadyInboundFile.rows,扩展字段来源)。
Returns:
领域行 dict 列表(键=movement 契约 field code + 行级溯源 sheet_name/row_no,
即 sync_ledger_rows 的 parsed_rows 契约)。
"""
raw_by_key: dict[tuple[str, Any], Mapping] = {}
for raw in raw_rows or []:
if not isinstance(raw, Mapping):
continue
raw_by_key[(str(raw.get("sheet") or "").strip(), raw.get("row_no"))] = raw
groups: dict[tuple[str, str, str, str, str], dict] = {}
ordered: list[dict] = []
for row in parsed:
raw = raw_by_key.get((row.sheet, row.row_no)) or {}
# 聚合键含外部单据身份(2026-10-21):不同外部单号/项次不折叠、不数量相加。
key = (row.invoice_no, row.material_no, row.movement_date.isoformat(),
_natural_key_text(raw.get("external_doc_no")),
_natural_key_text(raw.get("external_line_no")))
group = groups.get(key)
if group is None:
group = {
"doc_no": row.invoice_no,
# 无项次列的导出按空串落自然键(可空成分 NOT NULL + default '')。
"line_no": str(raw.get("line_no") or "").strip(),
"in_out_flag": str(raw.get("in_out_flag") or "").strip(),
"material_code": row.material_no,
"material_name": row.material_name,
"specification": row.specification,
"warehouse_code": row.warehouse_code,
"storage_code": str(raw.get("storage_code") or "").strip(),
"lot_no": row.lot_no,
"quantity": Decimal(str(row.movement_quantity)),
"unit": row.unit,
"movement_date": row.movement_date.isoformat(),
"line_seq": str(raw.get("line_seq") or "").strip(),
"order_type": str(raw.get("order_type") or "").strip(),
"odm_id": str(raw.get("odm_id") or "").strip(),
"odm_name": str(raw.get("odm_name") or "").strip(),
"carton_id": str(raw.get("carton_id") or "").strip(),
"pallet_id": str(raw.get("pallet_id") or "").strip(),
# 外部单据身份(2026-10-21 扩展:外部单号/外部项次=WMS Order #/
# 行号)——异动档自然键成分(档幂等主键管控),缺列按空串落键。
"external_doc_no": str(raw.get("external_doc_no") or "").strip(),
"external_line_no": str(raw.get("external_line_no") or "").strip(),
# 🔖预留列(出货报告确认后直接映射):入站侧照常透传原值。
"doc_nature": str(raw.get("doc_nature") or "").strip(),
"movement_type": str(raw.get("movement_type") or "").strip(),
"reason_code": str(raw.get("reason_code") or "").strip(),
"source_ref_no": str(raw.get("source_ref_no") or "").strip(),
"partner_code": str(raw.get("partner_code") or "").strip(),
"remark": str(raw.get("remark") or "").strip(),
"sheet_name": row.sheet,
"row_no": row.row_no,
}
groups[key] = group
ordered.append(group)
else:
# [数量聚合] 同 (单号,料号,日期) 多行数量相加(与旧 items 汇总同口径)。
group["quantity"] = group["quantity"] + Decimal(str(row.movement_quantity))
rows: list[dict] = []
for group in ordered:
flattened = dict(group)
flattened["quantity"] = str(group["quantity"])
rows.append(flattened)
return rows
def _natural_key_text(value: Any) -> str:
"""自然键/料号成分归一化(与 ledger_sync._key_text 同口径):None → 空串 + strip。
Args:
value: 领域行 dict 成分原值。
Returns:
可比对的归一化文本。
"""
return "" if value is None else str(value).strip()
def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
"""检测批内档自然键坍缩(终审 I3,纯函数不改行)。
【AI 触发时机】sync_source_rows 组装落档前调用;不要在匹配/执行链路调用。
判定:档自然键行级八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
lot_no, external_doc_no, external_line_no)(source_code/record_kind 整批恒定
不入键;carton_id/lot_no 随 tt14 键扩维入检;外部单据身份随 2026-10-21 键
扩维入检——批内等值才可能与既有档行同键)批内出现 ≥2 行且 material_code
不同 → 该键坍缩(落地侧第二料号行必被幂等吞掉)。同料号多行不算坍缩(数量
聚合合法形态,且规格 §4.2 判据即料号不同)。首见序返回,保证审计内容确定。
Args:
rows: _assemble_ledger_rows 产物(成分已归一化)。
Returns:
坍缩键信息列表(仅含坍缩键):doc_no/line_no/line_seq/in_out_flag/
carton_id/lot_no/external_doc_no/external_line_no + material_codes
(首见序全量料号)+ dropped_material_codes(首见后被吞料号)。
"""
seen: dict[tuple[str, ...], dict] = {}
for row in rows:
key = (
_natural_key_text(row.get("doc_no")),
_natural_key_text(row.get("line_no")),
_natural_key_text(row.get("line_seq")),
_natural_key_text(row.get("in_out_flag")),
_natural_key_text(row.get("carton_id")),
_natural_key_text(row.get("lot_no")),
_natural_key_text(row.get("external_doc_no")),
_natural_key_text(row.get("external_line_no")),
)
material = _natural_key_text(row.get("material_code"))
entry = seen.get(key)
if entry is None:
seen[key] = {"key": key, "materials": [material], "dropped": []}
elif material not in entry["materials"]:
entry["materials"].append(material)
entry["dropped"].append(material)
return [
{
"doc_no": entry["key"][0], "line_no": entry["key"][1],
"line_seq": entry["key"][2], "in_out_flag": entry["key"][3],
"carton_id": entry["key"][4], "lot_no": entry["key"][5],
"external_doc_no": entry["key"][6], "external_line_no": entry["key"][7],
"material_codes": entry["materials"],
"dropped_material_codes": entry["dropped"],
}
for entry in seen.values() if entry["dropped"]
]
def _natural_key_collapse_event(*, source_code: str, collapse: dict,
record_kind: str = RECORD_KIND_INBOUND):
"""构造档自然键坍缩审计事件(未落库,由调用方 add——build 契约同 ledger_sync)。
Args:
source_code: 来源实例编码(自然键成分,整批一致)。
collapse: _detect_natural_key_collapses 的单条坍缩键信息。
record_kind: 记录类型(入站/出站共用检测口径;聚合键与快照随流声明)。
Returns:
已计算 Hash 的 TransferAuditEvent(event_type=ledger_natural_key_collapse,
result='failure':数据质量降级——行被吞是既成事实,须运维介入核导出模板)。
"""
natural_key = "/".join((
source_code, record_kind,
collapse["doc_no"], collapse["line_no"], collapse["line_seq"], collapse["in_out_flag"],
collapse["carton_id"], collapse["lot_no"],
collapse["external_doc_no"], collapse["external_line_no"],
))
return build_transfer_audit_event(
event_type=LEDGER_NATURAL_KEY_COLLAPSE_EVENT,
aggregate_type="transfer_movement_ledger",
# aggregate_id 列宽 String(128):超长截断防御(全量字段在 after 快照留存,
# 与 ledger_sync._cross_check_event 同款防御)。
aggregate_id=natural_key[:128],
actor_type="system",
result="failure",
after={
"source_code": source_code, "record_kind": record_kind,
"doc_no": collapse["doc_no"], "line_no": collapse["line_no"],
"line_seq": collapse["line_seq"], "in_out_flag": collapse["in_out_flag"],
"carton_id": collapse["carton_id"], "lot_no": collapse["lot_no"],
"external_doc_no": collapse["external_doc_no"],
"external_line_no": collapse["external_line_no"],
"material_codes": collapse["material_codes"],
"dropped_material_codes": collapse["dropped_material_codes"],
"resolution": "first_seen_wins",
},
)
def parse_archive_to_ledger_rows(*, source_code: str, rows: list[dict]) -> list[dict]:
"""归档原始行 → 档行领域 dict 列表(解析+组装单一口径,运行期/重建共用)。
【AI 触发时机】运行期落档(sync_source_rows)与维护重建
(backlog_reparse_service 清空并重解析,spec §6)在把归档原始行组装为落档
领域行时都必须经本函数;禁止任何一方绕开自组解析(两套解析=映射漂移温床)。
「归档字节 → 本函数入参原始行」的提取段在
movement_file_repository._extract_movement_rows(latest_ready_file 与重建路径
同一实现),本函数承接其后的行校验解析(parse_movement_rows)与明细粒度
聚合组装(_assemble_ledger_rows)——两段合起来才是完整的「归档字节→档行」。
Args:
source_code: 来源实例编码(解析行来源身份一致性校验)。
rows: 归档原始行 dict 列表(ReadyInboundFile.rows 同构:领域字段 +
溯源 sheet/row_no)。
Returns:
领域行 dict 列表(sync_ledger_rows 的 parsed_rows 契约)。
Raises:
MovementFileSchemaError: 任一行必填缺失/非法值(调用方按场景分层处理:
运行期落解析失败标记;重建整体中止 TRANSFER.REPARSE_PARSE_FAILED)。
"""
parsed = parse_movement_rows(source_code=source_code, rows=rows)
return _assemble_ledger_rows(parsed, rows)
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
"""解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。
"""解析来源最新可用入站文件并幂等落档(零外部调用,flush 不 commit)。
【AI 触发时机】入站 RPA 回调桥(sync_and_commit_for_callback)与来源解析
失败重试入口调用;不要在匹配/重查链路调用(匹配从档圈定,不写档)。
【解析失败分层 2026-09-29】成功返回前清除当前可用文件的解析失败标记
(parse_failed 三列置空,来源投影恢复 ready)——能走到成功返回即代表该
文件已成功解析;无标记时为 no-op。
(parse_failed 三列置空)——能走到成功返回即代表该文件已成功解析;无标记时
为 no-op。
Args:
source_code: 来源实例编码。
deps: TransferDeps(只用 file_repository 与 route_resolver)。
deps: TransferDeps(只用 file_repository)。
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。
now: 落档时间基准(插入/更新显式续 updated_at)。
Returns:
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None(该分支
不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。
@@ -96,152 +333,46 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date)
if ready is None:
return None
parsed = parse_movement_rows(source_code=source_code, rows=ready.rows)
invoices = filter_invoices_for_type(
aggregate_invoices(parsed, file_version=ready.file_version),
TransferType.IN_TRANSIT_TO_HUB,
# [STEP 1] 解析+组装领域行(明细粒度聚合):经 parse_archive_to_ledger_rows
# 单一口径(运行期与重建共用,schema 类失败原样上抛——桥内 rollback +
# 落解析失败标记)。
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=list(ready.rows))
# [STEP 2] 幂等落档;ledger_sync 只 flush 不 commit(提交归调用方:桥自行
# commit,匹配/重查随主事务)。溯源文件 id:当前可用归档文件(Fake 仓库
# 测试场景/文件已清理时为 None,档事实留存不依赖文件存在)。
# 【阶段 B Task 4】文件身份改取 freight_rpa.reports.queries 只读视图(主键 file_id)。
file_view = latest_usable_inbound_file(source_code)
outcome = sync_ledger_rows(
source_code=source_code,
record_kind=RECORD_KIND_INBOUND,
parsed_rows=assembled,
file_meta=FileMeta(
source_file_id=file_view.file_id if file_view is not None else None,
file_version=ready.file_version,
file_sha256=ready.checksum,
),
now=now,
)
# [档自然键坍缩守卫 终审 I3] 组装产物复检:同自然键批内料号不同(同单号多
# 料号且项次全空)→ 每个坍缩键写一条审计事件(行处理不变,首见为准——把
# 静默丢行变显式可观测)。只在批内实际落档(inserted/updated>0)时打事件:
# 幂等重落(sha 未变全跳过)不重复打,防只追加审计表被同文件重落刷爆
# (与 ledger_sync 交叉校验事件「矛盾标记随落档动作发生」同款防刷口径)。
collapses = _detect_natural_key_collapses(assembled)
if collapses and (outcome.inserted or outcome.updated):
for collapse in collapses:
db.session.add(_natural_key_collapse_event(
source_code=source_code, collapse=collapse))
result = SyncOutcome(
source_code=source_code,
file_sha256=ready.checksum or "",
inserted=outcome.inserted,
updated=outcome.updated,
skipped=outcome.skipped,
sealed_skipped=outcome.sealed_skipped,
cross_flagged=outcome.cross_flagged,
)
# [STEP 1] 圈定本来源全部非终态既有行,按四元组建索引(matching_id 已放开
# 非空,落地行不受 uq_transfer_invoice_items_matching_grain 保护,幂等去重
# 由本应用层四元组负责)。
existing = TransferInvoiceItem.query.filter(
TransferInvoiceItem.source_code == source_code,
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
).all()
by_key = {(r.source_code, r.invoice_no, r.material_no, r.receipt_date): r for r in existing}
# [终态去重圈] 终态行同样纳入四元组去重范围(只查四列,轻量):若只在非终态
# 行内去重,来源全终态后同文件重落地(同日 RPA 重试再触发落地桥 / align 兜底
# 重解析)时 quad 缺席索引会被当全新行重插 pending——已执行的调拨单「复活」
# 回待办池,存在以新 doc_no 二次真实执行的风险。终态不复活是冻结约束:
# 重落地对终态行既不重插也不触碰。
terminal_keys = {
tuple(r)
for r in TransferInvoiceItem.query.with_entities(
TransferInvoiceItem.source_code,
TransferInvoiceItem.invoice_no,
TransferInvoiceItem.material_no,
TransferInvoiceItem.receipt_date,
).filter(
TransferInvoiceItem.source_code == source_code,
TransferInvoiceItem.status.in_(_TERMINAL_ITEM_STATUSES),
).all()
}
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "absent_kept": 0, "skipped": 0}
incoming_keys: set[tuple] = set()
# [STEP 2] 文件内单逐张三分类:跳过 / 插入 / 刷新+重置。
for invoice in invoices:
receipt_date_iso = invoice.receipt_date.isoformat()
key = (source_code, invoice.invoice_no, invoice.material_no, receipt_date_iso)
incoming_keys.add(key)
row = by_key.get(key)
# [终态不复活] 该四元组已有终态行(已执行/已关闭等):同文件重落地跳过
# 整行——不重插新 pending 行,也不触碰终态行本身(计数归 skipped 口径)。
# 必须在插入判定之前拦截,否则全终态来源重落地会重开已执行的调拨单。
if row is None and key in terminal_keys:
counters["skipped"] += 1
continue
# [证据变化判定] 只比对收料事实(数量/批号/仓库);material_name 等展示
# 字段不触发重置(重置会作废旧库存查询,代价是重查)。
evidence_changed = row is None or (
str(row.receipt_quantity) != str(invoice.receipt_quantity)
or (row.lot_no or "") != (invoice.lot_no or "")
or (row.receipt_warehouse_code or "") != (invoice.warehouse_code or "")
)
if row is not None and not evidence_changed and _item_evaluated_sha(row) == ready.checksum:
counters["skipped"] += 1 # [幂等] 同文件重复落地:零写入(不续新鲜度)
continue
if row is None:
from_wh, to_wh = _resolve_route_best_effort(deps, source_code, invoice)
db.session.add(TransferInvoiceItem(
matching_id=None, # 落地行尚无匹配归属(列已放开非空)
source_code=source_code,
invoice_no=invoice.invoice_no,
material_no=invoice.material_no,
material_name=invoice.material_name,
specification=invoice.specification,
receipt_date=receipt_date_iso,
status=status_machine.TransferStatus.MATCHING.value,
result_code=SYNC_RESULT_PENDING,
result_message=None,
from_warehouse=from_wh,
to_warehouse=to_wh,
receipt_quantity=str(invoice.receipt_quantity),
external_quantity=None,
lot_no=invoice.lot_no or "",
receipt_warehouse_code=invoice.warehouse_code or "",
unit="", # 单位只取 ERP stock_unit,匹配查询时落列
raw_lines_json=[
{"sheet": line.sheet, "row_no": line.row_no,
"file_version": line.file_version, "file_sha256": ready.checksum}
for line in invoice.raw_lines
],
updated_at=now,
))
counters["inserted"] += 1
continue
# [Important② 复现行] 历史残留消失标记行(blocked_file_removed)重新出现
# 在最新文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)
# 已失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。
# 非终态行恢复不违反终态冻结。历史残留行防御(2026-09-28 起同步不再新产生该码)。
restored_from_removed = row.result_code == RESULT_FILE_REMOVED
# [版本戳] 行随最新文件版本刷新(复现行与普通行同路径换新戳,对齐入口
# 据此收敛直通)。
row.raw_lines_json = [
{"sheet": line.sheet, "row_no": line.row_no,
"file_version": line.file_version, "file_sha256": ready.checksum}
for line in invoice.raw_lines
]
# [Important① 展示字段] 名称/规格属展示字段:进入非跳过分支即刷新
# (放在证据分支判断之外)——是否重置待查只由三证据字段决定,避免纯
# 名称变更落入 refreshed 后展示值随新戳固化(align 直通后永不更新)。
row.material_name = invoice.material_name
row.specification = invoice.specification
if evidence_changed:
# [STEP 3] 收料事实变化:刷新证据值(数量/批号/仓库)。
row.receipt_quantity = str(invoice.receipt_quantity)
row.lot_no = invoice.lot_no or ""
row.receipt_warehouse_code = invoice.warehouse_code or ""
if evidence_changed or restored_from_removed:
# [重置/恢复] 值变 → 重置回待查(旧库存是对旧数量查的,作废);
# 复现行 → 恢复待查(重新进入待办池,计数同归 reset_pending 口径)。
row.status = status_machine.TransferStatus.MATCHING.value
row.result_code = SYNC_RESULT_PENDING
row.result_message = None
row.external_quantity = None # 旧库存对旧数量,作废待重查
# [库存查得时刻] 库存作废即置空取数时刻(不变式:本字段=当前
# external_quantity 的取数时间;NULL=无库存数据,stale 不判定)。
row.inventory_checked_at = None
counters["reset_pending"] += 1
else:
counters["refreshed"] += 1
# refreshed/absent_kept 只换文件版本戳——本分支不续期 inventory_checked_at
#(2026-09-29 起 stale 判定时钟,换戳≠查过库存),仅 updated_at 照常续期。
row.updated_at = now
# [STEP 4] 文件里缺席的非终态行 → 存续处理(2026-09-28 语义升级):收料 RPA
# 导出非全量,缺席≠删除(行业存续原则)——保留原 status/result_code/message,
# 只把版本戳换到最新文件 sha(保留 sheet/row_no 行定位):对齐入口 row_shas
# 收敛直通、执行门禁②继续放行(历史行不会被 TRANSFER.FILE_CHANGED 死锁)。
# 行日后复现时 evaluated_sha≠新文件 sha,自然走 STEP 2 刷新/重置分支;真实
# 删除由人工关闭兜底(待处理池 3/5/7 天老化防遗忘)。终态行不在 by_key,
# 绝不触碰。
for key, row in by_key.items():
if key in incoming_keys:
continue
row.raw_lines_json = [
{**line, "file_version": ready.file_version, "file_sha256": ready.checksum}
for line in (row.raw_lines_json or [])
]
row.updated_at = now
counters["absent_kept"] += 1
# [STEP 5] 只 flush 不 commit:落地桥自行 commit,匹配/重查随主事务。
db.session.flush()
outcome = SyncOutcome(source_code=source_code, file_sha256=ready.checksum or "", **counters)
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_EVIDENCE_SYNCED",
aggregate_type="transfer_source",
@@ -249,92 +380,38 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
actor_type="system",
result="success",
after={
"file_sha256": outcome.file_sha256,
"inserted": outcome.inserted, "refreshed": outcome.refreshed,
"reset_pending": outcome.reset_pending, "absent_kept": outcome.absent_kept,
"skipped": outcome.skipped,
"file_sha256": result.file_sha256,
"record_kind": RECORD_KIND_INBOUND,
"inserted": result.inserted, "updated": result.updated,
"skipped": result.skipped, "sealed_skipped": result.sealed_skipped,
"cross_flagged": result.cross_flagged,
},
))
# [解析失败分层 2026-09-29] 同步成功 = 当前可用文件已成功解析:清除其解析
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。查询口径与
# source_file_status 一致(_latest_usable_report_file);只 flush 不 commit,
# 提交归调用方(桥自行 commit / 匹配随主事务)。无可用 ORM 文件(Fake
# 仓库测试场景/文件已清理)时为 no-op。
report = _latest_usable_report_file(source_code)
if report is not None and report.parse_failed_at is not None:
clear_receipt_parse_failure(report=report)
return outcome
def align_scope_rows(*, source_codes: list[str], deps, business_date: str, now: datetime) -> dict:
"""兜底对齐入口:行版本戳 ≠ 最新文件 sha 的来源才重新解析(一致直通零开销)。
【AI 触发时机】:匹配(run_matching STEP 0)与重查(requery_* STEP 0)调用;
落地同步(主链路)失败的静默兜底——稳态下 sha 一致,本函数零解析直通。
Args:
source_codes: 来源实例编码列表。
deps: TransferDeps(透传 sync_source_rows)。
business_date: 业务日期(文件新鲜度口径)。
now: 新鲜度基准。
Returns:
{source_code: SyncOutcome|None};None=已对齐或无可用文件(未解析)。
"""
outcomes: dict = {}
for code in source_codes:
latest = resolve_source_file_status(source_code=code) or {}
latest_sha = latest.get("file_sha256")
if not latest_sha:
outcomes[code] = None
continue
rows = TransferInvoiceItem.query.filter(
TransferInvoiceItem.source_code == code,
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
).all()
row_shas = {_item_evaluated_sha(r) for r in rows}
if row_shas == {latest_sha}:
outcomes[code] = None # 已对齐:直通
continue
outcomes[code] = sync_source_rows(source_code=code, deps=deps,
business_date=business_date, now=now)
return outcomes
def _resolve_route_best_effort(deps, source_code: str, invoice) -> tuple[str, str]:
"""同步期预解析路由落列(纯配置查表);解析失败留空不阻断(匹配时再解析)。
Args:
deps: TransferDeps(只用 route_resolver)。
source_code: 来源实例编码。
invoice: AggregatedInvoice(取 invoice_no / warehouse_code)。
Returns:
(from_warehouse, to_warehouse);未配置路由返回 ("", "")。
"""
try:
route = deps.route_resolver.resolve(
source_code=source_code, invoice_no=invoice.invoice_no,
warehouse_code=invoice.warehouse_code or "",
)
return route.from_warehouse, route.to_warehouse
except RouteNotResolvedError:
return "", ""
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。只 flush 不 commit,
# 提交归调用方。无可用归档时为 no-op。
if file_view is not None and file_view.parse_failed_at is not None:
clear_inbound_parse_failure(file_view.file_id)
return result
def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: datetime) -> bool:
"""收料回调桥专用入口:同步 + 自行 commit + 异常全吞(仅 warning 日志)。
"""入站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
【AI 触发时机】:收料 RPA 回调 success 终态落文件后由
shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路
的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。
【AI 触发时机】:入站 RPA 回调 success 终态落文件后由
shipping_notice 域 ShippingInboundReport 归档存储的桥函数调用——桥是记账
不是入站链路的正确性依赖,任何异常不得向 ShippingInboundReport 归档主链路传播(B3:必须自行 commit)。
【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上。
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上;
丢失的落档由回调重试/来源「重试 RPA」入口(本地重解析)兜底
(原 align 兜底入口已随对档对账切换退役)。
Args:
source_code: 来源实例编码(收料单元行上的 source_code)。
source_code: 来源实例编码(入站单元行上的 source_code)。
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
now: 新鲜度基准(显式续 updated_at)。
now: 落档时间基准。
Returns:
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志;
True=落档成功或无事可做(无可用文件);False=落档失败(已记日志;
schema 类失败尽力把解析失败标记落库并独立提交,标记失败仅告警不影响返回)。
"""
from flask import current_app
@@ -344,37 +421,37 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
business_date=business_date, now=now)
# [桥隔离] sync_source_rows 只 flush 不 commit;桥由回调主链路在归档
# commit 之后独立调用,提交时机不归调用方管(B3 持久性教训),必须
# 在此自行提交,否则请求结束 session 回滚会丢掉已解析的待办行。
# 在此自行提交,否则请求结束 session 回滚会丢掉已解析的档行。
db.session.commit()
if outcome is not None:
current_app.logger.info(
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s absent=%s skipped=%s",
source_code, outcome.inserted, outcome.refreshed,
outcome.reset_pending, outcome.absent_kept, outcome.skipped)
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s updated=%s skipped=%s sealed=%s cross=%s",
source_code, outcome.inserted, outcome.updated,
outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged)
return True
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
# [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,同步崩溃
# 绝不允许波及收料归档终态;丢失的同步由对齐入口 align_scope_rows 兜底。
# [桥隔离] 为什么吞异常:桥是记账不是入站链路的正确性依赖,落档崩溃
# 绝不允许波及 ShippingInboundReport 归档终态;丢失的落档由回调重试/人工重取兜底。
current_app.logger.warning(
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
db.session.rollback()
# [解析失败分层 2026-09-29] rollback 之后再写标记,避免脏会话污染写路径;
# 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / ReceiptFileSchemaError)
# 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / MovementFileSchemaError)
# 落库——通用异常(网络/DB 故障等)不是文件解析问题,不落标记。标记写入后
# 独立 commit(B3:桥自行提交;同步数据已回滚,本次 commit 只持久化失败
# 独立 commit(B3:桥自行提交;落档数据已回滚,本次 commit 只持久化失败
# 事实),桥隔离语义保持,仍返回 False。
# [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows
# 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。
# 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉,
# B3(任何异常不得向收料归档主链路传播)优先于标记落库,丢失标记由下次重试补。
# B3(任何异常不得向 ShippingInboundReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。
try:
code = getattr(exc, "code", None) or ""
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, ReceiptFileSchemaError):
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, MovementFileSchemaError):
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
report = _latest_usable_report_file(source_code)
if report is not None:
record_receipt_parse_failure(
report=report,
file_view = latest_usable_inbound_file(source_code)
if file_view is not None:
mark_inbound_parse_failure(
file_view.file_id,
error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID),
error_message=str(detail)[:2000],
)
@@ -386,7 +463,7 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
def _default_deps():
"""装配默认 TransferDeps(桥入口专用:收料链路无 deps 可透传)。
"""装配默认 TransferDeps(桥入口专用:入站链路无 deps 可透传)。
Returns:
TransferDeps(测试经 deps._override 注入 Fake 时返回注入值)。
@@ -82,12 +82,12 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
"""按阻断原因归类 Sheet。"""
sheet = workbook.create_sheet(sheet_name)
sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"])
sheet.append(["Invoice", "来源", "料号", "异动数量", "外部系统 数量", "原因"])
for item in items:
if (item.result_code or "") in codes or item.status in codes:
sheet.append([
item.invoice_no, item.source_code, item.material_no,
item.receipt_quantity, item.external_quantity or "",
item.movement_quantity, item.external_quantity or "",
item.result_message or item.result_code or item.status,
])
@@ -2,15 +2,20 @@
用途:在途调拨执行服务(单据级重构 + D8 异步拆分):API 同步段 prepare_execution
只做门禁 + 建 queued Run + D1 五元组分组建单 + 一次入队;worker 段
execute_run 二次门禁复核后逐单执行(final_only 判定 → 非 final_only 写前
execute_run 逐单执行(final_only 判定 → 非 final_only 写前
库存复查(漂移行 fail-closed 移出本单)→ create_transfer(business_ref=doc_no
透传,调用日志按单号锚定)→ 六态落位);
retrigger_document 是 result_unknown 单的唯一人工出口(D11)。
依赖:orchestrator、capability_client(TransferOrder/StockTarget)、quantity
(classify_quantity_match)、document_id、contracts、audit、status、
source_file_status、matching_service(门禁/scope/路由契约)、
jobs.queue(TRANSFER_RUN 入队)、models。
逻辑:防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按
matching_service(scope/路由契约)、jobs.queue(TRANSFER_RUN 入队)、models。
逻辑:执行门禁只做存在性校验(行可执行 + 匹配未取消)。文件版本对账门禁
(TRANSFER.FILE_CHANGED,API 侧整批拒绝 + worker 侧整 Run 落败)已于
2026-10-22 退役——入站抓取是部分导出,新文件不含旧行 ≠ 旧行失效,按
最新文件 sha 对账会错误卡死未处理行;写前安全由逐单执行的写前库存
复查(_recheck_stock_for_document,按实时 ERP 账面严格相等核对)承担,
行级「文件已更新」徽标保留为纯提示(matching_service._item_dto)。
防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按
五元组建单,同组存在失败单则复用其单号/时间戳全量重跑(doc.run_id 改指新
Run,现任归属语义),存在 result_unknown/executing 单则阻断新行
(group_order_unresolved);部分唯一索引竞态以 SAVEPOINT + 复用重查重试
@@ -37,6 +42,7 @@ from app.models import (
TransferDocument,
TransferInvoiceItem,
TransferMatching,
TransferMovementLedger,
TransferRun,
User,
)
@@ -56,10 +62,8 @@ from app.services.in_transit_transfer.matching_service import (
RESULT_EXECUTABLE,
RouteMapping,
TransferDeps,
_item_evaluated_sha,
scope_item_query,
item_external_lot_no,
)
from app.services.in_transit_transfer.movement_contract import external_lot_no
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.orchestrator import (
create_execution_run_for_items,
@@ -68,7 +72,11 @@ from app.services.in_transit_transfer.orchestrator import (
# 单投影统一走公共序列化(Task 17 重构:serializers.serialize_order 为唯一契约源;
# serializers 不再顶层引用本模块,无循环导入)。
from app.services.in_transit_transfer.serializers import serialize_order
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
# [测试补丁锚点] 文件版本对账门禁已退役(2026-10-22),本模块不再消费此符号;
# 保留导入仅为存量测试替身(conftest.patch_source_file_status 等 monkeypatch)
# 的目标地址不变。新代码禁止再消费——门禁语义见 _gated_items docstring。
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status # noqa: F401
ITEM_EXECUTION_ERROR_RESULT = "item_execution_error"
# D7① 附加守卫:同组存在未了结单时新行的阻断原因码。
@@ -122,19 +130,23 @@ def _item_result_of(item: TransferInvoiceItem) -> str:
# ---------------------------------------------------------------------------
def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInvoiceItem]:
"""执行两道门禁(顺序校验,命中即抛、后续不执行,fail-closed 零写入)。
"""执行存在性门禁(命中即抛、后续不执行,fail-closed 零写入)。
门禁:
① 存在且可执行:id 存在且 status == ready_to_execute,否则
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID")。
② 文件版本对账:行评估版本戳(_item_evaluated_sha)≠ 来源最新可用文件
sha(含来源无可用文件/行无版本戳)→ ValidationError(code="TRANSFER.FILE_CHANGED")。
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID");所属匹配已
取消的行一并拒绝(防御性双保险,规格 §9)。
[2026-09-25 TTL 退役] 原门禁②「行级新鲜度(updated_at 距 now 超过
confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」已删除:匹配 10 分钟后必被拒
是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值(stale 徽标,见
matching_service._item_dto),防错由本函数门禁②的文件版本对账 + worker
写前库存复查(_execute_document 的 _recheck_stock_for_document)承担。
[2026-09-25 TTL 退役] 原门禁「行级新鲜度(updated_at 距 now 超过
confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」删除:匹配 10 分钟后必被拒
是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值(stale 徽标)。
[2026-10-22 文件版本对账门禁退役] 原「行评估 sha ≠ 证据流最新可用文件 sha
→ TRANSFER.FILE_CHANGED 整批拒绝」删除:入站抓取是**部分导出**——新文件
不含某行 ≠ 该行失效/已处理,按「最新文件 sha」对账会把大量未处理行错误
卡死(业务实测 557 行积压被卡)。证据变化的保护下沉两层:①行级「文件
已更新」徽标(file_current=false,仅提示不拦截,见 matching_service
_item_dto);②worker 写前库存复查(_recheck_stock_for_document)——按
实时 ERP 账面严格相等核对,数量/批号漂移的行在写前被行级阻断,不会错写。
Returns:
去重并保持首现顺序的可执行行列表。
@@ -151,34 +163,32 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv
).all()
by_id = {row.id: row for row in rows}
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
# [防御性双保险(规格 §9)] 所属匹配已取消的行不得执行:取消路径已把匹配
# 名下 ready 行退役,此处按匹配状态再拒一次(防绕过取消路径的状态组合)。
from app.models import TransferMatching as _Matching
row_matching_ids = {row.matching_id for row in rows if row.matching_id is not None}
cancelled_matching_ids: set[int] = set()
if row_matching_ids:
cancelled_matching_ids = {
mid for (mid,) in (
db.session.query(_Matching.id)
.filter(_Matching.id.in_(row_matching_ids), _Matching.status == "cancelled")
.all()
)
}
invalid = [
i for i in ordered_ids
if by_id.get(i) is None or by_id[i].status != ready_status
if by_id.get(i) is None
or by_id[i].status != ready_status
or by_id[i].matching_id in cancelled_matching_ids
]
if invalid:
raise ValidationError(
"items not executable", code="TRANSFER.EXECUTE_ITEMS_INVALID",
details={"invalid_item_ids": invalid},
)
items = [by_id[i] for i in ordered_ids]
# [门禁②] 文件版本对账(按去重来源投影最新可用文件,行评估 sha 必须一致)。
latest_files: dict[str, dict] = {
source_code: resolve_source_file_status(source_code=source_code)
for source_code in sorted({item.source_code for item in items})
}
changed = []
for item in items:
evaluated_sha = _item_evaluated_sha(item)
latest = latest_files.get(item.source_code) or {}
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
changed.append(item.id)
if changed:
raise ValidationError(
"source receipt file changed since evaluation", code="TRANSFER.FILE_CHANGED",
details={"changed_item_ids": changed},
)
return items
return [by_id[i] for i in ordered_ids]
def prepare_execution(
@@ -197,7 +207,7 @@ def prepare_execution(
核心逻辑:[STEP 1] 两道门禁(见 _gated_items);[STEP 2] 建 queued Run 并关联
行(orchestrator);[STEP 3] 写前路由解析取 external_org,按 D1 五元组
(external_org, source_code, receipt_date, from_warehouse, to_warehouse,全部
(external_org, source_code, movement_date, from_warehouse, to_warehouse,全部
.strip() 规范化)分组建单(_ensure_document:新建/复用/阻断三分支);
[STEP 4] TRANSFER_RUN {run_id, item_ids} 恰入队一次 → 返回 queued 摘要。
@@ -223,13 +233,13 @@ def prepare_execution(
for item in items:
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
warehouse_code=item.movement_warehouse_code or "",
)
org = str(route.external_org or "").strip()
key = (
org,
str(item.source_code or "").strip(),
str(item.receipt_date or "").strip(),
str(item.movement_date or "").strip(),
str(item.from_warehouse or "").strip(),
str(item.to_warehouse or "").strip(),
)
@@ -302,7 +312,7 @@ def _ensure_document(
) -> tuple[TransferDocument | None, list[TransferInvoiceItem]]:
"""D7① 三分支组建单:同组无单新建 / 失败单复用 / result_unknown·executing 阻断。
组键 = D1 五元组(external_org, source_code, receipt_date, from_warehouse,
组键 = D1 五元组(external_org, source_code, movement_date, from_warehouse,
to_warehouse,全部 .strip() 规范化)。
分支语义:
@@ -322,7 +332,7 @@ def _ensure_document(
Returns:
(单或 None, 处理后的 items)——分支③返回 (None, blocked items)。
"""
org, source_code, receipt_date, from_wh, to_wh = group_key
org, source_code, movement_date, from_wh, to_wh = group_key
def _live() -> TransferDocument | None:
"""查同组未完结单(no_autoflush 防止半建对象提前落库干扰判定)。"""
@@ -331,7 +341,7 @@ def _ensure_document(
TransferDocument.query.filter(
TransferDocument.source_code == source_code,
TransferDocument.external_org == org,
TransferDocument.receipt_date == receipt_date,
TransferDocument.movement_date == movement_date,
TransferDocument.from_warehouse == from_wh,
TransferDocument.to_warehouse == to_wh,
TransferDocument.status.in_(UNRESOLVED_DOC_STATUSES),
@@ -347,7 +357,7 @@ def _ensure_document(
# [分支①] 新建 pending 单(D2/D3 幂等锚一次生成终身复用)。
doc = TransferDocument(
run_id=run.id, source_code=source_code, external_org=org,
receipt_date=receipt_date, from_warehouse=from_wh, to_warehouse=to_wh,
movement_date=movement_date, from_warehouse=from_wh, to_warehouse=to_wh,
doc_no=next_document_no(org, sequence_loader=_sequence_loader),
submit_timestamp=new_submit_timestamp(),
status="pending",
@@ -485,13 +495,12 @@ def execute_run(
run.status = status_machine.TransferRunStatus.EXECUTING.value
run.started_at = run.started_at or datetime.utcnow()
db.session.flush()
if doc_id is None:
# [二次门禁] 文件 Hash 复核(fail-closed):失败则整 Run 落败,零外部写入。
failure = _recheck_gates(run, deps)
if failure is not None:
_mark_recheck_failed(run, docs, failure)
db.session.commit()
return run.status
# [2026-10-22 文件版本对账门禁退役] 原 worker 二次门禁 _recheck_gates(文件
# Hash 复核失败 → 整 Run technical_failed 零写入)随 API 侧门禁②一并退役:
# 入站抓取是部分导出,新文件不含旧行 ≠ 旧行失效,按最新文件 sha 对账会错误
# 卡死未处理行。写前安全由逐单执行的写前库存复查(_execute_document 的
# _recheck_stock_for_document)独立承担——按实时 ERP 账面严格相等核对,
# 数量/批号漂移的行在写前被行级阻断,不会错写。
# [逐单执行] 单间失败隔离:单单异常落 technical_failed,不影响其他单。
for doc in docs:
try:
@@ -513,62 +522,6 @@ def execute_run(
return run.status
def _recheck_gates(run: TransferRun, deps: TransferDeps) -> tuple[str, str] | None: # noqa: ARG001 —— 本函数只做文件 Hash 门禁;库存写前复查在 _execute_document(_recheck_stock_for_document)
"""worker 二次门禁复核(文件 Hash),返回 None 表示通过。
[2026-09-25 TTL 退役] 原新鲜度复核(updated_at 距 now 超过
confirm_ttl_seconds → items_stale 整 Run 落败)已删除:worker 排队/等待
超 10 分钟即被拒是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值
(stale 徽标),写前安全由文件版本对账(本函数)+ 逐单执行的写前库存
复查(_recheck_stock_for_document)承担。
Args:
run: 执行 Run(其关联行即本次执行范围)。
deps: 注入依赖(文件门禁不消费外部能力,仅为签名对称保留)。
Returns:
None=通过;否则 (原因码, 原因消息)。
"""
items = [
item for item in run.items
if item.status in (
status_machine.TransferStatus.EXECUTING.value,
status_machine.TransferStatus.READY_TO_EXECUTE.value,
)
]
latest_files: dict[str, dict] = {
source_code: resolve_source_file_status(source_code=source_code)
for source_code in sorted({item.source_code for item in items})
}
for item in items:
evaluated_sha = _item_evaluated_sha(item)
latest = latest_files.get(item.source_code) or {}
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
return ("file_changed", "source receipt file changed since evaluation")
return None
def _mark_recheck_failed(run: TransferRun, docs: list[TransferDocument], failure: tuple[str, str]) -> None:
"""二次门禁失败落位(fail-closed):单 technical_failed、行阻断、Run failed。"""
code, message = failure
for doc in docs:
# [P2-1] pending(未起跑)与 executing(上次 worker 中途搁浅)统一落
# technical_failed:零外部写入;stage 已成的单后续全量重跑由 stage SQL
# DELETE 同时间戳幂等兜底;落失败态使其可被 D18 关闭释放组锁,不留悬挂。
if doc.status in ("pending", "executing"):
doc.status = "technical_failed"
doc.error_code = code
doc.error_message = message
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
for item in run.items:
if item.status not in _PROTECTED_ITEM_STATUSES and item.status != blocked_status:
item.status = blocked_status
item.result_code = code
item.result_message = message
run.status = status_machine.TransferRunStatus.FAILED.value
run.completed_at = run.completed_at or datetime.utcnow()
db.session.flush()
# ---------------------------------------------------------------------------
# 逐单执行(计划 [STEP 1-4] 伪码逐字落实)
# ---------------------------------------------------------------------------
@@ -584,7 +537,7 @@ def _recheck_stock_for_document(
【为什么】TTL 门禁退役(2026-09-25)后写前安全的最后防线:匹配到 worker 执行
之间存在时间窗,账面可能已被其他业务挪用/清零;在 create_transfer 之前按
「收料数量 == 账面」严格相等再裁一次,防止对错误数量建单。
「异动数量 == 账面」严格相等再裁一次,防止对错误数量建单。
【为什么不复查 final_only】result_unknown/executing 续跑(final_only=True)单
可能已在 ERP 建成,D7② 只触发末步——此时任何阻断都是假失败,故调用方保证
final_only 路径不进入本函数。
@@ -606,18 +559,18 @@ def _recheck_stock_for_document(
"""
grouped: dict[str, list[tuple[TransferInvoiceItem, RouteMapping]]] = {}
for item in items:
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
)
# [外部形态 + 仓库定义] 行级路由解析叠加行所属匹配类型的仓库定义
# (fixed 覆盖映射档);批号经匹配快照转换规则派生(与匹配/重查同一口径)。
from app.services.in_transit_transfer.retry_service import _route_for_item
route = _route_for_item(deps, item)
grouped.setdefault(str(route.external_org or "").strip(), []).append((item, route))
kept: list[TransferInvoiceItem] = []
for external_org, entries in grouped.items():
# [外部形态] 写前复查与匹配/重查同一批号派生口径(movement_contract.external_lot_no)。
targets = [
StockTarget(
material_no=item.material_no, warehouse_code=route.from_warehouse,
lot_no=external_lot_no(item.lot_no),
lot_no=item_external_lot_no(item),
)
for item, route in entries
]
@@ -632,7 +585,7 @@ def _recheck_stock_for_document(
for item, route in entries:
row = stock.lookup_row(
material_no=item.material_no,
warehouse_code=route.from_warehouse, lot_no=external_lot_no(item.lot_no),
warehouse_code=route.from_warehouse, lot_no=item_external_lot_no(item),
)
# [库存查得时刻] 写前复查是真实取数:无论查无/漂移/通过,随后落定的
# external_quantity 都以本次取数为准(stale 判定时钟,见 _item_dto)。
@@ -644,7 +597,7 @@ def _recheck_stock_for_document(
item.result_message = "external inventory not found (write recheck)"
item.external_quantity = "0"
continue
if classify_quantity_match(Decimal(item.receipt_quantity), row.quantity) != RESULT_EXECUTABLE:
if classify_quantity_match(Decimal(item.movement_quantity), row.quantity) != RESULT_EXECUTABLE:
# 数量漂移:原位刷新最新账面并移出本单(fail-closed,不写 ERP)。
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_quantity_mismatch"
@@ -695,7 +648,7 @@ def _execute_document(
continue # 人工关闭/取消行不复活(D18 语义:人工决定不被自动覆盖)。
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
warehouse_code=item.movement_warehouse_code or "",
)
if (
route.from_warehouse != item.from_warehouse
@@ -746,8 +699,8 @@ def _execute_document(
external_org=doc.external_org,
doc_no=doc.doc_no,
submit_timestamp=doc.submit_timestamp,
# D1:制单日期(gls_cm06)必须等于组收料日期;过账日期=执行当天业务日。
doc_date=doc.receipt_date,
# D1:制单日期(gls_cm06)必须等于组异动日期;过账日期=执行当天业务日。
doc_date=doc.movement_date,
posting_date=str(business_date_now()),
from_warehouse=doc.from_warehouse,
to_warehouse=doc.to_warehouse,
@@ -861,12 +814,12 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
"""
grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {}
for item in items:
# [外部形态] 聚合键批号按 WTP→HOW 派生(movement_contract.external_lot_no):
# ERP 行粒度=外部批号身份,同一 ERP 批次不得因 WMS 前缀形态差异拆行;
# 行下传 lot_no(key[1])随键即为外部形态。
# [外部形态] 聚合键批号经行所属匹配快照转换规则派生(类型配置驱动,
# 如 WTP→HOW):ERP 行粒度=外部批号身份,同一 ERP 批次不得因 WMS 前缀
# 形态差异拆行;行下传 lot_no(key[1])随键即为外部形态,行落库保持原值。
key = (
str(item.material_no or "").strip(),
external_lot_no(item.lot_no),
item_external_lot_no(item),
str(item.from_warehouse or "").strip(),
str(item.to_warehouse or "").strip(),
)
@@ -874,7 +827,7 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
lines: list[dict] = []
for index, key in enumerate(sorted(grouped), start=1):
group = grouped[key]
total = sum((Decimal(item.receipt_quantity) for item in group), Decimal("0"))
total = sum((Decimal(item.movement_quantity) for item in group), Decimal("0"))
quantity = total.quantize(_QUANTITY_QUANT)
unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "")
invoices = ",".join(sorted({item.invoice_no for item in group}))
@@ -922,15 +875,47 @@ def _order_snapshot(*, run_no: str, order: TransferOrder, final_only: bool, line
}
def _seal_ledger_records(items: list[TransferInvoiceItem], *, executed_doc_no: str | None) -> None:
"""档级封存回写(规格 §9 防二次执行的档级兜底)。
【AI 触发时机】仅 _apply_result 的 success/duplicate_success 分支调用——票据
执行成功落 ERP 单号时,把单内行关联的档记录置 transfer_executed=true +
executed_doc_no。失败/未知态不得调用(执行未成事实,记录仍可被圈定、
仍应可见于待匹配桶)。幂等:等值重复回写无副作用(封存位布尔语义,首次/
末次等效,复用单 duplicate_success 重跑恒封存);行无档关联(遗留行)跳过。
回写只 flush 不 commit(随调用方事务,与六态落位同生命周期)。
Args:
items: 本单(或遗留单行路径)参与落位的行集。
executed_doc_no: 回写单号(ERP 单号优先,缺失回退平台单号;为空直接跳过)。
"""
if not executed_doc_no:
return
record_ids = {item.ledger_record_id for item in items if item.ledger_record_id is not None}
if not record_ids:
return
records = (
db.session.query(TransferMovementLedger)
.filter(TransferMovementLedger.id.in_(record_ids))
.all()
)
for record in records:
record.transfer_executed = True
record.executed_doc_no = executed_doc_no
db.session.flush()
def _apply_result(*, doc: TransferDocument | None, items: list[TransferInvoiceItem], attempt: TransferAttempt, result: Any) -> None:
"""按写结果六态落位单、行与 Attempt(result_unknown 为终态,禁止自动重试)。
六态落位(D7②/D11):
- success / duplicate_success → 单与行推进成功族 + ERP 单号一致。
- success / duplicate_success → 单与行推进成功族 + ERP 单号一致;
并档级封存回写(_seal_ledger_records:items 关联档记录
transfer_executed=true + executed_doc_no,规格 §9 防二次执行)。
- result_unknown → 单/行 result_unknown 终态(唯一出口 = 人工 retrigger)。
- business_failed / technical_failed → 行 blocked_recoverable
(R6 裁决后非末步超时/失败已由引擎归 technical_failed),单保留失败态
待人工关闭(D18)或复用重跑(D7①②)。
待人工关闭(D18)或复用重跑(D7①②);档记录不封存(未成事实)。
"""
attempt.response_summary_json = {
"status": result.status,
@@ -950,6 +935,14 @@ def _apply_result(*, doc: TransferDocument | None, items: list[TransferInvoiceIt
item.external_document_no = result.document_no
item.result_code = None
item.result_message = None
# [档级封存回写(规格 §9)] 票据成功落 ERP 单号即封存其档记录:
# 防同一外部入站记录经新匹配二次执行;圈档/待匹配桶/队列的固定条件
# transfer_executed=false 恒排除已封存记录。幂等等值覆盖(复用单重跑恒封存)。
_seal_ledger_records(
items,
executed_doc_no=str(result.document_no or "").strip()
or (doc.doc_no if doc is not None else None),
)
attempt.status = "success"
elif result.status == "result_unknown":
for item in items:
@@ -1116,7 +1109,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
# [遗留兜底] 路由复查 → 单行临时单 → 写 Attempt → 调用 → 行级六态落位。
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
warehouse_code=item.movement_warehouse_code or "",
)
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
_mark_recheck_blocked(item, "matching_expired", "route mapping changed since matching")
@@ -1126,7 +1119,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
external_org=str(route.external_org or "").strip(),
doc_no=f"LEGACY-{item.id}",
submit_timestamp=new_submit_timestamp(),
doc_date=item.receipt_date or "",
doc_date=item.movement_date or "",
posting_date=str(business_date_now()),
from_warehouse=item.from_warehouse,
to_warehouse=item.to_warehouse,
@@ -1204,10 +1197,10 @@ def execute_matching_items(
actor_id: int | None = None,
request_id: str | None = None,
) -> ExecuteOutcome:
"""按匹配 scope 圈定 ready 行并按单执行(chat action / 自动排程共用入口)。
"""按匹配自有 items 圈定 ready 行并按单执行(chat action / 自动排程共用入口)。
行归属与匹配解耦(原地刷新)后,"这份匹配覆盖哪些行"由 scope 重新圈定
(scope_item_query:来源 + 收料日期区间 + 调拨类型前缀);本入口按 scope 取
【出生翻转】行由匹配创建时从档圈定且创建即绑定(matching_id),"这份匹配
覆盖哪些行"=自有 items(scope_item_query 实时圈行已退役);本入口按匹配取
ready_to_execute 行(可选 invoice_nos 过滤)后委托 execute_items 执行,
两道门禁与单据级组建单由 execute_items/prepare_execution 统一裁定。
@@ -1222,8 +1215,11 @@ def execute_matching_items(
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
ready_rows = (
scope_item_query(matching)
.filter(TransferInvoiceItem.status == ready_status)
TransferInvoiceItem.query
.filter(
TransferInvoiceItem.matching_id == matching.id,
TransferInvoiceItem.status == ready_status,
)
.order_by(TransferInvoiceItem.id.asc())
.all()
)
@@ -1277,15 +1273,15 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
material_name=item.material_name,
specification=item.specification,
invoice_no=item.invoice_no,
receipt_date=item.receipt_date,
movement_date=item.movement_date,
from_warehouse=item.from_warehouse,
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
to_warehouse=item.to_warehouse,
to_quantity=Decimal(item.receipt_quantity),
to_quantity=Decimal(item.movement_quantity),
result=result,
reason=item.result_message or "",
external_document_no=item.external_document_no,
receipt_warehouse_code=item.receipt_warehouse_code or "",
movement_warehouse_code=item.movement_warehouse_code or "",
# T7 交接补齐:交易单位原值透传(执行结果视图 unit 不再恒空,计划 D4)。
unit=str(item.unit or ""),
))
@@ -1305,7 +1301,7 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
reason=result,
# 行级人话原因(阻断单号等),前端优先展示、状态码标签兜底。
message=str(item.result_message or "").strip(),
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
facts=f"异动 {item.movement_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
))
return RunResultDTO(
run_no=run.run_no,
@@ -1363,7 +1359,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
(D9,无独立进度卡);逐单亮 ERP 单号与状态徽标。
核心逻辑:[STEP 1] 按 run_id 取单(复用单 run_id 指现任 Run,投影不丢),
展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):收料日期 → 数据源 →
展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):异动日期 → 数据源 →
拨出/拨入库位升序,created_at/id 兜底稳定排序(跨数据源不再按建单序出现
日期乱序);[STEP 2] 每单行集取自单挂接行(document_id →
items,复用单新旧行全量),按 ERP 行粒度(物料+批号+拨出/拨入库位,与
@@ -1375,7 +1371,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
Returns:
orders 数组(计划 Task 11 JSON 规格逐键 + T13-3 控制器裁决扩充):
[{doc_no, receipt_date, from_warehouse, to_warehouse, status,
[{doc_no, movement_date, from_warehouse, to_warehouse, status,
erp_document_no, error_message, lines: [{invoice_no, material_no,
material_name, lot_no, quantity(6 位小数字符串), unit, reason}]}]。
行 reason 契约(框线图失败行原因展示,偏离 Task 11 五键字面属控制器裁决):
@@ -1387,7 +1383,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
docs = (
TransferDocument.query.filter_by(run_id=run.id)
.order_by(
TransferDocument.receipt_date.asc(),
TransferDocument.movement_date.asc(),
TransferDocument.source_code.asc(),
TransferDocument.from_warehouse.asc(),
TransferDocument.to_warehouse.asc(),
@@ -0,0 +1,87 @@
"""services/in_transit_transfer/field_transforms.py
用途:调拨类型字段转换规则引擎——「外部系统值→ERP 值」的受控派生
(一期仅 lot_no 前缀替换),只在系统边界生效;行与档保持文件原值。
依赖:app.core.errors.ValidationError。
逻辑:parse 校验白名单 → TransformRule 元组;apply 按序链式派生(未命中恒等)。
【AI 触发时机】任何把行上字段值发往外部系统或按派生值聚合/展示的场景
(库存查询 targets、写前复查、建单单行、票行聚合键、前端批号展示),
必须经本引擎按当前匹配快照的规则求值;禁止直接调用硬编码前缀转换。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Sequence
from app.core.errors import ValidationError
# 受控字段/转换方式词表(封闭可扩展;新增须同步管理页下拉与 technical.md)。
TRANSFORM_FIELDS: frozenset[str] = frozenset({"lot_no"})
TRANSFORM_OPS: frozenset[str] = frozenset({"prefix_replace"})
@dataclass(frozen=True)
class TransformRule:
"""单条转换规则:field 字段 / op 转换方式 / source 原前缀 / target 新前缀。"""
field: str
op: str
source: str
target: str
def parse_transform_rules(raw: list[dict] | None) -> tuple[TransformRule, ...]:
"""校验并解析转换规则 JSON;空列表/None = 恒等(无转换)。
Args:
raw: [{"field", "op", "source", "target"}],来自调拨类型配置 JSON;
空列表/None 合法(= 该类型不做字段转换)。
Returns:
TransformRule 元组(source/target 统一大写,保证匹配口径一致)。
Raises:
ValidationError: field 不在 TRANSFORM_FIELDS、op 不在 TRANSFORM_OPS、
或 source/target 为空(code=TRANSFER.TRANSFORM_RULE_INVALID)。
"""
rules: list[TransformRule] = []
for item in raw or []:
field, op = str(item.get("field", "")), str(item.get("op", ""))
source, target = str(item.get("source", "")), str(item.get("target", ""))
if field not in TRANSFORM_FIELDS or op not in TRANSFORM_OPS or not source or not target:
raise ValidationError(
f"invalid transform rule: {field}/{op}", code="TRANSFER.TRANSFORM_RULE_INVALID",
details={"field": field, "op": op},
)
rules.append(TransformRule(field=field, op=op, source=source.upper(), target=target.upper()))
return tuple(rules)
def apply_field_transforms(field: str, value: str | None, rules: Sequence[TransformRule]) -> str | None:
"""按规则序链式派生;未命中规则恒等返回原值(None/空串透传)。
Args:
field: 行字段名(仅 TRANSFORM_FIELDS 内的字段会被规则命中)。
value: 该字段当前原值(来自行/档,永不被本函数改写——只返回新值)。
rules: parse_transform_rules 产出的规则元组,按配置序链式生效。
Returns:
派生后的新值;None 与空串原样透传(不做前缀替换)。
"""
result = value
for rule in rules:
if rule.field != field or not result:
continue
if rule.op == "prefix_replace" and result.upper().startswith(rule.source):
result = rule.target + result[len(rule.source):]
return result
def transform_rules_note(rules: Sequence[TransformRule]) -> str:
"""转换规则审计说明。
Args:
rules: parse_transform_rules 产出的规则元组。
Returns:
如 "lot_no prefix_replace WTP->HOW THEN lot_no prefix_replace HOW->HOWX"
的人读字符串(空规则返回空串),供审计日志/详情页展示。
"""
return " THEN ".join(f"{r.field} {r.op} {r.source}->{r.target}" for r in rules)
@@ -1,9 +1,12 @@
"""在途调拨收料文件字段/结构校验。
"""在途调拨异动文件字段/结构校验。
用途:校验收料文件必填列(Invoice No/料号/收料日期/收料数量)、数量与日期合法性、
来源身份一致性,输出 ParsedReceiptRow 供 Invoice 汇总。
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_receipt_quantity。
逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。
用途:校验异动文件必填列(单号/异动日期/异动数量;料号为空的行静默跳过)、
数量与日期合法性、来源身份一致性,输出 ParsedMovementRow 供 Invoice 汇总。
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_inbound_quantity。
逻辑:必填缺失或非法值整行阻断并携带行号细节;料号空行跳过不管控不落档
(2026-10-21 CRANE/Lognet 出站报告实测);本模块不接触文件存储。
tt14 入站化后统一走 movement 契约字段(parse_movement_rows 单一入口,
旧字段投影链路已并入,无兼容层)。
"""
from __future__ import annotations
@@ -16,14 +19,11 @@ from typing import Any, Iterable, Mapping
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
from app.services.in_transit_transfer.date_policy import parse_date
from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_receipt_quantity
REQUIRED_FIELDS = ("sheet", "row_no", "invoice_no", "material_no", "receipt_date", "receipt_quantity")
from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_inbound_quantity
@dataclass(frozen=True)
class ParsedReceiptRow:
"""单行已校验收料记录。"""
class ParsedMovementRow:
"""单行已校验异动记录。"""
source_code: str
sheet: str
@@ -32,20 +32,21 @@ class ParsedReceiptRow:
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
# 异动日期/异动数量(tt14 入站化:明细方向中立,与异动档 movement_date 对齐)。
movement_date: date
movement_quantity: Decimal
lot_no: str = ""
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
# 来源文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
warehouse_code: str = ""
# 交易单位列原值(movement 契约第 11 字段 unit,计划 D4):仅 trim 空白、
# 不做单位换算/清洗;空值不产生解析失败,由匹配阶段行级 blocked_missing_unit 阻断。
unit: str = ""
class ReceiptFileSchemaError(AppError):
"""收料文件结构/字段校验失败(整行阻断)。"""
class MovementFileSchemaError(AppError):
"""异动文件结构/字段校验失败(整行阻断)。"""
def __init__(self, message: str = "receipt file schema invalid", *, rows: list[dict[str, Any]] | None = None):
def __init__(self, message: str = "movement file schema invalid", *, rows: list[dict[str, Any]] | None = None):
super().__init__(
code=TRANSFER_FILE_SCHEMA_INVALID,
message=message,
@@ -59,48 +60,52 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
rows.append({"row_no": row_no, "reason": reason})
def _is_unusable_receipt_row(date_value: Any, quantity_raw: Any) -> bool:
"""判断是否为"非可用收料事实"的行:跳过,不参与匹配,也不阻断整文件。
def _is_unusable_movement_row(date_value: Any, quantity_raw: Any) -> bool:
"""判断是否为"非可用异动事实"的行:跳过,不参与匹配,也不阻断整文件。
WMS 异动报告会携带三类非可用收料行,均不是可用的收料事实:
① 未收料在途 ASN(Date Received 空、Qty Received 0);
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章);
③ 零数量收料行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
WMS 异动报告会携带三类非可用异动行,均不是可用的异动事实:
① 未收货在途 ASN(Date Received 空、Qty Received 0);
② 收货执行中(ASN Status=Executing,Qty Received 已计数但收货日期未盖章);
③ 零数量异动行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
WTP26082227 实测——扫码收货数量记在他行/收货取消的占位行)。
收料日期与正数量是行级匹配身份与成熟过滤的必要字段;此类行跳过后由下次排程
异动日期与正数量是行级匹配身份与日期圈定的必要字段;此类行跳过后由下次排程
抓取补齐(WMS 补数量/盖章后自然带出),不得整文件阻断。
"""
if not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()):
return True
try:
# 只跳过恰好为 0 的零收料行;负数属数据损坏,交由 validate_receipt_quantity 阻断。
# 只跳过恰好为 0 的零异动行;负数属数据损坏,交由 validate_inbound_quantity 阻断。
return Decimal(str(quantity_raw)) == 0
except (InvalidOperation, ValueError, TypeError):
# 数量缺失/空:日期已盖章但无数量,同为零收料家族;非数字垃圾交由
# validate_receipt_quantity 按非法数量阻断,不在此吞掉。
# 数量缺失/空:日期已盖章但无数量,同为零异动家族;非数字垃圾交由
# validate_inbound_quantity 按非法数量阻断,不在此吞掉。
return not str(quantity_raw or "").strip()
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedMovementRow]:
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
字段契约(领域定死)见 movement_contract.MOVEMENT_FIELDS;映射关系:
doc_no → invoice_no(幂等/汇总键)
quantity → receipt_quantity(严格数量匹配)
movement_date → receipt_date(成熟过滤)
quantity → movement_quantity(严格数量匹配)
movement_date → movement_date(日期圈定;tt14 入站化后明细侧同名对齐)
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
unit 原值透传至 ParsedReceiptRow.unit(movement 契约第 11 字段,仅 trim,
warehouse_code 透传至 ParsedMovementRow.warehouse_code(inventory_match 源路由匹配键);
unit 原值透传至 ParsedMovementRow.unit(movement 契约第 11 字段,仅 trim,
空值不阻断解析——行级 missing_unit 阻断在匹配阶段);
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
external_doc_no/external_line_no(2026-10-21 扩展:外部单号/外部项次)经原始行
透传至落档组装(_assemble_ledger_rows 从原始行取扩展字段,解析行不设槽位),
作为异动档自然键成分承担档幂等主键管控;
storage_code 仍仅展示保留。旧字段名投影链路(tt14 前的直连列名解析)已并入
本函数(入站化,无兼容层),校验逻辑一致。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 通用异动原始行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
已校验的 ParsedMovementRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
MovementFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
@@ -108,31 +113,8 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
projection={
"invoice_no": "doc_no",
"material_no": "material_code",
"receipt_quantity": "quantity",
"receipt_date": "movement_date",
},
)
def parse_receipt_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
"""校验并解析收料文件行。
Args:
source_code: 任务来源实例(用于校验行内来源身份一致性)。
rows: 原始文件行 dict。
Returns:
已校验的 ParsedReceiptRow 列表。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
return _parse_rows(
source_code=source_code,
rows=rows,
projection={
"invoice_no": "invoice_no",
"material_no": "material_no",
"receipt_quantity": "receipt_quantity",
"receipt_date": "receipt_date",
"movement_quantity": "quantity",
"movement_date": "movement_date",
},
)
@@ -142,61 +124,64 @@ def _parse_rows(
source_code: str,
rows: Iterable[Mapping[str, Any]],
projection: Mapping[str, str],
) -> list[ParsedReceiptRow]:
) -> list[ParsedMovementRow]:
"""按字段名投影校验并解析原始行。
Args:
source_code: 任务来源实例(行内来源身份一致性校验)。
rows: 原始文件行 dict。
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
projection: 调拨语义字段(invoice_no/material_no/movement_quantity/movement_date)
到原始行字段名的映射(如 {invoice_no: doc_no})。
Returns:
已校验的 ParsedReceiptRow 列表("无异动日期"的在途/执行中行已跳过)。
已校验的 ParsedMovementRow 列表("无异动日期"的在途/执行中行已跳过)。
Raises:
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
MovementFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
"""
invoice_key = str(projection.get("invoice_no") or "invoice_no")
material_key = str(projection.get("material_no") or "material_no")
quantity_key = str(projection.get("receipt_quantity") or "receipt_quantity")
date_key = str(projection.get("receipt_date") or "receipt_date")
quantity_key = str(projection.get("movement_quantity") or "movement_quantity")
date_key = str(projection.get("movement_date") or "movement_date")
errors: list[dict[str, Any]] = []
parsed: list[ParsedReceiptRow] = []
parsed: list[ParsedMovementRow] = []
for raw in rows:
row = raw if isinstance(raw, Mapping) else {}
row_no = row.get("row_no")
invoice_no = str(row.get(invoice_key) or "").strip()
material_no = str(row.get(material_key) or "").strip()
sheet = str(row.get("sheet") or "").strip()
receipt_date_value = row.get(date_key)
movement_date_value = row.get(date_key)
quantity_raw = row.get(quantity_key)
if not sheet or not row_no:
_fail(errors, row_no=row_no, reason="missing_sheet_or_row_no")
continue
if not material_no:
# [料号空行跳过 2026-10-21] 料号为空=非可用异动行(CRANE/Lognet 出站
# 报告的说明行/占位行实测):不做必填管控、不进异动表,静默跳过——
# 与 _is_unusable_movement_row 同家族(跳过不阻断整文件)。其余必填
#(单号)管控不变,仅对有料号的行生效。
continue
if not invoice_no:
_fail(errors, row_no=row_no, reason="missing_invoice_no")
continue
if not material_no:
_fail(errors, row_no=row_no, reason="missing_material_no")
continue
row_source = str(row.get("source_code") or "").strip()
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
if _is_unusable_receipt_row(receipt_date_value, quantity_raw):
if _is_unusable_movement_row(movement_date_value, quantity_raw):
continue
try:
receipt_date = parse_date(receipt_date_value)
movement_date = parse_date(movement_date_value)
except ValueError:
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_value!r}")
_fail(errors, row_no=row_no, reason=f"invalid_movement_date: {movement_date_value!r}")
continue
try:
quantity = validate_receipt_quantity(quantity_raw)
quantity = validate_inbound_quantity(quantity_raw)
except QuantityValidationError as exc:
_fail(errors, row_no=row_no, reason=str(exc))
continue
parsed.append(ParsedReceiptRow(
parsed.append(ParsedMovementRow(
source_code=str(source_code),
sheet=sheet,
row_no=int(row_no),
@@ -204,8 +189,8 @@ def _parse_rows(
material_no=material_no,
material_name=str(row.get("material_name") or "").strip(),
specification=str(row.get("specification") or "").strip(),
receipt_date=receipt_date,
receipt_quantity=quantity,
movement_date=movement_date,
movement_quantity=quantity,
lot_no=str(row.get("lot_no") or "").strip(),
warehouse_code=str(row.get("warehouse_code") or "").strip(),
# unit 原值透传(movement 契约第 11 字段):仅 trim,空值解析放行。
@@ -215,5 +200,5 @@ def _parse_rows(
# 诊断落库:消息携带前 3 条行级明细(行号+原因),随 parse_error_message
# 落库自描述(2026-10-08 CRANE 零数量行事故:此前只有通用消息、无法定位)。
summary = '; '.join(f"row {r.get('row_no')}: {r.get('reason')}" for r in errors[:3])
raise ReceiptFileSchemaError(f"receipt file schema invalid: {summary}", rows=errors)
raise MovementFileSchemaError(f"movement file schema invalid: {summary}", rows=errors)
return parsed
@@ -1,7 +1,8 @@
"""在途调拨收料文件 Ready 复用与来源级 RPA 触发。
"""在途调拨入站文件 Ready 复用与来源级 RPA 触发。
用途:按 (source_code, business_date, purpose=receipt) 检查最新 ready 文件;
存在则复用,不存在则按来源实例触发一次收料 RPA;存在活动 Source Job
用途:按 (source_code, business_date, 入站解析规则绑定) 检查最新 ready 文件;
存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingInboundReport RPA
产物,shipping_notice 域术语保留);存在活动 Source Job
时绑定已有任务,保证并发请求只触发一次抓取。
依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。
逻辑:文件仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身;
@@ -19,8 +20,8 @@ STAGE_FAILED = "failed"
@dataclass(frozen=True)
class ReadyReceiptFile:
"""当日最新 ready 收料文件快照(含已提取行,供解析)。"""
class ReadyInboundFile:
"""当日最新 ready 入站文件快照(含已提取行,供解析)。"""
source_code: str
business_date: str
@@ -35,30 +36,30 @@ class FilePreparationResult:
"""来源级文件准备结果。"""
stage: str
file: ReadyReceiptFile | None = None
file: ReadyInboundFile | None = None
error_code: str | None = None
error_message: str | None = None
class ReceiptFileRepository(Protocol):
"""收料 ready 文件仓库协议。"""
class InboundFileRepository(Protocol):
"""入站 ready 文件仓库协议。"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
"""返回该来源当日最新 ready 文件;不存在返回 None。"""
class RpaTrigger(Protocol):
"""收料 RPA 触发协议(DBS/Crane 共用)。"""
"""入站 RPA 触发协议(DBS/Crane 共用)。"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
"""触发一次收料抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。"""
"""触发一次入站抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。"""
def ensure_receipt_file_ready(
def ensure_inbound_file_ready(
*,
source_code: str,
business_date: str,
repository: ReceiptFileRepository,
repository: InboundFileRepository,
rpa_trigger: RpaTrigger,
active_source_job_key: str | None = None,
) -> FilePreparationResult:
@@ -1,10 +1,15 @@
"""在途调拨收料回调桥。
"""在途调拨入站回调桥。
用途:货代收料 RPA 回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
用途:货代入站 RPA(入站证据 = ShippingInboundReport RPA 产物,shipping_notice 域,术语保留)
回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。
依赖:models(TransferSourceJob)、datetime。
逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作,
避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。
避免回调迟到误推进其他阶段任务。生产调用方为调拨侧报表事实处理函数
handle_inbound_report(Task 7,inbound_report_handler.py——归档终态 commit 后
经 dispatch_report_fact 调入;返回 None 时调用方跳过提交分支);回归测试桥
(handle_inbound_report / 历史测试桥)仍走本函数。
SourceJob 状态为字符串常量(见 models)。
"""
from __future__ import annotations
@@ -19,7 +24,7 @@ _WAITING_RPA_CALLBACK = 'waiting_rpa_callback'
_FAILED = 'failed'
def advance_source_job_from_receipt_callback(
def advance_source_job_from_inbound_callback(
*, 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:
@@ -27,8 +32,8 @@ def advance_source_job_from_receipt_callback(
Args:
source_code: 回调所属来源实例。
file_no: 收料文件号(success 时)。
file_sha256: 收料文件 sha256(success 时)。
file_no: 入站文件号(success 时)。
file_sha256: 入站文件 sha256(success 时)。
callback_ok / error_code / error_message: 回调终态。
Returns:
被推进的任务;无等待任务或已终态时返回 None。
@@ -50,25 +55,25 @@ def advance_source_job_from_receipt_callback(
job.finished_at = datetime.utcnow()
else:
job.status = _FAILED
job.error_code = error_code or 'RPA_RECEIPT_CALLBACK_FAILED'
job.error_message = error_message or 'receipt rpa callback failed'
job.error_code = error_code or 'RPA_INBOUND_CALLBACK_FAILED'
job.error_message = error_message or 'inbound rpa callback failed'
job.finished_at = datetime.utcnow()
db.session.flush()
return job
def recover_stale_waiting_source_jobs() -> int:
"""把超过收料回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
"""把超过入站回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与收料超时回收同批调用;
不自动重试 RPA——用户可在来源选择卡手动重试(与收料回收"绝不自动重试"口径一致)。
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与入站超时回收同批调用;
不自动重试 RPA——用户可在来源选择卡手动重试(与入站回收"绝不自动重试"口径一致)。
Returns:
本次回收的任务数。
"""
from flask import current_app
try:
timeout = max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
timeout = max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
timeout = 900
cutoff = datetime.utcnow() - timedelta(seconds=timeout)
@@ -79,8 +84,8 @@ def recover_stale_waiting_source_jobs() -> int:
)
for job in stale:
job.status = _FAILED
job.error_code = 'RPA_RECEIPT_CALLBACK_TIMEOUT'
job.error_message = f'receipt rpa callback not received within {timeout}s'
job.error_code = 'RPA_INBOUND_CALLBACK_TIMEOUT'
job.error_message = f'inbound rpa callback not received within {timeout}s'
job.finished_at = datetime.utcnow()
if stale:
db.session.commit()
@@ -0,0 +1,20 @@
"""在途调拨入站归档文件的可用性门禁(口径唯一,语义归 freight_rpa.reports 维护)。
用途:把「一份入站归档文件是否可用于调拨链路」的判定收敛为
freight_rpa/reports/queries 的权威实现,并向调拨域既有 import 路径
(api 下载、历史消费方)透传,防止口径漂移。
依赖:freight_rpa.reports.queries(usable / expired 过滤表达式的唯一权威)。
逻辑:【阶段 B Task 4】本模块不再自带表达式实现,自身不 import 任何
freight_rpa 报表模型;可用 = 未删除 + 当天(Asia/Shanghai 业务日)抓取
+ 未过保留期;已失效(expired)= 未删除 且 该核心不成立——两条件同核
推导,规则文本与业务日窗口换算见 queries.py(禁止反向 import 出现环)。
"""
from __future__ import annotations
from app.services.freight_rpa.reports.queries import (
expired_inbound_file_condition,
usable_inbound_file_condition,
)
__all__ = ["expired_inbound_file_condition", "usable_inbound_file_condition"]
@@ -0,0 +1,134 @@
"""
services/in_transit_transfer/inbound_report_handler.py
用途:inbound 报表事实的调拨侧业务处理函数(阶段 B Task 7)——收料归档
终态 commit 后由 dispatch_report_fact 投递的 ReportFact 只在此推进
调拨自己的任务:TransferSourceJob 终态推进、调拨证据同步、收料排程收口。
依赖:app.db、app.models(FreightRpaInboundUnitRun——执行单元读取;报表文件/
配置模型禁止在本包引用,边界由 test_inbound_report_read_boundary 锁定)、
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 → in_transit_transfer.rpa_sinks.register_inbound_sinks)
注册为 'inbound' kind 处理函数;freight_rpa.inbound.report_archive.
ingest_inbound_callback 在每个终态 db.session.commit() 之后经
dispatch_report_fact 调入本函数。处理函数只改调拨自己的行;
【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚,
Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.core.errors import ValidationError
from app.models import FreightRpaInboundUnitRun
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
from app.services.in_transit_transfer.inbound_callback_bridge import (
advance_source_job_from_inbound_callback,
)
def handle_inbound_report(fact: ReportFact) -> None:
"""report_kind 必须是 inbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready;
ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。
(Task 7 契约 docstring 逐字保留如上;以下为补充说明。)
核心逻辑:
[STEP 1] kind 门禁(fail-closed);[STEP 2] 经桥推进等待中的来源任务(桥只改
status='waiting_rpa_callback' 的行,无等待行返回 None——「没有等待行则 return」
指调拨侧无任务行可改,第二次投递时该行已离开等待态,桥天然不重复推进);
[STEP 3] 桥只 flush 不 commit,推进结果必须在此提交(B3 持久性);[STEP 4]
success 事实触发调拨证据同步(与拆分前终态收尾同口径:按 ok 触发、不依赖
等待任务存在——独立收料批次无调拨任务也须把最新可用文件镜像落档;
桥内自吞异常并自行 commit,本处不包 try);[STEP 5] 精确定位「本次回调收尾的
执行单元」并回写收料排程进度、归集终态(finalize 函数住在 schedule 包——
freight_rpa 禁止 import 它,只能由本处理函数调用;「仍由该处理函数调用」= 拆分
前每笔终态回调后的收口行为保持不变;Task 7 修复轮 2 起定位依据为 fact.unit_run_id
——归档入口每次投递(含 failure/empty 与幂等重放)自单元行回填,success 与
failure 同一机制,绝不按来源/错误文本猜「最新单元」)。
【不捕获异常】任何一步失败原样外抛供 Worker 重试。
Args:
fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/
file_id/sha256/ok/error_code/error_message)。
Returns:
None(推进/同步/收口结果全部写库,不返回业务值)。
Raises:
ValidationError: report_kind 非 inbound(误注册/误分发,fail-closed)。
"""
# [STEP 1] kind 门禁:本函数只消费 inbound 事实(dispatch 已按 kind 路由,
# 此处防御性复核,防止误注册成其他 kind 的处理函数后静默错写调拨行)。
kind = require_report_kind(fact.report_kind)
if kind != 'inbound':
raise ValidationError(
f"handle_inbound_report only accepts inbound facts, got: {kind!r}",
code='SHIPPING.INBOUND_CALLBACK_INVALID',
details={'report_kind': fact.report_kind},
)
# [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready(绑定
# 文件号/指纹);否则 → failed(带错误码/描述)。桥只改 waiting_rpa_callback 行;
# 无等待行返回 None(调拨侧无行可改,直接结束推进分支)。
if fact.ok and fact.file_id is not None:
advanced = advance_source_job_from_inbound_callback(
source_code=fact.source_code,
file_no=str(fact.file_id),
file_sha256=fact.sha256,
callback_ok=True,
)
else:
advanced = advance_source_job_from_inbound_callback(
source_code=fact.source_code,
callback_ok=False,
error_code=fact.error_code,
error_message=fact.error_message,
)
# [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交,否则请求结束回滚会
# 丢掉已推进的任务(B3 持久性——empty/failed 且后续收口提前返回时无人提交)。
if advanced is not None:
db.session.commit()
# [STEP 4] 证据同步:success 事实(ok 且 file_id 有值)后把该来源最新可用
# 入站文件镜像落档。与拆分前终态收尾同口径(按 ok 触发、不依赖等待任务
# 存在——独立收料批次没有调拨任务,但其文件仍是运行期取数的证据源)。
# sync_and_commit_for_callback 桥内自吞异常并自行 commit;本处不包 try,
# 若有异常原样外抛(文件已提交,Worker 重试即可补齐落档)。
if fact.ok and fact.file_id is not None:
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
now = datetime.utcnow()
sync_and_commit_for_callback(
source_code=fact.source_code,
business_date=str(now.date()),
now=now,
)
# [STEP 5] 收料排程收口:精确定位「本次回调收尾的执行单元」的排程 run(Task 7
# 修复轮 2——事实自带 unit_run_id(归档入口每次投递自单元行回填),不再按来源/
# 错误文本猜单元:同来源、同错误文本的新单元存在时旧回调不得收口错误的 run)。
schedule_run_id: int | None = None
if fact.unit_run_id is not None:
# 归档入口产线恒回填 unit_run_id;None 仅为兼容手工构造事实的旧调用方——
# 无单元标识时不猜(跳过收口,不做任何「最新单元」式近似)。
unit = db.session.get(FreightRpaInboundUnitRun, int(fact.unit_run_id))
if unit is None:
# 分发紧跟终态 commit:单元行缺失属硬性不一致,fail-closed 而非静默跳过。
from app.core.errors import NotFoundError
raise NotFoundError(
f"Inbound 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_inbound_finalize import (
finalize_inbound_schedule_run_if_complete,
refresh_inbound_schedule_run_progress,
)
refresh_inbound_schedule_run_progress(schedule_run_id)
finalize_inbound_schedule_run_if_complete(schedule_run_id)
@@ -1,15 +1,20 @@
"""在途调拨真实收料 RPA 触发服务。
"""在途调拨入站 RPA 触发服务。
用途:为单个或多个来源触发收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = freight_rpa 入站 RPA 产物,
复用货代入站 trigger 链路),不创建排程。按来源取站点、入站配置与登录连接
(全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行
(awaiting_rpa,回调按 callback_id 查库可达),再装配入站 trigger unit 并
调用 write_inbound_export_batch_trigger 原子写 trigger。
依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、
freight_rpa.reports.queries(get_site / get_inbound_config / get_rpa_login_profile /
list_inbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。
逻辑:list_inbound_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/入站配置缺失/登录连接缺失时
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
trigger_receipt_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
trigger_inbound_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
【阶段 B Task 4】trigger unit 载荷键集与 Worker 契约(freight_rpa.inbound.v1)
逐键不变;读取改走只读函数后不再引用 freight_rpa 报表模型。
"""
from __future__ import annotations
@@ -18,7 +23,17 @@ import uuid
from datetime import datetime
from typing import Any, Callable
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
from app.services.freight_rpa.inbound.trigger_io import (
ACTION_INBOUND_EXPORT_BATCH,
SCHEMA,
write_inbound_export_batch_trigger,
)
from app.services.freight_rpa.reports.queries import (
get_inbound_config,
get_rpa_login_profile,
get_site,
list_inbound_configured_source_codes,
)
RouteTriggerWriter = Callable[..., str | None]
@@ -26,41 +41,42 @@ RouteTriggerWriter = Callable[..., str | None]
def _build_trigger_unit(
*, source_code: str, business_date: str, reason: str,
) -> dict[str, Any]:
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
"""装配单来源入站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
【阶段 B Task 4】站点(get_site)/ 入站配置(get_inbound_config)/ 登录连接
(get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的
unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
config = get_inbound_config(source_code)
if config is None:
raise RuntimeError(f'receipt config missing: {source_code}')
profile = source.rpa_profile
raise RuntimeError(f'inbound config missing: {source_code}')
profile = get_rpa_login_profile(source_code)
if profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
raise RuntimeError(f'inbound 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.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'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': source.rpa_profile_id,
'warehouse_id': None, 'rpa_profile_id': profile.profile_id,
}
return {
'inventory_source_id': source.id,
'callback_id': f'receipt:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
'source_id': site.source_id,
'callback_id': f'inbound:{uuid.uuid4().hex}',
'source_code': site.source_code,
'connector_type': site.connector_type,
'warehouse_id': None,
'rpa_profile_id': profile.id,
'rpa_profile_id': profile.profile_id,
'rpa_profile_code': profile.profile_code,
'login_url': profile.login_url,
'login_config': dict(profile.login_config_json or {}),
'login_config': dict(profile.login_config or {}),
'credential_envelope': {
'username_ciphertext': profile.username_ciphertext,
'password_ciphertext': profile.password_ciphertext,
@@ -73,38 +89,34 @@ def _build_trigger_unit(
}
def list_receipt_capable_source_codes() -> list[str]:
"""列出可产出收料文件的启用来源实例(enabled 库存源 + 已配置收料报表)。
def list_inbound_capable_source_codes() -> list[str]:
"""列出可产出入站文件的启用来源实例(已配置入站报表的启用站点)。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——收料文件只能
来自已配置收料报表的站点,与货代收料 RPA 排程的站点口径保持一致。
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件
只能来自已配置入站报表的站点,与货代入站 RPA 排程的站点口径一致。
【阶段 B Task 4】站点×入站配置 join 查询改委托
freight_rpa.reports.queries.list_inbound_configured_source_codes;本函数
保留为调拨域语义出口(既有调用方 import 路径不变)。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
from app import db
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
rows = db.session.query(ShippingInventorySource.source_code).join(
ShippingReceiptReportConfig,
ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all()
return [str(code) for (code,) in rows]
return list_inbound_configured_source_codes()
def trigger_receipt_rpa(
def trigger_inbound_rpa(
*,
source_code: str,
business_date: str,
reason: str = 'transfer_retry_receipt',
reason: str = 'transfer_retry_inbound',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源收料 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
"""触发一次来源入站 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
Args:
source_code: 来源实例编码。
business_date: 业务日期。
reason: 触发原因(写入 trigger)。
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
writer: 触发写者;缺省复用 write_inbound_export_batch_trigger。
Returns:
{"ok": True, "callback_id": ..., "trigger_path": ...} 或
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
@@ -112,16 +124,16 @@ def trigger_receipt_rpa(
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_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
return {"ok": False, "error_code": "RPA_INBOUND_CONFIG_MISSING", "error_message": str(exc)}
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
# 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
unit = ShippingReceiptRpaUnitRun(
unit = FreightRpaInboundUnitRun(
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
inventory_source_id=unit_payload['inventory_source_id'],
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'),
@@ -135,20 +147,20 @@ def trigger_receipt_rpa(
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
writer_fn = writer or write_inbound_export_batch_trigger
path = writer_fn(run_no, [unit_payload], payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'schema_version': SCHEMA,
'action': ACTION_INBOUND_EXPORT_BATCH,
'source_code': source_code,
'business_date': business_date,
'reason': reason,
})
if not path:
unit.status = 'failed'
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
unit.error_message = 'receipt trigger directory unavailable'
unit.error_code = 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
unit.error_message = 'inbound trigger directory unavailable'
db.session.commit()
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
return {"ok": False, "error_code": "RPA_INBOUND_TRIGGER_UNAVAILABLE"}
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
unit.trigger_snapshot_json = unit_payload
@@ -156,28 +168,28 @@ def trigger_receipt_rpa(
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
def trigger_receipt_rpa_batch(
def trigger_inbound_rpa_batch(
*,
source_codes: list[str],
business_date: str,
reason: str = 'transfer_retry_receipt',
reason: str = 'transfer_retry_inbound',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""批量触发多来源收料 RPA:全部有效来源合并写**一个** batch trigger 文件。
"""批量触发多来源入站 RPA:全部有效来源合并写**一个** batch trigger 文件。
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
行级单来源重试仍走 trigger_receipt_rpa(一源一文件语义不变)。
行级单来源重试仍走 trigger_inbound_rpa(一源一文件语义不变)。
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批;
parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行
ShippingReceiptRpaUnitRun 再一次性 write_receipt_export_batch_trigger 原子落盘。
RPA 单元运行行再一次性 write_inbound_export_batch_trigger 原子落盘。
Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。
Args:
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
business_date: 业务日期。
reason: 触发原因(写入 trigger payload)。
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
writer: 触发写者;缺省复用 write_inbound_export_batch_trigger。
Returns:
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
@@ -187,13 +199,13 @@ def trigger_receipt_rpa_batch(
跳过:{source_code, ok: false, error_code, error_message})。
"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
results: list[dict[str, Any]] = []
units: list[ShippingReceiptRpaUnitRun] = []
units: list[FreightRpaInboundUnitRun] = []
unit_payloads: list[dict[str, Any]] = []
# [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。
@@ -216,7 +228,7 @@ def trigger_receipt_rpa_batch(
except RuntimeError as exc:
results.append({
'source_code': code, 'ok': False,
'error_code': 'RPA_RECEIPT_CONFIG_MISSING', 'error_message': str(exc),
'error_code': 'RPA_INBOUND_CONFIG_MISSING', 'error_message': str(exc),
})
if not unit_payloads:
@@ -225,12 +237,12 @@ def trigger_receipt_rpa_batch(
db.session.commit()
if reparse_recovered:
return {"ok": True, "triggered": False, "results": results}
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_NO_TRIGGERABLE_SOURCE", "results": results}
return {"ok": False, "triggered": False, "error_code": "RPA_INBOUND_NO_TRIGGERABLE_SOURCE", "results": results}
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
for payload in unit_payloads:
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=payload['inventory_source_id'],
unit = FreightRpaInboundUnitRun(
source_id=payload['source_id'],
source_code=payload['source_code'],
connector_type=payload['connector_type'],
warehouse_id=payload.get('warehouse_id'),
@@ -246,10 +258,10 @@ def trigger_receipt_rpa_batch(
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
writer_fn = writer or write_inbound_export_batch_trigger
path = writer_fn(run_no, unit_payloads, payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'schema_version': SCHEMA,
'action': ACTION_INBOUND_EXPORT_BATCH,
'business_date': business_date,
'reason': reason,
'source_codes': [payload['source_code'] for payload in unit_payloads],
@@ -257,10 +269,10 @@ def trigger_receipt_rpa_batch(
if not path:
for unit in units:
unit.status = 'failed'
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
unit.error_message = 'receipt trigger directory unavailable'
unit.error_code = 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
unit.error_message = 'inbound trigger directory unavailable'
db.session.commit()
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE", "results": results}
return {"ok": False, "triggered": False, "error_code": "RPA_INBOUND_TRIGGER_UNAVAILABLE", "results": results}
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
for unit, payload in zip(units, unit_payloads):
@@ -1,9 +1,10 @@
"""在途调拨 Invoice 多行汇总。
用途:相同 Invoice+料号+收料日期 的多行只汇总收料数量,并永久保留原始
用途:相同 Invoice+料号+异动日期 的多行只汇总异动数量,并永久保留原始
Sheet/行号/文件版本;同 Invoice 跨料号或跨日期自然拆分为多张发票。
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
逻辑:汇总键 (source_code, invoice_no, material_no, receipt_date)。
逻辑:汇总键 (source_code, invoice_no, material_no, movement_date)(tt14 入站化:
明细字段方向中立,日期/数量键统一 movement_*)。
"""
from __future__ import annotations
@@ -15,7 +16,7 @@ from typing import Iterable
from app.core.errors import AppError
from app.services.in_transit_transfer.contracts import TRANSFER_INVOICE_CONFLICT, RawLineRefDTO
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow
from app.services.in_transit_transfer.file_parser import ParsedMovementRow
@dataclass(frozen=True)
@@ -27,11 +28,11 @@ class AggregatedInvoice:
material_no: str
material_name: str
specification: str
receipt_date: date
receipt_quantity: Decimal
movement_date: date
movement_quantity: Decimal
raw_lines: tuple[RawLineRefDTO, ...]
lot_no: str = ""
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
# 组内首行来源仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
warehouse_code: str = ""
# 组内首行交易单位原值(movement 契约第 11 字段 unit,计划 D4):与 lot_no 同为
# 「组内首行」口径;空值在匹配阶段行级 blocked_missing_unit 阻断,不在此换算/清洗。
@@ -39,7 +40,7 @@ class AggregatedInvoice:
class InvoiceConflictError(AppError):
"""同一 Invoice 出现冲突(多料号/多收料日期),整单阻断。"""
"""同一 Invoice 出现冲突(多料号/多异动日期),整单阻断。"""
def __init__(self, message: str = "invoice conflict", *, invoice_no: str, conflict: str):
super().__init__(
@@ -50,11 +51,11 @@ class InvoiceConflictError(AppError):
)
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice+料号+收料日期 汇总收料数量并保留原始行证据。
def aggregate_invoices(rows: Iterable[ParsedMovementRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
"""按 Invoice+料号+异动日期 汇总异动数量并保留原始行证据。
汇总键 (source_code, invoice_no, material_no, receipt_date):Invoice 语义为
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨收料日期时
汇总键 (source_code, invoice_no, material_no, movement_date):Invoice 语义为
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨异动日期时
自然拆分为多张发票(部分交付场景),不做整单阻断。
Args:
rows: 已校验的解析行。
@@ -62,14 +63,14 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
Returns:
汇总后的 Invoice 列表(按汇总键排序)。
"""
grouped: dict[tuple[str, str, str, date], list[ParsedReceiptRow]] = {}
grouped: dict[tuple[str, str, str, date], list[ParsedMovementRow]] = {}
for row in rows:
grouped.setdefault(
(row.source_code, row.invoice_no, row.material_no, row.receipt_date), [],
(row.source_code, row.invoice_no, row.material_no, row.movement_date), [],
).append(row)
invoices: list[AggregatedInvoice] = []
for (source_code, invoice_no, material_no, receipt_date), group in sorted(grouped.items()):
for (source_code, invoice_no, material_no, movement_date_key), group in sorted(grouped.items()):
first = group[0]
raw_lines = tuple(
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
@@ -81,8 +82,8 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
material_no=material_no,
material_name=first.material_name,
specification=first.specification,
receipt_date=receipt_date,
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
movement_date=movement_date_key,
movement_quantity=sum((row.movement_quantity for row in group), Decimal("0")),
raw_lines=raw_lines,
lot_no=first.lot_no,
warehouse_code=first.warehouse_code,
@@ -0,0 +1,334 @@
"""services/in_transit_transfer/ledger_sync.py
用途:库存异动档落地(ADR 0001)——外部记录镜像落地:把解析产物(movement 契约
领域行)按自然键幂等镜像到 transfer_movement_ledger;语义与 evidence_sync
三分类同源(插入/跳过/原行更新,ADR 0001),一期入站(record_kind='inbound'),
outbound 为预留合法值(出货侧结构就位,校验放行,不特判)。
依赖:models/in_transit_transfer.TransferMovementLedger、audit.build_transfer_audit_event、
movement_contract.MOVEMENT_FIELDS(档列镜像取值的唯一字段来源)。不解析文件
(parsed_rows 由调用方/Task 11 接线从解析产物组装)、不查外部系统、零外部调用。
逻辑:file_version 戳由 movement_file_version 统一生成(sha256: 前缀按档列宽度截断),
入站仓库、出站落档、清空重建、匹配进度快照都调用它,禁止各处自行拼接。
落档前先滤 movement_date 空值行——空=未发生异动(未收 ASN/未发货订单行),
落档即幽灵行,计入 date_skipped(解析层已滤一轮,此处为映射无关第二道防线)。
规格 §5 五条幂等语义——①自然键 (doc_no, line_no, line_seq, in_out_flag,
carton_id, lot_no, external_doc_no, external_line_no)(source_code/
record_kind 整批恒定不入行内键;tt14 扩维箱号/批号;2026-10-21 扩维外部
单据身份=外部单号+外部项次,作档幂等主键管控)查档不存在 → 插入
(record_kind/溯源五列随行写入);②行
file_sha256 与来件一致 → 跳过(完全不动行,不续 updated_at——档无 TTL,
无新鲜度概念);③证据变化 → 原行更新业务镜像列 + 换溯源(source_file_id/
file_version/file_sha256/sheet_name/row_no/updated_at);④文件缺席的档行
不删(入站 RPA 非全量导出,缺席≠删除——本函数从不删除,无需显式处理);
⑤transfer_executed=true 封存行永不更新永不复活(sealed_skipped 计数;封存
是最高优先事实,命中即计,与来件 sha 无关;同文件重落不产生第二行,自然键
唯一索引 DB 兜底)。
record_kind 与 in_out_flag 矛盾(inbound 行出库语义 '-1')→ 计 cross_flagged
并写 ledger_cross_check_failed 审计事件,记录照常落档;矛盾标记随落档动作
发生(插入/更新时)——幂等重落不重复打事件,防只追加审计表被同文件重落刷爆;
封存行不落档故不标记(sealed_skipped 即信号)。
只 flush 不 commit(与 evidence_sync 同契约,提交归调用方:落地桥自行 commit,
匹配/执行随主事务)。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Any
from app import db
from app.models import TransferMovementLedger
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
# 契约字段 code ↔ 档列名 1:1 镜像不变式(import 期锁定;MOVEMENT_FIELDS 追加字段
# 时必须同步 TransferMovementLedger 模型列,否则此处导入即失败——fail-fast)。
_MOVEMENT_CODES: tuple[str, ...] = tuple(f.code for f in MOVEMENT_FIELDS)
assert set(_MOVEMENT_CODES) <= {c.name for c in TransferMovementLedger.__table__.columns}
# record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。
INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"})
# 自然键 NOT NULL 成分(行级 8 成分;source_code/record_kind 整批恒定不入行内键):
# 镜像取值时缺值以空串落库(防 NULL 违反非空约束/逃逸唯一比对,与模型 default '' 同口径)。
_NOT_NULL_KEY_CODES: tuple[str, ...] = (
"doc_no", "line_no", "line_seq", "in_out_flag",
"carton_id", "lot_no", "external_doc_no", "external_line_no",
)
# 记录种类字面量:inbound=入站(ShippingInboundReport RPA 产物,shipping_notice 域术语保留);
# outbound=出站(出货侧结构就位)。
RECORD_KIND_INBOUND = "inbound"
RECORD_KIND_OUTBOUND = "outbound"
# 交叉校验矛盾审计事件 kind(任务简报冻结字面量;仓库事件 kind 无集中常量表,行内字面量惯例)。
LEDGER_CROSS_CHECK_EVENT = "ledger_cross_check_failed"
@dataclass(frozen=True)
class FileMeta:
"""一次落地的来源文件证据三元组(溯源的文件级成分;Task 11 从归档文件组装)。
Args:
source_file_id: 入站原样归档文件 id(freight_rpa_inbound_report_files.id;
测试/极端场景可为 None——档事实留存不依赖文件存在)。
file_version: 文件版本号(Task 13 执行门禁 file_current 比对依据)。
file_sha256: 文件 SHA-256(幂等跳过判定的唯一证据指纹)。
"""
source_file_id: int | None = None
file_version: str | None = None
file_sha256: str | None = None
def movement_file_version(sha256: str) -> str:
"""把文件 SHA-256 摘要打成异动档 file_version 戳。
核心逻辑:前缀 sha256: 加摘要后,按 TransferMovementLedger.file_version 列宽截断。
64 位摘要加前缀共 71 字符,超出 varchar(64) 时 PostgreSQL 会整批拒绝插入。
列宽取自模型,避免戳长和列定义各写一个 64。
Args:
sha256: 文件 SHA-256 十六进制摘要,不含前缀。
Returns:
以 sha256: 开头、长度不超过档列宽度的版本戳。
"""
limit = TransferMovementLedger.__table__.c.file_version.type.length
return f"sha256:{sha256}"[:limit]
@dataclass(frozen=True)
class LedgerSyncOutcome:
"""一次落档的结果计数(审计与兜底日志的数据源;字段名为冻结契约,顺序自 date_skipped 引入后不再承诺)。"""
inserted: int = 0 # 自然键不存在 → 插入新档行
updated: int = 0 # 证据变化 → 原行更新业务镜像列 + 换溯源
skipped: int = 0 # sha 未变的幂等跳过;同批自然键重复的后续行亦计入
date_skipped: int = 0 # movement_date 空=未发生异动,不落档
sealed_skipped: int = 0 # 封存行(transfer_executed=true)命中即计:永不更新永不复活
cross_flagged: int = 0 # record_kind 与 in_out_flag 矛盾且本次实际落档的行数
def _key_text(value: Any) -> str:
"""自然键成分归一化:None → 空串,其余 str + strip(键成分 NOT NULL 恒有值可比)。"""
return "" if value is None else str(value).strip()
def _mirror_text(value: Any) -> str | None:
"""业务镜像值归一化:None 保留(宽松落地可空),其余 str + strip 原样落档。"""
return None if value is None else str(value).strip()
def _opt_int(value: Any) -> int | None:
"""可选整数(row_no):缺失/无效宽容置 None(溯源缺失不打断落地)。"""
if value is None or value == "":
return None
try:
return int(value)
except (TypeError, ValueError):
return None
def _cross_check_event(
*,
source_code: str,
record_kind: str,
key: tuple[str, str, str, str, str, str, str, str],
sheet_name: str | None,
row_no: int | None,
file_meta: FileMeta,
):
"""构造交叉校验矛盾审计事件(未落库,由调用方 add——build 契约同 audit 模块)。
Args:
source_code / record_kind: 来源实例编码与记录种类。
key: 自然键八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
lot_no, external_doc_no, external_line_no)(已归一化;箱号/批号随
tt14 键扩维入事件,外部单据身份随 2026-10-21 键扩维入事件,保证
矛盾行可唯一定位)。
sheet_name / row_no: 行级溯源(入事件快照辅助定位来源行)。
file_meta: 来源文件证据三元组。
Returns:
已计算 Hash 的 TransferAuditEvent(event_type=ledger_cross_check_failed)。
"""
(doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
external_doc_no, external_line_no) = key
natural_key = "/".join((
source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
external_doc_no, external_line_no,
))
return build_transfer_audit_event(
event_type=LEDGER_CROSS_CHECK_EVENT,
aggregate_type="transfer_movement_ledger",
# aggregate_id 列宽 String(128):超长截断防御(全量字段在 after 快照留存)。
aggregate_id=natural_key[:128],
actor_type="system",
result="failure",
after={
"source_code": source_code, "record_kind": record_kind,
"doc_no": doc_no, "line_no": line_no, "line_seq": line_seq,
"in_out_flag": in_out_flag, "carton_id": carton_id, "lot_no": lot_no,
"external_doc_no": external_doc_no, "external_line_no": external_line_no,
"file_version": file_meta.file_version, "file_sha256": file_meta.file_sha256,
"sheet_name": sheet_name, "row_no": row_no,
},
)
def sync_ledger_rows(
*,
source_code: str,
record_kind: str,
parsed_rows: list[dict],
file_meta: FileMeta,
now: datetime,
) -> LedgerSyncOutcome:
"""按自然键幂等落地一批领域行到库存异动档(零外部调用,flush 不 commit)。
【AI 触发时机】Task 11 接线后由落地主链路(evidence_sync 同步入口)在入站
文件落地成功时调用;未来出货报告接入时以 record_kind='outbound' 复用。
不要在匹配/执行链路调用本函数(匹配从档圈定,不写档)。
Args:
source_code: 来源实例编码(自然键成分,整批一致)。
record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingInboundReport
RPA 产物);'outbound' 出货侧(预留合法值,校验放行,不特判)。
parsed_rows: 领域行 dict 列表,每行键=movement 契约 field code
(movement_contract.MOVEMENT_FIELDS:既有 11 + 扩展 7,与
档列名 1:1 镜像),值为解析原值(None=缺失,宽松落地);
可另含可选行级溯源键 sheet_name(str)/row_no(int)(由接线方
从解析产物 ParsedMovementRow 组装);未知键忽略。行必含自然键
成分 doc_no/line_no/line_seq/in_out_flag/carton_id/lot_no
(缺失按空串落档,必填校验归解析层,本函数不做二次阻断);
movement_date 为空(None/空白)的行不入档(未发生异动,
计入 date_skipped)。
file_meta: 来源文件证据三元组(FileMeta);file_sha256 为 None 时无法证明
与档行同源,一律走更新分支(宁可重写不误跳)。
now: 落档时间基准(插入/更新显式续 updated_at;跳过不续——完全不动行)。
Returns:
LedgerSyncOutcome 六分类计数(inserted/updated/skipped/date_skipped/
sealed_skipped/cross_flagged)。
"""
counters = {
"inserted": 0, "updated": 0, "skipped": 0,
"date_skipped": 0, "sealed_skipped": 0, "cross_flagged": 0,
}
# [STEP 0] movement_date 非空才落档:空值=未发生异动(未收 ASN/未发货订单行),
# 落档即幽灵行(永不进匹配圈档)。解析层 file_parser 已滤一轮(异动语义),
# 此处是映射无关的第二道防线:Profile 无论把哪列配到 movement_date,空值都进不了档。
total_in = len(parsed_rows)
parsed_rows = [raw for raw in parsed_rows if _key_text(raw.get("movement_date"))]
counters["date_skipped"] = total_in - len(parsed_rows)
# [STEP 1] 只圈定批内 doc_no 的既有档行(含封存行——封存命中必须可见),按自然键
# 建索引;source_code/record_kind 整批恒定,键只留行级八成分(tt14 扩维:
# carton_id/lot_no——真实 WMS 行身份=单据+行+箱/批;2026-10-21 扩维:
# external_doc_no/external_line_no——外部单据身份作档幂等主键管控)。档「缺席
# 不删、永不删除」行数单调增长(评审 Important 修复):按 source+kind 全量
# 水化会使每次落地成本随历史线性膨胀(Task 11 接生产落地热路径),故追加
# doc_no IN 批内过滤——批外键本就查不到、不参与任何分支,语义与全量查询 100%
# 等价;in_([]) 空批由 SQLAlchemy 渲染恒假子句,安全。
doc_nos = sorted({_key_text(raw.get("doc_no")) for raw in parsed_rows})
existing = (
TransferMovementLedger.query.filter_by(
source_code=source_code, record_kind=record_kind,
)
.filter(TransferMovementLedger.doc_no.in_(doc_nos))
.all()
)
by_key = {
(r.doc_no, r.line_no, r.line_seq, r.in_out_flag, r.carton_id, r.lot_no,
r.external_doc_no, r.external_line_no): r
for r in existing
}
# 同批自然键去重索引(首见为准):批内重复若不拦截,二次插入会撞
# uq_transfer_movement_ledger_natural_key 唯一约束炸 flush。
landed: dict[tuple[str, str, str, str, str, str, str, str], TransferMovementLedger] = {}
# [STEP 2] 逐行六分类:日期空 → 封存 → 跳过 → 插入/更新(矛盾标记随落档动作判定)。
for raw in parsed_rows:
doc_no = _key_text(raw.get("doc_no"))
line_no = _key_text(raw.get("line_no"))
line_seq = _key_text(raw.get("line_seq"))
in_out_flag = _key_text(raw.get("in_out_flag"))
carton_id = _key_text(raw.get("carton_id"))
lot_no = _key_text(raw.get("lot_no"))
external_doc_no = _key_text(raw.get("external_doc_no"))
external_line_no = _key_text(raw.get("external_line_no"))
key = (doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
external_doc_no, external_line_no)
sheet_name = _mirror_text(raw.get("sheet_name"))
row_no = _opt_int(raw.get("row_no"))
row = by_key.get(key) or landed.get(key)
# [封存不触碰] 封存是最高优先事实:命中即计 sealed_skipped 并跳过一切写
# (与来件 sha 无关)——永不更新、永不复活,防已执行记录被二次调拨。
if row is not None and row.transfer_executed:
counters["sealed_skipped"] += 1
continue
# [幂等跳过] 行 file_sha256 与来件一致 = 同一文件重落:完全不动行
#(不续 updated_at,档无 TTL);meta 无 sha 时无法证明同源,不跳过。
if (
row is not None
and file_meta.file_sha256 is not None
and row.file_sha256 == file_meta.file_sha256
):
counters["skipped"] += 1
continue
# [交叉校验] inbound 行出现出库语义 '-1' 即解析错位:计 cross_flagged 并写
# 审计事件,记录照常落档。仅在插入/更新(实际落档)时判定——幂等重落
#(sha 未变跳过)不重复打事件,封存行不落档故不标记。
if record_kind == RECORD_KIND_INBOUND and in_out_flag in INBOUND_CONTRADICTORY_FLAGS:
counters["cross_flagged"] += 1
db.session.add(_cross_check_event(
source_code=source_code, record_kind=record_kind, key=key,
sheet_name=sheet_name, row_no=row_no, file_meta=file_meta,
))
# [镜像取值] 业务值一律从领域行 dict 按契约 code 取(扩展字段无独立槽位);
# 自然键 NOT NULL 成分缺值以空串落库(_key_text,防 NULL 违反非空约束/
# 逃逸唯一比对——2026-10-21 外部身份扩维时修复的潜在缺陷:此前镜像缺值
# 即 None,仅因各组装方恒给空串而未暴露)。自然键成分同源同值,插入/更新
# 统一按全字段镜像写入(更新时键成分等值重写为无操作,SQLAlchemy 等值列
# 不入 UPDATE)。
mirror = {
code: (_key_text(raw.get(code)) if code in _NOT_NULL_KEY_CODES
else _mirror_text(raw.get(code)))
for code in _MOVEMENT_CODES
}
if row is None:
# [插入] 自然键不存在:新档行,record_kind + 溯源五列随行写入。
row = TransferMovementLedger(
source_code=source_code,
record_kind=record_kind,
**mirror,
source_file_id=file_meta.source_file_id,
file_version=file_meta.file_version,
file_sha256=file_meta.file_sha256,
sheet_name=sheet_name,
row_no=row_no,
updated_at=now,
)
db.session.add(row)
landed[key] = row
counters["inserted"] += 1
else:
# [原行更新] 证据变化:业务镜像列整体换新 + 换溯源五件套与 updated_at
#(sha 变而业务值未变时重写等值为无操作,仅溯源换新,计数同归 updated)。
for code, value in mirror.items():
setattr(row, code, value)
row.source_file_id = file_meta.source_file_id
row.file_version = file_meta.file_version
row.file_sha256 = file_meta.file_sha256
row.sheet_name = sheet_name
row.row_no = row_no
row.updated_at = now
counters["updated"] += 1
# [STEP 3] 缺席不删:文件里没有的自然键本函数从不触碰(入站 RPA 非全量导出,
# 缺席≠删除),无对应计数(Outcome 契约无 absent 字段)。
# [STEP 4] 只 flush 不 commit:与 evidence_sync 同契约,提交归调用方
#(落地桥自行 commit,匹配/执行随主事务)。
db.session.flush()
return LedgerSyncOutcome(**counters)
File diff suppressed because it is too large. Load diff
@@ -1,10 +1,10 @@
"""在途调拨通用异动/移动表领域字段契约。
用途:定义调拨消费的异动(入库/出库/收料/出货)文件领域字段——业务定死、不配置化。
用途:定义调拨消费的异动(入站/出站)文件领域字段——业务定死、不配置化。
未来出货/入库 Excel 复用同一套字段,靠 in_out_flag 区分方向。
依赖:标准库 dataclasses / enum。
逻辑:字段清单是 immutable 常量;幂等键为 doc_no,严格数量字段为 quantity,
成熟过滤字段为 movement_date;字段映射由 movement_parser 完成。
日期圈定过滤字段为 movement_date;字段映射由 file_parser.parse_movement_rows 完成。
"""
from __future__ import annotations
@@ -40,14 +40,22 @@ class MovementField:
required: bool = False
# 定死的 11 个通用异动字段(领域契约,不配置化)。
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
# 定死的通用异动字段(领域契约,不配置化):11 个核心字段 + 扩展可选维度字段。
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingInboundReport External ASN #);
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生收敛为 external_lot_no() 唯一实现——
# 库存查询 / 建单下传 / 单行聚合 / 展示统一按外部形态;落库保持文件原形态(证据原则)。
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生曾收敛为 external_lot_no() 唯一实现。
# [PROMPT_UPDATE] 2026-10-14(Task 11 切换):external_lot_no() 硬编码退役——批号
# 外部形态改由调拨类型配置的转换规则驱动(field_transforms 引擎,匹配快照固化),
# 行与档始终保存文件原形态(证据原则不变)。
# [PROMPT_UPDATE] 2026-09-24:追加第 11 字段 unit(交易单位,计划 D4)——ERP 写入
# 行必填(gls_cm19),但解析层放行空值(不产生解析失败),空值由匹配阶段行级
# blocked_missing_unit 阻断;unit 不参与幂等/匹配,也不进匹配 Hash 快照(口径冻结)。
# [PROMPT_UPDATE] 2026-10-14:追加 7 个可选维度字段(Task 8,调拨类型配置化+库存
# 异动档项目)——line_seq/specification/order_type/odm_id/odm_name/carton_id/pallet_id,
# 全部 required=False, is_identity=False,只追加不重排(unit 仍为第 11 字段);
# 解析层缺列容忍自动继承(row.get 投影,缺列不报错);幂等键 doc_no 与身份集
# (doc_no/material_code/movement_date)不变;字段值由库存异动档按 code 取值落档
# (Task 10),管理端字段目录/解析 Profile 映射白名单按 MOVEMENT_FIELDS 派生自动继承。
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
@@ -60,6 +68,22 @@ MOVEMENT_FIELDS: tuple[MovementField, ...] = (
MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True),
MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True),
MovementField("unit", "单位", MovementFieldValueType.TEXT),
# ---- 2026-10-14 扩展:可选维度字段(展示/圈档/异动档取值,非匹配身份) ----
MovementField("line_seq", "项序", MovementFieldValueType.TEXT),
MovementField("specification", "规格", MovementFieldValueType.TEXT),
MovementField("order_type", "订单类型", MovementFieldValueType.TEXT),
MovementField("odm_id", "ODM编号", MovementFieldValueType.TEXT),
MovementField("odm_name", "ODM名称", MovementFieldValueType.TEXT),
MovementField("carton_id", "箱号", MovementFieldValueType.TEXT),
MovementField("pallet_id", "栈板号", MovementFieldValueType.TEXT),
# ---- 2026-10-21 扩展:外部单据身份(外部单号/外部项次;CRANE/Lognet 出站
# 报告的 WMS Order #/行号)——解析放行空值(required=False),不进匹配身份
#(is_identity=False:匹配 grain 仍=单号/料号/异动日期,契约测试钉死不受扰);
# 但两字段自 2026-10-21 起作为库存异动档自然键成分(模型
# uq_transfer_movement_ledger_natural_key + ledger_sync 行级键)承担档幂等
# 主键管控:同一外部单号+项次的重复落档/证据更新收敛到同一档行。
MovementField("external_doc_no", "外部单号", MovementFieldValueType.TEXT),
MovementField("external_line_no", "外部项次", MovementFieldValueType.TEXT),
)
@@ -81,25 +105,3 @@ def movement_identity_fields() -> set[str]:
def movement_field_codes() -> set[str]:
"""全部定死字段名集合。"""
return {field.code for field in MOVEMENT_FIELDS}
def external_lot_no(lot_no: str | None) -> str:
"""批号外部形态派生:WMS 批号 WTP 前缀 → 外部系统真实批号 HOW 前缀。
【AI 触发时机】任何把行上 lot_no 发往外部系统的场景——库存查询 targets、
写前库存复查、建单单行——组装参数前必须经本函数转换;单行聚合键与展示列
「拨出/拨入批号」同规则(前端 features/chat/components/messages/transferBatch.ts
deriveBatchNo 为本函数的展示侧镜像,改动须双侧同步)。行上落库值保持文件
原形态(证据原则:raw_lines 对账/审计复算以文件为准),转换只发生在外部
系统边界。
Args:
lot_no: 行上批号原值(文件证据形态;None/空白按空串处理)。
Returns:
外部系统批号形态:WTP 前缀识别大小写不敏感,余串逐字保留;
非 WTP 前缀原样返回;空输入返回空串。
"""
value = str(lot_no or "").strip()
if value.upper().startswith("WTP"):
return f"HOW{value[3:]}"
return value
@@ -1,31 +1,70 @@
"""在途调拨真实异动(收料/出货)文件仓库。
"""在途调拨真实异动(入站/出站)文件仓库。
用途:读取货代收料链路已落库的 ShippingReceiptReportFile(对象存储原始 xlsx),
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、receipt_file_gate(可用性门禁)、openpyxl。
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
用途:读取货代入站链路已落库的入站归档文件(入站证据 = freight_rpa 入站
RPA 产物,对象存储原始 xlsx),用该来源入站报表配置绑定的 inbound
解析规则(purpose='inbound',端点=定死领域字段 MOVEMENT_FIELDS)的
field_mapping 把列映射为领域行,产出 ReadyInboundFile。
依赖:【阶段 B Task 4】freight_rpa.reports.queries(站点 get_site / 入站配置
get_inbound_config / 入站解析方案 get_inbound_parsing_profile / 最新可用
归档 latest_usable_inbound_file / 归档字节 read_inbound_file_bytes /
维护通道清单 list_reparseable_inbound_files——只读入口唯一权威)、
file_preparation(ReadyInboundFile 契约)、ledger_sync.movement_file_version
(file_version 戳的唯一生成处)、openpyxl。
逻辑:按来源取站点(enabled)与配置 → 解析方案须 published inbound → 最新
【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、文件缺失
或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内
折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。
另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道):
委托 queries 维护通道查询(同一 join 路径但显式去掉当日门禁),仅供
backlog_reparse_service 使用,运行期禁用。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import datetime
from io import BytesIO
from typing import Any, Mapping
from app.services.file_assets.storage import file_asset_storage
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
from app.services.freight_rpa.reports.queries import (
get_inbound_config,
get_inbound_parsing_profile,
get_site,
latest_usable_inbound_file,
list_reparseable_inbound_files,
read_inbound_file_bytes,
)
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
from app.services.in_transit_transfer.ledger_sync import movement_file_version
# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。
_HEADER_WS_RE = re.compile(r"\s+")
@dataclass(frozen=True)
class ReparseableArchiveFile:
"""一份「可重建」归档文件的维护视图(清空重建专用记录,非运行期取数契约)。
Args:
file_id: 归档文件 id(入站归档文件表主键,档行溯源列同源)。
storage_key: 对象存储键(重建时按此取归档字节)。
sha256: 文件 SHA-256(重落幂等指纹 / FileMeta.file_sha256)。
file_version: 文件版本戳(sha256: 前缀派生,与 latest_ready_file 同口径)。
archived_at: 归档时间(created_at;重建按此升序重落)。
original_filename: 原始文件名(预检清单/审计展示)。
"""
file_id: int
storage_key: str
sha256: str
file_version: str
archived_at: datetime
original_filename: str
def _normalize_header_label(value: Any) -> str:
"""归一化表头/别名文本:去首尾空白,内部任意空白(含 \\n)压成单空格。
@@ -37,64 +76,94 @@ def _normalize_header_label(value: Any) -> str:
return _HEADER_WS_RE.sub(" ", str(value or "").strip())
class ShippingReceiptFileRepository:
"""真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。"""
class ShippingInboundFileRepository:
"""真实入站/异动 ready 文件仓库(复用 freight_rpa 入站归档 + inbound 解析规则)。
def __init__(self) -> None:
self._storage = file_asset_storage
【阶段 B Task 4】模型/存储读取全部收敛到 freight_rpa.reports.queries 只读
入口,本类不再 import freight_rpa 报表模型或对象存储客户端;对调用方
(file_preparation / deps / backlog_reparse_service)的类名与方法签名不变。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
"""返回该来源最新且当天(业务日)抓取的未过期入站文件;否则返回 None。
核心逻辑:[STEP 1] 站点须启用(get_site)+ 入站配置须存在
(get_inbound_config)+ 绑定解析方案须 published inbound
(get_inbound_parsing_profile,与运行期规则门禁同一口径);
[STEP 2] 取最新可用归档视图(latest_usable_inbound_file,当天
fail-closed 门禁见 queries.usable_inbound_file_condition)并按
file_id 读归档字节(read_inbound_file_bytes);[STEP 3] 按方案
field_mapping 提取领域行。
Args:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
business_date: 业务日期(用于展示,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
ReadyInboundFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
site = get_site(source_code)
if site is None or not site.enabled:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
config = get_inbound_config(source_code)
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
profile = get_inbound_parsing_profile(source_code)
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
return None
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。
usable_receipt_file_condition(),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.first()
)
if report is None:
view = latest_usable_inbound_file(source_code)
if view is None:
return None
data = self._storage.get_bytes(report.storage_key)
definition = profile.definition_json or {}
data = read_inbound_file_bytes(view.file_id)
rows = _extract_movement_rows(
data,
field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}),
sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None,
header_row_index=(profile.definition_json or {}).get('header_row_index'),
field_mapping=dict(definition.get('field_mapping') or {}),
sheet_name=str(definition.get('sheet_name') or '').strip() or None,
header_row_index=definition.get('header_row_index'),
)
return ReadyReceiptFile(
return ReadyInboundFile(
source_code=source_code,
business_date=business_date,
file_no=report.original_filename or str(report.id),
file_version=f"sha256:{report.sha256}"[:64],
checksum=report.sha256,
file_no=view.original_filename or str(view.file_id),
file_version=movement_file_version(view.sha256),
checksum=view.sha256,
rows=tuple(rows),
)
def list_reparseable_archived_files(self, source_code: str, now: datetime) -> list[ReparseableArchiveFile]:
"""清空重建专用:该来源全部可重建归档(未清理+未过保留期),不设当日门禁。
【AI 触发时机】仅待匹配「清空并重新解析」维护链路使用;运行期落档
(evidence_sync)禁止改用本方法——当日 fail-closed 门禁是运行期语义,
本方法是显式的历史重建通道(spec §6),两者不得混用。
核心逻辑:委托 freight_rpa.reports.queries.list_reparseable_inbound_files
维护通道查询(同一 join 路径,显式去掉「当天业务日抓取」新鲜度门禁——
重建对象正是历史归档;保留期口径一致),并把只读视图映射为本仓库的
维护契约 ReparseableArchiveFile。只读查询,不触碰对象存储字节(字节
由调用方按需经 file_asset_storage 取)。
Args:
source_code: 来源实例编码(经收料执行单元行 source_code 关联)。
now: 保留期判定时刻。
Returns:
ReparseableArchiveFile 列表(archived_at 升序;无可重建归档为空表)。
"""
return [
ReparseableArchiveFile(
file_id=view.file_id,
storage_key=view.storage_key,
sha256=view.sha256,
file_version=movement_file_version(view.sha256),
archived_at=view.created_at,
original_filename=view.original_filename,
)
for view in list_reparseable_inbound_files(source_code, now=now)
]
def _extract_movement_rows(
data: bytes,
@@ -117,7 +186,7 @@ def _extract_movement_rows(
header_row_index: 1-based 表头行;空则自动探测。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index
wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True)
try:
@@ -172,4 +241,4 @@ def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str
if codes and index < len(row):
for code in codes:
output[code] = row[index]
return output
return output
@@ -5,7 +5,8 @@
依赖:models、status、date_policy、matching_service(编号生成/TransferDeps)。
逻辑:执行 Run 与匹配解耦(不回写 matching.run_id / confirmed_at);D8 异步拆分后
Run 初始态为 queued(prepare 段只建 Run+关联行+建单,worker 段置 executing);
行归属由调用方按 scope 圈定(见 matching_service.scope_item_query)后显式传入,
行归属由调用方圈定(出生翻转后 items 创建即绑定 matching_id,restore/执行
入口按匹配自有 items 圈行)后显式传入,
本模块只负责"建 Run + 关联选中行",已关联(run_id 非空)的行跳过。
"""
@@ -58,7 +59,6 @@ def create_execution_run_for_items(
source_codes_json=sorted({item.source_code for item in candidates}),
counts_json={
"file_invoice_count": len(candidates),
"not_matured_count": 0,
"matched_count": len(candidates),
"executable_count": len(candidates),
"blocked_count": 0,
@@ -0,0 +1,223 @@
"""services/in_transit_transfer/outbound_evidence_sync.py
用途:出站证据同步——出站回调 success 后把该来源最新可用出站归档按
purpose='outbound' 已发布解析规则解析、以 record_kind='outbound' 幂等落档
(transfer_movement_ledger),与 evidence_sync(入站专用,record_kind='inbound')
完全对称;解析失败把 parse_failed 三列独立落到出站归档文件上(2026-10-16
出站落档桥补齐——此前出站链路止步于归档+状态投影,异动档恒无 outbound 行)。
依赖:ledger_sync(sync_ledger_rows / RECORD_KIND_OUTBOUND / FileMeta /
movement_file_version)、
evidence_sync(parse_archive_to_ledger_rows 解析组装单一口径 +
_detect_natural_key_collapses/_natural_key_collapse_event 坍缩守卫 + SyncOutcome)、
movement_file_repository._extract_movement_rows(归档字节提取)、
source_file_status.latest_usable_outbound_file(出站可用文件视图,当天新鲜度
口径)、freight_rpa.reports.queries(get_outbound_config /
mark_outbound_parse_failure / clear_outbound_parse_failure)、file_asset_storage、
models、audit、db。
逻辑:sync_outbound_source_rows 只 flush 不 commit(提交归属调用方,契约同入站
sync_source_rows);sync_and_commit_for_outbound_callback 桥自行 commit +
异常全吞(B3 桥隔离——出站归档主链路不得被落档失败波及),schema 类失败
rollback 后把失败事实独立 commit 到当前可用文件(入站同款解析失败分层)。
规则门禁 fail-closed:无配置 / 未绑定规则 / 规则未发布 / purpose≠outbound
→ no-op(None)——规则缺失不是文件错误,不落解析失败标记(与入站仓库
latest_ready_file 门禁同口径)。cross_flag 交叉校验沿用 ledger_sync 既有
口径(当前仅 inbound 定义矛盾标志,outbound 行不计数)。
"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import FreightRpaParsingProfile
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.reports.queries import (
clear_outbound_parse_failure,
get_outbound_config,
mark_outbound_parse_failure,
)
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.evidence_sync import (
SyncOutcome,
_detect_natural_key_collapses,
_natural_key_collapse_event,
parse_archive_to_ledger_rows,
)
from app.services.in_transit_transfer.file_parser import MovementFileSchemaError
from app.services.in_transit_transfer.ledger_sync import (
RECORD_KIND_OUTBOUND,
FileMeta,
movement_file_version,
sync_ledger_rows,
)
from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows
from app.services.in_transit_transfer.source_file_status import latest_usable_outbound_file
_TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
# schema 类解析失败判据与入站桥同一口径(code 或异常类型)。
_SCHEMA_FAILURE_CODES = (_TRANSFER_FILE_SCHEMA_INVALID,)
def _load_published_outbound_profile(source_code: str) -> FreightRpaParsingProfile | None:
"""加载来源出站配置绑定的「已发布 purpose='outbound'」解析规则(fail-closed 门禁)。
核心逻辑:出站配置(get_outbound_config,缺失=None)→ parsing_profile_id →
规则行须 published 且 purpose='outbound'——与运行期入站取数门禁
(movement_file_repository.latest_ready_file 的 published inbound 校验)同构。
Args:
source_code: 来源实例编码。
Returns:
FreightRpaParsingProfile;任一环节缺失或门禁不符返回 None。
"""
config = get_outbound_config(source_code)
if config is None or config.parsing_profile_id is None:
return None
profile = db.session.get(FreightRpaParsingProfile, config.parsing_profile_id)
if profile is None or profile.status != "published" or profile.purpose != "outbound":
return None
return profile
def sync_outbound_source_rows(*, source_code: str, now: datetime) -> SyncOutcome | None:
"""解析来源最新可用出站归档并幂等落档(零外部调用,flush 不 commit)。
【AI 触发时机】出站 RPA 回调桥(sync_and_commit_for_outbound_callback)调用;
不要在匹配/重查链路调用(匹配从档圈定,不写档)。
Args:
source_code: 来源实例编码。
now: 落档时间基准(插入/更新显式续 updated_at;文件新鲜度判定时刻)。
Returns:
SyncOutcome;无可用出站文件或无 published outbound 规则返回 None
(该分支不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。
Raises:
MovementFileSchemaError: 行必填缺失/非法(schema 类失败原样上抛——桥内
rollback + 落解析失败标记)。
"""
file_view = latest_usable_outbound_file(source_code, now=now)
if file_view is None:
return None
profile = _load_published_outbound_profile(source_code)
if profile is None:
return None
definition = profile.definition_json or {}
# [STEP 1] 归档字节 → 原始行(提取口径与运行期入站/清空重建同源)→ 档行
# (parse_archive_to_ledger_rows 解析组装单一口径;schema 类失败原样上抛)。
data = file_asset_storage.get_bytes(file_view.storage_key)
raw_rows = _extract_movement_rows(
data,
field_mapping=dict(definition.get("field_mapping") or {}),
sheet_name=str(definition.get("sheet_name") or "").strip() or None,
header_row_index=definition.get("header_row_index"),
)
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows)
# [STEP 2] 幂等落档(record_kind='outbound');溯源文件三元组取当前可用归档。
# file_version 走 movement_file_version:出站归档无独立版本列,戳与入站仓库、
# 清空重建、匹配进度快照同一函数,避免再在此处自行拼接超长。
outcome = sync_ledger_rows(
source_code=source_code,
record_kind=RECORD_KIND_OUTBOUND,
parsed_rows=assembled,
file_meta=FileMeta(
source_file_id=file_view.file_id,
file_version=movement_file_version(file_view.sha256),
file_sha256=file_view.sha256,
),
now=now,
)
# [档自然键坍缩守卫] 与入站同口径复检(检测按行级六成分、record_kind 声明进
# 审计聚合键);仅实际落档时打事件,幂等重落不刷审计。
collapses = _detect_natural_key_collapses(assembled)
if collapses and (outcome.inserted or outcome.updated):
for collapse in collapses:
db.session.add(_natural_key_collapse_event(
source_code=source_code, collapse=collapse, record_kind=RECORD_KIND_OUTBOUND))
result = SyncOutcome(
source_code=source_code,
file_sha256=file_view.sha256 or "",
inserted=outcome.inserted,
updated=outcome.updated,
skipped=outcome.skipped,
sealed_skipped=outcome.sealed_skipped,
cross_flagged=outcome.cross_flagged,
)
db.session.add(build_transfer_audit_event(
event_type="TRANSFER_EVIDENCE_SYNCED",
aggregate_type="transfer_source",
aggregate_id=source_code,
actor_type="system",
result="success",
after={
"file_sha256": result.file_sha256,
"record_kind": RECORD_KIND_OUTBOUND,
"inserted": result.inserted, "updated": result.updated,
"skipped": result.skipped, "sealed_skipped": result.sealed_skipped,
"cross_flagged": result.cross_flagged,
},
))
# [解析失败分层] 同步成功 = 当前可用文件已成功解析:清除失败标记(若此前
# 失败过),出站流状态投影随之恢复 ready。只 flush 不 commit。
if file_view.parse_failed_at is not None:
clear_outbound_parse_failure(file_view.file_id)
return result
def sync_and_commit_for_outbound_callback(*, source_code: str, now: datetime) -> bool:
"""出站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
【AI 触发时机】出站 RPA 回调 success 终态落文件后由
handle_outbound_report(outbound_report_handler)调用——桥是记账不是出站
链路的正确性依赖,任何异常不得向出站归档主链路传播(B3:必须自行 commit)。
【解析失败分层】失败路径先 rollback(桥隔离),仅 schema 类解析失败把失败
事实(parse_failed 三列)独立 commit 落到当前可用出站文件上;丢失的落档由
回调重试/出站重抓兜底。
Args:
source_code: 来源实例编码(出站单元行上的 source_code)。
now: 落档时间基准。
Returns:
True=落档成功或无事可做(无可用文件/无可用规则);False=落档失败
(已记日志;schema 类失败尽力把解析失败标记落库并独立提交,标记失败
仅告警不影响返回)。
"""
from flask import current_app
try:
outcome = sync_outbound_source_rows(source_code=source_code, now=now)
# [桥隔离] sync_outbound_source_rows 只 flush 不 commit;桥由回调事实
# 处理在归档 commit 之后独立调用,必须在此自行提交(B3 持久性教训)。
db.session.commit()
if outcome is not None:
current_app.logger.info(
"TRANSFER_OUTBOUND_EVIDENCE_SYNC source=%s inserted=%s updated=%s skipped=%s sealed=%s cross=%s",
source_code, outcome.inserted, outcome.updated,
outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged)
return True
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志
# [桥隔离] 落档崩溃绝不波及出站归档终态;丢失的落档由回调重试/重抓兜底。
current_app.logger.warning(
"TRANSFER_OUTBOUND_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
db.session.rollback()
# [解析失败分层] rollback 之后再写标记;仅 schema 类失败落库——通用异常
# (网络/DB 故障等)不是文件解析问题,不落标记。标记写入后独立 commit
# (落档数据已回滚,本次 commit 只持久化失败事实),仍返回 False。
# 标记写入是尽力而为:再抛异常也必须吞掉(B3 优先),丢失标记由下次重试补。
try:
code = getattr(exc, "code", None) or ""
if code in _SCHEMA_FAILURE_CODES or isinstance(exc, MovementFileSchemaError):
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
file_view = latest_usable_outbound_file(source_code, now=now)
if file_view is not None:
mark_outbound_parse_failure(
file_view.file_id,
error_code=str(code or _TRANSFER_FILE_SCHEMA_INVALID),
error_message=str(detail)[:2000],
)
db.session.commit()
except Exception as mark_exc: # noqa: BLE001 —— 桥隔离:标记失败仅日志
current_app.logger.warning(
"TRANSFER_OUTBOUND_PARSE_MARK_FAILED source=%s error=%s", source_code, mark_exc)
return False
@@ -0,0 +1,161 @@
"""
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;第二次调用该行已离开等待态,不再改(可重入)。
【STEP 4 出站证据同步 2026-10-16】success 事实把最新可用出站归档按
purpose=outbound 规则解析、record_kind='outbound' 落异动档(与入站
handle_inbound_report STEP 4 对称;桥内自吞异常并自行 commit)。
"""
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] success 事实触发出站证据同步
(outbound_evidence_sync,record_kind='outbound',与入站 STEP 4 对称);
[STEP 5] 精确定位本次回调收尾的执行单元并回写出站排程进度、归集终态。
【不捕获异常】任何一步失败原样外抛供 Worker 重试(STEP 4 桥内自吞)。
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] 出站证据同步:success 事实(ok 且 file_id 有值)后把该来源最新
# 可用出站归档按 purpose=outbound 规则解析、record_kind='outbound' 落异动档
# (与入站 handle_inbound_report STEP 4 对称:按 ok 触发、不依赖等待任务存在;
# 桥内自吞异常并自行 commit,本处不包 try——文件已提交,Worker 重试即可补齐)。
if fact.ok and fact.file_id is not None:
from app.services.in_transit_transfer.outbound_evidence_sync import (
sync_and_commit_for_outbound_callback,
)
sync_and_commit_for_outbound_callback(
source_code=fact.source_code, now=datetime.utcnow(),
)
# [STEP 5] 出站排程收口:按 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}
@@ -1,6 +1,6 @@
"""在途调拨严格数量门禁。
用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
用途:实现"异动数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
禁止部分调拨、数量容差与隐式截断。
依赖:标准库 decimal。
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
@@ -18,11 +18,11 @@ MATCH_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
class QuantityValidationError(ValueError):
"""收料数量非法(0、负数、非数字)。"""
"""入站数量非法(0、负数、非数字)。"""
def validate_receipt_quantity(value: Any) -> Decimal:
"""校验并归一化收料数量。
def validate_inbound_quantity(value: Any) -> Decimal:
"""校验并归一化入站数量。
Args:
value: 数字或数字字符串。
@@ -34,9 +34,9 @@ def validate_receipt_quantity(value: Any) -> Decimal:
try:
quantity = Decimal(str(value))
except (InvalidOperation, ValueError) as exc:
raise QuantityValidationError(f"invalid receipt quantity: {value!r}") from exc
raise QuantityValidationError(f"invalid inbound quantity: {value!r}") from exc
if quantity <= 0:
raise QuantityValidationError(f"receipt quantity must be positive: {value!r}")
raise QuantityValidationError(f"inbound quantity must be positive: {value!r}")
return quantity
@@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool:
return Decimal(str(left)) == Decimal(str(right))
def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str:
def classify_quantity_match(inbound_quantity: Any, external_quantity: Any | None) -> str:
"""按严格相等规则分类数量匹配结果。
Args:
receipt_quantity: 收料数量。
inbound_quantity: 入站异动数量。
external_quantity: 外部系统 账面库存;None 表示无库存。
Returns:
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
"""
if external_quantity is None:
return MATCH_INVENTORY_NOT_FOUND
if strict_quantities_equal(receipt_quantity, external_quantity):
if strict_quantities_equal(inbound_quantity, external_quantity):
return MATCH_EXECUTABLE
return MATCH_QUANTITY_MISMATCH
@@ -1,69 +0,0 @@
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
两函数同核推导,规则文本只存在一处。
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import ColumnElement, and_, not_, or_
from app.models import ShippingReceiptReportFile
from app.services.in_transit_transfer.date_policy import business_date_utc_window
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
"""新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。"""
window_start, window_end = business_date_utc_window(now)
return and_(
ShippingReceiptReportFile.created_at >= window_start,
ShippingReceiptReportFile.created_at < window_end,
or_(
ShippingReceiptReportFile.archive_expires_at.is_(None),
ShippingReceiptReportFile.archive_expires_at > now,
),
)
def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「当前可用的收料归档文件」SQL 条件。
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
+ 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
ShippingReceiptReportFile.archive_deleted_at.is_(None),
_fresh_and_retention_valid(now),
)
def expired_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。
Args:
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
可直接并入 .filter() 的单个 SQLAlchemy 条件。
"""
now = now or datetime.utcnow()
return and_(
ShippingReceiptReportFile.archive_deleted_at.is_(None),
not_(_fresh_and_retention_valid(now)),
)
@@ -1,22 +1,33 @@
"""在途调拨人工重试服务(基于冻结文件仅重新查询 外部系统)。
"""在途调拨人工重试服务(基于冻结快照仅重新查询 外部系统)。
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps、
scope_rules.parse_scope_rules、scope_rules.record_kinds_of。
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断;
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制);
重查前置兜底对齐(STEP 0,同 run_matching):两个批量重查入口先 align_scope_rows
补救落地同步失败/迟到的证据,再圈行重查(待处理池后门不得基于过期证据作答);
【2026-10-14 对档对账(ADR 0001/规格 §9)】requery_items(匹配号入口)前置
「对档重圈 → 与本匹配自有 items 对账」:档新增记录 → 补建 item(绑同一
匹配);档证据变 → 刷新 item 证据并重置待查;档记录消失 → item 失效隔离
(沿用 blocked_file_removed 语义退出主视图)。圈档复用匹配创建的同一函数
(_circle_ledger_records:固定条件单点实现;记录类型取
record_kinds_of(快照 scope_rules))+ 同一快照规则(scope_json),
D17 占用互斥排除「其他匹配」的有效占用(本匹配自有 items 不构成占用);
终态行(已执行/人工关闭/取消/在流)绝不触碰——已执行行不得被证据刷新
复活(防同批档证据更新促成二次写 ERP)。
原 align_scope_rows 文件兜底对齐已随出生翻转退役(重查不再对文件对账);
库存查询按组织批量(2026-09-29):全部重查/恢复/单据重试入口统一经
_recheck_items_batch——路由解析按 external_org 分组,一组一次
capabilities.query_stock(与执行链写前复查同形态),行级评估 / Attempt /
审计 / 新鲜度续期保持单行粒度;N 行重查 = 每组织 1 次外部调用,
禁止回退逐行单查(N 行 N 次调用会打崩外部系统);
file_removed 失效行不可重查:匹配号圈行路径由 scope 谓词排除,按 id 直取与
路由解析叠加类型仓库定义(resolve_warehouse:fixed 覆盖映射档);
file_removed 失效行不可重查:匹配号圈行路径由对账口径排除,按 id 直取与
单行入口由资格门禁 _gate_retryable_item 兜底拒绝(拒绝逻辑单点闭环,消失
证据不可用旧库存翻回可执行);
交易单位唯一来源=ERP 库存行 stock_unit(img09):重查命中且数量一致但 ERP
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替)。
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替);
批号查询目标经行所属匹配快照的转换规则派生(item_external_lot_no)。
"""
from __future__ import annotations
@@ -34,20 +45,26 @@ from app.models import TransferAttempt, TransferInvoiceItem
from app.services.in_transit_transfer import status as status_machine
from app.services.in_transit_transfer.audit import build_transfer_audit_event
from app.services.in_transit_transfer.capability_client import StockTarget
from app.services.in_transit_transfer.date_policy import business_date_now
from app.services.in_transit_transfer.evidence_sync import align_scope_rows
from app.services.in_transit_transfer.matching_service import (
RESULT_EXTERNAL_QUERY_FAILED,
RESULT_EXECUTABLE,
RESULT_FILE_REMOVED,
RESULT_MISSING_UNIT,
RESULT_ROUTE_NOT_RESOLVED,
RouteMapping,
TransferDeps,
scope_item_query,
_born_item_from_record,
_circle_ledger_records,
_dedupe_ledger_records_for_item_birth,
_item_grain_of_ledger,
_resolve_route_with_config,
_SYNC_TERMINAL_STATUSES,
item_external_lot_no,
)
from app.services.in_transit_transfer.movement_contract import external_lot_no
from app.services.in_transit_transfer.quantity import classify_quantity_match
from app.services.in_transit_transfer.scope_rules import parse_scope_rules, record_kinds_of
from app.services.in_transit_transfer.serializers import DOCUMENT_STATUS_GROUPS
from app.services.in_transit_transfer.transfer_type import resolve_transfer_type
RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
@@ -62,6 +79,38 @@ _RETRYABLE_STATUSES = {
logger = logging.getLogger(__name__)
def _route_for_item(deps: TransferDeps, item: TransferInvoiceItem) -> RouteMapping:
"""行级路由解析:映射档解析 + 行所属匹配类型的仓库定义(mapped/fixed)叠加。
Args:
deps: 注入依赖(route_resolver=映射档解析)。
item: 重查行(matching_id 关联的匹配快照携带 transfer_type)。
Returns:
RouteMapping(fixed 角色按类型配置覆盖仓库/法人;无匹配或快照无类型码
时透传映射档——存量兼容兜底)。
Raises:
RouteNotResolvedError / ValidationError: 映射档不可解析或类型配置脏数据
(fail-closed,调用方按行级前置解析失败隔离)。
"""
config = None
if item.matching_id is not None and item.matching is not None:
scope = item.matching.scope_json if isinstance(item.matching.scope_json, dict) else {}
type_code = scope.get("transfer_type")
if type_code:
# 存量重跑/重查不要求类型仍启用(「停用后存量不受影响」)。
config = resolve_transfer_type(type_code, require_enabled=False)
if config is None:
return deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.movement_warehouse_code or "",
)
return _resolve_route_with_config(
deps, config,
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.movement_warehouse_code or "",
)
def _gate_retryable_item(item_id: int) -> TransferInvoiceItem:
"""单行重查资格门禁(单行与按 id 批量入口共用的拒绝单点)。
@@ -72,7 +121,7 @@ def _gate_retryable_item(item_id: int) -> TransferInvoiceItem:
Raises:
NotFoundError: item 不存在。
ValidationError: result_unknown 只读 / 状态不可重试 / file_removed 行
不可重查(消失证据不可恢复:证据行的源单已从最新收料文件中消失,
不可重查(消失证据不可恢复:证据行的源单已从最新入站文件中消失,
重查只会用外部系统旧库存把行翻回可执行,唯一出口=人工关闭 /
等重新同步恢复该行)。
"""
@@ -139,7 +188,7 @@ def _degrade_recheck_row(item: TransferInvoiceItem, *, attempt: TransferAttempt,
def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttempt,
before_status: str, receipt_qty: Decimal, stock_row,
before_status: str, inbound_qty: Decimal, stock_row,
operation_id: str, request_id: str | None) -> str:
"""行级评估收口:账面对照落状态/结果码/外部数量/单位,关闭 Attempt 并写审计。
@@ -147,14 +196,14 @@ def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttemp
item: 重查行(Attempt 已创建并 flush)。
attempt: 该行本次 external_query Attempt(running 态)。
before_status: 重查前状态(审计 before)。
receipt_qty: 行收料数量(严格相等判定的基准)。
inbound_qty: 行异动数量(严格相等判定的基准)。
stock_row: 批量查询结果中该行的账面行(StockRow);查无记录为 None。
operation_id / request_id: 审计上下文(查询 operation_id 组内共享)。
Returns:
重查后的行状态。
"""
stock_qty = stock_row.quantity if stock_row is not None else None
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
if stock_qty is None or classify_quantity_match(inbound_qty, stock_qty) != RESULT_EXECUTABLE:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
item.result_message = "external inventory not found" if stock_qty is None else "strict quantity mismatch"
@@ -232,19 +281,17 @@ def _recheck_items_batch(
行未被触碰、未建 Attempt;批量入口转为该行 ok=False,单行入口原样上抛
保持历史 fail-closed 行为)。
"""
# [STEP 1] 行级前置解析(行级隔离):路由解析 + 收料数量解析,失败行原位
# 跳过、不拖垮整批;行仓库字段刷新为本次解析值——查询与后续执行写路径必须
# 用同一仓库值:行上旧值可能来自更早配置(路由已漂移),也可能为空(如
# blocked_missing_unit 行在路由解析前被阻断)。
# [STEP 1] 行级前置解析(行级隔离):路由解析(叠加行所属匹配类型的仓库
# 定义,fixed 覆盖映射档)+ 异动数量解析,失败行原位跳过、不拖垮整批;行仓库
# 字段刷新为本次解析值——查询与后续执行写路径必须用同一仓库值:行上旧值可能
# 来自更早配置(路由已漂移),也可能为空(如 blocked_missing_unit 行在路由
# 解析前被阻断)。
resolved: list[tuple[TransferInvoiceItem, RouteMapping, Decimal]] = []
row_errors: dict[int, Exception] = {}
for item in items:
try:
route = deps.route_resolver.resolve(
source_code=item.source_code, invoice_no=item.invoice_no,
warehouse_code=item.receipt_warehouse_code or "",
)
receipt_qty = Decimal(item.receipt_quantity)
route = _route_for_item(deps, item)
inbound_qty = Decimal(item.movement_quantity)
except Exception as exc: # noqa: BLE001 —— 行级隔离:路由漂移/缺失/脏数量只影响该行
row_errors[item.id] = exc
logger.warning(
@@ -255,7 +302,7 @@ def _recheck_items_batch(
if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse:
item.from_warehouse = route.from_warehouse
item.to_warehouse = route.to_warehouse
resolved.append((item, route, receipt_qty))
resolved.append((item, route, inbound_qty))
# [STEP 2] 按组织分组(同写前复查的 external_org 分组口径):同组行共享
# 一次批量查询,N 行 = 每组织 1 次外部调用。
@@ -271,7 +318,7 @@ def _recheck_items_batch(
operation_id = f"op-{uuid.uuid4().hex[:12]}"
attempts: dict[int, TransferAttempt] = {}
before_statuses: dict[int, str] = {}
for item, route, receipt_qty in entries:
for item, route, inbound_qty in entries:
item.attempt_no += 1
before_statuses[item.id] = item.status
attempts[item.id] = TransferAttempt(
@@ -280,19 +327,20 @@ def _recheck_items_batch(
request_snapshot_json={
"invoice_no": item.invoice_no, "external_org": external_org,
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
"quantity": str(receipt_qty),
"quantity": str(inbound_qty),
},
)
db.session.add(attempts[item.id])
db.session.flush()
try:
# [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。
# [外部形态] 查询目标与回查同用行所属匹配快照转换规则派生批号
# (item_external_lot_no;行落库保持档原形)。
stock = deps.capabilities.query_stock(
operation_id=operation_id, external_org=external_org,
targets=[StockTarget(
material_no=item.material_no, warehouse_code=route.from_warehouse,
lot_no=external_lot_no(item.lot_no),
) for item, route, _receipt_qty in entries],
lot_no=item_external_lot_no(item),
) for item, route, _inbound_qty in entries],
)
except Exception as exc: # noqa: BLE001
# [降级] 外部系统网关/绑定故障是组级事实:组内各行统一降级为
@@ -303,22 +351,22 @@ def _recheck_items_batch(
"transfer recheck org query failed (degrade rows): org=%s rows=%s error=%s",
external_org, len(entries), detail,
)
for item, route, receipt_qty in entries:
for item, route, inbound_qty in entries:
statuses[item.id] = _degrade_recheck_row(
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
detail=detail, operation_id=operation_id, request_id=request_id,
)
db.session.commit()
continue
for item, route, receipt_qty in entries:
for item, route, inbound_qty in entries:
# [外部形态] 回查键与查询目标同用派生批号(三元组精确匹配)。
stock_row = stock.lookup_row(
material_no=item.material_no, warehouse_code=route.from_warehouse,
lot_no=external_lot_no(item.lot_no),
lot_no=item_external_lot_no(item),
)
statuses[item.id] = _apply_recheck_outcome(
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
receipt_qty=receipt_qty, stock_row=stock_row,
inbound_qty=inbound_qty, stock_row=stock_row,
operation_id=operation_id, request_id=request_id,
)
db.session.commit()
@@ -380,18 +428,6 @@ def requery_items_by_ids(
ids = [int(x) for x in (item_ids or []) if x is not None]
if not ids:
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
# [口径] 受影响来源=按 id 查回行的 source_code 去重(先查行→对齐→再重查)。
source_rows = (
db.session.query(TransferInvoiceItem.source_code)
.filter(TransferInvoiceItem.id.in_(ids))
.all()
)
affected_sources = sorted({(code or "").strip() for (code,) in source_rows})
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于任何
# 重查读取执行,否则待处理池后门会基于过期证据放行旧库存。
align_scope_rows(source_codes=affected_sources, deps=deps,
business_date=str(business_date_now()), now=datetime.utcnow())
results_by_id: dict[int, dict] = {}
eligible: list[TransferInvoiceItem] = []
for item_id in ids:
@@ -411,19 +447,179 @@ def requery_items_by_ids(
return {"total": len(ids), "results": [results_by_id[item_id] for item_id in ids]}
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行,按组织批量查询并刷新。
def _reconcile_items_with_ledger(
matching, *, deps: TransferDeps, wanted_doc_nos: list[str] | None,
) -> None:
"""对档重圈并与本匹配自有 items 对账(出生翻转后重查的前置步骤,规格 §9)。
圈行口径与匹配卡实时视图同源(scope_item_query:来源+收料日期区间+调拨类型),
行归属 matching_id 不参与——行归属解耦后行不随匹配迁移,视图能看到的历史行
(matching_id 指向旧匹配)必须同样可被本次匹配的重查触达,否则出现「卡片提示
重查、重查却查不到行」的死锁(2026-09-24 修复)。
核心逻辑:[STEP 1] 按匹配快照规则(scope_rules + 来源 + 异动日期范围)圈定
档记录——复用匹配创建的同一圈档函数 _circle_ledger_records(固定条件单点
实现,杜绝谓词漂移)。记录类型取 record_kinds_of(已解析的快照 rules)
(仅没有范围规则、也没有类型对象的调用点才显式只圈 inbound)。
排除已执行封存、其他匹配的有效占用(D17;本匹配自有
items 不构成占用)。[STEP 2] 三分类对账(**终态守卫:SUCCESS/DUPLICATE_
SUCCESS/MANUALLY_CLOSED/CANCELLED/EXECUTING/RESULT_UNKNOWN 行绝不触碰——
已执行行不得被证据刷新复活,否则同批档证据更新会促成二次写 ERP**):
①档有行无(自有 items 未覆盖的圈中记录)→ 补建 item(绑同一匹配;
类型配置缺失/路由不可解析时行级落 blocked(可解释、可重查),不影响
其余行——口径与 _route_for_item 的逐行兜底对齐);
②档证据变(数量/批号/仓库与 item 不一致)→ 刷新 item 证据并重置待查
(旧库存是对旧数量查的,作废),展示字段照常刷新(仅非终态行);
③自有 item 的档记录消失(防御:档缺席不删,仅异常清理场景)→ 失效隔离
(blocked_file_removed,退出主视图,恢复走人工恢复;仅非终态行)。
只 flush 不 commit(随调用方事务:requery_items 末尾 _recheck_items_batch
的组粒度提交兜底持久化)。
Args:
matching_no: 匹配编号(经 scope_json 圈定行集)。
matching: 匹配 ORM 行(scope_json 快照 + 自有 items)。
deps: 注入依赖(路由解析)。
wanted_doc_nos: 可选单号过滤(invoice_nos 限定重查范围时同步约束补圈)。
"""
from app.core.errors import ValidationError as _ValidationError
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
from app.services.in_transit_transfer.transfer_type_config_service import (
get_by_code as get_type_config,
)
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
rules = parse_scope_rules(scope.get("scope_rules"))
now = datetime.utcnow()
# [STEP 1] 快照规则圈档(共享圈档函数:与匹配创建同一固定条件实现)。
sources = [str(code) for code in (scope.get("source_codes") or [])]
records: list = []
if sources:
records = _dedupe_ledger_records_for_item_birth(
_circle_ledger_records(
source_codes=sources,
rules=rules,
movement_date_from=scope.get("movement_date_from"),
movement_date_to=scope.get("movement_date_to"),
record_kinds=record_kinds_of(rules),
exclude_occupied_by_matching_id=matching.id,
doc_nos=wanted_doc_nos,
)
)
# 类型配置(仓库定义):从快照类型码读现行配置(存量不要求启用)。
# [逐行容错] 类型缺失/脏配置不炸整次重查:config=None 时补建行走行级阻断
# (口径与 _route_for_item 的逐行兜底对齐;类型只有停用没有删除,正常不触发)。
type_code = str(scope.get("transfer_type") or "")
config = None
if type_code:
try:
config = get_type_config(type_code)
except _ValidationError:
config = None
# [终态守卫·占用面] own_by_record 收全部自有行(含终态):档记录已被本匹配
# 任一行(含已执行行)绑定时按「档有行有」处理——终态绑定永不补建第二个 item
#(否则已执行记录将以新待查行复活 → 二次写 ERP)。同 grain 兄弟档亦视为已绑。
own_by_record = {
item.ledger_record_id: item
for item in matching.items
if item.ledger_record_id is not None
}
own_grains = {
(str(item.source_code or ""), str(item.invoice_no or ""),
str(item.material_no or ""), str(item.movement_date or ""))
for item in matching.items
}
for record in records:
item = own_by_record.get(record.id)
if item is None:
grain = _item_grain_of_ledger(record)
if grain in own_grains:
# 同 grain 已有自有 item(兄弟档 / 择优后的另一 ledger_record_id)。
continue
# [①补建] 档新增记录:绑同一匹配(D17:本匹配占用即成立)。
route = None
route_failed = False
try:
if config is None:
raise _ValidationError(f"transfer type config missing: {type_code}")
route = _resolve_route_with_config(
deps, config,
source_code=record.source_code, invoice_no=record.doc_no,
warehouse_code=record.warehouse_code or "",
)
except Exception: # noqa: BLE001 —— 类型缺失/路由失败:行级阻断降级,不影响其余行
route = None
route_failed = True
born = _born_item_from_record(
record, matching_id=matching.id,
route=route, now=now,
)
if route_failed:
# [行级阻断] 可解释、可重查(配置/路由修复后重查即恢复)。
born.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
born.result_code = RESULT_ROUTE_NOT_RESOLVED
born.result_message = (
f"transfer type config missing: {type_code}" if config is None
else f"route not resolved for source {record.source_code}"
)
db.session.add(born)
own_grains.add(grain)
continue
# [②证据对账] 只比对异动事实(数量/批号/仓库);名称/规格为展示字段。
# [终态守卫·刷新面] 终态行(已执行/人工关闭/取消/在流)绝不触碰(含
# updated_at)——旧 evidence_sync「终态行绝不触碰/不复活」冻结约束在
# 翻转后的延续(防同批档证据更新促成二次写 ERP);非终态行照常对账。
if item.status in _SYNC_TERMINAL_STATUSES:
continue
evidence_changed = (
str(item.movement_quantity) != str(record.quantity or "")
or (item.lot_no or "") != (record.lot_no or "")
or (item.movement_warehouse_code or "") != (record.warehouse_code or "")
)
item.material_name = record.material_name or ""
item.specification = record.specification or ""
if evidence_changed:
item.movement_quantity = str(record.quantity or "0")
item.lot_no = record.lot_no or ""
item.movement_warehouse_code = record.warehouse_code or ""
# 重置待查:旧库存是对旧数量查的,作废;取数时刻同步置空。
item.status = status_machine.TransferStatus.MATCHING.value
item.result_code = SYNC_RESULT_PENDING
item.result_message = None
item.external_quantity = None
item.inventory_checked_at = None
item.updated_at = now
# [③失效隔离] 自有 item 的档记录不存在(档缺席不删,正常不触发;防御
# 异常清理)→ 沿用 blocked_file_removed 语义退出主视图(仅非终态行;
# 终态行的既定事实永不改写)。
from app.models import TransferMovementLedger as _Ledger
record_ids = {record.id for record in records}
for item in matching.items:
if item.status in _SYNC_TERMINAL_STATUSES:
continue
if item.ledger_record_id is None or item.ledger_record_id in record_ids:
continue
if db.session.get(_Ledger, item.ledger_record_id) is None:
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
item.result_code = RESULT_FILE_REMOVED
item.result_message = "ledger record removed"
item.updated_at = now
db.session.flush()
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
actor_id: int | None = None, request_id: str | None = None) -> dict:
"""批量重查 外部系统 库存:先对档对账(补建/刷新/隔离),再圈自有可重查行批量刷新。
【2026-10-14 对档对账(规格 §9)】原 scope_item_query 实时圈行退役——行由
匹配创建时从档圈定且创建即绑定,重查改为:按匹配快照规则对档重圈 → 与本
匹配自有 items 对账(档新增记录补建 / 档证据变刷新重置 / 档记录消失隔离)→
自有可重查行按组织批量重查。重查只对账本匹配自己的 items,不受 D17 圈档
互斥影响(自有占用不排除)。
Args:
matching_no: 匹配编号(scope_json 快照供圈档规则/类型码)。
deps: 注入依赖(capabilities = 外部系统网关客户端)。
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该 scope 全部可重查行。
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该匹配全部可重查行
(对账补圈同受此约束,避免范围外补建)。
actor_id / request_id: 审计上下文。
Returns:
{"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
@@ -434,21 +630,16 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
matching = TransferMatching.query.filter_by(matching_no=matching_no).first()
if matching is None:
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
# [口径一致] 受影响来源=scope_json 的 source_codes(与 scope_item_query 圈行同源,
# 提取口径同 matching_service.scope_item_query:非 dict 视为空 scope)。
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
affected_sources = sorted({str(code) for code in (scope.get("source_codes") or [])})
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于 scope
# 圈行执行,否则重查会圈到过期行、基于过期证据放行旧库存。
align_scope_rows(source_codes=affected_sources, deps=deps,
business_date=str(business_date_now()), now=datetime.utcnow())
# [口径统一] 圈行必须与匹配卡视图同谓词(scope:来源+日期区间+类型前缀)——
# 行归属解耦后 matching_id 停留在首次创建值,按它圈行会漏掉全部存量行。
# file_removed 行排除:消失证据不可重查恢复(唯一出口=人工关闭/出清)。
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
# [STEP A] 对档对账(补建/刷新/隔离,只 flush;持久化随后续组粒度提交)。
_reconcile_items_with_ledger(matching, deps=deps, wanted_doc_nos=wanted or None)
# [STEP B] 自有可重查行(阻断/可执行)批量重查;file_removed 隔离行排除
# (消失证据不可重查恢复,唯一出口=人工关闭/等对档修复)。
query = (
scope_item_query(matching)
.filter(
TransferInvoiceItem.query.filter(
TransferInvoiceItem.matching_id == matching.id,
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
or_(
TransferInvoiceItem.result_code.is_(None),
@@ -456,7 +647,6 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
),
)
)
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
if wanted:
query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted))
items = query.order_by(TransferInvoiceItem.id).all()
@@ -0,0 +1,149 @@
"""
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、models。
逻辑:由 app.create_app 调用 register_inbound_sinks / register_outbound_sinks(幂等)。
batch-ready:归档单元终态后立即尝试排程 finalize(文件返回= RPA/排程结束),
再投递事实;事实处理(证据同步等)失败不得挡排程收口。不 import shipping_notice。
"""
from __future__ import annotations
import logging
from typing import Any, Callable
_LOG = logging.getLogger(__name__)
_INBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'})
_OUTBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'})
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 _try_finalize_inbound_schedule_after_unit(payload: dict[str, Any]) -> None:
"""单元已落终态后按文件返回收口入站排程;解析/证据失败不得阻塞。
核心逻辑:用 callback_id 定位单元;仅当 status 已终态且挂了 schedule_run_id
时 refresh + finalize_if_complete(幂等)。异常只记日志,不回滚已提交单元。
"""
callback_id = str(payload.get('callback_id') or '').strip()
if not callback_id:
return
try:
from app.models import FreightRpaInboundUnitRun
from app.services.schedule.freight_rpa_inbound_finalize import (
finalize_inbound_schedule_run_if_complete,
refresh_inbound_schedule_run_progress,
)
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None or unit.schedule_run_id is None:
return
if str(unit.status or '') not in _INBOUND_UNIT_TERMINAL:
return
refresh_inbound_schedule_run_progress(int(unit.schedule_run_id))
finalize_inbound_schedule_run_if_complete(int(unit.schedule_run_id))
except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果
_LOG.warning(
'inbound schedule finalize after unit terminal failed callback_id=%s: %s',
callback_id,
exc,
exc_info=True,
)
def _try_finalize_outbound_schedule_after_unit(payload: dict[str, Any]) -> None:
"""单元已落终态后按文件返回收口出站排程;解析/证据失败不得阻塞。"""
callback_id = str(payload.get('callback_id') or '').strip()
if not callback_id:
return
try:
from app.models import FreightRpaOutboundUnitRun
from app.services.schedule.freight_rpa_outbound_finalize import (
finalize_outbound_schedule_run_if_complete,
refresh_outbound_schedule_run_progress,
)
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None or unit.schedule_run_id is None:
return
if str(unit.status or '') not in _OUTBOUND_UNIT_TERMINAL:
return
refresh_outbound_schedule_run_progress(int(unit.schedule_run_id))
finalize_outbound_schedule_run_if_complete(int(unit.schedule_run_id))
except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果
_LOG.warning(
'outbound schedule finalize after unit terminal failed callback_id=%s: %s',
callback_id,
exc,
exc_info=True,
)
def _inbound_batch_ready_sink(**payload: Any) -> dict[str, Any]:
"""入站 batch-ready:归档 →(单元终态后)排程收口 → 返回;事实投递异常仍尽量收口排程。"""
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
try:
data = ingest_inbound_callback(payload)
return {'success': True, 'data': data}
finally:
# 单元终态已 commit 后,无论事实处理是否抛错,都按文件返回尝试排程 finalize。
_try_finalize_inbound_schedule_after_unit(payload)
def _outbound_batch_ready_sink(**payload: Any) -> dict[str, Any]:
"""出站 batch-ready:归档 →(单元终态后)排程收口 → 返回。"""
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
try:
data = ingest_outbound_callback(payload)
return {'success': True, 'data': data}
finally:
_try_finalize_outbound_schedule_after_unit(payload)
def register_inbound_sinks() -> None:
"""注册全部 inbound 进度 sink 与 inbound 事实处理函数(幂等)。
核心逻辑:inbound-batch-ready 走归档+文件返回即排程 finalize;unit/batch-progress 挂
schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report(证据/
调拨推进;排程收口已在 batch-ready 侧完成,handler 内 finalize 仍幂等兜底)。
"""
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
register_sink('inbound-batch-ready', _inbound_batch_ready_sink)
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 走归档+文件返回即排程 finalize;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.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', _outbound_batch_ready_sink)
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)
@@ -0,0 +1,127 @@
"""services/in_transit_transfer/scope_rules.py
用途:调拨类型范围规则引擎——受控字段白名单上的「字段+匹配方式+值列表」规则,
规则间 AND、规则内多值 OR;内存谓词与 SQL 编译双形态共用同一解析结果,
供匹配创建圈档、重查对账、管理页校验三处单一口径。
依赖:app.core.errors.ValidationError;SQLAlchemy Select(编译形态)。
逻辑:parse 校验词表/匹配方式/值非空 → ScopeRule 元组;evaluate 逐规则 AND、
逐值 OR(prefix/contains 大小写不敏感);apply_scope_filters 生成等价 SQL;
record_kinds_of 从 record_kind 范围规则推导证据流(入站/出站)。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Mapping, Sequence
from sqlalchemy import Select, and_, or_, func
from app.core.errors import ValidationError
# 受控字段词表(封闭可扩展;新增字段须同步管理页下拉与 technical.md)。
SCOPE_FIELDS: frozenset[str] = frozenset({
"source_code", "doc_no", "warehouse_code", "storage_code", "lot_no",
"movement_date", "record_kind", "in_out_flag", "order_type", "odm_id",
"odm_name", "carton_id", "pallet_id", "material_code", "doc_nature",
"movement_type", "reason_code", "partner_code",
})
_MATCHES = ("prefix", "equals", "contains", "in")
_RECORD_KINDS = ("inbound", "outbound")
@dataclass(frozen=True)
class ScopeRule:
"""单条范围规则:field 字段 / match 匹配方式 / values 值列表(规则内 OR)。"""
field: str
match: str
values: tuple[str, ...]
def parse_scope_rules(raw: list[dict] | None) -> tuple[ScopeRule, ...]:
"""校验并解析范围规则 JSON(管理页保存与匹配快照共用)。
Args:
raw: [{"field", "match", "values"}];空列表/None 合法(=不限,由调用方决定是否放行)。
Returns:
ScopeRule 元组。
Raises:
ValidationError: 字段不在 SCOPE_FIELDS、match 非法、values 空/非字符串。
"""
rules: list[ScopeRule] = []
for item in raw or []:
field, match = str(item.get("field", "")), str(item.get("match", ""))
values = item.get("values") or []
if field not in SCOPE_FIELDS:
raise ValidationError(f"unknown scope field: {field}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field})
if match not in _MATCHES or not values or not all(isinstance(v, str) and v.strip() for v in values):
raise ValidationError(f"invalid scope rule: {field}/{match}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field, "match": match})
rules.append(ScopeRule(field=field, match=match, values=tuple(v.strip() for v in values)))
return tuple(rules)
def _hit(value: str | None, rule: ScopeRule) -> bool:
text = str(value or "").strip().upper()
if not text:
return False
if rule.match == "prefix":
return text.startswith(tuple(v.upper() for v in rule.values))
if rule.match == "equals":
return text in {v.upper() for v in rule.values}
if rule.match == "contains":
return any(v.upper() in text for v in rule.values)
return text in {v.upper() for v in rule.values} # in
def record_kinds_of(rules: tuple[ScopeRule, ...]) -> tuple[str, ...]:
"""从范围规则推导调拨类型需要的证据流(入站/出站)。
核心逻辑:筛 field=record_kind 的规则;无则默认双轨。多条规则时,各规则
允许的 inbound/outbound 集合(与 evaluate 同口径 _hit)逐条取交集;结果按
inbound→outbound 顺序输出,交集为空则返回空元组。
Args:
rules: parse_scope_rules 产出的 ScopeRule 元组。
Returns:
仅含 inbound/outbound 的去重元组。
"""
kind_rules = [rule for rule in rules if rule.field == "record_kind"]
if not kind_rules:
return _RECORD_KINDS
allowed: set[str] | None = None
for rule in kind_rules:
rule_allowed = {kind for kind in _RECORD_KINDS if _hit(kind, rule)}
allowed = rule_allowed if allowed is None else allowed & rule_allowed
if not allowed:
return ()
return tuple(kind for kind in _RECORD_KINDS if kind in allowed)
def evaluate_scope(record: Mapping[str, Any], rules: Sequence[ScopeRule]) -> bool:
"""内存求值:规则间 AND、规则内多值 OR(匹配/测试/小数据场景)。"""
return all(_hit(record.get(rule.field), rule) for rule in rules)
def apply_scope_filters(query: Select, model: type, rules: Sequence[ScopeRule]) -> Select:
"""SQL 编译(与 evaluate_scope 同口径):圈档与重查对账共用,防谓词漂移。"""
clauses = []
for rule in rules:
col = getattr(model, rule.field)
upper = func.upper(col)
if rule.match == "prefix":
clauses.append(or_(*(upper.like(f"{v.upper()}%") for v in rule.values)))
elif rule.match == "equals":
clauses.append(upper.in_([v.upper() for v in rule.values]))
elif rule.match == "contains":
clauses.append(or_(*(upper.contains(v.upper()) for v in rule.values)))
else:
clauses.append(upper.in_([v.upper() for v in rule.values]))
return query.filter(and_(*clauses)) if clauses else query
def scope_rules_note(rules: Sequence[ScopeRule]) -> str:
"""范围规则审计说明(写 scope_json 旁路人读字段)。"""
parts = []
for rule in rules:
parts.append(f"{rule.field} {rule.match} {'|'.join(rule.values)}")
return " AND ".join(parts)
@@ -12,7 +12,7 @@ from __future__ import annotations
from typing import Any
from app.services.in_transit_transfer.movement_contract import external_lot_no
from app.services.in_transit_transfer.matching_service import item_external_lot_no
# ---------------------------------------------------------------------------
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
@@ -41,11 +41,9 @@ def serialize_summary(summary) -> dict[str, Any]:
"matching_id": summary.matching_id,
"status": summary.status,
"business_date": summary.business_date,
"eligible_receipt_date_to": summary.eligible_receipt_date_to,
"expires_at": summary.expires_at,
"counts": {
"file_invoice_count": summary.counts.file_invoice_count,
"not_matured_count": summary.counts.not_matured_count,
"matched_count": summary.counts.matched_count,
"executable_count": summary.counts.executable_count,
"blocked_count": summary.counts.blocked_count,
@@ -74,7 +72,7 @@ def serialize_item(item) -> dict[str, Any]:
"specification": item.specification,
"invoice_no": item.invoice_no,
"lot_no": item.lot_no,
"receipt_date": item.receipt_date,
"movement_date": item.movement_date,
"from_warehouse": item.from_warehouse,
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
"to_warehouse": item.to_warehouse,
@@ -94,6 +92,8 @@ def serialize_item(item) -> dict[str, Any]:
"checked_at": item.checked_at,
"stale": item.stale,
"file_current": item.file_current,
# 出生匹配的调拨类型 code。可调拨明细跨类型混排时前端据此显示类别名称。
"transfer_type": item.transfer_type,
}
@@ -137,7 +137,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
items: 单挂接行集(TransferInvoiceItem 列表,调用方保证顺序)。
Returns:
单投影 dict(8 键):{doc_no, receipt_date, from_warehouse, to_warehouse,
单投影 dict(8 键):{doc_no, movement_date, from_warehouse, to_warehouse,
status, erp_document_no, error_message, lines}。
"""
# 延迟引用 execution_service 的行聚合(模块级互相引用会循环导入;
@@ -149,11 +149,11 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
name_by_key: dict[tuple[str, str, str, str], str] = {}
reason_by_key: dict[tuple[str, str, str, str], str] = {}
for item in ordered:
# [外部形态] join 键与 _build_order_lines 聚合键同形(批号 WTP→HOW 派生),
# 否则 WTP 前缀行的品名/原因投影 lookup 会 miss。
# [外部形态] join 键与 _build_order_lines 聚合键同形(批号经行所属匹配
# 快照转换规则派生),否则 WTP 前缀行的品名/原因投影 lookup 会 miss。
key = (
str(item.material_no or "").strip(),
external_lot_no(item.lot_no),
item_external_lot_no(item),
str(item.from_warehouse or "").strip(),
str(item.to_warehouse or "").strip(),
)
@@ -166,7 +166,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
reason_by_key[key] = message
return {
"doc_no": doc.doc_no,
"receipt_date": doc.receipt_date,
"movement_date": doc.movement_date,
"from_warehouse": doc.from_warehouse,
"to_warehouse": doc.to_warehouse,
"status": doc.status,
@@ -174,7 +174,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
"error_message": doc.error_message,
"lines": [
{
# 行级溯源收料通知号(2026-09-29 契约扩充,随 ERP 写入行同款口径
# 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
"invoice_no": line["invoice_no"],
"material_no": line["material_no"],
@@ -212,7 +212,7 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
"submit_timestamp": doc.submit_timestamp,
"status": base["status"],
"status_group": order_status_group(doc.status),
"receipt_date": base["receipt_date"],
"movement_date": base["movement_date"],
"from_warehouse": base["from_warehouse"],
"to_warehouse": base["to_warehouse"],
"erp_document_no": base["erp_document_no"],
@@ -227,10 +227,10 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
# deriveBatchNo 镜像转换(与匹配卡/可调拨明细/待办池同规则)。
"lot_no": item.lot_no or "",
"quantity": item.receipt_quantity,
"quantity": item.movement_quantity,
"unit": item.unit or "",
}
# 行序对齐统一规则第三键(2026-09-29):同单内收料日期/数据源恒同
# 行序对齐统一规则第三键(2026-09-29):同单内异动日期/数据源恒同
# (组键含两者),按 invoice_no 升序、id 兜底稳定排序。
for item in sorted(items, key=lambda row: (str(row.invoice_no or ""), row.id))
],
@@ -1,161 +1,551 @@
"""在途调拨来源收料文件状态投影服务。
"""在途调拨来源证据文件状态投影服务。
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 /
无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
receipt_file_gate(可用/失效判定单一事实来源)。
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
见 receipt_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→
parse_failed(不可当 ready,仍带 file_no/file_sha256 便于诊断);
有进行中单元 → fetching;最新单元为失败终态 → failed;
文件仍在但已失效 → expired;否则 → none。
record_receipt_parse_failure / clear_receipt_parse_failure 维护解析失败三列
(写入与清除均只 flush 不 commit,事务归属调用方)。
用途:只读货代入站/出站链路已有事实(执行单元行 + freight_rpa 归档文件),
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
调拨不维护独立抓取状态表(低耦合)。
依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 /
get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、
出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与
入站可用条件同口径)。
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
最新单元失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
出站先查 get_outbound_config,缺失 → unconfigured;有配置则对出站文件表与
FreightRpaOutboundUnitRun 走同一顺序。列表接口走
resolve_source_file_statuses:同一顺序一次性投影全部来源,查询次数不随
来源个数增长。record/clear_inbound_parse_failure 仍是入站解析失败标记的
兼容薄壳(按主键委托 queries.mark/clear,只 flush 不 commit,事务归属调用方)。
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Callable
from app import db
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.services.in_transit_transfer.receipt_file_gate import (
expired_receipt_file_condition,
usable_receipt_file_condition,
from sqlalchemy import and_, not_, or_
from app.core.errors import ValidationError
from app.models.freight_rpa_inbound_report import (
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
)
from app.models.freight_rpa_outbound_report import (
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
)
from app.services.freight_rpa.reports.queries import (
clear_inbound_parse_failure as _clear_parse_failure_by_id,
expired_inbound_file_condition,
get_outbound_config,
has_expired_inbound_file,
latest_usable_inbound_file,
mark_inbound_parse_failure as _mark_parse_failure_by_id,
usable_inbound_file_condition,
)
from app.services.in_transit_transfer.date_policy import business_date_utc_window
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
FAILED_UNIT_STATUSES = ('failed', 'cancelled')
# 空数据(no_receipt_data):抓取成功但当日无收料记录,属业务结果而非故障,
# 独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
# 空数据(RPA empty 回调契约值,shipping_notice 域术语保留):抓取成功但当日无记录,
# 属业务结果而非故障,独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
NO_DATA_UNIT_STATUSES = ('empty',)
_RECORD_KINDS = ('inbound', 'outbound')
def resolve_source_file_status(*, source_code: str) -> dict:
"""返回某来源的收料文件状态投影。
@dataclass(frozen=True)
class _FileFact:
"""批量投影用的文件身份,字段与单来源文件视图中参与状态判断的部分一致。"""
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
file_id: int
original_filename: str
sha256: str
parse_failed_at: datetime | None
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'};
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
仍带 file_no/file_sha256 便于诊断与前端提示。
@dataclass(frozen=True)
class _UnitFact:
"""批量投影用的执行单元,只保留状态判断需要的 status。"""
status: str
@dataclass(frozen=True)
class _OutboundFileView:
"""出站归档文件只读视图,字段与入站 InboundFileView 对齐,供同一投影顺序读取。"""
file_id: int
source_code: str
sha256: str
storage_key: str
original_filename: str
created_at: datetime
parse_failed_at: datetime | None = None
def _outbound_fresh_and_retention_valid(now: datetime):
"""出站归档的新鲜度 + 保留期条件,列与入站 _fresh_and_retention_valid 同口径。
核心逻辑:业务日窗口用 date_policy.business_date_utc_window(与 queries 内联
数学一致);archive_expires_at 为空视为长期有效。
"""
window_start, window_end = business_date_utc_window(now)
return and_(
FreightRpaOutboundReportFile.created_at >= window_start,
FreightRpaOutboundReportFile.created_at < window_end,
or_(
FreightRpaOutboundReportFile.archive_expires_at.is_(None),
FreightRpaOutboundReportFile.archive_expires_at > now,
),
)
def _outbound_file_view(report: FreightRpaOutboundReportFile) -> _OutboundFileView:
"""把出站归档 ORM 行映射为冻结只读视图。"""
return _OutboundFileView(
file_id=report.id,
source_code=report.unit_run.source_code,
sha256=report.sha256,
storage_key=report.storage_key,
original_filename=report.original_filename,
created_at=report.created_at,
parse_failed_at=report.parse_failed_at,
)
def latest_usable_outbound_file(
source_code: str,
*,
now: datetime | None = None,
) -> _OutboundFileView | None:
"""返回某来源当前可用的出站归档只读视图,最新优先。
用途:出站证据流状态投影取文件身份;口径与 latest_usable_inbound_file 相同
(未删除 + 当天业务日抓取 + 未过期),不读取对象存储字节。
核心逻辑:经出站执行单元行的 source_code 过滤,按 created_at/id 倒序取第一条。
Args:
source_code: 来源实例编码(写在 FreightRpaOutboundUnitRun.source_code 上)。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
_OutboundFileView;无可用文件返回 None。
"""
now = now or datetime.utcnow()
report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
FreightRpaOutboundReportFile.query
.join(FreightRpaOutboundReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
usable_receipt_file_condition(),
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
_outbound_fresh_and_retention_valid(now),
)
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
.order_by(FreightRpaOutboundReportFile.created_at.desc(), FreightRpaOutboundReportFile.id.desc())
.first()
)
if report is not None:
# 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败,
# 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。
if report.parse_failed_at is not None:
if report is None:
return None
return _outbound_file_view(report)
def has_expired_outbound_file(source_code: str, *, now: datetime | None = None) -> bool:
"""返回某来源是否存在未删除但已失效的出站归档(expired 投影依据)。
用途:出站状态投影在无可用文件、无进行中/终态单元之后,判断是否因隔日旧文件
或保留期已到而提示重抓。只读不写。
核心逻辑:未删除且新鲜度+保留期不成立,与 has_expired_inbound_file 同核。
Args:
source_code: 来源实例编码。
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
Returns:
存在失效但未清理的出站归档 → True;否则 False。
"""
now = now or datetime.utcnow()
expired = (
FreightRpaOutboundReportFile.query
.join(FreightRpaOutboundReportFile.unit_run)
.filter(
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
not_(_outbound_fresh_and_retention_valid(now)),
)
.first()
)
return expired is not None
def _empty_status(file_status: str) -> dict:
"""没有可用文件身份时的投影字典。"""
return {'file_status': file_status, 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
def _status_from_facts(
*,
file_view: Any | None,
active_unit: Any | None,
latest_unit: Any | None,
expired: bool,
) -> dict:
"""按既定优先级把已取到的文件与单元事实收成状态字典。
核心逻辑:可用文件(解析失败优先于 ready)→ 进行中单元 → 最新单元空数据 →
最新单元失败终态 → 失效文件 → none。单来源与批量投影共用,避免两条路径
各写一套优先级。
Args:
file_view: 可用文件视图;须有 original_filename、file_id、parse_failed_at、sha256。
没有可用文件时为 None。
active_unit: 仍在进行的执行单元;没有时为 None。只要求对象存在。
latest_unit: id 最大的执行单元;没有时为 None。须有 status。
expired: 是否仍有未清理的失效归档。
Returns:
file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。
"""
if file_view is not None:
file_no = file_view.original_filename or str(file_view.file_id)
# 解析失败分层:文件本身可用但解析失败,不得当 ready,保留文件身份供诊断。
if file_view.parse_failed_at is not None:
return {
'file_status': 'parse_failed',
'has_ready_file': False,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
'file_no': file_no,
'file_sha256': file_view.sha256,
}
return {
'file_status': 'ready',
'has_ready_file': True,
'file_no': report.original_filename or str(report.id),
'file_sha256': report.sha256,
'file_no': file_no,
'file_sha256': file_view.sha256,
}
active_unit = (
ShippingReceiptRpaUnitRun.query
.filter_by(source_code=source_code)
.filter(ShippingReceiptRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES))
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
if active_unit is not None:
return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
latest_unit = (
ShippingReceiptRpaUnitRun.query
.filter_by(source_code=source_code)
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
return _empty_status('fetching')
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
# 空数据:抓取成功但当日无收料记录——如实投影 no_data,不得与抓取失败混淆。
return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
# 空数据:抓取成功但当日无记录——如实投影 no_data,不得与抓取失败混淆。
return _empty_status('no_data')
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
expired_report = (
ShippingReceiptReportFile.query
.join(ShippingReceiptReportFile.unit_run)
.filter(
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
expired_receipt_file_condition(),
)
.first()
)
if expired_report is not None:
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
return _empty_status('failed')
if expired:
return _empty_status('expired')
return _empty_status('none')
def record_receipt_parse_failure(
def _project_file_status(
source_code: str,
*,
report: ShippingReceiptReportFile,
error_code: str,
error_message: str,
now: datetime | None = None,
) -> None:
"""标记一份收料归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
latest_file: Callable[..., Any],
unit_model: type,
has_expired: Callable[..., bool],
) -> dict:
"""按入站既有顺序把文件视图与执行单元投影成文件状态。
【AI 触发时机】收料归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、
让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后
改调 clear_receipt_parse_failure。
核心逻辑:[STEP 1] 写入失败时间(now 或当前 UTC)与截断后的错误码/错误信息;
[STEP 2] db.session.flush() 使投影同事务内立即可见。只 flush 不 commit,
事务提交时机归调用方(与解析流程共用同一事务,禁止在 service 层越权提交)。
核心逻辑:有可用文件就不再查单元;没有进行中单元才看最新单元;最新单元
已是空数据或失败终态就不再查失效文件。入站与出站共用,差异只在三个协作参数。
Args:
report: 待标记的 ShippingReceiptReportFile(须已入库,主键可用)。
error_code: 机器可读错误码,超 64 字符截断(对齐列宽 String(64))。
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
now: 可选失败时刻;缺省取当前 UTC(与全链路 utcnow 口径一致)。
source_code: 来源实例编码。
latest_file: 返回可用文件视图或 None;视图须有 original_filename、file_id、
parse_failed_at、sha256。
unit_model: 带 query/status/id/source_code 的执行单元模型。
has_expired: 该来源是否仍有失效未清理文件。
Returns:
None。失败标记写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。
"""
report.parse_failed_at = now or datetime.utcnow()
report.parse_error_code = (error_code or '')[:64]
report.parse_error_message = (error_message or '')[:2000]
db.session.flush()
file_view = latest_file(source_code)
active_unit = None
latest_unit = None
expired = False
if file_view is None:
active_unit = (
unit_model.query
.filter_by(source_code=source_code)
.filter(unit_model.status.in_(RUNNING_UNIT_STATUSES))
.order_by(unit_model.id.desc())
.first()
)
if active_unit is None:
latest_unit = (
unit_model.query
.filter_by(source_code=source_code)
.order_by(unit_model.id.desc())
.first()
)
terminal = latest_unit is not None and latest_unit.status in (
*NO_DATA_UNIT_STATUSES, *FAILED_UNIT_STATUSES,
)
if not terminal:
expired = has_expired(source_code)
return _status_from_facts(
file_view=file_view,
active_unit=active_unit,
latest_unit=latest_unit,
expired=expired,
)
def clear_receipt_parse_failure(*, report: ShippingReceiptReportFile) -> None:
"""清除一份收料归档文件的解析失败标记(三列置空),投影恢复 ready。
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
"""一次取出这批来源各自最新的可用归档。
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
Args:
file_model: 入站或出站归档文件模型。
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
source_ids: 要投影的来源主键。
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
Returns:
source_code 到文件事实的映射;没有可用文件的来源不出现。
"""
rows = (
file_model.query
.join(unit_model, file_model.unit_run_id == unit_model.id)
.filter(unit_model.source_id.in_(source_ids), *filters)
.with_entities(
unit_model.source_code,
file_model.id,
file_model.original_filename,
file_model.sha256,
file_model.parse_failed_at,
)
.order_by(file_model.created_at.desc(), file_model.id.desc())
.all()
)
picked: dict[str, _FileFact] = {}
for source_code, file_id, filename, sha256, parse_failed_at in rows:
if source_code in picked:
continue
picked[str(source_code)] = _FileFact(
file_id=file_id,
original_filename=filename,
sha256=sha256,
parse_failed_at=parse_failed_at,
)
return picked
def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str, _UnitFact], dict[str, _UnitFact]]:
"""一次取出这批来源的最新单元,以及仍在进行的最新单元。
核心逻辑:按 id 倒序扫描,每个来源遇到的第一行就是最新单元;状态属于进行中
的第一行就是该来源仍在抓取的单元。较新的失败单元因此盖不住更早仍在进行的单元。
Args:
unit_model: 入站或出站执行单元模型。
source_ids: 要投影的来源主键。
Returns:
(最新单元, 进行中单元),键都是 source_code。没有单元时对应字典为空。
"""
rows = (
unit_model.query
.filter(unit_model.source_id.in_(source_ids))
.with_entities(unit_model.source_code, unit_model.id, unit_model.status)
.order_by(unit_model.id.desc())
.all()
)
latest: dict[str, _UnitFact] = {}
active: dict[str, _UnitFact] = {}
for source_code, _unit_id, status in rows:
code = str(source_code)
if code not in latest:
latest[code] = _UnitFact(status=status)
if status in RUNNING_UNIT_STATUSES and code not in active:
active[code] = _UnitFact(status=status)
return latest, active
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
"""一次找出仍有失效未清理归档的来源编码。
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
Args:
file_model: 入站或出站归档文件模型。
unit_model: 对应的执行单元模型。
source_ids: 要投影的来源主键。
filters: 失效文件条件。
Returns:
至少有一份失效未清理归档的 source_code 集合。
"""
rows = (
file_model.query
.join(unit_model, file_model.unit_run_id == unit_model.id)
.filter(unit_model.source_id.in_(source_ids), *filters)
.with_entities(unit_model.source_code)
.distinct()
.all()
)
return {str(row[0]) for row in rows}
def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict]]:
"""批量投影一组来源的入站与出站证据文件状态。
用途:GET /sources 渲染来源选择卡。来源个数增加时仍只做固定几条查询,
供页面同时展示调拨类型和数据源时不必按来源等待。
核心逻辑:出站配置、入站/出站的可用文件、执行单元、失效文件各查一次,
再按与 resolve_source_file_status 相同的优先级收口。没有出站配置的来源
直接记 unconfigured,不把入站状态抄到出站。
Args:
sources: 已加载的来源行,须有 id 与 source_code。空列表不查库。
Returns:
{source_code: {"inbound": 状态字典, "outbound": 状态字典}}。
状态字典键与 resolve_source_file_status 相同。
"""
if not sources:
return {}
now = datetime.utcnow()
source_ids = [int(source.id) for source in sources]
configured_outbound = {
int(row[0])
for row in (
FreightRpaOutboundReportConfig.query
.filter(FreightRpaOutboundReportConfig.source_id.in_(source_ids))
.with_entities(FreightRpaOutboundReportConfig.source_id)
.all()
)
}
inbound_files = _latest_files_by_source(
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
source_ids,
usable_inbound_file_condition(now=now),
)
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
inbound_expired = _expired_source_codes(
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
source_ids,
expired_inbound_file_condition(now=now),
)
outbound_files = _latest_files_by_source(
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
source_ids,
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
_outbound_fresh_and_retention_valid(now),
)
outbound_latest, outbound_active = _units_by_source(FreightRpaOutboundUnitRun, source_ids)
outbound_expired = _expired_source_codes(
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
source_ids,
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
not_(_outbound_fresh_and_retention_valid(now)),
)
projected: dict[str, dict[str, dict]] = {}
for source in sources:
code = str(source.source_code)
inbound = _status_from_facts(
file_view=inbound_files.get(code),
active_unit=inbound_active.get(code),
latest_unit=inbound_latest.get(code),
expired=code in inbound_expired,
)
if int(source.id) not in configured_outbound:
outbound = _empty_status('unconfigured')
else:
outbound = _status_from_facts(
file_view=outbound_files.get(code),
active_unit=outbound_active.get(code),
latest_unit=outbound_latest.get(code),
expired=code in outbound_expired,
)
projected[code] = {'inbound': inbound, 'outbound': outbound}
return projected
def resolve_source_file_status(*, source_code: str, record_kind: str = 'inbound') -> dict:
"""返回某来源在指定记录类型上的证据文件状态投影。
用途:来源列表与重试门禁按流入站或出站询问文件是否就绪。缺省 record_kind
为 inbound,既有只传来源的调用返回值与改造前相同。
核心逻辑:record_kind 不是 inbound/outbound 时抛 ValidationError。出站先查
get_outbound_config,没有配置行则 unconfigured,不再往下看文件或单元。
有配置(以及全部入站)再按同一顺序投影。失效判定不依赖保留期清理任务:
保留期已到,或非当前业务日(Asia/Shanghai)抓取。
Args:
source_code: 来源实例编码。
record_kind: inbound 或 outbound,默认 inbound。
Returns:
{"file_status", "has_ready_file", "file_no", "file_sha256"}。
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data',
'expired', 'none', 'unconfigured'}。parse_failed 时 has_ready_file=False,
仍带 file_no/file_sha256。unconfigured 仅出站且无出站报表配置时出现。
Raises:
ValidationError: record_kind 不是 inbound 或 outbound。
"""
if record_kind not in _RECORD_KINDS:
raise ValidationError(
f'unsupported record_kind: {record_kind}',
details={'record_kind': record_kind},
)
if record_kind == 'outbound':
if get_outbound_config(source_code) is None:
return _empty_status('unconfigured')
return _project_file_status(
source_code,
latest_file=latest_usable_outbound_file,
unit_model=FreightRpaOutboundUnitRun,
has_expired=has_expired_outbound_file,
)
return _project_file_status(
source_code,
latest_file=latest_usable_inbound_file,
unit_model=FreightRpaInboundUnitRun,
has_expired=has_expired_inbound_file,
)
def record_inbound_parse_failure(
*,
report: Any,
error_code: str,
error_message: str,
) -> None:
"""标记一份入站归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
【AI 触发时机】入站归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、
让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后
改调 clear_inbound_parse_failure。
【阶段 B Task 4 兼容薄壳】全量语义(失败时刻取当前 UTC、错误码按 64 字符/
错误信息按 2000 字符截断、只 flush 不 commit——事务提交时机归属调用方)已
收口 freight_rpa.reports.queries.mark_inbound_parse_failure(唯一实现);
本壳只为既有调用方按归档文件对象传参的签名而保留——取对象主键委托真实现。
Args:
report: 入站归档文件对象(仅取主键 .id;须已入库)。
error_code: 机器可读错误码(真实现内按列宽截断)。
error_message: 人类可读错误信息(真实现内做防御性截断)。
Returns:
None。失败标记随调用方事务落库。
"""
_mark_parse_failure_by_id(report.id, error_code=error_code, error_message=error_message)
def clear_inbound_parse_failure(*, report: Any) -> None:
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态
投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。
核心逻辑:[STEP 1] 将 parse_failed_at / parse_error_code / parse_error_message
三列置 None(三者全空即未失败/已清除的约定态);[STEP 2] flush 使同事务内
投影立即可见。只 flush 不 commit,事务提交时机归调用方。
【阶段 B Task 4 兼容薄壳】语义收口同 record_inbound_parse_failure:取对象
主键委托 freight_rpa.reports.queries.clear_inbound_parse_failure(置空三列
后 flush,不 commit,事务归属调用方)。
Args:
report: 待清除标记的 ShippingReceiptReportFile(须已入库,主键可用)。
report: 入站归档文件对象(仅取主键 .id;须已入库)。
Returns:
None。清除写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
None。清除随调用方事务落库。
"""
report.parse_failed_at = None
report.parse_error_code = None
report.parse_error_message = None
db.session.flush()
_clear_parse_failure_by_id(report.id)
@@ -1,15 +1,17 @@
"""在途调拨状态机与转换门禁。
用途:定义提示词冻结的 13 个业务状态(TransferStatus)、Run 生命周期
用途:定义提示词冻结的 12 个业务状态(TransferStatus)、Run 生命周期
(TransferRunStatus)与通知状态(TransferNotificationStatus),
并强制所有状态转换走服务端门禁。
依赖:app.core.errors.AppError。
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
result_unknown / manually_closed / success / duplicate_success /
not_matured / cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义:
cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义:
DOCUMENT_RETRIGGER_TRANSITIONS 允许 result_unknown 单经人工 retrigger
→ executing,D11 唯一出口;QUEUED Run 经 worker 领取 → executing);
通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。
【not_matured 状态已退役 2026-10-16】成熟概念删除(数据无成熟属性,
日期边界由调用方入参给定);存量行经 tt16 迁移重映射为 cancelled。
"""
from __future__ import annotations
@@ -23,7 +25,7 @@ INVALID_STATE_TRANSITION_CODE = "TRANSFER.INVALID_STATE_TRANSITION"
class TransferStatus(StrEnum):
"""Invoice 项业务状态(含提示词冻结的全部 13 个状态)。"""
"""Invoice 项业务状态(含提示词冻结的全部 12 个状态)。"""
FILE_PENDING = "file_pending"
FILE_READY = "file_ready"
@@ -33,7 +35,6 @@ class TransferStatus(StrEnum):
SUCCESS = "success"
DUPLICATE_SUCCESS = "duplicate_success"
BLOCKED_RECOVERABLE = "blocked_recoverable"
NOT_MATURED = "not_matured"
RESULT_UNKNOWN = "result_unknown"
MANUALLY_CLOSED = "manually_closed"
CANCELLED = "cancelled"
@@ -72,7 +73,6 @@ TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({
TransferStatus.RESULT_UNKNOWN.value,
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.NOTIFICATION_FAILED.value,
})
@@ -89,7 +89,6 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
TransferStatus.MATCHING.value: frozenset({
TransferStatus.READY_TO_EXECUTE.value,
TransferStatus.BLOCKED_RECOVERABLE.value,
TransferStatus.NOT_MATURED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.READY_TO_EXECUTE.value: frozenset({
@@ -114,7 +113,6 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
TransferStatus.MANUALLY_CLOSED.value,
TransferStatus.CANCELLED.value,
}),
TransferStatus.NOT_MATURED.value: frozenset(),
TransferStatus.SUCCESS.value: frozenset(),
TransferStatus.DUPLICATE_SUCCESS.value: frozenset(),
# [T10/R7 出边] result_unknown 行唯一出边 = 人工 retrigger 驱动 → executing
@@ -1,127 +1,84 @@
"""在途调拨类型契约。
"""在途调拨类型契约(配置化,ADR 0002)。
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝匹配,规则先冻结)。
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
逻辑:类型决定匹配纳入哪些收料单——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
的单(大小写不敏感,范围外单与收料日期范围过滤同语义,静默排除不入明细);
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
类型 3 规则待业务定义。范围判断统一走 invoice_in_scope 谓词(匹配过滤与
scope 行圈定共用);调用方必须先 ensure_transfer_type_supported 再过滤。
用途:匹配链路的类型门禁唯一入口——把 API/服务传入的类型编码解析为
transfer_type_configs 配置 DTO(存在性/启停校验 fail-closed)。
依赖:transfer_type_config_service(get_by_code,唯一读取口径)、app.core.errors。
逻辑:【2026-10-14 配置化切换】类型不再硬编码枚举:合法值=配置表 code,
数据范围/仓库定义/转换规则全部随配置(scope_rules / warehouse_config /
transform_rules),匹配创建时快照进 scope_json。本模块只做「编码 → 配置
DTO」的门禁解析:None/空 → REQUIRED;无此码(含空配置表)→ NOT_CONFIGURED;
停用 → DISABLED(require_enabled=False 供存量匹配的重跑/重查使用——
「停用后新匹配不可选,存量不受影响」,规格 §4.1)。
旧枚举/前缀常量/谓词(TransferType / SUPPORTED_TRANSFER_TYPES /
normalize_transfer_type / ensure_transfer_type_supported / invoice_in_scope /
filter_invoices_for_type / transfer_type_scope_note)已随翻转退役:
范围职责移交 scope_rules 引擎 + 匹配快照,批号转换移交 field_transforms。
"""
from __future__ import annotations
from enum import StrEnum
from typing import Iterable
from app.core.errors import ValidationError
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
from app.services.in_transit_transfer.transfer_type_config_service import (
TransferTypeConfigDTO,
get_by_code,
)
# 类型不支持(占位类型被调用)时的稳定错误码。
TRANSFER_TYPE_NOT_SUPPORTED = "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
# 匹配创建未携带类型编码(必填缺失)的稳定错误码(规格 §11,四语言已配齐)。
TRANSFER_TYPE_REQUIRED = "TRANSFER.TRANSFER_TYPE_REQUIRED"
# 配置表为空或无此编码(fail-closed,D8 不做种子数据)。
TRANSFER_TYPE_NOT_CONFIGURED = "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
# 类型存在但已停用(停用后新匹配不可选)。
TRANSFER_TYPE_DISABLED = "TRANSFER.TRANSFER_TYPE_DISABLED"
class TransferType(StrEnum):
"""调拨业务类型(值与前端/i18n、transfer_runs.transfer_type 列一致)。"""
def resolve_transfer_type(code: str | None, *, require_enabled: bool = True) -> TransferTypeConfigDTO:
"""把类型编码解析为配置 DTO(匹配链路的类型门禁唯一入口)。
IN_TRANSIT_TO_HUB = "in_transit_to_hub" # 在途仓至HUB仓
HUB_REPAIR_OUT = "hub_repair_out" # HUB仓维修出(占位)
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
# 一期已实现匹配/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES: tuple[str, ...] = ("HOM", "HOX", "WTP")
# 类型 2(HUB仓维修出)数据范围:ODM ID 精确值;待 movement 文件暴露 odm_id 后启用。
HUB_REPAIR_OUT_ODM_ID = "HoxinRMA"
def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
"""规范化调拨类型入参;缺省/空值回落到类型 1(存量调用方语义不变)。
【AI 触发时机】匹配创建(run_matching / create_matching / API 必填校验)与
存量匹配的重跑/重查需要类型配置(范围规则/仓库定义/转换规则)时,
必须经本函数解析;禁止绕过配置直取编码或假设固定类型。
Args:
value: 前端/API 传入的调拨类型值。
code: 类型编码(transfer_type_configs.code,创建后不可变)。
require_enabled: True(默认)=停用类型拒绝(新匹配路径);False=存量
匹配的重跑/重查放行停用类型(「存量不受影响」语义)。
Returns:
TransferType 枚举。
TransferTypeConfigDTO(scope_rules/warehouse_config/transform_rules 均为
引擎解析后的受控对象)。
Raises:
ValidationError: 非法类型值(不在枚举内)。
ValidationError: code 为 None/空白 → TRANSFER.TRANSFER_TYPE_REQUIRED;
配置表无此码(含空表)→ TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED;
停用且 require_enabled → TRANSFER.TRANSFER_TYPE_DISABLED。
"""
raw = str(value.value if isinstance(value, TransferType) else (value or "")).strip()
if not raw:
return TransferType.IN_TRANSIT_TO_HUB
try:
return TransferType(raw)
except ValueError as exc:
cleaned = str(code or "").strip()
if not cleaned:
raise ValidationError(
f"unknown transfer type: {raw}",
code="TRANSFER.TRANSFER_TYPE_INVALID",
details={"transfer_type": raw},
) from exc
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入匹配。
Args:
transfer_type: 已规范化的调拨类型。
Raises:
ValidationError: 类型未实现(TRANSFER_TYPE_NOT_SUPPORTED)。
"""
if transfer_type not in SUPPORTED_TRANSFER_TYPES:
raise ValidationError(
f"transfer type not supported yet: {transfer_type.value}",
code=TRANSFER_TYPE_NOT_SUPPORTED,
details={"transfer_type": transfer_type.value},
"transfer_type is required",
code=TRANSFER_TYPE_REQUIRED,
http_status=422, # 规格 §11:匹配创建类型门禁统一 422
)
# 复用配置服务的唯一读取口径:脏配置在其读取侧已被引擎拦截(fail-closed)。
from app.services.in_transit_transfer.transfer_type_config_service import (
TRANSFER_TYPE_NOT_CONFIGURED as _NOT_CONFIGURED,
)
def invoice_in_scope(invoice_no: str, transfer_type: TransferType | str | None) -> bool:
"""判断 Invoice 单号是否落在调拨类型的收料数据范围内(单一判断口径)。
用途:匹配过滤(filter_invoices_for_type)与 scope 行圈定(matching_service
的 scope_item_query)共用本谓词,避免"单过滤"与"行圈定"口径漂移。
Args:
invoice_no: 收料单单号(大小写不敏感,前后空白忽略;空值恒 False)。
transfer_type: 调拨类型(未规范化值允许,缺省/空回落类型 1)。
Returns:
True 表示该单在类型范围内(应纳入匹配/scope 查询);
占位类型(规则未启用)恒 False。
"""
resolved = normalize_transfer_type(transfer_type)
if resolved == TransferType.IN_TRANSIT_TO_HUB:
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
return str(invoice_no or "").strip().upper().startswith(prefixes)
# 类型 2/3 的范围规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
return False
def filter_invoices_for_type(
invoices: Iterable[AggregatedInvoice],
transfer_type: TransferType,
) -> list[AggregatedInvoice]:
"""按类型的收料数据范围过滤汇总单(返回保留项,保持原顺序)。
Args:
invoices: 已汇总的收料单。
transfer_type: 已规范化且已确认支持的调拨类型。
Returns:
类型范围内的单列表(判断口径统一走 invoice_in_scope)。
"""
return [
invoice for invoice in invoices
if invoice_in_scope(invoice.invoice_no, transfer_type)
]
def transfer_type_scope_note(transfer_type: TransferType) -> str:
"""类型的范围规则说明(写入 TransferMatching.scope_json 供审计追溯)。"""
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
return f"invoice_prefix:{'+'.join(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES).lower()}"
if transfer_type == TransferType.HUB_REPAIR_OUT:
return f"odm_id:{HUB_REPAIR_OUT_ODM_ID}"
return "pending_rule"
try:
config = get_by_code(cleaned)
except ValidationError as exc:
if exc.code == _NOT_CONFIGURED:
# 归一为本模块稳定错误码(匹配链路与 API 复用同一码面)。
raise ValidationError(
f"transfer type not configured: {cleaned}",
code=TRANSFER_TYPE_NOT_CONFIGURED,
details={"transfer_type": cleaned},
http_status=422, # 规格 §11:空配置/停用类型 → 422
) from exc
raise
if require_enabled and not config.enabled:
raise ValidationError(
f"transfer type is disabled: {cleaned}",
code=TRANSFER_TYPE_DISABLED,
details={"transfer_type": cleaned},
http_status=422, # 规格 §11:空配置/停用类型 → 422
)
return config
@@ -0,0 +1,459 @@
"""services/in_transit_transfer/transfer_type_config_service.py
用途:调拨类型配置域服务(ADR 0002)——transfer_type_configs 表的唯一 CRUD 入口:
列表/启用列表/按码读取/创建/更新(code 创建后不可变,只有停用没有删除),
以及 mapped/fixed 双模式仓库角色解析 resolve_warehouse(Task 11 路由接入、
Task 5 管理 API 消费)。
依赖:models.in_transit_transfer.TransferTypeConfig、app.db(db.session)、
scope_rules.parse_scope_rules、field_transforms.parse_transform_rules、
app.core.errors.ValidationError;RouteMapping 仅类型标注(TYPE_CHECKING)。
逻辑:写路径先过三块配置 parse 门禁(范围规则/仓库定义/转换规则)→ 组装规范化
JSON 后走 ORM 插入/更新(JSON 四列无 server_default,禁止原生 SQL 插入);
读路径 DTO 组装同样全部走 parse——库内脏数据在读取侧也被拦截(fail-closed);
resolve_warehouse 按 role 取 from/to 角色:mapped 透传 RouteMapping,
fixed 覆盖仓库、external_org 非空才覆盖法人。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING, Any
from app import db
from app.core.errors import ValidationError
from app.models.in_transit_transfer import TransferTypeConfig
from app.services.in_transit_transfer.field_transforms import TransformRule, parse_transform_rules
from app.services.in_transit_transfer.scope_rules import ScopeRule, parse_scope_rules
if TYPE_CHECKING:
from app.services.in_transit_transfer.matching_service import RouteMapping
# 稳定错误码(Task 5 同步四语言 errors.json;参数形态类失败走既有通用码)。
TRANSFER_TYPE_NOT_CONFIGURED = "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
TRANSFER_TYPE_CODE_EXISTS = "TRANSFER.TRANSFER_TYPE_CODE_EXISTS"
TRANSFER_TYPE_CODE_IMMUTABLE = "TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE"
WAREHOUSE_CONFIG_INVALID = "TRANSFER.WAREHOUSE_CONFIG_INVALID"
# code 契约:小写字母开头,仅小写字母/数字/下划线,总长 2..64(与列宽一致)。
CODE_PATTERN = re.compile(r"^[a-z][a-z0-9_]{1,63}$")
# 参数形态类校验失败复用既有通用码(不新增四语言条目,管理页表单层先行拦截)。
_PARAM_INVALID = "VALIDATION.INVALID_PARAM"
_WAREHOUSE_MODES = ("mapped", "fixed")
_WAREHOUSE_ROLE_KEYS = {"from": "from_role", "to": "to_role"}
@dataclass(frozen=True)
class WarehouseRole:
"""单角色仓库定义:mapped=沿用来源映射档;fixed=类型固定仓库(可覆盖法人)。"""
mode: str
warehouse_code: str | None = None
external_org: str | None = None
@dataclass(frozen=True)
class WarehouseConfig:
"""类型仓库定义:拨出(from)/拨入(to)两角色各自 mapped 或 fixed。"""
from_role: WarehouseRole
to_role: WarehouseRole
@dataclass(frozen=True)
class TransferTypeConfigDTO:
"""调拨类型配置读取视图:三块配置均为引擎解析后的受控对象(非原始 JSON)。"""
code: str
names: dict[str, Any]
enabled: bool
sort_order: int
scope_rules: tuple[ScopeRule, ...]
warehouse_config: WarehouseConfig
transform_rules: tuple[TransformRule, ...]
description: str | None
updated_at: datetime
def _reject_param(message: str, **details: Any) -> ValidationError:
"""参数形态类校验失败的统一出口(通用码 + 定位详情)。"""
return ValidationError(message, code=_PARAM_INVALID, details=details)
def _clean_str(value: Any) -> str | None:
"""字符串规范化:非字符串 → None;空白串 → None;其余去首尾空白。"""
if not isinstance(value, str):
return None
return value.strip() or None
def _parse_warehouse_config(raw: dict | None) -> WarehouseConfig:
"""校验并规范化仓库定义 JSON(保存与读取共用;非法 fail-closed)。
Args:
raw: {"from": {...}, "to": {...}},角色项缺省视为 mapped(沿用映射档);
mapped 项不消费固定仓库值(规范化为纯 {"mode": "mapped"})。
Returns:
规范化后的 WarehouseConfig。
Raises:
ValidationError: code=TRANSFER.WAREHOUSE_CONFIG_INVALID——mode 不在白名单、
fixed 缺非空 warehouse_code、或结构非 dict。
"""
if raw is None:
raw = {}
if not isinstance(raw, dict):
raise ValidationError(
"warehouse_config must be an object", code=WAREHOUSE_CONFIG_INVALID,
)
def _role(role_key: str) -> WarehouseRole:
entry = raw.get(role_key)
if entry is None:
return WarehouseRole(mode="mapped")
if not isinstance(entry, dict):
raise ValidationError(
f"warehouse role {role_key} must be an object", code=WAREHOUSE_CONFIG_INVALID,
details={"role": role_key},
)
mode = str(entry.get("mode", ""))
if mode not in _WAREHOUSE_MODES:
raise ValidationError(
f"invalid warehouse mode: {mode}", code=WAREHOUSE_CONFIG_INVALID,
details={"role": role_key, "mode": mode},
)
if mode != "fixed":
return WarehouseRole(mode="mapped")
warehouse_code = _clean_str(entry.get("warehouse_code"))
if not warehouse_code:
raise ValidationError(
f"fixed warehouse role requires warehouse_code: {role_key}",
code=WAREHOUSE_CONFIG_INVALID, details={"role": role_key},
)
return WarehouseRole(
mode="fixed", warehouse_code=warehouse_code,
external_org=_clean_str(entry.get("external_org")),
)
return WarehouseConfig(from_role=_role("from"), to_role=_role("to"))
def _warehouse_role_json(role: WarehouseRole) -> dict[str, Any]:
"""WarehouseRole → 规范化 JSON 项(mapped 固化空值,保证读写对称)。"""
return {"mode": role.mode, "warehouse_code": role.warehouse_code, "external_org": role.external_org}
def _warehouse_config_json(config: WarehouseConfig) -> dict[str, Any]:
"""WarehouseConfig → 入库 JSON(from/to 键与规格 §7 示例一致)。"""
return {
"from": _warehouse_role_json(config.from_role),
"to": _warehouse_role_json(config.to_role),
}
def _to_dto(row: TransferTypeConfig) -> TransferTypeConfigDTO:
"""ORM 行 → DTO;三块配置全部重走 parse,库内脏数据在读取侧被拦截。
Raises:
ValidationError: 脏数据命中任一引擎白名单校验(SCOPE/WAREHOUSE/TRANSFORM)。
"""
return TransferTypeConfigDTO(
code=row.code,
names=dict(row.names_json or {}),
enabled=bool(row.enabled),
sort_order=int(row.sort_order or 0),
scope_rules=parse_scope_rules(row.scope_rules_json),
warehouse_config=_parse_warehouse_config(row.warehouse_config_json),
transform_rules=parse_transform_rules(row.transform_rules_json),
description=row.description,
updated_at=row.updated_at,
)
def _query_by_code(code: str) -> TransferTypeConfig | None:
"""按 code 精确查询(入参去首尾空白;不查 None/空串)。"""
cleaned = str(code or "").strip()
if not cleaned:
return None
return db.session.query(TransferTypeConfig).filter(TransferTypeConfig.code == cleaned).one_or_none()
def _scope_rules_of(payload: dict) -> tuple[ScopeRule, ...]:
"""解析 payload 中的范围规则(parse 门禁复用 Task 2 引擎,非法透传其错误码)。
Raises:
ValidationError: TRANSFER.SCOPE_RULE_INVALID(规则字段/匹配方式/值非法)。
"""
return parse_scope_rules(payload.get("scope_rules"))
def _enforce_scope_policy(payload: dict, rules: tuple[ScopeRule, ...]) -> None:
"""空规则默认拒绝(防误圈全量);payload 显式确认(allow_empty_scope_rules)才放行。
[规格 §6] 是否允许「空=不限」由管理页显式确认——本服务默认要求至少一条。
"""
if rules or payload.get("allow_empty_scope_rules") is True:
return
raise _reject_param("scope_rules requires at least one rule unless explicitly confirmed")
def _validated_names(payload: dict, *, required: bool) -> dict[str, Any] | None:
"""校验 names:dict 且含非空 zh-CN(四语言名称的门禁底线)。
Args:
payload: 创建/更新载荷。
required: 创建恒为 True(names_json 必须含非空 zh-CN,缺 key 同拒);
更新为 False(未提供保持原值,提供则同门禁校验)。
Returns:
names dict(更新未提供时 None,由调用方保持原值)。
Raises:
ValidationError: required 且缺 key、非 dict、缺 zh-CN 或 zh-CN 非非空字符串。
"""
if "names" not in payload:
if required:
raise _reject_param("names is required with non-empty zh-CN")
return None
names = payload.get("names")
zh = names.get("zh-CN") if isinstance(names, dict) else None
if not isinstance(zh, str) or not zh.strip():
raise _reject_param("names requires non-empty zh-CN", names=names)
return dict(names)
def _coerce_sort_order(value: Any) -> int:
"""sort_order 宽松转 int(JSON 数字/数字字符串),失败走参数校验码。"""
try:
return int(value)
except (TypeError, ValueError) as exc:
raise _reject_param(f"invalid sort_order: {value!r}", sort_order=value) from exc
def list_configs() -> list[TransferTypeConfigDTO]:
"""全量类型配置(含停用),按 sort_order 升序、code 次序稳定排序。
Returns:
TransferTypeConfigDTO 列表(管理页列表用;含停用项)。
Raises:
ValidationError: 任一行的范围规则/仓库定义/转换规则为脏数据时,经 _to_dto
抛对应引擎错误码(TRANSFER.SCOPE_RULE_INVALID /
TRANSFER.WAREHOUSE_CONFIG_INVALID / TRANSFER.TRANSFORM_RULE_INVALID,
fail-closed,不降级返回脏配置)。
"""
rows = (
db.session.query(TransferTypeConfig)
.order_by(TransferTypeConfig.sort_order.asc(), TransferTypeConfig.code.asc())
.all()
)
return [_to_dto(row) for row in rows]
def get_enabled() -> list[TransferTypeConfigDTO]:
"""启用中的类型配置,按 sort_order 升序(chat 侧类型列表与 Task 5 公开接口用)。
Returns:
仅 enabled 的 TransferTypeConfigDTO 列表。
Raises:
ValidationError: 脏数据同 list_configs——读取侧 parse fail-closed
(对应引擎错误码,不降级返回脏配置)。
"""
rows = (
db.session.query(TransferTypeConfig)
.filter(TransferTypeConfig.enabled.is_(True))
.order_by(TransferTypeConfig.sort_order.asc(), TransferTypeConfig.code.asc())
.all()
)
return [_to_dto(row) for row in rows]
def get_by_code(code: str) -> TransferTypeConfigDTO:
"""按 code 读取单个类型配置。
Args:
code: 类型编码(创建后不可变的业务主键)。
Returns:
TransferTypeConfigDTO。
Raises:
ValidationError: 不存在 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED(匹配链
fail-closed 同码);脏配置 → 对应引擎错误码。
"""
row = _query_by_code(code)
if row is None:
raise ValidationError(
f"transfer type not configured: {code}", code=TRANSFER_TYPE_NOT_CONFIGURED,
details={"code": code},
)
return _to_dto(row)
def create_config(payload: dict, operator_id: int | None = None) -> TransferTypeConfigDTO:
"""创建类型配置(写入唯一入口;JSON 四列必须经 ORM 插入,无 server_default)。
Args:
payload: {code, names, enabled?, sort_order?, scope_rules?, warehouse_config?,
transform_rules?, description?, allow_empty_scope_rules?}。
operator_id: 创建人 users.id(可空,系统初始化场景)。
Returns:
新建配置的 TransferTypeConfigDTO。
Raises:
ValidationError: code 重复 → TRANSFER.TRANSFER_TYPE_CODE_EXISTS;code 格式
非法/缺 zh-CN/空 scope_rules 未显式确认 → 通用参数码;
规则/仓库/转换非法 → 对应引擎错误码。
"""
if not isinstance(payload, dict):
raise _reject_param("payload must be an object")
# [STEP 1] code 契约:格式先行(唯一性后置到 DB 前查重)。
code = _clean_str(payload.get("code"))
if not code or not CODE_PATTERN.match(code):
raise _reject_param(f"invalid transfer type code: {code!r}", code=code)
# [STEP 2] names 必填且含非空 zh-CN(创建路径硬门禁,缺 key 同拒)。
names = _validated_names(payload, required=True)
# [STEP 3] 三块配置 parse 门禁:范围规则(含空规则默认拒绝)、仓库定义、转换规则。
scope_rules = _scope_rules_of(payload)
_enforce_scope_policy(payload, scope_rules)
warehouse_config = _parse_warehouse_config(payload.get("warehouse_config"))
transform_rules = parse_transform_rules(payload.get("transform_rules"))
# [STEP 4] 唯一性预检(并发窗口由 uq_transfer_type_configs_code 兜底)。
if _query_by_code(code) is not None:
raise ValidationError(
f"transfer type code already exists: {code}", code=TRANSFER_TYPE_CODE_EXISTS,
details={"code": code},
)
# [STEP 5] ORM 插入:JSON 列写入规范化结果(读回必可 parse,读写对称)。
row = TransferTypeConfig(
code=code,
names_json=names,
enabled=bool(payload.get("enabled", False)),
sort_order=_coerce_sort_order(payload.get("sort_order", 0)),
scope_rules_json=[
{"field": r.field, "match": r.match, "values": list(r.values)} for r in scope_rules
],
warehouse_config_json=_warehouse_config_json(warehouse_config),
transform_rules_json=[
{"field": r.field, "op": r.op, "source": r.source, "target": r.target}
for r in transform_rules
],
description=_clean_str(payload.get("description")),
created_by=operator_id,
updated_by=operator_id,
)
db.session.add(row)
db.session.commit()
return _to_dto(row)
def update_config(code: str, payload: dict, operator_id: int | None = None) -> TransferTypeConfigDTO:
"""更新类型配置(部分更新:payload 未提供的字段保持原值;code 不可变)。
原子校验:所有提供的键先全量 parse/校验,全部通过后才统一赋值提交——
任一键非法时整单拒绝且行保持原值(不落半截变更,评审 Finding 2 契约)。
Args:
code: 目标类型编码(路径参数)。
payload: 待更新字段;含 code 且与目标不等 → 改名被拒。
operator_id: 更新人 users.id(可空)。
Returns:
更新后的 TransferTypeConfigDTO。
Raises:
ValidationError: 不存在 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED;改 code →
TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE;字段校验失败同 create
(引擎错误码或参数形态码),抛出时行未被修改。
"""
if not isinstance(payload, dict):
raise _reject_param("payload must be an object")
row = _query_by_code(code)
if row is None:
raise ValidationError(
f"transfer type not configured: {code}", code=TRANSFER_TYPE_NOT_CONFIGURED,
details={"code": code},
)
# [STEP 1] code 不可变(transfer_runs.transfer_type 引用它,改名即断链)。
payload_code = payload.get("code")
if payload_code is not None and str(payload_code).strip() != row.code:
raise ValidationError(
f"transfer type code is immutable: {row.code}", code=TRANSFER_TYPE_CODE_IMMUTABLE,
details={"code": row.code, "attempted": payload_code},
)
# [STEP 2] 全量预校验(与 create 同构):所有可更新键先 parse/校验到 updates,
# 任一非法即整体抛出——此阶段不触碰 ORM 行,杜绝半截变更残留 session
# (评审 Finding 2:形如 {"description": 新值, "transform_rules": 非法}
# 的载荷禁止先改 description 再抛错)。
updates: dict[str, Any] = {}
names = _validated_names(payload, required=False)
if names is not None:
updates["names_json"] = names
if "scope_rules" in payload:
scope_rules = _scope_rules_of(payload)
_enforce_scope_policy(payload, scope_rules)
updates["scope_rules_json"] = [
{"field": r.field, "match": r.match, "values": list(r.values)} for r in scope_rules
]
if "warehouse_config" in payload:
warehouse_config = _parse_warehouse_config(payload.get("warehouse_config"))
updates["warehouse_config_json"] = _warehouse_config_json(warehouse_config)
if "transform_rules" in payload:
transform_rules = parse_transform_rules(payload.get("transform_rules"))
updates["transform_rules_json"] = [
{"field": r.field, "op": r.op, "source": r.source, "target": r.target}
for r in transform_rules
]
if "enabled" in payload:
updates["enabled"] = bool(payload.get("enabled"))
if "sort_order" in payload:
updates["sort_order"] = _coerce_sort_order(payload.get("sort_order"))
if "description" in payload:
updates["description"] = _clean_str(payload.get("description"))
# [STEP 3] 全部通过后统一赋值(键为本函数白名单字面量)+ updated_by,一次提交。
for attr, value in updates.items():
setattr(row, attr, value)
row.updated_by = operator_id
db.session.commit()
return _to_dto(row)
def resolve_warehouse(
route_mapped: "RouteMapping", config: WarehouseConfig, role: str,
) -> tuple[str, str]:
"""按角色解析运行期 (external_org, warehouse_code):mapped 透传、fixed 覆盖。
【AI 触发时机】匹配圈档/建单/库存查询需要「拨出仓、拨入仓、法人」三元组时,
必须经本函数按类型配置解析;禁止绕过配置直取 RouteMapping 或硬编码仓库。
Args:
route_mapped: 来源路由映射档解析结果(DefaultRouteResolver 产物)。
config: 类型配置的仓库定义(WarehouseConfig)。
role: "from"(拨出)或 "to"(拨入),其他值 fail-closed。
Returns:
(external_org, warehouse_code):mapped 双双透传映射档;fixed 取配置仓库,
external_org 非空覆盖法人、为空沿用映射档。
Raises:
ValidationError: role 非法,或 fixed 角色缺 warehouse_code
(TRANSFER.WAREHOUSE_CONFIG_INVALID;解析侧兜底防线)。
"""
if role == "from":
role_config = config.from_role
elif role == "to":
role_config = config.to_role
else:
raise ValidationError(
f"unknown warehouse role: {role}", code=WAREHOUSE_CONFIG_INVALID, details={"role": role},
)
if role_config.mode == "fixed":
if not role_config.warehouse_code:
raise ValidationError(
f"fixed warehouse role requires warehouse_code: {role}",
code=WAREHOUSE_CONFIG_INVALID, details={"role": role},
)
return (role_config.external_org or route_mapped.external_org, role_config.warehouse_code)
warehouse = route_mapped.from_warehouse if role == "from" else route_mapped.to_warehouse
return (route_mapped.external_org, warehouse)
@@ -59,10 +59,9 @@ class WecomSummarySender:
matched=counts.get("matched_count", 0),
pending=counts.get("pending_stock_check_count", 0),
),
"可执行: {executable} 数量不符: {blocked} 未成熟: {not_matured}".format(
"可执行: {executable} 数量不符: {blocked}".format(
executable=counts.get("executable_count", 0),
blocked=counts.get("blocked_count", 0),
not_matured=counts.get("not_matured_count", 0),
),
])
+5 -3
View File
@@ -343,11 +343,13 @@ def _register_headers_from_config() -> None:
for name, cfg in get_all_schedule_sql_configs().items():
if cfg.alias_order and cfg.header_labels:
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
from app.services.schedule.freight_receipt_rpa_finalize import register_receipt_rpa_excel_headers
from app.services.schedule.freight_rpa_onhand_finalize import register_inventory_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,49 +0,0 @@
"""收料原样归档三年到期对象清理。"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import ShippingReceiptReportFile
from app.services.file_assets.storage import file_asset_storage
from app.services.shipping_notice.audit_service import append_shipping_audit_event
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。"""
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
now = datetime.utcnow()
rows = ShippingReceiptReportFile.query.filter(
ShippingReceiptReportFile.archive_expires_at.is_not(None),
ShippingReceiptReportFile.archive_expires_at <= now,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
).order_by(ShippingReceiptReportFile.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_shipping_audit_event(
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
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}],
)
success += 1
except Exception as exc:
errors.append(f'{report_file.id}: {exc}')
append_shipping_audit_event(
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
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}],
)
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'}]
@@ -1,11 +1,11 @@
"""
backend/app/services/schedule/shipping_receipt_rpa_archive.py
backend/app/services/schedule/freight_rpa_inbound_archive.py
用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingReceiptReportFile / ShippingReceiptRpaUnitRun、
file_asset_storage、timezone_util、freight_receipt_rpa_finalize.is_freight_receipt_rpa_task。
逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`;
用途:货代入站 RPA 排程 run 的原始入站 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、FreightRpaInboundReportFile / FreightRpaInboundUnitRun、
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。
"""
@@ -21,37 +21,37 @@ from typing import Any
from flask import current_app
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
from app.models import ScheduleRun, FreightRpaInboundReportFile, FreightRpaInboundUnitRun
from app.services.file_assets.storage import file_asset_storage
from app.services.schedule.freight_receipt_rpa_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。
"""
configured = ''
if current_app:
raw = current_app.config.get('FREIGHT_RPA_RECEIPT_ARCHIVE_DIR')
raw = current_app.config.get('FREIGHT_RPA_INBOUND_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_RECEIPT_ARCHIVE_DIR or '').strip()
configured = str(Config.FREIGHT_RPA_INBOUND_ARCHIVE_DIR or '').strip()
archive_dir = Path(configured)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
@@ -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,84 +98,84 @@ 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 的企微/下载展示名(对齐库存 inventory_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 下可打包的收料归档文件。
核心逻辑:join unit_run,过滤 archive_deleted_at 为空;按 file id 升序稳定序号。
Yields:
ShippingReceiptReportFile: 可从 MinIO 读取的归档记录。
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 = (
ShippingReceiptReportFile.query.join(
ShippingReceiptRpaUnitRun,
ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id,
FreightRpaInboundReportFile.query.join(
FreightRpaInboundUnitRun,
FreightRpaInboundReportFile.unit_run_id == FreightRpaInboundUnitRun.id,
)
.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
FreightRpaInboundUnitRun.schedule_run_id == run.id,
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.id.asc())
.order_by(FreightRpaInboundReportFile.id.asc())
.all()
)
for report_file in rows:
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,19 +217,19 @@ 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 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != '.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,12 +245,12 @@ 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、
且真实路径位于 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内;任一不满足则 404。
核心逻辑:读取 summary.raw_inbound_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
@@ -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,9 +1,11 @@
"""
backend/app/services/schedule/freight_receipt_rpa_finalize.py
backend/app/services/schedule/freight_rpa_inbound_finalize.py
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微。
依赖:ShippingReceiptRpaUnitRun、shipping_receipt_rpa_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom。
用途:独立入站 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。
依赖:FreightRpaInboundUnitRun、freight_rpa_inbound_archive、scheduler_service 企微通知。
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom;
超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。
"""
from __future__ import annotations
@@ -12,56 +14,58 @@ 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 ShippingReceiptRpaUnitRun
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_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_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
_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(
RECEIPT_RPA_JOB_KEY,
INBOUND_RPA_JOB_KEY,
_RECEIPT_RPA_HEADER_ORDER,
_RECEIPT_RPA_HEADER_LABELS,
)
def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> 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 升序的明细行。
@@ -79,7 +83,7 @@ def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> l
'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 '',
@@ -87,25 +91,25 @@ def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> l
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) == RECEIPT_RPA_JOB_KEY
and any(isinstance(row, dict) and row.get('status') == AWAITING_RECEIPT_RPA_CALLBACK_STATUS for row in step_logs or [])
and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY
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
@@ -114,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: 排程执行记录主键。
@@ -137,10 +141,10 @@ 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 = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
units = FreightRpaInboundUnitRun.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)
@@ -169,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:
@@ -182,7 +186,7 @@ def report_receipt_batch_progress(payload: dict) -> dict:
Returns:
dict: updated / rejected 及当前计数。
"""
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
if payload.get('schema_version') != INBOUND_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
@@ -195,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)),
@@ -224,18 +228,18 @@ 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 幂等返回。
"""
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
if payload.get('schema_version') != INBOUND_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 = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
unit = FreightRpaInboundUnitRun.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'}:
@@ -243,28 +247,28 @@ 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'}
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
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):
return {'finalized': False, 'reason': 'units_pending'}
@@ -280,9 +284,9 @@ 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()
header_order, header_labels = resolve_schedule_header(RECEIPT_RPA_JOB_KEY)
# [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
try:
@@ -296,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.shipping_receipt_rpa_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.shipping_receipt_rpa_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,
@@ -347,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:
@@ -356,32 +360,32 @@ 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_RECEIPT_TIMEOUT_SECONDS', 900)))
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'
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY
)
def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitRun]) -> datetime:
def _inbound_last_activity(run: ScheduleRun, units: list[FreightRpaInboundUnitRun]) -> datetime:
"""收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。
极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。
"""
@@ -394,57 +398,78 @@ def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitR
return max(stamps)
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。
def _fail_inbound_unit_with_timeout(
unit: FreightRpaInboundUnitRun, *, now: datetime, timeout_seconds: int,
run_no: str | None = None,
) -> None:
"""单个入站单元回调超时收口为失败并写审计(run 级与孤儿级回收共用的唯一实现)。
截止判据为最后活动锚(_receipt_last_activity)而非 run.started_at——
核心逻辑:错误码/错误文案/审计事件三者的单一事实来源——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.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',
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_inbound_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
"""将无回调的独立入站运行收口为失败,保留其单元与触发审计事实。
截止判据为最后活动锚(_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 = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
if _receipt_last_activity(run, units) > cutoff:
units = FreightRpaInboundUnitRun.query.filter_by(schedule_run_id=run.id).all()
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:
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.finished_at = now
append_shipping_audit_event(
event_type='shipping_receipt_rpa_callback_timeout', aggregate_type='shipping_receipt_unit',
aggregate_id=str(unit.id), run_no=run.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},
)
_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:
@@ -452,14 +477,57 @@ 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:
db.session.commit()
return recovered
def recover_all_stale_orphan_inbound_units() -> int:
"""回收按需触发(无排程绑定)的超时入站单元,解除来源投影永久 fetching。
【AI 触发时机】仅由排程队列每轮领取维护(queue_service)调用。调拨工作台
重试/自动调拨补抓创建的单元 schedule_run_id 为 NULL(见 inbound_trigger_service),
不在 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 级 _inbound_last_activity 是
笔间静默口径、刻意不含 created_at,两者语义不同)超过
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_inbound_rpa_unit)
原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。
[STEP 2] 逐单元经 _fail_inbound_unit_with_timeout 收口(failed +
RPA.INBOUND_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
绝不自动重试或重发——恢复走调拨工作台显式「重试 RPA」
(与 recover_stale_waiting_source_jobs 口径一致)。
Returns:
本次回收的单元数。
"""
timeout_seconds = _inbound_timeout_seconds()
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
orphans = (
FreightRpaInboundUnitRun.query
.filter(
FreightRpaInboundUnitRun.schedule_run_id.is_(None),
FreightRpaInboundUnitRun.status.in_(('queued', 'awaiting_rpa', 'processing')),
func.coalesce(FreightRpaInboundUnitRun.started_at, FreightRpaInboundUnitRun.created_at) < cutoff,
)
.all()
)
if not orphans:
return 0
now = datetime.utcnow()
for unit in orphans:
_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_receipt_rpa_job.py
backend/app/services/schedule/freight_rpa_inbound_job.py
用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。
依赖:receipt_rpa.write_receipt_export_batch_trigger、assert_receipt_rpa_worker_ready、
ShippingInventorySource / ShippingReceiptReportConfig / ShippingReceiptRpaUnitRun、
用途:独立入站 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-receipt-rpa 调用本 handler;写 trigger 前 fail-fast;
口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。
逻辑:job_registry 的 freight-rpa-inbound 调用本 handler;写 trigger 前 fail-fast;
口径与 onhand 排程一致(选中 N 源 → N unit),query_parameters 原样下发。
"""
from __future__ import annotations
@@ -16,20 +16,20 @@ from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
from app.services.shipping_notice.rpa_worker_heartbeat import (
from app.models import ScheduleRun, ScheduleTask, FreightRpaSource, FreightRpaInboundReportConfig, FreightRpaInboundUnitRun
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,
)
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
INBOUND_RPA_JOB_KEY = 'freight-rpa-inbound'
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):
@@ -37,17 +37,17 @@ def _wanted_source_codes(task: ScheduleTask) -> set[str]:
return {str(value).strip().upper() for value in values if str(value).strip()}
def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]:
"""读取已启用且已配置收料报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
def _eligible_sources(task: ScheduleTask) -> list[tuple[FreightRpaSource, FreightRpaInboundReportConfig]]:
"""读取已启用且已配置入站报表的站点;不依赖库存报表路径、解析绑定或 Warehouse 条件。"""
wanted = _wanted_source_codes(task)
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True)).all()
rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join(
FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.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: ShippingReceiptReportConfig) -> list[dict[str, Any]]:
"""浅拷贝收料查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
def _copy_query_parameters(config: FreightRpaInboundReportConfig) -> list[dict[str, Any]]:
"""浅拷贝入站查询条件原样入快照;空列表表示 Worker 使用页面默认、不填 Warehouse。"""
return [
dict(item) for item in (config.query_parameters_json or [])
if isinstance(item, dict)
@@ -55,25 +55,25 @@ def _copy_query_parameters(config: ShippingReceiptReportConfig) -> list[dict[str
def _build_unit(
source: ShippingInventorySource, config: ShippingReceiptReportConfig, schedule_run_id: int,
) -> ShippingReceiptRpaUnitRun:
"""冻结可审计的收料执行单元(一源一单元);DBS 日期字段不进入查询快照。"""
callback_id = f'receipt:{uuid.uuid4().hex}'
source: FreightRpaSource, config: FreightRpaInboundReportConfig, schedule_run_id: int,
) -> FreightRpaInboundUnitRun:
"""冻结可审计的入站执行单元(一源一单元);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),
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
}
return ShippingReceiptRpaUnitRun(
schedule_run_id=schedule_run_id, inventory_source_id=source.id, source_code=source.source_code,
return FreightRpaInboundUnitRun(
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: ShippingReceiptRpaUnitRun) -> dict[str, Any]:
def _serialize_trigger_unit(unit: FreightRpaInboundUnitRun) -> dict[str, Any]:
"""生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 receipt trigger 下发。"""
source = unit.inventory_source
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'receipt source profile unavailable: {unit.source_code}')
@@ -98,27 +98,27 @@ def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> 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[ShippingReceiptRpaUnitRun] = [
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,23 +134,23 @@ 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_receipt_export_batch_trigger(run.run_no, trigger_units, {
'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': 'shipping_receipt_rpa.v1',
trigger_path = write_inbound_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.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)},
}]
@@ -0,0 +1,23 @@
"""收料原样归档三年到期对象清理(排程壳)。
批次 R Task 10 起,清理能力本体已下沉 freight_rpa.inbound.report_archive
(run_freight_rpa_inbound_retention_schedule,函数名 receipt 词根→inbound);
本文件仅保留排程平台 Job 处理器接缝(job_registry 按 schedule 包路径注册,
Task 11 已随排程壳平移改名为 freight_rpa_inbound_retention,git mv 保留历史)。
"""
from __future__ import annotations
from typing import Any
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 执行三年保留清理(行为不变)。
核心逻辑:本函数与 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)
@@ -1,8 +1,8 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_archive.py
backend/app/services/schedule/freight_rpa_onhand_archive.py
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
依赖:ScheduleRun、FreightRpaOnhandReportFile、freight_rpa_onhand_finalize.is_shipping_inventory_rpa_task。
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」;
完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。
@@ -21,8 +21,8 @@ from flask import current_app
from app import db
from app.core.errors import NotFoundError
from app.models import ScheduleRun, ShippingInventoryFile
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
from app.models import ScheduleRun, FreightRpaOnhandReportFile
from app.services.schedule.freight_rpa_onhand_finalize import is_shipping_inventory_rpa_task
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
@@ -39,14 +39,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
def get_inventory_archive_dir() -> str:
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
archive_dir = Path(
current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
current_app.config.get("FREIGHT_RPA_ONHAND_ARCHIVE_DIR")
if current_app
else ""
)
if not str(archive_dir):
from app.core.config.settings import Config
archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
archive_dir = Path(Config.FREIGHT_RPA_ONHAND_ARCHIVE_DIR)
archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir)
@@ -137,12 +137,13 @@ def _iter_packable_inventory_files(
created: list[dict[str, Any]] | None = None,
):
"""
遍历可实际打包的库存快照。
遍历可实际打包的库存文件。
核心逻辑:需存在 ShippingInventoryFile 且 storage_path 指向可读文件。
核心逻辑:优先 FreightRpaOnhandReportFile(解析入库后);若无 inventory_file_no
则回退 created.file_path(HTTP 文件返回即终态时的收件副本)。
Yields:
tuple[dict, ShippingInventoryFile, Path]: created 项、快照记录、可读路径。
tuple[dict, FreightRpaOnhandReportFile | None, Path]: created 项、快照记录(可空)、可读路径。
"""
if not is_shipping_inventory_rpa_task(getattr(run, "task", None)):
return
@@ -150,22 +151,28 @@ def _iter_packable_inventory_files(
items = _normalize_created_items(created) if created is not None else _api_response_created(run)
for item in items:
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
if not inventory_file_no:
if inventory_file_no:
inv_file = (
db.session.query(FreightRpaOnhandReportFile)
.filter(FreightRpaOnhandReportFile.onhand_file_no == inventory_file_no)
.first()
)
if not inv_file:
continue
storage_path = Path(str(inv_file.storage_path or "").strip())
if not storage_path.is_file():
continue
yield item, inv_file, storage_path
continue
inv_file = (
db.session.query(ShippingInventoryFile)
.filter(ShippingInventoryFile.inventory_file_no == inventory_file_no)
.first()
)
if not inv_file:
# RPA 文件返回即终态:尚无快照号时用回调/收件副本路径打包。
file_path = str(item.get("file_path") or "").strip()
if not file_path:
continue
storage_path = Path(str(inv_file.storage_path or "").strip())
storage_path = Path(file_path)
if not storage_path.is_file():
continue
yield item, inv_file, storage_path
yield item, None, storage_path
def inventory_raw_zip_available_from_summary(summary: dict[str, Any] | None) -> bool:
@@ -208,8 +215,12 @@ def persist_inventory_rpa_raw_zip_archive(
with zipfile.ZipFile(archive_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:
for zip_index, (item, inv_file, storage_path) in enumerate(packable_files, start=1):
inventory_file_no = str(item.get("inventory_file_no") or "").strip()
source_code = str(item.get("source_code") or inv_file.source_code or "").strip()
warehouse_id = str(item.get("warehouse_id") or inv_file.warehouse_id or "").strip()
source_code = str(
item.get("source_code") or (getattr(inv_file, "source_code", None) or "")
).strip()
warehouse_id = str(
item.get("warehouse_id") or (getattr(inv_file, "warehouse_id", None) or "")
).strip()
entry_name = _build_zip_entry_name(
index=zip_index,
source_code=source_code,
@@ -217,12 +228,16 @@ def persist_inventory_rpa_raw_zip_archive(
original_suffix=storage_path.suffix or ".xlsx",
)
archive.write(storage_path, arcname=entry_name)
original_name = (
str(getattr(inv_file, "source_file_name", None) or "").strip()
or storage_path.name
)
files_manifest.append({
"inventory_file_no": inventory_file_no,
"source_code": source_code,
"warehouse_id": warehouse_id,
"file_name": entry_name,
"original_file_name": inv_file.source_file_name or storage_path.name,
"original_file_name": original_name,
})
manifest = {
@@ -251,7 +266,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
"""
校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_ONHAND_ARCHIVE_DIR 内。
"""
resolved = zip_path.resolve()
if resolved.suffix.lower() != ".zip":
@@ -272,7 +287,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
且真实路径位于 FREIGHT_RPA_ONHAND_ARCHIVE_DIR 内;任一不满足则 404。
Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
@@ -1,10 +1,12 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_finalize.py
backend/app/services/schedule/freight_rpa_onhand_finalize.py
用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。
逻辑:shipping_inventory_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize;
run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common、
freight_rpa.onhand.workflow_protocol(结果状态归一)。
逻辑:freight_rpa_onhand_job 写 trigger 后 defer;HTTP batch-ready 按 RPA 导出结果 finalize
(文件返回即 RPA/排程结束);解析 Job 可后置且不得重新打开 awaiting;
run_task_now / cron 启动前回收超时 awaiting run。
"""
from __future__ import annotations
@@ -21,7 +23,7 @@ from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import normalize_platform_api_path
from app.services.shipping_notice.tool_common import rpa_inventory_timeout_seconds
SHIPPING_INVENTORY_RPA_JOB_KEY = "shipping-inventory-rpa"
ONHAND_RPA_JOB_KEY = "freight-rpa-onhand"
AWAITING_RPA_CALLBACK_STATUS = "awaiting_rpa_callback"
FinalizeScheduleRunResult = dict[str, Any]
@@ -52,7 +54,7 @@ def register_inventory_rpa_excel_headers() -> None:
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
"""
register_schedule_header(
SHIPPING_INVENTORY_RPA_JOB_KEY,
ONHAND_RPA_JOB_KEY,
_INVENTORY_RPA_HEADER_ORDER,
_INVENTORY_RPA_HEADER_LABELS,
)
@@ -78,7 +80,7 @@ def is_shipping_inventory_rpa_task(task: ScheduleTask | None) -> bool:
"""判断是否为货代库存 RPA 平台排程任务。"""
if not task or task.schedule_type != "platform_job":
return False
return normalize_platform_api_path(task.platform_api_path) == SHIPPING_INVENTORY_RPA_JOB_KEY
return normalize_platform_api_path(task.platform_api_path) == ONHAND_RPA_JOB_KEY
def is_awaiting_rpa_callback(step_logs: list | None) -> bool:
@@ -111,6 +113,82 @@ def _compute_run_status(*, total_count: int, success_count: int, failed_count: i
return "partial_failed"
def map_rpa_batch_results_for_schedule_finalize(
results: list[Any] | None,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
"""把 Worker batch results 映射为排程 finalize 的 created/failed/skipped。
【AI 触发时机】:HTTP onhand-batch-ready 收件后、入队解析 Job 前调用;
只认 RPA 导出成败(含 file_path),不依赖解析入库后的 inventory_file_no。
Args:
results: Worker 回调 results 列表。
Returns:
(created, failed, skipped):供 finalize_shipping_inventory_schedule_run 使用。
"""
from app.services.freight_rpa.onhand.workflow_protocol import normalize_inventory_batch_item_status
created: list[dict[str, Any]] = []
failed: list[dict[str, Any]] = []
skipped: list[dict[str, Any]] = []
for raw in results or []:
if not isinstance(raw, dict):
continue
source_code = str(raw.get("source_code") or "").strip().upper()
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
status = normalize_inventory_batch_item_status(raw)
if status == "success":
created.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"inventory_file_no": str(raw.get("inventory_file_no") or "").strip(),
"file_path": str(raw.get("file_path") or "").strip(),
})
continue
if status == "skipped":
skipped.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"skip_reason": str(raw.get("skip_reason") or raw.get("reason") or "skipped")[:200],
"message": str(raw.get("message") or raw.get("error_message") or "")[:500],
})
continue
failed.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"error": str(
raw.get("error") or raw.get("error_message") or raw.get("message") or "rpa_export_failed"
)[:500],
})
return created, failed, skipped
def finalize_shipping_inventory_schedule_run_from_rpa_results(
schedule_run_id: int,
payload: dict[str, Any],
) -> FinalizeScheduleRunResult:
"""按 RPA 导出结果终态化排程(文件返回即结束,不等解析)。
核心逻辑:map Worker results → finalize;解析 Job 稍后仍可入库,但不得重新 awaiting。
Args:
schedule_run_id: ScheduleRun 主键。
payload: 已收件的 batch-ready 载荷(含 results)。
Returns:
FinalizeScheduleRunResult: 与 finalize_shipping_inventory_schedule_run 同形。
"""
created, failed, skipped = map_rpa_batch_results_for_schedule_finalize(payload.get("results"))
return finalize_shipping_inventory_schedule_run(
schedule_run_id,
created=created,
failed=failed,
skipped=skipped,
payload=payload,
)
def _build_finalize_details(
pending_details: list[dict[str, Any]],
*,
@@ -276,7 +354,7 @@ def _try_recover_stale_awaiting_run(
finished_at = datetime.utcnow()
step_logs = list(run.step_logs or [])
step_logs.append({
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": "failed",
"detail": {"message": "RPA 库存导出等待超时", "timeout_seconds": timeout_seconds},
})
@@ -468,7 +546,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
)
register_inventory_rpa_excel_headers()
header_order, header_labels = resolve_schedule_header(SHIPPING_INVENTORY_RPA_JOB_KEY)
header_order, header_labels = resolve_schedule_header(ONHAND_RPA_JOB_KEY)
excel_export_ok = True
try:
file_data, file_name, file_size = export_schedule_result_excel(
@@ -495,13 +573,13 @@ def _finalize_shipping_inventory_schedule_run_impl(
status = "partial_failed"
else:
# 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name
from app.services.schedule.freight_rpa_onhand_archive import inventory_rpa_result_excel_name
file_name = inventory_rpa_result_excel_name(run)
step_logs = list(run.step_logs or [])
step_logs.append({
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": "success" if status == "success" else "failed" if status == "failed" else "partial_failed",
"detail": {
"created_count": success_count,
@@ -537,7 +615,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
"raw_inventory_zip_size": 0,
}
try:
from app.services.schedule.shipping_inventory_rpa_archive import persist_inventory_rpa_raw_zip_archive
from app.services.schedule.freight_rpa_onhand_archive import persist_inventory_rpa_raw_zip_archive
archive_summary = persist_inventory_rpa_raw_zip_archive(run, created=created)
except Exception as archive_exc:
@@ -1,10 +1,10 @@
"""
backend/app/services/schedule/shipping_inventory_rpa_job.py
backend/app/services/schedule/freight_rpa_onhand_job.py
用途:排程触发货代库存 RPA 批量导出(每个 Inventory Source 一次执行)。
依赖:inventory_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用;
写 trigger 后返回 awaiting_rpa_callback;终态由 shipping_inventory_rpa_finalize 在 RPA 回调时写入。
依赖:onhand_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
逻辑:platform_api_path=freight-rpa-onhand 时由 job_registry 调用;
写 trigger 后返回 awaiting_rpa_callback;终态由 freight_rpa_onhand_finalize 在 RPA 回调时写入。
"""
from __future__ import annotations
@@ -16,10 +16,10 @@ from typing import Any
from app import db
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
from app.services.shipping_notice.rpa_worker_heartbeat import (
from app.services.schedule.freight_rpa_onhand_finalize import AWAITING_RPA_CALLBACK_STATUS
from app.services.shipping_notice.onhand_source_repository import list_database_inventory_sources
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
from app.services.freight_rpa.common.worker_heartbeat import (
RPA_WORKER_OFFLINE_MESSAGE,
assert_inventory_rpa_worker_ready,
)
@@ -105,21 +105,21 @@ def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]:
return enabled
def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
def run_freight_rpa_onhand_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
写入批量库存 RPA trigger,由 worker 异步导出并在 callback 入库。
核心逻辑:写 trigger 后返回 awaiting_rpa_callback;终态由 finalize 在回调时写入。
"""
sources = _filter_sources(task)
step_logs: list[dict[str, Any]] = [{
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": "started",
"detail": {"source_count": len(sources)},
}]
if not sources:
message = "no enabled inventory sources"
step_logs.append({"step": "shipping_inventory_rpa", "status": "skipped", "detail": {"message": message}})
step_logs.append({"step": "freight_rpa_onhand", "status": "skipped", "detail": {"message": message}})
return 0, 0, 0, 1, [], [message], step_logs
run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
@@ -139,7 +139,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
message = str(exc.message or RPA_WORKER_OFFLINE_MESSAGE)
detail_message = str((exc.details or {}).get("detail_message") or message)
step_logs.append({
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": "failed",
"detail": {
"message": message,
@@ -151,7 +151,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
return len(sources), 0, len(sources), 0, [], [detail_message], step_logs
if not trigger_path:
message = "inventory RPA trigger dir not configured"
step_logs.append({"step": "shipping_inventory_rpa", "status": "failed", "detail": {"message": message}})
step_logs.append({"step": "freight_rpa_onhand", "status": "failed", "detail": {"message": message}})
return len(sources), 0, len(sources), 0, [], [message], step_logs
run.api_request_json = {
@@ -162,7 +162,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
db.session.commit()
step_logs.append({
"step": "shipping_inventory_rpa",
"step": "freight_rpa_onhand",
"status": AWAITING_RPA_CALLBACK_STATUS,
"detail": {"trigger_path": trigger_path, "run_no": run_no},
})
@@ -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'}]
@@ -1,15 +1,19 @@
"""自动调拨排程。
用途:自动处理当日新成熟可调拨项与历史可恢复异常;执行结果通知统一走
用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走
排程「启用通知」通用企微通知,本任务不自建领域通知。
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)、
inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、
date_policy(业务日与日期解析)。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
不依赖其他排程成功;来源留空兜底为全部启用收料来源;可选收料日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层;
空数据日(无 run_no 且无 errors)置 domain_notification_managed 保持
静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎
只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置
偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(无
run_no 且无 errors)置 domain_notification_managed 保持静默(C5),有
Run 或硬失败交由框架完成卡按排程「启用通知」发送。
"""
from __future__ import annotations
@@ -21,7 +25,7 @@ from app.models import ScheduleRun, ScheduleTask
from app.services.in_transit_transfer import deps as transfer_deps
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
from app.services.schedule.job_registry import ScheduleExecuteResult
@@ -31,12 +35,12 @@ def _task_params(task: ScheduleTask) -> dict[str, Any]:
def _wanted_source_codes(task: ScheduleTask) -> list[str]:
"""提取结构化 source_codes;留空回落为全部启用且已配置收料报表的来源。
"""提取结构化 source_codes;留空回落为全部启用且已配置收料报表(入站证据)的来源。
Args:
task: 排程任务(job_params.source_codes 可为列表/字符串/缺省)。
Returns:
去空白后的来源编码列表;留空时为 list_receipt_capable_source_codes() 结果。
去空白后的来源编码列表;留空时为 list_inbound_capable_source_codes() 结果。
"""
params = _task_params(task)
values = params.get("source_codes") or []
@@ -44,12 +48,12 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
values = [values]
codes = [str(item).strip() for item in values if str(item).strip()]
if not codes:
codes = list_receipt_capable_source_codes()
codes = list_inbound_capable_source_codes()
return codes
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
"""把「T−N 偏移天数」参数换算为执行日口径的具体收料日期(T−N)。
"""把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。
Args:
business_date: 业务日期 T(YYYY-MM-DD)。
@@ -79,10 +83,11 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
可选收料日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
偏移非法(负数/小数/非数字)快速失败不执行;范围越界由匹配层
ValidationError 落 errors 走硬失败路径。
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
成熟积压,偏移终点 0/1(T−1/当天)由匹配层 ValidationError 落 errors 走
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
Args:
task: 排程任务(job_params: source_codes/recover_history/
@@ -99,21 +104,27 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
# 防止坏参数被静默忽略后退化成全量积压处理。
param_errors: list[str] = []
receipt_date_from = _offset_to_date(
business_date, params.get("receipt_from_offset_days"), "收料日期起点", param_errors)
receipt_date_to = _offset_to_date(
business_date, params.get("receipt_to_offset_days"), "收料日期终点", param_errors)
movement_date_from = _offset_to_date(
business_date, params.get("receipt_from_offset_days"), "异动日期起点", param_errors)
movement_date_to = _offset_to_date(
business_date, params.get("receipt_to_offset_days"), "异动日期终点", param_errors)
if param_errors:
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
deps = transfer_deps.get_transfer_dependencies()
# [出生翻转 2026-10-14] 调拨类型配置化(D8 匹配创建必填):排程参数
# job_params.transfer_type 承载类型编码,原样透传匹配层;缺省 None 时
# 匹配层 fail-closed(TRANSFER_TYPE_REQUIRED 随 errors 硬失败透出),
# 不回落固定类型(类型=平台配置,排程不隐式假设)。
transfer_type = str(params.get("transfer_type") or "").strip() or None
outcome = run_auto_transfer(
business_date=business_date,
deps=deps,
source_codes=source_codes,
recover_history=recover_history,
receipt_date_from=receipt_date_from,
receipt_date_to=receipt_date_to,
movement_date_from=movement_date_from,
movement_date_to=movement_date_to,
transfer_type=transfer_type,
)
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
+28 -13
View File
@@ -2,9 +2,10 @@
backend/app/services/schedule/job_options.py
用途:平台任务参数 schema 的动态选项来源(options_source → 统一 label/value 列表)。
依赖:models.Agent、shipping_notice.inventory_source_repository。
依赖: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 与 freight_rpa_outbound_sources。
"""
from __future__ import annotations
@@ -33,9 +34,9 @@ def _agent_apps_options() -> list[dict[str, Any]]:
]
def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
"""启用中的货代库存源(value=source_code,来自数据库主数据)。"""
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
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 [
{
@@ -51,16 +52,29 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
]
def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置收料报表的站点,供独立收料排程选择。"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
def _freight_rpa_inbound_sources_options() -> list[dict[str, Any]]:
"""已启用且已配置入站报表的站点,供独立入站排程选择。"""
from app.models import FreightRpaSource, FreightRpaInboundReportConfig
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True)).all()
rows = db.session.query(FreightRpaSource, FreightRpaInboundReportConfig).join(
FreightRpaInboundReportConfig, FreightRpaInboundReportConfig.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} · 收料已配置',
'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]
@@ -101,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,
"shipping_inventory_sources": _shipping_inventory_sources_options,
"shipping_receipt_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,
}
+1 -1
View File
@@ -133,7 +133,7 @@ def validate_task_params(
[STEP 4] check_options=True 时校验 select/multi_select 值在选项范围内。
Args:
task_type: platform job key(如 shipping-inventory-rpa)。
task_type: platform job key(如 freight-rpa-onhand)。
job_params: 前端提交或 task.job_params 存储的参数 dict;None 视为空。
check_options: 是否联动 options_source 校验取值范围;执行期建议 False(选项可能漂移)。
+48 -27
View File
@@ -2,7 +2,7 @@
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:shipping_inventory_rpa_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 通用渲染。
"""
@@ -34,7 +34,7 @@ class PlatformJobDefinition:
"label_key": "...", # 前端 i18n key(可选)
"required": False,
"default": [],
"options_source": "shipping_inventory_sources", # select/multi_select 动态选项来源(可选)
"options_source": "freight_rpa_sources", # select/multi_select 动态选项来源(可选)
"placeholder": "...", "placeholder_key": "...",
"help": "...", "help_key": "...",
}
@@ -44,7 +44,7 @@ class PlatformJobDefinition:
label: str
handler: PlatformJobHandler
description: str = ""
# 前端 i18n key(如 admin.schedule.form.platformJobShippingInventory);
# 前端 i18n key(如 admin.schedule.form.platformJobFreightRpaOnhand);
# 前端下拉优先 $t(label_key),label 仅作 fallback/debug。
label_key: str = ""
description_key: str = ""
@@ -132,9 +132,11 @@ def _register_builtin_platform_jobs() -> None:
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
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.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
from app.services.schedule.freight_receipt_rpa_retention_job import run_freight_receipt_rpa_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_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,
@@ -371,48 +373,67 @@ def _register_builtin_platform_jobs() -> None:
defaults={"hash_sample_limit": 500, "dry_run": True, "limit": 1},
))
register_platform_job(PlatformJobDefinition(
key="shipping-inventory-rpa",
key="freight-rpa-onhand",
label="货代库存 RPA",
label_key="admin.schedule.form.platformJobShippingInventory",
handler=run_shipping_inventory_rpa_schedule,
label_key="admin.schedule.form.platformJobFreightRpaOnhand",
handler=run_freight_rpa_onhand_schedule,
description="按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。",
description_key="admin.schedule.form.shippingInventoryJobHint",
description_key="admin.schedule.form.freightRpaOnhandJobHint",
category="shipping",
params_schema=(
{
"key": "source_codes",
"type": "multi_select",
"label": "库存源",
"label_key": "admin.schedule.form.shippingInventorySources",
"label_key": "admin.schedule.form.freightRpaSources",
# 兼容历史任务语义:留空 = 导出全部启用库存源,故不设 required
"required": False,
"default": [],
"options_source": "shipping_inventory_sources",
"options_source": "freight_rpa_sources",
"placeholder": "留空则导出全部启用库存源",
"placeholder_key": "admin.schedule.form.shippingInventorySourcesPlaceholder",
"placeholder_key": "admin.schedule.form.freightRpaSourcesPlaceholder",
"help": "选择需要执行的库存源;选项来自库存源配置,留空则全部执行。",
"help_key": "admin.schedule.form.shippingInventorySourcesHelp",
"help_key": "admin.schedule.form.freightRpaSourcesHelp",
},
),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key="freight-receipt-rpa",
label="货代收料 RPA",
handler=run_freight_receipt_rpa_schedule,
description="按计划从已配置收料报表的站点导出并归档收料文件。",
key="freight-rpa-inbound",
label="货代入站 RPA",
handler=run_freight_rpa_inbound_schedule,
description="按计划从已配置入站报表的站点导出并归档入站文件。",
category="shipping",
params_schema=({
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
"default": [], "options_source": "shipping_receipt_sources",
"help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。",
"key": "source_codes", "type": "multi_select", "label": "入站站点", "required": False,
"default": [], "options_source": "freight_rpa_inbound_sources",
"help": "选择需要执行的入站站点;留空则执行所有已启用入站配置。",
},),
defaults={"source_codes": []},
))
register_platform_job(PlatformJobDefinition(
key='freight-receipt-rpa-retention', label='货代收料归档到期清理',
handler=run_freight_receipt_rpa_retention_schedule,
description='仅删除已过三年保留期的收料对象,保留运行、文件事实和审计记录。', category='shipping',
key='freight-rpa-inbound-retention', label='货代入站归档到期清理',
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(
@@ -596,7 +617,7 @@ def _register_builtin_platform_jobs() -> None:
"label_key": "admin.schedule.form.transferSourceCodes",
"required": False,
"default": [],
"options_source": "shipping_inventory_sources",
"options_source": "freight_rpa_sources",
},
{
"key": "recover_history",
@@ -612,7 +633,7 @@ def _register_builtin_platform_jobs() -> None:
"label": "收料日期起(T-N)",
"label_key": "admin.schedule.form.transferReceiptDateFrom",
"required": False,
"help": "填天数 N,按执行日换算收料日期下限 T−N;例:4=从 T−4 起。留空=全部成熟积压(默认 ≤ T-2)。",
"help": "填天数 N,按执行日换算异动日期下限 T−N;例:4=从 T−4 起。留空=全部积压。",
},
{
"key": "receipt_to_offset_days",
@@ -620,7 +641,7 @@ def _register_builtin_platform_jobs() -> None:
"label": "收料日期止(T-N)",
"label_key": "admin.schedule.form.transferReceiptDateTo",
"required": False,
"help": "填天数 N,按执行日换算收料日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于成熟上限(默认 T-2)。",
"help": "填天数 N,按执行日换算异动日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于执行日业务日期。",
},
),
defaults={"source_codes": [], "recover_history": True},
+27 -5
View File
@@ -1,3 +1,11 @@
"""
backend/app/services/schedule/query_service.py
用途:排程任务与运行记录的查询/序列化。
依赖:ScheduleRun / ScheduleTask、库存/入站/出站 raw-zip 可用性判定。
逻辑:list_tasks / get_run / serialize_run 供管理端排程工作台与下载按钮读取。
执行记录日期窗用 coalesce(started_at, created_at),排队中尚未开始的 run 仍落在创建日。
"""
from __future__ import annotations
from datetime import datetime, timezone
@@ -9,8 +17,9 @@ from sqlalchemy.orm import joinedload
from app import db
from app.models import ScheduleRun, ScheduleTask
from app.core.response import utc_iso
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_onhand_archive import inventory_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 +70,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 +96,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,
@@ -149,6 +160,15 @@ def list_runs(
started_before: Optional[datetime] = None,
limit: int = 100,
) -> list[dict]:
"""
按任务、状态与时间窗列出执行记录。
核心逻辑:时间窗比较 coalesce(started_at, created_at)。手动入队时 started_at 仍为空,
若只比 started_at,工作台默认「今天」会把排队中的 run 滤掉,再次点击则因活动 run 冲突。
Returns:
序列化后的运行记录,按 created_at 倒序,最多 500 条。
"""
query = db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
if task_id is not None:
query = query.filter(ScheduleRun.schedule_task_id == task_id)
@@ -156,10 +176,12 @@ def list_runs(
query = query.filter(ScheduleTask.name.ilike(f'%{schedule_name}%'))
if status:
query = query.filter(ScheduleRun.status == status)
# 排队 run 还没有 started_at,用创建时间落入同一日期窗,避免工作台看起来像没触发。
activity_at = func.coalesce(ScheduleRun.started_at, ScheduleRun.created_at)
if started_after is not None:
query = query.filter(ScheduleRun.started_at >= _as_naive_utc(started_after))
query = query.filter(activity_at >= _as_naive_utc(started_after))
if started_before is not None:
query = query.filter(ScheduleRun.started_at < _as_naive_utc(started_before))
query = query.filter(activity_at < _as_naive_utc(started_before))
if owner_user_id is not None:
query = query.filter(ScheduleTask.owner_user_id == owner_user_id)
if notify_user_id is not None:
+41 -17
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。
@@ -19,14 +20,20 @@ from app import db
from app.jobs.queue import enqueue, fail_job, finish_job, recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job, ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import (
from app.services.schedule.freight_rpa_onhand_finalize import (
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.freight_receipt_rpa_finalize import (
recover_all_stale_receipt_rpa_schedule_runs,
recover_stale_receipt_rpa_schedule_runs,
is_awaiting_receipt_rpa_schedule_run,
from app.services.schedule.freight_rpa_inbound_finalize import (
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
@@ -232,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 = (
@@ -286,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)
@@ -331,12 +340,12 @@ def prepare_schedule_queue() -> int:
if not _worker_initialized:
# [STEP 1] 兼容升级前由 Web 线程留下的 running 记录;无活动 Job 承接时标记中断。
from app.services.schedule.shipping_inventory_rpa_finalize import is_awaiting_rpa_schedule_run
from app.services.schedule.freight_rpa_onhand_finalize import is_awaiting_rpa_schedule_run
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)
@@ -357,7 +366,7 @@ def prepare_schedule_queue() -> int:
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered:
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
from app.services.freight_rpa.onhand.callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
@@ -370,7 +379,7 @@ def prepare_schedule_queue() -> int:
# 调拨来源等待回调 Job 的超时回收与下方 RPA 心跳告警同属每轮领取维护:
# 不能挂在 worker 启动一次性分支里,否则进程长期驻留期间超时任务永远无法终态化。
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
from app.services.in_transit_transfer.inbound_callback_bridge import recover_stale_waiting_source_jobs
transfer_stale = recover_stale_waiting_source_jobs()
if transfer_stale:
@@ -378,13 +387,28 @@ def prepare_schedule_queue() -> int:
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_receipt_rpa_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)
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_rpa_inbound_finalize。
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_inbound_units()
if 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.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
from app.services.freight_rpa.common.worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=False)
except Exception as exc:
@@ -23,13 +23,14 @@ VALID_DATA_PIPELINE_SOURCES = frozenset({DATA_SOURCE_DATABASE, DATA_SOURCE_EXTER
LEGACY_SCHEDULE_TYPES = frozenset({"platform_app", "dify_app"})
# 仍在导入 JSON 里出现的历史 data_source。货代在手任务的旧键已由 s17c 整列改写,
# 运行期只认 platform job key freight-rpa-onhand。
LEGACY_DATA_SOURCE_TO_PLATFORM_JOB = {
"shipping_inventory_rpa": "shipping-inventory-rpa",
"faq_hot_aggregate": "faq-aggregate-hot",
}
# 允许写 ScheduleTaskConfig 的 platform_job(其余平台任务仅存 cron + job key,禁配置)
PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"shipping-inventory-rpa"})
PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"freight-rpa-onhand"})
def platform_job_allows_config(key: str | None) -> bool:
@@ -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;
@@ -18,22 +20,27 @@ from typing import Any
from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, User
from app.models import ScheduleRun, ScheduleTask, FreightRpaInboundReportFile, User
from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path
from app.services.schedule.freight_receipt_rpa_job import RECEIPT_RPA_JOB_KEY
from app.services.schedule.shipping_inventory_rpa_finalize import (
from app.services.schedule.freight_rpa_inbound_job import INBOUND_RPA_JOB_KEY
from app.services.schedule.freight_rpa_onhand_finalize import (
apply_deferred_schedule_run_state,
is_awaiting_rpa_schedule_run,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
from app.services.schedule.freight_receipt_rpa_finalize import (
apply_deferred_receipt_schedule_run_state,
recover_stale_receipt_rpa_schedule_runs,
should_defer_receipt_schedule_run,
from app.services.schedule.freight_rpa_inbound_finalize import (
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.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_onhand_archive import inventory_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,38 +125,41 @@ 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[ShippingReceiptReportFile]:
def _inbound_report_files_for_run(run: ScheduleRun) -> list[FreightRpaInboundReportFile]:
"""
收集收料排程 run 名下可投递的收料报表文件;非收料任务返回空列表。
收集入站排程 run 名下可投递的入站报表文件;非收料任务返回空列表。
核心逻辑:按 platform_api_path 识别收料排程,返回该 run 全部单元已归档且
核心逻辑:按 platform_api_path 识别入站排程,返回该 run 全部单元已归档且
未被清理(archive_deleted_at 为空)的报表文件。企微完成通知已改为发 ZIP,
本函数保留给管理员单文件重发等旁路读取。
"""
from app.models import ShippingReceiptRpaUnitRun
from app.models import FreightRpaInboundUnitRun
task = run.task
if (
task is None
or task.schedule_type != 'platform_job'
or normalize_platform_api_path(task.platform_api_path) != RECEIPT_RPA_JOB_KEY
or normalize_platform_api_path(task.platform_api_path) != INBOUND_RPA_JOB_KEY
):
return []
return (
ShippingReceiptReportFile.query.join(
ShippingReceiptRpaUnitRun, ShippingReceiptReportFile.unit_run_id == ShippingReceiptRpaUnitRun.id,
FreightRpaInboundReportFile.query.join(
FreightRpaInboundUnitRun, FreightRpaInboundReportFile.unit_run_id == FreightRpaInboundUnitRun.id,
)
.filter(
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
ShippingReceiptReportFile.archive_deleted_at.is_(None),
FreightRpaInboundUnitRun.schedule_run_id == run.id,
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
)
.order_by(ShippingReceiptReportFile.id)
.order_by(FreightRpaInboundReportFile.id)
.all()
)
@@ -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)
@@ -171,13 +182,16 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
from app.services.schedule.freight_rpa_onhand_archive import inventory_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,
@@ -238,7 +252,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
raw_zip_media_id = None
raw_zip_file_name = None
try:
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
from app.services.schedule.freight_rpa_onhand_archive import resolve_inventory_raw_zip_download
raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run)
raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name)
@@ -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.shipping_receipt_rpa_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,
)
@@ -16,7 +16,7 @@ from app.services.shipping_notice.line_auto_fulfill_coordinator import (
coordinate_post_ot_auto_fulfill,
enqueue_post_ot_auto_fulfill_job,
)
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.line_onhand_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
list_eligible_post_ot_snapshot_line_ids,
)
@@ -5,7 +5,7 @@ services/shipping_notice/auto_progress_controller.py
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务;
process_gate_job_service.cancel_inventory_external_wait_polls(显式回到库存准备时终止轮询)。
逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job
在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 inventory_preparation 时
在同一数据库事务落库。retry_rpa 或 manual_override_source 定向回 onhand_preparation 时
覆盖 waiting_external 残留 poll 并入队准备动作(改源默认 auto 复用指定源快照)。
库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
"""
@@ -22,7 +22,7 @@ from app import db
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Job, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.onhand_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate
from app.services.shipping_notice.tool_common import log_task_event
@@ -149,8 +149,8 @@ def determine_formal_start_gate(
return 'field_conflict_resolution'
candidate = candidate_set if candidate_set is not None else get_active_candidate_set(task)
if candidate is None or str(getattr(candidate, 'lifecycle_status', '') or '').lower() != 'frozen':
return 'inventory_source_routing'
return 'inventory_preparation'
return 'onhand_source_routing'
return 'onhand_preparation'
def _create_formal_execution_for_task(
@@ -418,7 +418,7 @@ def submit_auto_progress(
# (manual_override_source)。后者 inventory_mode 可为 auto(复用指定源快照),
# 但仍须取消残留 poll / 活动 Attempt,否则会只读轮询、不按新源取数。
explicit_inventory_retry = (
str(resume_gate_code or '').strip() == 'inventory_preparation'
str(resume_gate_code or '').strip() == 'onhand_preparation'
and (
str(inventory_mode or '').strip() == 'retry_rpa'
or str(trigger or '').strip() == 'manual_override_source'
@@ -433,7 +433,7 @@ def submit_auto_progress(
db.session.flush()
execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one()
current_gate = (
'inventory_preparation'
'onhand_preparation'
if explicit_inventory_retry
else str(execution.current_gate_code or '').strip() or None
)
@@ -479,16 +479,16 @@ def submit_auto_progress(
stale_job.message = '显式库存重抓:取消残留活动 Job'
gate.status = 'blocked_retryable'
gate.passed_at = None
gate.blocking_reason_code = 'inventory_rpa_retry_requested'
gate.next_action_code = 'retry_inventory_preparation'
gate.blocking_reason_code = 'onhand_rpa_retry_requested'
gate.next_action_code = 'retry_onhand_preparation'
gate.evaluation_version = int(gate.evaluation_version) + 1
gate.lock_version = int(gate.lock_version) + 1
gate.updated_at = _utc_now()
execution.current_gate_code = 'inventory_preparation'
execution.current_gate_code = 'onhand_preparation'
# 阶段能力回退同时切换责任方;保留旧 Gate 的 owner 会使技术 Gate
# 被 submit_auto_progress 误判为人工节点,从而跳过 Attempt/RPA 入队。
execution.responsible_party = 'worker'
execution.primary_next_action_code = 'retry_inventory_preparation'
execution.primary_next_action_code = 'retry_onhand_preparation'
execution.updated_at = _utc_now()
db.session.flush()
active_attempt = (
@@ -532,7 +532,7 @@ def submit_auto_progress(
# 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的
# system/worker Gate 才可自动创建 Attempt 并入队。
# 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。
# upload_inventory_file 等导航动作必须保留给用户;否则成功回调已同步
# upload_onhand_file 等导航动作必须保留给用户;否则成功回调已同步
# 的库存事实会被旧人工阻断动作再次覆盖。
if (
gate is not None
@@ -57,7 +57,7 @@ def _unmark_running(bucket: set[str], key: str) -> None:
def _should_orchestrate_task(task: Any) -> bool:
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
if not task_is_active(task):
return False
@@ -100,7 +100,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
return {"status": "skipped", "message": "task already running"}
try:
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.onhand_file_store import has_ready_inventory_file_for_task
task = get_task_by_ref(normalized_task_no)
if not task:
@@ -130,7 +130,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
):
# [STEP] 先做一次同步超时复查:单次 RPA 触发已过期且无成功回执时直接落
# rpa_exhausted(needs_human),避免仅依赖异步 Gate 轮询导致单票卡在 running。
from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait
from app.services.shipping_notice.onhand_rpa_workflow import maybe_recheck_inventory_rpa_wait
recheck = maybe_recheck_inventory_rpa_wait(task, source='batch_orchestrator')
if recheck is not None:
@@ -65,7 +65,7 @@ _PROCESSING_ITEM_LIFECYCLES = frozenset({
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'onhand_matching',
'generating_excel',
})
@@ -13,7 +13,7 @@ from __future__ import annotations
from datetime import datetime
from typing import Any
from app.models import ShippingOrderTask, ShippingTemporaryInventorySession
from app.models import ShippingOrderTask, ShippingTemporaryOnhandSession
from app.services.agent_runtime_context.builder import serialize_for_dify
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
@@ -40,18 +40,18 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N
normalized = str(conversation_id or '').strip()
if not normalized:
return None
item = ShippingTemporaryInventorySession.query.filter(
ShippingTemporaryInventorySession.conversation_id == normalized,
ShippingTemporaryInventorySession.status.in_([
item = ShippingTemporaryOnhandSession.query.filter(
ShippingTemporaryOnhandSession.conversation_id == normalized,
ShippingTemporaryOnhandSession.status.in_([
'created',
'awaiting_profile_confirmation',
'awaiting_mapping_suggestion',
'awaiting_mapping_confirmation',
]),
ShippingTemporaryInventorySession.expires_at > datetime.utcnow(),
ShippingTemporaryOnhandSession.expires_at > datetime.utcnow(),
).order_by(
ShippingTemporaryInventorySession.updated_at.desc(),
ShippingTemporaryInventorySession.id.desc(),
ShippingTemporaryOnhandSession.updated_at.desc(),
ShippingTemporaryOnhandSession.id.desc(),
).first()
return str(item.session_no or '').strip().upper() or None if item else None
Loaded 100 of 790 files, more files were not shown because too many files have changed in this diff. Show more