feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环
This commit is contained in:
1 parent
cfa19a0b7b
commit
8e0bbf7a81
180 files changed
+31210
-1864
No files matched your search
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
scripts/rpa/download_artifact_fallback.py
|
||||
|
||||
用途:在浏览器实际已落盘但 Playwright 未返回 Download 对象时,按下载目录中的新文件构造兼容适配器。
|
||||
依赖:pathlib、shutil、time。
|
||||
逻辑:由 DSV 导出链路在 `expect_download` 超时后调用;不改变站点交互,只补文件系统兜底。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class FilesystemDownloadArtifact:
|
||||
"""兼容 Playwright Download 的最小适配器,仅提供 `suggested_filename` 与 `save_as()`。"""
|
||||
|
||||
def __init__(self, path: Path) -> None:
|
||||
self._path = Path(path)
|
||||
self.suggested_filename = self._path.name
|
||||
|
||||
def save_as(self, dest: str) -> None:
|
||||
target = Path(dest)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
if self._path.resolve() == target.resolve():
|
||||
return
|
||||
shutil.move(str(self._path), str(target))
|
||||
|
||||
|
||||
def wait_for_new_download_file(
|
||||
*,
|
||||
download_dir: str | Path,
|
||||
baseline_names: set[str],
|
||||
timeout_seconds: float = 12.0,
|
||||
poll_seconds: float = 0.5,
|
||||
) -> FilesystemDownloadArtifact | None:
|
||||
"""
|
||||
等待下载目录里出现本次新生成且大小稳定的文件。
|
||||
|
||||
核心逻辑:忽略 `.crdownload/.tmp` 等临时文件;优先接受 Excel/CSV 类产物,
|
||||
同时兼容 Chromium 在 `downloads_path` 中落下的无扩展名原始文件;
|
||||
连续两次观察到大小不变后,认为浏览器已完成落盘。
|
||||
"""
|
||||
root = Path(download_dir)
|
||||
if not root.is_dir():
|
||||
return None
|
||||
|
||||
deadline = time.monotonic() + max(1.0, timeout_seconds)
|
||||
stable_sizes: dict[Path, int] = {}
|
||||
allowed_suffixes = {".xlsx", ".xls", ".xlsm", ".xltx", ".xltm", ".csv", ""}
|
||||
transient_suffixes = {".crdownload", ".tmp", ".part"}
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
candidates = []
|
||||
for path in root.iterdir():
|
||||
if not path.is_file():
|
||||
continue
|
||||
if path.name in baseline_names:
|
||||
continue
|
||||
suffix = path.suffix.lower()
|
||||
if suffix in transient_suffixes or suffix not in allowed_suffixes:
|
||||
continue
|
||||
candidates.append(path)
|
||||
candidates.sort(key=lambda item: item.stat().st_mtime, reverse=True)
|
||||
for path in candidates:
|
||||
try:
|
||||
size = path.stat().st_size
|
||||
except OSError:
|
||||
continue
|
||||
last_size = stable_sizes.get(path)
|
||||
if last_size is not None and last_size == size and size > 0:
|
||||
return FilesystemDownloadArtifact(path)
|
||||
stable_sizes[path] = size
|
||||
time.sleep(max(0.1, poll_seconds))
|
||||
return None
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
scripts/rpa/dsv_export_timeout_diagnostics.py
|
||||
|
||||
用途:汇总 DSV Excel 导出等待超时现场,输出适合直接写入 worker.log 的诊断字符串。
|
||||
依赖:json、标准库。
|
||||
逻辑:由 dsv_report_export 在 `page.expect_download(...)` 超时时调用;不参与任何业务判断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
|
||||
def build_download_timeout_log(
|
||||
*,
|
||||
report_name: str,
|
||||
error_type: str,
|
||||
error_message: str,
|
||||
selected_frame_index: int | None,
|
||||
selected_frame_name: str,
|
||||
selected_frame_url: str,
|
||||
report_state: dict[str, Any] | None,
|
||||
export_controls: dict[str, Any] | None,
|
||||
page_snapshot: str,
|
||||
) -> str:
|
||||
"""
|
||||
生成 DSV 导出等待超时诊断日志。
|
||||
|
||||
核心逻辑:把当前报表、选中结果 frame、导出控件探针和页面快照压成一条 JSON,
|
||||
便于在不接 Debug Server 的情况下,直接从 worker.log 反推出导出按钮是否真实可见。
|
||||
|
||||
Returns:
|
||||
str: 以 `[dsv-download-timeout]` 开头的单行日志。
|
||||
"""
|
||||
payload = {
|
||||
"report_name": str(report_name or ""),
|
||||
"error_type": str(error_type or ""),
|
||||
"error_message": str(error_message or "")[:500],
|
||||
"selected_frame_index": selected_frame_index,
|
||||
"selected_frame_name": str(selected_frame_name or "")[:120],
|
||||
"selected_frame_url": str(selected_frame_url or "")[:300],
|
||||
"report_state": report_state or {},
|
||||
"export_controls": export_controls or {},
|
||||
"page_snapshot": str(page_snapshot or "")[:2500],
|
||||
}
|
||||
return "[dsv-download-timeout] " + json.dumps(payload, ensure_ascii=False, default=str)
|
||||
@@ -20,6 +20,7 @@ from rpa_common import click_visible_selector_or_text_in_root as _click_visible_
|
||||
from rpa_common import env as _env
|
||||
from rpa_common import visible_locator as _visible_locator
|
||||
from rpa_common import visible_locator_in_root as _visible_locator_in_root
|
||||
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file
|
||||
import dsv_debug
|
||||
from dsv_debug import (
|
||||
debug_dsv_page_snapshot as _debug_dsv_page_snapshot,
|
||||
@@ -27,6 +28,7 @@ from dsv_debug import (
|
||||
emit_debug_event as _emit_debug_event,
|
||||
report_debug_event as _report_debug_event,
|
||||
)
|
||||
from dsv_export_timeout_diagnostics import build_download_timeout_log as _build_download_timeout_log
|
||||
import dsv_navigation
|
||||
from dsv_navigation import (
|
||||
click_dsv_menu_item as _click_dsv_menu_item,
|
||||
@@ -1197,8 +1199,60 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
|
||||
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
|
||||
if not _dsv_report_has_inventory_data_rows(page):
|
||||
raise NoInventoryDataError("DSV report has no inventory data")
|
||||
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
|
||||
_click_dsv_export_excel(page)
|
||||
download_dir = str(source.get("__download_dir") or "").strip()
|
||||
baseline_names = set()
|
||||
if download_dir:
|
||||
try:
|
||||
baseline_names = {path.name for path in Path(download_dir).iterdir() if path.is_file()}
|
||||
except OSError:
|
||||
baseline_names = set()
|
||||
try:
|
||||
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
|
||||
_click_dsv_export_excel(page)
|
||||
except Exception as exc:
|
||||
selected = _find_dsv_report_result_frame(page)
|
||||
selected_frame_index = selected[0] if selected is not None else None
|
||||
selected_frame = selected[1] if selected is not None else None
|
||||
selected_frame_name = ""
|
||||
selected_frame_url = ""
|
||||
if selected_frame is not None:
|
||||
try:
|
||||
selected_frame_name = str(selected_frame.name or "")
|
||||
except Exception:
|
||||
selected_frame_name = ""
|
||||
try:
|
||||
selected_frame_url = str(selected_frame.url or "")
|
||||
except Exception:
|
||||
selected_frame_url = ""
|
||||
report_state = _get_dsv_report_result_state(selected_frame) if selected_frame is not None else {}
|
||||
export_controls = _probe_dsv_report_export_controls(selected_frame) if selected_frame is not None else {}
|
||||
print(
|
||||
_build_download_timeout_log(
|
||||
report_name=_dsv_report_name(source),
|
||||
error_type=type(exc).__name__,
|
||||
error_message=str(exc),
|
||||
selected_frame_index=selected_frame_index,
|
||||
selected_frame_name=selected_frame_name,
|
||||
selected_frame_url=selected_frame_url,
|
||||
report_state=report_state,
|
||||
export_controls=export_controls,
|
||||
page_snapshot=_debug_dsv_page_snapshot(page, target_text="Excel"),
|
||||
),
|
||||
file=sys.stderr,
|
||||
)
|
||||
if download_dir:
|
||||
fallback_download = _wait_for_new_download_file(
|
||||
download_dir=download_dir,
|
||||
baseline_names=baseline_names,
|
||||
)
|
||||
if fallback_download is not None:
|
||||
print(
|
||||
"[dsv-download-fallback] "
|
||||
f"using downloaded file from directory because Playwright download event timed out: "
|
||||
f"{fallback_download.suggested_filename}",
|
||||
)
|
||||
return fallback_download
|
||||
raise
|
||||
return download_info.value
|
||||
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import hashlib
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
@@ -356,6 +357,26 @@ def _mask_secret(value: str) -> str:
|
||||
return f"{value[:4]}...{value[-4:]}"
|
||||
|
||||
|
||||
def _resolve_tool_api_auth_debug() -> tuple[str, str]:
|
||||
"""
|
||||
返回 Tool API 鉴权来源与脱敏后的 Key,供 Worker 启动日志快速排查环境变量问题。
|
||||
|
||||
核心逻辑:按实际请求相同的优先级检查三个环境变量;只返回来源名与脱敏值,避免明文泄露。
|
||||
|
||||
Returns:
|
||||
tuple[str, str]: `(source, masked_value)`;未配置时返回 `("missing", "")`。
|
||||
"""
|
||||
for env_name in (
|
||||
"SHIPPING_NOTICE_TOOL_API_KEY",
|
||||
"INTEGRATION_API_KEY",
|
||||
"HXOPS_TOOLS_API_KEY",
|
||||
):
|
||||
key = _env(env_name)
|
||||
if key:
|
||||
return env_name, _mask_secret(key)
|
||||
return "missing", ""
|
||||
|
||||
|
||||
def _post_callback(path: str, payload: dict) -> None:
|
||||
"""
|
||||
向 HXOPS 货代 Tool API 发送 JSON 回调。
|
||||
@@ -818,6 +839,8 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
|
||||
source = trigger.get("rpa_inventory_source")
|
||||
if not isinstance(source, dict):
|
||||
raise RuntimeError("inventory trigger missing rpa_inventory_source")
|
||||
source = dict(source)
|
||||
source["__download_dir"] = str(drop_dir)
|
||||
connector_type = _worker_connector_type(source)
|
||||
source_code = str(source.get("source_code") or "").strip() or connector_type or "UNKNOWN"
|
||||
_validate_inventory_source_for_rpa(source)
|
||||
@@ -965,7 +988,7 @@ def _configuration_test_callback_payload(run_no: str, results: list) -> dict:
|
||||
|
||||
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
|
||||
body = json.loads(trigger_path.read_text(encoding="utf-8"))
|
||||
run_no = str(body.get("run_no") or trigger_path.stem).strip()
|
||||
run_no = str(body.get("batch_run_no") or body.get("run_no") or trigger_path.stem).strip()
|
||||
task_no = str(body.get("task_no") or "").strip()
|
||||
sources = body.get("inventory_sources") or []
|
||||
failed_dir = trigger_path.parent / "failed"
|
||||
@@ -977,6 +1000,21 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
mode = "mock" if mock else "browser"
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
# v2 claimed 回调只记录领取事实,不代表业务成功。
|
||||
if body.get("schema_version") == "shipping_inventory_rpa.v2":
|
||||
claimed_items = []
|
||||
for source in sources:
|
||||
if isinstance(source, dict) and source.get("source_run_no"):
|
||||
claimed_items.append({k: source.get(k) for k in ("task_no", "source_code", "attempt_no", "source_run_no", "lease_token")})
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-batch-claimed", {
|
||||
"schema_version": "shipping_inventory_rpa.v2", "batch_run_no": run_no,
|
||||
"claimed_at": datetime.utcnow().isoformat(), "worker_id": _env("SHIPPING_NOTICE_RPA_WORKER_ID", "worker"),
|
||||
"items": claimed_items,
|
||||
})
|
||||
except Exception as exc:
|
||||
print(f"[inventory-batch] claimed callback failed: {exc}", file=sys.stderr)
|
||||
|
||||
def report_configuration_test_progress(source: dict) -> None:
|
||||
"""实际操作站点前回传领取状态;进度回调故障不能中断库存导出。"""
|
||||
if str(body.get("trigger_type") or "").strip() != "configuration_test_batch":
|
||||
@@ -1009,6 +1047,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
"file_path": str(out_file),
|
||||
"task_no": task_no or None,
|
||||
"validation_run_no": source.get("validation_run_no"),
|
||||
**{k: source.get(k) for k in ("task_no", "attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")},
|
||||
})
|
||||
else:
|
||||
# 一个 Profile 对应一个独立浏览器登录态;同 Driver 的不同账号绝不能共用 session。
|
||||
@@ -1025,6 +1064,8 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
# 同组的 Profile 相同,登录和导出期间使用同一组临时凭据。
|
||||
with _profile_credentials(site_sources[0]):
|
||||
for index, source in enumerate(site_sources):
|
||||
source = dict(source)
|
||||
source["__download_dir"] = str(drop_dir)
|
||||
code = str(source.get("source_code") or "")
|
||||
wh = str(source.get("warehouse_id") or "")
|
||||
try:
|
||||
@@ -1043,7 +1084,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
_reset_crane_export_entry(page, entry_url)
|
||||
download = export_fn(page, body, source, skip_navigation=skip_navigation) if site == "dsv360" else export_fn(page, body, source)
|
||||
out_file = _save_batch_download(download, drop_dir, run_no, source)
|
||||
results.append({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or None, "validation_run_no": source.get("validation_run_no")})
|
||||
results.append({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or source.get("task_no") or None, "validation_run_no": source.get("validation_run_no"), **{k: source.get(k) for k in ("attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}})
|
||||
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
|
||||
except NoInventoryDataError as exc:
|
||||
results.append({"source_code": code, "warehouse_id": wh, "status": "skipped", "success": False, "skipped": True, "skip_reason": "no_inventory_data", "message": str(exc), "validation_run_no": source.get("validation_run_no")})
|
||||
@@ -1072,11 +1113,14 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
elif trigger_type == "configuration_test_batch":
|
||||
callback_path = "/api/shipping-notice/rpa/inventory-configuration-test-batch-ready"
|
||||
callback_payload = {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no,
|
||||
"validation_batch_id": body.get("validation_batch_id"),
|
||||
"batch_no": body.get("batch_no"),
|
||||
"rpa_mode": mode,
|
||||
"results": results,
|
||||
"results": [{**item, "callback_id": f"{run_no}:{item.get('source_run_no')}:C1"} for item in results],
|
||||
}
|
||||
else:
|
||||
callback_path = "/api/shipping-notice/rpa/inventory-batch-ready"
|
||||
@@ -1572,9 +1616,19 @@ def main() -> None:
|
||||
|
||||
inv_processed = inv_trigger_dir / "processed"
|
||||
upload_processed = upload_trigger_dir / "processed"
|
||||
api_base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
|
||||
heartbeat_seconds = max(
|
||||
15,
|
||||
int(_env("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"),
|
||||
)
|
||||
auth_source, masked_auth = _resolve_tool_api_auth_debug()
|
||||
|
||||
print("[freight_rpa_worker] started")
|
||||
print(f" mock={_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')}")
|
||||
print(f" api_base={api_base}")
|
||||
print(f" heartbeat_seconds={heartbeat_seconds}")
|
||||
print(f" auth_source={auth_source}")
|
||||
print(f" auth_key={masked_auth or 'missing'}")
|
||||
print(f" inventory_triggers={inv_trigger_dir}")
|
||||
print(f" upload_triggers={upload_trigger_dir}")
|
||||
print(f" drop={drop_dir}")
|
||||
|
||||
Reference in new issue
Block a user