feat(shipping-notice): 完成货代发货通知全门禁恢复MVP收口

完成全门禁恢复MVP版本交付:调整自动上传与重试配置,重构正式执行链路;修复多处代码bug,新增测试与审计工具;更新全流程文档与契约规范。
This commit is contained in:
hugo committed 2026-08-11 14:04:39 +08:00
1 parent 8e0bbf7a81
commit c94d173f92
181 files changed
+12947 -1724

No files matched your search

+113 -9
View File
@@ -446,6 +446,25 @@ def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exceptio
_move_trigger(trigger_path, failed_dir, "callback failed")
_INVENTORY_V2_REQUIRED_FIELDS = (
"schema_version", "callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
"lease_token", "candidate_set_id", "execution_id", "gate_id",
"expected_warehouse_id",
)
def _inventory_v2_identity_errors(body: dict[str, Any]) -> list[str]:
"""校验库存 RPA v2 Trigger 身份;缺失字段时禁止启动外部库存操作。"""
missing = []
for key in _INVENTORY_V2_REQUIRED_FIELDS:
value = body.get(key)
if value is None or (isinstance(value, str) and not value.strip()):
missing.append(key)
if body.get("schema_version") != "shipping_inventory_rpa.v2":
missing.append("schema_version")
return list(dict.fromkeys(missing))
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
sample = _env("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY")
if sample and Path(sample).is_file():
@@ -995,6 +1014,38 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
if not isinstance(sources, list) or not sources:
trigger_path.unlink(missing_ok=True)
return
identity_errors = []
if body.get("schema_version") != "shipping_inventory_rpa.v2":
identity_errors.append("schema_version")
if body.get("callback_id") is None or (isinstance(body.get("callback_id"), str) and not body.get("callback_id").strip()):
identity_errors.append("callback_id")
if body.get("task_no") is None or (isinstance(body.get("task_no"), str) and not body.get("task_no").strip()):
identity_errors.append("task_no")
for index, source in enumerate(sources):
if not isinstance(source, dict):
identity_errors.append(f"inventory_sources[{index}]")
continue
identity_errors.extend(
f"inventory_sources[{index}].{key}"
for key in _INVENTORY_V2_REQUIRED_FIELDS
if key not in {"schema_version", "task_no", "callback_id"}
and (source.get(key) is None or (isinstance(source.get(key), str) and not source.get(key).strip()))
)
if identity_errors:
try:
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": None,
"batch_run_no": run_no or None,
"business_status": "rejected",
"status": "rejected",
"error_code": "trigger_identity_invalid",
"identity_errors": list(dict.fromkeys(identity_errors)),
"results": [],
})
finally:
_move_trigger(trigger_path, failed_dir, "invalid v2 identity")
return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
mode = "mock" if mock else "browser"
@@ -1103,6 +1154,30 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
if runtime_profile_dir is not None:
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
# v2 业务结果必须原样保留逐源身份,后端据此绑定 SourceAttempt;
# Worker 不生成新身份,只从已校验的 trigger source 复制。
source_identity_by_key = {
(
str(source.get("source_code") or "").strip().upper(),
str(source.get("expected_warehouse_id") or source.get("warehouse_id") or "").strip().upper(),
): source
for source in sources
if isinstance(source, dict)
}
for result in results:
source = source_identity_by_key.get((
str(result.get("source_code") or "").strip().upper(),
str(result.get("warehouse_id") or result.get("expected_warehouse_id") or "").strip().upper(),
))
if not source:
continue
for key in (
"callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
"lease_token", "candidate_set_id", "execution_id", "gate_id", "expected_warehouse_id",
):
if key in source:
result[key] = source.get(key)
try:
batch_summary = _summarize_inventory_batch_results(results)
trigger_type = str(body.get("trigger_type") or "").strip()
@@ -1125,6 +1200,9 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
else:
callback_path = "/api/shipping-notice/rpa/inventory-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,
"status": batch_summary["status"],
"success": batch_summary["success"],
@@ -1163,36 +1241,62 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
trigger_path.unlink(missing_ok=True)
return
identity_errors = _inventory_v2_identity_errors({**body, "task_no": task_no})
if identity_errors:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": None,
"task_no": task_no,
"business_status": "rejected",
"status": "rejected",
"error_code": "trigger_identity_invalid",
"identity_errors": identity_errors,
})
finally:
_move_trigger(trigger_path, failed_dir, "invalid v2 identity")
return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true"
mode = "mock" if mock else "browser"
# 单源 Trigger 与 batch 使用同一 v2 身份契约;Worker 只能回传后端冻结的字段。
identity = {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": str(body.get("callback_id") or "").strip(),
"task_no": task_no,
"source_code": str(body.get("source_code") or ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else "") or "").strip().upper(),
"source_run_no": str(body.get("source_run_no") or "").strip(),
"run_no": str(body.get("source_run_no") or "").strip(),
"attempt_no": body.get("attempt_no") or body.get("attempt"),
"lease_token": str(body.get("lease_token") or "").strip(),
"candidate_set_id": body.get("candidate_set_id"),
"execution_id": body.get("execution_id"),
"gate_id": body.get("gate_id"),
"expected_warehouse_id": body.get("expected_warehouse_id"),
}
try:
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,
**identity,
"status": "success",
"success": True,
"file_path": str(out_file),
"file_sha256": hashlib.sha256(out_file.read_bytes()).hexdigest(),
"rpa_mode": mode,
"source_code": ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else None),
})
_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,
**identity,
"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)
@@ -1202,7 +1306,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
except Exception as exc:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
**identity,
"status": "failed",
"success": False,
"skipped": False,