fix(shipping-notice,admin-schedule,frontend): 修复发货通知与后台排程的业务bug并优化各模块功能

1.  后端发货通知模块:
    清空重试任务旧状态避免残留,新增RPA进度回调接口
    优化库存匹配性能,修复人工确认校验逻辑与登录弹窗遮挡问题
    新增排程worker启动脚本,清理冗余环境配置与缓存查询开销
2.  前端后台排程模块:
    新增任务key归一化工具兼容历史格式,修复参数表单隐藏问题
    添加加载错误处理,更新多语言文案替换裸JSON占位符
This commit is contained in:
hugo committed 2026-08-26 22:05:25 +08:00
1 parent 1e5aedb9ed
commit 06c18b3c7c
81 files changed
+3301 -424

No files matched your search

+91 -21
View File
@@ -1080,6 +1080,34 @@ def _configuration_test_callback_payload(run_no: str, results: list) -> dict:
}
def _emit_batch_progress(body: dict[str, Any], run_no: str, results: list[dict[str, Any]]) -> None:
"""
定时排程批量导出每完成一个站点即上报累计进度,后端实时回写排程 run 笔数。
核心逻辑:仅 scheduled 触发且携带 schedule_run_id 时上报,按需单票不受影响;
best-effort,上报失败不影响导出与最终回调;最终笔数以 inventory-batch-ready 为准。
"""
if str(body.get("trigger_type") or "").strip() != "scheduled":
return
schedule_run_id = body.get("schedule_run_id")
if schedule_run_id is None:
return
summary = _summarize_inventory_batch_results(results)
try:
_post_callback("/api/shipping-notice/rpa/inventory-batch-progress", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": body.get("callback_id"),
"batch_run_no": run_no,
"run_no": run_no,
"schedule_run_id": schedule_run_id,
"success_count": summary["success_count"],
"skipped_count": summary["skipped_count"],
"failed_count": summary["failed_count"],
})
except Exception as exc:
print(f"[inventory-batch] progress callback failed {run_no}: {exc}", file=sys.stderr)
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("batch_run_no") or body.get("run_no") or trigger_path.stem).strip()
@@ -1094,7 +1122,19 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
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()):
# 定时排程批量触发是按 run 计价的:只携带 run_no/schedule_run_id,没有逐源
# Attempt/Gate 身份。身份校验按模式取值:scheduled 只强制信封与站点分发字段,
# 业务终态由后端按 schedule_run_id + DB 配置校验;其余模式保持逐源身份 fail-closed。
is_scheduled_batch = str(body.get("trigger_type") or "").strip() == "scheduled"
source_required = set(_INVENTORY_V2_REQUIRED_FIELDS) - {"schema_version", "task_no", "callback_id"}
if is_scheduled_batch:
source_required -= {
"task_no", "source_run_no", "attempt_no", "lease_token", "candidate_set_id",
"execution_id", "gate_id", "callback_id", "expected_warehouse_id",
}
if not is_scheduled_batch and (
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):
@@ -1107,9 +1147,8 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
).strip().lower() not in {"crane", "crane_footprint"}
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 (key != "expected_warehouse_id" or requires_expected_warehouse)
for key in source_required
if (key != "expected_warehouse_id" or requires_expected_warehouse)
and (source.get(key) is None or (isinstance(source.get(key), str) and not source.get(key).strip()))
)
if identity_errors:
@@ -1152,6 +1191,11 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
mode = "mock" if mock else "browser"
results: list[dict[str, Any]] = []
def record_result(item: dict[str, Any]) -> None:
"""记录单站点结果并即时上报累计进度(仅定时排程会真正上报)。"""
results.append(item)
_emit_batch_progress(body, run_no, results)
# v2 claimed 回调只记录领取事实,不代表业务成功。
if body.get("schema_version") == "shipping_inventory_rpa.v2":
claimed_items = []
@@ -1191,7 +1235,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
report_configuration_test_progress(source)
task_stub = run_no
out_file = _write_sample_inventory(drop_dir, task_stub)
results.append({
record_result({
"source_code": source.get("source_code"),
"warehouse_id": source.get("warehouse_id"),
"status": "success",
@@ -1228,28 +1272,52 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
_validate_inventory_source_for_rpa(source)
skip_navigation = False
if site == "dsv360":
# DSV 报表页会保留 iframe、导出菜单与下载等待状态;同一 tab
# 串行切换站点会让下一站误用上一站页面。复用 context 登录态,但每站新开页面。
if index > 0:
# [STEP 3] 批内同一 Profile 只登录一次:首源完整登录,后续源复用当前 tab
# 的登录态——同导航走 _return_to_dsv_report_parameters 复用参数页,
# 导航不同走 _reset_dsv_export_entry(goto entry + 会话检测,不重复 OAuth)。
# 曾因"每源新开空白页 + 写死 index=0"导致每源重复走 SSO 重定向链
# (每源 2-2.5 分钟,且偶发 OAuth 空白页单源失败),现已移除。
# 页面串站状态由整页/帧重载兜底,无需隔离页。
previous_source = site_sources[index - 1] if index > 0 else None
try:
# 返回 True 表示参数页已就绪:后续跳过菜单导航直接填参/导出。
skip_navigation = bool(
_prepare_dsv_batch_export_step(page, entry_url, previous_source, source, index=index)
)
except Exception as exc:
# 会话复用的安全网:登录/会话类偶发异常(SSO/OAuth 链、
# “密码升级”弹窗遮挡、字段未渲染)时,新开干净页面重试一次完整登录;
# 凭据校验类(invalid/verification)不重试,直接失败。
message = str(exc).lower()
login_related = any(token in message for token in ("login", "session", "oauth"))
credential_mismatch = any(token in message for token in ("invalid", "verification"))
if not login_related or credential_mismatch:
raise
print(
f"[inventory-batch] dsv360 session prepare failed for {code}, retry with clean page: {exc}",
file=sys.stderr,
)
page = _open_clean_batch_page(context, page)
_prepare_dsv_batch_export_step(page, entry_url, None, source, index=0)
skip_navigation = bool(
_prepare_dsv_batch_export_step(page, entry_url, None, source, index=0)
)
elif index == 0:
_ensure_crane_session(page, entry_url)
else:
_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 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")}})
record_result({"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")})
record_result({"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")})
print(f"[inventory-batch] {site} export skipped {code}/{wh}: {exc}")
except Exception as exc:
results.append({"source_code": code, "warehouse_id": wh, "status": "failed", "success": False, "error_code": "rpa_export_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
record_result({"source_code": code, "warehouse_id": wh, "status": "failed", "success": False, "error_code": "rpa_export_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
except Exception as exc:
for source in site_sources:
results.append({"source_code": source.get("source_code"), "warehouse_id": source.get("warehouse_id"), "status": "failed", "success": False, "error_code": "rpa_profile_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
record_result({"source_code": source.get("source_code"), "warehouse_id": source.get("warehouse_id"), "status": "failed", "success": False, "error_code": "rpa_profile_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
finally:
_close_batch_browser_resources(context, playwright, runtime_profile_dir)
@@ -1837,20 +1905,22 @@ def main() -> None:
print(f" drop={drop_dir}")
print(f" queue={upload_queue_dir}")
last_heartbeat_mono = 0.0
last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
# 启动时立即上报一次,让管理端第一时间看到 Worker 上线。
freight_rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
last_sent_mono=last_heartbeat_mono,
last_sent_mono=0.0,
force=True,
)
# 心跳节奏交由独立守护线程承担:批量站点导出会长时间阻塞主循环,
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
freight_rpa_heartbeat.start_heartbeat_loop(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
interval_seconds=heartbeat_seconds,
)
while True:
last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
last_sent_mono=last_heartbeat_mono,
)
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
time.sleep(poll)