381 lines
16 KiB
Python
381 lines
16 KiB
Python
"""
|
||
services/shipping_notice/rpa.py
|
||
|
||
用途:管理库存导出与货代上传相关的 RPA 目录、触发文件和落盘辅助逻辑。
|
||
依赖:Flask current_app 配置、Path/JSON/文件系统工具。
|
||
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等上游模块调用本文件,与外部 RPA 文件投递目录进行交互。
|
||
"""
|
||
|
||
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
|
||
from app.core.errors import ValidationError
|
||
|
||
|
||
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("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") or "false").strip().lower()
|
||
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
|
||
|
||
|
||
def _path(key: str) -> Path | None:
|
||
value = str(current_app.config.get(key) or "").strip()
|
||
if not value:
|
||
return None
|
||
return Path(value)
|
||
|
||
|
||
def inventory_drop_dir() -> Path | None:
|
||
"""RPA 库存 Excel 落盘目录(SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR)。"""
|
||
return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR")
|
||
|
||
|
||
def inventory_processed_dir() -> Path | None:
|
||
"""已处理库存文件归档子目录(drop_dir/processed)。"""
|
||
base = inventory_drop_dir()
|
||
if not base:
|
||
return None
|
||
return base / "processed"
|
||
|
||
|
||
def inventory_trigger_dir() -> Path | None:
|
||
"""RPA 库存导出触发 JSON 目录。"""
|
||
return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_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 upload_queue_dir() -> Path | None:
|
||
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。"""
|
||
return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR")
|
||
|
||
|
||
def upload_trigger_dir() -> Path | None:
|
||
"""RPA 货代上传触发 JSON 目录。"""
|
||
return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR")
|
||
|
||
|
||
def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
|
||
"""
|
||
写入 RPA 库存导出触发文件 inventory_export_{task_no}.json。
|
||
|
||
Returns:
|
||
str | None: 触发文件绝对路径;目录未配置时返回 None。
|
||
"""
|
||
trigger_dir = inventory_trigger_dir()
|
||
if not trigger_dir:
|
||
return None
|
||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||
body = {
|
||
"action": "inventory_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)
|
||
|
||
|
||
def write_inventory_export_batch_trigger(
|
||
run_no: str,
|
||
sources: list[dict[str, Any]],
|
||
*,
|
||
payload: dict[str, Any] | None = None,
|
||
) -> str | None:
|
||
"""
|
||
写入批量库存导出 trigger(DSV/Crane 一次登录多 Warehouse)。
|
||
【AI 触发时机】:定时排程或后台批量预热库存快照时调用。
|
||
|
||
Args:
|
||
run_no: RPA 批次号,写入回调 audit。
|
||
sources: build_rpa_inventory_source 构造的源列表。
|
||
payload: 额外字段(trigger_type、schedule_run_id 等)。
|
||
|
||
Returns:
|
||
str | None: 触发文件绝对路径。
|
||
"""
|
||
trigger_dir = inventory_trigger_dir()
|
||
if not trigger_dir or not sources:
|
||
return None
|
||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||
inventory_sources = []
|
||
for source in sources:
|
||
if not isinstance(source, dict) or not source.get("source_code"):
|
||
continue
|
||
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
|
||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||
configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'}
|
||
trigger_source = get_rpa_trigger_inventory_source(
|
||
str(source["source_code"]), enabled_only=not configuration_test,
|
||
) or source
|
||
source = {**source, **trigger_source}
|
||
business_connector = str(source.get("connector_type") or "").strip().lower()
|
||
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
|
||
item = {
|
||
"source_code": source.get("source_code"),
|
||
"connector_type": business_connector,
|
||
"worker_connector_type": worker_connector,
|
||
"rpa_profile_code": source.get("rpa_profile_code"),
|
||
"warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"),
|
||
"login_url": source.get("login_url"),
|
||
"entry_url": source.get("login_url"),
|
||
"navigation": source.get("navigation") or {},
|
||
"parameters": source.get("parameters") or [],
|
||
"query": source.get("query") or {},
|
||
"credential_envelope": source.get("credential_envelope") or {},
|
||
# 配置测试回调据此将批次结果精确回写到各自站点运行。
|
||
"validation_run_no": source.get("validation_run_no"),
|
||
}
|
||
# v2 逐源身份必须由后端显式写入,Worker 不得重新生成。
|
||
for identity_key in (
|
||
"callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version",
|
||
"execution_id", "gate_id", "expected_warehouse_id", "lease_token",
|
||
):
|
||
if source.get(identity_key) is not None:
|
||
item[identity_key] = source[identity_key]
|
||
if not item.get('callback_id') and item.get('source_run_no'):
|
||
item['callback_id'] = f"{item['source_run_no']}:C1"
|
||
inventory_sources.append(item)
|
||
if not inventory_sources:
|
||
return None
|
||
|
||
body = {
|
||
"action": "inventory_export_batch",
|
||
"schema_version": "shipping_inventory_rpa.v2",
|
||
"callback_id": f"{run_no}:batch:C1",
|
||
"batch_run_no": run_no,
|
||
"run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段
|
||
"trigger_type": "scheduled",
|
||
"requested_at": datetime.utcnow().isoformat(),
|
||
"inventory_sources": inventory_sources,
|
||
**(payload or {}),
|
||
}
|
||
safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch"
|
||
path = trigger_dir / f"inventory_export_batch_{safe_run}.json"
|
||
_write_trigger_json_atomic(path, body)
|
||
return str(path)
|
||
|
||
|
||
def inventory_rpa_batch_enabled() -> bool:
|
||
"""是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。"""
|
||
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED")
|
||
if raw is None:
|
||
raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
|
||
|
||
|
||
def build_on_demand_inventory_trigger_source(
|
||
task_no: str,
|
||
rpa_source: dict[str, Any],
|
||
*,
|
||
body: dict[str, Any],
|
||
) -> dict[str, Any]:
|
||
"""
|
||
构造按需库存导出批次触发内的单源条目(含 Profile 凭据与逐源身份键)。
|
||
【AI 触发时机】:单源 on-demand 触发与多候选合并批次触发(per_source_rpa_service)共用本构造,
|
||
保证两条路径投递给 Worker 的输入契约完全一致。
|
||
|
||
Args:
|
||
task_no: 发货任务号。
|
||
rpa_source: 调用方持有的非敏感源快照(含 source_code);DB 配置/Profile 存在时以其为准。
|
||
body: 触发载荷,提供 callback_id/source_run_no/attempt_no/lease_token 等逐源身份键。
|
||
|
||
Returns:
|
||
可直接传入 write_inventory_export_batch_trigger 的单源条目。
|
||
"""
|
||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||
|
||
source_code = str(rpa_source.get('source_code') or '').strip()
|
||
rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source
|
||
# Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。
|
||
rpa_source = dict(rpa_source)
|
||
business_connector = str(rpa_source.get('connector_type') or '').strip().lower()
|
||
rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector))
|
||
rpa_source.setdefault('entry_url', rpa_source.get('login_url'))
|
||
rpa_source.setdefault('credential_envelope', {})
|
||
source_item = dict(rpa_source)
|
||
source_item.update({
|
||
"source_code": source_code,
|
||
"callback_id": body.get("callback_id") or (
|
||
f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None
|
||
),
|
||
"task_no": task_no,
|
||
# 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致
|
||
# Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。
|
||
"attempt_no": body.get("attempt_no") or body.get("attempt"),
|
||
"source_run_no": body.get("source_run_no"),
|
||
"candidate_set_id": body.get("candidate_set_id"),
|
||
"candidate_set_version": body.get("candidate_set_version"),
|
||
"execution_id": body.get("execution_id"),
|
||
"gate_id": body.get("gate_id"),
|
||
"expected_warehouse_id": body.get("expected_warehouse_id"),
|
||
"lease_token": body.get("lease_token"),
|
||
})
|
||
return source_item
|
||
|
||
|
||
def write_inventory_export_trigger_for_task(
|
||
task_no: str,
|
||
rpa_source: dict[str, Any],
|
||
*,
|
||
payload: dict[str, Any] | None = None,
|
||
) -> str | None:
|
||
"""
|
||
写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。
|
||
【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。
|
||
|
||
核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed,
|
||
不再生成 legacy inventory_export trigger。
|
||
"""
|
||
body = dict(payload or {})
|
||
if inventory_rpa_batch_enabled():
|
||
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
|
||
source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body)
|
||
return write_inventory_export_batch_trigger(
|
||
run_no,
|
||
[source_item],
|
||
payload={
|
||
"schema_version": "shipping_inventory_rpa.v2",
|
||
"trigger_type": "on_demand",
|
||
"task_no": task_no,
|
||
**body,
|
||
},
|
||
)
|
||
raise ValidationError(
|
||
'shipping inventory RPA v2 batch trigger is required',
|
||
code='SHIPPING.INVENTORY_RPA_V2_REQUIRED',
|
||
)
|
||
|
||
|
||
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": "shipment_upload",
|
||
"schema_version": "shipping_notice_upload_rpa.v1",
|
||
"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
|
||
|
||
|
||
def find_latest_inventory_file() -> Path | None:
|
||
"""在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。"""
|
||
drop = inventory_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)
|