Files
syops/scripts/rpa/dsv_report_parameters.py
T

477 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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 _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 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,
) -> None:
"""
按 ReportViewer 控件类型填充 DSV 报表参数。
核心逻辑:优先使用 JSON/页面默认 selector;Warehouse 走 select_option,Owner/PutawayZone 走 checkbox。
"""
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 = _DSV_REPORT_PARAM_DEFAULTS.get(label, {})
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]
if defaults.get("control") == "multi_value" or label in {"Owner", "PutawayZone"}:
if _fill_multi_value_parameter(page, label, values, timeout_ms=timeout_ms):
_debug(f"filter-filled-{label.lower()}", text)
return
select_selector = custom_selector or defaults.get("selector", "")
if defaults.get("control") == "select" or label == "Warehouse" 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
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)
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],
) -> bool:
"""
填充由 YAML `mode: multi_select` 显式声明的 SSRS checkbox 下拉参数。
【AI 触发时机】:当 DSV 报表参数不是原生 select,而是 `txtValue + divDropDown + checkbox`
组合控件时调用;例如 AWSAMS 的 Warehouse 下拉需要全选。
"""
config_override = {"control": "multi_value"}
if selectors:
for key in ("text", "toggle", "dropdown"):
value = str(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,
)