feat(schedule): 增加库存源选项描述字段与站点ID支持
This commit is contained in:
1 parent
f4e74f7b07
commit
8b1efbedb9
37 files changed
+8488
-4126
No files matched your search
@@ -0,0 +1,466 @@
|
||||
"""
|
||||
scripts/rpa/rpa_common.py
|
||||
|
||||
用途:RPA worker 与 DSV/Crane driver 共用的浏览器与环境变量工具。
|
||||
依赖:标准库、Playwright(运行时)。
|
||||
逻辑:由 freight_rpa_worker、dsv_*、crane_* 导入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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 环境变量,并兼容 .env 中常见的外层单双引号写法。
|
||||
|
||||
核心逻辑:先读取原始环境变量并去除首尾空白;若值整体被同种引号包裹,
|
||||
再剥离最外层一对引号,避免账号密码把引号一并输入到第三方登录页。
|
||||
|
||||
Args:
|
||||
name: 环境变量名。
|
||||
default: 未设置时的默认值。
|
||||
|
||||
Returns:
|
||||
str: 去除空白与外层成对引号后的环境变量值。
|
||||
"""
|
||||
value = str(os.getenv(name) 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_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_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 = Path(__file__).resolve().parent / "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_{prefix}_USERNAME"
|
||||
password_env = f"FREIGHT_RPA_{prefix}_PASSWORD"
|
||||
if not _env(username_env) or not _env(password_env):
|
||||
return
|
||||
|
||||
user_filled = _fill_login_field(
|
||||
page,
|
||||
f"FREIGHT_RPA_{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_{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_{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