feat(schedule): 新增平台任务参数契约与动态选项支持
This commit is contained in:
1 parent
2ce1aca023
commit
8b5b0b49bf
76 files changed
+7103
-1203
No files matched your search
@@ -92,7 +92,7 @@ python scripts/rpa/freight_rpa_worker.py
|
||||
|
||||
Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,**Crane 一次登录**循环各 Warehouse;完成后回调 `POST /api/shipping-notice/rpa/inventory-batch-ready`。
|
||||
|
||||
库存源定义见 `backend/config/shipping_inventory_sources.json`(新增 Warehouse 只改 JSON)。
|
||||
库存源定义见 `backend/config/shipping_inventory_sources.yaml`(新增 Warehouse 只改 YAML)。
|
||||
|
||||
页面控件如果默认可见文本无法稳定点击,可通过环境变量覆盖 selector:
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
scripts/rpa/dsv_export_batch_smoke.py
|
||||
|
||||
用途:本地验证 DSV 360 同一浏览器 session 内连续导出 3 份库存 Excel。
|
||||
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、shipping_inventory_sources.json、freight_rpa_worker。
|
||||
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、shipping_inventory_sources.yaml、freight_rpa_worker。
|
||||
逻辑:复用 worker 批量导出循环(一次登录 + reset 入口),不依赖 HXOPS callback。
|
||||
|
||||
场景:
|
||||
warehouse — 同一 source_code / 同一 3lv 报表,仅 Warehouse 参数变化
|
||||
source_code — 三个不同 source_code(JSON 中独立配置项)
|
||||
source_code — 三个不同 source_code(YAML 中独立配置项)
|
||||
|
||||
用法:
|
||||
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py warehouse
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
scripts/rpa/dsv_export_smoke.py
|
||||
|
||||
用途:本地手动验证指定 DSV 360 库存源(默认 BYAWSATL01)的浏览器导出全流程。
|
||||
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、backend/config/shipping_inventory_sources.json。
|
||||
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、backend/config/shipping_inventory_sources.yaml。
|
||||
逻辑:加载 rpa_inventory_source → _download_inventory_with_browser → 输出 Excel 路径。
|
||||
|
||||
用法(仓库根目录):
|
||||
@@ -20,6 +20,8 @@ import traceback
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def _repo_root() -> Path:
|
||||
return Path(__file__).resolve().parents[2]
|
||||
@@ -36,11 +38,11 @@ def _load_worker():
|
||||
|
||||
def _build_source_from_config(source_code: str) -> dict:
|
||||
"""
|
||||
从 JSON 配置构造 worker 兼容的 rpa_inventory_source(不依赖 Flask 上下文)。
|
||||
从 YAML 配置构造 worker 兼容的 rpa_inventory_source(不依赖 Flask 上下文)。
|
||||
核心逻辑:复用与 inventory_sources._build_legacy_query 相同的 query 口径。
|
||||
"""
|
||||
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.json"
|
||||
payload = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.yaml"
|
||||
payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))
|
||||
raw = next(
|
||||
(item for item in (payload.get("sources") or []) if str(item.get("source_code") or "").upper() == source_code.upper()),
|
||||
None,
|
||||
|
||||
@@ -22,11 +22,15 @@ Optional:
|
||||
FREIGHT_RPA_HEADLESS=false
|
||||
FREIGHT_RPA_BROWSER_CHANNEL=msedge
|
||||
FREIGHT_RPA_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
|
||||
FREIGHT_RPA_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log
|
||||
FREIGHT_RPA_LOG_MAX_BYTES=10485760
|
||||
FREIGHT_RPA_LOG_BACKUP_COUNT=5
|
||||
FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD
|
||||
FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
@@ -37,7 +41,7 @@ import urllib.error
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from typing import Any, Callable, TextIO
|
||||
|
||||
try:
|
||||
from openpyxl import Workbook
|
||||
@@ -68,6 +72,107 @@ def _env(name: str, default: str = "") -> str:
|
||||
return value
|
||||
|
||||
|
||||
class _TeeStream:
|
||||
"""
|
||||
同时写入控制台与日志文件的轻量 stream。
|
||||
|
||||
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
|
||||
文件 flush 采用行级同步,RPA 异常退出时尽量保留最后几行排障信息。
|
||||
"""
|
||||
|
||||
def __init__(self, console: TextIO, log_file: TextIO) -> None:
|
||||
self._console = console
|
||||
self._log_file = log_file
|
||||
self.encoding = getattr(console, "encoding", "utf-8")
|
||||
|
||||
def write(self, text: str) -> int:
|
||||
self._console.write(text)
|
||||
written = self._log_file.write(text)
|
||||
self.flush()
|
||||
return written
|
||||
|
||||
def flush(self) -> None:
|
||||
self._console.flush()
|
||||
self._log_file.flush()
|
||||
|
||||
def isatty(self) -> bool:
|
||||
return bool(getattr(self._console, "isatty", lambda: False)())
|
||||
|
||||
|
||||
def _configure_file_logging() -> Path | None:
|
||||
"""
|
||||
按 FREIGHT_RPA_LOG_FILE 启用 worker 文件日志。
|
||||
|
||||
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
|
||||
让所有 print/stdout/stderr 同时落盘,便于排查登录、下载、回调失败。
|
||||
|
||||
Returns:
|
||||
Path | None: 已启用的日志路径;未配置时返回 None。
|
||||
"""
|
||||
raw = _env("FREIGHT_RPA_LOG_FILE")
|
||||
if not raw:
|
||||
return None
|
||||
path = Path(raw).expanduser()
|
||||
if not path.is_absolute():
|
||||
path = (_backend_dir() / path).resolve()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
_rotate_log_file_if_needed(path)
|
||||
log_file = path.open("a", encoding="utf-8", buffering=1)
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
sys.stdout = _TeeStream(original_stdout, log_file) # type: ignore[assignment]
|
||||
sys.stderr = _TeeStream(original_stderr, log_file) # type: ignore[assignment]
|
||||
|
||||
def _close_log() -> None:
|
||||
sys.stdout = original_stdout
|
||||
sys.stderr = original_stderr
|
||||
log_file.close()
|
||||
|
||||
atexit.register(_close_log)
|
||||
print(f"[logging] tee enabled path={path}")
|
||||
return path
|
||||
|
||||
|
||||
def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int:
|
||||
"""读取日志相关整数环境变量;非法值回退默认值。"""
|
||||
try:
|
||||
value = int(_env(name, str(default)) or str(default))
|
||||
except ValueError:
|
||||
return default
|
||||
return max(value, min_value)
|
||||
|
||||
|
||||
def _rotate_log_file_if_needed(path: Path) -> None:
|
||||
"""
|
||||
在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。
|
||||
|
||||
核心逻辑:当 `FREIGHT_RPA_LOG_FILE` 已存在且大小达到 `FREIGHT_RPA_LOG_MAX_BYTES`
|
||||
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `FREIGHT_RPA_LOG_BACKUP_COUNT`
|
||||
的旧文件会被删除。`FREIGHT_RPA_LOG_MAX_BYTES<=0` 时禁用轮转。
|
||||
"""
|
||||
max_bytes = _log_int_env("FREIGHT_RPA_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
|
||||
backup_count = _log_int_env("FREIGHT_RPA_LOG_BACKUP_COUNT", 5, min_value=0)
|
||||
if max_bytes <= 0 or not path.is_file():
|
||||
return
|
||||
try:
|
||||
if path.stat().st_size < max_bytes:
|
||||
return
|
||||
except OSError:
|
||||
return
|
||||
|
||||
if backup_count <= 0:
|
||||
path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
oldest = Path(f"{path}.{backup_count}")
|
||||
oldest.unlink(missing_ok=True)
|
||||
for index in range(backup_count - 1, 0, -1):
|
||||
src = Path(f"{path}.{index}")
|
||||
if src.exists():
|
||||
src.replace(Path(f"{path}.{index + 1}"))
|
||||
path.replace(Path(f"{path}.1"))
|
||||
|
||||
|
||||
def _backend_dir() -> Path:
|
||||
"""
|
||||
返回仓库内 backend 根目录。
|
||||
@@ -1880,9 +1985,10 @@ def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> Non
|
||||
def _click_dsv_view_report(page: Any) -> None:
|
||||
"""
|
||||
点击 SSRS 参数页 View Report。
|
||||
核心逻辑:report-frame 挂载后按钮可能延迟渲染,先短轮询再尝试多种点击方式。
|
||||
核心逻辑:在各 frame 内轮询 ReportViewer 固定控件 ID 与通用按钮选择器,挂载后尝试多种点击方式。
|
||||
"""
|
||||
selectors = (
|
||||
"#ReportViewerMain_ctl08_ctl00",
|
||||
'input[id^="ReportViewerMain_"][value="View Report"]',
|
||||
'input[type="submit"][value="View Report"]',
|
||||
'input[value="View Report"]',
|
||||
@@ -1890,63 +1996,63 @@ def _click_dsv_view_report(page: Any) -> None:
|
||||
)
|
||||
_debug_dsv_stage(page, "view-report-before-click", target_text="View Report")
|
||||
wait_ms = max(15_000, int(_env("FREIGHT_RPA_DSV_VIEW_REPORT_WAIT_MS", "30000") or "30000"))
|
||||
if _wait_for_visible_selector(page, "", selectors, timeout_ms=wait_ms) is None:
|
||||
print(f"[dsv-debug] view report missing {_debug_dsv_page_snapshot(page, target_text='View Report')}")
|
||||
raise RuntimeError("DSV View Report button was not found")
|
||||
for frame in page.frames:
|
||||
for selector in selectors:
|
||||
try:
|
||||
locator = frame.locator(selector).first
|
||||
locator.wait_for(state="attached", timeout=1_000)
|
||||
click_attempts = ("click", "enter", "space", "evaluate-click", "request-submit")
|
||||
for attempt in click_attempts:
|
||||
try:
|
||||
deadline = time.monotonic() + (wait_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="attached", timeout=1_000)
|
||||
click_attempts = ("click", "enter", "space", "evaluate-click", "request-submit")
|
||||
for attempt in click_attempts:
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=1_000)
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=1_000)
|
||||
except Exception:
|
||||
pass
|
||||
if attempt == "click":
|
||||
locator.click(timeout=2_000, force=True)
|
||||
elif attempt == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
elif attempt == "space":
|
||||
locator.press("Space", timeout=1_500)
|
||||
elif attempt == "evaluate-click":
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
target.click();
|
||||
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
else:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
if (target.form && typeof target.form.requestSubmit === 'function') {
|
||||
target.form.requestSubmit(target);
|
||||
} else if (target.form) {
|
||||
target.form.submit();
|
||||
} else {
|
||||
target.click();
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
if attempt == "click":
|
||||
locator.click(timeout=2_000, force=True)
|
||||
elif attempt == "enter":
|
||||
locator.press("Enter", timeout=1_500)
|
||||
elif attempt == "space":
|
||||
locator.press("Space", timeout=1_500)
|
||||
elif attempt == "evaluate-click":
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
target.click();
|
||||
target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
|
||||
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
"""
|
||||
)
|
||||
else:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(target) => {
|
||||
if (target.form && typeof target.form.requestSubmit === 'function') {
|
||||
target.form.requestSubmit(target);
|
||||
} else if (target.form) {
|
||||
target.form.submit();
|
||||
} else {
|
||||
target.click();
|
||||
}
|
||||
}
|
||||
"""
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
deadline = time.monotonic() + 4
|
||||
while time.monotonic() < deadline:
|
||||
if _dsv_report_submission_started(frame, locator):
|
||||
print(f"[dsv] view report submitted via selector={selector!r} attempt={attempt}")
|
||||
_debug_dsv_stage(page, f"view-report-after-click-{attempt}", target_text="View Report")
|
||||
return
|
||||
time.sleep(0.3)
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
submit_deadline = time.monotonic() + 4
|
||||
while time.monotonic() < submit_deadline:
|
||||
if _dsv_report_submission_started(frame, locator):
|
||||
print(f"[dsv] view report submitted via selector={selector!r} attempt={attempt}")
|
||||
_debug_dsv_stage(page, f"view-report-after-click-{attempt}", target_text="View Report")
|
||||
return
|
||||
time.sleep(0.3)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
print(f"[dsv-debug] view report missing {_debug_dsv_page_snapshot(page, target_text='View Report')}")
|
||||
raise RuntimeError("DSV View Report button was not found")
|
||||
|
||||
@@ -2435,6 +2541,22 @@ def _wait_for_dsv_app_after_login(
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
return True
|
||||
if not auth_transition and _wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
_DSV_REPORTS_NAV_SELECTORS,
|
||||
timeout_ms=400,
|
||||
) is not None:
|
||||
if on_portal_shell_seen is not None:
|
||||
on_portal_shell_seen()
|
||||
_debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports")
|
||||
_report_debug_event(
|
||||
"J",
|
||||
"freight_rpa_worker.py:_wait_for_dsv_app_after_login:success",
|
||||
"[DEBUG] dsv reports nav visible after login",
|
||||
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
|
||||
)
|
||||
return True
|
||||
on_portal_home = _is_dsv_on_portal_home(page)
|
||||
if on_portal_home and not auth_transition:
|
||||
if on_portal_shell_seen is not None and not portal_shell_callback_fired:
|
||||
@@ -2454,6 +2576,13 @@ def _wait_for_dsv_app_after_login(
|
||||
if _has_dsv_password_upgrade_prompt(page, timeout_ms=250):
|
||||
_dismiss_dsv_password_upgrade_prompt(page)
|
||||
continue
|
||||
# [STEP] 合规/认证过渡页仅用轻量短超时探测 Reports 导航,避免与首页长轮询混淆。
|
||||
_wait_for_visible_selector(
|
||||
page,
|
||||
"",
|
||||
_DSV_REPORTS_NAV_SELECTORS,
|
||||
timeout_ms=400,
|
||||
)
|
||||
time.sleep(0.25)
|
||||
continue
|
||||
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
|
||||
@@ -3793,11 +3922,63 @@ def _dismiss_dsv_password_upgrade_prompt(page: Any) -> None:
|
||||
# #endregion
|
||||
|
||||
|
||||
_INVENTORY_EXCEL_MIN_BYTES = 512
|
||||
_INVENTORY_EXCEL_HEADER_MARKERS = (
|
||||
"on hand inventory",
|
||||
"supplier id",
|
||||
"aws sku",
|
||||
"sku description",
|
||||
)
|
||||
|
||||
|
||||
def _validate_inventory_excel(path: Path) -> None:
|
||||
"""
|
||||
校验 RPA 下载的库存 Excel 可被打开且具备报表基本结构。
|
||||
核心逻辑:拒绝过小/HTML 错误页伪装文件;检查前几行是否含库存报表表头特征。
|
||||
Args:
|
||||
path: 本地 Excel 路径。
|
||||
Raises:
|
||||
RuntimeError: 文件过小、非 Excel 或缺少库存报表关键表头。
|
||||
"""
|
||||
size = path.stat().st_size
|
||||
if size < _INVENTORY_EXCEL_MIN_BYTES:
|
||||
raise RuntimeError(f"downloaded inventory Excel is too small ({size} bytes)")
|
||||
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("openpyxl required to validate inventory Excel") from exc
|
||||
|
||||
try:
|
||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"downloaded file is not valid Excel: {exc}") from exc
|
||||
|
||||
try:
|
||||
worksheet = workbook.active
|
||||
if worksheet is None:
|
||||
raise RuntimeError("downloaded file is not valid Excel: missing active sheet")
|
||||
preview_lines: list[str] = []
|
||||
for row in worksheet.iter_rows(max_row=6, values_only=True):
|
||||
cells = [str(cell).strip() for cell in row if cell is not None and str(cell).strip()]
|
||||
if cells:
|
||||
preview_lines.append(" | ".join(cells).lower())
|
||||
haystack = "\n".join(preview_lines)
|
||||
title = str(worksheet.title or "").lower().replace("_", "")
|
||||
if not any(marker in haystack for marker in _INVENTORY_EXCEL_HEADER_MARKERS):
|
||||
if "inventory" not in title and "onhand" not in title:
|
||||
raise RuntimeError("downloaded file is not valid Excel: missing inventory report headers")
|
||||
finally:
|
||||
workbook.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))
|
||||
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
|
||||
_validate_inventory_excel(dest)
|
||||
return dest
|
||||
|
||||
|
||||
@@ -3816,6 +3997,8 @@ def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dic
|
||||
warehouse_id = str(source.get("warehouse_id") or source.get("warehouse_code") or "WH")
|
||||
dest = drop_dir / _batch_download_name(run_no, source_code, warehouse_id, suffix=suffix)
|
||||
download.save_as(str(dest))
|
||||
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
|
||||
_validate_inventory_excel(dest)
|
||||
return dest
|
||||
|
||||
|
||||
@@ -4509,6 +4692,7 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
_configure_file_logging()
|
||||
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")
|
||||
|
||||
Reference in new issue
Block a user