feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。 - 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。 - 更新 ORM 模型,增加出站报表相关的持久化模型。 - 统一命名规范,确保在手、入站与出站的概念一致性。
This commit is contained in:
1 parent
39fe3c05f2
commit
911afa0f73
152 files changed
+9861
-2984
No files matched your search
@@ -0,0 +1 @@
|
||||
"""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)
|
||||
Reference in new issue
Block a user