feat(shipping-notice): 增加 RPA 库存回调处理逻辑,支持跳过无库存情况
This commit is contained in:
1 parent
f21216f81e
commit
c3f05ba96b
25 files changed
+1619
-81
No files matched your search
@@ -59,6 +59,7 @@ import dsv_debug # noqa: E402
|
||||
import dsv_driver # noqa: E402
|
||||
import dsv_navigation # noqa: E402
|
||||
import dsv_report_export # noqa: E402
|
||||
from dsv_report_export import NoInventoryDataError # noqa: E402
|
||||
import dsv_session # noqa: E402
|
||||
|
||||
# 测试与 smoke 向后兼容 re-export
|
||||
@@ -353,7 +354,28 @@ def _browser_profile_root() -> Path:
|
||||
return _resolve_backend_relative_path(profile, default=default)
|
||||
|
||||
|
||||
def _mask_secret(value: str) -> str:
|
||||
"""
|
||||
对 API Key 等敏感字符串做首尾保留脱敏,供 callback 请求日志打印。
|
||||
|
||||
Args:
|
||||
value: 原始密钥字符串。
|
||||
|
||||
Returns:
|
||||
str: 长度 ≤8 时返回 `***`;否则保留前 4 与后 4 字符。
|
||||
"""
|
||||
value = str(value or "")
|
||||
if len(value) <= 8:
|
||||
return "***"
|
||||
return f"{value[:4]}...{value[-4:]}"
|
||||
|
||||
|
||||
def _post_callback(path: str, payload: dict) -> None:
|
||||
"""
|
||||
向 HXOPS 货代 Tool API 发送 JSON 回调。
|
||||
|
||||
核心逻辑:组装 URL 与双 Header 密钥 → 打印脱敏请求日志 → POST;HTTP 错误时打印响应体摘要。
|
||||
"""
|
||||
base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
|
||||
key = (
|
||||
_env("SHIPPING_NOTICE_TOOL_API_KEY")
|
||||
@@ -372,6 +394,14 @@ def _post_callback(path: str, payload: dict) -> None:
|
||||
|
||||
url = f"{base}{path}"
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
print(
|
||||
"[callback-request] "
|
||||
f"POST {url} "
|
||||
f"headers={{'Content-Type': 'application/json', "
|
||||
f"'X-Integration-Key': '{_mask_secret(key)}', "
|
||||
f"'X-Shipping-Tool-Key': '{_mask_secret(key)}'}} "
|
||||
f"payload={data.decode('utf-8', errors='replace')[:4000]}"
|
||||
)
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
@@ -388,6 +418,11 @@ def _post_callback(path: str, payload: dict) -> None:
|
||||
print(f"[callback] {path} -> {resp.status} {body[:200]}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
err = exc.read().decode("utf-8", errors="replace")
|
||||
print(
|
||||
"[callback-response] "
|
||||
f"POST {url} -> HTTP {exc.code} {err[:1000]}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise RuntimeError(f"callback {path} HTTP {exc.code}: {err[:300]}") from exc
|
||||
|
||||
|
||||
@@ -748,6 +783,67 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def _normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
|
||||
"""
|
||||
batch 明细状态归一化(比单任务更严格:缺省字段不算 success)。
|
||||
|
||||
核心逻辑:worker 自生成 results 均带 status/success;空 dict 或缺字段归为 failed,
|
||||
避免 batch summary 误计成功。
|
||||
"""
|
||||
raw_status = str(item.get("status") or "").strip().lower()
|
||||
if raw_status in {"success", "skipped", "failed"}:
|
||||
return raw_status
|
||||
if item.get("skipped"):
|
||||
return "skipped"
|
||||
if item.get("success") is True:
|
||||
return "success"
|
||||
return "failed"
|
||||
|
||||
|
||||
def _summarize_inventory_batch_results(results: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""
|
||||
汇总 batch 回调顶层状态。
|
||||
|
||||
核心逻辑:
|
||||
- status:新监控用,区分 success / partial_failed / failed;
|
||||
- success(legacy):与旧 any(item.success) 兼容,有 success 或 skipped 即为 true;
|
||||
- has_success:是否至少有一条实际导出成功。
|
||||
"""
|
||||
zero = {
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"has_success": False,
|
||||
"success_count": 0,
|
||||
"skipped_count": 0,
|
||||
"failed_count": 0,
|
||||
}
|
||||
statuses = [
|
||||
_normalize_inventory_batch_item_status(item)
|
||||
for item in results
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
if not statuses:
|
||||
return dict(zero)
|
||||
|
||||
success_count = sum(1 for status in statuses if status == "success")
|
||||
skipped_count = sum(1 for status in statuses if status == "skipped")
|
||||
failed_count = sum(1 for status in statuses if status == "failed")
|
||||
if failed_count == 0:
|
||||
top_status = "success"
|
||||
elif success_count == 0 and skipped_count == 0:
|
||||
top_status = "failed"
|
||||
else:
|
||||
top_status = "partial_failed"
|
||||
return {
|
||||
"status": top_status,
|
||||
"success": (success_count + skipped_count) > 0,
|
||||
"has_success": success_count > 0,
|
||||
"success_count": success_count,
|
||||
"skipped_count": skipped_count,
|
||||
"failed_count": failed_count,
|
||||
}
|
||||
|
||||
|
||||
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()
|
||||
@@ -772,6 +868,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
"source_code": source.get("source_code"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(out_file),
|
||||
"task_no": task_no or None,
|
||||
@@ -799,7 +896,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
"source_code": source.get("source_code"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"error_code": "unsupported_source_type",
|
||||
"error_message": f"unsupported source_type: {site}",
|
||||
})
|
||||
continue
|
||||
@@ -829,17 +928,32 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
"source_code": code,
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": wh,
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(out_file),
|
||||
"task_no": task_no or None,
|
||||
})
|
||||
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
|
||||
except NoInventoryDataError as exc:
|
||||
results.append({
|
||||
"source_code": code,
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": wh,
|
||||
"status": "skipped",
|
||||
"success": False,
|
||||
"skipped": True,
|
||||
"skip_reason": "no_inventory_data",
|
||||
"message": str(exc),
|
||||
})
|
||||
print(f"[inventory-batch] {site} export skipped {code}/{wh}: {exc}")
|
||||
except Exception as exc:
|
||||
results.append({
|
||||
"source_code": code,
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": wh,
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"error_code": "rpa_export_failed",
|
||||
"error_message": str(exc),
|
||||
})
|
||||
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
|
||||
@@ -852,16 +966,28 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
|
||||
|
||||
try:
|
||||
batch_summary = _summarize_inventory_batch_results(results)
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
|
||||
"run_no": run_no,
|
||||
"success": any(item.get("success") for item in results),
|
||||
"status": batch_summary["status"],
|
||||
"success": batch_summary["success"],
|
||||
"has_success": batch_summary["has_success"],
|
||||
"success_count": batch_summary["success_count"],
|
||||
"skipped_count": batch_summary["skipped_count"],
|
||||
"failed_count": batch_summary["failed_count"],
|
||||
"rpa_mode": mode,
|
||||
"trigger_type": body.get("trigger_type"),
|
||||
"schedule_run_id": body.get("schedule_run_id"),
|
||||
"results": results,
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[inventory-batch] callback done run={run_no} success={sum(1 for r in results if r.get('success'))}/{len(results)}")
|
||||
print(
|
||||
f"[inventory-batch] callback done run={run_no} "
|
||||
f"status={batch_summary['status']} "
|
||||
f"success={batch_summary['success_count']} "
|
||||
f"skipped={batch_summary['skipped_count']} "
|
||||
f"failed={batch_summary['failed_count']}/{len(results)}"
|
||||
)
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
|
||||
@@ -885,6 +1011,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir)
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
|
||||
"task_no": task_no,
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(out_file),
|
||||
"rpa_mode": mode,
|
||||
@@ -892,11 +1019,34 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
|
||||
})
|
||||
_move_trigger(trigger_path, processed_dir, "processed")
|
||||
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
|
||||
except NoInventoryDataError as exc:
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
|
||||
"task_no": task_no,
|
||||
"status": "skipped",
|
||||
"success": False,
|
||||
"skipped": True,
|
||||
"skip_reason": "no_inventory_data",
|
||||
"message": str(exc),
|
||||
"rpa_mode": mode,
|
||||
"source_code": (
|
||||
(body.get("rpa_inventory_source") or {}).get("source_code")
|
||||
if isinstance(body.get("rpa_inventory_source"), dict)
|
||||
else None
|
||||
),
|
||||
})
|
||||
if trigger_path.exists():
|
||||
trigger_path.unlink(missing_ok=True)
|
||||
print(f"[inventory] {mode} export skipped for {task_no}: {exc}")
|
||||
except Exception as callback_exc:
|
||||
_report_callback_failure(trigger_path, failed_dir, callback_exc)
|
||||
except Exception as exc:
|
||||
try:
|
||||
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
|
||||
"task_no": task_no,
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
"skipped": False,
|
||||
"rpa_mode": mode,
|
||||
"error_message": str(exc),
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user