""" 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/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 except ImportError: Workbook = None # type: ignore def _env(name: str, default: str = "") -> str: return str(os.getenv(name) or default).strip() 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: print(f"[dsv] skip {label} filter; no selector configured") return _fill_selector_or_label(page, selector_env, label, text) 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. """ 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 _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) for selector in ( f"#report-mega-legacy :text-is({text_literal})", f".mega-dropdown-menu :text-is({text_literal})", f".dropdown-menu :text-is({text_literal})", f"text={text}", ): try: locator = page.locator(selector).first locator.wait_for(state="visible", timeout=10_000) locator.click(timeout=3_000, force=True) return except Exception: pass raise RuntimeError(f"DSV report group was not found: {text}") def _click_dsv_view_report(page: Any) -> None: selectors = ( '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=1_000) locator.evaluate( """ (target) => { if (target.form && typeof target.form.requestSubmit === 'function') { target.form.requestSubmit(target); } else if (target.form) { target.form.submit(); } else { target.dispatchEvent(new MouseEvent('click', { 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: selectors = ( "#report-mega-legacy > a.dropdown-toggle.nav-link", "#report-mega-legacy a.dropdown-toggle", "#report-mega-legacy a.nav-link", ) for selector in selectors: try: locator = page.locator(selector).first locator.wait_for(state="attached", timeout=30_000) locator.evaluate( """ (target) => { target.click(); target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); } """ ) return except Exception: pass raise RuntimeError("DSV Reports menu was not found") def _click_dsv_password_method(page: Any) -> bool: 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 ) script_row_click = """ () => { const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim(); 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 (text === '密码' || text === 'Password' || text === '输入您的密码并登录。' || text.includes('输入您的密码并登录')) && !text.includes('忘记密码'); }); if (!typeNode) return false; const row = typeNode.closest('li, .row, form, button, a, [role="button"]') || typeNode; const target = row.querySelector('.device-continue, button, a, [role="button"], input[type="submit"]') || row; 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; } """ 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 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 && (text === '密码' || text === 'Password' || text.includes('输入您的密码并登录')); }); if (!node) return null; const row = node.closest('li, .row, .mb-2, .device-selection, .device, button, a, [role="button"]') || node; 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) return True if frame.evaluate(script_row_click): return True except Exception: pass deadline = time.monotonic() + 10 while time.monotonic() < deadline: try: rows = page.locator("form[name='mfaForm'] li.mb-2").all() for row in rows: text = row.inner_text(timeout=1_000) if ("密码" in text or "Password" in text) and "忘记密码" not in 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) return True except Exception: pass time.sleep(0.5) 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: 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: for frame in page.frames: try: text = frame.locator("body").inner_text(timeout=500) except Exception: text = "" if ("电子邮箱或SIMS ID或手机号" in text or "E-Mail or SIMS ID" in text) and ("继续" in text or "Continue" in text): return True return False def _submit_dsv_password_form(page: Any) -> bool: for selector in ( 'button[name="login"]', '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 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 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' }); submit.click(); submit.dispatchEvent(new MouseEvent('click', { 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, timeout=2_000): 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") 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}") raise RuntimeError("DSV login email step detected but continue button was not found") print("[dsv-login] continue clicked") 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: 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 if _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 method_ready = _wait_for_dsv_login_method_page(page, timeout_ms=2_000) 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}") 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): raise RuntimeError("DSV login did not complete; password may be invalid or verification is required") print("[dsv-login] login completed") def _dismiss_dsv_password_upgrade_prompt(page: Any) -> None: """ DSV 首次登录后可能提示升级密码登录;RPA 选择“也许以后”继续进入系统。 """ selector = _env("FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR") if selector: candidates = (selector,) else: candidates = ( 'button:has-text("也许以后")', 'a:has-text("也许以后")', 'text=也许以后', '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=2_000) locator.evaluate( """ (target) => { target.click(); target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); } """ ) print("[dsv-login] password upgrade prompt dismissed") page.wait_for_load_state("domcontentloaded", timeout=10_000) return except Exception: pass 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)) 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" / "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) 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) print("[dsv] select program") program_selector = _env("FREIGHT_RPA_DSV_PROGRAM_SELECTOR") if program_selector: page.locator(program_selector).first.click(timeout=_browser_timeout_ms()) else: _click_dsv_menu_item(page, str(query.get("program_label") or "")) print("[dsv] select report group") report_group_selector = _env("FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR") if report_group_selector: page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms()) else: _click_dsv_report_group(page, str(query.get("report_group") or "Inventory")) print("[dsv] select report") report_name_selector = _env("FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR") if report_name_selector: page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms()) else: _click_dsv_menu_item(page, str(query.get("report_name") or "On Hand Inventory by Location")) 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()) 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()