feat(shipping-notice): 增加 RPA 库存回调处理逻辑,支持跳过无库存情况
This commit is contained in:
1 parent
f21216f81e
commit
c3f05ba96b
25 files changed
+1619
-81
No files matched your search
@@ -557,6 +557,121 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
|
||||
)
|
||||
|
||||
|
||||
def _normalize_rpa_inventory_result_status(payload: dict[str, Any]) -> str:
|
||||
"""
|
||||
归一化单任务 RPA 库存回调结果。
|
||||
|
||||
核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段;
|
||||
缺省 success 视为 true(历史单任务回调兼容)。
|
||||
|
||||
Returns:
|
||||
str: success | skipped | failed
|
||||
"""
|
||||
raw_status = str(payload.get("status") or "").strip().lower()
|
||||
if raw_status in {"success", "skipped", "failed"}:
|
||||
return raw_status
|
||||
if payload.get("skipped"):
|
||||
return "skipped"
|
||||
if bool(payload.get("success", True)):
|
||||
return "success"
|
||||
return "failed"
|
||||
|
||||
|
||||
def _normalize_rpa_inventory_batch_item_status(item: dict[str, Any]) -> str:
|
||||
"""
|
||||
归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。
|
||||
|
||||
核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或
|
||||
缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。
|
||||
|
||||
Returns:
|
||||
str: success | skipped | failed
|
||||
"""
|
||||
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_rpa_inventory_batch_outcome(
|
||||
*,
|
||||
created: list[Any],
|
||||
skipped: list[Any],
|
||||
failed: list[Any],
|
||||
) -> str:
|
||||
"""
|
||||
汇总批量库存回调业务结果(与 worker batch status 语义对齐)。
|
||||
|
||||
Returns:
|
||||
str: success | partial_failed | failed
|
||||
"""
|
||||
success_count = len(created)
|
||||
skipped_count = len(skipped)
|
||||
failed_count = len(failed)
|
||||
if failed_count == 0:
|
||||
return "success"
|
||||
if success_count == 0 and skipped_count == 0:
|
||||
return "failed"
|
||||
return "partial_failed"
|
||||
|
||||
|
||||
def _resolve_rpa_inventory_batch_response_outcome(
|
||||
*,
|
||||
created: list[Any],
|
||||
skipped: list[Any],
|
||||
failed: list[Any],
|
||||
finalize_result: dict[str, Any],
|
||||
schedule_run_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
汇总批量回调响应中的 result_status 与计数。
|
||||
|
||||
核心逻辑:非排程场景仅按回调 results 计算;含 schedule_run_id 且 finalize 成功时,
|
||||
优先采用 finalize 的 run_status 与 success/skipped/failed 计数,与 ScheduleRun 终态一致。
|
||||
"""
|
||||
callback_result_status = _summarize_rpa_inventory_batch_outcome(
|
||||
created=created,
|
||||
skipped=skipped,
|
||||
failed=failed,
|
||||
)
|
||||
outcome = {
|
||||
"result_status": callback_result_status,
|
||||
"callback_result_status": callback_result_status,
|
||||
"success_count": len(created),
|
||||
"skipped_count": len(skipped),
|
||||
"failed_count": len(failed),
|
||||
}
|
||||
if schedule_run_id is None or not finalize_result.get("ok"):
|
||||
return outcome
|
||||
|
||||
run_status = str(finalize_result.get("run_status") or "").strip()
|
||||
if run_status:
|
||||
outcome["result_status"] = run_status
|
||||
if finalize_result.get("success_count") is not None:
|
||||
outcome["success_count"] = int(finalize_result["success_count"])
|
||||
if finalize_result.get("skipped_count") is not None:
|
||||
outcome["skipped_count"] = int(finalize_result["skipped_count"])
|
||||
if finalize_result.get("failed_count") is not None:
|
||||
outcome["failed_count"] = int(finalize_result["failed_count"])
|
||||
return outcome
|
||||
|
||||
|
||||
def _inventory_rpa_skipped_message(*, skip_reason: str, detail: str) -> str:
|
||||
"""
|
||||
生成单任务「无库存跳过」的人工作业提示。
|
||||
|
||||
核心逻辑:skipped 不是 RPA 技术失败,提示用户确认仓库或改用手动上传。
|
||||
"""
|
||||
if skip_reason == "no_inventory_data":
|
||||
return "货代系统显示该仓当前无可用库存,请确认仓库是否正确,或改用手动上传库存 Excel。"
|
||||
base = detail.strip() or "货代库存导出已跳过"
|
||||
return f"{base}。请确认仓库是否正确,或改用手动上传库存 Excel。"
|
||||
|
||||
|
||||
def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
@@ -565,11 +680,53 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
|
||||
# [STEP 1] 先处理 RPA 回调失败分支。
|
||||
# 失败时要累计尝试次数,并在耗尽后明确切换到人工上传兜底。
|
||||
success = bool(payload.get("success", True))
|
||||
runtime = _save_last_inventory_rpa_runtime(task, payload)
|
||||
if not success:
|
||||
callback_status = _normalize_rpa_inventory_result_status(payload)
|
||||
|
||||
# [STEP 1] skipped:已执行但无库存,记审计事件,不计入 RPA 技术失败重试。
|
||||
if callback_status == "skipped":
|
||||
skip_reason = str(payload.get("skip_reason") or "no_inventory_data").strip()
|
||||
detail = str(payload.get("message") or payload.get("error_message") or "").strip()
|
||||
message = _inventory_rpa_skipped_message(skip_reason=skip_reason, detail=detail)
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = None
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload["inventory_rpa_skipped"] = {
|
||||
"skip_reason": skip_reason,
|
||||
"message": detail or message,
|
||||
"reported_at": datetime.utcnow().isoformat(),
|
||||
"rpa_runtime": runtime,
|
||||
}
|
||||
task.step_payload_json = step_payload
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="货代系统当前无可用库存",
|
||||
progress_percent=100,
|
||||
detail="请确认仓库是否正确,或手动上传货代库存 Excel。",
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_rpa_skipped",
|
||||
{
|
||||
"skip_reason": skip_reason,
|
||||
"message": detail or message,
|
||||
"rpa_runtime": runtime,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=message,
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
)
|
||||
|
||||
# [STEP 2] failed:RPA 技术失败,累计尝试次数并在耗尽后转人工上传兜底。
|
||||
if callback_status == "failed":
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500]
|
||||
log_task_event(task, "inventory_rpa_failed", {"error": task.error_message, "rpa_runtime": runtime})
|
||||
@@ -595,7 +752,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
# [STEP 2] 成功回调后先把 RPA 文件正式纳入系统库存目录,再交给统一 ingest。
|
||||
# [STEP 3] 成功回调后先把 RPA 文件正式纳入系统库存目录,再交给统一 ingest。
|
||||
# 这样 inventory_uploads 会保留任务级正式附件,回调路径也能与人工上传共享同一托管约定。
|
||||
file_path = str(payload.get("file_path") or "").strip()
|
||||
path = Path(file_path) if file_path else find_latest_inventory_file()
|
||||
@@ -662,6 +819,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
核心逻辑:遍历 results;定时任务只入库;带 task_no 的成功项关联对应任务;
|
||||
含 schedule_run_id 时委托 finalize 终态化排程 run。
|
||||
响应:tool_response.status 恒为 ok(payload 合法且处理完成);业务成败看 result_status。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
|
||||
@@ -678,13 +836,14 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
created: list[dict[str, Any]] = []
|
||||
failed: list[dict[str, Any]] = []
|
||||
skipped: list[dict[str, Any]] = []
|
||||
|
||||
for item in results:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
source_code = str(item.get("source_code") or "").strip().upper()
|
||||
warehouse_id = str(item.get("warehouse_id") or "").strip()
|
||||
success = bool(item.get("success", False))
|
||||
raw_status = _normalize_rpa_inventory_batch_item_status(item)
|
||||
source = build_rpa_inventory_source(source_code) or {
|
||||
"source_code": source_code,
|
||||
"site_id": item.get("site_id"),
|
||||
@@ -692,11 +851,16 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"source_type": item.get("source_type"),
|
||||
}
|
||||
|
||||
if success:
|
||||
if raw_status == "success":
|
||||
file_path = str(item.get("file_path") or "").strip()
|
||||
path = Path(file_path) if file_path else None
|
||||
if not path or not path.is_file():
|
||||
failed.append({"source_code": source_code, "warehouse_id": warehouse_id, "error": "file_missing"})
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"error": "file_missing",
|
||||
})
|
||||
continue
|
||||
inv_file = create_inventory_snapshot_from_rpa(
|
||||
source=source,
|
||||
@@ -710,6 +874,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
created.append({
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"source_code": source_code,
|
||||
"site_id": item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
})
|
||||
|
||||
@@ -733,6 +898,14 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
require_mapping_review=True,
|
||||
event_type="inventory_rpa_ready",
|
||||
)
|
||||
elif raw_status == "skipped":
|
||||
skipped.append({
|
||||
"source_code": source_code,
|
||||
"site_id": item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"skip_reason": item.get("skip_reason") or "skipped",
|
||||
"message": item.get("message") or item.get("error_message") or "",
|
||||
})
|
||||
else:
|
||||
create_inventory_snapshot_from_rpa(
|
||||
source=source,
|
||||
@@ -745,7 +918,9 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"error_code": item.get("error_code") or "rpa_export_failed",
|
||||
"error": item.get("error_message"),
|
||||
})
|
||||
|
||||
@@ -758,6 +933,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
finalize_result = finalize_shipping_inventory_schedule_run(
|
||||
schedule_run_id,
|
||||
created=created,
|
||||
skipped=skipped,
|
||||
failed=failed,
|
||||
payload=payload,
|
||||
)
|
||||
@@ -765,6 +941,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
response_data = {
|
||||
"run_no": run_no,
|
||||
"created": created,
|
||||
"skipped": skipped,
|
||||
"failed": failed,
|
||||
"rpa_mode": payload.get("rpa_mode"),
|
||||
"schedule_finalize_status": finalize_result.get("schedule_finalize_status"),
|
||||
@@ -774,8 +951,32 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if finalize_result.get("manual_retryable"):
|
||||
response_data["schedule_finalize_manual_retryable"] = True
|
||||
|
||||
outcome = _resolve_rpa_inventory_batch_response_outcome(
|
||||
created=created,
|
||||
skipped=skipped,
|
||||
failed=failed,
|
||||
finalize_result=finalize_result,
|
||||
schedule_run_id=schedule_run_id,
|
||||
)
|
||||
result_status = str(outcome["result_status"])
|
||||
response_data["result_status"] = result_status
|
||||
response_data["callback_result_status"] = outcome["callback_result_status"]
|
||||
response_data["success_count"] = outcome["success_count"]
|
||||
response_data["skipped_count"] = outcome["skipped_count"]
|
||||
response_data["failed_count"] = outcome["failed_count"]
|
||||
|
||||
return tool_response(
|
||||
status="ok" if created else "failed",
|
||||
message=f"批量库存回调完成:成功 {len(created)},失败 {len(failed)}",
|
||||
status="ok",
|
||||
message=(
|
||||
f"批量库存回调完成({result_status}):"
|
||||
f"成功 {outcome['success_count']},跳过 {outcome['skipped_count']},"
|
||||
f"失败 {outcome['failed_count']}"
|
||||
),
|
||||
data=response_data,
|
||||
extra={
|
||||
"result_status": result_status,
|
||||
"success_count": outcome["success_count"],
|
||||
"skipped_count": outcome["skipped_count"],
|
||||
"failed_count": outcome["failed_count"],
|
||||
},
|
||||
)
|
||||
Reference in new issue
Block a user