feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约

将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。
共享目录与 Worker 契约一次切换至 onhand/inbound/upload,
并补 outbound 骨架与 tt16 排程 job key 迁移。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-10-17 23:18:48 +08:00
1 parent bf3154033b
commit ffc0d4a430
147 files changed
+4221 -2678

No files matched your search

@@ -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 契约串以本文件常量为单一真相
([PROMPT_UPDATE] 2026-10-16 批次 R 新裁定:upload 契约随发布窗口一次切换——
action 由 shipment_upload 改为 outbound_upload、schema 由 shipping_notice_upload_rpa.v1
改为 freight_rpa.upload.v1,Worker 侧 Task 12 同窗口对齐,旧串全仓清零)。
"""
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_OUTBOUND_UPLOAD = "outbound_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_OUTBOUND_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