""" 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 from datetime import datetime from pathlib import Path from typing import Any from flask import current_app def _runtime_summary(mode: str) -> dict[str, str | bool]: """将 browser/mock 规范化为前端安全展示摘要。""" normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser" mock_enabled = normalized == "mock" return { "mode": normalized, "label": "Mock RPA" if mock_enabled else "真实 RPA", "mock": mock_enabled, } def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]: """返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。""" if isinstance(runtime, dict): mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower() if mode in {"browser", "mock"}: return _runtime_summary(mode) raw = str(os.getenv("FREIGHT_RPA_MOCK", current_app.config.get("FREIGHT_RPA_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 落盘目录(FREIGHT_INVENTORY_DROP_DIR)。""" return _path("FREIGHT_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("FREIGHT_RPA_INVENTORY_TRIGGER_DIR") def upload_queue_dir() -> Path | None: """货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。""" return _path("FREIGHT_UPLOAD_QUEUE_DIR") def upload_trigger_dir() -> Path | None: """RPA 货代上传触发 JSON 目录。""" return _path("FREIGHT_RPA_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: 触发文件绝对路径;目录未配置或 worker 未就绪时返回 None。 """ from app.services.shipping_notice.rpa_worker_heartbeat import assert_inventory_rpa_worker_ready assert_inventory_rpa_worker_ready() 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, "requested_at": datetime.utcnow().isoformat(), **(payload or {}), } path = trigger_dir / f"inventory_export_{task_no}.json" path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8") 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: 触发文件绝对路径。 """ from app.services.shipping_notice.rpa_worker_heartbeat import assert_inventory_rpa_worker_ready assert_inventory_rpa_worker_ready() 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 inventory_sources.append({ "source_code": source.get("source_code"), "source_type": source.get("source_type"), "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), "entry_url": source.get("entry_url"), "navigation": source.get("navigation") or {}, "parameters": source.get("parameters") or [], "query": source.get("query") or {}, }) if not inventory_sources: return None body = { "action": "inventory_export_batch", "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" path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8") 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 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 导出时调用。 核心逻辑:batch 模式写 inventory_export_batch(含 task_no);否则写 legacy inventory_export。 """ body = dict(payload or {}) if inventory_rpa_batch_enabled(): run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}" return write_inventory_export_batch_trigger( run_no, [rpa_source], payload={ "trigger_type": "on_demand", "task_no": task_no, **body, }, ) return write_inventory_export_trigger( task_no, { "rpa_inventory_source": rpa_source, **body, }, ) def write_upload_trigger(task_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]: """ 复制 Excel 至上传队列并写入 RPA 上传触发 JSON。 Returns: tuple[str | None, str | None]: (queue 文件路径, trigger 文件路径);失败时 (None, None)。 """ queue = upload_queue_dir() trigger_dir = upload_trigger_dir() if not queue or not trigger_dir: return 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 dest = queue / f"{task_no}_{src.name}" shutil.copy2(src, dest) body = { "action": "shipment_upload", "task_no": task_no, "file_path": str(dest), "requested_at": datetime.utcnow().isoformat(), **(payload or {}), } trigger_path = trigger_dir / f"upload_{task_no}.json" trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8") return str(dest), str(trigger_path) 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)