Files
syops/scripts/rpa/freight_rpa_worker.py
T
hugo 9c036c825b refactor(chat/shipping): 重构发货通知模块为统一UI State驱动模式
- 重构发货通知的状态与动作获取逻辑:移除从聊天文本解析HXOPS_SHIPPING_ACTIONS注释的旧逻辑,改为统一从后端shipping_ui_state获取任务状态、动作按钮与工作流步骤
- 新增SSE实时推送shipping_ui_state事件,支持前端即时更新聊天气泡与工作台的状态与按钮
- 优化路由与登录流程:调整根路径重定向逻辑,退出登录时跳转到登录页;移除chat路由不必要的props传参;将原路由守卫中的根路径判断迁移到路由配置中
- 完善库存RPA与本地导入流程:新增本地库存文件托管接口,优化RPA回调的文件落盘与任务关联逻辑
- 新增多组单元测试覆盖焦点切换、决策处理、SSE同步等核心场景
- 修复多语言显示逻辑,使用te方法判断翻译key是否存在,避免缺失翻译时的渲染异常
- 新增reparse_inventory菜单动作,支持静默重新解析库存且不追加额外聊天消息
- 重构工作流步骤渲染函数,优先使用后端返回的步骤数据, fallback到本地推导的旧逻辑
- 清理后端旧的chat-actions API接口,将相关逻辑迁移到统一的ui_state接口中
2026-07-02 01:55:19 +08:00

2346 lines
96 KiB
Python

"""
Freight RPA worker (PoC).
Polls trigger JSON files written by hxops and reports results back via Tool API callbacks.
Set FREIGHT_RPA_MOCK=true to simulate export/upload without a real freight UI.
Usage:
python scripts/rpa/freight_rpa_worker.py
Required env (same as backend):
HXOPS_API_BASE e.g. http://127.0.0.1:5052
SHIPPING_NOTICE_TOOL_API_KEY
FREIGHT_INVENTORY_DROP_DIR
FREIGHT_RPA_INVENTORY_TRIGGER_DIR
FREIGHT_UPLOAD_QUEUE_DIR
FREIGHT_RPA_UPLOAD_TRIGGER_DIR
Optional:
FREIGHT_RPA_MOCK=true
FREIGHT_RPA_POLL_SECONDS=3
FREIGHT_RPA_SAMPLE_INVENTORY=path/to/sample.xlsx
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
FREIGHT_RPA_HEADLESS=false
FREIGHT_RPA_BROWSER_CHANNEL=msedge
FREIGHT_RPA_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD
FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD
"""
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime
from pathlib import Path
from typing import Any
try:
from openpyxl import Workbook
from openpyxl import load_workbook
except ImportError:
Workbook = None # type: ignore
load_workbook = None # type: ignore
def _env(name: str, default: str = "") -> str:
return str(os.getenv(name) or default).strip()
# #region debug-point A:report-helper
def _debug_report(hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
"""Report minimal runtime evidence to the TRAE debug server."""
debug_env = Path(__file__).resolve().parents[2] / ".dbg" / "dsv-password-login.env"
url = "http://127.0.0.1:7777/event"
session_id = "dsv-password-login"
try:
if debug_env.is_file():
content = debug_env.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
payload = {
"sessionId": session_id,
"runId": _env("FREIGHT_RPA_DEBUG_RUN_ID", "pre-fix") or "pre-fix",
"hypothesisId": hypothesis_id,
"location": location,
"msg": f"[DEBUG] {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) as resp:
resp.read()
except Exception:
pass
# #endregion
def _require_path(name: str) -> Path:
value = _env(name)
if not value:
raise SystemExit(f"Missing env: {name}")
backend_dir = Path(__file__).resolve().parents[2] / "backend"
path = Path(value)
if not path.is_absolute():
normalized = value.replace("\\", "/")
if normalized.startswith("backend/"):
path = backend_dir / normalized[len("backend/") :]
else:
path = backend_dir / value
path = path.resolve()
path.mkdir(parents=True, exist_ok=True)
return path
def _post_callback(path: str, payload: dict) -> None:
base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
key = _env("SHIPPING_NOTICE_TOOL_API_KEY") or _env("INTEGRATION_API_KEY")
if not key:
raise SystemExit("Missing SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY")
try:
key.encode("latin-1")
except UnicodeEncodeError as exc:
raise RuntimeError(
"SHIPPING_NOTICE_TOOL_API_KEY/INTEGRATION_API_KEY must be an ASCII token, "
"not a Chinese placeholder or description"
) from exc
url = f"{base}{path}"
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=30) as resp:
body = resp.read().decode("utf-8")
print(f"[callback] {path} -> {resp.status} {body[:200]}")
except urllib.error.HTTPError as exc:
err = exc.read().decode("utf-8", errors="replace")
raise RuntimeError(f"callback {path} HTTP {exc.code}: {err[:300]}") from exc
def _move_trigger(trigger_path: Path, target_dir: Path, reason: str) -> None:
target_dir.mkdir(parents=True, exist_ok=True)
done = target_dir / trigger_path.name
trigger_path.replace(done)
print(f"[trigger] {reason}: {trigger_path.name} -> {target_dir.name}")
def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exception) -> None:
print(f"[callback-error] {trigger_path.name}: {exc}", file=sys.stderr)
if trigger_path.exists():
_move_trigger(trigger_path, failed_dir, "callback failed")
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
sample = _env("FREIGHT_RPA_SAMPLE_INVENTORY")
if sample and Path(sample).is_file():
dest = drop_dir / Path(sample).name
shutil.copy2(sample, dest)
return dest
if Workbook is None:
raise RuntimeError("openpyxl required to generate mock inventory")
dest = drop_dir / f"inventory_{task_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
wb = Workbook()
ws = wb.active
ws.title = "Inventory"
ws.append(["料号", "可用数量"])
ws.append(["A001", 100])
ws.append(["A002", 50])
wb.save(dest)
return dest
def _download_name(task_no: str, source_code: str, suffix: str = ".xlsx") -> str:
safe_source = "".join(ch for ch in source_code if ch.isalnum() or ch in {"-", "_"}) or "UNKNOWN"
stamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
return f"inventory_{task_no}_{safe_source}_{stamp}{suffix}"
def _require_playwright():
try:
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from playwright.sync_api import sync_playwright
except ImportError as exc:
raise RuntimeError(
"Playwright is required for real RPA. Install it on the RPA terminal with: "
"pip install playwright && python -m playwright install chromium"
) from exc
return sync_playwright, PlaywrightTimeoutError
def _browser_timeout_ms() -> int:
return max(5_000, int(_env("FREIGHT_RPA_BROWSER_TIMEOUT_MS", "60000") or "60000"))
def _click_text(page: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> None:
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
text_literal = json.dumps(text)
for selector in (
f"a.dropdown-item:has-text({text_literal})",
f".dropdown-item:has-text({text_literal})",
f"button:has-text({text_literal})",
f'[role="button"]:has-text({text_literal})',
f"a:has-text({text_literal})",
f"li:has-text({text_literal})",
f"div.device-type:has-text({text_literal})",
):
locator = page.locator(selector).first
try:
locator.click(timeout=3_000)
return
except Exception:
pass
try:
locator.click(timeout=3_000, force=True)
return
except Exception:
pass
for role in ("button", "link"):
try:
page.get_by_role(role, name=text, exact=exact).first.click(timeout=3_000)
return
except Exception:
pass
locator = page.get_by_text(text, exact=False).first
try:
locator.click(timeout=min(timeout, 3_000))
return
except Exception:
pass
locator.click(timeout=min(timeout, 3_000), force=True)
def _click_selector_or_text(page: Any, selector_env: str, fallback_text: str | None = None) -> None:
selector = _env(selector_env)
if selector:
page.locator(selector).first.click(timeout=_browser_timeout_ms())
return
if selector_env == "FREIGHT_RPA_DSV_VIEW_REPORT_SELECTOR":
for view_selector in (
'input[type="submit"][value="View Report"]',
'button:has-text("View Report")',
'.btn:has-text("View Report")',
'input[value="View Report"]',
'[role="button"]:has-text("View Report")',
):
try:
locator = page.locator(view_selector).first
locator.wait_for(state="visible", timeout=30_000)
locator.evaluate("(node) => node.click()")
return
except Exception:
pass
if fallback_text:
_click_text(page, fallback_text, exact=True)
return
raise RuntimeError(f"Missing selector env: {selector_env}")
def _fill_selector_or_label(page: Any, selector_env: str, label: str, value: str | None) -> None:
text = str(value or "").strip()
if not text:
return
selector = _env(selector_env)
locator = page.locator(selector).first if selector else page.get_by_label(label).first
try:
current = str(locator.input_value(timeout=3_000) or "").strip()
if current == text:
return
except Exception:
pass
locator.fill(text, timeout=_browser_timeout_ms())
def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: str | None) -> None:
text = str(value or "").strip()
if not text:
return
selector = _env(selector_env)
if page.get_by_text(text, exact=False).first.is_visible(timeout=2_000):
return
if not selector and selector_env == "FREIGHT_RPA_DSV_OWNER_SELECTOR":
selector = "#ReportViewerMain_ctl08_ctl03_txtValue"
if not selector and selector_env == "FREIGHT_RPA_DSV_PUTAWAY_ZONE_SELECTOR":
selector = "#ReportViewerMain_ctl08_ctl07_txtValue"
if not selector:
print(f"[dsv] skip {label} filter; no selector configured")
return
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
for frame in page.frames:
try:
if frame.evaluate(
"""
({ selector, value }) => {
const node = document.querySelector(selector);
if (!node) return false;
node.disabled = false;
node.removeAttribute('disabled');
node.readOnly = false;
node.removeAttribute('readonly');
node.focus();
node.value = value;
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
""",
{"selector": selector, "value": text},
):
return
except Exception:
pass
time.sleep(0.5)
print(f"[dsv] skip {label} filter; selector not found: {selector}")
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 _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 _click_dsv_export_excel(page: Any) -> None:
"""
DSV report viewer exports require opening the save/export dropdown, then choosing Excel.
"""
_wait_for_dsv_report_result_ready(page)
def run_export_script(script: str) -> bool:
for frame in page.frames:
try:
if frame.evaluate(script):
return True
except Exception:
pass
return False
direct_export_script = """
() => {
if (typeof window.$find === 'function') {
const viewer = window.$find('ReportViewerMain');
if (viewer && typeof viewer.exportReport === 'function') {
viewer.exportReport('EXCELOPENXML');
return true;
}
}
const excel = document.querySelector('a[onclick*="EXCELOPENXML"]')
|| document.querySelector('a.ActiveLink[title="Excel"]')
|| document.querySelector('a[title="Excel"]');
if (!excel) return false;
excel.scrollIntoView({ block: 'center', inline: 'center' });
if (typeof excel.click === 'function') excel.click();
else {
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
excel.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
}
return true;
}
"""
if run_export_script(direct_export_script):
return
open_export_script = """
() => {
const visible = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
};
const menu = document.querySelector('#ReportViewerMain_ctl09_ctl04_ctl00_Menu');
if (menu && visible(menu)) return true;
const button = document.querySelector('#ReportViewerMain_ctl09_ctl04_ctl00')
|| document.querySelector('#ReportViewerMain_ctl09_ctl04_ctl00_Button')
|| document.querySelector('.ToolbarExport.WidgetSet')
|| Array.from(document.querySelectorAll('[title], [aria-label], a, div, span')).find((node) => {
const text = ((node.getAttribute('title') || node.getAttribute('aria-label') || node.innerText || node.textContent || '') + '').trim();
return text === 'Export' || text === 'Save';
});
if (!button) return false;
button.scrollIntoView({ block: 'center', inline: 'center' });
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
button.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
return true;
}
"""
if run_export_script(open_export_script):
deadline = time.monotonic() + 10
excel_script = """
() => {
const visible = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
};
const excel = document.querySelector('#ReportViewerMain_ctl09_ctl04_ctl00_Menu a.ActiveLink[title="Excel"]')
|| document.querySelector('#ReportViewerMain_ctl09_ctl04_ctl00_Menu a[onclick*="EXCELOPENXML"]')
|| document.querySelector('a.ActiveLink[title="Excel"][onclick*="EXCELOPENXML"]')
|| document.querySelector('a[title="Excel"]')
|| Array.from(document.querySelectorAll('a, div, span')).find((node) => {
const text = ((node.getAttribute('title') || node.getAttribute('alt') || node.innerText || node.textContent || '') + '').trim();
const onclick = ((node.getAttribute('onclick') || '') + '');
return text === 'Excel' || onclick.includes('EXCELOPENXML');
});
if (!excel || !visible(excel)) return false;
excel.scrollIntoView({ block: 'center', inline: 'center' });
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
excel.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
if (typeof excel.click === 'function') excel.click();
return true;
}
"""
while time.monotonic() < deadline:
if run_export_script(excel_script):
return
time.sleep(0.5)
legacy_selector = _env("FREIGHT_RPA_DSV_EXPORT_SELECTOR")
if legacy_selector:
page.locator(legacy_selector).first.click(timeout=_browser_timeout_ms())
elif not _click_visible_selector_or_text(
page,
"FREIGHT_RPA_DSV_EXPORT_MENU_SELECTOR",
("file_download", "Save", "Export"),
):
raise RuntimeError("DSV report export menu was not found")
if not _click_visible_selector_or_text(
page,
"FREIGHT_RPA_DSV_EXCEL_EXPORT_SELECTOR",
("Excel", "EXCELOPENXML"),
):
for excel_selector in (
'a.ActiveLink[title="Excel"]',
'a[title="Excel"]',
'a[onclick*="EXCELOPENXML"]',
):
locator = _visible_locator(page, excel_selector)
if locator is not None:
locator.click(timeout=3_000, force=True)
return
raise RuntimeError("DSV Excel export option was not found")
def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int | None = None) -> None:
"""Wait until SSRS finishes rendering the result toolbar after View Report."""
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
deadline = time.monotonic() + (timeout / 1000)
state_script = """
() => {
const visible = (node) => {
if (!node) return false;
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
};
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
const pageText = textOf(document.body);
const asyncWait = Array.from(document.querySelectorAll(
'#ReportViewerMain_AsyncWait, #ReportViewerMain_AsyncWait_Wait, [id*="AsyncWait"], [id*="Wait"]'
)).some((node) => visible(node));
const exportButton = document.querySelector('#ReportViewerMain_ctl09_ctl04_ctl00')
|| document.querySelector('#ReportViewerMain_ctl09_ctl04_ctl00_Button')
|| document.querySelector('.ToolbarExport.WidgetSet')
|| Array.from(document.querySelectorAll('[title], [aria-label], a, div, span')).find((node) => {
const label = ((node.getAttribute('title') || node.getAttribute('aria-label') || textOf(node)) + '').trim();
return label === 'Export' || label === 'Save';
});
const excelLink = document.querySelector('a[onclick*="EXCELOPENXML"]')
|| document.querySelector('a.ActiveLink[title="Excel"]')
|| document.querySelector('a[title="Excel"]');
const reportBody = document.querySelector('#ReportViewerMain_ctl10')
|| document.querySelector('[id*="ReportArea"]')
|| document.querySelector('[id*="ReportViewerMain"][id*="FixedTable"]')
|| Array.from(document.querySelectorAll('table, div, span')).find((node) => {
const text = textOf(node);
return text.includes('On Hand Inventory') || text.includes('AWS DUB') || text.includes('Owner');
});
const textReady = pageText.includes('AWS DUB On Hand Inventory by Location')
|| pageText.includes('On Hand Inventory by Location')
|| pageText.includes('Supplier ID')
|| pageText.includes('CADU-0000000100');
return {
asyncWait,
exportReady: visible(exportButton),
excelReady: visible(excelLink),
bodyReady: visible(reportBody) || textReady,
url: window.location.href,
};
}
"""
last_state: dict[str, Any] | None = None
while time.monotonic() < deadline:
for frame in page.frames:
try:
state = frame.evaluate(state_script)
except Exception:
continue
if isinstance(state, dict):
last_state = state
if not state.get("asyncWait") and (
state.get("exportReady") or state.get("excelReady")
) and state.get("bodyReady"):
return
time.sleep(0.5)
raise RuntimeError(f"DSV report result was not ready for export: {last_state}")
def _click_dsv_menu_item(page: Any, text: str) -> None:
text = str(text or "").strip()
if not text:
raise RuntimeError("DSV menu item text is empty")
text_literal = json.dumps(text)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
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"a.dropdown-item:has-text({text_literal})",
f"a:has-text({text_literal})",
):
try:
locator = page.locator(selector).first
locator.wait_for(state="visible", timeout=2_000)
locator.click(timeout=2_000, force=True)
return
except Exception:
pass
time.sleep(0.5)
raise RuntimeError(f"DSV menu item was not found: {text}")
def _click_dsv_report_group(page: Any, text: str) -> None:
text = str(text or "").strip()
if not text:
raise RuntimeError("DSV report group text is empty")
text_literal = json.dumps(text)
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
for selector in (
f"#report-mega-legacy :text-is({text_literal})",
f"#report-mega-legacy :has-text({text_literal})",
f".mega-dropdown-menu :text-is({text_literal})",
f".mega-dropdown-menu :has-text({text_literal})",
f".dropdown-menu :text-is({text_literal})",
f".dropdown-menu :has-text({text_literal})",
f"text={text}",
):
try:
locator = page.locator(selector).first
locator.wait_for(state="visible", timeout=2_000)
locator.click(timeout=3_000, force=True)
return
except Exception:
pass
try:
clicked = page.evaluate(
"""
(label) => {
const visible = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
};
const textOf = (node) => ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim();
const candidates = Array.from(document.querySelectorAll('#report-mega-legacy *, .mega-dropdown-menu *, .dropdown-menu *, li, a, div, span'))
.filter((node) => visible(node) && textOf(node).includes(label));
const target = candidates.find((node) => ['A', 'LI', 'DIV', 'SPAN'].includes(node.tagName));
if (!target) return false;
target.scrollIntoView({ block: 'center', inline: 'center' });
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
if (typeof target.click === 'function') target.click();
return true;
}
""",
text,
)
if clicked:
return
except Exception:
pass
time.sleep(0.5)
raise RuntimeError(f"DSV report group was not found: {text}")
def _ensure_dsv_reports_menu_open(page: Any) -> None:
try:
menu = page.locator("#report-mega-list-legacy").first
if menu.is_visible(timeout=1_000):
return
except Exception:
pass
_click_dsv_reports_menu(page)
def _select_dsv_inventory_report(page: Any, query: dict[str, Any]) -> None:
"""Select DSV360 Program, report group, and report with menu reopen retries."""
program_label = str(query.get("program_label") or "")
report_group = str(query.get("report_group") or "Inventory")
report_name = str(query.get("report_name") or "On Hand Inventory by Location")
program_selector = _env("FREIGHT_RPA_DSV_PROGRAM_SELECTOR")
report_group_selector = _env("FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR")
report_name_selector = _env("FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR")
last_error: Exception | None = None
for attempt in range(1, 4):
try:
print(f"[dsv] select program attempt={attempt}")
if program_selector:
page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
else:
_ensure_dsv_reports_menu_open(page)
_click_dsv_menu_item(page, program_label)
print(f"[dsv] select report group attempt={attempt}")
if report_group_selector:
page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms())
else:
_ensure_dsv_reports_menu_open(page)
_click_dsv_report_group(page, report_group)
print(f"[dsv] select report attempt={attempt}")
if report_name_selector:
page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms())
else:
if attempt == 1:
try:
_click_dsv_reports_menu(page)
time.sleep(1)
except Exception:
pass
_ensure_dsv_reports_menu_open(page)
_click_dsv_menu_item(page, report_name)
return
except Exception as exc:
last_error = exc
print(f"[dsv] select report path retry attempt={attempt} error={exc}")
try:
_click_dsv_reports_menu(page)
except Exception:
pass
time.sleep(1)
raise RuntimeError(f"DSV inventory report path was not selected: {last_error}")
def _click_dsv_view_report(page: Any) -> None:
script = """
() => {
const visible = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
};
const target = document.querySelector('#ReportViewerMain_ctl08_ctl00')
|| document.querySelector('input[name="ReportViewerMain$ctl08$ctl00"]')
|| Array.from(document.querySelectorAll('input, button, a, [role="button"]')).find((node) => {
const text = ((node.value || node.innerText || node.textContent || '') + '').replace(/\\s+/g, ' ').trim();
return text === 'View Report';
});
if (!target) return false;
if (visible(target)) target.scrollIntoView({ block: 'center', inline: 'center' });
if (typeof target.click === 'function') target.click();
else {
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
}
return true;
}
"""
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
for frame in page.frames:
try:
if frame.evaluate(script):
return
except Exception:
pass
time.sleep(0.5)
selectors = (
"#ReportViewerMain_ctl08_ctl00",
'input[name="ReportViewerMain$ctl08$ctl00"]',
'.SubmitButtonCell input[value="View Report"]',
'input[id^="ReportViewerMain_"][value="View Report"]',
'input[type="submit"][value="View Report"]',
'input[value="View Report"]',
'button:has-text("View Report")',
)
for frame in page.frames:
for selector in selectors:
try:
locator = frame.locator(selector).first
locator.wait_for(state="attached", timeout=500)
try:
locator.scroll_into_view_if_needed(timeout=500)
except Exception:
pass
try:
locator.click(timeout=1_000)
except Exception:
locator.evaluate(
"""
(target) => {
target.scrollIntoView({ block: 'center', inline: 'center' });
if (typeof target.click === 'function') target.click();
else {
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
}
}
"""
)
return
except Exception:
pass
raise RuntimeError("DSV View Report button was not found")
def _click_dsv_reports_menu(page: Any) -> None:
def reports_menu_opened() -> bool:
try:
menu = page.locator("#report-mega-list-legacy").first
if menu.is_visible(timeout=1_000):
return True
except Exception:
pass
try:
toggle = page.locator("#report-mega-legacy > a.dropdown-toggle.nav-link").first
expanded = str(toggle.get_attribute("aria-expanded", timeout=1_000) or "").lower()
return expanded == "true"
except Exception:
return False
selectors = (
"#report-mega-legacy > a.dropdown-toggle.nav-link",
"#report-mega-legacy a.dropdown-toggle",
"#report-mega-legacy a.nav-link",
'li#report-mega-legacy:has-text("Reports") > a',
'a.nav-link:has-text("Reports")',
'a:has-text("Reports")',
)
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
if reports_menu_opened():
return
try:
page.wait_for_load_state("domcontentloaded", timeout=3_000)
except Exception:
pass
for selector in selectors:
try:
locator = page.locator(selector).first
locator.wait_for(state="visible", timeout=3_000)
locator.scroll_into_view_if_needed(timeout=3_000)
try:
locator.click(timeout=3_000)
except Exception:
locator.click(timeout=3_000, force=True)
if reports_menu_opened():
return
locator.evaluate(
"""
(target) => {
target.scrollIntoView({ block: 'center', inline: 'center' });
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
}
"""
)
if reports_menu_opened():
return
except Exception:
pass
time.sleep(1)
raise RuntimeError("DSV Reports menu was not found")
def _click_dsv_password_method(page: Any) -> bool:
"""
点击 DSV 的“密码 / Password”登录方式。
核心逻辑:优先在 iframe 内定位 `.device-list` 的密码方式行,再把 deviceId 写入 `mfaForm` 提交;
若失败则回退到原有文本扫描/坐标点击方案,但每次点击后都必须验证密码输入框是否出现,避免假阳性。
"""
def password_ready() -> bool:
return (
_wait_for_visible_selector(
page,
"FREIGHT_RPA_DSV_PASSWORD_SELECTOR",
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
timeout_ms=1_000,
)
is not None
)
def debug_candidates() -> str:
candidates: list[str] = []
for idx, frame in enumerate(page.frames):
try:
frame_candidates = frame.evaluate(
"""
() => {
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '')
.replace(/\\s+/g, ' ')
.trim();
const fromDeviceList = Array.from(document.querySelectorAll('.device-list li.mb-2'))
.map((node) => textOf(node))
.filter(Boolean);
const fallback = Array.from(document.querySelectorAll('.device-type, .device-description, li, button, a, [role="button"]'))
.map((node) => textOf(node))
.filter(Boolean);
return Array.from(new Set([...fromDeviceList, ...fallback])).slice(0, 20);
}
""",
timeout=1_000,
)
except Exception:
frame_candidates = []
if frame_candidates:
candidates.append(f"frame[{idx}]={frame_candidates!r}")
return " | ".join(candidates)[:1000]
# #region debug-point B:password-method-entry
_debug_report(
"B",
"freight_rpa_worker.py:_click_dsv_password_method:entry",
"entered password method selection",
{
"url": getattr(page, "url", ""),
"frame_count": len(page.frames),
"candidates": debug_candidates(),
},
)
# #endregion
def wait_password_ready_after_click() -> bool:
for _ in range(3):
time.sleep(1)
if password_ready():
return True
return False
def validate_click_result(source: str) -> bool:
if wait_password_ready_after_click():
# #region debug-point B:password-method-switched
_debug_report(
"B",
"freight_rpa_worker.py:_click_dsv_password_method:validate_click_result",
"password method click switched to password page",
{
"source": source,
"url": getattr(page, "url", ""),
},
)
# #endregion
return True
print(f"[dsv-login] password method clicked but password field still missing source={source} candidates={debug_candidates()}")
# #region debug-point C:password-method-no-switch
_debug_report(
"C",
"freight_rpa_worker.py:_click_dsv_password_method:validate_click_result",
"password method click did not switch to password page",
{
"source": source,
"url": getattr(page, "url", ""),
"candidates": debug_candidates(),
},
)
# #endregion
return False
def is_password_option_text(text: str) -> bool:
normalized = str(text or "").replace("\n", " ").strip()
lowered = normalized.lower()
if "忘记密码" in normalized or "forgot password" in lowered or "reset password" in lowered:
return False
return "输入您的密码并登录" in normalized or "enter your password" in lowered or normalized in {"密码", "Password"}
def submit_password_method_from_dom(frame: Any) -> bool:
return bool(
frame.evaluate(
"""
() => {
const passwordIcon = document.querySelector('.device-list li.mb-2 img.device.password');
const passwordRow = passwordIcon && passwordIcon.closest('li.mb-2');
if (!passwordRow) return false;
const clickExpression = passwordRow.getAttribute('v-on:click')
|| passwordRow.getAttribute('@click')
|| passwordRow.getAttribute('onclick')
|| '';
const match = clickExpression.match(/doSelect\\(['"]([^'"]+)['"]\\)/);
const form = document.forms.mfaForm || document.querySelector('form[name="mfaForm"]');
const deviceInput = form && form.querySelector('input[name="deviceId"]');
const actionInput = form && form.querySelector('input[name="action"]');
if (!form || !deviceInput || !match) return false;
passwordRow.scrollIntoView({ block: 'center', inline: 'center' });
deviceInput.value = match[1];
if (actionInput) actionInput.value = 'START_AUTHN';
deviceInput.dispatchEvent(new Event('input', { bubbles: true }));
deviceInput.dispatchEvent(new Event('change', { bubbles: true }));
if (actionInput) actionInput.dispatchEvent(new Event('change', { bubbles: true }));
if (typeof form.requestSubmit === 'function') {
form.requestSubmit();
} else {
form.submit();
}
return true;
}
""",
timeout=1_500,
)
)
# [STEP 1] 优先读取 Vue doSelect(deviceId) 绑定,直接填 mfaForm 并提交;源码中 li 是 form 的兄弟节点,不是子节点。
for frame in page.frames:
try:
if submit_password_method_from_dom(frame) and validate_click_result("frame-dom-submit-password-method"):
return True
except Exception:
pass
# [STEP 2] 在 iframe 内直接定位密码登录方式,避免 page.mouse 跨 iframe 点击造成坐标漂移。
for frame in page.frames:
for selector in (
'.device-list li.mb-2:has(.device.password)',
'.device-list li.mb-2:has-text("密码")',
'.device-list li.mb-2:has-text("Password")',
):
try:
row = frame.locator(selector).first
row.wait_for(state="visible", timeout=1_500)
row.scroll_into_view_if_needed(timeout=1_500)
try:
row.click(timeout=1_500)
except Exception:
row.click(timeout=1_500, force=True)
if validate_click_result(f"frame-locator:{selector}"):
return True
except Exception:
pass
try:
clicked = frame.evaluate(
"""
(selector) => {
const row = document.querySelector(selector);
if (!row) return false;
row.scrollIntoView({ block: 'center', inline: 'center' });
const target = row.querySelector('.device-continue, button, a, [role="button"], input[type="submit"]') || row;
target.click();
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
return true;
}
""",
selector,
timeout=1_500,
)
if clicked and validate_click_result(f"frame-js:{selector}"):
return True
except Exception:
pass
script_row_click = """
() => {
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
const isPasswordMethod = (text) => {
const lowered = text.toLowerCase();
if (text.includes('忘记密码') || lowered.includes('forgot password') || lowered.includes('reset password')) return false;
return text === '密码' || text === 'Password' || text.includes('输入您的密码并登录') || lowered.includes('enter your password');
};
const typeNode = Array.from(document.querySelectorAll('body *')).find((node) => {
const text = textOf(node);
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0) return false;
return isPasswordMethod(text);
});
if (!typeNode) return false;
const row = typeNode.closest('.device-list li.mb-2, li.mb-2, .device-selection, [data-device-id], button, [role="button"]') || typeNode;
if (row.matches && row.matches('a, a *')) return false;
const rowText = textOf(row);
if (!isPasswordMethod(rowText)) return false;
const target = row.querySelector('.device-continue, button, [role="button"], input[type="submit"]') || row;
if (target.matches && target.matches('a, a *')) return false;
target.scrollIntoView({ block: 'center', inline: 'center' });
const rect = target.getBoundingClientRect();
const x = rect.left + Math.max(10, rect.width * 0.85);
const y = rect.top + rect.height / 2;
const atPoint = document.elementFromPoint(x, y) || target;
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
atPoint.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window, clientX: x, clientY: y }));
}
return true;
}
"""
# [STEP 3] 保留原有兜底:扫描可见文本并尝试点击,但点击后必须验证已进入密码输入页。
for frame in page.frames:
try:
row_box = frame.evaluate(
"""
() => {
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
const isPasswordMethod = (text) => {
const lowered = text.toLowerCase();
if (text.includes('忘记密码') || lowered.includes('forgot password') || lowered.includes('reset password')) return false;
return text === '密码' || text === 'Password' || text.includes('输入您的密码并登录') || lowered.includes('enter your password');
};
const node = Array.from(document.querySelectorAll('body *')).find((item) => {
const text = textOf(item);
const rect = item.getBoundingClientRect();
const style = window.getComputedStyle(item);
return style.display !== 'none'
&& style.visibility !== 'hidden'
&& rect.width > 0
&& rect.height > 0
&& isPasswordMethod(text);
});
if (!node) return null;
const row = node.closest('.device-list li.mb-2, li.mb-2, .device-selection, [data-device-id], button, [role="button"]') || node;
if (row.matches && row.matches('a, a *')) return null;
if (!isPasswordMethod(textOf(row))) return null;
row.scrollIntoView({ block: 'center', inline: 'center' });
const rect = row.getBoundingClientRect();
return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };
}
"""
)
if row_box:
page.mouse.click(row_box["x"] + row_box["width"] * 0.96, row_box["y"] + row_box["height"] / 2)
if validate_click_result("frame-bounding-box"):
return True
if frame.evaluate(script_row_click):
if validate_click_result("frame-script-row-click"):
return True
except Exception:
pass
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
try:
rows = page.locator(".device-list li.mb-2").all()
for row in rows:
text = row.inner_text(timeout=1_000)
if is_password_option_text(text):
row.scroll_into_view_if_needed(timeout=3_000)
box = row.bounding_box(timeout=3_000)
if not box:
continue
page.mouse.click(box["x"] + box["width"] * 0.85, box["y"] + box["height"] / 2)
if validate_click_result("page-mfa-row-bounding-box"):
return True
except Exception:
pass
time.sleep(0.5)
print(f"[dsv-login] password method not found or not switched candidates={debug_candidates()}")
# #region debug-point E:password-method-failed
_debug_report(
"E",
"freight_rpa_worker.py:_click_dsv_password_method:exit",
"password method not found or page did not switch",
{
"url": getattr(page, "url", ""),
"frame_count": len(page.frames),
"candidates": debug_candidates(),
},
)
# #endregion
return False
def _submit_dsv_username_form(username_locator: Any) -> bool:
try:
return bool(
username_locator.evaluate(
"""
(node) => {
const form = node.closest('form');
if (!form) return false;
if (typeof form.requestSubmit === 'function') {
form.requestSubmit();
} else {
form.submit();
}
return true;
}
""",
timeout=2_000,
)
)
except Exception:
return False
def _click_dsv_continue(page: Any, username_locator: Any | None = None) -> bool:
if username_locator is not None:
if _submit_dsv_username_form(username_locator):
return True
try:
username_locator.press("Enter", timeout=3_000)
return True
except Exception:
pass
for selector in (
'button:has-text("继续")',
'button:has-text("Continue")',
'input[value="继续"]',
'input[value="Continue"]',
'[role="button"]:has-text("继续")',
'[role="button"]:has-text("Continue")',
'a:has-text("继续")',
'a:has-text("Continue")',
'.dbs-sims-button-primary',
'button[type="submit"]',
'input[type="submit"]',
):
for frame in page.frames:
try:
locator = frame.locator(selector).first
locator.wait_for(state="attached", timeout=1_000)
try:
locator.click(timeout=1_000)
except Exception:
locator.click(timeout=1_000, force=True)
return True
except Exception:
pass
for frame in page.frames:
try:
identifier = frame.locator("input#identifier").first
identifier.wait_for(state="attached", timeout=1_000)
identifier.press("Enter", timeout=3_000)
return True
except Exception:
pass
script = """
() => {
const candidates = Array.from(document.querySelectorAll('body *')).filter((node) => {
const style = window.getComputedStyle(node);
const rect = node.getBoundingClientRect();
return style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0;
});
const label = candidates.find((node) => {
const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim();
return text === '继续' || text === 'Continue' || text.includes('继续') || text.includes('Continue');
});
const target = label && (label.closest('button, input, a, [role="button"], .dbs-sims-button-primary, [onclick], form') || label);
if (!target) return false;
target.scrollIntoView({ block: 'center', inline: 'center' });
if (target.tagName === 'FORM') {
if (typeof target.requestSubmit === 'function') target.requestSubmit();
else target.submit();
return true;
}
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
return true;
}
"""
for frame in page.frames:
try:
if frame.evaluate(script):
return True
except Exception:
pass
return False
def _dsv_locator_can_edit(locator: Any) -> bool:
try:
if locator.is_editable(timeout=1_000):
return True
except Exception:
pass
try:
return bool(
locator.evaluate(
"(node) => !node.disabled && !node.readOnly && node.getAttribute('aria-disabled') !== 'true'",
timeout=1_000,
)
)
except Exception:
return False
def _dsv_username_has_value(locator: Any) -> bool:
for _ in range(5):
try:
if locator.input_value(timeout=1_000).strip():
return True
except Exception:
pass
time.sleep(0.2)
return False
def _wait_for_dsv_app_after_login(page: Any, timeout_ms: int | None = None) -> bool:
wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline:
_dismiss_dsv_password_upgrade_prompt(page, timeout_ms=500)
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=2_000) is not None:
return True
if "s360.dbschenker.com" in page.url and "auth.dbschenker.com" not in page.url:
try:
page.wait_for_load_state("domcontentloaded", timeout=5_000)
except Exception:
pass
time.sleep(1)
return False
def _debug_dsv_login_method_page(page: Any) -> str:
snippets: list[str] = []
for idx, frame in enumerate(page.frames):
try:
body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500]
except Exception:
body = ""
try:
candidates = frame.evaluate(
"""
() => Array.from(document.querySelectorAll('.device-type, .device-description, li, button, a, [role="button"]'))
.map((node) => ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim())
.filter(Boolean)
.slice(0, 30)
""",
timeout=1_000,
)
except Exception:
candidates = []
if body or candidates:
snippets.append(f"frame[{idx}] body={body!r} candidates={candidates!r}")
return " | ".join(snippets)[:2000]
def _fill_dsv_password_page_fields(page: Any, username: str, password: str) -> bool:
filled_password = False
for frame in page.frames:
try:
inputs = frame.locator("input").all()
except Exception:
inputs = []
for input_locator in inputs:
try:
input_type = str(input_locator.get_attribute("type", timeout=500) or "").lower()
input_name = str(input_locator.get_attribute("name", timeout=500) or "").lower()
input_id = str(input_locator.get_attribute("id", timeout=500) or "").lower()
if not input_locator.is_visible(timeout=500):
continue
if input_type == "password" or "password" in input_name or "password" in input_id:
input_locator.fill(password, timeout=2_000)
filled_password = True
elif input_type in {"", "text", "email"} or "user" in input_name or "identifier" in input_name:
current = str(input_locator.input_value(timeout=500) or "").strip()
if not current:
input_locator.fill(username, timeout=2_000)
except Exception:
pass
return filled_password
def _is_dsv_username_page(page: Any) -> bool:
saw_username_page = False
for frame in page.frames:
try:
text = frame.locator("body").inner_text(timeout=500)
except Exception:
text = ""
if not text:
continue
# [STEP 1] 方法选择页与密码页会短暂保留第一步文案;只要检测到更靠后的阶段,就禁止回退邮箱重试。
if any(
needle in text
for needle in (
"选择登录方法",
"Choose a sign-on method",
"输入您的密码并登录",
"Enter your password",
"无法访问该选项",
"Access this option",
)
):
return False
if ("电子邮箱或SIMS ID或手机号" in text or "E-Mail or SIMS ID" in text) and ("继续" in text or "Continue" in text):
saw_username_page = True
return saw_username_page
def _submit_dsv_password_form(page: Any) -> bool:
script = """
() => {
const visible = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
};
const password = Array.from(document.querySelectorAll('input#userpassword, input[name="userpassword"], input[type="password"]'))
.find((node) => visible(node) && !node.disabled);
if (!password) return false;
const form = password.closest('form');
const scope = form || document;
const passwordValue = password.value || '';
const hiddenPassword = scope.querySelector('input#password[name="pf.pass"], input[name="pf.pass"], input#password');
if (hiddenPassword && hiddenPassword.value !== passwordValue) {
hiddenPassword.value = passwordValue;
hiddenPassword.dispatchEvent(new Event('input', { bubbles: true }));
hiddenPassword.dispatchEvent(new Event('change', { bubbles: true }));
}
const okInput = scope.querySelector('input[name="pf.ok"]');
if (okInput && !okInput.value) {
okInput.value = 'clicked';
okInput.dispatchEvent(new Event('change', { bubbles: true }));
}
const submit = scope.querySelector('button[name="login"], button.btn.dbs-sims-button-primary, button.dbs-sims-button-primary')
|| Array.from(scope.querySelectorAll('button, input[type="submit"], [role="button"], .btn.dbs-sims-button-primary, .dbs-sims-button-primary, .dbs-sims-button'))
.find((node) => {
const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim();
return text === '登录' || text === 'Login' || text === 'Log in' || text === 'Sign in';
}) || (form ? form.querySelector('button[name="login"], button[type="submit"], input[type="submit"], button:not([type]), .btn.dbs-sims-button-primary, .dbs-sims-button-primary') : null);
if (submit) {
submit.scrollIntoView({ block: 'center', inline: 'center' });
if (typeof submit.click === 'function') submit.click();
else {
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
submit.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
}
return true;
}
if (form && typeof form.requestSubmit === 'function') {
form.requestSubmit();
return true;
}
if (form) {
form.submit();
return true;
}
password.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
return true;
}
"""
for frame in page.frames:
try:
if frame.evaluate(script):
return True
except Exception:
pass
for selector in (
'button[name="login"]',
'button[type="button"].dbs-sims-button-primary',
'button.btn.dbs-sims-button-primary',
'button.dbs-sims-button-primary',
):
for frame in page.frames:
try:
button = frame.locator(selector).first
button.wait_for(state="visible", timeout=1_000)
button.click(timeout=2_000, force=True)
return True
except Exception:
pass
return False
def _wait_for_dsv_login_method_page(page: Any, timeout_ms: int | None = None) -> bool:
wait_ms = timeout_ms if timeout_ms is not None else max(30_000, int(_env("FREIGHT_RPA_LOGIN_READY_TIMEOUT_MS", "300000") or "300000"))
deadline = time.monotonic() + (wait_ms / 1000)
needles = ("选择登录方法", "密码", "Password", "输入您的密码并登录", "Choose a sign-on method")
while time.monotonic() < deadline:
if "s360.dbschenker.com" in page.url and "auth.dbschenker.com" not in page.url:
return True
for frame in page.frames:
try:
text = frame.locator("body").inner_text(timeout=1_000)
except Exception:
text = ""
lowered = text.lower()
if "real person" in lowered and ("rabbit" in lowered or "scale" in lowered):
_wait_for_dsv_human_check_if_present(page)
continue
if any(needle in text for needle in needles):
return True
time.sleep(0.5)
return False
def _wait_for_dsv_human_check_if_present(page: Any, timeout_ms: int | None = None) -> None:
wait_ms = timeout_ms if timeout_ms is not None else 300_000
try:
text = page.locator("body").inner_text(timeout=2_000)
except Exception:
text = ""
lowered = text.lower()
if "real person" not in lowered and "rabbit" not in lowered and "scale" not in lowered and "真人" not in text:
return
print("[dsv-login] human check detected; please click the requested object in the browser")
deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline:
try:
current = page.locator("body").inner_text(timeout=2_000)
except Exception:
current = ""
lowered_current = current.lower()
if "real person" not in lowered_current and "rabbit" not in lowered_current and "scale" not in lowered_current:
print("[dsv-login] human check passed")
return
time.sleep(2)
raise RuntimeError("DSV login human check was not completed in time")
def _dsv_login_debug_value(page: Any) -> tuple[str, dict[str, Any]]:
identifier_value = ""
button_state: dict[str, Any] = {}
for frame in page.frames:
if not identifier_value:
try:
identifier_value = frame.locator("input#identifier").first.input_value(timeout=1_000)
except Exception:
pass
if not button_state:
try:
button_state = frame.locator("button[name='login']").first.evaluate(
"(node) => ({ disabled: node.disabled, text: node.textContent, className: node.className })",
timeout=1_000,
)
except Exception:
pass
if identifier_value or button_state:
break
return identifier_value, button_state
def _fill_dsv_username(page: Any, username: str):
selectors = (
"input#identifier",
'input[name="identifier"]',
'input[placeholder="电子邮箱或SIMS ID或手机号"]',
'input[type="text"]',
)
timeout_ms = max(5_000, int(_env("FREIGHT_RPA_LOGIN_READY_TIMEOUT_MS", "300000") or "300000"))
deadline = time.monotonic() + (timeout_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="visible", timeout=1_000)
locator.wait_for(state="attached", timeout=1_000)
if not locator.is_enabled(timeout=1_000):
continue
if not _dsv_locator_can_edit(locator):
continue
locator.click(timeout=2_000)
try:
locator.fill(username, timeout=3_000)
except Exception:
locator.press("Control+A")
locator.press("Backspace")
locator.type(username, delay=30)
if _dsv_username_has_value(locator):
return locator
locator.evaluate(
"""
(node, value) => {
node.focus();
node.value = value;
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
}
""",
username,
)
if _dsv_username_has_value(locator):
return locator
except Exception:
pass
time.sleep(0.5)
return None
def _wait_for_visible_selector(
page: Any,
selector_env: str,
fallback_selectors: tuple[str, ...],
*,
timeout_ms: int | None = None,
):
selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item)
wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline:
for selector in selectors:
for frame in page.frames:
locator = frame.locator(selector).first
try:
if locator.is_visible(timeout=1_000):
return locator
except Exception:
pass
time.sleep(0.5)
return None
def _maybe_auto_login(page: Any, prefix: str) -> None:
"""
如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。
"""
username_env = f"FREIGHT_RPA_{prefix}_USERNAME"
password_env = f"FREIGHT_RPA_{prefix}_PASSWORD"
if not _env(username_env) or not _env(password_env):
return
user_filled = _fill_login_field(
page,
f"FREIGHT_RPA_{prefix}_USERNAME_SELECTOR",
username_env,
(
'input[name="username"]',
'input[name="userName"]',
'input[name="email"]',
'input[type="email"]',
'input[type="text"]',
),
)
password_filled = _fill_login_field(
page,
f"FREIGHT_RPA_{prefix}_PASSWORD_SELECTOR",
password_env,
('input[name="password"]', 'input[type="password"]'),
)
if not user_filled and not password_filled:
return
if user_filled != password_filled:
raise RuntimeError(f"{prefix} login form partially detected; please configure login selectors")
if not _click_login_submit(
page,
f"FREIGHT_RPA_{prefix}_LOGIN_BUTTON_SELECTOR",
("Sign in", "Login", "Log in", "登录"),
):
raise RuntimeError(f"{prefix} login fields detected but submit button was not found")
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
raise RuntimeError(f"{prefix} login did not complete; MFA/SSO/manual verification may be required")
def _maybe_auto_login_dsv(page: Any) -> None:
"""
DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。
"""
username = _env("FREIGHT_RPA_DSV_USERNAME")
password = _env("FREIGHT_RPA_DSV_PASSWORD")
if not username or not password:
return
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=15_000) is not None:
print("[dsv-login] existing session detected")
return
print("[dsv-login] waiting username field")
username_locator = _wait_for_visible_selector(
page,
"FREIGHT_RPA_DSV_USERNAME_SELECTOR",
(
"input#identifier",
'input[name="identifier"]',
'input[name="username"]',
'input[name="userName"]',
'input[name="email"]',
'input[autocomplete="username"]',
'input[placeholder="电子邮箱或SIMS ID或手机号"]',
'input[type="email"]',
'input[type="text"]',
),
timeout_ms=15_000,
)
if username_locator is not None:
username_locator = _fill_dsv_username(page, username)
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")
return
try:
text = page.locator("body").inner_text(timeout=3_000)
except Exception:
text = ""
raise RuntimeError(f"DSV login state is unknown url={page.url} body={text[:300]!r}")
print("[dsv-login] username filled")
# #region debug-point A:username-filled
_debug_report(
"A",
"freight_rpa_worker.py:_maybe_auto_login_dsv:username_filled",
"username step completed",
{
"url": getattr(page, "url", ""),
"frame_count": len(page.frames),
},
)
# #endregion
continue_selector = _env("FREIGHT_RPA_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}")
# #region debug-point A:continue-missing
_debug_report(
"A",
"freight_rpa_worker.py:_maybe_auto_login_dsv:continue_missing",
"continue button was not found",
{
"url": getattr(page, "url", ""),
"identifier_value": identifier_value,
"button_state": button_state,
},
)
# #endregion
raise RuntimeError("DSV login email step detected but continue button was not found")
print("[dsv-login] continue clicked")
# #region debug-point A:continue-clicked
_debug_report(
"A",
"freight_rpa_worker.py:_maybe_auto_login_dsv:continue_clicked",
"continue button clicked",
{
"url": getattr(page, "url", ""),
},
)
# #endregion
print("[dsv-login] waiting password field")
password_locator = None
login_deadline = time.monotonic() + (max(30_000, int(_env("FREIGHT_RPA_LOGIN_READY_TIMEOUT_MS", "300000") or "300000")) / 1000)
password_method_clicked_at = 0.0
while time.monotonic() < login_deadline:
_dismiss_dsv_password_upgrade_prompt(page, timeout_ms=500)
password_locator = _wait_for_visible_selector(
page,
"FREIGHT_RPA_DSV_PASSWORD_SELECTOR",
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
timeout_ms=2_000,
)
if password_locator is not None:
break
if _fill_dsv_password_page_fields(page, username, password):
print("[dsv-login] password filled")
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")
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
_dismiss_dsv_password_upgrade_prompt(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")
print("[dsv-login] login completed")
return
_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):
print("[dsv-login] login completed")
return
method_ready = _wait_for_dsv_login_method_page(page, timeout_ms=2_000)
# #region debug-point D:method-page-status
_debug_report(
"D",
"freight_rpa_worker.py:_maybe_auto_login_dsv:method_ready_loop",
"checked login method page readiness",
{
"url": getattr(page, "url", ""),
"method_ready": method_ready,
"password_method_clicked_recently": bool(password_method_clicked_at and time.monotonic() - password_method_clicked_at < 6),
},
)
# #endregion
if not method_ready 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")
time.sleep(1)
continue
password_locator = _wait_for_visible_selector(
page,
"FREIGHT_RPA_DSV_PASSWORD_SELECTOR",
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
timeout_ms=1_000,
)
if password_locator is not None:
break
if not method_ready:
time.sleep(1)
continue
if password_method_clicked_at and time.monotonic() - password_method_clicked_at < 6:
time.sleep(1)
continue
password_method_selector = _env("FREIGHT_RPA_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()
print("[dsv-login] password method clicked")
if password_locator is None:
if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000):
print("[dsv-login] login completed")
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}")
password_locator = _wait_for_visible_selector(
page,
"FREIGHT_RPA_DSV_PASSWORD_SELECTOR",
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
timeout_ms=_browser_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")
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")
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
_dismiss_dsv_password_upgrade_prompt(page)
print("[dsv-login] login completed")
return
print(f"[dsv-login] password field missing url={page.url} body={text[:300]!r}")
# #region debug-point D:password-field-missing
_debug_report(
"D",
"freight_rpa_worker.py:_maybe_auto_login_dsv:password_field_missing",
"password field was still missing after method selection",
{
"url": getattr(page, "url", ""),
"body": text[:500],
},
)
# #endregion
raise RuntimeError("DSV login password field was not found")
password_locator.fill(password, timeout=_browser_timeout_ms())
print("[dsv-login] password filled")
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")
page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms())
_dismiss_dsv_password_upgrade_prompt(page)
if page.locator('input[type="password"]').first.is_visible(timeout=3_000):
# #region debug-point D:login-not-complete
_debug_report(
"D",
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_not_complete",
"password field remained visible after login attempt",
{
"url": getattr(page, "url", ""),
},
)
# #endregion
raise RuntimeError("DSV login did not complete; password may be invalid or verification is required")
print("[dsv-login] login completed")
# #region debug-point D:login-complete
_debug_report(
"D",
"freight_rpa_worker.py:_maybe_auto_login_dsv:login_complete",
"login flow reached post-auth state",
{
"url": getattr(page, "url", ""),
},
)
# #endregion
def _dismiss_dsv_password_upgrade_prompt(page: Any, timeout_ms: int = 2_000) -> None:
"""
DSV 首次登录后可能提示升级密码登录;RPA 选择“也许以后”继续进入系统。
"""
quick_script = """
() => {
const visible = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
};
const textOf = (node) => ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim();
const pageText = textOf(document.body || document.documentElement);
const target = Array.from(document.querySelectorAll('button, a, [role="button"], body *')).find((node) => {
const text = textOf(node);
return visible(node) && (text === '也许以后' || text === 'Maybe later' || text === 'Not now');
});
if (!target) return false;
const clickable = target.closest('button, a, [role="button"]') || target;
const vueNode = clickable.closest('#sims-login-controller, [id], body') || clickable;
const vue = clickable.__vue__ || vueNode.__vue__ || vueNode.__vueParentComponent?.proxy || null;
if (vue && typeof vue.skipAddingDevice === 'function') {
vue.skipAddingDevice();
return true;
}
const vueButtons = Array.from(document.querySelectorAll('[v-on\\\\:click*="skipAddingDevice"], [onclick*="skipAddingDevice"]'));
for (const node of vueButtons) {
const vueCandidate = node.__vue__ || node.closest('#sims-login-controller, [id], body')?.__vue__;
if (vueCandidate && typeof vueCandidate.skipAddingDevice === 'function') {
vueCandidate.skipAddingDevice();
return true;
}
}
clickable.scrollIntoView({ block: 'center', inline: 'center' });
if (typeof clickable.click === 'function') clickable.click();
else {
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
clickable.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
}
return true;
}
"""
for frame in getattr(page, "frames", []) or []:
try:
if frame.evaluate(quick_script):
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
try:
text = frame.locator("body").inner_text(timeout=500)
except Exception:
text = ""
if "使用密码升级登录" not in text and "也许以后" not in text and "Maybe later" not in text:
print("[dsv-login] password upgrade prompt dismissed")
try:
page.wait_for_load_state("domcontentloaded", timeout=10_000)
except Exception:
pass
return
time.sleep(0.5)
except Exception:
pass
selector = _env("FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR")
if selector:
candidates = (selector,)
else:
candidates = (
'button.dbs-sims-button-secondary:has-text("也许以后")',
'button[v-on\\:click="skipAddingDevice();"]',
'button[onclick*="skipAddingDevice"]',
'button:has-text("也许以后")',
'a:has-text("也许以后")',
'text=也许以后',
'button.dbs-sims-button-secondary:has-text("Maybe later")',
'button:has-text("Maybe later")',
'a:has-text("Maybe later")',
'text=Maybe later',
'button:has-text("Not now")',
'a:has-text("Not now")',
'text=Not now',
)
for candidate in candidates:
try:
locator = page.locator(candidate).first
locator.wait_for(state="attached", timeout=min(timeout_ms, 500))
locator.evaluate(
"""
(target) => {
target.scrollIntoView({ block: 'center', inline: 'center' });
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
}
"""
)
print("[dsv-login] password upgrade prompt dismissed")
# #region debug-point D:maybe-later-dismissed
_debug_report(
"D",
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:dismissed",
"maybe later prompt dismissed",
{
"selector": candidate,
"url": getattr(page, "url", ""),
},
)
# #endregion
try:
page.wait_for_load_state("domcontentloaded", timeout=10_000)
except Exception:
pass
return
except Exception:
pass
def _wait_for_download_file_ready(path: Path, timeout_ms: int | None = None) -> None:
"""Wait until a saved download exists and its size stops changing."""
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
deadline = time.monotonic() + (timeout / 1000)
previous_size = -1
stable_count = 0
while time.monotonic() < deadline:
if path.is_file():
size = path.stat().st_size
if size > 0 and size == previous_size:
stable_count += 1
if stable_count >= 3:
return
else:
stable_count = 0
previous_size = size
time.sleep(0.5)
raise RuntimeError(f"download file was not completed: {path}")
def _validate_inventory_excel(path: Path) -> None:
"""Validate that the downloaded DSV inventory file is an openable Excel with inventory rows."""
if not path.is_file():
raise RuntimeError(f"downloaded inventory file does not exist: {path}")
size = path.stat().st_size
if size < 1_024:
raise RuntimeError(f"downloaded inventory file is too small: {path} size={size}")
if load_workbook is None:
return
try:
wb = load_workbook(path, read_only=True, data_only=True)
except Exception as exc:
raise RuntimeError(f"downloaded inventory file is not a valid Excel file: {path}") from exc
try:
if not wb.sheetnames:
raise RuntimeError(f"downloaded inventory file has no worksheets: {path}")
ws = wb[wb.sheetnames[0]]
nonempty_rows = 0
saw_title = False
saw_header = False
for row in ws.iter_rows(values_only=True):
values = [str(value).strip() if value is not None else "" for value in row]
if not any(values):
continue
nonempty_rows += 1
joined = " | ".join(values)
if "On Hand Inventory by Location" in joined:
saw_title = True
if "Supplier ID" in values and ("AWS Sku" in values or "Sku Description" in values):
saw_header = True
if nonempty_rows >= 50 and saw_title and saw_header:
return
if not saw_title or not saw_header or nonempty_rows < 3:
raise RuntimeError(
"downloaded inventory Excel did not contain expected inventory report data: "
f"path={path} rows={nonempty_rows} title={saw_title} header={saw_header}"
)
finally:
wb.close()
def _save_download(download: Any, drop_dir: Path, task_no: str, source_code: str) -> Path:
suggested = str(download.suggested_filename or "")
suffix = Path(suggested).suffix or ".xlsx"
dest = drop_dir / _download_name(task_no, source_code, suffix=suffix)
download.save_as(str(dest))
_wait_for_download_file_ready(dest)
_validate_inventory_excel(dest)
return dest
def _open_browser(download_dir: Path):
sync_playwright, _timeout = _require_playwright()
playwright = sync_playwright().start()
profile = _env("FREIGHT_RPA_BROWSER_PROFILE_DIR")
if not profile:
profile = str(
Path(__file__).resolve().parents[2]
/ "backend"
/ "data"
/ "shipping_notice"
/ "freight_rpa"
/ "browser_profile"
)
profile_dir = Path(profile)
profile_dir.mkdir(parents=True, exist_ok=True)
headless = _env("FREIGHT_RPA_HEADLESS", "false").lower() == "true"
channel = _env("FREIGHT_RPA_BROWSER_CHANNEL")
executable_path = _env("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH")
launch_options: dict[str, Any] = {
"headless": headless,
"accept_downloads": True,
"downloads_path": str(download_dir),
}
if executable_path:
launch_options["executable_path"] = executable_path
elif channel:
launch_options["channel"] = channel
context = playwright.chromium.launch_persistent_context(
str(profile_dir),
**launch_options,
)
page = context.pages[0] if context.pages else context.new_page()
page.set_default_timeout(_browser_timeout_ms())
return playwright, context, page
def _download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
query = source.get("query") if isinstance(source.get("query"), dict) else {}
entry_url = str(source.get("entry_url") or "").strip()
if not entry_url:
raise RuntimeError("DSV360 inventory source missing entry_url")
print("[dsv] open entry")
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
_maybe_auto_login_dsv(page)
_dismiss_dsv_password_upgrade_prompt(page)
_wait_for_dsv_app_after_login(page, timeout_ms=_browser_timeout_ms())
print("[dsv] open reports")
reports_selector = _env("FREIGHT_RPA_DSV_REPORTS_SELECTOR")
if reports_selector:
page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True)
else:
_click_dsv_reports_menu(page)
_select_dsv_inventory_report(page, query)
print("[dsv] fill filters")
_fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"))
_fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"))
print("[dsv] click view report")
_click_dsv_view_report(page)
print("[dsv] wait report result")
page.wait_for_load_state("networkidle", timeout=_browser_timeout_ms())
_wait_for_dsv_report_result_ready(page)
print("[dsv] export excel")
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
_click_dsv_export_excel(page)
return download_info.value
def _download_crane_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any:
query = source.get("query") if isinstance(source.get("query"), dict) else {}
entry_url = str(source.get("entry_url") or "").strip()
if not entry_url:
raise RuntimeError("Crane inventory source missing entry_url")
page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
_maybe_auto_login(page, "CRANE")
_select_or_fill(page, "FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code"))
_select_or_fill(page, "FREIGHT_RPA_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code"))
_select_or_fill(page, "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR", "Choose Warehouse ..", query.get("warehouse_code"))
_click_selector_or_text(page, "FREIGHT_RPA_CRANE_RUN_SELECTOR", "Run Report")
export_selector = _env("FREIGHT_RPA_CRANE_EXPORT_SELECTOR")
export_text = _env("FREIGHT_RPA_CRANE_EXPORT_TEXT", "file_download")
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, export_text, exact=True)
return download_info.value
def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) -> Path:
task_no = str(trigger.get("task_no") or "").strip()
source = trigger.get("rpa_inventory_source")
if not isinstance(source, dict):
raise RuntimeError("inventory trigger missing rpa_inventory_source")
source_type = str(source.get("source_type") or "").strip()
source_code = str(source.get("source_code") or "").strip() or source_type or "UNKNOWN"
if not source_type:
raise RuntimeError("inventory source missing source_type")
playwright = context = None
keep_open_on_error = _env("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"
failed = False
try:
playwright, context, page = _open_browser(drop_dir)
if source_type == "dsv360":
download = _download_dsv360_inventory(page, trigger, source)
elif source_type == "crane_footprint":
download = _download_crane_inventory(page, trigger, source)
else:
raise RuntimeError(f"unsupported inventory source_type: {source_type}")
return _save_download(download, drop_dir, task_no, source_code)
except Exception:
failed = True
raise
finally:
if failed and keep_open_on_error:
print("[browser] keeping browser open after error because FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true")
while True:
time.sleep(3600)
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
task_no = str(body.get("task_no") or "").strip()
failed_dir = trigger_path.parent / "failed"
if not task_no:
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
trigger_path.unlink(missing_ok=True)
return
mock = _env("FREIGHT_RPA_MOCK", "true").lower() == "true"
try:
out_file = _write_sample_inventory(drop_dir, task_no) if mock else _download_inventory_with_browser(body, drop_dir)
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
"success": True,
"file_path": str(out_file),
"source_code": ((body.get("rpa_inventory_source") or {}).get("source_code") if isinstance(body.get("rpa_inventory_source"), dict) else None),
})
_move_trigger(trigger_path, processed_dir, "processed")
mode = "mock" if mock else "browser"
print(f"[inventory] {mode} export done for {task_no} -> {out_file.name}")
except Exception as exc:
try:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"task_no": task_no,
"success": False,
"error_message": str(exc),
})
if trigger_path.exists():
trigger_path.unlink(missing_ok=True)
except Exception as callback_exc:
_report_callback_failure(trigger_path, failed_dir, callback_exc)
def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
task_no = str(body.get("task_no") or "").strip()
file_path = str(body.get("file_path") or "").strip()
failed_dir = trigger_path.parent / "failed"
if not task_no:
trigger_path.unlink(missing_ok=True)
return
mock = _env("FREIGHT_RPA_MOCK", "true").lower() == "true"
if not mock:
print(f"[upload] real RPA not implemented; trigger kept: {trigger_path.name}")
return
if file_path and not Path(file_path).is_file():
try:
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"task_no": task_no,
"success": False,
"error_message": f"queue file missing: {file_path}",
})
trigger_path.unlink(missing_ok=True)
except Exception as callback_exc:
_report_callback_failure(trigger_path, failed_dir, callback_exc)
return
ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}"
try:
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"task_no": task_no,
"success": True,
"freight_ref_no": ref,
})
_move_trigger(trigger_path, processed_dir, "processed")
print(f"[upload] mock upload done for {task_no} ref={ref}")
except Exception as callback_exc:
_report_callback_failure(trigger_path, failed_dir, callback_exc)
def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
if not trigger_dir.is_dir():
return
for path in sorted(trigger_dir.glob("*.json")):
if not path.is_file():
continue
try:
handler(path, *extra_args)
except Exception as exc:
print(f"[error] {path.name}: {exc}", file=sys.stderr)
def main() -> None:
drop_dir = _require_path("FREIGHT_INVENTORY_DROP_DIR")
inv_trigger_dir = _require_path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
upload_queue_dir = _require_path("FREIGHT_UPLOAD_QUEUE_DIR")
upload_trigger_dir = _require_path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
poll = max(1, int(_env("FREIGHT_RPA_POLL_SECONDS", "3") or "3"))
inv_processed = inv_trigger_dir / "processed"
upload_processed = upload_trigger_dir / "processed"
print("[freight_rpa_worker] started")
print(f" mock={_env('FREIGHT_RPA_MOCK', 'true')}")
print(f" inventory_triggers={inv_trigger_dir}")
print(f" upload_triggers={upload_trigger_dir}")
print(f" drop={drop_dir}")
print(f" queue={upload_queue_dir}")
while True:
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
time.sleep(poll)
if __name__ == "__main__":
main()