feat(rpa): 恢复FREIGHT_RPA命名空间统一运行目录并完成收料部署对齐与readiness加固
- AGENTS.md §8.1 红线改写:env 命名空间恢复 FREIGHT_RPA_*,SHIPPING_NOTICE_RPA_* 一刀切废弃、不设兼容层
- 全仓机械前缀替换(70 文件)并删除兼容层;4 个既有基线测试失败一并清零(过期桩/存储隔离/排程 fail-fast 接线)
- 运行期数据目录统一 freight_rpa/{inventory,receipt,common}:settings 默认、4 个 env、2 个 ps1 三侧一致
- 代码目录 scripts/rpa 更名 scripts/freight_rpa 与数据根对齐;全仓路径引用同步,README 部署走查与升级小节
- 收料部署对齐库存:计划任务注册脚本(独立任务名)、可选 -SessionReuse 会话复用、DSV 老别名链移除
- readiness 加固:排程离线立即 failed(不挂 awaiting);无 Redis 时追加进程内存储原因码与本地测试指引
- DSV 会话准备遇 SSO 重定向中止时改走自动登录,首源不再因未登录判死
This commit is contained in:
1 parent
95488db656
commit
c3eef5cf20
90 files changed
+2022
-1463
No files matched your search
@@ -0,0 +1,481 @@
|
||||
"""
|
||||
scripts/freight_rpa/rpa_common.py
|
||||
|
||||
用途:RPA worker 与 DSV/Crane driver 共用的浏览器与环境变量工具。
|
||||
依赖:标准库、Playwright(运行时)。
|
||||
逻辑:由 freight_rpa_worker、dsv_*、crane_* 导入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys as _sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
_RPA_ROOT = next(
|
||||
(_c for _c in _Path(__file__).resolve().parents
|
||||
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
|
||||
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
|
||||
None,
|
||||
)
|
||||
if _RPA_ROOT is not None:
|
||||
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
|
||||
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
|
||||
if _dir not in _sys.path:
|
||||
_sys.path.insert(0, _dir)
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any, TextIO
|
||||
|
||||
|
||||
def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
|
||||
"""惰性委托 dsv_debug.emit_debug_event,避免 rpa_common ↔ dsv_debug 循环导入。"""
|
||||
try:
|
||||
from dsv_debug import emit_debug_event
|
||||
|
||||
emit_debug_event(run_id, hypothesis_id, location, msg, data)
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
def _env(name: str, default: str = "") -> str:
|
||||
"""
|
||||
读取 RPA 环境变量,并去除首尾空白与最外层成对引号。
|
||||
|
||||
核心逻辑:直接读取规范名称;历史 SHIPPING_NOTICE_RPA_* 前缀已于
|
||||
2026-09-18 一刀切废弃,不再提供任何别名兼容。
|
||||
|
||||
Args:
|
||||
name: 规范环境变量名(FREIGHT_RPA_*)。
|
||||
default: 未设置时的默认值。
|
||||
|
||||
Returns:
|
||||
str: 去除空白与外层成对引号后的环境变量值。
|
||||
"""
|
||||
value = str(os.getenv(name, default) or default).strip()
|
||||
if len(value) >= 2 and (
|
||||
(value.startswith('"') and value.endswith('"'))
|
||||
or (value.startswith("'") and value.endswith("'"))
|
||||
):
|
||||
return value[1:-1]
|
||||
return value
|
||||
|
||||
|
||||
def _browser_timeout_ms() -> int:
|
||||
return max(5_000, int(_env("FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS", "60000") or "60000"))
|
||||
|
||||
def _click_text(page: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> None:
|
||||
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
text_literal = json.dumps(text)
|
||||
for selector in (
|
||||
f"a.dropdown-item:has-text({text_literal})",
|
||||
f".dropdown-item:has-text({text_literal})",
|
||||
f"button:has-text({text_literal})",
|
||||
f'[role="button"]:has-text({text_literal})',
|
||||
f"a:has-text({text_literal})",
|
||||
f"li:has-text({text_literal})",
|
||||
f"div.device-type:has-text({text_literal})",
|
||||
):
|
||||
locator = page.locator(selector).first
|
||||
try:
|
||||
locator.click(timeout=3_000)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=3_000, force=True)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
for role in ("button", "link"):
|
||||
try:
|
||||
page.get_by_role(role, name=text, exact=exact).first.click(timeout=3_000)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator = page.get_by_text(text, exact=False).first
|
||||
try:
|
||||
locator.click(timeout=min(timeout, 3_000))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.click(timeout=min(timeout, 3_000), force=True)
|
||||
|
||||
|
||||
def _click_selector_or_text(page: Any, selector_env: str, fallback_text: str | None = None) -> None:
|
||||
selector = _env(selector_env)
|
||||
if selector:
|
||||
page.locator(selector).first.click(timeout=_browser_timeout_ms())
|
||||
return
|
||||
if selector_env == "FREIGHT_RPA_WORKER_DSV_VIEW_REPORT_SELECTOR":
|
||||
for view_selector in (
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'button:has-text("View Report")',
|
||||
'.btn:has-text("View Report")',
|
||||
'input[value="View Report"]',
|
||||
'[role="button"]:has-text("View Report")',
|
||||
):
|
||||
try:
|
||||
locator = page.locator(view_selector).first
|
||||
locator.wait_for(state="visible", timeout=30_000)
|
||||
locator.evaluate("(node) => node.click()")
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
if fallback_text:
|
||||
_click_text(page, fallback_text, exact=True)
|
||||
return
|
||||
raise RuntimeError(f"Missing selector env: {selector_env}")
|
||||
|
||||
|
||||
def _fill_selector_or_label(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
selector = _env(selector_env)
|
||||
locator = page.locator(selector).first if selector else page.get_by_label(label).first
|
||||
try:
|
||||
current = str(locator.input_value(timeout=3_000) or "").strip()
|
||||
if current == text:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.fill(text, timeout=_browser_timeout_ms())
|
||||
|
||||
|
||||
def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
"""委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。"""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
module_path = _RPA_ROOT / "connectors" / "dsv" / "dsv_report_parameters.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
module.fill_dsv_filter_if_needed(
|
||||
page,
|
||||
selector_env,
|
||||
label,
|
||||
value,
|
||||
env=_env,
|
||||
browser_timeout_ms=_browser_timeout_ms,
|
||||
debug_stage=_debug_dsv_stage,
|
||||
)
|
||||
|
||||
|
||||
def _select_or_fill(page: Any, selector_env: str, label: str, value: str | None) -> None:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
selector = _env(selector_env)
|
||||
locator = page.locator(selector).first if selector else page.get_by_label(label)
|
||||
try:
|
||||
locator.select_option(label=text, timeout=_browser_timeout_ms())
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.select_option(value=text, timeout=_browser_timeout_ms())
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
locator.fill(text, timeout=_browser_timeout_ms())
|
||||
|
||||
|
||||
def _visible_locator(page: Any, selector: str | None):
|
||||
if not selector:
|
||||
return None
|
||||
for frame in page.frames:
|
||||
locator = frame.locator(selector).first
|
||||
try:
|
||||
return locator if locator.is_visible(timeout=1_000) else None
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _visible_locator_in_root(root: Any, selector: str | None):
|
||||
if not selector:
|
||||
return None
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
return locator if locator.is_visible(timeout=1_000) else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _click_text_in_root(root: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> bool:
|
||||
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
text_literal = json.dumps(text)
|
||||
for selector in (
|
||||
f'a.dropdown-item:has-text({text_literal})',
|
||||
f'.dropdown-item:has-text({text_literal})',
|
||||
f'button:has-text({text_literal})',
|
||||
f'[role="button"]:has-text({text_literal})',
|
||||
f'a:has-text({text_literal})',
|
||||
f'li:has-text({text_literal})',
|
||||
f'span:has-text({text_literal})',
|
||||
):
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.click(timeout=min(timeout, 3_000))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.click(timeout=min(timeout, 3_000), force=True)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
for role in ("button", "link"):
|
||||
try:
|
||||
root.get_by_role(role, name=text, exact=exact).first.click(timeout=min(timeout, 3_000))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000))
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000), force=True)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _click_visible_selector_or_text_in_root(root: Any, selector: str | None, fallback_texts: tuple[str, ...]) -> bool:
|
||||
locator = _visible_locator_in_root(root, selector)
|
||||
if locator is not None:
|
||||
# #region debug-point H4:root-selector-click-attempt
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-attempt",
|
||||
"[DEBUG] attempting selector click in selected root",
|
||||
{"selector": selector or "", "fallbackTexts": list(fallback_texts)},
|
||||
)
|
||||
# #endregion
|
||||
try:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
# #region debug-point H4:root-selector-click-success
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-success",
|
||||
"[DEBUG] selector click succeeded in selected root",
|
||||
{"selector": selector or ""},
|
||||
)
|
||||
# #endregion
|
||||
return True
|
||||
except Exception as exc:
|
||||
# #region debug-point H4:root-selector-click-error
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-error",
|
||||
"[DEBUG] selector click failed in selected root",
|
||||
{"selector": selector or "", "error": str(exc)[:300]},
|
||||
)
|
||||
# #endregion
|
||||
for text in fallback_texts:
|
||||
# #region debug-point H4:root-text-click-attempt
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-attempt",
|
||||
"[DEBUG] attempting text click in selected root",
|
||||
{"text": text, "selector": selector or ""},
|
||||
)
|
||||
# #endregion
|
||||
clicked = _click_text_in_root(root, text, exact=True, timeout_ms=3_000)
|
||||
# #region debug-point H4:root-text-click-result
|
||||
_emit_debug_event(
|
||||
"pre-fix",
|
||||
"H4",
|
||||
"freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-result",
|
||||
"[DEBUG] text click result in selected root",
|
||||
{"text": text, "clicked": clicked, "selector": selector or ""},
|
||||
)
|
||||
# #endregion
|
||||
if clicked:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _fill_login_field(page: Any, selector_env: str, value_env: str, fallback_selectors: tuple[str, ...]) -> bool:
|
||||
value = _env(value_env)
|
||||
if not value:
|
||||
return False
|
||||
selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item)
|
||||
for selector in selectors:
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is None:
|
||||
continue
|
||||
locator.fill(value, timeout=_browser_timeout_ms())
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _fill_first_visible_text_input(page: Any, value: str) -> bool:
|
||||
for selector in (
|
||||
'input:not([type])',
|
||||
'input[type="text"]',
|
||||
'input[type="email"]',
|
||||
'input',
|
||||
):
|
||||
for frame in page.frames:
|
||||
try:
|
||||
inputs = frame.locator(selector).all()
|
||||
except Exception:
|
||||
inputs = []
|
||||
for locator in inputs:
|
||||
try:
|
||||
if not locator.is_visible(timeout=500) or not _dsv_locator_can_edit(locator):
|
||||
continue
|
||||
locator.fill(value, timeout=2_000)
|
||||
if locator.input_value(timeout=1_000).strip():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_login_submit(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool:
|
||||
selector = _env(selector_env)
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
return True
|
||||
for text in fallback_texts:
|
||||
try:
|
||||
page.get_by_role("button", name=text).click(timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.get_by_text(text, exact=True).click(timeout=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _click_visible_selector_or_text(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool:
|
||||
selector = _env(selector_env)
|
||||
locator = _visible_locator(page, selector)
|
||||
if locator is not None:
|
||||
locator.click(timeout=_browser_timeout_ms())
|
||||
return True
|
||||
if any(text in {"登录", "Login", "Log in", "Sign in"} for text in fallback_texts):
|
||||
for submit_selector in (
|
||||
'button[type="submit"]',
|
||||
'input[type="submit"]',
|
||||
"#signOnButton",
|
||||
".btn-primary",
|
||||
):
|
||||
locator = _visible_locator(page, submit_selector)
|
||||
if locator is None:
|
||||
continue
|
||||
locator.click(timeout=3_000, force=True)
|
||||
return True
|
||||
for text in fallback_texts:
|
||||
try:
|
||||
_click_text(page, text, exact=True, timeout_ms=3_000)
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
def _wait_for_visible_selector(
|
||||
page: Any,
|
||||
selector_env: str,
|
||||
fallback_selectors: tuple[str, ...],
|
||||
*,
|
||||
timeout_ms: int | None = None,
|
||||
):
|
||||
selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item)
|
||||
wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
for selector in selectors:
|
||||
for frame in page.frames:
|
||||
locator = frame.locator(selector).first
|
||||
try:
|
||||
if locator.is_visible(timeout=1_000):
|
||||
return locator
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def _maybe_auto_login(page: Any, prefix: str) -> None:
|
||||
"""
|
||||
如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。
|
||||
"""
|
||||
username_env = f"FREIGHT_RPA_WORKER_{prefix}_USERNAME"
|
||||
password_env = f"FREIGHT_RPA_WORKER_{prefix}_PASSWORD"
|
||||
if not _env(username_env) or not _env(password_env):
|
||||
return
|
||||
|
||||
user_filled = _fill_login_field(
|
||||
page,
|
||||
f"FREIGHT_RPA_WORKER_{prefix}_USERNAME_SELECTOR",
|
||||
username_env,
|
||||
(
|
||||
'input[name="username"]',
|
||||
'input[name="userName"]',
|
||||
'input[name="email"]',
|
||||
'input[type="email"]',
|
||||
'input[type="text"]',
|
||||
),
|
||||
)
|
||||
password_filled = _fill_login_field(
|
||||
page,
|
||||
f"FREIGHT_RPA_WORKER_{prefix}_PASSWORD_SELECTOR",
|
||||
password_env,
|
||||
('input[name="password"]', 'input[type="password"]'),
|
||||
)
|
||||
if not user_filled and not password_filled:
|
||||
return
|
||||
if user_filled != password_filled:
|
||||
raise RuntimeError(f"{prefix} login form partially detected; please configure login selectors")
|
||||
|
||||
if not _click_login_submit(
|
||||
page,
|
||||
f"FREIGHT_RPA_WORKER_{prefix}_LOGIN_BUTTON_SELECTOR",
|
||||
("Sign in", "Login", "Log in", "登录"),
|
||||
):
|
||||
raise RuntimeError(f"{prefix} login fields detected but submit button was not found")
|
||||
|
||||
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
|
||||
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
|
||||
raise RuntimeError(f"{prefix} login did not complete; MFA/SSO/manual verification may be required")
|
||||
|
||||
|
||||
|
||||
# 公开 API
|
||||
env = _env
|
||||
browser_timeout_ms = _browser_timeout_ms
|
||||
click_text = _click_text
|
||||
click_selector_or_text = _click_selector_or_text
|
||||
fill_selector_or_label = _fill_selector_or_label
|
||||
fill_dsv_filter_if_needed = _fill_dsv_filter_if_needed
|
||||
select_or_fill = _select_or_fill
|
||||
visible_locator = _visible_locator
|
||||
visible_locator_in_root = _visible_locator_in_root
|
||||
click_text_in_root = _click_text_in_root
|
||||
click_visible_selector_or_text_in_root = _click_visible_selector_or_text_in_root
|
||||
fill_login_field = _fill_login_field
|
||||
fill_first_visible_text_input = _fill_first_visible_text_input
|
||||
click_login_submit = _click_login_submit
|
||||
click_visible_selector_or_text = _click_visible_selector_or_text
|
||||
wait_for_visible_selector = _wait_for_visible_selector
|
||||
maybe_auto_login = _maybe_auto_login
|
||||
Reference in new issue
Block a user