Files
syops/scripts/rpa/dsv_report_parameters.py
T
hugo 06c18b3c7c fix(shipping-notice,admin-schedule,frontend): 修复发货通知与后台排程的业务bug并优化各模块功能
1.  后端发货通知模块:
    清空重试任务旧状态避免残留,新增RPA进度回调接口
    优化库存匹配性能,修复人工确认校验逻辑与登录弹窗遮挡问题
    新增排程worker启动脚本,清理冗余环境配置与缓存查询开销
2.  前端后台排程模块:
    新增任务key归一化工具兼容历史格式,修复参数表单隐藏问题
    添加加载错误处理,更新多语言文案替换裸JSON占位符
2026-08-26 22:05:25 +08:00

589 lines
24 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 _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,
)