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

- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
This commit is contained in:
hugo committed 2026-10-19 18:45:16 +08:00
1 parent 39fe3c05f2
commit 911afa0f73
152 files changed
+9861 -2984

No files matched your search

@@ -1,13 +1,14 @@
"""
services/freight_rpa/common/worker_heartbeat.py
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/入站/出站就绪检查与状态查询。
依赖:Flask current_app、redis_client、同包 rpa_runtime(mock 模式)、
freight_rpa.onhand.trigger_io(onhand trigger 目录)、
freight_rpa.upload.trigger_io(上传目录)、
freight_rpa.inbound.trigger_io(inbound trigger 目录)。
逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound trigger 前强制就绪检查;
管理端 /rpa-workers/status?scope=onhand|inbound 展示对应 Worker 心跳徽标。
freight_rpa.inbound.trigger_io(inbound trigger 目录)、
freight_rpa.outbound.trigger_io(outbound trigger 目录)。
逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound/outbound trigger 前强制就绪检查;
管理端 /rpa-workers/status?scope=onhand|inbound|outbound 展示对应 Worker 心跳徽标。
"""
from __future__ import annotations
@@ -40,8 +41,11 @@ RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 W
ONHAND_EXPORT_CAPABILITY = "onhand_export"
FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload"
INBOUND_EXPORT_CAPABILITY = "inbound_export"
OUTBOUND_EXPORT_CAPABILITY = "outbound_export"
# inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。
INBOUND_WORKER_ID_SUFFIX = "-inbound"
# outbound Worker 由 start_outbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-outbound。
OUTBOUND_WORKER_ID_SUFFIX = "-outbound"
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
@@ -59,6 +63,7 @@ _REASON_USER_HINTS: dict[str, str] = {
"environment_mismatch": "Worker 环境与后端环境不一致",
"missing_onhand_export_capability": "Worker 未声明 onhand_export 能力",
"missing_inbound_export_capability": "Worker 未声明 inbound_export 能力",
"missing_outbound_export_capability": "Worker 未声明 outbound_export 能力",
"missing_freight_rpa_upload_capability": "Worker 未声明 freight_rpa_upload 能力",
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
@@ -369,7 +374,7 @@ def _verify_shared_trigger_mount(
trigger_dir: Path | None, *, require_sentinel: bool = True,
) -> tuple[bool, list[str]]:
"""
校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。
校验 trigger 目录可写;默认要求共享哨兵(库存与入站同口径)。
Args:
trigger_dir: 共享 trigger 目录。
@@ -407,7 +412,7 @@ def _verify_shared_trigger_mount(
return not reasons, reasons
def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool:
def is_inbound_rpa_worker(worker: dict[str, Any]) -> bool:
"""
判断心跳是否来自 inbound(原收料)Worker。
@@ -428,6 +433,27 @@ def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool:
return False
def is_outbound_rpa_worker(worker: dict[str, Any]) -> bool:
"""
判断心跳是否来自 outbound Worker。
优先认 <主机名>-outbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与 outbound 目录对齐判定。
"""
if str(worker.get("worker_id") or "").strip().lower().endswith(OUTBOUND_WORKER_ID_SUFFIX):
return True
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
expected = outbound_trigger_dir()
actual = str(worker.get("trigger_dir") or "").strip()
if expected is None or not actual:
return False
try:
return Path(actual).resolve() == expected.resolve()
except OSError:
return False
def _worker_scope_matches(worker: dict[str, Any]) -> tuple[bool, list[str]]:
expected_scope = shared_scope_id()
if not expected_scope:
@@ -454,7 +480,7 @@ def _worker_is_eligible(
backend_env: 后端归一环境(dev/test/prod)。
ttl_seconds: 心跳 TTL。
now: 当前 epoch 秒。
required_capability: 必选能力(onhand_export / inbound_export / freight_rpa_upload)。
required_capability: 必选能力(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。
Returns:
(是否合格, 不合格原因列表)。
@@ -482,7 +508,7 @@ def _worker_is_eligible(
def _missing_capability_reason(required_capability: str) -> str:
"""按必选能力生成缺失原因码(onhand_export / inbound_export / freight_rpa_upload)。"""
"""按必选能力生成缺失原因码(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。"""
return f"missing_{required_capability}_capability"
@@ -521,8 +547,8 @@ def _check_rpa_worker_ready_for_capability(
trigger_dir: 待校验的共享 trigger 目录。
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
extra_reasons: 调用方预检附加原因(凭据/队列等)。
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。
worker_predicate: 可选过滤(如仅入站 Worker);不匹配的心跳不进入列表。
require_sentinel: 是否要求共享哨兵(库存/入站同口径均 True)。
Returns:
RpaWorkerReadiness。
@@ -637,9 +663,9 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
)
def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
def check_inbound_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
检查入站 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求
inbound_export 能力;校验 inbound trigger 目录可写;与 onhand 同口径要求共享哨兵。
@@ -649,24 +675,24 @@ def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
return _check_rpa_worker_ready_for_capability(
trigger_dir=inbound_trigger_dir(),
required_capability=INBOUND_EXPORT_CAPABILITY,
worker_predicate=is_receipt_rpa_worker,
worker_predicate=is_inbound_rpa_worker,
require_sentinel=True,
)
def assert_receipt_rpa_worker_ready() -> None:
def assert_inbound_rpa_worker_ready() -> None:
"""
写收料 trigger 前的强制就绪检查。
写入站 trigger 前的强制就绪检查。
核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError,
排程不得进入 awaiting_receipt_rpa。
排程不得进入 awaiting_inbound_rpa。
Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
"""
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
result = check_receipt_rpa_worker_ready()
result = check_inbound_rpa_worker_ready()
if result.ready:
return
code = 'RPA.WORKER_OFFLINE'
@@ -691,6 +717,60 @@ def assert_receipt_rpa_worker_ready() -> None:
)
def check_outbound_rpa_worker_ready() -> RpaWorkerReadiness:
"""
检查出站 RPA Worker 是否在线(写 trigger 前 fail-fast)。
核心逻辑:仅看 outbound Worker 心跳(*-outbound 或 trigger_dir 对齐);要求
outbound_export 能力;校验 outbound trigger 目录可写;与 onhand/inbound 同口径要求共享哨兵。
"""
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
return _check_rpa_worker_ready_for_capability(
trigger_dir=outbound_trigger_dir(),
required_capability=OUTBOUND_EXPORT_CAPABILITY,
worker_predicate=is_outbound_rpa_worker,
require_sentinel=True,
)
def assert_outbound_rpa_worker_ready() -> None:
"""
写出站 trigger 前的强制就绪检查。
核心逻辑:镜像 assert_inbound_rpa_worker_ready;离线则抛 ServiceUnavailableError,
排程不得进入 awaiting_outbound_rpa_callback。
Raises:
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
"""
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
result = check_outbound_rpa_worker_ready()
if result.ready:
return
code = 'RPA.WORKER_OFFLINE'
if 'heartbeat_storage_unavailable' in result.reasons:
code = 'RPA.HEARTBEAT_STORAGE_UNAVAILABLE'
logger.warning(
'[rpa-heartbeat] outbound readiness blocked code=%s reasons=%s detail=%s',
code,
result.reasons,
result.detail_message,
)
raise ServiceUnavailableError(
result.message,
code=code,
details={
'reasons': result.reasons,
'detail_message': result.detail_message,
'checked_at': result.checked_at,
'shared_scope_id': shared_scope_id(),
'trigger_dir': str(outbound_trigger_dir() or ''),
},
)
def _freight_upload_config_reasons() -> list[str]:
"""
预检货代上传静态配置:凭据主密钥、上传队列目录、回调 API 基址。
@@ -852,19 +932,23 @@ def assert_inventory_rpa_worker_ready() -> None:
def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]:
"""
管理端展示:按 scope 返回在手(onhand)或入站(inbound)Worker 心跳摘要。
管理端展示:按 scope 返回在手(onhand)、入站(inbound)或出站(outbound)Worker 心跳摘要。
Args:
scope: onhand(默认,库存 RPA 工作台)或 inbound(入站 RPA 工作台);
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识(Task 12)无关。
scope: onhand(默认,库存 RPA 工作台)、inbound(入站)或 outbound(出站);
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识无关。
"""
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
normalized = str(scope or "onhand").strip().lower()
if normalized == "inbound":
readiness = check_receipt_rpa_worker_ready()
readiness = check_inbound_rpa_worker_ready()
trigger_path = str(inbound_trigger_dir() or "")
elif normalized == "outbound":
readiness = check_outbound_rpa_worker_ready()
trigger_path = str(outbound_trigger_dir() or "")
else:
readiness = check_inventory_rpa_worker_ready()
trigger_path = str(onhand_trigger_dir() or "")
@@ -2,19 +2,16 @@
services/freight_rpa/inbound/report_archive.py
用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
三年保留期、不写库存快照表)、到期对象清理(retention)、单文件企微投递与管理员
强制重发(resend)。批次 R Task 10 自 shipping_notice.receipt_report_storage /
schedule.freight_rpa_inbound_retention / shipping_notice.receipt_report_notification
平移而来(函数名 receipt 词根→inbound;模型 ShippingInboundReport* 引用不变——批次 S 才改表)。
依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun / FreightRpaInboundNotificationDelivery /
User / ScheduleRun 相关模型经行对象访问)、file_assets.storage、integrations.wecom.notify、
freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
三年保留期、不写库存快照表)与到期对象清理(retention)。per-file 企微投递与 resend
已拆除(Task 2);排程终态通知仍走 freight_rpa_inbound_finalize 统一出口。
依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun、ScheduleRun 经行对象访问)、
file_assets.storage、freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
freight_rpa.common.report_audit(本域唯一审计写入口,批次 B Task 6 起替代
shipping_notice.audit_service——freight_rpa 禁止 import shipping_notice 业务模块,
边界由 tests/services/freight_rpa/test_import_boundary.py 空白名单锁定)、
freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递,Task 6)。
逻辑:Worker 回调进入 /api/freight-rpa/inbound-batch-ready 后由组合根注册的业务 sink
(shipping_notice.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
(in_transit_transfer.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」——
commit 后构造 ReportFact(report_kind='inbound', ...) 调 dispatch_report_fact;
处理函数异常原样外抛(不吞、不回滚已提交终态),kind 未注册时 404
@@ -36,19 +33,14 @@ from flask import current_app
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
FreightRpaInboundNotificationDelivery,
FreightRpaInboundReportFile,
FreightRpaInboundUnitRun,
User,
)
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
from app.services.freight_rpa.reports.facts import ReportFact
from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media
def _read_inbound_callback_file(file_path: str) -> bytes:
"""只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
@@ -59,7 +51,7 @@ def _read_inbound_callback_file(file_path: str) -> bytes:
"""
configured_root = str(inbound_drop_dir() or '').strip()
if not configured_root:
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
raise ValidationError('inbound callback file root is unavailable', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
root = Path(configured_root).resolve()
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
name = Path(str(file_path).replace('\\', '/')).name
@@ -67,12 +59,12 @@ def _read_inbound_callback_file(file_path: str) -> bytes:
try:
path.relative_to(root)
except ValueError as exc:
raise ValidationError('receipt callback file is outside receipt drop root', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') from exc
raise ValidationError('inbound callback file is outside inbound drop root', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') from exc
if path.suffix.lower() != '.xlsx' or not path.is_file():
raise ValidationError('receipt callback file must be an existing xlsx', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
raise ValidationError('inbound callback file must be an existing xlsx', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024
if path.stat().st_size > max_size:
raise ValidationError('receipt callback file exceeds configured size limit', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
raise ValidationError('inbound callback file exceeds configured size limit', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
return path.read_bytes()
@@ -96,23 +88,23 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
(供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。
"""
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID')
raise ValidationError('inbound callback schema_version is invalid', code='SHIPPING.INBOUND_CALLBACK_INVALID')
callback_id = str(payload.get('callback_id') or '').strip()
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
raise NotFoundError('Receipt RPA unit not found', code='SHIPPING.RECEIPT_UNIT_NOT_FOUND')
raise NotFoundError('Inbound RPA unit not found', code='SHIPPING.INBOUND_UNIT_NOT_FOUND')
status = str(payload.get('status') or '').strip().lower()
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
if status in {'empty', 'no_data'}:
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_inbound_data。
unit.status = 'empty'
unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64]
unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000]
unit.error_code = str(payload.get('error_code') or 'no_inbound_data')[:64]
unit.error_message = str(payload.get('error_message') or 'no_inbound_data')[:2000]
unit.finished_at = datetime.utcnow()
append_rpa_report_event(
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success',
actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success',
before=before,
after={
'status': 'empty',
@@ -127,17 +119,17 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
db.session.commit()
dispatch_report_fact(ReportFact(
report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False,
error_code=unit.error_code or 'no_receipt_data',
error_message=unit.error_message or 'no_receipt_data',
error_code=unit.error_code or 'no_inbound_data',
error_message=unit.error_message or 'no_inbound_data',
unit_run_id=unit.id,
))
return {'unit_run_id': unit.id, 'status': 'empty'}
if status != 'success':
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow()
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.INBOUND_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'inbound export failed')[:2000]; unit.finished_at = datetime.utcnow()
append_rpa_report_event(
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='failure',
actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='failure',
before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message},
metadata={'callback_status': status},
)
@@ -154,7 +146,7 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
sha256 = hashlib.sha256(data).hexdigest()
claimed = str(payload.get('sha256') or '').lower()
if claimed and claimed != sha256:
raise ValidationError('receipt callback sha256 mismatch', code='SHIPPING.RECEIPT_CALLBACK_SHA_MISMATCH')
raise ValidationError('inbound callback sha256 mismatch', code='SHIPPING.INBOUND_CALLBACK_SHA_MISMATCH')
existing = FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
if existing:
# [STEP] 幂等重放:不插第二行,仍投递 ok=True 事实(同一 file_id),供处理函数重试;
@@ -171,7 +163,7 @@ def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
db.session.add(record)
unit.status = 'success'; unit.finished_at = datetime.utcnow()
db.session.flush()
append_rpa_report_event(event_type='shipping_inbound_report_archived', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
append_rpa_report_event(event_type='shipping_inbound_report_archived', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'inbound_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
# [STEP] 先 commit 归档,再投递 ok=True 事实(Task 6 顺序契约);unit_run_id
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
db.session.commit()
@@ -210,7 +202,7 @@ def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='success',
before={'status': 'archived'}, after={'status': 'archive_deleted'},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
success += 1
except Exception as exc:
@@ -220,88 +212,8 @@ def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
unit_id=report_file.unit_run_id, result='failure',
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
)
failed += 1
db.session.commit()
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
def _recipient_ids(report_file: FreightRpaInboundReportFile) -> list[int]:
"""从所属排程冻结的接收人列表取目标用户;停用通知时返回空。"""
run = report_file.unit_run.schedule_run
task = run.task if run else None
if task is None or not task.notify_enabled:
return []
return sorted({int(user_id) for user_id in (task.notify_user_ids_json or []) if str(user_id).isdigit()})
def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
"""向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。
Args:
file_id: 已归档收料文件主键(FreightRpaInboundReportFile.id)。
force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。
Returns:
dict: success_count / failed_count(file_not_found 时附 reason)。
"""
report_file = db.session.get(FreightRpaInboundReportFile, file_id)
if report_file is None:
return {'success_count': 0, 'failed_count': 0, 'reason': 'file_not_found'}
success_count = failed_count = 0
for user_id in _recipient_ids(report_file):
key = f'receipt:file:{report_file.id}:user:{user_id}'
delivery = FreightRpaInboundNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
if delivery and delivery.status == 'success' and not force:
success_count += 1
continue
if delivery is None:
delivery = FreightRpaInboundNotificationDelivery(
unit_run_id=report_file.unit_run_id, report_file_id=report_file.id, recipient_user_id=user_id,
message_type='file', idempotency_key=key, status='pending',
)
db.session.add(delivery)
db.session.flush()
user = db.session.get(User, user_id)
if user is None or not user.wecom_userid:
delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding'
failed_count += 1
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
after={'delivery_status': delivery.status, 'error_code': delivery.error_code},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
)
continue
try:
media_id = upload_wecom_temp_media(file_asset_storage.get_bytes(report_file.storage_key), report_file.original_filename)
result = send_wecom_file_message(user.wecom_userid, media_id)
if int(result.get('errcode', -1)) != 0:
raise RuntimeError(str(result.get('errmsg') or result.get('errcode')))
delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.error_code = None; delivery.error_message = None
delivery.response_summary_json = {'media_uploaded': True, 'errcode': 0}
success_count += 1
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file', aggregate_id=str(report_file.id),
actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='success',
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
)
except Exception as exc:
delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]
failed_count += 1
append_rpa_report_event(
event_type='shipping_inbound_file_notification_attempted', aggregate_type='shipping_inbound_file',
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
unit_id=report_file.unit_run_id, result='failure',
before={'delivery_status': 'pending'},
after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message},
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
)
db.session.commit()
return {'success_count': success_count, 'failed_count': failed_count}
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'inbound_retention', 'status': 'completed'}]
@@ -0,0 +1 @@
"""outbound:出站 RPA。"""
@@ -0,0 +1,246 @@
"""
services/freight_rpa/outbound/report_archive.py
用途:outbound(出站)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
三年保留期、不写库存快照表)。
依赖:models(FreightRpaOutboundReportFile / FreightRpaOutboundUnitRun)、
file_assets.storage、freight_rpa.outbound.trigger_io(回调 SCHEMA 与 drop 根)、
freight_rpa.common.report_audit(本域唯一审计写入口)、
freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递)。
逻辑:Worker 回调进入 /api/freight-rpa/outbound-batch-ready 后由组合根(Task 10)
或测内临时 register 的 sink 调 ingest_outbound_callback 完成原样归档;
empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」——
commit 后构造 ReportFact(report_kind='outbound', ...) 调 dispatch_report_fact;
处理函数异常原样外抛(不吞、不回滚已提交终态);同一 unit_run_id + sha256
已有文件时不插第二行、仍投递 ok=True 的事实供处理函数重试。
跨机路径:file_path 只认 outbound drop 根内文件名,禁止把 Worker Windows
绝对路径当 Linux 路径打开(对照 inbound._read_inbound_callback_file)。
本模块不 import shipping_notice / in_transit_transfer,不移植入站逐文件企微投递。
"""
from __future__ import annotations
import hashlib
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
from flask import current_app
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
FreightRpaOutboundReportFile,
FreightRpaOutboundUnitRun,
)
from app.services.file_assets.storage import file_asset_storage
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_TRIGGER_SCHEMA, outbound_drop_dir
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
from app.services.freight_rpa.reports.facts import ReportFact
def _read_outbound_callback_file(file_path: str) -> bytes:
"""只读取 outbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...)。
一律 replace('\\','/') 后取 .name,再拼本机 FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR,
relative_to(root) 防穿越。禁止把回调串当 Linux 路径直接 open。
"""
configured_root = str(outbound_drop_dir() or "").strip()
if not configured_root:
raise ValidationError(
"outbound callback file root is unavailable",
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
)
root = Path(configured_root).resolve()
# [STEP] 跨机:先归一分隔符再取末段文件名,绝不 Path(file_path).read_bytes()。
name = Path(str(file_path).replace("\\", "/")).name
path = (root / name).resolve()
try:
path.relative_to(root)
except ValueError as exc:
raise ValidationError(
"outbound callback file is outside outbound drop root",
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
) from exc
if path.suffix.lower() != ".xlsx" or not path.is_file():
raise ValidationError(
"outbound callback file must be an existing xlsx",
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
)
max_size = max(int(current_app.config.get("FILE_ASSET_MAX_SIZE_MB", 30) or 30), 1) * 1024 * 1024
if path.stat().st_size > max_size:
raise ValidationError(
"outbound callback file exceeds configured size limit",
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
)
return path.read_bytes()
def ingest_outbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
"""幂等接收单个 outbound 单元回调,原样归档三年且不写库存快照表。
Args:
payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。
Returns:
dict: unit_run_id/status[/file_id/idempotent],供 HTTP envelope 的 data 使用。
(brief 曾写 -> None;与入站 API envelope 对齐仍返回 dict。)
Raises:
ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。
NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。
AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。
业务顺序:每个终态分支先 db.session.commit() 再构造
ReportFact(report_kind='outbound', source_code=unit.source_code, ...) 调
dispatch_report_fact;事实恒带 unit_run_id=unit.id;处理函数异常原样外抛;
同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实。
"""
if payload.get("schema_version") != OUTBOUND_TRIGGER_SCHEMA:
raise ValidationError(
"outbound callback schema_version is invalid",
code="SHIPPING.OUTBOUND_CALLBACK_INVALID",
)
callback_id = str(payload.get("callback_id") or "").strip()
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
if unit is None:
raise NotFoundError("Outbound RPA unit not found", code="SHIPPING.OUTBOUND_UNIT_NOT_FOUND")
status = str(payload.get("status") or "").strip().lower()
before = {"status": unit.status, "error_code": unit.error_code, "error_message": unit.error_message}
if status in {"empty", "no_data"}:
# [STEP] 与入站 empty / 库存 no_inventory_data 对齐:empty 是合法业务结果。
unit.status = "empty"
unit.error_code = str(payload.get("error_code") or "no_outbound_data")[:64]
unit.error_message = str(payload.get("error_message") or "no_outbound_data")[:2000]
unit.finished_at = datetime.utcnow()
append_rpa_report_event(
event_type="shipping_outbound_rpa_callback_received",
aggregate_type="shipping_outbound_unit",
aggregate_id=str(unit.id),
run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type="rpa",
actor_id="outbound-worker",
unit_id=unit.id,
result="success",
before=before,
after={
"status": "empty",
"callback_id": unit.callback_id,
"error_code": unit.error_code,
"error_message": unit.error_message,
},
metadata={"callback_status": status, "skip_reason": unit.error_code},
)
db.session.commit()
dispatch_report_fact(ReportFact(
report_kind="outbound",
source_code=unit.source_code,
file_id=None,
sha256=None,
ok=False,
error_code=unit.error_code or "no_outbound_data",
error_message=unit.error_message or "no_outbound_data",
unit_run_id=unit.id,
))
return {"unit_run_id": unit.id, "status": "empty"}
if status != "success":
unit.status = "failed"
unit.error_code = str(payload.get("error_code") or "RPA.OUTBOUND_EXPORT_FAILED")[:64]
unit.error_message = str(payload.get("error_message") or "outbound export failed")[:2000]
unit.finished_at = datetime.utcnow()
append_rpa_report_event(
event_type="shipping_outbound_rpa_callback_received",
aggregate_type="shipping_outbound_unit",
aggregate_id=str(unit.id),
run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type="rpa",
actor_id="outbound-worker",
unit_id=unit.id,
result="failure",
before=before,
after={"status": "failed", "error_code": unit.error_code, "error_message": unit.error_message},
metadata={"callback_status": status},
)
db.session.commit()
dispatch_report_fact(ReportFact(
report_kind="outbound",
source_code=unit.source_code,
file_id=None,
sha256=None,
ok=False,
error_code=unit.error_code,
error_message=unit.error_message,
unit_run_id=unit.id,
))
return {"unit_run_id": unit.id, "status": "failed"}
data = _read_outbound_callback_file(str(payload.get("file_path") or ""))
sha256 = hashlib.sha256(data).hexdigest()
claimed = str(payload.get("sha256") or "").lower()
if claimed and claimed != sha256:
raise ValidationError(
"outbound callback sha256 mismatch",
code="SHIPPING.OUTBOUND_CALLBACK_SHA_MISMATCH",
)
existing = FreightRpaOutboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
if existing:
dispatch_report_fact(ReportFact(
report_kind="outbound",
source_code=unit.source_code,
file_id=existing.id,
sha256=sha256,
ok=True,
unit_run_id=unit.id,
))
return {"unit_run_id": unit.id, "status": unit.status, "file_id": existing.id, "idempotent": True}
filename = Path(str(payload.get("original_filename") or payload.get("file_path") or "outbound.xlsx")).name
storage_key = f"shipping/outbound-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx"
file_asset_storage.upload_bytes(
storage_key=storage_key,
data=data,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
record = FreightRpaOutboundReportFile(
unit_run_id=unit.id,
storage_provider="minio",
storage_bucket=file_asset_storage.bucket_name,
storage_key=storage_key,
original_filename=filename,
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
file_size=len(data),
sha256=sha256,
archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3),
)
db.session.add(record)
unit.status = "success"
unit.finished_at = datetime.utcnow()
db.session.flush()
append_rpa_report_event(
event_type="shipping_outbound_report_archived",
aggregate_type="shipping_outbound_unit",
aggregate_id=str(unit.id),
run_no=unit.schedule_run.run_no if unit.schedule_run else None,
actor_type="rpa",
actor_id="outbound-worker",
unit_id=unit.id,
result="success",
before=before,
after={
"status": "success",
"source_run_no": unit.callback_id,
"file_id": record.id,
"sha256": sha256,
"file_size": len(data),
},
artifact_refs=[{"kind": "outbound_report", "id": str(record.id), "sha256": sha256}],
metadata={"file_size": len(data), "retention_days": 365 * 3},
)
db.session.commit()
dispatch_report_fact(ReportFact(
report_kind="outbound",
source_code=unit.source_code,
file_id=record.id,
sha256=sha256,
ok=True,
unit_run_id=unit.id,
))
return {"unit_run_id": unit.id, "status": "success", "file_id": record.id, "idempotent": False}
@@ -0,0 +1,92 @@
"""
services/freight_rpa/outbound/trigger_io.py
用途:outbound(出站)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON
原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
逻辑:由 schedule.freight_rpa_outbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
in_transit_transfer.outbound_trigger_service(调拨按需/批量触发)、
freight_rpa.common.worker_heartbeat(outbound trigger 目录探测/就绪检查)、
freight_rpa.outbound.report_archive(drop 目录定位与回调 SCHEMA 校验,后续任务)等调用,
与外部 RPA Worker 的文件投递目录交互;schema/action 以本文件常量为单一真相
(Worker 侧对表:freight_rpa.outbound.v1 / outbound_export_batch)。
"""
from __future__ import annotations
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
SCHEMA = "freight_rpa.outbound.v1"
ACTION_OUTBOUND_EXPORT_BATCH = "outbound_export_batch"
def _path(key: str) -> Path | None:
value = str(current_app.config.get(key) or "").strip()
if not value:
return None
return Path(value)
def outbound_trigger_dir() -> Path | None:
"""RPA outbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR);
绝不回落到 onhand/inbound trigger 目录。"""
return _path("FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR")
def outbound_drop_dir() -> Path | None:
"""RPA outbound 导出文件落盘目录(FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR)。"""
return _path("FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR")
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
try:
with open(temp_path, 'w', encoding='utf-8') as handle:
json.dump(body, handle, ensure_ascii=False, indent=2)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp_path, path)
finally:
if temp_path.exists():
temp_path.unlink(missing_ok=True)
def write_outbound_export_batch_trigger(
run_no: str,
units: list[dict[str, Any]],
meta: dict[str, Any] | None = None,
) -> str | None:
"""
写入 outbound 批量 trigger 文件 outbound_export_batch_{run_no}.json
(Worker 轮询 <root>/*.json 按内容消费,schema/action 取本文件常量)。
Args:
run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。
units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。
meta: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。
Returns:
str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。
"""
trigger_dir = outbound_trigger_dir()
if not trigger_dir or not units:
return None
trigger_dir.mkdir(parents=True, exist_ok=True)
safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'outbound'
body = {
'schema_version': SCHEMA, 'action': ACTION_OUTBOUND_EXPORT_BATCH,
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
**(meta or {}),
}
path = trigger_dir / f'outbound_export_batch_{safe_run_no}.json'
_write_trigger_json_atomic(path, body)
return str(path)
@@ -0,0 +1,364 @@
"""
services/freight_rpa/parsing_profile.py
用途:管理货代「报表规则」(FreightRpaParsingProfile)的草稿/发布与运行期定义读取。
purpose=onhand 走库存字段目录 + match_keys;purpose=inbound/outbound 走调拨
MOVEMENT_FIELDS 契约(与在途异动对齐)。
依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig、FreightRpaInboundReportConfig、
FreightRpaOutboundReportConfig、ShippingOrderField、
in_transit_transfer.movement_contract.MOVEMENT_FIELDS、
shipping_notice.order_schema(仅 onhand 发布时校验订单字段)。
逻辑:管理员保存草稿并发布不可变版本;来源站点 / 入站·出站报表配置只绑定 published
Profile;退役前检查 onhand/inbound/outbound 配置引用。管理端入口
/api/admin/freight-rpa/.../parsing-profiles。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
from sqlalchemy import func
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
FreightRpaOnhandField,
FreightRpaOnhandReportConfig,
FreightRpaParsingProfile,
FreightRpaOnhandStructureAnalysis,
ShippingOrderField,
FreightRpaInboundReportConfig,
FreightRpaOutboundReportConfig,
)
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
field_ids: list[int] = []
for raw_id in field_mapping:
try:
field_id = int(raw_id)
except (TypeError, ValueError) as exc:
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') from exc
if field_id <= 0:
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
field_ids.append(field_id)
rows = FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(set(field_ids))).all() if field_ids else []
fields = {str(row.id): row for row in rows if row.status == 'active'}
if len(fields) != len(set(str(item) for item in field_ids)):
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
return fields
def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set[str]:
"""校验解析方案具备匹配与库存数量能力,不限定字段名称。"""
match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'}
quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'}
if not match_ids or len(quantity_ids) != 1:
raise ValidationError(
'Parsing profile requires at least one match field and exactly one inventory quantity field',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
return match_ids | quantity_ids
# 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
"""校验 inbound/outbound 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
movement_codes = {field.code for field in MOVEMENT_FIELDS}
mapping = definition.get('field_mapping') or {}
mapped_codes = {str(code) for code in mapping.keys() if str(code).strip()}
unknown = mapped_codes - movement_codes
if unknown:
raise ValidationError(
f'Movement parsing profile references unknown field: {sorted(unknown)}',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
if missing:
raise ValidationError(
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
return mapped_codes
def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]:
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。
Args:
raw: 解析定义对象。
purpose: 'onhand'(库存字段目录 + match_keys)或
'inbound'/'outbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
"""
if not isinstance(raw, dict):
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
field_mapping = raw.get('field_mapping')
if not isinstance(field_mapping, dict) or not field_mapping:
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if any(not str(value or '').strip() for value in field_mapping.values()):
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
header_row_index = raw.get('header_row_index')
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if purpose in {'inbound', 'outbound'}:
_required_movement_field_ids(raw)
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
'header_row_index': header_row_index,
'field_mapping': {str(key).strip(): str(value).strip() for key, value in field_mapping.items()},
'match_keys': [],
}
catalog_fields = _catalog_fields(field_mapping)
_required_catalog_field_ids(catalog_fields)
match_keys = raw.get('match_keys')
if not isinstance(match_keys, list) or not match_keys:
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
normalized_keys: list[dict[str, str]] = []
seen_order_fields: set[str] = set()
seen_inventory_fields: set[str] = set()
for item in match_keys:
field = db.session.get(ShippingOrderField, str(item.get('order_field_id') or '')) if isinstance(item, dict) else None
inventory_field = str(item.get('inventory_field_id') or item.get('inventory_field') or '') if isinstance(item, dict) else ''
inventory = catalog_fields.get(inventory_field)
if (
field is None or field.status != 'active' or field.scope != 'line'
or inventory is None or inventory.usage_type != 'match_identity'
):
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if field.id in seen_order_fields or inventory_field in seen_inventory_fields:
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
seen_order_fields.add(field.id)
seen_inventory_fields.add(inventory_field)
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
'header_row_index': header_row_index,
'field_mapping': {str(int(key)): str(value).strip() for key, value in field_mapping.items()},
'match_keys': normalized_keys,
}
def _require_sample_evidence(
sample_analysis_id: Any,
definition: dict[str, Any],
*,
file_format: str,
) -> FreightRpaOnhandStructureAnalysis:
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
try:
analysis_id = int(sample_analysis_id)
except (TypeError, ValueError) as exc:
raise ValidationError(
'Parsing profile requires sample analysis evidence',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
) from exc
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format:
raise ValidationError(
'Parsing profile sample analysis evidence is unavailable',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
)
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
selected = next((candidate for candidate in candidates if isinstance(candidate, dict)
and candidate.get('sheet_name') == definition.get('sheet_name')
and candidate.get('header_row_index') == definition.get('header_row_index')), None)
if not isinstance(selected, dict):
raise ValidationError(
'Parsing profile worksheet or header row is not present in sample evidence',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
)
headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()}
if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()):
raise ValidationError(
'Parsing profile mapping is not present in sample evidence',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
)
duplicates = {
str(column.get('header') or '').strip()
for column in selected.get('columns', []) if isinstance(column, dict) and column.get('duplicate')
}
if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()):
raise ValidationError(
'Parsing profile mapping uses duplicate sample headers',
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
)
return analysis
def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]:
"""序列化解析 Profile 管理 DTO。"""
sample_analysis = profile.sample_analysis
return {
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'purpose': profile.purpose, 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
'definition': profile.definition_json or {}, 'checksum': profile.checksum,
'published_at': profile.published_at.isoformat() if profile.published_at else None,
'source_count': len(profile.sources),
'sample_analysis_id': profile.sample_analysis_id,
'sample_evidence_history': profile.sample_evidence_history_json or [],
'sample_evidence': {
'id': sample_analysis.id,
'source_file_name': sample_analysis.source_file_name,
'file_checksum': sample_analysis.file_checksum,
'file_format': sample_analysis.file_format,
'structure': sample_analysis.structure_json or {},
'sample_rows': sample_analysis.sample_rows_json or [],
'validation_summary': sample_analysis.validation_summary_json or {},
'created_at': sample_analysis.created_at.isoformat() if sample_analysis.created_at else None,
} if sample_analysis is not None else None,
}
def list_profiles() -> list[dict[str, Any]]:
"""列出全部解析 Profile 版本。"""
return [payload(item) for item in FreightRpaParsingProfile.query.order_by(
FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.version.desc(),
).all()]
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
"""创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile_id else None
if profile_id and profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile is not None and profile.status != 'draft':
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
code = str(data.get('profile_code') or '').strip().upper()
if not code:
raise ValidationError('profile_code is required', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if profile is not None and code != profile.profile_code:
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
if profile is None:
next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
db.session.add(profile)
purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower()
if purpose not in {'onhand', 'inbound', 'outbound'}:
raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if profile_id and purpose != profile.purpose:
raise ValidationError(
'Draft parsing profile purpose is immutable',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
profile.purpose = purpose
profile.display_name = str(data.get('display_name') or code).strip()
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
raise ValidationError('file_format is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
if profile_id and requested_file_format != profile.file_format:
raise ValidationError(
'Draft parsing profile file format is immutable',
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
)
profile.file_format = requested_file_format
definition = _validate_definition(data.get('definition'), purpose=purpose)
if profile.file_format == 'csv' and definition.get('sheet_name'):
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
sample_analysis = _require_sample_evidence(
data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format,
)
if profile.sample_analysis_id and profile.sample_analysis_id != sample_analysis.id:
if not bool(data.get('confirm_sample_replacement')):
raise ValidationError(
'Replacing inventory sample evidence requires confirmation',
code='SHIPPING.ONHAND_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
)
history = list(profile.sample_evidence_history_json or [])
history.append({
'previous_analysis_id': profile.sample_analysis_id,
'replacement_analysis_id': sample_analysis.id,
'replaced_at': datetime.utcnow().isoformat(),
'replaced_by': actor_id,
})
profile.sample_evidence_history_json = history
profile.definition_json = definition
profile.sample_analysis = sample_analysis
db.session.commit()
return payload(profile)
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID')
_require_sample_evidence(
profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
# inbound/outbound 无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand 维持原约束。
referenced_field_ids = {
str(item.get('order_field_id') or '')
for item in (profile.definition_json or {}).get('match_keys', [])
if isinstance(item, dict)
}
if profile.purpose == 'onhand':
published_field_ids = {
str(item.get('field_id') or '')
for item in order_schema_service.get_published_contract().get('fields', [])
}
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
raise ValidationError(
'Parsing profile match keys must reference the current published order schema',
code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID',
)
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
profile.checksum = hashlib.sha256(encoded).hexdigest()
profile.status = 'published'
profile.published_by = actor_id
profile.published_at = datetime.utcnow()
db.session.commit()
return payload(profile)
def retire(profile_id: int) -> dict[str, Any]:
"""退役无库存源/入站/出站报表配置引用的 published Profile,避免使现有绑定静默失效。"""
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'published':
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID')
# s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。
bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
# 入站/出站报表配置同样绑定解析 Profile:退役前必须一并核查,
# 否则入站/出站文件解析链会静默失去规则。
bound_inbound_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
bound_outbound_configs = FreightRpaOutboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
if bound_sources or bound_inbound_configs or bound_outbound_configs:
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED')
profile.status = 'retired'
db.session.commit()
return payload(profile)
def delete_draft(profile_id: int) -> None:
"""删除从未发布的解析 Profile 草稿。"""
profile = db.session.get(FreightRpaParsingProfile, profile_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.ONHAND_PARSING_PROFILE_DELETE_BLOCKED')
db.session.delete(profile)
db.session.commit()
def require_source_profile(source: Any) -> FreightRpaParsingProfile:
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
config = getattr(source, 'onhand_report_config', None)
profile = config.parsing_profile if config is not None else None
if profile is None or profile.status != 'published':
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
return profile
@@ -1,7 +1,7 @@
"""freight_rpa/reports/__init__.py
用途:报表读域(阶段 B Task 3)——发货(shipping_notice 域)与在途调拨
(in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包。
用途:报表读域——发货(shipping_notice 域)与在途调拨
(in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包(含出站配置视图)。
依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。
逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice)
一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。
@@ -15,12 +15,15 @@ from app.services.freight_rpa.reports.queries import (
InboundConfigView,
InboundFileView,
OnhandConfigView,
OutboundConfigView,
SiteView,
clear_inbound_parse_failure,
get_inbound_config,
get_onhand_config,
get_outbound_config,
get_site,
latest_usable_inbound_file,
list_outbound_configured_source_codes,
mark_inbound_parse_failure,
read_inbound_file_bytes,
usable_inbound_file_condition,
@@ -31,13 +34,16 @@ __all__ = [
'InboundConfigView',
'InboundFileView',
'OnhandConfigView',
'OutboundConfigView',
'ReportFact',
'SiteView',
'clear_inbound_parse_failure',
'get_inbound_config',
'get_onhand_config',
'get_outbound_config',
'get_site',
'latest_usable_inbound_file',
'list_outbound_configured_source_codes',
'mark_inbound_parse_failure',
'read_inbound_file_bytes',
'require_report_kind',
@@ -4,8 +4,9 @@
终态、再投递事实」的第二段分发(批次 B Task 6)。
依赖:app.core.errors.AppError、freight_rpa.reports.facts(ReportFact、
require_report_kind)。
逻辑:组合根(Task 7 的 shipping_notice.rpa_sinks.register_inbound_sinks /
register_onhand_sinks 等)在应用启动时调用 register_report_handler 注入各
逻辑:组合根(shipping_notice.rpa_sinks.register_onhand_sinks /
in_transit_transfer.rpa_sinks.register_inbound_sinks /
register_outbound_sinks)在应用启动时调用 register_report_handler 注入各
kind 的业务处理函数;归档入口(如 freight_rpa.inbound.report_archive.
ingest_inbound_callback)在每个终态 db.session.commit() 之后调用
dispatch_report_fact。kind 未注册时显式 404(FREIGHT_RPA.
@@ -33,8 +34,8 @@ def register_report_handler(report_kind: str, handler: Handler) -> None:
"""
注册一个报表事实处理函数(由组合根在应用启动时调用)。
【AI 触发时机】:组合根装配(Task 7 的 register_inbound_sinks /
register_onhand_sinks)时调用;测试直接调用注入临时处理函数。
【AI 触发时机】:组合根装配(register_onhand_sinks / register_inbound_sinks /
register_outbound_sinks)时调用;测试直接调用注入临时处理函数。
核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound /
outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。
Args:
@@ -42,7 +43,7 @@ def register_report_handler(report_kind: str, handler: Handler) -> None:
handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用,
不校验其内部行为。
Raises:
ValidationError: report_kind 不在白名单(code=SHIPPING.RECEIPT_CALLBACK_INVALID)。
ValidationError: report_kind 不在白名单(code=SHIPPING.INBOUND_CALLBACK_INVALID)。
"""
kind = require_report_kind(report_kind)
_REPORT_HANDLERS[kind] = handler
@@ -4,7 +4,7 @@
依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。
逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作;
report kind 只认 onhand / inbound / outbound,非法值抛
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),
ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),
与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。
本模块不 import shipping_notice / in_transit_transfer。
【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递
@@ -23,7 +23,7 @@ REPORT_KINDS = ('onhand', 'inbound', 'outbound')
# 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码,
# 避免为同一类入参错误分裂出多个近义 code。
_INVALID_KIND_ERROR_CODE = 'SHIPPING.RECEIPT_CALLBACK_INVALID'
_INVALID_KIND_ERROR_CODE = 'SHIPPING.INBOUND_CALLBACK_INVALID'
@dataclass(frozen=True)
@@ -53,7 +53,7 @@ def require_report_kind(value: str) -> str:
用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。
核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛
ValidationError(code='SHIPPING.RECEIPT_CALLBACK_INVALID'),fail-closed。
ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),fail-closed。
Args:
value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。
@@ -2,10 +2,11 @@
用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+
解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露
freight_rpa 报表事实(站点、登录连接、在手/入站报表配置、入站解析方案、
freight_rpa 报表事实(站点、登录连接、在手/入站/出站报表配置、入站解析方案、
入站归档文件),使消费方不再直接 import freight_rpa 模型表。
依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig /
FreightRpaInboundReportConfig / FreightRpaInboundReportFile;登录连接
FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig /
FreightRpaInboundReportFile;登录连接
(RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、
app.core.errors(NotFoundError)、
file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。
@@ -23,8 +24,8 @@
config_id/config_version;新增登录连接(get_rpa_login_profile)、入站解析
方案(get_inbound_parsing_profile)、失效文件存在性(has_expired_inbound_
file)、重建通道归档清单(list_reparseable_inbound_files)、入站可用站点
编码清单(list_inbound_configured_source_codes)——供 in_transit_transfer
收敛为「只按 source_code / file_id 读取」的只读函数消费面。
编码清单(list_inbound_configured_source_codes / list_outbound_configured_source_codes)
——供 in_transit_transfer 收敛为「只按 source_code / file_id 读取」的只读函数消费面。
mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。
"""
@@ -42,6 +43,7 @@ from app.models import (
FreightRpaInboundReportConfig,
FreightRpaInboundReportFile,
FreightRpaOnhandReportConfig,
FreightRpaOutboundReportConfig,
FreightRpaSource,
)
from app.services.file_assets.storage import file_asset_storage
@@ -200,6 +202,21 @@ class InboundConfigView:
config_version: int = 1
@dataclass(frozen=True)
class OutboundConfigView:
"""出站报表配置只读视图(freight_rpa_outbound_report_configs 行),与入站同构。
config_id / config_version 供调拨出站触发落可审计单元行快照使用,
不再引用配置模型。
"""
report_path_json: dict
query_parameters_json: list
parsing_profile_id: int | None
config_id: int = 0
config_version: int = 1
@dataclass(frozen=True)
class InboundProfileView:
"""入站解析方案只读视图(freight_rpa_parsing_profiles 行)。
@@ -321,6 +338,36 @@ def get_inbound_config(source_code: str) -> InboundConfigView | None:
)
def get_outbound_config(source_code: str) -> OutboundConfigView | None:
"""按 source_code 返回出站报表配置只读视图(与入站配置同构)。
用途:调拨出站触发读路径取出站报表定义;出站不设独立启停,是否运行由站点
enabled 与本配置行是否存在决定。
核心逻辑:join 站点表按 source_code 查 freight_rpa_outbound_report_configs 行,
命中即映射视图;缺失返回 None。
Args:
source_code: 站点实例编码。
Returns:
OutboundConfigView;站点或配置不存在返回 None。
"""
config = (
FreightRpaOutboundReportConfig.query
.join(FreightRpaSource, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id)
.filter(FreightRpaSource.source_code == source_code)
.first()
)
if config is None:
return None
return OutboundConfigView(
report_path_json=dict(config.report_path_json or {}),
query_parameters_json=list(config.query_parameters_json or []),
parsing_profile_id=config.parsing_profile_id,
config_id=config.id,
config_version=int(config.config_version or 1),
)
def get_rpa_login_profile(source_code: str) -> RpaLoginProfileView | None:
"""按 source_code 返回站点绑定的 RPA 登录连接只读视图。
@@ -478,6 +525,24 @@ def list_inbound_configured_source_codes() -> list[str]:
return [str(code) for (code,) in rows]
def list_outbound_configured_source_codes() -> list[str]:
"""列出已配置出站报表的启用站点编码(调拨排程缺省执行范围)。
用途:在途自动调拨排程 source_codes 留空时的缺省范围
(outbound_trigger_service.list_outbound_capable_source_codes 委托本函数)
——出站文件只能来自已配置出站报表的启用站点。
核心逻辑:站点 join 出站配置行、仅启用站点、按 source_code 排序;只读查询。
Returns:
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
"""
rows = db.session.query(FreightRpaSource.source_code).join(
FreightRpaOutboundReportConfig,
FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id,
).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all()
return [str(code) for (code,) in rows]
def latest_usable_inbound_file(
source_code: str,
*,