feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环

This commit is contained in:
hugo committed 2026-08-09 11:43:53 +08:00
1 parent cfa19a0b7b
commit 8e0bbf7a81
180 files changed
+31210 -1864

No files matched your search

+57 -3
View File
@@ -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}")