1165 lines
43 KiB
Python
1165 lines
43 KiB
Python
"""
|
||
scripts/rpa/crane_report_export.py
|
||
|
||
用途:Crane On Hand Details Query 异步报表导出(Run Report → Schedule Report → Scheduled Reports 下载)。
|
||
依赖:Playwright Page;由 freight_rpa_worker._export_crane_inventory_source 委托调用。
|
||
逻辑:必须先 Run Report 产出查询结果,再 Schedule 异步导出;轮询仅在 scheduled-reports 路由进行。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import sys
|
||
import time
|
||
import uuid
|
||
from typing import Any, Callable
|
||
from urllib.parse import urlparse
|
||
|
||
# Schedule Report Description 默认取 UUID 前 12 位十六进制(无连字符)。
|
||
# 48 bit ≈ 2.8e14 种组合,单租户 RPA 导出场景碰撞可忽略;页面示例多为 6~8 位人工填写。
|
||
_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT = 12
|
||
_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_MAX = 32
|
||
|
||
_CRANE_RUN_REPORT_SELECTORS: tuple[str, ...] = (
|
||
'button.button.is-primary.is-small:has-text("Run Report")',
|
||
'button.button.is-primary:has-text("Run Report")',
|
||
'button:has-text("Run Report")',
|
||
)
|
||
|
||
_CRANE_SCHEDULE_REPORT_SELECTORS: tuple[str, ...] = (
|
||
'button.button.is-small.ml-2:has-text("Schedule Report")',
|
||
'button:has-text("Schedule Report")',
|
||
'button:has(.material-icons):has-text("Schedule Report")',
|
||
)
|
||
|
||
_CRANE_SCHEDULED_REPORTS_LINK_SELECTORS: tuple[str, ...] = (
|
||
'a.has-link[href="#/scheduled-reports"]',
|
||
'a[href="#/scheduled-reports"]',
|
||
'a:has-text("Scheduled Reports")',
|
||
'a.navbar-item:has-text("Scheduled Reports")',
|
||
)
|
||
|
||
_CRANE_SCHEDULE_MODAL_SELECTORS: tuple[str, ...] = (
|
||
"div.modal.is-active",
|
||
"div.modal.px-4.is-active",
|
||
)
|
||
|
||
_CRANE_SCHEDULE_DESCRIPTION_SELECTORS: tuple[str, ...] = (
|
||
"div.modal-card-body input.input.is-small",
|
||
"section.modal-card-body input.input",
|
||
"div.modal.is-active input.input",
|
||
)
|
||
|
||
_CRANE_SCHEDULE_OK_SELECTORS: tuple[str, ...] = (
|
||
'div.modal-card-body button.button.is-primary:has-text("Ok")',
|
||
'div.modal.is-active button.button.is-primary:has-text("Ok")',
|
||
'section.modal-card-body button.button.is-primary:has-text("Ok")',
|
||
)
|
||
|
||
_CRANE_SCHEDULED_REPORTS_ROUTE = "scheduled-reports"
|
||
|
||
_CRANE_REPORT_SUBMISSION_STATUS_TEXTS: tuple[str, ...] = (
|
||
"Report Submitted",
|
||
"Report Creation Status",
|
||
)
|
||
|
||
_CRANE_SCHEDULED_TABLE_SELECTOR = "table.table.is-fullwidth tbody tr"
|
||
|
||
# Scheduled Reports 表列序:Name | Submitted | Description | Download(页面默认按 Submitted 降序)。
|
||
_CRANE_SCHEDULED_COL_NAME = 0
|
||
_CRANE_SCHEDULED_COL_SUBMITTED = 1
|
||
_CRANE_SCHEDULED_COL_DESCRIPTION = 2
|
||
_CRANE_SCHEDULED_COL_DOWNLOAD = 3
|
||
_CRANE_SCHEDULED_REPORT_NAME_DEFAULT = "OnHandDetails.xlsx"
|
||
_CRANE_SCHEDULED_SCAN_MAX_ROWS_DEFAULT = 20
|
||
_CRANE_SESSION_MODULE: Any | None = None
|
||
|
||
|
||
def _load_crane_session_module() -> Any:
|
||
"""运行时加载 crane_session(模块级缓存,避免轮询时重复 import)。"""
|
||
global _CRANE_SESSION_MODULE
|
||
if _CRANE_SESSION_MODULE is not None:
|
||
return _CRANE_SESSION_MODULE
|
||
|
||
import importlib.util
|
||
from pathlib import Path
|
||
|
||
module_path = Path(__file__).resolve().parent / "crane_session.py"
|
||
spec = importlib.util.spec_from_file_location("crane_session_export_runtime", module_path)
|
||
assert spec and spec.loader
|
||
module = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(module)
|
||
_CRANE_SESSION_MODULE = module
|
||
return module
|
||
|
||
|
||
def _default_crane_entry_url(source: dict[str, Any] | None) -> str:
|
||
"""从 source 读取 Crane entry_url。"""
|
||
if isinstance(source, dict):
|
||
configured = str(source.get("entry_url") or "").strip()
|
||
if configured:
|
||
return configured
|
||
return "https://wms-portal.craneww.com/#/on-hand-details-query"
|
||
|
||
|
||
def _is_crane_login_page(page: Any) -> bool:
|
||
"""当前是否显示 Crane 登录表单(含 hash=scheduled-reports 但 session 已过期的场景)。"""
|
||
return bool(_load_crane_session_module().is_crane_login_page(page))
|
||
|
||
|
||
def _scheduled_reports_table_visible(page: Any) -> bool:
|
||
"""
|
||
Scheduled Reports 表格是否已渲染(不依赖 session 路由判定)。
|
||
核心逻辑:reload 过渡态可能同时闪登录框与旧表格,以表格可见为准视为仍在列表页。
|
||
"""
|
||
table_selector = _CRANE_SCHEDULED_TABLE_SELECTOR
|
||
for root in (page, *list(getattr(page, "frames", []))):
|
||
try:
|
||
rows = root.locator(table_selector)
|
||
if rows.count() > 0:
|
||
return True
|
||
except Exception:
|
||
continue
|
||
return False
|
||
|
||
|
||
def _is_crane_login_blocking(page: Any) -> bool:
|
||
"""
|
||
是否处于需要重登的状态。
|
||
核心逻辑:仅当登录框可见且 Scheduled Reports 表格不可见时才视为 session 失效;
|
||
reload /bootstrap 期间登录框可能短暂出现,但表格仍在则不应触发重登。
|
||
"""
|
||
if not _is_crane_login_page(page):
|
||
return False
|
||
if _scheduled_reports_table_visible(page):
|
||
return False
|
||
return True
|
||
|
||
|
||
def _wait_for_scheduled_reports_list_ready(
|
||
page: Any,
|
||
*,
|
||
browser_timeout_ms: int,
|
||
) -> bool:
|
||
"""
|
||
reload/goto 后等待 Scheduled Reports 列表渲染完成。
|
||
核心逻辑:优先等表格出现;超时后再判断是否真正落在登录页。
|
||
"""
|
||
deadline = time.monotonic() + min(browser_timeout_ms / 1000, 15.0)
|
||
while time.monotonic() < deadline:
|
||
if _scheduled_reports_table_visible(page):
|
||
return True
|
||
if _is_crane_login_blocking(page):
|
||
return False
|
||
time.sleep(0.35)
|
||
return _scheduled_reports_table_visible(page)
|
||
|
||
|
||
def _navigate_to_scheduled_reports_route(
|
||
page: Any,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
) -> None:
|
||
"""直接打开 Scheduled Reports hash 路由(不经过 On Hand Details 首页)。"""
|
||
target = _scheduled_reports_url(page, env=env)
|
||
print(f"[crane-export] goto scheduled reports url={target!r}", file=sys.stderr)
|
||
page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||
try:
|
||
page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 8_000))
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _recover_crane_session_on_scheduled_reports(
|
||
page: Any,
|
||
entry_url: str,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
) -> None:
|
||
"""
|
||
在 Scheduled Reports 等待期间恢复登录态并回到列表页。
|
||
核心逻辑:重登后不 navigate 到 On Hand Details,直接 goto #/scheduled-reports 继续轮询。
|
||
"""
|
||
session = _load_crane_session_module()
|
||
if session.is_crane_session_active(page, entry_url) and _is_on_scheduled_reports_page(page):
|
||
return
|
||
if _is_crane_login_blocking(page):
|
||
print("[crane-export] session lost on scheduled reports; re-login and return to list", file=sys.stderr)
|
||
session.maybe_auto_login_crane(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
if not session.is_crane_session_active(page, entry_url):
|
||
raise RuntimeError("Crane session lost during scheduled report wait; re-login did not succeed")
|
||
if not _is_on_scheduled_reports_page(page):
|
||
_navigate_to_scheduled_reports_route(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
_wait_for_scheduled_reports_list_ready(page, browser_timeout_ms=browser_timeout_ms)
|
||
print("[crane-export] session restored; staying on scheduled reports", file=sys.stderr)
|
||
|
||
|
||
def _ensure_crane_session_for_export(
|
||
page: Any,
|
||
entry_url: str,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
) -> None:
|
||
"""
|
||
导出等待过程中检测并恢复 Crane 登录态。
|
||
核心逻辑:列表表格仍可见时不重登;仅 session 真正失效时重登并回到 Scheduled Reports。
|
||
"""
|
||
if _scheduled_reports_table_visible(page) and _CRANE_SCHEDULED_REPORTS_ROUTE in _current_url_fragment(page):
|
||
return
|
||
_recover_crane_session_on_scheduled_reports(
|
||
page,
|
||
entry_url,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
)
|
||
|
||
|
||
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 _click_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 _click_first_visible(
|
||
page: Any,
|
||
*,
|
||
selector_env: str,
|
||
env: Callable[[str, str], str],
|
||
fallback_selectors: tuple[str, ...],
|
||
role_name: str | None = None,
|
||
browser_timeout_ms: int,
|
||
) -> bool:
|
||
"""按环境变量 selector 与 fallback 点击首个可见控件。"""
|
||
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 _click_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||
print(f"[crane-export] clicked selector={selector!r}")
|
||
return True
|
||
|
||
if role_name:
|
||
for root in (page, *list(getattr(page, "frames", []))):
|
||
try:
|
||
locator = root.get_by_role("button", name=role_name, exact=False).first
|
||
if locator.is_visible(timeout=500) and _click_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||
print(f"[crane-export] clicked role button name={role_name!r}")
|
||
return True
|
||
except Exception:
|
||
pass
|
||
try:
|
||
locator = root.get_by_role("link", name=role_name, exact=False).first
|
||
if locator.is_visible(timeout=500) and _click_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||
print(f"[crane-export] clicked role link name={role_name!r}")
|
||
return True
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
|
||
def _fill_crane_report_parameters(
|
||
page: Any,
|
||
source: dict[str, Any],
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
select_or_fill: Callable[..., None],
|
||
) -> None:
|
||
"""
|
||
按 source.parameters 填充可选报表参数(Owner/Project);Warehouse 已废弃不再填写。
|
||
"""
|
||
parameters = source.get("parameters")
|
||
if isinstance(parameters, list) and parameters:
|
||
label_map = {
|
||
"owner": "Select Owner...",
|
||
"project": "Select Project...",
|
||
}
|
||
for item in parameters:
|
||
if not isinstance(item, dict):
|
||
continue
|
||
name = str(item.get("name") or "").strip().lower()
|
||
if name == "warehouse":
|
||
print("[crane-export] skip Warehouse parameter (not required)")
|
||
continue
|
||
mode = str(item.get("mode") or "single").strip().lower()
|
||
selector_env = str(item.get("selector_env") or "").strip()
|
||
values = [str(v).strip() for v in (item.get("values") or []) if str(v).strip()]
|
||
if not values:
|
||
continue
|
||
label = label_map.get(name, str(item.get("name") or ""))
|
||
if mode == "multi_text":
|
||
joiner = str(item.get("joiner") or ",")
|
||
select_or_fill(page, selector_env, label, joiner.join(values))
|
||
continue
|
||
select_or_fill(page, selector_env, label, values[0])
|
||
return
|
||
|
||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||
if query.get("owner_code"):
|
||
select_or_fill(page, "FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code"))
|
||
if query.get("project_code"):
|
||
select_or_fill(page, "FREIGHT_RPA_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code"))
|
||
|
||
|
||
def _click_run_report(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> None:
|
||
"""点击表单底部 Run Report。"""
|
||
if _click_first_visible(
|
||
page,
|
||
selector_env="FREIGHT_RPA_CRANE_RUN_SELECTOR",
|
||
env=env,
|
||
fallback_selectors=_CRANE_RUN_REPORT_SELECTORS,
|
||
role_name="Run Report",
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
):
|
||
return
|
||
raise RuntimeError("Crane Run Report button not found")
|
||
|
||
|
||
def _click_schedule_report(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> None:
|
||
"""点击右上角 Schedule Report(含 file_download 图标)。"""
|
||
if _click_first_visible(
|
||
page,
|
||
selector_env="FREIGHT_RPA_CRANE_SCHEDULE_REPORT_SELECTOR",
|
||
env=env,
|
||
fallback_selectors=_CRANE_SCHEDULE_REPORT_SELECTORS,
|
||
role_name="Schedule Report",
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
):
|
||
return
|
||
raise RuntimeError("Crane Schedule Report button not found")
|
||
|
||
|
||
def _schedule_description_hex_len(env: Callable[[str, str], str]) -> int:
|
||
"""读取 Description 十六进制长度;默认 12,上限 32(完整 uuid4.hex)。"""
|
||
raw = str(env("FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN", "") or "").strip()
|
||
if not raw:
|
||
return _CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT
|
||
try:
|
||
length = int(raw)
|
||
except ValueError:
|
||
return _CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT
|
||
return max(8, min(length, _CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_MAX))
|
||
|
||
|
||
def _build_schedule_description(
|
||
source: dict[str, Any],
|
||
trigger: dict[str, Any] | None,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
) -> str:
|
||
"""
|
||
生成 Schedule Report 弹窗 Description,用于 Scheduled Reports 列表唯一识别。
|
||
核心逻辑:默认取 UUID4 前 12 位 hex(无连字符);可用 FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION 覆盖。
|
||
"""
|
||
override = str(env("FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION", "") or "").strip()
|
||
if override:
|
||
return override[:120]
|
||
|
||
hex_len = _schedule_description_hex_len(env)
|
||
return uuid.uuid4().hex[:hex_len]
|
||
|
||
|
||
def _wait_for_schedule_modal(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> Any | None:
|
||
"""等待 Schedule Report 弹窗出现。"""
|
||
selectors = tuple(
|
||
item for item in (env("FREIGHT_RPA_CRANE_SCHEDULE_MODAL_SELECTOR"), *_CRANE_SCHEDULE_MODAL_SELECTORS) if item
|
||
)
|
||
deadline = time.monotonic() + (min(browser_timeout_ms, 15_000) / 1000)
|
||
while time.monotonic() < deadline:
|
||
for selector in selectors:
|
||
locator = _visible_locator(page, selector)
|
||
if locator is not None:
|
||
return locator
|
||
time.sleep(0.25)
|
||
return None
|
||
|
||
|
||
def _fill_schedule_description(
|
||
page: Any,
|
||
description: str,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
) -> bool:
|
||
"""在 Schedule Report 弹窗填写 Description。"""
|
||
text = str(description or "").strip()
|
||
if not text:
|
||
return False
|
||
|
||
selectors = tuple(
|
||
item for item in (env("FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_SELECTOR"), *_CRANE_SCHEDULE_DESCRIPTION_SELECTORS)
|
||
if item
|
||
)
|
||
for selector in selectors:
|
||
locator = _visible_locator(page, selector)
|
||
if locator is not None:
|
||
try:
|
||
locator.fill(text, timeout=browser_timeout_ms)
|
||
print(f"[crane-export] filled schedule description via selector={selector!r}")
|
||
return True
|
||
except Exception:
|
||
pass
|
||
|
||
for root in (page, *list(getattr(page, "frames", []))):
|
||
try:
|
||
locator = root.get_by_label("Description", exact=False).first
|
||
if locator.is_visible(timeout=500):
|
||
locator.fill(text, timeout=browser_timeout_ms)
|
||
print("[crane-export] filled schedule description via label")
|
||
return True
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
|
||
def _click_schedule_modal_ok(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool:
|
||
"""点击 Schedule Report 弹窗 Ok 按钮。"""
|
||
selectors = tuple(item for item in (env("FREIGHT_RPA_CRANE_SCHEDULE_OK_SELECTOR"), *_CRANE_SCHEDULE_OK_SELECTORS) if item)
|
||
for selector in selectors:
|
||
locator = _visible_locator(page, selector)
|
||
if locator is not None and _click_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||
print(f"[crane-export] clicked schedule modal Ok selector={selector!r}")
|
||
return True
|
||
|
||
for root in (page, *list(getattr(page, "frames", []))):
|
||
try:
|
||
modal = root.locator("div.modal.is-active").first
|
||
if not modal.is_visible(timeout=500):
|
||
continue
|
||
locator = modal.get_by_role("button", name="Ok", exact=True).first
|
||
if locator.is_visible(timeout=500) and _click_locator(locator, browser_timeout_ms=browser_timeout_ms):
|
||
print("[crane-export] clicked schedule modal Ok via role")
|
||
return True
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
|
||
def _confirm_schedule_report_modal(
|
||
page: Any,
|
||
description: str,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
) -> None:
|
||
"""
|
||
处理 Schedule Report 弹窗:填写 Description → 点击 Ok。
|
||
核心逻辑:Description 非必填但用于 Scheduled Reports 列表唯一匹配下载项。
|
||
"""
|
||
modal = _wait_for_schedule_modal(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
if modal is None:
|
||
print("[crane-export] schedule modal not detected; continue without description", file=sys.stderr)
|
||
return
|
||
|
||
if not _fill_schedule_description(page, description, env=env, browser_timeout_ms=browser_timeout_ms):
|
||
print(
|
||
f"[crane-export] failed to fill schedule description={description!r}; continuing",
|
||
file=sys.stderr,
|
||
)
|
||
if not _click_schedule_modal_ok(page, env=env, browser_timeout_ms=browser_timeout_ms):
|
||
raise RuntimeError("Crane Schedule Report modal Ok button not found")
|
||
|
||
deadline = time.monotonic() + 5.0
|
||
while time.monotonic() < deadline:
|
||
if _wait_for_schedule_modal(page, env=env, browser_timeout_ms=1_000) is None:
|
||
print(f"[crane-export] schedule modal closed description={description!r}")
|
||
return
|
||
time.sleep(0.2)
|
||
|
||
|
||
def _is_report_submission_status_visible(page: Any) -> bool:
|
||
"""Ok 后底部是否仍显示 Report Creation Status / Report Submitted 提示。"""
|
||
for root in (page, *list(getattr(page, "frames", []))):
|
||
for text in _CRANE_REPORT_SUBMISSION_STATUS_TEXTS:
|
||
try:
|
||
if root.get_by_text(text, exact=False).first.is_visible(timeout=300):
|
||
return True
|
||
except Exception:
|
||
pass
|
||
return False
|
||
|
||
|
||
def _wait_for_report_submission_complete(
|
||
page: Any,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
) -> None:
|
||
"""
|
||
等待 Ok 后的 Report Submitted 等待态结束,再进入 Scheduled Reports。
|
||
核心逻辑:先等提示出现,再等提示消失(或超时后继续并打日志)。
|
||
"""
|
||
total_ms = int(env("FREIGHT_RPA_CRANE_SUBMISSION_COMPLETE_WAIT_MS", "45000") or "45000")
|
||
appear_ms = min(30_000, total_ms)
|
||
deadline = time.monotonic() + (total_ms / 1000)
|
||
appear_deadline = time.monotonic() + (appear_ms / 1000)
|
||
seen = False
|
||
|
||
while time.monotonic() < appear_deadline:
|
||
if _is_report_submission_status_visible(page):
|
||
seen = True
|
||
print("[crane-export] report submission status visible")
|
||
break
|
||
time.sleep(0.3)
|
||
|
||
if not seen:
|
||
print("[crane-export] submission status toast not detected; brief settle wait", file=sys.stderr)
|
||
time.sleep(2.0)
|
||
return
|
||
|
||
while time.monotonic() < deadline:
|
||
if not _is_report_submission_status_visible(page):
|
||
print("[crane-export] report submission status dismissed, ready for Scheduled Reports")
|
||
return
|
||
time.sleep(0.5)
|
||
|
||
print(
|
||
"[crane-export] submission status still visible after timeout; proceeding to Scheduled Reports",
|
||
file=sys.stderr,
|
||
)
|
||
|
||
|
||
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_on_scheduled_reports_page(page: Any) -> bool:
|
||
"""
|
||
判定是否已在 Scheduled Reports 列表页。
|
||
核心逻辑:hash 含 scheduled-reports;表格已渲染则视为在列表页(reload 过渡态不误判)。
|
||
"""
|
||
fragment = _current_url_fragment(page)
|
||
if not fragment or _CRANE_SCHEDULED_REPORTS_ROUTE not in fragment:
|
||
return False
|
||
if _scheduled_reports_table_visible(page):
|
||
return True
|
||
if _is_crane_login_blocking(page):
|
||
return False
|
||
return True
|
||
|
||
|
||
def _scheduled_reports_page_has_expected_table(page: Any) -> bool:
|
||
"""
|
||
Scheduled Reports 列表是否已渲染。
|
||
核心逻辑:Crane 表可能无 thead,仅检查标题或 tbody 行即可。
|
||
"""
|
||
if _CRANE_SCHEDULED_REPORTS_ROUTE not in _current_url_fragment(page):
|
||
return False
|
||
if _scheduled_reports_table_visible(page):
|
||
return True
|
||
for root in (page, *list(getattr(page, "frames", []))):
|
||
try:
|
||
if root.get_by_text("Scheduled Reports", exact=False).first.is_visible(timeout=300):
|
||
return True
|
||
except Exception:
|
||
continue
|
||
return False
|
||
|
||
|
||
def _refresh_scheduled_reports_list(
|
||
page: Any,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
entry_url: str,
|
||
) -> None:
|
||
"""
|
||
从服务端重新拉取 Scheduled Reports 列表。
|
||
核心逻辑:goto 同一路由刷新数据;reload 后等表格就绪;表格在则不重登,避免闪回登录页。
|
||
"""
|
||
fragment = _current_url_fragment(page)
|
||
on_route = _CRANE_SCHEDULED_REPORTS_ROUTE in fragment
|
||
if not on_route and not _scheduled_reports_table_visible(page):
|
||
return
|
||
if _is_crane_login_blocking(page):
|
||
_recover_crane_session_on_scheduled_reports(
|
||
page,
|
||
entry_url,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
)
|
||
return
|
||
|
||
target = _scheduled_reports_url(page, env=env)
|
||
print("[crane-export] refreshing scheduled reports list from server", file=sys.stderr)
|
||
try:
|
||
page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||
except Exception as exc:
|
||
print(f"[crane-export] scheduled reports goto refresh failed: {exc}; trying reload", file=sys.stderr)
|
||
try:
|
||
page.reload(wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||
except Exception as reload_exc:
|
||
print(f"[crane-export] scheduled reports reload failed: {reload_exc}", file=sys.stderr)
|
||
return
|
||
|
||
if not _wait_for_scheduled_reports_list_ready(page, browser_timeout_ms=browser_timeout_ms):
|
||
if _is_crane_login_blocking(page):
|
||
_recover_crane_session_on_scheduled_reports(
|
||
page,
|
||
entry_url,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
)
|
||
|
||
|
||
def _probe_scheduled_download_status(
|
||
page: Any,
|
||
description: str,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT,
|
||
) -> tuple[str | None, Any | None]:
|
||
"""
|
||
查询目标行的当前 Download 列状态,并在可下载时返回链接 locator。
|
||
核心逻辑:每轮 poll 先读状态;status=Download 时返回 locator 供点击。
|
||
"""
|
||
if not _is_on_scheduled_reports_page(page):
|
||
return None, None
|
||
|
||
text = str(description or "").strip()
|
||
report_name = str(expected_report_name or _CRANE_SCHEDULED_REPORT_NAME_DEFAULT).strip()
|
||
if not text or not report_name:
|
||
return None, None
|
||
|
||
table_selector = env("FREIGHT_RPA_CRANE_SCHEDULED_TABLE_SELECTOR") or _CRANE_SCHEDULED_TABLE_SELECTOR
|
||
max_rows = int(env("FREIGHT_RPA_CRANE_SCHEDULED_SCAN_MAX_ROWS", str(_CRANE_SCHEDULED_SCAN_MAX_ROWS_DEFAULT)) or "20")
|
||
|
||
for root in (page, *list(getattr(page, "frames", []))):
|
||
try:
|
||
rows = root.locator(table_selector)
|
||
count = rows.count()
|
||
except Exception:
|
||
continue
|
||
|
||
for index in range(min(count, max(1, max_rows))):
|
||
row = rows.nth(index)
|
||
try:
|
||
if not row.is_visible(timeout=300):
|
||
continue
|
||
except Exception:
|
||
continue
|
||
if not _row_matches_scheduled_report(row, description=text, expected_report_name=report_name):
|
||
continue
|
||
|
||
submitted_at = _read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_SUBMITTED)
|
||
status = _read_scheduled_row_status(row)
|
||
status_lower = status.lower()
|
||
if status_lower == "failed":
|
||
raise RuntimeError(f"Crane scheduled report failed for description={text!r}")
|
||
if status_lower != "download":
|
||
return status or "Submitted", None
|
||
|
||
for selector in ('a:has-text("Download")', 'td a', 'a'):
|
||
try:
|
||
locator = row.locator(selector).first
|
||
if locator.is_visible(timeout=500):
|
||
print(
|
||
f"[crane-export] row ready name={report_name!r} description={text!r} "
|
||
f"submitted={submitted_at!r} status={status!r}"
|
||
)
|
||
return status, locator
|
||
except Exception:
|
||
pass
|
||
try:
|
||
locator = row.get_by_role("link", name="Download", exact=True).first
|
||
if locator.is_visible(timeout=500):
|
||
return status, locator
|
||
except Exception:
|
||
pass
|
||
return status, None
|
||
|
||
return None, None
|
||
|
||
|
||
def _goto_scheduled_reports_hash(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> None:
|
||
"""
|
||
通过 SPA hash 路由进入 Scheduled Reports。
|
||
核心逻辑:Run Report 后仍停在 on-hand-details-query 时,点击链接可能无效,需显式改 hash。
|
||
"""
|
||
target = _scheduled_reports_url(page, env=env)
|
||
parsed = urlparse(target)
|
||
base_url = f"{parsed.scheme}://{parsed.netloc}/"
|
||
route = _CRANE_SCHEDULED_REPORTS_ROUTE
|
||
|
||
print(f"[crane-export] navigating scheduled reports hash route={route!r}")
|
||
try:
|
||
current = str(page.url or "").lower()
|
||
except Exception:
|
||
current = ""
|
||
if "craneww.com" in current and not _is_crane_login_blocking(page):
|
||
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
|
||
return
|
||
|
||
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
|
||
|
||
|
||
def _scheduled_reports_url(page: Any, *, env: Callable[[str, str], str]) -> str:
|
||
"""构造 Scheduled Reports 页面 URL(用于链接点击失败时 goto)。"""
|
||
override = str(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORTS_URL", "") or "").strip()
|
||
if override:
|
||
return override
|
||
try:
|
||
current = str(page.url or "").strip()
|
||
except Exception:
|
||
current = ""
|
||
if "://" in current:
|
||
base = current.split("#", 1)[0]
|
||
return f"{base}#/{_CRANE_SCHEDULED_REPORTS_ROUTE}"
|
||
return f"https://wms-portal.craneww.com/#/{_CRANE_SCHEDULED_REPORTS_ROUTE}"
|
||
|
||
|
||
def _open_scheduled_reports(
|
||
page: Any,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
entry_url: str = "",
|
||
) -> None:
|
||
"""
|
||
进入 Scheduled Reports 列表页。
|
||
核心逻辑:session 过期时先重登;优先点链接;未切换 hash 时用 SPA hash 赋值。
|
||
"""
|
||
entry = entry_url or _default_crane_entry_url(None)
|
||
_ensure_crane_session_for_export(page, entry, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
|
||
if _is_on_scheduled_reports_page(page) and not _is_crane_login_blocking(page):
|
||
print("[crane-export] already on scheduled-reports route")
|
||
return
|
||
|
||
if _scheduled_reports_page_has_expected_table(page):
|
||
print("[crane-export] already on scheduled reports page")
|
||
return
|
||
|
||
if _click_first_visible(
|
||
page,
|
||
selector_env="FREIGHT_RPA_CRANE_SCHEDULED_REPORTS_SELECTOR",
|
||
env=env,
|
||
fallback_selectors=_CRANE_SCHEDULED_REPORTS_LINK_SELECTORS,
|
||
role_name="Scheduled Reports",
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
):
|
||
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
|
||
deadline = time.monotonic() + 5.0
|
||
while time.monotonic() < deadline:
|
||
if _is_on_scheduled_reports_page(page):
|
||
break
|
||
time.sleep(0.25)
|
||
if _is_on_scheduled_reports_page(page):
|
||
return
|
||
|
||
target = _scheduled_reports_url(page, env=env)
|
||
print(f"[crane-export] fallback goto scheduled reports url={target!r}")
|
||
page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms)
|
||
if _is_on_scheduled_reports_page(page):
|
||
return
|
||
|
||
_goto_scheduled_reports_hash(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
if not _is_on_scheduled_reports_page(page):
|
||
raise RuntimeError(
|
||
"Crane scheduled reports navigation failed: still not on scheduled-reports route "
|
||
f"(url={page.url!r})"
|
||
)
|
||
|
||
|
||
def _read_scheduled_row_cell(row: Any, column_index: int) -> str:
|
||
"""读取 Scheduled Reports 行指定列文本(Name/Submitted/Description/Download)。"""
|
||
try:
|
||
cells = row.locator("td")
|
||
if cells.count() <= column_index:
|
||
return ""
|
||
return str(cells.nth(column_index).inner_text(timeout=300) or "").strip()
|
||
except Exception:
|
||
return ""
|
||
|
||
|
||
def _read_scheduled_row_status(row: Any) -> str:
|
||
"""读取 Scheduled Reports 行 Download 列状态文本(Submitted / Download / Failed)。"""
|
||
return _read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_DOWNLOAD)
|
||
|
||
|
||
def _resolve_scheduled_report_file_name(
|
||
source: dict[str, Any] | None,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
) -> str:
|
||
"""
|
||
解析 Scheduled Reports 目标文件名(Name 列)。
|
||
核心逻辑:source.navigation.scheduled_report_file_name → 环境变量 → 默认 OnHandDetails.xlsx。
|
||
"""
|
||
navigation = source.get("navigation") if isinstance(source, dict) and isinstance(source.get("navigation"), dict) else {}
|
||
configured = str(
|
||
navigation.get("scheduled_report_file_name") or navigation.get("scheduled_report_name") or ""
|
||
).strip()
|
||
if configured:
|
||
return configured
|
||
env_value = str(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_NAME", _CRANE_SCHEDULED_REPORT_NAME_DEFAULT) or "").strip()
|
||
return env_value or _CRANE_SCHEDULED_REPORT_NAME_DEFAULT
|
||
|
||
|
||
def _row_matches_scheduled_report(
|
||
row: Any,
|
||
*,
|
||
description: str,
|
||
expected_report_name: str,
|
||
) -> bool:
|
||
"""
|
||
判断行是否为目标导出:Name 精确匹配且 Description 为本次 UUID。
|
||
核心逻辑:表按 Submitted 降序,自上而下取首条匹配即最近一笔。
|
||
"""
|
||
wanted_name = str(expected_report_name or "").strip()
|
||
wanted_description = str(description or "").strip()
|
||
if not wanted_name or not wanted_description:
|
||
return False
|
||
|
||
name = _read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_NAME)
|
||
if name != wanted_name:
|
||
return False
|
||
|
||
row_description = _read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_DESCRIPTION)
|
||
return row_description == wanted_description
|
||
|
||
|
||
def _find_scheduled_download_by_description(
|
||
page: Any,
|
||
description: str,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT,
|
||
) -> Any | None:
|
||
"""
|
||
在 Scheduled Reports 表中定位可点击的 Download 链接。
|
||
核心逻辑:委托 _probe_scheduled_download_status,仅 status=Download 时返回 locator。
|
||
"""
|
||
_status, locator = _probe_scheduled_download_status(
|
||
page,
|
||
description,
|
||
env=env,
|
||
expected_report_name=expected_report_name,
|
||
)
|
||
return locator
|
||
|
||
|
||
def _is_scheduled_download_ready(
|
||
page: Any,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
description: str = "",
|
||
expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT,
|
||
) -> Any | None:
|
||
"""在 Scheduled Reports 列表中查找可点击的 Download;须 Name+Description 匹配且状态为 Download。"""
|
||
if not description:
|
||
return None
|
||
return _find_scheduled_download_by_description(
|
||
page,
|
||
description,
|
||
env=env,
|
||
expected_report_name=expected_report_name,
|
||
)
|
||
|
||
|
||
def _wait_and_click_scheduled_download(
|
||
page: Any,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
description: str = "",
|
||
expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT,
|
||
entry_url: str = "",
|
||
) -> Any:
|
||
"""
|
||
轮询 Scheduled Reports 直至目标行 Download 列由 Submitted 变为 Download 并点击。
|
||
核心逻辑:每 2s 读一次状态;每 10s goto 刷新列表;表格可见时不重登,避免闪回登录页。
|
||
"""
|
||
entry = entry_url or _default_crane_entry_url(None)
|
||
wait_ms = int(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_WAIT_MS", "300000") or "300000")
|
||
deadline = time.monotonic() + (wait_ms / 1000)
|
||
poll_seconds = float(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_POLL_SECONDS", "2") or "2")
|
||
list_refresh_seconds = float(
|
||
env(
|
||
"FREIGHT_RPA_CRANE_SCHEDULED_REPORT_LIST_REFRESH_SECONDS",
|
||
env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_SOFT_REFRESH_SECONDS", "10") or "10",
|
||
)
|
||
or "10"
|
||
)
|
||
wait_started = time.monotonic()
|
||
last_list_refresh = time.monotonic()
|
||
poll_index = 0
|
||
last_status = "not_found"
|
||
|
||
while time.monotonic() < deadline:
|
||
poll_index += 1
|
||
loop_started = time.monotonic()
|
||
|
||
if _is_crane_login_blocking(page) or not _is_on_scheduled_reports_page(page):
|
||
try:
|
||
_recover_crane_session_on_scheduled_reports(
|
||
page,
|
||
entry,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
)
|
||
except RuntimeError:
|
||
raise
|
||
if not _is_on_scheduled_reports_page(page):
|
||
try:
|
||
_open_scheduled_reports(
|
||
page,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
entry_url=entry,
|
||
)
|
||
except Exception as exc:
|
||
print(f"[crane-export] reopen scheduled reports failed: {exc}", file=sys.stderr)
|
||
last_list_refresh = time.monotonic()
|
||
|
||
# [STEP] 每 N 秒刷新列表拉服务端最新状态,再读 Download 列
|
||
if time.monotonic() - last_list_refresh >= list_refresh_seconds:
|
||
_refresh_scheduled_reports_list(
|
||
page,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
entry_url=entry,
|
||
)
|
||
last_list_refresh = time.monotonic()
|
||
|
||
current_status, locator = _probe_scheduled_download_status(
|
||
page,
|
||
description,
|
||
env=env,
|
||
expected_report_name=expected_report_name,
|
||
)
|
||
if current_status:
|
||
last_status = current_status
|
||
|
||
if locator is not None:
|
||
remaining_ms = max(int((deadline - time.monotonic()) * 1000), 5_000)
|
||
click_timeout = min(browser_timeout_ms, remaining_ms)
|
||
elapsed = int(time.monotonic() - wait_started)
|
||
print(
|
||
f"[crane-export] clicking download link name={expected_report_name!r} "
|
||
f"description={description!r} status={last_status!r} after~{elapsed}s polls={poll_index}",
|
||
file=sys.stderr,
|
||
)
|
||
with page.expect_download(timeout=click_timeout) as download_info:
|
||
if not _click_locator(locator, browser_timeout_ms=click_timeout):
|
||
raise RuntimeError(
|
||
f"Crane scheduled report Download link click failed for description={description!r}"
|
||
)
|
||
print(
|
||
f"[crane-export] download started name={expected_report_name!r} description={description!r}"
|
||
)
|
||
return download_info.value
|
||
|
||
loop_elapsed_ms = int((time.monotonic() - loop_started) * 1000)
|
||
remaining = int(deadline - time.monotonic())
|
||
total_elapsed = int(time.monotonic() - wait_started)
|
||
print(
|
||
f"[crane-export] poll#{poll_index} elapsed={total_elapsed}s status={last_status!r} "
|
||
f"loop={loop_elapsed_ms}ms next_sleep={max(poll_seconds, 1.0)}s remaining~{max(remaining, 0)}s",
|
||
file=sys.stderr,
|
||
)
|
||
time.sleep(max(poll_seconds, 1.0))
|
||
|
||
raise RuntimeError(
|
||
f"Crane scheduled report not ready for download within {wait_ms}ms; "
|
||
f"description={description!r}"
|
||
)
|
||
|
||
|
||
def _wait_for_run_report_results(
|
||
page: Any,
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
) -> None:
|
||
"""
|
||
等待 Run Report 内联查询完成后再 Schedule。
|
||
核心逻辑:页面出现「items found」或结果表首行数据即视为 Run 完成;超时后打日志并继续尝试 Schedule。
|
||
"""
|
||
wait_ms = int(env("FREIGHT_RPA_CRANE_RUN_REPORT_WAIT_MS", "180000") or "180000")
|
||
deadline = time.monotonic() + (wait_ms / 1000)
|
||
|
||
while time.monotonic() < deadline:
|
||
for root in (page, *list(getattr(page, "frames", []))):
|
||
try:
|
||
if root.get_by_text("items found", exact=False).first.is_visible(timeout=500):
|
||
print("[crane-export] run report finished: items found visible")
|
||
return
|
||
except Exception:
|
||
pass
|
||
try:
|
||
rows = root.locator("table.table.is-fullwidth tbody tr")
|
||
if rows.count() > 0 and rows.first.is_visible(timeout=500):
|
||
print("[crane-export] run report finished: result table has rows")
|
||
return
|
||
except Exception:
|
||
pass
|
||
time.sleep(0.5)
|
||
|
||
print(
|
||
"[crane-export] run report results not detected before timeout; proceeding to Schedule Report",
|
||
file=sys.stderr,
|
||
)
|
||
|
||
|
||
def _should_run_report_before_schedule(
|
||
source: dict[str, Any],
|
||
*,
|
||
env: Callable[[str, str], str],
|
||
) -> bool:
|
||
"""
|
||
scheduled_report 模式是否先点 Run Report。
|
||
核心逻辑:默认 True(Crane 须先 Run 才有可 Schedule 的查询结果);仅显式配置可关闭。
|
||
"""
|
||
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
|
||
if navigation.get("run_before_schedule") is False:
|
||
return False
|
||
return str(env("FREIGHT_RPA_CRANE_RUN_BEFORE_SCHEDULE", "true") or "true").lower() != "false"
|
||
|
||
|
||
def export_crane_inventory_report(
|
||
page: Any,
|
||
source: dict[str, Any],
|
||
*,
|
||
trigger: dict[str, Any] | None = None,
|
||
env: Callable[[str, str], str],
|
||
browser_timeout_ms: int,
|
||
select_or_fill: Callable[..., None],
|
||
click_text: Callable[..., None],
|
||
) -> Any:
|
||
"""
|
||
导出 Crane 库存报表。
|
||
核心逻辑:Run Report(等待结果)→ Schedule Report(填 Description)→ Scheduled Reports 按 Description 下载。
|
||
|
||
Args:
|
||
page: Playwright 页面。
|
||
source: rpa_inventory_source 配置。
|
||
env: 环境变量读取函数。
|
||
browser_timeout_ms: 浏览器操作超时。
|
||
select_or_fill: worker 提供的下拉/输入填充函数。
|
||
click_text: worker 提供的文本点击函数(file_download 直出模式备用)。
|
||
trigger: inventory_export / batch trigger,用于生成唯一 Description。
|
||
|
||
Returns:
|
||
Playwright Download 对象。
|
||
"""
|
||
download_mode = _resolve_download_mode(source)
|
||
entry_url = _default_crane_entry_url(source)
|
||
schedule_description = _build_schedule_description(source, trigger, env=env)
|
||
scheduled_report_name = _resolve_scheduled_report_file_name(source, env=env)
|
||
_fill_crane_report_parameters(
|
||
page,
|
||
source,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
select_or_fill=select_or_fill,
|
||
)
|
||
|
||
if download_mode == "file_download":
|
||
_click_run_report(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
export_selector = env("FREIGHT_RPA_CRANE_EXPORT_SELECTOR")
|
||
with page.expect_download(timeout=browser_timeout_ms) as download_info:
|
||
if export_selector:
|
||
page.locator(export_selector).first.click(timeout=browser_timeout_ms)
|
||
else:
|
||
click_text(page, env("FREIGHT_RPA_CRANE_EXPORT_TEXT", "file_download"), exact=True)
|
||
return download_info.value
|
||
|
||
# [STEP 1] Run Report:须先产出查询结果,再 Schedule 异步导出
|
||
if _should_run_report_before_schedule(source, env=env):
|
||
_click_run_report(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
_wait_for_run_report_results(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
else:
|
||
print("[crane-export] run_before_schedule disabled; scheduling without inline Run Report", file=sys.stderr)
|
||
|
||
# [STEP 2] Schedule Report → 弹窗填写 Description → Ok
|
||
_click_schedule_report(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
_confirm_schedule_report_modal(
|
||
page,
|
||
schedule_description,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
)
|
||
_wait_for_report_submission_complete(page, env=env, browser_timeout_ms=browser_timeout_ms)
|
||
|
||
# [STEP 3] Scheduled Reports → Name+Description 匹配首行,等待 Submitted→Download 并下载
|
||
_open_scheduled_reports(
|
||
page,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
entry_url=entry_url,
|
||
)
|
||
wait_ms = int(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_WAIT_MS", "300000") or "300000")
|
||
return _wait_and_click_scheduled_download(
|
||
page,
|
||
env=env,
|
||
browser_timeout_ms=browser_timeout_ms,
|
||
description=schedule_description,
|
||
expected_report_name=scheduled_report_name,
|
||
entry_url=entry_url,
|
||
)
|
||
|
||
|
||
def _resolve_download_mode(source: dict[str, Any]) -> str:
|
||
"""从 source.navigation.download_mode 读取导出模式,默认 scheduled_report。"""
|
||
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
|
||
mode = str(navigation.get("download_mode") or "scheduled_report").strip().lower()
|
||
return mode
|