Merge branch 'dev' into runny827

feat(training): 新增精益培训视频与周任务管理

# Conflicts:
#	backend/app/models/__init__.py
This commit is contained in:
runny committed 2026-09-08 18:29:45 +08:00
commit 85d27e9ffa
28 files changed
+24 -11418

No files matched your search

-99
View File
@@ -1,99 +0,0 @@
"""
scripts/rpa/crane_login_smoke.py
用途:本地手动验证 Crane FootPrint Portal 自动登录。
依赖:Playwright、SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD。
逻辑:打开 On Hand Details Query 入口 → maybe_auto_login_crane → 保持窗口供人工确认。
用法(仓库根目录):
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
backend\\venv\\Scripts\\python.exe scripts\\rpa\\crane_login_smoke.py
"""
from __future__ import annotations
import importlib.util
import os
import shutil
import sys
import tempfile
import traceback
from pathlib import Path
def _load_worker():
repo_root = Path(__file__).resolve().parents[2]
module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main() -> int:
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
os.environ.setdefault(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile",
)
if not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") and not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
worker = _load_worker()
username = worker._env("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME")
password = worker._env("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD")
if not username or not password:
print("[crane-smoke] 缺少 SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD,请先配置环境变量。")
return 1
entry_url = "https://wms-portal.craneww.com/#/on-hand-details-query"
drop_dir = Path(tempfile.mkdtemp(prefix="crane_smoke_drop_"))
playwright = context = runtime_profile_dir = None
print(f"[crane-smoke] headless={worker._env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false')}")
print(f"[crane-smoke] user={username[:3]}*** entry={entry_url}")
print("[crane-smoke] 正在打开浏览器并执行 Crane 自动登录…")
try:
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
worker._ensure_crane_session(page, entry_url)
print(f"[crane-smoke] SUCCESS — Crane session ready, url={page.url}")
print("[crane-smoke] 请在浏览器中确认 On Hand Details Query 表单可见。按 Enter 关闭浏览器…")
try:
input()
except EOFError:
import time
print("[crane-smoke] 非交互终端,保持浏览器 300 秒后自动关闭。")
time.sleep(300)
return 0
except Exception as exc:
print(f"[crane-smoke] FAILED — {exc}")
traceback.print_exc()
print("[crane-smoke] 浏览器将保持打开 120 秒以便排查,按 Enter 提前关闭…")
try:
input()
except EOFError:
import time
time.sleep(120)
return 2
finally:
if context is not None:
try:
context.close()
except Exception:
pass
if playwright is not None:
try:
playwright.stop()
except Exception:
pass
if runtime_profile_dir is not None:
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
shutil.rmtree(drop_dir, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())
-410
View File
@@ -1,410 +0,0 @@
"""
scripts/rpa/crane_navigation.py
用途:Crane FootPrint Portal 报表页导航(On Hand Details Query)。
依赖:Playwright Page;由 crane_session.wait_for_crane_app_ready 在登录后调用。
逻辑:优先点击首页 Queries 区 On Hand Details 卡片;失败再走顶部 Queries 下拉菜单;最后 goto entry_url。
"""
from __future__ import annotations
import sys
import time
from typing import Any, Callable
from urllib.parse import urlparse
_ON_HAND_DETAILS_LABEL = "On Hand Details"
_ON_HAND_DETAILS_ROUTE = "on-hand-details-query"
# 首页 Queries 区大卡片:Vue hash 路由常见 href="#/on-hand-details-query"(非 "/on-hand-details-query")
_CRANE_DASHBOARD_REPORT_TILE_SELECTORS: tuple[str, ...] = (
'a[href*="on-hand-details-query"]',
'a.box[href*="on-hand-details-query"]',
'a.box.has-text-centered[href*="on-hand-details-query"]',
'a.box:has-text("On Hand Details")',
'a:has-text("On Hand Details")',
'.box:has-text("On Hand Details")',
)
# 顶部导航 Queries 下拉(第二张图)
_CRANE_NAV_QUERIES_MENU_SELECTORS: tuple[str, ...] = (
'a.navbar-link:has-text("Queries")',
'.navbar-item.has-dropdown > a.navbar-link',
)
_CRANE_NAV_ON_HAND_DETAILS_SELECTORS: tuple[str, ...] = (
'.navbar-dropdown a.navbar-item:has-text("On Hand Details")',
'a.navbar-item:has-text("On Hand Details")',
)
# 报表表单就绪信号:必须出现 Run Report 或报表参数字段;首页 Queries 区标题不算 ready
_CRANE_REPORT_FORM_READY_SELECTORS: tuple[str, ...] = (
'button:has-text("Run Report")',
'[role="button"]:has-text("Run Report")',
'text=Choose Warehouse',
'text=Select Owner',
)
def _visible_locator(page: Any, selector: str) -> Any | None:
"""在 page 与各 frame 中查找首个可见 locator。"""
for root in (page, *list(getattr(page, "frames", []))):
try:
locator = root.locator(selector).first
if locator.is_visible(timeout=500):
return locator
except Exception:
continue
return None
def _report_route_from_entry_url(entry_url: str) -> str:
"""从 entry_url hash 提取报表路由片段,默认 on-hand-details-query。"""
parsed = urlparse(str(entry_url or "").strip())
fragment = (parsed.fragment or "").strip().lstrip("/").lower()
if fragment:
return fragment
return _ON_HAND_DETAILS_ROUTE
def _current_url_fragment(page: Any) -> str:
"""读取当前页 URL hash 片段(不含 #/ 前缀)。"""
try:
current_url = str(page.url or "")
except Exception:
return ""
parsed = urlparse(current_url)
return (parsed.fragment or "").strip().lstrip("/").lower()
def is_crane_on_homepage(page: Any) -> bool:
"""
判定是否停在 Crane 登录后首页(/#/ 或空 hash)。
核心逻辑:首页 Queries 区有 On Hand Details 卡片,但报表表单尚未打开,不能视为 ready。
"""
fragment = _current_url_fragment(page)
if not fragment or fragment in {"home", "dashboard", "index"}:
return True
return False
def is_crane_on_report_route(page: Any, entry_url: str) -> bool:
"""当前 URL hash 是否已落在目标报表路由。"""
target_route = _report_route_from_entry_url(entry_url)
fragment = _current_url_fragment(page)
if not fragment:
return False
return target_route in fragment
def _has_report_form_controls(page: Any) -> bool:
"""Run Report 或报表参数字段是否可见。"""
for selector in _CRANE_REPORT_FORM_READY_SELECTORS:
if _visible_locator(page, selector) is not None:
return True
return False
def is_crane_report_form_ready(page: Any, entry_url: str) -> bool:
"""
判定 On Hand Details Query 报表表单是否已就绪。
核心逻辑:首页 /#/ 不算 ready;必须 hash 落在报表路由且出现 Run Report / 参数字段。
"""
if is_crane_on_homepage(page):
return False
if not is_crane_on_report_route(page, entry_url):
return False
return _has_report_form_controls(page)
def _click_visible_locator(locator: Any, *, browser_timeout_ms: int) -> bool:
try:
locator.click(timeout=browser_timeout_ms)
return True
except Exception:
pass
try:
locator.click(timeout=browser_timeout_ms, force=True)
return True
except Exception:
return False
def _wait_for_crane_homepage_ready(page: Any, *, browser_timeout_ms: int) -> bool:
"""
登录后等待首页 Queries 区渲染完成。
核心逻辑:On Hand Details 卡片或 Queries 标题出现后再尝试点击,避免 SPA 未挂载时误判失败。
"""
deadline = time.monotonic() + (min(browser_timeout_ms, 20_000) / 1000)
while time.monotonic() < deadline:
for selector in (
'text=On Hand Details',
'text=Queries',
'a[href*="on-hand-details-query"]',
'.box:has-text("On Hand Details")',
):
if _visible_locator(page, selector) is not None:
print("[crane-nav] homepage shell ready")
return True
time.sleep(0.25)
print("[crane-nav] homepage shell not detected before timeout", file=sys.stderr)
return False
def _click_by_role_link(page: Any, name: str, *, browser_timeout_ms: int) -> bool:
for root in (page, *list(getattr(page, "frames", []))):
try:
locator = root.get_by_role("link", name=name, exact=False).first
if locator.is_visible(timeout=500):
return _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms)
except Exception:
pass
return False
def _click_on_hand_details_tile(page: Any, *, browser_timeout_ms: int) -> bool:
"""
通过文本语义点击首页 Queries 区的 On Hand Details 卡片。
核心逻辑:hash 路由下 tile 可能是 a[href*=#/on-hand-details-query] 或 .box 包裹的 router-link。
"""
tile_selectors = (
'.columns .box:has-text("On Hand Details")',
'section:has-text("Queries") .box:has-text("On Hand Details")',
'.box:has-text("On Hand Details")',
'a[href*="on-hand-details-query"]',
'[class*="box"]:has-text("On Hand Details")',
)
for selector in tile_selectors:
locator = _visible_locator(page, selector)
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
print(f"[crane-nav] clicked On Hand Details tile selector={selector!r}")
return True
for root in (page, *list(getattr(page, "frames", []))):
try:
locator = root.get_by_role("link", name=_ON_HAND_DETAILS_LABEL, exact=False).first
if locator.is_visible(timeout=500) and _click_visible_locator(
locator, browser_timeout_ms=browser_timeout_ms
):
print("[crane-nav] clicked On Hand Details tile via link role")
return True
except Exception:
pass
for root in (page, *list(getattr(page, "frames", []))):
try:
locator = root.get_by_text(_ON_HAND_DETAILS_LABEL, exact=False).first
if not locator.is_visible(timeout=500):
continue
for candidate in (
locator.locator("xpath=ancestor-or-self::a[1]"),
locator.locator("xpath=ancestor-or-self::*[contains(@class,'box')][1]"),
locator,
):
try:
target = candidate.first
if target.is_visible(timeout=300) and _click_visible_locator(
target, browser_timeout_ms=browser_timeout_ms
):
print("[crane-nav] clicked On Hand Details tile via text locator")
return True
except Exception:
continue
except Exception:
pass
return False
def _click_dashboard_on_hand_details(
page: Any,
*,
env: Callable[[str, str], str],
browser_timeout_ms: int,
) -> bool:
"""
点击首页 Queries 区域的 On Hand Details 卡片(优先策略)。
核心逻辑:先文本语义定位 tile,再匹配 href*=on-hand-details-query 的 hash 路由链接。
"""
if _click_on_hand_details_tile(page, browser_timeout_ms=browser_timeout_ms):
return True
selectors = tuple(
item
for item in (env("SHIPPING_NOTICE_RPA_WORKER_CRANE_DASHBOARD_REPORT_SELECTOR"), *_CRANE_DASHBOARD_REPORT_TILE_SELECTORS)
if item
)
for selector in selectors:
locator = _visible_locator(page, selector)
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
print(f"[crane-nav] clicked dashboard tile selector={selector!r}")
return True
if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms):
print("[crane-nav] clicked dashboard tile via link role")
return True
return False
def _open_queries_nav_menu(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool:
"""展开顶部 Queries 下拉菜单。"""
selectors = tuple(
item for item in (env("SHIPPING_NOTICE_RPA_WORKER_CRANE_NAV_QUERIES_SELECTOR"), *_CRANE_NAV_QUERIES_MENU_SELECTORS) if item
)
for selector in selectors:
locator = _visible_locator(page, selector)
if locator is None:
continue
try:
locator.hover(timeout=min(browser_timeout_ms, 5_000))
except Exception:
pass
if _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
print(f"[crane-nav] opened Queries menu selector={selector!r}")
return True
for root in (page, *list(getattr(page, "frames", []))):
try:
locator = root.get_by_role("link", name="Queries", exact=False).first
if not locator.is_visible(timeout=500):
continue
try:
locator.hover(timeout=3_000)
except Exception:
pass
if _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
print("[crane-nav] opened Queries menu via link role")
return True
except Exception:
pass
return False
def _click_navbar_on_hand_details(
page: Any,
*,
env: Callable[[str, str], str],
browser_timeout_ms: int,
) -> bool:
"""
通过顶部 Queries 下拉进入 On Hand Details(回退策略)。
核心逻辑:先展开 Queries navbar-dropdown,再点 a.navbar-item On Hand Details。
"""
if not _open_queries_nav_menu(page, env=env, browser_timeout_ms=browser_timeout_ms):
print("[crane-nav] Queries navbar menu not opened", file=sys.stderr)
return False
time.sleep(0.35)
selectors = tuple(
item for item in (env("SHIPPING_NOTICE_RPA_WORKER_CRANE_NAV_REPORT_SELECTOR"), *_CRANE_NAV_ON_HAND_DETAILS_SELECTORS) if item
)
for selector in selectors:
locator = _visible_locator(page, selector)
if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms):
print(f"[crane-nav] clicked navbar item selector={selector!r}")
return True
if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms):
print("[crane-nav] clicked navbar On Hand Details via link role")
return True
return False
def _wait_for_report_navigation(
page: Any,
entry_url: str,
*,
browser_timeout_ms: int,
) -> bool:
"""点击导航后短等待目标路由或表单控件出现。"""
deadline = time.monotonic() + (min(browser_timeout_ms, 15_000) / 1000)
while time.monotonic() < deadline:
if is_crane_report_form_ready(page, entry_url):
return True
time.sleep(0.25)
return False
def _navigate_hash_route(page: Any, entry_url: str, *, browser_timeout_ms: int) -> None:
"""
通过 goto + hash 赋值进入 SPA 报表路由。
核心逻辑:登录后常落在 /#/ 首页,仅 goto 完整 entry_url 时 Vue 路由可能不切换。
"""
target = str(entry_url or "").strip()
if not target:
raise RuntimeError("Crane report navigation failed: entry_url is empty")
route = _report_route_from_entry_url(entry_url)
parsed = urlparse(target)
base_url = f"{parsed.scheme}://{parsed.netloc}/"
print(f"[crane-nav] fallback direct goto entry_url={target!r}")
page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms)
if is_crane_on_report_route(page, entry_url) and _has_report_form_controls(page):
return
print(f"[crane-nav] assigning hash route via SPA base={base_url!r} route={route!r}")
try:
page.goto(base_url, wait_until="domcontentloaded", timeout=browser_timeout_ms)
page.evaluate(
"""
(route) => {
const hash = route.startsWith('/') ? route : `/${route}`;
if (window.location.hash !== `#${hash}`) {
window.location.hash = hash;
}
}
""",
route,
)
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
try:
page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 10_000))
except Exception:
pass
except Exception as exc:
print(f"[crane-nav] hash route assignment failed: {exc}", file=sys.stderr)
def navigate_to_crane_report(
page: Any,
entry_url: str,
*,
env: Callable[[str, str], str],
browser_timeout_ms: int,
) -> str:
"""
导航至 On Hand Details Query 报表页。
核心逻辑:[STEP 1] 首页卡片点击 → [STEP 2] 顶部 Queries 菜单 → [STEP 3] 直接 goto entry_url。
Returns:
使用的导航模式:`already_ready` | `dashboard_tile` | `navbar_menu` | `direct_goto`。
Raises:
RuntimeError: 三种方式均未能进入报表表单。
"""
if is_crane_report_form_ready(page, entry_url):
print("[crane-nav] report form already ready, skip navigation")
return "already_ready"
_wait_for_crane_homepage_ready(page, browser_timeout_ms=browser_timeout_ms)
# [STEP 1] 首页 Queries 区 On Hand Details 卡片
if _click_dashboard_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms):
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
return "dashboard_tile"
print("[crane-nav] dashboard tile click did not reach report form, trying navbar", file=sys.stderr)
# [STEP 2] 顶部 Queries → On Hand Details
if _click_navbar_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms):
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
return "navbar_menu"
print("[crane-nav] navbar navigation did not reach report form, trying direct goto", file=sys.stderr)
# [STEP 3] 直接打开配置的 entry_url(hash 路由)
_navigate_hash_route(page, entry_url, browser_timeout_ms=browser_timeout_ms)
if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms):
return "direct_goto"
raise RuntimeError(
"Crane report navigation failed: dashboard tile, navbar menu, and direct goto did not reach report form"
)
File diff suppressed because it is too large. Load diff
-382
View File
@@ -1,382 +0,0 @@
"""
scripts/rpa/crane_session.py
用途:Crane AWS FootPrint Portal 登录、报表导航与 session 检测。
依赖:Playwright Page、crane_navigation;由 freight_rpa_worker._ensure_crane_session 委托调用。
逻辑:识别登录页并自动填写;登录后委托 navigate_to_crane_report 进入 On Hand Details Query。
"""
from __future__ import annotations
import sys
import time
from typing import Any, Callable
from urllib.parse import urlparse
# Crane FootPrint 登录页(Bulma 表单)实测控件;用户名无 name 属性,靠 placeholder/label 定位。
_CRANE_USERNAME_SELECTORS: tuple[str, ...] = (
'input[placeholder="Enter user name..."]',
'input[placeholder*="user name" i]',
'form input.input[type="text"]',
'input[name="userName"]',
'input[name="username"]',
)
_CRANE_PASSWORD_SELECTORS: tuple[str, ...] = (
'input[placeholder="Enter password..."]',
'input.input.is-small.p-2.mt-1[type="password"]',
'input[placeholder*="password" i]',
'form input.input[type="password"]',
'input[type="password"]',
)
_CRANE_LOGIN_SUBMIT_SELECTORS: tuple[str, ...] = (
'button.button.is-primary:has-text("Sign in")',
'form button.button.is-primary',
'button.button.is-primary',
)
_CRANE_LOGIN_SUBMIT_TEXTS: tuple[str, ...] = ("Sign in", "Login", "Log in", "登录")
def _load_crane_navigation_module() -> Any:
"""运行时加载 crane_navigation,避免与 crane_session 循环 import。"""
import importlib.util
from pathlib import Path
module_path = Path(__file__).resolve().parent / "crane_navigation.py"
spec = importlib.util.spec_from_file_location("crane_navigation_runtime", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _visible_locator(page: Any, selector: str) -> Any | None:
"""在 page 与各 frame 中查找首个可见 locator。"""
for root in (page, *list(getattr(page, "frames", []))):
try:
locator = root.locator(selector).first
if locator.is_visible(timeout=500):
return locator
except Exception:
continue
return None
def _dispatch_input_events(locator: Any) -> None:
"""触发 input/change 事件,驱动 Vue 表单解除 Sign in 按钮 disabled。"""
try:
locator.evaluate(
"""
(node) => {
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
}
"""
)
except Exception:
pass
def _fill_visible_locator(locator: Any, value: str, *, browser_timeout_ms: int) -> bool:
"""向已定位控件写入文本,并触发前端校验以启用 Sign in。"""
try:
locator.fill(value, timeout=browser_timeout_ms)
_dispatch_input_events(locator)
return True
except Exception:
pass
try:
locator.click(timeout=3_000)
locator.press("Control+A")
locator.press("Backspace")
locator.type(value, delay=30)
_dispatch_input_events(locator)
return True
except Exception:
return False
def _is_crane_button_enabled(locator: Any) -> bool:
"""Sign in 初始为 disabled,需等用户名/密码填写后解除。"""
try:
return bool(
locator.evaluate(
"""
(node) => {
if (!node) return false;
const disabled = Boolean(node.disabled);
const ariaDisabled = String(node.getAttribute('aria-disabled') || '').toLowerCase() === 'true';
const classDisabled = node.classList && node.classList.contains('is-disabled');
return !disabled && !ariaDisabled && !classDisabled;
}
"""
)
)
except Exception:
pass
try:
return locator.is_enabled(timeout=500)
except Exception:
return False
def _find_crane_sign_in_button(
page: Any,
*,
selector_env: str,
env: Callable[[str, str], str],
browser_timeout_ms: int,
) -> Any | None:
"""
查找已启用的 Sign in 按钮。
核心逻辑:页面按钮 class 为 button is-primary,填写凭据前带 disabled 属性。
"""
selectors = tuple(
item
for item in (env(selector_env), *_CRANE_LOGIN_SUBMIT_SELECTORS, 'button[type="submit"]')
if item
)
deadline = time.monotonic() + (browser_timeout_ms / 1000)
while time.monotonic() < deadline:
for selector in selectors:
locator = _visible_locator(page, selector)
if locator is not None and _is_crane_button_enabled(locator):
return locator
for root in (page, *list(getattr(page, "frames", []))):
for text in _CRANE_LOGIN_SUBMIT_TEXTS:
try:
locator = root.get_by_role("button", name=text, exact=False).first
if locator.is_visible(timeout=500) and _is_crane_button_enabled(locator):
return locator
except Exception:
pass
time.sleep(0.25)
# 最后再试一次可见按钮(部分环境 disabled 属性更新滞后,但 click 仍有效)
for selector in selectors:
locator = _visible_locator(page, selector)
if locator is not None:
return locator
return None
def _fill_crane_field(
page: Any,
*,
selector_env: str,
value: str,
env: Callable[[str, str], str],
browser_timeout_ms: int,
fallback_selectors: tuple[str, ...],
label: str | None = None,
placeholder: str | None = None,
) -> bool:
"""
填写 Crane 登录字段。
核心逻辑:优先环境变量 selector,再试页面实测 fallback,最后用 label/placeholder 语义定位。
"""
text = str(value or "").strip()
if not text:
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 not None and _fill_visible_locator(locator, text, browser_timeout_ms=browser_timeout_ms):
print(f"[crane-login] filled field via selector={selector!r}")
return True
for root in (page, *list(getattr(page, "frames", []))):
if label:
try:
locator = root.get_by_label(label, exact=False).first
if locator.is_visible(timeout=500) and _fill_visible_locator(
locator, text, browser_timeout_ms=browser_timeout_ms
):
print(f"[crane-login] filled field via label={label!r}")
return True
except Exception:
pass
if placeholder:
try:
locator = root.get_by_placeholder(placeholder, exact=False).first
if locator.is_visible(timeout=500) and _fill_visible_locator(
locator, text, browser_timeout_ms=browser_timeout_ms
):
print(f"[crane-login] filled field via placeholder={placeholder!r}")
return True
except Exception:
pass
return False
def _click_crane_login_submit(
page: Any,
*,
selector_env: str,
env: Callable[[str, str], str],
browser_timeout_ms: int,
) -> bool:
"""
点击 Crane Sign in 按钮。
核心逻辑:等待 button.button.is-primary 解除 disabled 后再点击。
"""
locator = _find_crane_sign_in_button(
page,
selector_env=selector_env,
env=env,
browser_timeout_ms=min(browser_timeout_ms, 15_000),
)
if locator is None:
return False
try:
locator.click(timeout=browser_timeout_ms)
return True
except Exception:
pass
try:
locator.click(timeout=browser_timeout_ms, force=True)
return True
except Exception:
return False
def is_crane_login_page(page: Any) -> bool:
"""当前页是否为 Crane FootPrint 登录表单。"""
for selector in (
'input[placeholder="Enter user name..."]',
'input[placeholder="Enter password..."]',
):
if _visible_locator(page, selector) is not None:
return True
for root in (page, *list(getattr(page, "frames", []))):
try:
if root.get_by_label("User Name", exact=False).first.is_visible(timeout=500):
return True
except Exception:
pass
return False
def _crane_entry_host(entry_url: str) -> str:
"""从 entry_url 提取 host。"""
parsed = urlparse(str(entry_url or "").strip())
return (parsed.netloc or "").lower()
def is_crane_session_active(page: Any, entry_url: str) -> bool:
"""
判定浏览器是否已在 Crane portal 维持有效登录态。
核心逻辑:仍在 craneww 域且不再显示登录表单,即视为 session 有效。
"""
host = _crane_entry_host(entry_url)
if not host:
return False
try:
current_url = str(page.url or "").lower()
except Exception:
return False
if host not in current_url:
return False
if is_crane_login_page(page):
return False
return True
def wait_for_crane_app_ready(
page: Any,
entry_url: str,
*,
env: Callable[[str, str], str],
browser_timeout_ms: int,
) -> None:
"""
登录后导航并等待 Crane 报表表单就绪。
核心逻辑:先 navigate_to_crane_report(首页卡片 → 顶部菜单 → goto),再轮询表单控件。
"""
navigation = _load_crane_navigation_module()
mode = navigation.navigate_to_crane_report(
page,
entry_url,
env=env,
browser_timeout_ms=browser_timeout_ms,
)
print(f"[crane-nav] navigation mode={mode!r}")
deadline = time.monotonic() + (browser_timeout_ms / 1000)
while time.monotonic() < deadline:
if navigation.is_crane_report_form_ready(page, entry_url):
print("[crane-login] report form ready")
return
time.sleep(0.5)
raise RuntimeError("Crane report form did not become ready after navigation; check selectors or permissions")
def maybe_auto_login_crane(
page: Any,
*,
env: Callable[[str, str], str],
browser_timeout_ms: int,
) -> None:
"""
Crane FootPrint 自动登录:User Name → Password → Sign in。
核心逻辑:页面无登录框则跳过;填写后等待离开登录页并进入报表路由。
"""
username = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME")
password = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD")
if not username or not password:
return
if not is_crane_login_page(page):
print("[crane-login] no login form detected, skip auto login")
return
user_filled = _fill_crane_field(
page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR",
value=username,
env=env,
browser_timeout_ms=browser_timeout_ms,
fallback_selectors=_CRANE_USERNAME_SELECTORS,
label="User Name",
placeholder="Enter user name...",
)
password_filled = _fill_crane_field(
page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR",
value=password,
env=env,
browser_timeout_ms=browser_timeout_ms,
fallback_selectors=_CRANE_PASSWORD_SELECTORS,
label="Password",
placeholder="Enter password...",
)
if not user_filled and not password_filled:
print("[crane-login] login form visible but fields not filled", file=sys.stderr)
return
if user_filled != password_filled:
raise RuntimeError("CRANE login form partially detected; please configure login selectors")
if not _click_crane_login_submit(
page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
env=env,
browser_timeout_ms=browser_timeout_ms,
):
raise RuntimeError("CRANE login fields detected but Sign in button was not found")
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
if is_crane_login_page(page):
raise RuntimeError("CRANE login did not complete; MFA/SSO/manual verification may be required")
# [STEP] 登录后 Crane 常先落到 /#/ 首页,等待 SPA 壳层渲染再进入报表导航
try:
page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 15_000))
except Exception:
pass
-76
View File
@@ -1,76 +0,0 @@
"""
scripts/rpa/download_artifact_fallback.py
用途:在浏览器实际已落盘但 Playwright 未返回 Download 对象时,按下载目录中的新文件构造兼容适配器。
依赖:pathlib、shutil、time。
逻辑:由 DSV 导出链路在 `expect_download` 超时后调用;不改变站点交互,只补文件系统兜底。
"""
from __future__ import annotations
import shutil
import time
from pathlib import Path
class FilesystemDownloadArtifact:
"""兼容 Playwright Download 的最小适配器,仅提供 `suggested_filename` 与 `save_as()`。"""
def __init__(self, path: Path) -> None:
self._path = Path(path)
self.suggested_filename = self._path.name
def save_as(self, dest: str) -> None:
target = Path(dest)
target.parent.mkdir(parents=True, exist_ok=True)
if self._path.resolve() == target.resolve():
return
shutil.move(str(self._path), str(target))
def wait_for_new_download_file(
*,
download_dir: str | Path,
baseline_names: set[str],
timeout_seconds: float = 12.0,
poll_seconds: float = 0.5,
) -> FilesystemDownloadArtifact | None:
"""
等待下载目录里出现本次新生成且大小稳定的文件。
核心逻辑:忽略 `.crdownload/.tmp` 等临时文件;优先接受 Excel/CSV 类产物,
同时兼容 Chromium 在 `downloads_path` 中落下的无扩展名原始文件;
连续两次观察到大小不变后,认为浏览器已完成落盘。
"""
root = Path(download_dir)
if not root.is_dir():
return None
deadline = time.monotonic() + max(1.0, timeout_seconds)
stable_sizes: dict[Path, int] = {}
allowed_suffixes = {".xlsx", ".xls", ".xlsm", ".xltx", ".xltm", ".csv", ""}
transient_suffixes = {".crdownload", ".tmp", ".part"}
while time.monotonic() < deadline:
candidates = []
for path in root.iterdir():
if not path.is_file():
continue
if path.name in baseline_names:
continue
suffix = path.suffix.lower()
if suffix in transient_suffixes or suffix not in allowed_suffixes:
continue
candidates.append(path)
candidates.sort(key=lambda item: item.stat().st_mtime, reverse=True)
for path in candidates:
try:
size = path.stat().st_size
except OSError:
continue
last_size = stable_sizes.get(path)
if last_size is not None and last_size == size and size > 0:
return FilesystemDownloadArtifact(path)
stable_sizes[path] = size
time.sleep(max(0.1, poll_seconds))
return None
File diff suppressed because it is too large. Load diff
-433
View File
@@ -1,433 +0,0 @@
"""
scripts/rpa/dsv_auth_login_flow.py
用途:DSV 360 PingID 自动登录主编排(maybe_auto_login_dsv)。
依赖:rpa_common、dsv_debug、dsv_auth(表单/探测辅助)、dsv_session(登录后首页 ready)。
逻辑:由 dsv_auth 在模块末尾 re-export;dsv_report_export ensure 时触发。
"""
from __future__ import annotations
import sys
import time
from typing import Any, Callable
from rpa_common import browser_timeout_ms as _browser_timeout_ms
from rpa_common import env as _env
from rpa_common import fill_first_visible_text_input as _fill_first_visible_text_input
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
from dsv_debug import (
collect_dsv_reports_probe as _collect_dsv_reports_probe,
debug_dsv_stage as _debug_dsv_stage,
report_debug_event as _report_debug_event,
report_dsv_chain_stage as _report_dsv_chain_stage,
)
import dsv_auth
# 绑定私有符号,避免 dsv_auth 末尾 re-export 时的循环导入竞态。
_DSV_USERNAME_SELECTORS = dsv_auth._DSV_USERNAME_SELECTORS
_click_dsv_continue = dsv_auth._click_dsv_continue
_click_dsv_password_method = dsv_auth._click_dsv_password_method
_debug_dsv_login_method_page = dsv_auth._debug_dsv_login_method_page
_dismiss_dsv_password_upgrade_prompt = dsv_auth._dismiss_dsv_password_upgrade_prompt
_dismiss_dsv_password_upgrade_prompt_after_login_redirect = dsv_auth._dismiss_dsv_password_upgrade_prompt_after_login_redirect
_dsv_login_debug_value = dsv_auth._dsv_login_debug_value
_dsv_login_ready_timeout_ms = dsv_auth._dsv_login_ready_timeout_ms
_fill_dsv_password_page_fields = dsv_auth._fill_dsv_password_page_fields
_fill_dsv_username = dsv_auth._fill_dsv_username
_find_dsv_password_locator = dsv_auth._find_dsv_password_locator
_has_dsv_human_check_prompt = dsv_auth._has_dsv_human_check_prompt
_has_dsv_password_upgrade_prompt = dsv_auth._has_dsv_password_upgrade_prompt
_is_dsv_blank_auth_transition = dsv_auth._is_dsv_blank_auth_transition
_is_dsv_oauth_handshake_url = dsv_auth._is_dsv_oauth_handshake_url
_is_dsv_password_upgrade_redirect = dsv_auth._is_dsv_password_upgrade_redirect
_is_dsv_username_page = dsv_auth._is_dsv_username_page
_submit_dsv_password_form = dsv_auth._submit_dsv_password_form
_wait_for_dsv_auth_page_ready = dsv_auth._wait_for_dsv_auth_page_ready
_wait_for_dsv_human_check_if_present = dsv_auth._wait_for_dsv_human_check_if_present
_wait_for_dsv_login_method_page = dsv_auth._wait_for_dsv_login_method_page
def _wait_for_dsv_home_ready_after_login(
page: Any,
*,
timeout_ms: int | None = None,
on_portal_shell_seen: Callable[[], None] | None = None,
) -> None:
"""登录完成后等待首页 ready;惰性导入 dsv_session 避免循环依赖。"""
import dsv_session
dsv_session.wait_for_dsv_home_ready(
page,
timeout_ms=timeout_ms,
on_portal_shell_seen=on_portal_shell_seen,
)
def _wait_for_dsv_app_after_login(
page: Any,
timeout_ms: int | None = None,
on_portal_shell_seen: Callable[[], None] | None = None,
) -> bool:
"""登录轮询 portal 壳层;委托 dsv_session。"""
import dsv_session
return dsv_session.wait_for_dsv_app_after_login(
page,
timeout_ms=timeout_ms,
on_portal_shell_seen=on_portal_shell_seen,
)
def _has_existing_dsv_portal_session(page: Any) -> bool:
"""
轻量判断当前页面是否已是有效 DSV Portal 首页。
核心逻辑:持久化 Browser Profile 恢复时,Portal 首页可能已可见,但旧登录流程仍先
等待用户名控件和认证页渲染。仅当已离开 auth 域且首页业务标记出现时短路;Reports
菜单是否可点击仍由后续首页就绪校验负责,避免把认证中转页误判为已登录。
"""
try:
current_url = str(page.url or "").lower()
except Exception:
return False
if "s360.dbschenker.com" not in current_url or "auth.dbschenker.com" in current_url:
return False
try:
body = str(page.locator("body").inner_text(timeout=1_000) or "").lower()
except Exception:
return False
return any(marker in body for marker in ("home favorites", "recent reports", "favorites"))
def _maybe_auto_login_dsv(page: Any) -> None:
"""
DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。
"""
username = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME")
password = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD")
auto_login_started_at = time.monotonic()
username_step_started_at = auto_login_started_at
continue_to_method_started_at: float | None = None
method_to_password_started_at: float | None = None
submit_to_home_started_at: float | None = None
portal_shell_seen_at: float | None = None
def _report_auto_login_substage(name: str, started_at: float | None) -> None:
"""记录 auto_login 内部子阶段耗时,帮助定位认证链路具体卡点。"""
if started_at is None:
return
_report_dsv_chain_stage(
f"auto_login.{name}",
"end",
started_at=started_at,
extra={"sinceAutoLoginMs": int((time.monotonic() - auto_login_started_at) * 1000)},
)
def _report_portal_shell_seen() -> None:
"""记录 portal 壳层首次可见时间,区分 auth 收尾和首页 ready 的等待。"""
nonlocal portal_shell_seen_at
if portal_shell_seen_at is not None:
return
portal_shell_seen_at = time.monotonic()
_report_auto_login_substage("portal_shell_seen", submit_to_home_started_at)
if not username or not password:
return
# [STEP 1] Profile 会话恢复优先于任何登录页等待。否则已在 Portal 首页时会白等
# username selector 的长超时,随后才迟到地发现 existing session。
if _has_existing_dsv_portal_session(page):
print("[dsv-login] existing portal session detected before auth probe")
_report_debug_event(
"E",
"freight_rpa_worker.py:_maybe_auto_login_dsv:existing_portal_session",
"[DEBUG] dsv portal session detected before auth flow",
_collect_dsv_reports_probe(page),
)
return
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=15_000) is not None:
print("[dsv-login] existing session detected")
# #region debug-point E:existing-session
_report_debug_event(
"E",
"freight_rpa_worker.py:_maybe_auto_login_dsv:existing_session",
"[DEBUG] dsv existing session detected before login flow",
_collect_dsv_reports_probe(page),
)
# #endregion
return
_wait_for_dsv_auth_page_ready(page)
login_ready_ms = _dsv_login_ready_timeout_ms()
print("[dsv-login] waiting username field")
username_locator = _wait_for_visible_selector(
page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME_SELECTOR",
_DSV_USERNAME_SELECTORS,
timeout_ms=login_ready_ms,
)
if username_locator is not None:
username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator)
user_filled = username_locator is not None
else:
username_locator = None
user_filled = _fill_first_visible_text_input(page, username)
if not user_filled:
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=10_000) is not None:
print("[dsv-login] existing session detected")
# #region debug-point E:existing-session-late
_report_debug_event(
"E",
"freight_rpa_worker.py:_maybe_auto_login_dsv:existing_session_late",
"[DEBUG] dsv existing session detected after username probe",
_collect_dsv_reports_probe(page),
)
# #endregion
return
if _is_dsv_oauth_handshake_url(page.url):
print("[dsv-login] still on blank oauth handshake before giving up, reload once")
try:
page.reload(wait_until="domcontentloaded", timeout=45_000)
except Exception as exc:
print(f"[dsv-login] final oauth reload failed: {exc}", file=sys.stderr)
if _wait_for_dsv_auth_page_ready(page, timeout_ms=30_000):
username_locator = _wait_for_visible_selector(
page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME_SELECTOR",
_DSV_USERNAME_SELECTORS,
timeout_ms=15_000,
)
if username_locator is not None:
username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator)
if username_locator is not None:
user_filled = True
if not user_filled:
try:
text = page.locator("body").inner_text(timeout=3_000)
except Exception:
text = ""
raise RuntimeError(
"DSV login state is unknown "
f"url={page.url} body={text[:300]!r} "
"(oauth handshake page stayed blank; check network/VPN or complete login manually in browser)"
)
print("[dsv-login] username filled")
_report_auto_login_substage("username_step", username_step_started_at)
continue_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_CONTINUE_BUTTON_SELECTOR")
if continue_selector:
page.locator(continue_selector).first.click(timeout=_browser_timeout_ms(), force=True)
clicked_continue = True
else:
clicked_continue = _click_dsv_continue(page, username_locator)
if not clicked_continue:
identifier_value, button_state = _dsv_login_debug_value(page)
print(f"[dsv-login] continue missing identifier_value={identifier_value!r} button={button_state!r}")
raise RuntimeError("DSV login email step detected but continue button was not found")
print("[dsv-login] continue clicked")
continue_to_method_started_at = time.monotonic()
# #region debug-point E:continue-clicked
_report_debug_event(
"E",
"freight_rpa_worker.py:_maybe_auto_login_dsv:continue_clicked",
"[DEBUG] dsv username step submitted",
_collect_dsv_reports_probe(page),
)
# #endregion
print("[dsv-login] waiting password field")
password_locator = None
login_deadline = time.monotonic() + (
max(60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_STAGE_TIMEOUT_MS", "120000") or "120000")) / 1000
)
password_method_clicked_at = 0.0
username_retry_allowed_at = time.monotonic() + 6
while time.monotonic() < login_deadline:
# [STEP 1] DSV 在密码阶段前(authorization.ping)也会弹出“使用密码升级登录!”
# 引导弹窗(也许以后/立即启用),会遮挡密码表单和登录按钮;先点“也许以后”关闭再探测。
if _is_dsv_password_upgrade_redirect(page) and _has_dsv_password_upgrade_prompt(page):
_dismiss_dsv_password_upgrade_prompt(page)
password_locator = _find_dsv_password_locator(page, timeout_ms=250)
if password_locator is not None:
break
if _fill_dsv_password_page_fields(page, username, password):
print("[dsv-login] password filled")
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
_report_auto_login_substage("method_to_password", method_to_password_started_at)
if not _submit_dsv_password_form(page):
raise RuntimeError("DSV login password step detected but login button was not found")
print("[dsv-login] login clicked")
submit_to_home_started_at = time.monotonic()
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
_debug_dsv_stage(page, "after-login-click-inline-password", target_text="Reports")
_dismiss_dsv_password_upgrade_prompt_after_login_redirect(page)
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
raise RuntimeError("DSV login did not complete; password may be invalid or verification is required")
_wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen)
_report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at)
_report_auto_login_substage("password_submit_to_home", submit_to_home_started_at)
print("[dsv-login] login completed")
return
if _has_dsv_human_check_prompt(page):
_wait_for_dsv_human_check_if_present(page, timeout_ms=300_000)
if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen):
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
_report_auto_login_substage("method_to_password", method_to_password_started_at)
print("[dsv-login] login completed")
# #region debug-point E:login-completed-direct
_report_debug_event(
"E",
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_completed_direct",
"[DEBUG] dsv login completed directly after human check/app wait",
_collect_dsv_reports_probe(page),
)
# #endregion
return
method_ready = _wait_for_dsv_login_method_page(page, timeout_ms=2_000)
if method_ready:
# #region debug-point E:password-method-page
_report_debug_event(
"E",
"freight_rpa_worker.py:_maybe_auto_login_dsv:password_method_page",
"[DEBUG] dsv password method page detected",
_collect_dsv_reports_probe(page),
)
# #endregion
if password_method_clicked_at and time.monotonic() - password_method_clicked_at < 2:
time.sleep(1)
continue
password_method_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_METHOD_SELECTOR")
if password_method_selector:
page.locator(password_method_selector).first.click(timeout=_browser_timeout_ms(), force=True)
clicked_password_method = True
else:
clicked_password_method = _click_dsv_password_method(page)
if not clicked_password_method:
print(f"[dsv-login] password method debug {_debug_dsv_login_method_page(page)}")
time.sleep(1)
continue
password_method_clicked_at = time.monotonic()
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
continue_to_method_started_at = None
method_to_password_started_at = password_method_clicked_at
username_retry_allowed_at = max(username_retry_allowed_at, password_method_clicked_at + 4)
print("[dsv-login] password method clicked")
# #region debug-point E:password-method-clicked
_report_debug_event(
"E",
"freight_rpa_worker.py:_maybe_auto_login_dsv:password_method_clicked",
"[DEBUG] dsv password method clicked",
_collect_dsv_reports_probe(page),
)
# #endregion
continue
# [STEP 2] Continue 刚提交或刚点过“密码”时,先给 PingID 页面一点切换时间,
# 避免方法页尚未稳定时又误判回邮箱页,造成来回重填账号。
if time.monotonic() >= username_retry_allowed_at and _is_dsv_username_page(page):
username_locator = _fill_dsv_username(page, username)
if username_locator is None and not _fill_first_visible_text_input(page, username):
print(f"[dsv-login] username retry failed {_debug_dsv_login_method_page(page)}")
time.sleep(1)
continue
if _click_dsv_continue(page, username_locator):
print("[dsv-login] username page retried")
username_retry_allowed_at = time.monotonic() + 6
time.sleep(1)
continue
password_locator = _find_dsv_password_locator(page, timeout_ms=250)
if password_locator is not None:
break
if _is_dsv_blank_auth_transition(page):
_wait_for_dsv_auth_page_ready(page, timeout_ms=5_000)
password_locator = _find_dsv_password_locator(page, timeout_ms=500)
if password_locator is not None:
break
time.sleep(1)
if password_locator is None:
if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen):
print("[dsv-login] login completed")
# #region debug-point E:login-completed-late
_report_debug_event(
"E",
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_completed_late",
"[DEBUG] dsv login completed after password wait fallback",
_collect_dsv_reports_probe(page),
)
# #endregion
return
try:
text = page.locator("body").inner_text(timeout=3_000)
except Exception:
text = ""
if not text.strip():
print(f"[dsv-login] password page still loading url={page.url}")
if _is_dsv_blank_auth_transition(page):
_wait_for_dsv_auth_page_ready(page, timeout_ms=_dsv_login_ready_timeout_ms())
password_locator = _wait_for_visible_selector(
page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_SELECTOR",
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
timeout_ms=_dsv_login_ready_timeout_ms(),
)
if password_locator is None:
if not _fill_dsv_password_page_fields(page, username, password):
raise RuntimeError("DSV login password field was not found")
print("[dsv-login] password filled")
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
_report_auto_login_substage("method_to_password", method_to_password_started_at)
if not _submit_dsv_password_form(page):
raise RuntimeError("DSV login password step detected but login button was not found")
print("[dsv-login] login clicked")
submit_to_home_started_at = time.monotonic()
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
_debug_dsv_stage(page, "after-login-click-late-password", target_text="Reports")
_dismiss_dsv_password_upgrade_prompt_after_login_redirect(page)
_wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen)
_report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at)
_report_auto_login_substage("password_submit_to_home", submit_to_home_started_at)
print("[dsv-login] login completed")
return
print(f"[dsv-login] password field missing url={page.url} body={text[:300]!r} method_debug={_debug_dsv_login_method_page(page)}")
raise RuntimeError("DSV login password field was not found")
password_locator.fill(password, timeout=_browser_timeout_ms())
print("[dsv-login] password filled")
_report_auto_login_substage("continue_to_method", continue_to_method_started_at)
_report_auto_login_substage("method_to_password", method_to_password_started_at)
if not _submit_dsv_password_form(page):
raise RuntimeError("DSV login password step detected but login button was not found")
print("[dsv-login] login clicked")
submit_to_home_started_at = time.monotonic()
# #region debug-point N:login-clicked
_report_debug_event(
"N",
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_clicked",
"[DEBUG] dsv login button submitted",
{"url": page.url},
)
# #endregion
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
# #region debug-point N:after-domcontentloaded
_report_debug_event(
"N",
"freight_rpa_worker.py:_maybe_auto_login_dsv:after_domcontentloaded",
"[DEBUG] dsv login flow reached domcontentloaded after submit",
{"url": page.url},
)
# #endregion
_debug_dsv_stage(page, "after-login-click-password-locator", target_text="Reports")
_dismiss_dsv_password_upgrade_prompt_after_login_redirect(page)
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
raise RuntimeError("DSV login did not complete; password may be invalid or verification is required")
_wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen)
_report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at)
_report_auto_login_substage("password_submit_to_home", submit_to_home_started_at)
print("[dsv-login] login completed")
# 公开 API
maybe_auto_login_dsv = _maybe_auto_login_dsv
has_existing_dsv_portal_session = _has_existing_dsv_portal_session
-349
View File
@@ -1,349 +0,0 @@
"""
scripts/rpa/dsv_debug.py
用途:DSV 360 RPA 调试探针与链路阶段日志。
依赖:rpa_common。
逻辑:供 dsv_session、dsv_navigation、dsv_report_export 调用。
"""
from __future__ import annotations
import json
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any
from rpa_common import browser_timeout_ms as _browser_timeout_ms
from rpa_common import env as _env
def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
_payload = {
"sessionId": "dsv-export-stall",
"runId": run_id,
"hypothesisId": hypothesis_id,
"location": location,
"msg": msg,
"data": data or {},
"ts": int(time.time() * 1000),
}
_url = "http://127.0.0.1:7778/event"
_env_file = Path(".dbg/dsv-export-stall.env")
try:
if _env_file.is_file():
_content = _env_file.read_text(encoding="utf-8")
_url = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SERVER_URL=")), _url)
_payload["sessionId"] = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SESSION_ID=")), _payload["sessionId"])
urllib.request.urlopen(
urllib.request.Request(
_url,
data=json.dumps(_payload, ensure_ascii=False).encode("utf-8"),
headers={"Content-Type": "application/json"},
),
timeout=1.5,
).read()
except Exception:
pass
def _debug_dsv_page_snapshot(page: Any, *, target_text: str = "") -> str:
"""
汇总 DSV 当前页面与各 frame 的可见文本快照,便于定位菜单/报表文案漂移。
核心逻辑:采集 page.url、顶层 body 文本、关键菜单容器是否存在,以及各 frame 中
可见的链接/按钮/菜单项候选文本;当目标文案找不到时,日志里直接输出“页面上实际看到了什么”。
Args:
page: Playwright Page 对象。
target_text: 当前正在寻找的菜单/报表文案,可为空。
Returns:
str: 截断后的页面快照字符串,适合直接输出到 worker 日志。
"""
focus = str(target_text or "").strip()
try:
page_url = page.url
except Exception:
page_url = ""
snippets = [f"url={page_url!r}"]
try:
body = page.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500]
except Exception:
body = ""
if body:
snippets.append(f"page_body={body!r}")
try:
from dsv_session import has_dsv_report_nav_attached as _has_dsv_report_nav_attached
report_nav_exists = _has_dsv_report_nav_attached(page)
except Exception:
report_nav_exists = False
snippets.append(f"report_nav_exists={report_nav_exists}")
candidate_script = """
(focusText) => {
const normalize = (value) => ((value || '') + '').replace(/\\s+/g, ' ').trim();
const isVisible = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
};
const selectors = [
'#report-mega-legacy',
'#report-mega-legacy *',
'.mega-dropdown-menu *',
'.dropdown-menu *',
'a',
'button',
'[role="button"]',
'li',
'.nav-link',
'.dropdown-item',
];
const focus = normalize(focusText).toLowerCase();
const values = Array.from(document.querySelectorAll(selectors.join(',')))
.filter((node) => isVisible(node))
.map((node) => normalize(node.innerText || node.textContent || node.value))
.filter(Boolean);
const deduped = Array.from(new Set(values));
const matched = focus
? deduped.filter((text) => text.toLowerCase().includes(focus)).slice(0, 20)
: [];
return {
matched,
candidates: deduped.slice(0, 40),
};
}
"""
for idx, frame in enumerate(page.frames):
try:
frame_url = frame.url
except Exception:
frame_url = ""
try:
frame_name = frame.name
except Exception:
frame_name = ""
try:
frame_body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:400]
except Exception:
frame_body = ""
try:
frame_data = frame.evaluate(candidate_script, focus, timeout=1_500)
except Exception:
frame_data = {"matched": [], "candidates": []}
matched = list((frame_data or {}).get("matched") or [])
candidates = list((frame_data or {}).get("candidates") or [])
if frame_body or candidates or matched:
snippets.append(
f"frame[{idx}] name={frame_name!r} url={frame_url!r} body={frame_body!r} matched={matched!r} candidates={candidates!r}"
)
return " | ".join(snippets)[:5000]
def _debug_dsv_stage(page: Any, stage: str, *, target_text: str = "") -> None:
"""
输出 DSV 关键阶段的运行时快照,用于排查“短暂到页后又跳走”或 DOM 未就绪的问题。
核心逻辑:在登录后等待首页、展开 Reports、选择 Program 等关键节点打印统一格式日志,
让失败复现时可以按时间顺序观察 URL、标题、body、frame 候选文本是否发生变化。
Args:
page: Playwright Page 对象。
stage: 当前阶段名,例如 `after-login-click`、`wait-app-3s`。
target_text: 当前关注的菜单或文案目标。
"""
try:
title = page.title()
except Exception:
title = ""
snapshot = _debug_dsv_page_snapshot(page, target_text=target_text)
print(f"[dsv-stage] stage={stage} title={title!r} {snapshot}")
# #region debug-point A:reports-debug-server
def _debug_server_config() -> tuple[str, str]:
"""读取 reports-menu-stuck 调试会话配置,未命中时回退默认本地地址。"""
env_path = Path(__file__).resolve().parents[2] / ".dbg" / "reports-menu-stuck.env"
url = "http://127.0.0.1:7778/event"
session_id = "reports-menu-stuck"
try:
content = env_path.read_text(encoding="utf-8")
for line in content.splitlines():
if line.startswith("DEBUG_SERVER_URL="):
url = line.split("=", 1)[1].strip() or url
elif line.startswith("DEBUG_SESSION_ID="):
session_id = line.split("=", 1)[1].strip() or session_id
except Exception:
pass
return url, session_id
def _report_debug_event(hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
"""向 Debug Server 上报结构化运行时证据;失败时静默,不影响业务流程。"""
try:
url, session_id = _debug_server_config()
payload = {
"sessionId": session_id,
"runId": "pre-fix",
"hypothesisId": hypothesis_id,
"location": location,
"msg": msg,
"data": data or {},
"ts": int(time.time() * 1000),
}
req = urllib.request.Request(
url,
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=2):
pass
except Exception:
pass
def _report_dsv_chain_stage(stage: str, status: str, *, started_at: float | None = None, extra: dict[str, Any] | None = None) -> None:
"""
统一记录 DSV 主链路各阶段耗时。
核心逻辑:只在主编排链路输出 `start/end/error` 三类探针,不参与任何业务判断,
让一次真实运行即可回放从登录到导出的完整阶段耗时分布。
"""
payload = dict(extra or {})
if started_at is not None:
payload["elapsedMs"] = int((time.monotonic() - started_at) * 1000)
print(
"[dsv-chain] "
f"stage={stage} "
f"status={status} "
+ (
" ".join(f"{key}={payload[key]!r}" for key in sorted(payload))
if payload
else ""
)
)
_report_debug_event(
"T",
f"freight_rpa_worker.py:_download_dsv360_inventory:{stage}:{status}",
"[DEBUG] dsv chain stage probe",
{"stage": stage, "status": status, **payload},
)
def _collect_dsv_reports_probe(page: Any) -> dict[str, Any]:
"""采集 Reports 导航的最小 DOM 证据,帮助判断是否点早、点错或被遮挡。"""
try:
probe = page.evaluate(
"""
() => {
const nav = document.querySelector('#report-mega-legacy');
const link = nav?.querySelector('a.dropdown-toggle, a.nav-link, a');
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
const rectOf = (node) => {
if (!node || !node.getBoundingClientRect) return null;
const r = node.getBoundingClientRect();
return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) };
};
const centerNode = (() => {
const rect = rectOf(link);
if (!rect || rect.width <= 0 || rect.height <= 0) return null;
return document.elementFromPoint(rect.x + Math.max(Math.floor(rect.width / 2), 1), rect.y + Math.max(Math.floor(rect.height / 2), 1));
})();
return {
navExists: !!nav,
navClass: nav?.className || '',
navAriaExpanded: nav?.getAttribute('aria-expanded') || '',
linkText: textOf(link),
linkClass: link?.className || '',
linkAriaExpanded: link?.getAttribute('aria-expanded') || '',
linkRect: rectOf(link),
centerTag: centerNode?.tagName || '',
centerText: textOf(centerNode).slice(0, 120),
activeTag: document.activeElement?.tagName || '',
activeText: textOf(document.activeElement).slice(0, 120),
};
}
""",
)
except Exception as exc:
probe = {"probe_error": str(exc)[:200]}
try:
probe["url"] = page.url
except Exception:
probe["url"] = ""
try:
from dsv_navigation import is_dsv_reports_menu_open as _is_dsv_reports_menu_open
probe["menuOpen"] = _is_dsv_reports_menu_open(page)
except Exception as exc:
probe["menuOpen"] = False
probe["menuOpenError"] = str(exc)[:120]
return probe
# #endregion
def _collect_dsv_menu_probe(page: Any, target_text: str = "") -> dict[str, Any]:
"""采集 Reports 级联菜单当前可见层级,帮助判断下拉是否真的推进到了下一层。"""
target_text = str(target_text or "").strip()
target_literal = json.dumps(target_text)
try:
probe = page.evaluate(
f"""
() => {{
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
const nodes = Array.from(document.querySelectorAll(
'#report-mega-legacy a, #report-mega-legacy button, #report-mega-legacy [role="menuitem"], #report-mega-legacy [data-program], #report-mega-legacy [data-report], #report-mega-legacy .dropdown-item, #report-mega-legacy .menu-item, #report-mega-legacy div, #report-mega-legacy span, .mega-dropdown-menu a, .mega-dropdown-menu button, .mega-dropdown-menu [role="menuitem"], .mega-dropdown-menu [data-program], .mega-dropdown-menu [data-report], .mega-dropdown-menu .dropdown-item, .mega-dropdown-menu .menu-item, .mega-dropdown-menu div, .mega-dropdown-menu span, .dropdown-menu a, .dropdown-menu button, .dropdown-menu [role="menuitem"], .dropdown-menu [data-program], .dropdown-menu [data-report], .dropdown-menu .dropdown-item, .dropdown-menu .menu-item, .dropdown-menu div, .dropdown-menu span'
));
const visible = nodes
.filter((node) => {{
const rect = node.getBoundingClientRect ? node.getBoundingClientRect() : null;
const style = window.getComputedStyle ? window.getComputedStyle(node) : null;
return rect && rect.width > 0 && rect.height > 0 && style && style.visibility !== 'hidden' && style.display !== 'none';
}})
.map((node) => {{
const rect = node.getBoundingClientRect();
return {{
text: textOf(node),
className: node.className || '',
ariaExpanded: node.getAttribute('aria-expanded') || '',
tagName: node.tagName || '',
dataProgram: node.getAttribute('data-program') || '',
dataReport: node.getAttribute('data-report') || '',
x: Math.round(rect.x),
y: Math.round(rect.y),
}};
}})
.filter((item) => item.text)
.slice(0, 40);
const target = {target_literal};
const matched = target
? visible.filter((item) => item.text.toLowerCase().includes(target.toLowerCase())).slice(0, 10)
: [];
return {{
visibleItems: visible,
matchedItems: matched,
bodySnippet: textOf(document.body).slice(0, 600),
activeText: textOf(document.activeElement).slice(0, 120),
}};
}}
""",
)
except Exception as exc:
probe = {"probe_error": str(exc)[:200]}
try:
probe["url"] = page.url
except Exception:
probe["url"] = ""
return probe
# 公开 API
emit_debug_event = _emit_debug_event
debug_dsv_page_snapshot = _debug_dsv_page_snapshot
debug_dsv_stage = _debug_dsv_stage
debug_server_config = _debug_server_config
report_debug_event = _report_debug_event
report_dsv_chain_stage = _report_dsv_chain_stage
collect_dsv_reports_probe = _collect_dsv_reports_probe
collect_dsv_menu_probe = _collect_dsv_menu_probe
-29
View File
@@ -1,29 +0,0 @@
"""
scripts/rpa/dsv_driver.py
用途:DSV 360 库存 RPA 对外编排入口(session → 导航 → 导出)。
依赖:dsv_report_export。
逻辑:freight_rpa_worker 在 connector_type=dsv360 时仅调用本模块公开函数。
"""
from __future__ import annotations
from typing import Any
from dsv_report_export import (
ensure_dsv_session,
export_dsv_inventory_source,
prepare_dsv_batch_export_step,
)
def download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
"""
单票 trigger 的 DSV 360 导出。
核心逻辑:ensure session → 导航至参数页 → 填参并导出 Excel。
"""
entry_url = str(source.get("entry_url") or "").strip()
if not entry_url:
raise RuntimeError("DSV360 inventory source missing entry_url")
ensure_dsv_session(page, entry_url)
return export_dsv_inventory_source(page, trigger, source)
@@ -1,47 +0,0 @@
"""
scripts/rpa/dsv_export_timeout_diagnostics.py
用途:汇总 DSV Excel 导出等待超时现场,输出适合直接写入 worker.log 的诊断字符串。
依赖:json、标准库。
逻辑:由 dsv_report_export 在 `page.expect_download(...)` 超时时调用;不参与任何业务判断。
"""
from __future__ import annotations
import json
from typing import Any
def build_download_timeout_log(
*,
report_name: str,
error_type: str,
error_message: str,
selected_frame_index: int | None,
selected_frame_name: str,
selected_frame_url: str,
report_state: dict[str, Any] | None,
export_controls: dict[str, Any] | None,
page_snapshot: str,
) -> str:
"""
生成 DSV 导出等待超时诊断日志。
核心逻辑:把当前报表、选中结果 frame、导出控件探针和页面快照压成一条 JSON,
便于在不接 Debug Server 的情况下,直接从 worker.log 反推出导出按钮是否真实可见。
Returns:
str: 以 `[dsv-download-timeout]` 开头的单行日志。
"""
payload = {
"report_name": str(report_name or ""),
"error_type": str(error_type or ""),
"error_message": str(error_message or "")[:500],
"selected_frame_index": selected_frame_index,
"selected_frame_name": str(selected_frame_name or "")[:120],
"selected_frame_url": str(selected_frame_url or "")[:300],
"report_state": report_state or {},
"export_controls": export_controls or {},
"page_snapshot": str(page_snapshot or "")[:2500],
}
return "[dsv-download-timeout] " + json.dumps(payload, ensure_ascii=False, default=str)
-100
View File
@@ -1,100 +0,0 @@
"""
scripts/rpa/dsv_login_smoke.py
用途:本地手动验证 DSV 360 自动登录(含密码方式第二步、首页 ready)。
依赖:Playwright、SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD。
逻辑:打开可见浏览器 → _ensure_dsv_session → 保持窗口供人工观察,按 Enter 关闭。
用法(仓库根目录):
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_login_smoke.py
"""
from __future__ import annotations
import importlib.util
import os
import shutil
import sys
import tempfile
import traceback
from pathlib import Path
def _load_worker():
repo_root = Path(__file__).resolve().parents[2]
module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main() -> int:
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
os.environ.setdefault(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile",
)
# Playwright 自带 Chromium 未安装时,回退到本机 Edge(Windows 开发机常见情况)。
if not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") and not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
worker = _load_worker()
username = worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME")
password = worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD")
if not username or not password:
print("[smoke] 缺少 SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD,请先配置环境变量。")
return 1
drop_dir = Path(tempfile.mkdtemp(prefix="dsv_smoke_drop_"))
playwright = context = runtime_profile_dir = None
entry_url = "https://s360.dbschenker.com/"
print(f"[smoke] headless={worker._env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false')}")
print(f"[smoke] user={username[:3]}*** entry={entry_url}")
print("[smoke] 正在打开浏览器并执行 DSV 自动登录…")
try:
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
worker._ensure_dsv_session(page, entry_url)
print(f"[smoke] SUCCESS — DSV session ready, url={page.url}")
print("[smoke] 请在浏览器中确认 Reports 导航可见。按 Enter 关闭浏览器…")
try:
input()
except EOFError:
import time
print("[smoke] 非交互终端,保持浏览器 300 秒后自动关闭。")
time.sleep(300)
return 0
except Exception as exc:
print(f"[smoke] FAILED — {exc}")
traceback.print_exc()
print("[smoke] 浏览器将保持打开 120 秒以便排查,按 Enter 提前关闭…")
try:
input()
except EOFError:
import time
time.sleep(120)
return 2
finally:
if context is not None:
try:
context.close()
except Exception:
pass
if playwright is not None:
try:
playwright.stop()
except Exception:
pass
if runtime_profile_dir is not None:
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
shutil.rmtree(drop_dir, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())
-960
View File
@@ -1,960 +0,0 @@
"""
scripts/rpa/dsv_navigation.py
用途:DSV 360 Reports 菜单导航至 SSRS 参数页。
依赖:rpa_common、dsv_debug、dsv_session。
逻辑:由 dsv_report_export 在填参导出前调用。
"""
from __future__ import annotations
import json
import sys
import time
from typing import Any
from rpa_common import browser_timeout_ms as _browser_timeout_ms
from rpa_common import env as _env
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
import dsv_debug
from dsv_debug import (
collect_dsv_menu_probe as _collect_dsv_menu_probe,
collect_dsv_reports_probe as _collect_dsv_reports_probe,
debug_dsv_page_snapshot as _debug_dsv_page_snapshot,
debug_dsv_stage as _debug_dsv_stage,
report_debug_event as _report_debug_event,
)
import dsv_session
from dsv_session import (
DSV_REPORTS_NAV_SELECTORS as _DSV_REPORTS_NAV_SELECTORS,
has_dsv_report_nav_attached as _has_dsv_report_nav_attached,
has_dsv_report_nav_usable as _has_dsv_report_nav_usable,
is_dsv_on_portal_home as _is_dsv_on_portal_home,
has_dsv_portal_shell as _has_dsv_portal_shell,
is_dsv_home_ready as _is_dsv_home_ready,
dismiss_dsv_password_upgrade_prompt as _dismiss_dsv_password_upgrade_prompt,
has_dsv_password_upgrade_prompt as _has_dsv_password_upgrade_prompt,
wait_for_dsv_app_after_login as _wait_for_dsv_app_after_login,
)
def _has_dsv_report_form_shell(page: Any) -> bool:
"""
判断 DSV 报表参数页的 shell 是否已经挂载完成。
核心逻辑:用户在菜单里选中目标报表后,`View Report` 按钮常常已经可以点击,
但报表标题文本未必立刻出现在 frame 正文里;此时只要 portal reports 路由和
SSRS 相关 frame 已出现,就可以认定表单页已基本就绪,避免额外等待标题文本刷出。
"""
try:
current_url = str(page.url or "").lower()
except Exception:
current_url = ""
if "/main/portal/frame/reports/" in current_url:
return True
for frame in getattr(page, "frames", []):
try:
frame_name = str(frame.name or "").strip().lower()
except Exception:
frame_name = ""
try:
frame_url = str(frame.url or "").strip().lower()
except Exception:
frame_url = ""
if frame_name in {"myiframe", "report-frame"}:
return True
if "/s360reports/ssrs/" in frame_url or "/s360reports/reports/default.aspx" in frame_url:
return True
return False
def _dsv_report_submission_started(frame: Any, locator: Any) -> bool:
"""
判断 View Report 点击后是否已开始提交。
核心逻辑:优先检测按钮是否变为 disabled/隐藏,其次检测 frame 文本里是否出现常见的加载提示,
避免“程序化 submit 已调用,但页面其实没有开始处理”的误判。
"""
try:
if not locator.is_visible(timeout=500):
return True
except Exception:
return True
try:
state = locator.evaluate(
"""
(node) => ({
disabled: Boolean(node.disabled),
ariaDisabled: node.getAttribute('aria-disabled'),
value: node.value || node.textContent || '',
})
"""
)
value = str((state or {}).get("value") or "").strip().lower()
if (state or {}).get("disabled") or str((state or {}).get("ariaDisabled") or "").lower() == "true":
return True
if value and value != "view report":
return True
except Exception:
pass
try:
body = frame.locator("body").inner_text(timeout=800).lower()
except Exception:
body = ""
transition_markers = (
"loading",
"please wait",
"generating",
"processing",
"export",
"save",
"excel",
"no records",
"no data",
)
return any(marker in body for marker in transition_markers)
def _dsv_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool:
"""
判断当前 DSV 页面或 frame 中是否已经出现目标文案。
核心逻辑:同时扫描顶层页面与各 frame 的可见文本和常见菜单节点,
用于级联菜单点击后的“下一层已展开”确认,避免只点到一级菜单就误判成功。
Args:
page: Playwright Page 对象。
text: 需要确认出现的目标文案。
timeout_ms: 单次检查的等待时间,默认 1 秒。
Returns:
bool: 找到目标文案时返回 True,否则返回 False。
"""
normalized = str(text or "").strip().lower()
if not normalized:
return False
selectors = (
f"text={text}",
f"a:has-text({json.dumps(text)})",
f".dropdown-item:has-text({json.dumps(text)})",
f"button:has-text({json.dumps(text)})",
)
for root in (page, *page.frames):
for selector in selectors:
try:
if root.locator(selector).first.is_visible(timeout=timeout_ms):
return True
except Exception:
pass
try:
body = root.locator("body").inner_text(timeout=timeout_ms).lower()
except Exception:
body = ""
if normalized in body:
return True
return False
def _dsv_dropdown_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool:
"""
仅判断当前展开的 DSV 下拉菜单中是否出现目标文案。
核心逻辑:主页 `Recent Reports` 也会出现与报表菜单同名的文本;
这里将确认范围收紧为 `Reports` 级联菜单容器内的可见项,避免把首页正文误判成下一级菜单已展开。
"""
normalized = str(text or "").strip().lower()
if not normalized:
return False
selectors = (
f"#report-mega-legacy a.dropdown-item:has-text({json.dumps(text)})",
f".mega-dropdown-menu a.dropdown-item:has-text({json.dumps(text)})",
f".dropdown-menu a.dropdown-item:has-text({json.dumps(text)})",
f"#report-mega-legacy [role='menuitem']:has-text({json.dumps(text)})",
f".mega-dropdown-menu [role='menuitem']:has-text({json.dumps(text)})",
f".dropdown-menu [role='menuitem']:has-text({json.dumps(text)})",
f"#report-mega-legacy a:has-text({json.dumps(text)})",
f".mega-dropdown-menu a:has-text({json.dumps(text)})",
f".dropdown-menu a:has-text({json.dumps(text)})",
)
for selector in selectors:
try:
if page.locator(selector).first.is_visible(timeout=timeout_ms):
return True
except Exception:
pass
# DSV 的部分 Program(例如 Salt Lake City/AWSSL)由自定义 div/span 渲染,
# 不一定带 dropdown-item、a 或 role=menuitem;精确文本定位可命中其嵌套节点。
try:
for container in ("#report-mega-legacy", ".mega-dropdown-menu", ".dropdown-menu"):
if page.locator(container).get_by_text(text, exact=True).first.is_visible(timeout=timeout_ms):
return True
except Exception:
pass
probe = _collect_dsv_menu_probe(page, text)
for item in probe.get("matchedItems") or []:
item_text = str((item or {}).get("text") or "").strip().lower()
if item_text and normalized in item_text:
return True
return False
def _try_dsv_menu_item_fast_path(page: Any, text: str, *, next_text: str = "") -> bool:
"""
尝试一次 DSV 菜单标准点击,并确认预期下级已展开。
核心逻辑:真实页面已验证的菜单通常可由精确文本一次 hover/click 打开;
仅在明确看到 next_text 后才返回成功,避免把点击事件已发送误当作层级已切换。
Args:
page: Playwright Page 对象。
text: 当前菜单文本。
next_text: 点击后应出现的下级文本;为空时只确认点击本身完成。
Returns:
bool: 下一级已确认出现或无需确认时为 True;其余情况为 False。
"""
for container in ("#report-mega-legacy", ".mega-dropdown-menu", ".dropdown-menu"):
try:
locator = page.locator(container).get_by_text(text, exact=True).first
locator.wait_for(state="visible", timeout=1_500)
locator.hover(timeout=1_000)
locator.click(timeout=1_500)
if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500):
return True
except Exception:
continue
return False
def _try_dsv_report_group_fast_path(page: Any, text: str, *, next_text: str = "") -> bool:
"""
尝试一次 Report Group 标准点击,并确认目标报表已展开。
核心逻辑:Report Group 使用精确文本,避免旧逻辑对多个宽泛 selector
分别等待十秒;失败时由兼容路径继续处理 hover 丢失等旧页面结构。
Args:
page: Playwright Page 对象。
text: Report Group 文本。
next_text: 点击后应出现的报表名称。
Returns:
bool: 报表文本确认出现时为 True,否则为 False。
"""
return _try_dsv_menu_item_fast_path(page, text, next_text=next_text)
def _click_dsv_menu_item_compat(page: Any, text: str, *, next_text: str = "") -> None:
"""
点击 DSV 级联菜单项,并在需要时确认下一级目标已经出现。
核心逻辑:对同一菜单项依次尝试 hover/click/force/evaluate/keyboard 等方式;
若传入 next_text,则只有在页面上真正看到下一级菜单文本后才认为本次点击成功。
Args:
page: Playwright Page 对象。
text: 当前要点击的菜单文案。
next_text: 预期因本次点击而出现的下一级菜单文案;为空时仅要求当前点击成功。
"""
text = str(text or "").strip()
if not text:
raise RuntimeError("DSV menu item text is empty")
_report_debug_event(
"F",
"freight_rpa_worker.py:_click_dsv_menu_item:entry",
"[DEBUG] entering dsv menu item selection",
{
"targetText": text,
"nextText": str(next_text or ""),
"elapsedMs": 0,
**_collect_dsv_menu_probe(page, text),
},
)
text_literal = json.dumps(text)
deadline = time.monotonic() + 30
started_at = time.monotonic()
while time.monotonic() < deadline:
locator_candidates = [
(page.locator(selector).first, selector)
for selector in (
f"#report-mega-legacy a.dropdown-item:has-text({text_literal})",
f".mega-dropdown-menu a.dropdown-item:has-text({text_literal})",
f".dropdown-menu a.dropdown-item:has-text({text_literal})",
f"#report-mega-legacy [role='menuitem']:has-text({text_literal})",
f".mega-dropdown-menu [role='menuitem']:has-text({text_literal})",
f".dropdown-menu [role='menuitem']:has-text({text_literal})",
f"#report-mega-legacy a:has-text({text_literal})",
f".mega-dropdown-menu a:has-text({text_literal})",
f".dropdown-menu a:has-text({text_literal})",
)
]
# 兼容自定义菜单节点及嵌套 span 文本(AWSSL 使用该类结构)。
for container in ("#report-mega-legacy", ".mega-dropdown-menu", ".dropdown-menu"):
try:
locator_candidates.append(
(page.locator(container).get_by_text(text, exact=True).first, f"{container} >> text={text!r}")
)
except Exception:
pass
for locator, selector in locator_candidates:
try:
locator.wait_for(state="visible", timeout=2_000)
for action in ("hover", "click", "force-click", "evaluate", "enter", "space"):
try:
try:
locator.scroll_into_view_if_needed(timeout=1_000)
except Exception:
pass
if action == "hover":
locator.hover(timeout=1_500)
time.sleep(0.2)
continue
elif action == "click":
locator.click(timeout=1_500)
elif action == "force-click":
locator.click(timeout=1_500, force=True)
elif action == "evaluate":
locator.evaluate("(node) => node.click()")
elif action == "enter":
locator.press("Enter", timeout=1_500)
else:
locator.press("Space", timeout=1_500)
except Exception:
continue
_report_debug_event(
"F",
"freight_rpa_worker.py:_click_dsv_menu_item:attempt",
"[DEBUG] dsv menu item attempt dispatched",
{
"targetText": text,
"nextText": str(next_text or ""),
"selector": selector,
"action": action,
"elapsedMs": int((time.monotonic() - started_at) * 1000),
**_collect_dsv_menu_probe(page, next_text or text),
},
)
if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500):
_report_debug_event(
"F",
"freight_rpa_worker.py:_click_dsv_menu_item:success",
"[DEBUG] dsv menu item selection considered successful",
{
"targetText": text,
"nextText": str(next_text or ""),
"selector": selector,
"action": action,
"elapsedMs": int((time.monotonic() - started_at) * 1000),
**_collect_dsv_menu_probe(page, next_text or text),
},
)
return
except Exception:
pass
time.sleep(0.5)
_report_debug_event(
"F",
"freight_rpa_worker.py:_click_dsv_menu_item:failed",
"[DEBUG] dsv menu item selection timed out",
{
"targetText": text,
"nextText": str(next_text or ""),
"elapsedMs": int((time.monotonic() - started_at) * 1000),
**_collect_dsv_menu_probe(page, next_text or text),
},
)
print(f"[dsv-debug] menu item missing target={text!r} {_debug_dsv_page_snapshot(page, target_text=text)}")
raise RuntimeError(f"DSV menu item was not found: {text}")
def _click_dsv_report_group_compat(page: Any, text: str, *, next_text: str = "") -> None:
"""
点击 DSV Report Group,并在需要时确认目标报表已经出现在菜单中。
核心逻辑:Report Group 往往位于 Program 的二级菜单下,单次 click 很容易因为 hover 丢失而失效;
这里在每次尝试后立刻检查 next_text,确保真正进入到报表项层级。
Args:
page: Playwright Page 对象。
text: 当前 report group 文案。
next_text: 预期出现的报表名称;为空时仅要求当前 group 点击成功。
"""
text = str(text or "").strip()
if not text:
raise RuntimeError("DSV report group text is empty")
_report_debug_event(
"G",
"freight_rpa_worker.py:_click_dsv_report_group:entry",
"[DEBUG] entering dsv report group selection",
{
"targetText": text,
"nextText": str(next_text or ""),
"elapsedMs": 0,
**_collect_dsv_menu_probe(page, text),
},
)
text_literal = json.dumps(text)
started_at = time.monotonic()
for selector in (
f"#report-mega-legacy :text-is({text_literal})",
f".mega-dropdown-menu :text-is({text_literal})",
f".dropdown-menu :text-is({text_literal})",
):
try:
locator = page.locator(selector).first
locator.wait_for(state="visible", timeout=10_000)
for action in ("hover", "click", "force-click", "evaluate", "enter", "space"):
try:
if action == "hover":
locator.hover(timeout=1_500)
time.sleep(0.2)
continue
elif action == "click":
locator.click(timeout=1_500)
elif action == "force-click":
locator.click(timeout=1_500, force=True)
elif action == "evaluate":
locator.evaluate("(node) => node.click()")
elif action == "enter":
locator.press("Enter", timeout=1_500)
else:
locator.press("Space", timeout=1_500)
except Exception:
continue
_report_debug_event(
"G",
"freight_rpa_worker.py:_click_dsv_report_group:attempt",
"[DEBUG] dsv report group attempt dispatched",
{
"targetText": text,
"nextText": str(next_text or ""),
"selector": selector,
"action": action,
"elapsedMs": int((time.monotonic() - started_at) * 1000),
**_collect_dsv_menu_probe(page, next_text or text),
},
)
if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500):
_report_debug_event(
"G",
"freight_rpa_worker.py:_click_dsv_report_group:success",
"[DEBUG] dsv report group selection considered successful",
{
"targetText": text,
"nextText": str(next_text or ""),
"selector": selector,
"action": action,
"elapsedMs": int((time.monotonic() - started_at) * 1000),
**_collect_dsv_menu_probe(page, next_text or text),
},
)
return
except Exception:
pass
_report_debug_event(
"G",
"freight_rpa_worker.py:_click_dsv_report_group:failed",
"[DEBUG] dsv report group selection timed out",
{
"targetText": text,
"nextText": str(next_text or ""),
**_collect_dsv_menu_probe(page, next_text or text),
},
)
print(f"[dsv-debug] report group missing target={text!r} {_debug_dsv_page_snapshot(page, target_text=text)}")
raise RuntimeError(f"DSV report group was not found: {text}")
def _click_dsv_menu_item(page: Any, text: str, *, next_text: str = "") -> None:
"""
点击 DSV 级联菜单,并在标准路径失败后回退全部兼容动作。
核心逻辑:先走一次精确文本 hover/click 快速路径;只有下一级没有被确认时,
才调用原有多 selector、多输入方式的兼容逻辑,兼顾性能和历史页面兼容性。
Args:
page: Playwright Page 对象。
text: 当前菜单文案。
next_text: 预期出现的下一级菜单文案。
"""
text = str(text or "").strip()
if not text:
raise RuntimeError("DSV menu item text is empty")
if _try_dsv_menu_item_fast_path(page, text, next_text=next_text):
print(f"[dsv-navigation] fast-path menu item selected target={text!r}")
return
_click_dsv_menu_item_compat(page, text, next_text=next_text)
def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> None:
"""
点击 DSV Report Group,并在标准路径失败后回退完整兼容链。
核心逻辑:快速路径确认报表名称已出现才结束;否则保留历史多动作策略,
防止旧页面的 hover 状态不稳定时降低导出成功率。
Args:
page: Playwright Page 对象。
text: Report Group 文案。
next_text: 预期出现的报表名称。
"""
text = str(text or "").strip()
if not text:
raise RuntimeError("DSV report group text is empty")
if _try_dsv_report_group_fast_path(page, text, next_text=next_text):
print(f"[dsv-navigation] fast-path report group selected target={text!r}")
return
_click_dsv_report_group_compat(page, text, next_text=next_text)
def _click_dsv_view_report(page: Any) -> None:
"""
点击 SSRS 参数页 View Report。
核心逻辑:在各 frame 内轮询 ReportViewer 固定控件 ID 与通用按钮选择器,挂载后尝试多种点击方式。
"""
selectors = (
"#ReportViewerMain_ctl08_ctl00",
'input[id^="ReportViewerMain_"][value="View Report"]',
'input[type="submit"][value="View Report"]',
'input[value="View Report"]',
'button:has-text("View Report")',
)
_debug_dsv_stage(page, "view-report-before-click", target_text="View Report")
wait_ms = max(15_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_VIEW_REPORT_WAIT_MS", "30000") or "30000"))
deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline:
for frame in page.frames:
for selector in selectors:
try:
locator = frame.locator(selector).first
locator.wait_for(state="attached", timeout=1_000)
click_attempts = ("click", "enter", "space", "evaluate-click", "request-submit")
for attempt in click_attempts:
try:
try:
locator.scroll_into_view_if_needed(timeout=1_000)
except Exception:
pass
if attempt == "click":
locator.click(timeout=2_000, force=True)
elif attempt == "enter":
locator.press("Enter", timeout=1_500)
elif attempt == "space":
locator.press("Space", timeout=1_500)
elif attempt == "evaluate-click":
locator.evaluate(
"""
(target) => {
target.click();
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
}
"""
)
else:
locator.evaluate(
"""
(target) => {
if (target.form && typeof target.form.requestSubmit === 'function') {
target.form.requestSubmit(target);
} else if (target.form) {
target.form.submit();
} else {
target.click();
}
}
"""
)
except Exception:
continue
submit_deadline = time.monotonic() + 4
while time.monotonic() < submit_deadline:
if _dsv_report_submission_started(frame, locator):
print(f"[dsv] view report submitted via selector={selector!r} attempt={attempt}")
_debug_dsv_stage(page, f"view-report-after-click-{attempt}", target_text="View Report")
return
time.sleep(0.3)
except Exception:
pass
time.sleep(0.3)
print(f"[dsv-debug] view report missing {_debug_dsv_page_snapshot(page, target_text='View Report')}")
raise RuntimeError("DSV View Report button was not found")
def _is_dsv_reports_menu_open(page: Any) -> bool:
"""
判断 DSV Reports 下拉是否已真正展开,而不是仅仅点到了导航按钮。
核心逻辑:优先检查 `#report-mega-legacy` 上的 `show/open/aria-expanded` 状态,
再兜底检查常见下拉容器里是否出现可见菜单项,避免“点击成功但菜单没开”的误判。
"""
for selector in (
"#report-mega-legacy.show",
"#report-mega-legacy.open",
"#report-mega-legacy[aria-expanded='true']",
"#report-mega-legacy .mega-dropdown-menu.show",
"#report-mega-legacy .dropdown-menu.show",
".mega-dropdown-menu.show",
".dropdown-menu.show",
):
try:
if page.locator(selector).first.is_visible(timeout=150):
return True
except Exception:
pass
for selector in (
"#report-mega-legacy .dropdown-item",
".mega-dropdown-menu a.dropdown-item",
".dropdown-menu a.dropdown-item",
):
try:
locator = page.locator(selector).first
if locator.is_visible(timeout=150):
return True
except Exception:
pass
return False
def _click_dsv_reports_menu(page: Any) -> None:
started_at = time.monotonic()
# #region debug-point B:reports-click-entry
_report_debug_event(
"B",
"freight_rpa_worker.py:_click_dsv_reports_menu:entry",
"[DEBUG] entering reports click flow",
{"elapsedMs": 0, **_collect_dsv_reports_probe(page)},
)
# #endregion
click_selectors = (
"#report-mega-legacy > a.dropdown-toggle.nav-link",
"#report-mega-legacy a.dropdown-toggle",
"#report-mega-legacy a.nav-link",
"nav a:has-text('Reports')",
"a.nav-link:has-text('Reports')",
)
click_roots = [page, *list(getattr(page, "frames", []))]
for selector in click_selectors:
for root in click_roots:
try:
locator = root.locator(selector).first
locator.wait_for(state="attached", timeout=5_000)
except Exception:
continue
# [STEP 1] Reports 打开优先走真实 click,避免先 hover 白等一轮再退回 click。
for action_name in ("click", "evaluate", "enter", "space", "hover"):
try:
locator.scroll_into_view_if_needed(timeout=2_000)
except Exception:
pass
try:
if action_name == "hover":
locator.hover(timeout=2_000)
elif action_name == "click":
locator.click(timeout=2_000, force=True)
elif action_name == "evaluate":
locator.evaluate(
"""
(target) => {
target.click();
target.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, cancelable: true, view: window }));
target.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true, cancelable: true, view: window }));
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
}
"""
)
elif action_name == "enter":
locator.press("Enter", timeout=1_500)
else:
locator.press("Space", timeout=1_500)
except Exception:
continue
# #region debug-point B:reports-click-attempt
_report_debug_event(
"B",
"freight_rpa_worker.py:_click_dsv_reports_menu:attempt",
"[DEBUG] reports click attempt dispatched",
{
"selector": selector,
"action": action_name,
**_collect_dsv_reports_probe(page),
},
)
# #endregion
post_action_wait_seconds = 0.6 if action_name == "hover" else 1.2
action_deadline = time.monotonic() + post_action_wait_seconds
while time.monotonic() < action_deadline:
if _is_dsv_reports_menu_open(page):
print(f"[dsv] reports expanded via {action_name} selector={selector!r}")
_debug_dsv_stage(page, f"reports-expanded-{action_name}", target_text="Reports")
# #region debug-point D:reports-expanded
_report_debug_event(
"D",
"freight_rpa_worker.py:_click_dsv_reports_menu:expanded",
"[DEBUG] reports menu expanded after click attempt",
{
"selector": selector,
"action": action_name,
"elapsedMs": int((time.monotonic() - started_at) * 1000),
**_collect_dsv_reports_probe(page),
},
)
# #endregion
return
time.sleep(0.2)
print(f"[dsv-debug] reports menu missing {_debug_dsv_page_snapshot(page, target_text='Reports')}")
# #region debug-point C:reports-click-failed
_report_debug_event(
"C",
"freight_rpa_worker.py:_click_dsv_reports_menu:failed",
"[DEBUG] reports menu click flow exhausted without expansion",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
)
# #endregion
raise RuntimeError("DSV Reports menu was not found")
def _wait_for_dsv_reports_nav_stable(page: Any, *, timeout_ms: int | None = None) -> None:
"""
在首页 ready 之后,继续等待 Reports 导航进入可稳定交互态。
核心逻辑:首页首屏刚渲染完成时,Reports 虽然已经可见,但 hover/click 仍可能被吞掉;
这里要求导航链接连续多次保持可见,降低“刚进首页就急着点”的误触发概率。
"""
wait_ms = timeout_ms if timeout_ms is not None else 8_000
selectors = (
"#report-mega-legacy > a.dropdown-toggle.nav-link",
"#report-mega-legacy a.dropdown-toggle",
"#report-mega-legacy a.nav-link",
)
deadline = time.monotonic() + (wait_ms / 1000)
stable_hits = 0
started_at = time.monotonic()
# #region debug-point L:reports-nav-stable-entry
_report_debug_event(
"L",
"freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:entry",
"[DEBUG] waiting for dsv reports nav stable",
{"timeoutMs": wait_ms, **_collect_dsv_reports_probe(page)},
)
# #endregion
while time.monotonic() < deadline:
visible = False
click_roots = [page, *list(getattr(page, "frames", []))]
for selector in selectors:
for root in click_roots:
try:
locator = root.locator(selector).first
if locator.is_visible(timeout=200):
visible = True
break
except Exception:
pass
if visible:
break
if visible:
stable_hits += 1
if stable_hits >= 3:
# #region debug-point L:reports-nav-stable-success
_report_debug_event(
"L",
"freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:success",
"[DEBUG] dsv reports nav considered stable",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)},
)
# #endregion
return
else:
stable_hits = 0
time.sleep(0.4)
# #region debug-point L:reports-nav-stable-timeout
_report_debug_event(
"L",
"freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:timeout",
"[DEBUG] dsv reports nav did not become stable in time",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)},
)
# #endregion
def _wait_for_dsv_reports_open(page: Any, *, timeout_ms: int | None = None) -> None:
"""
等待 Reports 下拉真正展开。
核心逻辑:菜单导航偶发存在 hover/click 已触发但 DOM 尚未展开的情况;
这里统一以 `_is_dsv_reports_menu_open()` 为成功判据,避免“看起来点了,实际没开”。
"""
wait_ms = timeout_ms if timeout_ms is not None else 15_000
deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline:
if _is_dsv_reports_menu_open(page):
_debug_dsv_stage(page, "reports-open-confirmed", target_text="Reports")
# #region debug-point D:reports-open-confirmed
_report_debug_event(
"D",
"freight_rpa_worker.py:_wait_for_dsv_reports_open:confirmed",
"[DEBUG] reports open confirmed",
_collect_dsv_reports_probe(page),
)
# #endregion
return
time.sleep(0.3)
_debug_dsv_stage(page, "reports-open-timeout", target_text="Reports")
# #region debug-point D:reports-open-timeout
_report_debug_event(
"D",
"freight_rpa_worker.py:_wait_for_dsv_reports_open:timeout",
"[DEBUG] reports open confirmation timed out",
_collect_dsv_reports_probe(page),
)
# #endregion
raise RuntimeError("DSV Reports menu did not expand")
def _wait_for_dsv_report_form_ready(page: Any, report_name: str, *, timeout_ms: int | None = None) -> None:
"""
等待报表表单页稳定可操作。
核心逻辑:选择 Program / Group / Report 后,不立即假设已进入表单页;
优先要求 `View Report` 按钮出现,同时满足“报表标题文本已出现”或“报表 shell/frame 已挂载”,
这样既能避免顺序错乱,也不会因为标题文本稍晚刷新而额外空等数秒。
"""
wait_ms = timeout_ms if timeout_ms is not None else max(
60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_FORM_TIMEOUT_MS", "60000") or "60000")
)
deadline = time.monotonic() + (wait_ms / 1000)
started_at = time.monotonic()
normalized_report = str(report_name or "").strip().lower()
last_probe_signature: tuple[bool, bool, bool] | None = None
last_probe_logged_at = 0.0
_report_debug_event(
"H",
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:entry",
"[DEBUG] waiting for dsv report form ready",
{
"reportName": str(report_name or ""),
**_collect_dsv_menu_probe(page, report_name or "View Report"),
},
)
while time.monotonic() < deadline:
view_report_visible = False
try:
if _wait_for_visible_selector(
page,
"",
(
'input[id^="ReportViewerMain_"][value="View Report"]',
'input[type="submit"][value="View Report"]',
'input[value="View Report"]',
'button:has-text("View Report")',
),
timeout_ms=1_000,
) is not None:
view_report_visible = True
except Exception:
view_report_visible = False
report_title_visible = False
if normalized_report:
for frame in page.frames:
try:
body = frame.locator("body").inner_text(timeout=500).lower()
except Exception:
body = ""
if normalized_report in body:
report_title_visible = True
break
form_shell_ready = _has_dsv_report_form_shell(page)
probe_signature = (view_report_visible, report_title_visible, form_shell_ready)
now = time.monotonic()
if probe_signature != last_probe_signature or (now - last_probe_logged_at) >= 2.0:
print(
"[dsv-report-form-probe] "
f"elapsedMs={int((now - started_at) * 1000)} "
f"viewReportVisible={view_report_visible} "
f"reportTitleVisible={report_title_visible} "
f"formShellReady={form_shell_ready} "
f"stateChanged={probe_signature != last_probe_signature}"
)
_report_debug_event(
"H",
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:probe",
"[DEBUG] dsv report form probe state",
{
"reportName": str(report_name or ""),
"elapsedMs": int((now - started_at) * 1000),
"viewReportVisible": view_report_visible,
"reportTitleVisible": report_title_visible,
"formShellReady": form_shell_ready,
"stateChanged": probe_signature != last_probe_signature,
**_collect_dsv_menu_probe(page, report_name or "View Report"),
},
)
last_probe_signature = probe_signature
last_probe_logged_at = now
if form_shell_ready and report_title_visible and not view_report_visible:
remaining_ms = max(0, int((deadline - time.monotonic()) * 1000))
if remaining_ms > 0:
if _wait_for_visible_selector(
page,
"",
(
'input[id^="ReportViewerMain_"][value="View Report"]',
'input[type="submit"][value="View Report"]',
'input[value="View Report"]',
'button:has-text("View Report")',
),
timeout_ms=min(remaining_ms, 45_000),
) is not None:
view_report_visible = True
print(
"[dsv-report-form-probe] viewReport appeared after shell+title "
f"elapsedMs={int((time.monotonic() - started_at) * 1000)}"
)
if view_report_visible and (report_title_visible or form_shell_ready or not normalized_report):
_report_debug_event(
"H",
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:success",
"[DEBUG] dsv report form became ready",
{
"reportName": str(report_name or ""),
"elapsedMs": int((time.monotonic() - started_at) * 1000),
"viewReportVisible": view_report_visible,
"reportTitleVisible": report_title_visible,
"formShellReady": form_shell_ready,
**_collect_dsv_menu_probe(page, report_name or "View Report"),
},
)
_debug_dsv_stage(page, "report-form-ready", target_text=report_name or "View Report")
return
time.sleep(0.5)
_report_debug_event(
"H",
"freight_rpa_worker.py:_wait_for_dsv_report_form_ready:timeout",
"[DEBUG] dsv report form wait timed out",
{
"reportName": str(report_name or ""),
"elapsedMs": int((time.monotonic() - started_at) * 1000),
"viewReportVisible": view_report_visible,
"reportTitleVisible": report_title_visible,
"formShellReady": _has_dsv_report_form_shell(page),
**_collect_dsv_menu_probe(page, report_name or "View Report"),
},
)
_debug_dsv_stage(page, "report-form-timeout", target_text=report_name or "View Report")
raise RuntimeError("DSV report form was not ready")
# 公开 API
has_dsv_report_form_shell = _has_dsv_report_form_shell
dsv_report_submission_started = _dsv_report_submission_started
dsv_text_visible = _dsv_text_visible
dsv_dropdown_text_visible = _dsv_dropdown_text_visible
click_dsv_menu_item = _click_dsv_menu_item
click_dsv_report_group = _click_dsv_report_group
click_dsv_view_report = _click_dsv_view_report
is_dsv_reports_menu_open = _is_dsv_reports_menu_open
click_dsv_reports_menu = _click_dsv_reports_menu
wait_for_dsv_reports_nav_stable = _wait_for_dsv_reports_nav_stable
wait_for_dsv_reports_open = _wait_for_dsv_reports_open
wait_for_dsv_report_form_ready = _wait_for_dsv_report_form_ready
File diff suppressed because it is too large. Load diff
-588
View File
@@ -1,588 +0,0 @@
"""
scripts/rpa/dsv_report_parameters.py
用途:填充 DSV 360 SSRS ReportViewer 报表参数(Owner / PutawayZone / Warehouse)。
依赖:Playwright Page/Frame;由 freight_rpa_worker._fill_dsv_filter_if_needed 委托调用。
逻辑:识别 multi-value checkbox 与 ValidValue select,在 report iframe 内操作并等待控件启用。
"""
from __future__ import annotations
import json
import sys
import time
from typing import Any, Callable
# BYAWSATL01 等 3lv 报表在 SSRS 中的默认控件 ID(与页面源码一致)。
_DSV_REPORT_PARAM_DEFAULTS: dict[str, dict[str, str]] = {
"Owner": {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl03_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl03_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl03_divDropDown",
},
"PutawayZone": {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl07_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl07_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl07_divDropDown",
},
"Warehouse": {
"control": "select",
"selector": "#ReportViewerMain_ctl08_ctl17_ddValue",
},
}
def _normalize_report_name(report_name: str) -> str:
"""报表名归一化:去首尾空白并折叠连续空白、统一小写,用于模板精确匹配。"""
return " ".join(str(report_name or "").strip().lower().split())
# 报表名 → 参数控件模板。同名的 SSRS 参数在不同报表里的控件长相不同:
# - 3lv 版(On Hand Inventory By Location 3lv,Bison/AWSBI):Warehouse 是原生 select(ddValue);
# - JDA 版(On Hand Inventory by Location,Moerdijk 等):Warehouse 是 txtValue + toggle + divDropDown
# 组成的多选框下拉(multi_value),历史 YAML 为该源配置的 selectors 即源于此。
# 模板按"归一化报表名"精确匹配;未命中时回退 _DSV_REPORT_PARAM_DEFAULTS(保持旧行为)。
_DSV_REPORT_PARAM_TEMPLATES: dict[str, dict[str, dict[str, str]]] = {
"on hand inventory by location 3lv": {
"Warehouse": {
"control": "select",
"selector": "#ReportViewerMain_ctl08_ctl17_ddValue",
},
},
"on hand inventory by location": {
"Warehouse": {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
},
},
}
def resolve_parameter_controls(report_name: str | None, label: str) -> dict[str, str]:
"""
按(报表名, 参数名)解析 SSRS 控件配置;报表模板优先,未命中返回空 dict。
Args:
report_name: 当前报表名(如 navigation.report_name),允许为空。
label: 参数名(Owner / PutawayZone / Warehouse)。
Returns:
dict[str, str]: 控件配置(control/selector 或 control/text/toggle/dropdown);
报表未登记时为空 dict,由调用方回退参数名默认值。
"""
key = _normalize_report_name(report_name)
template = _DSV_REPORT_PARAM_TEMPLATES.get(key) or {}
return dict(template.get(str(label or "").strip()) or {})
def _iter_dsv_report_roots(page: Any) -> list[Any]:
"""返回包含 ReportViewerMain 的 frame;找不到时回退到全部 roots。"""
matched: list[Any] = []
for frame in getattr(page, "frames", []):
try:
if frame.locator("#ReportViewerMain").count() > 0:
matched.append(frame)
except Exception:
continue
if matched:
return matched
return [page, *list(getattr(page, "frames", []))]
def _find_locator(page: Any, selector: str) -> tuple[Any | None, Any | None]:
"""在 report roots 中查找 selector 对应的 locator。"""
for root in _iter_dsv_report_roots(page):
try:
locator = root.locator(selector).first
locator.wait_for(state="attached", timeout=1_000)
return root, locator
except Exception:
continue
return None, None
def _warehouse_select_state(locator: Any, value: str) -> dict[str, Any]:
"""探测 Warehouse select 是否已有目标 option、是否已解除 disabled。"""
try:
result = locator.evaluate(
"""
(select, target) => {
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim().toLowerCase();
const wanted = normalize(target);
const options = Array.from(select.options || []);
const hasTarget = options.some((item) => normalize(item.textContent) === wanted);
const realOptions = options.filter((item) => {
const label = normalize(item.textContent);
return label && label !== '<select a value>' && !label.includes('select a value');
}).length;
return {
hasTarget,
enabled: !select.disabled && !select.classList.contains('aspNetDisabled'),
optionCount: options.length,
realOptionCount: realOptions,
};
}
""",
value,
)
if isinstance(result, dict):
return result
except Exception:
pass
return {"hasTarget": False, "enabled": False, "optionCount": 0, "realOptionCount": 0}
def _apply_select_value_via_script(locator: Any, value: str) -> bool:
"""通过脚本写入 select 值;SSRS 常在 option 已加载但仍保持 aspNetDisabled。"""
try:
return bool(
locator.evaluate(
"""
(select, target) => {
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
const wanted = normalize(target).toLowerCase();
const option = Array.from(select.options).find(
(item) => normalize(item.textContent).toLowerCase() === wanted
);
if (!option) return false;
select.disabled = false;
select.classList.remove('aspNetDisabled');
select.removeAttribute('disabled');
select.value = option.value;
select.dispatchEvent(new Event('input', { bubbles: true }));
select.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
""",
value,
)
)
except Exception:
return False
def _wait_for_warehouse_select_ready(locator: Any, value: str, *, timeout_ms: int) -> tuple[bool, int, dict[str, Any]]:
"""
等待 Warehouse 下拉出现目标 option。
核心逻辑:SSRS 报表参数页会先渲染 Owner/PutawayZone 默认值,Warehouse 的 option 列表
由 ReportViewer 异步拉取;此期间 select 长期保持 aspNetDisabled,肉眼像“卡住不能选”。
"""
started_at = time.monotonic()
deadline = started_at + (timeout_ms / 1000)
last_log_at = 0.0
last_state: dict[str, Any] = {}
while time.monotonic() < deadline:
last_state = _warehouse_select_state(locator, value)
if last_state.get("hasTarget"):
elapsed_ms = int((time.monotonic() - started_at) * 1000)
return True, elapsed_ms, last_state
now = time.monotonic()
if now - last_log_at >= 2.0:
print(
"[dsv-filter] waiting warehouse options "
f"target={value!r} optionCount={last_state.get('optionCount')} "
f"realOptionCount={last_state.get('realOptionCount')} enabled={last_state.get('enabled')}"
)
last_log_at = now
time.sleep(0.2)
elapsed_ms = int((time.monotonic() - started_at) * 1000)
return False, elapsed_ms, last_state
def _wait_until_enabled(locator: Any, *, timeout_ms: int = 15_000) -> bool:
"""等待 SSRS 控件从 aspNetDisabled 变为可操作。"""
deadline = time.monotonic() + (timeout_ms / 1000)
while time.monotonic() < deadline:
try:
disabled = locator.evaluate(
"(node) => Boolean(node.disabled || node.classList.contains('aspNetDisabled'))"
)
if not disabled:
return True
except Exception:
pass
time.sleep(0.25)
return False
def _fill_input_via_script(root: Any, selector: str, value: str) -> bool:
"""
通过脚本解除 disabled 并写入文本框(Owner/PutawayZone 兜底)。
核心逻辑:ReportViewer 初始常把参数控件设为 aspNetDisabled,需先启用再赋值。
"""
try:
return bool(
root.evaluate(
"""
({ selector, value }) => {
const node = document.querySelector(selector);
if (!node) return false;
node.disabled = false;
node.removeAttribute('disabled');
node.classList.remove('aspNetDisabled');
node.readOnly = false;
node.removeAttribute('readonly');
node.value = value;
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
""",
{"selector": selector, "value": value},
)
)
except Exception:
return False
def _fill_multi_value_parameter(
page: Any,
label: str,
values: list[str],
*,
timeout_ms: int,
config_override: dict[str, str] | None = None,
select_all: bool = False,
) -> bool:
"""
填充 SSRS MultiValueParameterInputControl(Owner / PutawayZone)。
核心逻辑:展开 dropdown → 按 label 勾选/取消 checkbox → 关闭 dropdown。
"""
config = {**_DSV_REPORT_PARAM_DEFAULTS.get(label, {}), **(config_override or {})}
if config.get("control") != "multi_value":
return False
cleaned = [str(item).strip() for item in values if str(item).strip()]
if not cleaned and not select_all:
return False
_, text_locator = _find_locator(page, config["text"])
if text_locator is not None and not select_all:
try:
current = str(text_locator.input_value(timeout=2_000) or "").strip()
if current and all(item in current for item in cleaned):
print(f"[dsv-filter] {label} already set text={current!r}")
return True
except Exception:
pass
root, toggle = _find_locator(page, config["toggle"])
if root is not None and toggle is not None:
try:
toggle.click(timeout=timeout_ms, force=True)
time.sleep(0.4)
except Exception:
pass
root, _ = _find_locator(page, config["dropdown"])
if root is None:
return False
desired = {item.casefold() for item in cleaned}
try:
adjusted = root.evaluate(
"""
({ dropdownSelector, desiredValues, restrictToDesired, selectAll }) => {
const dropdown = document.querySelector(dropdownSelector);
if (!dropdown) return false;
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
const labels = Array.from(dropdown.querySelectorAll('label'));
let changed = false;
let selectAllClicked = false;
const entries = [];
for (const labelNode of labels) {
const text = normalize(labelNode.textContent);
if (!text) continue;
let checkbox = null;
const htmlFor = labelNode.getAttribute('for');
if (htmlFor) {
checkbox = document.getElementById(htmlFor);
}
if (!checkbox) {
checkbox = labelNode.previousElementSibling;
}
if (!checkbox || checkbox.type !== 'checkbox') continue;
const isSelectAll = text === '(Select All)' || text.toLowerCase().includes('select all');
entries.push({ text, checkbox, isSelectAll });
if (selectAll && isSelectAll) {
if (!checkbox.checked) {
checkbox.click();
changed = true;
}
selectAllClicked = true;
}
}
if (selectAll && !selectAllClicked) {
for (const entry of entries) {
if (!entry.isSelectAll && !entry.checkbox.checked) {
entry.checkbox.click();
changed = true;
}
}
}
if (selectAll) {
return changed || entries.length > 0;
}
for (const entry of entries) {
if (entry.isSelectAll) continue;
const shouldCheck = desiredValues.includes(text.toLowerCase());
if (restrictToDesired) {
if (entry.checkbox.checked !== shouldCheck) {
entry.checkbox.click();
changed = true;
}
} else if (shouldCheck && !entry.checkbox.checked) {
entry.checkbox.click();
changed = true;
}
}
return changed || labels.length > 0;
}
""",
{
"dropdownSelector": config["dropdown"],
"desiredValues": list(desired),
"restrictToDesired": label == "PutawayZone",
"selectAll": select_all,
},
)
if adjusted:
if select_all:
print(f"[dsv-filter] {label} multi_value select_all")
else:
print(f"[dsv-filter] {label} multi_value checkboxes={cleaned!r}")
if toggle is not None:
try:
toggle.click(timeout=2_000, force=True)
except Exception:
pass
return True
except Exception as exc:
print(f"[dsv-filter] {label} multi_value checkbox failed: {exc}", file=sys.stderr)
joined = ", ".join(cleaned)
for root in _iter_dsv_report_roots(page):
if _fill_input_via_script(root, config["text"], joined):
print(f"[dsv-filter] {label} multi_value script text={joined!r}")
return True
return False
def _fill_select_parameter(page: Any, label: str, value: str, selector: str, *, timeout_ms: int) -> bool:
"""
填充 SSRS ValidValueParameterInputControl(Warehouse 等原生 select)。
核心逻辑:目标 option 出现在 DOM 后即用脚本赋值,不必等 Playwright 可见的 enabled 状态。
"""
_, locator = _find_locator(page, selector)
if locator is None:
return False
wait_cap_ms = min(timeout_ms, 45_000) if label == "Warehouse" else timeout_ms
ready, waited_ms, state = _wait_for_warehouse_select_ready(locator, value, timeout_ms=wait_cap_ms)
if ready and _apply_select_value_via_script(locator, value):
mode = "script-after-options" if not state.get("enabled") else "script-after-enabled"
print(
f"[dsv-filter] {label} select {mode} value={value!r} "
f"waitedMs={waited_ms} selector={selector!r}"
)
return True
if waited_ms >= 500:
print(
f"[dsv-filter] {label} warehouse options not ready after {waited_ms}ms; "
f"fallback enabled-wait state={state!r}"
)
enable_started = time.monotonic()
_wait_until_enabled(locator, timeout_ms=min(wait_cap_ms, 15_000))
enable_wait_ms = int((time.monotonic() - enable_started) * 1000)
if enable_wait_ms >= 500:
print(f"[dsv-filter] {label} enabled-waitMs={enable_wait_ms}")
try:
locator.select_option(label=value, timeout=min(timeout_ms, 10_000))
print(f"[dsv-filter] {label} select_option label={value!r} selector={selector!r}")
return True
except Exception:
pass
if _apply_select_value_via_script(locator, value):
print(f"[dsv-filter] {label} select script fallback value={value!r} selector={selector!r}")
return True
return False
def _probe_report_parameter_controls(page: Any) -> dict[str, Any]:
"""
枚举报表参数区(ReportViewerMain_ctl08)的实际控件,用于填参失败时定位控件类型漂移。
核心逻辑:SSRS 对同一参数名在不同报表里可能渲染成原生 select、文本框或多选框下拉;
失败日志带上本探针后,无需人工开浏览器即可判断目标控件是否存在、option 数是否为空。
"""
roots = _iter_dsv_report_roots(page)
probe: dict[str, Any] = {"roots": len(roots), "controls": []}
for root in roots:
try:
items = root.evaluate(
"""
() => {
const normalize = (text) => ((text || '') + '').replace(/\\s+/g, ' ').trim();
const nodes = Array.from(document.querySelectorAll(
'#ReportViewerMain_ctl08 select, #ReportViewerMain_ctl08 input, ' +
'#ReportViewerMain_ctl08 [id$="_divDropDown"]'
));
return nodes.slice(0, 60).map((node) => {
const table = node.tagName.toLowerCase() === 'select'
? Array.from(node.options || []).map((item) => normalize(item.textContent)).filter(Boolean)
: [];
const dropdown = node.getAttribute('id') || '';
return {
id: dropdown,
tag: node.tagName.toLowerCase(),
type: node.getAttribute('type') || '',
hidden: node.getAttribute('type') === 'hidden',
optionCount: table.length,
firstOptions: table.slice(0, 12),
labelText: normalize(
(node.closest('td') || {}).innerText || ''
).slice(0, 120),
};
});
}
""",
)
if isinstance(items, list):
probe["controls"].extend(items)
except Exception as exc:
probe["controls"].append({"probe_error": str(exc)[:120]})
return probe
def fill_dsv_filter_if_needed(
page: Any,
selector_env: str,
label: str,
value: str | None,
*,
env: Callable[[str, str], str],
browser_timeout_ms: Callable[[], int],
debug_stage: Callable[..., None] | None = None,
report_name: str | None = None,
) -> None:
"""
按 ReportViewer 控件类型填充 DSV 报表参数。
核心逻辑:优先使用 JSON/页面默认 selector;Warehouse 走 select_option,Owner/PutawayZone 走 checkbox。
报表模板(_DSV_REPORT_PARAM_TEMPLATES)登记了同类报表的控件差异:传入 report_name 时,
先按模板选择 multi_value/select;未命中的报表回退参数名默认值(旧行为)。
"""
text = str(value or "").strip()
if not text:
return
def _debug(stage: str, target: str) -> None:
if debug_stage is not None:
debug_stage(page, stage, target_text=target)
try:
if page.get_by_text(text, exact=False).first.is_visible(timeout=1_500):
print(f"[dsv-filter] {label} already visible text={text!r}")
_debug(f"filter-skip-{label.lower()}", text)
return
except Exception:
pass
timeout_ms = browser_timeout_ms()
defaults = dict(_DSV_REPORT_PARAM_DEFAULTS.get(label, {}))
# 报表模板优先:同一参数名在不同报表的控件长相不同(3lv select vs JDA multi_value)。
template_controls = resolve_parameter_controls(report_name, label)
if template_controls:
defaults.update(template_controls)
custom_selector = str(env(selector_env) or "").strip()
selector = custom_selector or defaults.get("selector") or defaults.get("text")
if not selector and not defaults:
print(f"[dsv] skip {label} filter; no selector configured")
_debug(f"filter-no-selector-{label.lower()}", text)
return
values = [part.strip() for part in text.split(",") if part.strip()] if label == "PutawayZone" else [text]
# [STEP 1] 模板登记为 multi_value(或 Owner/PutawayZone 固有多选)时,优先走 checkbox 下拉填充。
if defaults.get("control") == "multi_value" or label in {"Owner", "PutawayZone"}:
if _fill_multi_value_parameter(
page, label, values, timeout_ms=timeout_ms, config_override=defaults,
):
_debug(f"filter-filled-{label.lower()}", text)
return
# [STEP 2] 原生 select 路径:模板为 select 或未登记时继续旧行为(ddValue + 选项等待/脚本赋值)。
select_selector = custom_selector or defaults.get("selector", "")
if select_selector and (defaults.get("control") == "select" or select_selector.endswith("ddValue")):
if _fill_select_parameter(page, label, text, select_selector, timeout_ms=timeout_ms):
_debug(f"filter-filled-{label.lower()}", text)
return
# [STEP 3] 文本输入/脚本兜底:适用于普通文本参数与多选控件的输入框。
print(f"[dsv-filter] filling {label} text={text!r} selector={selector!r}")
for root in _iter_dsv_report_roots(page):
if _fill_input_via_script(root, selector, text):
_debug(f"filter-filled-{label.lower()}", text)
return
# 最后回退:Playwright fill(适用于普通文本参数)
_, locator = _find_locator(page, selector)
if locator is not None:
_wait_until_enabled(locator, timeout_ms=timeout_ms)
try:
locator.fill(text, timeout=timeout_ms)
_debug(f"filter-filled-{label.lower()}", text)
return
except Exception as exc:
print(f"[dsv-filter] {label} fill fallback failed: {exc}", file=sys.stderr)
# 全部路径失败:输出参数区控件探针,便于下轮直接定位控件 ID/类型漂移。
print(
f"[dsv-filter] {label} control probe: "
f"{json.dumps(_probe_report_parameter_controls(page), ensure_ascii=False)[:1500]}",
file=sys.stderr,
)
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
_debug(f"filter-failed-{label.lower()}", text)
def fill_dsv_multi_select_parameter(
page: Any,
label: str,
values: list[str],
*,
selectors: dict[str, str] | None = None,
select_all: bool = False,
browser_timeout_ms: Callable[[], int],
report_name: str | None = None,
) -> bool:
"""
填充由 YAML `mode: multi_select` 显式声明的 SSRS checkbox 下拉参数。
【AI 触发时机】:当 DSV 报表参数不是原生 select,而是 `txtValue + divDropDown + checkbox`
组合控件时调用;例如 AWSAMS 的 Warehouse 下拉需要全选。
核心逻辑:selectors 缺省时按报表模板(report_name)解析控件;两者都没有则返回 False。
"""
config_override = {"control": "multi_value"}
effective_selectors = selectors or (resolve_parameter_controls(report_name, label) or None)
if effective_selectors:
for key in ("text", "toggle", "dropdown"):
value = str(effective_selectors.get(key) or "").strip()
if value:
config_override[key] = value
if not all(config_override.get(key) for key in ("text", "toggle", "dropdown")):
return False
return _fill_multi_value_parameter(
page,
label,
values,
timeout_ms=browser_timeout_ms(),
config_override=config_override,
select_all=select_all,
)
-488
View File
@@ -1,488 +0,0 @@
"""
scripts/rpa/dsv_session.py
用途:DSV 360 portal 壳层检测、首页 Reports 导航就绪与 entry_url 打开。
依赖:rpa_common、dsv_debug、dsv_auth(升级提示与登录后回调)。
逻辑:dsv_navigation / dsv_debug 探针;dsv_report_export 在 ensure 前检测 session。
"""
from __future__ import annotations
import sys
import time
from typing import Any, Callable
from rpa_common import browser_timeout_ms as _browser_timeout_ms
from rpa_common import env as _env
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
import dsv_debug
from dsv_debug import (
collect_dsv_reports_probe as _collect_dsv_reports_probe,
debug_dsv_stage as _debug_dsv_stage,
report_debug_event as _report_debug_event,
)
_DSV_REPORTS_NAV_SELECTORS: tuple[str, ...] = (
"#report-mega-legacy",
"#report-mega-legacy > a.dropdown-toggle.nav-link",
"#report-mega-legacy a.dropdown-toggle",
"#report-mega-legacy a.nav-link",
"nav a:has-text('Reports')",
"a.nav-link:has-text('Reports')",
)
def _iter_dsv_report_nav_locators(page: Any):
"""在所有 frame 与顶层 page 中查找 Reports 顶栏相关 locator。"""
roots = [page, *list(getattr(page, "frames", []))]
for root in roots:
for selector in _DSV_REPORTS_NAV_SELECTORS:
try:
locator = root.locator(selector).first
if locator.count() > 0:
yield root, selector, locator
except Exception:
continue
def _has_dsv_report_nav_attached(page: Any) -> bool:
"""Reports 顶栏 DOM 是否已挂载(跨 frame + 文本 fallback)。"""
return next(_iter_dsv_report_nav_locators(page), None) is not None
def _has_dsv_report_nav_usable(page: Any) -> bool:
"""
Reports 导航是否已可用于后续点击。
核心逻辑:用户肉眼看到首页时,顶栏 Reports 可能已 visible 但 #report-mega-legacy 计数仍为 0;
因此同时接受 attached 与短超时 visible 探测。
"""
for _, _, locator in _iter_dsv_report_nav_locators(page):
try:
if locator.is_visible(timeout=200):
return True
except Exception:
pass
return _has_dsv_report_nav_attached(page)
def _is_dsv_in_report_navigation_context(page: Any) -> bool:
"""
判断当前是否仍处于报表 iframe / SSRS 上下文,而非 portal 首页。
核心逻辑:报表 frame URL 与 portal 首页一样会渲染 Home/Favorites 侧栏与 Reports 顶栏;
仅探测 Reports 导航不足以区分,必须结合顶层 URL 与 report-frame 是否仍挂载。
"""
try:
current_url = str(page.url or "").lower()
except Exception:
current_url = ""
if "/main/portal/frame/reports/" in current_url:
return True
if "/s360reports/" in current_url:
return True
for frame in getattr(page, "frames", []):
try:
frame_url = str(frame.url or "").lower()
except Exception:
frame_url = ""
if "/s360reports/reports/default.aspx" in frame_url:
return True
if "/s360reports/ssrs/" in frame_url:
return True
try:
if frame.locator("#ReportViewerMain").count() > 0:
return True
except Exception:
continue
return False
def _is_dsv_on_portal_home(page: Any) -> bool:
"""URL 已在 portal 且主页面已出现 Home/Favorites/Recent Reports 等内容。"""
try:
current_url = str(page.url or "").lower()
except Exception:
current_url = ""
if "auth.dbschenker.com" in current_url:
return False
if "s360.dbschenker.com" not in current_url:
return False
if _is_dsv_in_report_navigation_context(page):
return False
try:
body = str(page.locator("body").inner_text(timeout=1_000) or "").lower()
except Exception:
body = ""
return any(marker in body for marker in ("home favorites", "recent reports", "favorites"))
def _dsv_sso_return_timeout_ms() -> int:
"""读取登录提交后 SSO 回跳的独立上限,避免混入首页菜单等待。"""
return max(30_000, int(
_env("SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS", "90000") or "90000"
))
def _dsv_sso_reload_after_ms() -> int:
"""读取空白授权中转页的一次性刷新阈值,默认等待 12 秒。"""
return max(5_000, int(
_env("SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS", "12000") or "12000"
))
def _wait_for_dsv_app_after_login(
page: Any,
timeout_ms: int | None = None,
on_portal_shell_seen: Callable[[], None] | None = None,
) -> bool:
"""
等待 DSV 从登录链路切回 portal 壳层。
核心逻辑:`Verifying compliance` 这类认证过渡页并不代表首页导航已经可操作;
这里单独识别 auth/合规过渡态,避免在该阶段反复用长超时探测 `#report-mega-legacy`,
从而把“认证收尾慢”和“Reports 菜单慢”混在一起。
"""
import dsv_auth
requested_wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
sso_wait_ms = _dsv_sso_return_timeout_ms()
# SSO 回跳和 Portal 菜单加载各有独立时间预算,不能互相吞掉。
wait_ms = sso_wait_ms + requested_wait_ms
deadline = time.monotonic() + (wait_ms / 1000)
last_debug_at = 0.0
started_at = time.monotonic()
# #region debug-point J:wait-app-entry
_report_debug_event(
"J",
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:entry",
"[DEBUG] waiting for dsv app shell after login",
{"timeoutMs": wait_ms, "url": page.url},
)
# #endregion
_debug_dsv_stage(page, "wait-app-start", target_text="Reports")
last_portal_home_log_at = 0.0
portal_shell_callback_fired = False
sso_started_at: float | None = None
sso_reload_attempted = False
last_sso_log_at = 0.0
while time.monotonic() < deadline:
now = time.monotonic()
current_url = str(page.url or "").lower()
auth_transition = False
try:
current_title = str(page.title() or "").lower()
except Exception:
current_title = ""
auth_transition = "auth.dbschenker.com" in current_url or "verifying compliance" in current_title
if now - last_debug_at >= 3:
elapsed = int((time.monotonic() - started_at) * 1000)
_debug_dsv_stage(page, f"wait-app-{elapsed // 1000}s", target_text="Reports")
last_debug_at = now
if _has_dsv_report_nav_usable(page):
if on_portal_shell_seen is not None:
on_portal_shell_seen()
_debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports")
_report_debug_event(
"J",
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:success",
"[DEBUG] dsv reports nav usable after login",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
)
return True
if auth_transition:
if sso_started_at is None:
sso_started_at = now
print(f"[dsv-sso] authorization return started url={page.url!r}")
sso_elapsed_ms = int((now - sso_started_at) * 1000)
if now - last_sso_log_at >= 10.0:
print(
"[dsv-sso] waiting authorization return "
f"elapsedMs={sso_elapsed_ms} reloaded={sso_reload_attempted} url={page.url!r}"
)
last_sso_log_at = now
is_blank_transition = dsv_auth.is_dsv_blank_auth_transition(page)
if (
is_blank_transition
and not sso_reload_attempted
and sso_elapsed_ms >= _dsv_sso_reload_after_ms()
):
sso_reload_attempted = True
print("[dsv-sso] blank authorization transition persisted; reload once")
try:
page.reload(wait_until="commit", timeout=15_000)
except Exception as exc:
print(f"[dsv-sso] authorization refresh failed: {exc}", file=sys.stderr)
continue
if sso_elapsed_ms >= sso_wait_ms:
raise RuntimeError(
"DSV SSO authorization return timed out "
f"after {sso_elapsed_ms}ms; portal did not return after login"
)
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=250):
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
continue
time.sleep(0.25)
continue
if not auth_transition and _wait_for_visible_selector(
page,
"",
_DSV_REPORTS_NAV_SELECTORS,
timeout_ms=400,
) is not None:
if on_portal_shell_seen is not None:
on_portal_shell_seen()
_debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports")
_report_debug_event(
"J",
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:success",
"[DEBUG] dsv reports nav visible after login",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
)
return True
# Portal 壳层已出现后,只轮询 Reports 定位器,不再反复读取整页和 iframe 文本。
on_portal_home = portal_shell_callback_fired or _is_dsv_on_portal_home(page)
if on_portal_home and not auth_transition:
if on_portal_shell_seen is not None and not portal_shell_callback_fired:
on_portal_shell_seen()
portal_shell_callback_fired = True
if sso_started_at is not None:
print(
"[dsv-sso] authorization return completed "
f"elapsedMs={int((now - sso_started_at) * 1000)}"
)
print("[dsv-portal] portal shell visible; waiting Reports navigation")
if now - last_portal_home_log_at >= 2.0:
print(
"[dsv-home] portal home visible, waiting Reports nav "
f"elapsedMs={int((time.monotonic() - started_at) * 1000)} "
f"report_nav_attached={_has_dsv_report_nav_attached(page)} url={page.url!r}"
)
last_portal_home_log_at = now
elif _has_dsv_portal_shell(page) and on_portal_shell_seen is not None and not portal_shell_callback_fired:
on_portal_shell_seen()
portal_shell_callback_fired = True
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
if not _has_dsv_report_nav_usable(page) and dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=250):
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
continue
try:
page.wait_for_load_state("domcontentloaded", timeout=1_500)
except Exception:
pass
time.sleep(0.5)
_debug_dsv_stage(page, "wait-app-timeout", target_text="Reports")
# #region debug-point J:wait-app-timeout
_report_debug_event(
"J",
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:timeout",
"[DEBUG] dsv app shell wait timed out",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
)
# #endregion
return False
def _has_dsv_portal_shell(page: Any) -> bool:
"""
判断 DSV portal 内容壳层是否已出现。
核心逻辑:dashboard iframe 的欢迎语/Recent Reports 往往先于顶栏 `#report-mega-legacy`
渲染完成;此函数用于记录 portal_shell_seen 时间点,但不应单独作为 home-ready 判据。
"""
if _has_dsv_report_nav_attached(page):
return True
portal_markers = ("home favorites", "recent reports", "360 — your contract logistics portal")
roots = [page, *getattr(page, "frames", [])]
for root in roots:
try:
body = str(root.locator("body").inner_text(timeout=1_000) or "").lower()
except Exception:
body = ""
if any(marker in body for marker in portal_markers):
return True
return False
def _is_dsv_home_ready(page: Any) -> bool:
"""
判断 DSV 是否已经稳定进入首页导航态。
核心逻辑:必须离开认证域名与报表 iframe 上下文,且 Reports 导航已可用;
停留在 `/main/portal/frame/reports/` 时即使顶栏可见,也不应视为 home-ready。
"""
if "auth.dbschenker.com" in page.url:
return False
if _is_dsv_in_report_navigation_context(page):
return False
return _has_dsv_report_nav_usable(page)
def _wait_for_dsv_home_ready(
page: Any,
*,
timeout_ms: int | None = None,
on_portal_shell_seen: Callable[[], None] | None = None,
) -> None:
"""
等待 DSV 首页真正稳定可操作。
核心逻辑:登录和升级提示都可能导致页面短暂回跳;这里统一要求首页导航稳定出现。
app wait 超时但 portal 壳层已可见时,追加 grace wait;仍失败则在首页阶段报错。
"""
import dsv_auth
wait_ms = timeout_ms if timeout_ms is not None else 60_000
started_at = time.monotonic()
# #region debug-point K:home-wait-entry
_report_debug_event(
"K",
"freight_rpa_worker.py:_wait_for_dsv_home_ready:entry",
"[DEBUG] entering dsv home ready wait",
{"timeoutMs": wait_ms, "url": page.url, **_collect_dsv_reports_probe(page)},
)
# #endregion
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
if _is_dsv_home_ready(page):
if on_portal_shell_seen is not None:
on_portal_shell_seen()
_debug_dsv_stage(page, "home-ready", target_text="Reports")
# #region debug-point A:home-ready
_report_debug_event(
"A",
"freight_rpa_worker.py:_wait_for_dsv_home_ready:ready",
"[DEBUG] dsv home considered ready before wait loop",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
)
# #endregion
return
if _wait_for_dsv_app_after_login(page, timeout_ms=wait_ms, on_portal_shell_seen=on_portal_shell_seen):
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
if _is_dsv_home_ready(page):
if on_portal_shell_seen is not None:
on_portal_shell_seen()
_debug_dsv_stage(page, "home-ready-after-wait", target_text="Reports")
# #region debug-point A:home-ready-after-wait
_report_debug_event(
"A",
"freight_rpa_worker.py:_wait_for_dsv_home_ready:ready_after_wait",
"[DEBUG] dsv home considered ready after app wait",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
)
# #endregion
return
if _wait_for_dsv_report_nav_grace(
page,
timeout_ms=30_000,
on_portal_shell_seen=on_portal_shell_seen,
):
# #region debug-point A:home-ready-after-grace
_report_debug_event(
"A",
"freight_rpa_worker.py:_wait_for_dsv_home_ready:ready_after_grace",
"[DEBUG] dsv home became ready during portal grace wait",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
)
# #endregion
return
_debug_dsv_stage(page, "home-not-ready", target_text="Reports")
# #region debug-point A:home-not-ready
_report_debug_event(
"A",
"freight_rpa_worker.py:_wait_for_dsv_home_ready:timeout",
"[DEBUG] dsv home was not ready before reports click",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)},
)
# #endregion
raise RuntimeError("DSV home page was not ready after login")
def _wait_for_dsv_report_nav_grace(
page: Any,
*,
timeout_ms: int = 30_000,
on_portal_shell_seen: Callable[[], None] | None = None,
) -> bool:
"""
Portal 首屏已出现但 Reports 导航尚未 visible 时的额外等待。
核心逻辑:SSO/合规页较慢时,portal 壳层(Home/Favorites)常先于顶栏 Reports 可点击;
在判定 home-not-ready 前给导航一次 grace 窗口,降低首条 batch 误失败概率。
Returns:
bool: grace 窗口内首页变为 ready 则 True,否则 False。
"""
import dsv_auth
if not _is_dsv_on_portal_home(page):
return False
print(
"[dsv-home] portal shell visible, grace wait for Reports nav "
f"timeoutMs={timeout_ms} report_nav_attached={_has_dsv_report_nav_attached(page)} "
f"url={page.url!r}"
)
deadline = time.monotonic() + (timeout_ms / 1000)
while time.monotonic() < deadline:
if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150):
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
if _is_dsv_home_ready(page):
if on_portal_shell_seen is not None:
on_portal_shell_seen()
_debug_dsv_stage(page, "home-ready-after-grace", target_text="Reports")
return True
time.sleep(0.5)
return False
def _goto_dsv_entry_url(page: Any, entry_url: str) -> None:
"""
打开 DSV entry_url;domcontentloaded 超时时若已跳转到 auth/portal 则继续。
核心逻辑:s360 -> auth 重定向链可能超过单次 goto 默认超时,不应因此中断 batch。
"""
try:
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
except Exception as exc:
message = str(exc).lower()
if "timeout" not in message:
raise
try:
current_url = str(page.url or "").lower()
except Exception:
current_url = ""
if any(token in current_url for token in ("auth.dbschenker.com", "s360.dbschenker.com")):
print(
"[dsv] entry goto domcontentloaded timeout, continue auth redirect "
f"url={page.url!r}"
)
return
raise
# 公开 API
DSV_REPORTS_NAV_SELECTORS = _DSV_REPORTS_NAV_SELECTORS
goto_dsv_entry_url = _goto_dsv_entry_url
has_dsv_portal_shell = _has_dsv_portal_shell
has_dsv_report_nav_attached = _has_dsv_report_nav_attached
has_dsv_report_nav_usable = _has_dsv_report_nav_usable
is_dsv_home_ready = _is_dsv_home_ready
is_dsv_in_report_navigation_context = _is_dsv_in_report_navigation_context
is_dsv_on_portal_home = _is_dsv_on_portal_home
iter_dsv_report_nav_locators = _iter_dsv_report_nav_locators
wait_for_dsv_app_after_login = _wait_for_dsv_app_after_login
wait_for_dsv_home_ready = _wait_for_dsv_home_ready
wait_for_dsv_report_nav_grace = _wait_for_dsv_report_nav_grace
# 向后兼容:登录 API 仍可从 dsv_session 引用
from dsv_auth import ( # noqa: E402
DSV_USERNAME_SELECTORS,
click_dsv_continue,
click_dsv_password_method,
dismiss_dsv_password_upgrade_prompt,
fill_dsv_password_page_fields,
fill_dsv_username,
find_dsv_password_locator,
has_dsv_human_check_prompt,
has_dsv_password_upgrade_prompt,
is_dsv_username_page,
looks_like_dsv_login_method_page,
maybe_auto_login_dsv,
submit_dsv_password_form,
wait_for_dsv_human_check_if_present,
wait_for_dsv_login_method_page,
)
@@ -1,42 +0,0 @@
"""Crane 收料报表导出适配器。"""
from __future__ import annotations
from typing import Any, Callable
from urllib.parse import urlsplit, urlunsplit
import crane_report_export
import crane_session
def _inbound_details_entry_url(login_url: str) -> str:
"""将复用的 Crane Profile 登录地址固定到收料 Inbound Details 路由。"""
parsed = urlsplit(str(login_url or '').strip())
if not parsed.scheme or not parsed.netloc:
raise RuntimeError('Crane receipt unit requires an absolute login_url')
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path or '/', parsed.query, '/inbound-details-query'))
def export_receipt_report(
page: Any, unit: dict[str, Any], *, env: Callable[[str, str], str], browser_timeout_ms: int,
select_or_fill: Callable[..., None], click_text: Callable[..., None], first_in_profile: bool,
) -> Any:
"""创建并下载唯一 Description 对应的 Crane Inbound Details 文件,禁止按最新历史文件选择。"""
report_path = dict(unit.get('report_path_json') or {})
if str(report_path.get('report_name') or '').strip() != 'Inbound Details':
raise RuntimeError('Crane receipt report must be Inbound Details')
entry_url = _inbound_details_entry_url(str(unit.get('login_url') or '').strip())
if first_in_profile:
page.goto(entry_url, wait_until='domcontentloaded', timeout=browser_timeout_ms)
crane_session.maybe_auto_login_crane(page, env=env, browser_timeout_ms=browser_timeout_ms)
crane_session.wait_for_crane_app_ready(page, entry_url, env=env, browser_timeout_ms=browser_timeout_ms)
# 旧 Crane driver 的 Scheduled Reports 匹配名来自 source;收料固定为
# Inbound Details,不能沿用库存的 OnHandDetails.xlsx 默认值。
source = {
'entry_url': entry_url,
'scheduled_report_name': 'Inbound Details',
}
return crane_report_export.export_crane_inventory_report(
page, source, trigger={'callback_id': unit.get('callback_id')}, env=env,
browser_timeout_ms=browser_timeout_ms, select_or_fill=select_or_fill, click_text=click_text,
)
-27
View File
@@ -1,27 +0,0 @@
"""DBS 收料报表导出适配器。"""
from __future__ import annotations
from typing import Any
import dsv_report_export
def export_receipt_report(page: Any, unit: dict[str, Any], *, entry_url: str, first_in_profile: bool) -> Any:
"""在既有 DBS 登录态内执行收料路径、Warehouse 与受控非日期条件。"""
source = {
'entry_url': entry_url,
'report_path_json': dict(unit.get('report_path_json') or {}),
'parameters': list(unit.get('query_parameters_json') or []),
'__download_dir': str(unit.get('__download_dir') or ''),
}
warehouse_id = str(unit.get('warehouse_id') or '').strip()
if not warehouse_id:
raise RuntimeError('DBS receipt unit requires warehouse_id')
source['parameters'].append({
'name': 'Warehouse', 'mode': 'single', 'values': [warehouse_id],
'required': True, 'select_all': False,
})
if first_in_profile:
dsv_report_export.ensure_dsv_session(page, entry_url)
return dsv_report_export.export_dsv_inventory_source(page, {'action': 'receipt_export_batch'}, source)
-228
View File
@@ -1,228 +0,0 @@
"""独立货代收料 RPA Worker:仅消费 receipt trigger,不触及库存 Worker 的目录或 callback。"""
from __future__ import annotations
import hashlib
import json
import os
import shutil
import tempfile
import time
import urllib.request
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Any
from cryptography.fernet import Fernet, InvalidToken
_RPA_DIR = Path(__file__).resolve().parent
if str(_RPA_DIR) not in __import__('sys').path:
__import__('sys').path.insert(0, str(_RPA_DIR))
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
import freight_receipt_crane_export # noqa: E402
import freight_receipt_dbs_export # noqa: E402
def _backend_dir() -> Path:
"""从脚本位置确定 backend 根目录,避免计划任务 cwd 漂移。"""
return Path(__file__).resolve().parents[2] / 'backend'
def _require_dir(variable: str) -> Path:
"""读取 receipt 专用目录;不回退至库存共享路径。"""
value = env(variable)
if not value:
raise SystemExit(f'Missing env: {variable}')
path = Path(value)
if not path.is_absolute():
path = (_backend_dir() / value).resolve()
path.mkdir(parents=True, exist_ok=True)
return path
def _post_callback(payload: dict[str, Any]) -> None:
"""向独立收料 callback 上报一个单元结果,认证密钥从进程 Secret 注入。"""
key = env('SHIPPING_NOTICE_TOOL_API_KEY') or env('INTEGRATION_API_KEY')
if not key:
raise RuntimeError('Missing SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY')
base = env('HXOPS_API_BASE', 'http://127.0.0.1:5052').rstrip('/')
request = urllib.request.Request(
f'{base}/api/shipping-notice/rpa/receipt-batch-ready',
data=json.dumps(payload, ensure_ascii=False).encode('utf-8'), method='POST',
headers={'Content-Type': 'application/json', 'X-Integration-Key': key},
)
with urllib.request.urlopen(request, timeout=30) as response:
if response.status < 200 or response.status >= 300:
raise RuntimeError(f'receipt callback failed: HTTP {response.status}')
@contextmanager
def _profile_credentials(unit: dict[str, Any]):
"""在单个 Profile 分组内临时解密凭据并清理环境,绝不输出明文。"""
envelope = unit.get('credential_envelope') or {}
username_ciphertext = str(envelope.get('username_ciphertext') or '').strip()
password_ciphertext = str(envelope.get('password_ciphertext') or '').strip()
if not username_ciphertext and not password_ciphertext:
yield
return
if not username_ciphertext or not password_ciphertext:
raise RuntimeError('RPA Profile credentials are incomplete')
key = env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY')
if not key:
raise RuntimeError('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is required')
try:
fernet = Fernet(key.encode('ascii'))
username = fernet.decrypt(username_ciphertext.encode('ascii')).decode('utf-8')
password = fernet.decrypt(password_ciphertext.encode('ascii')).decode('utf-8')
except (ValueError, InvalidToken, UnicodeDecodeError) as exc:
raise RuntimeError('RPA Profile credentials cannot be decrypted') from exc
connector = str(unit.get('connector_type') or '').lower()
names = ('SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME', 'SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD') if connector == 'dbs' else ('SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME', 'SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD')
before = {name: os.environ.get(name) for name in names}
os.environ[names[0]], os.environ[names[1]] = username, password
try:
yield
finally:
for name, old_value in before.items():
if old_value is None:
os.environ.pop(name, None)
else:
os.environ[name] = old_value
def _open_browser(download_dir: Path):
"""为一个 receipt Profile 分组创建临时浏览器上下文,组内登录一次、串行导出。"""
try:
from playwright.sync_api import sync_playwright
except ImportError as exc:
raise RuntimeError('Playwright is required for real receipt RPA') from exc
profile_root = _require_dir('SHIPPING_NOTICE_RPA_WORKER_RECEIPT_BROWSER_PROFILE_DIR')
runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root)))
playwright = sync_playwright().start()
options: dict[str, Any] = {'headless': env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false').lower() == 'true', 'accept_downloads': True, 'downloads_path': str(download_dir)}
channel = env('SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL')
if channel:
options['channel'] = channel
context = playwright.chromium.launch_persistent_context(str(runtime_profile), **options)
page = context.pages[0] if context.pages else context.new_page()
page.set_default_timeout(browser_timeout_ms())
return playwright, context, page, runtime_profile
def _save_download(download: Any, drop_dir: Path, unit: dict[str, Any]) -> Path:
"""保存本单元下载文件到 receipt drop 并计算 callback 需要的身份。"""
suffix = Path(str(download.suggested_filename or '')).suffix.lower() or '.xlsx'
if suffix != '.xlsx':
raise RuntimeError('receipt report download must be xlsx')
safe_callback = ''.join(ch for ch in str(unit['callback_id']) if ch.isalnum() or ch in {'-', '_'})
target = drop_dir / f'receipt_{safe_callback}_{datetime.utcnow():%Y%m%d%H%M%S}.xlsx'
download.save_as(str(target))
if target.stat().st_size <= 0:
raise RuntimeError('receipt report download is empty')
return target
def _validate_unit(unit: dict[str, Any]) -> None:
"""拒绝不完整或非 v1 单元,日期参数永不传入 DBS/Crane driver。"""
for key in ('callback_id', 'source_code', 'connector_type', 'rpa_profile_code', 'login_url'):
if not str(unit.get(key) or '').strip():
raise RuntimeError(f'receipt unit missing {key}')
if str(unit.get('connector_type')).lower() not in {'dbs', 'crane'}:
raise RuntimeError('unsupported receipt connector_type')
parameters = list(unit.get('query_parameters_json') or [])
if any('date' in str(row.get('name') or '').lower() for row in parameters if isinstance(row, dict)):
raise RuntimeError('receipt date filtering is forbidden')
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.RECEIPT_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
"""按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 收料单元。"""
units = body.get('units')
if body.get('schema_version') != 'shipping_receipt_rpa.v1' or body.get('action') != 'receipt_export_batch' or not isinstance(units, list) or not units:
raise RuntimeError('invalid receipt trigger contract')
grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = {}
for item in units:
if not isinstance(item, dict):
raise RuntimeError('receipt unit must be object')
_validate_unit(item)
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
for (connector, _profile, login_url), group in grouped.items():
mock = env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false').lower() == 'true'
resources = (None, None, None, None)
try:
if not mock:
resources = _open_browser(drop_dir)
playwright, context, page, profile_dir = resources
with _profile_credentials(group[0]):
for index, unit in enumerate(group):
try:
if mock:
from openpyxl import Workbook
mock_path = drop_dir / f"receipt_{unit['callback_id'].replace(':', '_')}.xlsx"
workbook = Workbook(); workbook.active.append(['Receipt RPA mock']); workbook.save(mock_path); workbook.close()
output = mock_path
else:
unit['__download_dir'] = str(drop_dir)
if connector == 'dbs':
if index:
page = context.new_page(); page.set_default_timeout(browser_timeout_ms())
download = freight_receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0)
else:
download = freight_receipt_crane_export.export_receipt_report(page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), select_or_fill=select_or_fill, click_text=click_text, first_in_profile=index == 0)
output = _save_download(download, drop_dir, unit)
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit['callback_id'], 'status': 'success', 'file_path': str(output), 'original_filename': output.name, 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()})
except Exception as exc:
_report_failure(unit, exc)
finally:
playwright, context, _page, profile_dir = resources
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
if profile_dir is not None:
shutil.rmtree(profile_dir, ignore_errors=True)
def _claim_and_process(path: Path, drop_dir: Path, processed_dir: Path, failed_dir: Path) -> None:
"""原子领取一个 receipt trigger;成功归档 processed,callback 异常归档 failed。"""
claimed_dir = path.parent / 'processing'
claimed_dir.mkdir(parents=True, exist_ok=True)
claimed = claimed_dir / path.name
try:
path.replace(claimed)
except OSError:
return
try:
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
processed_dir.mkdir(parents=True, exist_ok=True)
claimed.replace(processed_dir / claimed.name)
except Exception:
failed_dir.mkdir(parents=True, exist_ok=True)
claimed.replace(failed_dir / claimed.name)
raise
def main() -> None:
"""轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
drop_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR')
trigger_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR')
poll = max(1, int(env('SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS', '3') or '3'))
processed_dir, failed_dir = trigger_dir / 'processed', trigger_dir / 'failed'
print(f'[freight_receipt_rpa_worker] started trigger_dir={trigger_dir} drop_dir={drop_dir}')
while True:
for path in sorted(trigger_dir.glob('*.json')):
try:
_claim_and_process(path, drop_dir, processed_dir, failed_dir)
except Exception as exc:
print(f'[receipt-trigger] failed {path.name}: {exc}')
time.sleep(poll)
if __name__ == '__main__':
main()
-276
View File
@@ -1,276 +0,0 @@
"""
scripts/rpa/freight_rpa_heartbeat.py
用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
依赖:rpa_common.env、urllib、socket。
逻辑:由 freight_rpa_worker 主循环按 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;同步写入共享目录哨兵文件。
"""
from __future__ import annotations
import json
import os
import socket
import sys
import threading
import time
import urllib.error
import urllib.request
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from rpa_common import env as _env
_RUNTIME_STATUS = "idle"
_LAST_HEARTBEAT_MONO = 0.0
_DEFAULT_SENTINEL_NAME = ".hxops_rpa_shared_mount"
_HEARTBEAT_THREAD: threading.Thread | None = None
_HEARTBEAT_THREAD_LOCK = threading.Lock()
def set_worker_runtime_status(status: str) -> None:
"""更新 worker 运行态(idle / busy),供心跳上报。"""
global _RUNTIME_STATUS
normalized = str(status or "idle").strip().lower()
_RUNTIME_STATUS = normalized if normalized in {"idle", "busy"} else "idle"
def get_worker_runtime_status() -> str:
return _RUNTIME_STATUS
def _resolve_worker_environment() -> str:
raw = (
_env("SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT")
or _env("ENV_NAME")
or _env("HXOPS_ENV")
or "dev"
)
value = str(raw or "dev").strip().lower()
if value in {"development", ""}:
return "dev"
if value in {"testing"}:
return "test"
if value in {"production"}:
return "prod"
return value
def _resolve_shared_scope_id() -> str:
raw = (
_env("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID")
or _env("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID")
or ""
)
value = str(raw or "").strip()
if value:
return value
trigger = str(_env("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR") or "").replace("\\", "/").lower()
for token in ("hxops-rpa-test-data", "hxops-rpa-prod-data"):
if token in trigger:
return token
return ""
def _resolve_sentinel_name() -> str:
return str(
_env("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME")
or _env("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME")
or _DEFAULT_SENTINEL_NAME
).strip() or _DEFAULT_SENTINEL_NAME
def _resolve_worker_id(hostname: str) -> str:
explicit = str(_env("SHIPPING_NOTICE_RPA_WORKER_ID") or "").strip()
if explicit:
return explicit
pid = os.getpid()
return f"{hostname}-{pid}"
def write_shared_mount_sentinel(*, trigger_dir: str | Path, hostname: str | None = None) -> None:
"""
在 trigger 共享目录写入哨兵文件,供 Ubuntu 后端校验 CIFS 挂载与 scope 一致。
核心逻辑:不创建 trigger 根目录,仅更新已存在目录下的哨兵文件。
"""
scope_id = _resolve_shared_scope_id()
if not scope_id:
return
root = Path(trigger_dir)
if not root.is_dir():
return
host = hostname or socket.gethostname()
body = "\n".join([
f"scope_id={scope_id}",
f"updated_at={datetime.now(UTC).replace(tzinfo=None).isoformat()}",
f"host={host}",
f"worker_id={_resolve_worker_id(host)}",
])
sentinel_path = root / _resolve_sentinel_name()
sentinel_path.write_text(body + "\n", encoding="utf-8")
def build_heartbeat_payload(
*,
trigger_dir: str | Path,
drop_dir: str | Path,
status: str | None = None,
) -> dict[str, Any]:
"""
组装心跳 payload。
核心逻辑:capabilities 含 inventory_export;Worker 开启上传时附加 freight_upload;
shared_scope_id 用于跨平台路径对齐与环境隔离。
"""
hostname = socket.gethostname()
capabilities = ["inventory_export"]
upload_enabled = str(_env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in {
"1", "true", "yes", "on",
}
if upload_enabled:
capabilities.append("freight_upload")
return {
"worker_id": _resolve_worker_id(hostname),
"hostname": hostname,
"environment": _resolve_worker_environment(),
"capabilities": capabilities,
"status": status or get_worker_runtime_status(),
"trigger_dir": str(trigger_dir),
"drop_dir": str(drop_dir),
"shared_scope_id": _resolve_shared_scope_id(),
"version": str(_env("SHIPPING_NOTICE_RPA_WORKER_VERSION", "rpa-poc") or "rpa-poc"),
"timestamp": datetime.now(UTC).replace(tzinfo=None).isoformat(),
}
def post_heartbeat(payload: dict[str, Any]) -> bool:
"""
向后端上报心跳。
Returns:
bool: HTTP 2xx 时 True,否则 False(不中断 worker 主循环)。
"""
base = str(_env("HXOPS_API_BASE", "http://127.0.0.1:5052") or "http://127.0.0.1:5052").rstrip("/")
key = (
_env("SHIPPING_NOTICE_TOOL_API_KEY")
or _env("INTEGRATION_API_KEY")
or _env("HXOPS_TOOLS_API_KEY")
)
if not key:
print("[heartbeat] skipped: missing SHIPPING_NOTICE_TOOL_API_KEY", file=sys.stderr)
return False
url = f"{base}/api/shipping-notice/rpa/heartbeat"
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(
url,
data=data,
headers={
"Content-Type": "application/json",
"X-Integration-Key": key,
"X-Shipping-Tool-Key": key,
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=8) as resp:
return 200 <= int(resp.status) < 300
except urllib.error.HTTPError as exc:
body = ""
try:
body = exc.read().decode("utf-8", errors="replace")[:500]
except Exception:
body = ""
print(f"[heartbeat] HTTP {exc.code} {body}", file=sys.stderr)
return False
except Exception as exc:
print(f"[heartbeat] failed: {exc}", file=sys.stderr)
return False
def _start_heartbeat_request(payload: dict[str, Any]) -> bool:
"""
非阻塞地提交一次心跳 HTTP 请求。
核心逻辑:心跳仅用于 Worker 就绪观测,不能阻塞库存 Trigger 扫描;同一时刻最多
保留一条后台请求。若网络库在底层超时后仍未返回,后续周期跳过新请求而主循环照常继续。
Returns:
bool: 已启动新请求时为 True;已有未完成请求时为 False。
"""
global _HEARTBEAT_THREAD
with _HEARTBEAT_THREAD_LOCK:
if _HEARTBEAT_THREAD is not None and _HEARTBEAT_THREAD.is_alive():
print("[heartbeat] skipped: previous request still in progress", file=sys.stderr)
return False
thread = threading.Thread(
target=post_heartbeat,
args=(payload,),
name="shipping-rpa-heartbeat",
daemon=True,
)
_HEARTBEAT_THREAD = thread
thread.start()
return True
def maybe_send_heartbeat(
*,
trigger_dir: str | Path,
drop_dir: str | Path,
last_sent_mono: float,
force: bool = False,
) -> float:
"""
按 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS 节流发送心跳。
Returns:
float: 最近一次尝试后的 monotonic 时间戳(成功或失败均更新节流时钟)。
"""
global _LAST_HEARTBEAT_MONO
interval = max(15, int(_env("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"))
now = time.monotonic()
if not force and last_sent_mono and (now - last_sent_mono) < interval:
return last_sent_mono
write_shared_mount_sentinel(trigger_dir=trigger_dir)
payload = build_heartbeat_payload(trigger_dir=trigger_dir, drop_dir=drop_dir)
_start_heartbeat_request(payload)
_LAST_HEARTBEAT_MONO = now
return now
def start_heartbeat_loop(
*,
trigger_dir: str | Path,
drop_dir: str | Path,
interval_seconds: float,
) -> threading.Thread:
"""
启动独立守护心跳线程,使心跳节奏与业务主循环解耦。
核心逻辑:批量站点导出(浏览器登录+下载)会长时间阻塞 worker 主循环;若心跳由
主循环发送,执行期间会停发,后端按心跳 TTL 误判 Worker 离线。本线程按固定间隔
持续上报,主循环只负责业务扫描;线程内异常仅打印,绝不退出。
Args:
trigger_dir: 触发目录(哨兵写入与心跳 payload 使用)。
drop_dir: 库存落盘目录(心跳 payload 使用)。
interval_seconds: 心跳间隔;实际以环境变量最小 15s 为准。
Returns:
已启动的守护线程(daemon,随进程退出)。
"""
def _loop() -> None:
while True:
time.sleep(max(5.0, float(interval_seconds)))
try:
maybe_send_heartbeat(
trigger_dir=trigger_dir,
drop_dir=drop_dir,
last_sent_mono=0.0,
force=True,
)
except Exception:
print("[heartbeat] loop tick failed", file=sys.stderr)
thread = threading.Thread(target=_loop, name="shipping-rpa-heartbeat-loop", daemon=True)
thread.start()
return thread
File diff suppressed because it is too large. Load diff
-43
View File
@@ -1,43 +0,0 @@
<#
.SYNOPSIS
为同一 Windows 用户下的 RPA Worker 创建当前用户可解密的 Secret 文件。
.DESCRIPTION
Secret 文件使用 PowerShell SecureString/Windows DPAPI 保存,不能被其他用户直接解密。
启动脚本只在 Worker 子进程中设置 Process 级环境变量,不写入 User/Machine 环境变量。
Secret 文件应保存在仓库之外,例如 C:\HxopsRpaSecrets\test.xml。
DSV/Crane 登录地址、账号和密码不在本文件中保存;它们由 HXOPS RPA Profile
配置并随加密 credential_envelope 进入 trigger,Worker 使用 CredentialKey 解密。
#>
param(
[Parameter(Mandatory = $true)]
[ValidateSet("test", "prod")]
[string]$Environment,
[string]$OutputRoot = "C:\HxopsRpaSecrets"
)
$ErrorActionPreference = "Stop"
$secretPath = Join-Path $OutputRoot ("{0}.xml" -f $Environment)
New-Item -ItemType Directory -Force -Path $OutputRoot | Out-Null
function Read-RequiredSecret {
param([Parameter(Mandatory = $true)][string]$Prompt)
$value = Read-Host $Prompt -AsSecureString
if (-not $value -or $value.Length -eq 0) {
throw "$Prompt 不能为空"
}
return $value
}
$record = [pscustomobject]@{
ToolApiKey = Read-RequiredSecret "请输入 $Environment 环境 SHIPPING_NOTICE_TOOL_API_KEY"
CredentialKey = Read-RequiredSecret "请输入 $Environment 环境 SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"
}
$record | Export-Clixml -LiteralPath $secretPath
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
icacls $secretPath /inheritance:r /grant:r "${currentUser}:F" | Out-Null
Write-Host "Secret 文件已创建:$secretPath"
Write-Host "仅当前 Windows 用户可解密;不要复制到其他账号、提交 Git 或写入日志。"
@@ -1,181 +0,0 @@
<#
.SYNOPSIS
Register the test/prod RPA Worker scheduled tasks in FULL-BACKGROUND mode.
.DESCRIPTION
Runs the Worker as a background scheduled task with NO visible console and NO
visible Edge (the Worker launches Playwright headless via -Headless). Deliberately
ASCII-only so it parses identically under any Windows console code page.
Differences vs the standard "visible" scheduled task (README step 11 / 2.3):
- powershell.exe gets -WindowStyle Hidden -> no console window to close by accident.
- start_rpa_worker.ps1 gets -Headless -> no visible Edge / no interactive desktop.
Shape constraints (same as README 2.3):
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
- Do NOT switch to SYSTEM / AtStartup / Session 0 service: the Secret file is
per-user DPAPI (Export-Clixml in new_rpa_worker_secret.ps1) and cannot be
decrypted in a non-interactive context.
- The RPA account should be configured for auto-logon and must not be locked
/ logged-off, otherwise the AtLogOn task does not stay resident.
- Before trusting headless, run the headless smoke preflight (README 2.3.1):
set $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS="true" then run
dsv_login_smoke.py / crane_login_smoke.py.
Scope:
All actions can target one environment or both via -Scope test|prod|all (default all).
Usage (run in the RPA account's PowerShell):
.\scripts\rpa\register_rpa_background_tasks.ps1 # register test+prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test # register only test
.\scripts\rpa\register_rpa_background_tasks.ps1 -Start # start both now
.\scripts\rpa\register_rpa_background_tasks.ps1 -Start -Scope prod # start only prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Status -Scope test # only test
.\scripts\rpa\register_rpa_background_tasks.ps1 -Stop -Scope prod # stop only prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Unregister # unregister both
#>
[CmdletBinding()]
param(
[switch]$Register,
[switch]$Start,
[switch]$Stop,
[switch]$Status,
[switch]$Unregister,
[ValidateSet("test", "prod", "all")]
[string]$Scope = "all",
[string]$TestApiBase = "http://192.168.100.192:8890",
[string]$ProdApiBase = "http://192.168.100.230:8890",
[string]$TestRoot = "C:\HxopsRpaTest",
[string]$ProdRoot = "C:\HxopsRpaProd",
[string]$SecretFile = "C:\HxopsRpaSecrets"
)
$ErrorActionPreference = "Stop"
$TestTask = "HXOPS Inventory RPA Worker TEST"
$ProdTask = "HXOPS Inventory RPA Worker PROD"
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
function Get-TasksForScope {
# Return the task name(s) selected by -Scope.
param([string]$Scope)
switch ($Scope) {
"test" { return @($TestTask) }
"prod" { return @($ProdTask) }
default { return @($TestTask, $ProdTask) }
}
}
function Assert-Launcher {
# Validate the launcher and DPAPI Secret file required for one environment.
param([string]$Root, [string]$Environment)
$launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1"
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
throw "Launcher not found: $launcher"
}
$secret = Join-Path $SecretFile ("{0}.xml" -f $Environment)
if (-not (Test-Path -LiteralPath $secret -PathType Leaf)) {
throw "Secret file not found: $secret. Run new_rpa_worker_secret.ps1 first."
}
}
function New-TaskDefinition {
param(
[string]$TaskName,
[string]$Root,
[string]$ApiBase,
[string]$EnvName
)
$launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1"
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
# Key differences vs the visible scheduled task:
# -WindowStyle Hidden (no console) + -Headless (no visible browser).
$actionArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$launcher`" -Environment $EnvName -Headless -ApiBase `"$ApiBase`" -WorkerRoot `"$Root`" -SecretFile `"$secret`""
$action = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument $actionArgs `
-WorkingDirectory $Root
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $RunAsUser
$principal = New-ScheduledTaskPrincipal `
-UserId $RunAsUser `
-LogonType Interactive `
-RunLevel Limited
$settings = New-ScheduledTaskSettingsSet `
-StartWhenAvailable `
-RestartCount 10 `
-RestartInterval (New-TimeSpan -Minutes 1) `
-ExecutionTimeLimit ([TimeSpan]::Zero) `
-MultipleInstances IgnoreNew
Register-ScheduledTask `
-TaskName $TaskName `
-Action $action `
-Trigger $trigger `
-Principal $principal `
-Settings $settings `
-Description "HXOPS RPA Worker ($EnvName) background (headless + hidden console)"
}
# Default action is Register when no switch is given.
if ($Start -or $Stop -or $Status -or $Unregister -or $Register) {
# handled below
} else {
$Register = $true
}
if ($Unregister) {
foreach ($t in (Get-TasksForScope $Scope)) {
Stop-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName $t -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "Unregistered task: $t"
}
exit 0
}
if ($Start) {
foreach ($t in (Get-TasksForScope $Scope)) {
Start-ScheduledTask -TaskName $t
Write-Host "Started task: $t"
}
exit 0
}
if ($Stop) {
foreach ($t in (Get-TasksForScope $Scope)) {
Stop-ScheduledTask -TaskName $t
Write-Host "Stopped task: $t"
}
exit 0
}
if ($Status) {
foreach ($t in (Get-TasksForScope $Scope)) {
$tobj = Get-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
if ($tobj) {
$info = Get-ScheduledTaskInfo -TaskName $t
Write-Host ("{0} State={1} LastRun={2} LastResult={3}" -f $t, $info.State, $info.LastRunTime, $info.LastTaskResult)
Write-Host " (267009 / 0x41301 = running, not an error)"
} else {
Write-Host "Task not registered yet: $t"
}
}
exit 0
}
if ($Register) {
if ($Scope -eq "test" -or $Scope -eq "all") {
Assert-Launcher $TestRoot "test"
New-TaskDefinition -TaskName $TestTask -Root $TestRoot -ApiBase $TestApiBase -EnvName "test"
}
if ($Scope -eq "prod" -or $Scope -eq "all") {
Assert-Launcher $ProdRoot "prod"
New-TaskDefinition -TaskName $ProdTask -Root $ProdRoot -ApiBase $ProdApiBase -EnvName "prod"
}
Write-Host "Registered background task(s) for scope=${Scope}:"
foreach ($t in (Get-TasksForScope $Scope)) { Write-Host " $t" }
Write-Host "Tasks are AtLogOn + Interactive + headless + hidden console."
Write-Host "Use -Start to launch now. Configure auto-logon for the RPA account."
exit 0
}
-532
View File
@@ -1,532 +0,0 @@
"""
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
import warnings
from pathlib import Path
from typing import Any, TextIO
_RPA_LEGACY_TO_CANONICAL = {
"SHIPPING_RPA_CREDENTIAL_KEY": "SHIPPING_NOTICE_RPA_CREDENTIAL_KEY",
"FREIGHT_INVENTORY_DROP_DIR": "SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR",
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR": "SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR",
"FREIGHT_UPLOAD_QUEUE_DIR": "SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR",
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR": "SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR",
"FREIGHT_RPA_SHARED_SCOPE_ID": "SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID",
"FREIGHT_RPA_SHARED_SENTINEL_NAME": "SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME",
"FREIGHT_RPA_INVENTORY_ARCHIVE_DIR": "SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR",
"FREIGHT_RPA_WORKER_ID": "SHIPPING_NOTICE_RPA_WORKER_ID",
"FREIGHT_RPA_WORKER_VERSION": "SHIPPING_NOTICE_RPA_WORKER_VERSION",
}
_WARNED_LEGACY_RPA_ENV: set[str] = set()
def _canonical_rpa_env_name(name: str) -> str:
"""
将历史 RPA 环境变量名转换为 Shipping Notice 统一命名空间。
核心逻辑:共享目录和凭据密钥使用显式映射;其余 `FREIGHT_RPA_*`
均属于 Windows Worker 运行参数,统一映射到 `SHIPPING_NOTICE_RPA_WORKER_*`。
Args:
name: 调用方传入的新或旧环境变量名。
Returns:
str: 规范环境变量名;非 RPA 变量原样返回。
"""
if name in _RPA_LEGACY_TO_CANONICAL:
return _RPA_LEGACY_TO_CANONICAL[name]
if name.startswith("FREIGHT_RPA_"):
return f"SHIPPING_NOTICE_RPA_WORKER_{name.removeprefix('FREIGHT_RPA_')}"
return name
def _legacy_rpa_env_name(name: str) -> str | None:
"""
返回规范 RPA 环境变量对应的历史名称,供过渡期只读兼容。
Args:
name: 规范环境变量名。
Returns:
str | None: 历史名称;不存在历史名称时返回 None。
"""
for legacy, canonical in _RPA_LEGACY_TO_CANONICAL.items():
if canonical == name:
return legacy
if name.startswith("SHIPPING_NOTICE_RPA_WORKER_"):
return f"FREIGHT_RPA_{name.removeprefix('SHIPPING_NOTICE_RPA_WORKER_')}"
return None
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 环境变量,并兼容历史变量名与外层单双引号写法。
核心逻辑:规范名称优先;仅当新名称未设置时读取旧名称并发出弃用警告。
随后去除首尾空白与最外层成对引号,避免账号密码把引号输入登录页。
Args:
name: 新或旧环境变量名;RPA 旧名称会自动转换到统一命名空间。
default: 未设置时的默认值。
Returns:
str: 去除空白与外层成对引号后的环境变量值。
"""
canonical_name = _canonical_rpa_env_name(name)
legacy_name = _legacy_rpa_env_name(canonical_name)
raw_value = os.getenv(canonical_name)
if raw_value is None and legacy_name:
raw_value = os.getenv(legacy_name)
if raw_value is not None and legacy_name not in _WARNED_LEGACY_RPA_ENV:
warnings.warn(
f"{legacy_name} is deprecated; use {canonical_name}",
DeprecationWarning,
stacklevel=2,
)
_WARNED_LEGACY_RPA_ENV.add(legacy_name)
value = str(raw_value if raw_value is not None else 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("SHIPPING_NOTICE_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 == "SHIPPING_NOTICE_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 = 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"SHIPPING_NOTICE_RPA_WORKER_{prefix}_USERNAME"
password_env = f"SHIPPING_NOTICE_RPA_WORKER_{prefix}_PASSWORD"
if not _env(username_env) or not _env(password_env):
return
user_filled = _fill_login_field(
page,
f"SHIPPING_NOTICE_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"SHIPPING_NOTICE_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"SHIPPING_NOTICE_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
@@ -1,73 +0,0 @@
"""Run one database-generated inventory batch trigger without starting the polling worker."""
from __future__ import annotations
import importlib.util
import os
import sys
from pathlib import Path
def _repo_root() -> Path:
"""Return the HXOPS repository root for relative operational directories."""
return Path(__file__).resolve().parents[2]
def _load_dotenv_dev() -> None:
"""Load missing local runtime variables without exposing or overwriting credentials."""
env_path = _repo_root() / ".env.dev"
if not env_path.is_file():
return
for raw_line in env_path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, value = line.partition("=")
if key.strip() and key.strip() not in os.environ:
os.environ[key.strip()] = value.strip().strip('"').strip("'")
def _load_worker():
"""Load the polling worker module so manual runs share the production trigger contract."""
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_runner", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main() -> int:
"""Execute a complete, database-generated batch trigger and post its normal callback."""
if len(sys.argv) < 2:
print("usage: python scripts/rpa/run_inventory_batch_trigger.py <trigger.json>")
return 1
trigger_path = Path(sys.argv[1]).expanduser()
if not trigger_path.is_file():
trigger_path = _repo_root() / sys.argv[1]
if not trigger_path.is_file():
print(f"[batch-run] trigger not found: {sys.argv[1]}")
return 1
_load_dotenv_dev()
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "true")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "backend/data/shipping_notice/freight_rpa/browser_profile")
if not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") and not os.environ.get("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052")
if not os.environ.get("SHIPPING_NOTICE_TOOL_API_KEY"):
print("[batch-run] SHIPPING_NOTICE_TOOL_API_KEY is required")
return 1
drop_dir = Path(os.environ.get("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR") or "backend/data/shipping_notice/freight_rpa/inventory_drop")
if not drop_dir.is_absolute():
drop_dir = _repo_root() / drop_dir
processed_dir = trigger_path.parent / "processed"
processed_dir.mkdir(parents=True, exist_ok=True)
drop_dir.mkdir(parents=True, exist_ok=True)
worker = _load_worker()
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
return 0
if __name__ == "__main__":
raise SystemExit(main())
-57
View File
@@ -1,57 +0,0 @@
<#
.SYNOPSIS
在当前 PowerShell 进程树启动独立货代收料 RPA Worker。
.DESCRIPTION
只设置 Process 级环境变量和 receipt 专用目录;可与库存 Worker 并行运行,
但二者不共享 trigger、drop、browser profile 或日志目录。
#>
param(
[Parameter(Mandatory = $true)][ValidateSet('test', 'prod')][string]$Environment,
[Parameter(Mandatory = $true)][string]$ApiBase,
[Parameter(Mandatory = $true)][string]$WorkerRoot,
[Parameter(Mandatory = $true)][string]$SecretFile,
[string]$PythonExe = 'python.exe',
[switch]$Mock,
[switch]$Headless
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile" }
$workerScript = Join-Path $WorkerRoot 'scripts\rpa\freight_receipt_rpa_worker.py'
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" }
function ConvertTo-PlainText {
param([Parameter(Mandatory = $true)][System.Security.SecureString]$Value)
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Value)
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
}
$secret = Import-Clixml -LiteralPath $SecretFile
foreach ($required in @('ToolApiKey', 'CredentialKey')) {
if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" }
}
$dataRoot = Join-Path $WorkerRoot 'data\freight_receipt_rpa'
$processVars = [ordered]@{
HXOPS_API_BASE = $ApiBase
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = $Environment
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = 'msedge'
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop'
SHIPPING_NOTICE_RPA_WORKER_RECEIPT_BROWSER_PROFILE_DIR = Join-Path $dataRoot 'browser_profile'
}
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
try {
Write-Host "Starting receipt RPA Worker: environment=$Environment root=$WorkerRoot"
& $PythonExe $workerScript
exit $LASTEXITCODE
}
finally {
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, $null, 'Process') }
}
-102
View File
@@ -1,102 +0,0 @@
<#
.SYNOPSIS
在当前 PowerShell 进程树中启动指定环境的 RPA Worker。
.DESCRIPTION
该脚本只写入 Process 级环境变量,绝不调用 User/Machine 环境变量 API。
test/prod 可由同一 Windows 用户、同一交互式桌面、两个独立计划任务同时运行。
每个环境必须有独立 root、scope、共享目录、browser profile、日志和 DPAPI Secret 文件。
DSV/Crane 登录地址、账号和密码来自 HXOPS trigger 的 credential_envelope,
不从本机 Secret 文件读取。
#>
param(
[Parameter(Mandatory = $true)]
[ValidateSet("test", "prod")]
[string]$Environment,
[Parameter(Mandatory = $true)]
[string]$ApiBase,
[Parameter(Mandatory = $true)]
[string]$WorkerRoot,
[Parameter(Mandatory = $true)]
[string]$SecretFile,
[string]$PythonExe = "python.exe",
[switch]$Mock,
[switch]$Headless,
[switch]$ReuseDsvSession
)
$ErrorActionPreference = "Stop"
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) {
throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。"
}
$workerScript = Join-Path $WorkerRoot "scripts\rpa\freight_rpa_worker.py"
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) {
throw "Worker 不存在:$workerScript"
}
if ($Environment -eq "test") {
$scopeId = "hxops-rpa-test-data"
} else {
$scopeId = "hxops-rpa-prod-data"
}
$dataRoot = Join-Path $WorkerRoot "data"
function ConvertTo-PlainText {
param([Parameter(Mandatory = $true)][System.Security.SecureString]$Value)
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Value)
try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }
}
$secret = Import-Clixml -LiteralPath $SecretFile
foreach ($required in @("ToolApiKey", "CredentialKey")) {
if (-not ($secret.PSObject.Properties.Name -contains $required)) {
throw "Secret 文件缺少字段:$required"
}
}
# 只设置当前 launcher 及其 Worker 子进程可见的环境变量;不写 User/Machine 持久配置。
$processVars = [ordered]@{
HXOPS_API_BASE = $ApiBase
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = $Environment
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = $scopeId
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20"
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" })
# 仅显式启用时让 DSV 库存任务复用专属 profile;默认继续使用一次性会话。
SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE = $(if ($ReuseDsvSession) { "true" } else { "false" })
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge"
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $dataRoot "inventory_triggers"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $dataRoot "inventory_drop"
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $dataRoot "upload_triggers"
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $dataRoot "upload_queue"
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $dataRoot "browser_profile"
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot "logs\worker.log"
SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760"
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5"
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED = "false"
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT = "false"
}
foreach ($entry in $processVars.GetEnumerator()) {
[Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, "Process")
}
Write-Host "Starting RPA Worker: environment=$Environment scope=$scopeId root=$WorkerRoot"
try {
& $PythonExe $workerScript
exit $LASTEXITCODE
}
finally {
foreach ($entry in $processVars.GetEnumerator()) {
[Environment]::SetEnvironmentVariable($entry.Key, $null, "Process")
}
}