feat(shipping-notice): 新增库存快照管理与RPA批量导出功能

This commit is contained in:
hugo committed 2026-07-08 08:59:08 +08:00
1 parent fc694a8f43
commit d54f51ddc3
48 files changed
+4970 -543

No files matched your search

+18 -1
View File
@@ -6,7 +6,7 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
| 环境变量 | 用途 |
|---------|------|
| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{task_no}.json`,RPA 读取后导库存 |
| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{task_no}.json` 或 `inventory_export_batch_{run_no}.json`,RPA 读取后导库存 |
| `FREIGHT_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest |
| `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` |
| `FREIGHT_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel |
@@ -77,6 +77,23 @@ python scripts/rpa/freight_rpa_worker.py
| `dsv360` | 打开 DSV 360,进入 Reports / Program / Inventory 报表并下载 |
| `crane_footprint` | 打开 Crane FootPrint On Hand Details Query,选择 Owner/Project/Warehouse 后下载 |
### 批量库存导出(`inventory_export_batch`)
定时排程或后台预热会写入 `inventory_export_batch_{run_no}.json`,字段示例:
```json
{
"action": "inventory_export_batch",
"run_no": "RUN20260707030000",
"trigger_type": "scheduled",
"inventory_sources": [{ "source_code": "DSV360_AWSDU", "source_type": "dsv360", "warehouse_id": "AWSDU" }]
}
```
Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,**Crane 一次登录**循环各 Warehouse;完成后回调 `POST /api/shipping-notice/rpa/inventory-batch-ready`。
库存源定义见 `backend/config/shipping_inventory_sources.json`(新增 Warehouse 只改 JSON)。
页面控件如果默认可见文本无法稳定点击,可通过环境变量覆盖 selector:
| 环境变量 | 用途 |
+226
View File
@@ -0,0 +1,226 @@
"""
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。
逻辑:复用 worker 批量导出循环(一次登录 + reset 入口),不依赖 HXOPS callback。
场景:
warehouse — 同一 source_code / 同一 3lv 报表,仅 Warehouse 参数变化
source_code — 三个不同 source_code(JSON 中独立配置项)
用法:
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py warehouse
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py source_code
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_batch_smoke.py all
"""
from __future__ import annotations
import importlib.util
import json
import os
import shutil
import sys
import tempfile
import time
import traceback
from copy import deepcopy
from datetime import datetime
from pathlib import Path
from typing import Any
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _load_worker():
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _load_export_smoke_helpers():
module_path = _repo_root() / "scripts" / "rpa" / "dsv_export_smoke.py"
spec = importlib.util.spec_from_file_location("dsv_export_smoke_batch", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _with_warehouse(source: dict[str, Any], warehouse: str, *, keep_source_code: bool) -> dict[str, Any]:
"""
克隆 source 并替换 Warehouse 参数与 query。
keep_source_code=True 时用于「同 source、仅 Warehouse 变化」场景。
"""
cloned = deepcopy(source)
wh = str(warehouse).strip()
if not keep_source_code:
cloned["source_code"] = f"DSV360_AWSBI_{wh}"
cloned["warehouse_id"] = wh
cloned["warehouse_code"] = wh
query = dict(cloned.get("query") or {})
query["warehouse_code"] = wh
cloned["query"] = query
parameters = []
for item in cloned.get("parameters") or []:
if not isinstance(item, dict):
continue
param = dict(item)
if str(param.get("name") or "").lower() == "warehouse":
param["values"] = [wh]
parameters.append(param)
cloned["parameters"] = parameters
return cloned
def _build_warehouse_scenario_sources() -> list[dict[str, Any]]:
"""场景 1:同一 source_code,3lv 报表不变,仅 Warehouse 下拉值变化。"""
helper = _load_export_smoke_helpers()
base = helper._build_source_from_config("DSV360_AWSBI_BYAWSCMH01")
warehouses = ["BYAWSATL01", "BYAWSCMH01", "BYAWSAVP01"]
return [_with_warehouse(base, wh, keep_source_code=True) for wh in warehouses]
def _build_source_code_scenario_sources() -> list[dict[str, Any]]:
"""场景 2:三个独立 source_code。"""
helper = _load_export_smoke_helpers()
codes = [
"DSV360_AWSBI_BYAWSATL01",
"DSV360_AWSBI_BYAWSCMH01",
"DSV360_AWSBI_BYAWSAVP01",
]
return [helper._build_source_from_config(code) for code in codes]
def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]], drop_dir: Path) -> list[dict[str, Any]]:
"""
在同一 DSV session 内连续导出多份库存。
核心逻辑:与 _handle_inventory_batch_trigger 浏览器分支一致,但不 POST callback。
"""
run_no = f"BATCH-SMOKE-{scenario.upper()}-{datetime.now().strftime('%Y%m%d%H%M%S')}"
trigger = {"run_no": run_no, "task_no": run_no}
entry_url = str((sources[0] or {}).get("entry_url") or "https://s360.dbschenker.com/").strip()
results: list[dict[str, Any]] = []
started = time.monotonic()
playwright = context = runtime_profile_dir = None
try:
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
export_fn = worker._export_dsv_inventory_source
previous_source: dict[str, Any] | None = None
for index, source in enumerate(sources):
code = str(source.get("source_code") or "")
wh = str(source.get("warehouse_id") or source.get("warehouse_code") or "")
print(
f"[batch-smoke] scenario={scenario} step={index + 1}/{len(sources)} "
f"source_code={code} warehouse={wh}"
)
try:
skip_navigation = worker._prepare_dsv_batch_export_step(
page,
entry_url,
previous_source,
source,
index=index,
)
download = export_fn(page, trigger, source, skip_navigation=skip_navigation)
out_file = worker._save_batch_download(download, drop_dir, run_no, source)
size_kb = out_file.stat().st_size / 1024
results.append(
{
"source_code": code,
"warehouse_id": wh,
"success": True,
"file_path": str(out_file),
"size_kb": round(size_kb, 1),
}
)
print(f"[batch-smoke] OK {code}/{wh} -> {out_file.name} ({size_kb:.1f} KB)")
except Exception as exc:
results.append(
{
"source_code": code,
"warehouse_id": wh,
"success": False,
"error_message": str(exc),
}
)
print(f"[batch-smoke] FAIL {code}/{wh}: {exc}", file=sys.stderr)
traceback.print_exc()
previous_source = source
finally:
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
if runtime_profile_dir is not None:
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
elapsed_s = int(time.monotonic() - started)
ok = sum(1 for item in results if item.get("success"))
print(
f"[batch-smoke] scenario={scenario} done success={ok}/{len(results)} "
f"elapsed={elapsed_s}s drop_dir={drop_dir}"
)
return results
def _run_scenario(worker: Any, scenario: str) -> int:
if scenario == "warehouse":
sources = _build_warehouse_scenario_sources()
elif scenario == "source_code":
sources = _build_source_code_scenario_sources()
else:
raise ValueError(f"unknown scenario: {scenario}")
drop_dir = Path(tempfile.mkdtemp(prefix=f"dsv_batch_{scenario}_"))
print(f"[batch-smoke] scenario={scenario} exports={len(sources)} drop_dir={drop_dir}")
for index, source in enumerate(sources, start=1):
print(
f"[batch-smoke] plan[{index}] source_code={source.get('source_code')} "
f"warehouse={source.get('warehouse_id')} "
f"query={json.dumps(source.get('query') or {}, ensure_ascii=False)}"
)
results = _run_batch_exports(worker, scenario, sources, drop_dir)
if not results or not all(item.get("success") for item in results):
return 2
return 0
def main() -> int:
scenario_arg = (sys.argv[1] if len(sys.argv) > 1 else "all").strip().lower()
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true")
os.environ.setdefault(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile",
)
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
worker = _load_worker()
if not worker._env("FREIGHT_RPA_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"):
print("[batch-smoke] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD")
return 1
scenarios = ["warehouse", "source_code"] if scenario_arg == "all" else [scenario_arg]
exit_code = 0
for scenario in scenarios:
if scenario not in {"warehouse", "source_code"}:
print(f"[batch-smoke] 未知场景: {scenario}(可用 warehouse / source_code / all)")
return 1
print(f"\n[batch-smoke] ===== 开始场景: {scenario} =====")
code = _run_scenario(worker, scenario)
exit_code = max(exit_code, code)
return exit_code
if __name__ == "__main__":
sys.exit(main())
+148
View File
@@ -0,0 +1,148 @@
"""
scripts/rpa/dsv_export_smoke.py
用途:本地手动验证指定 DSV 360 库存源(默认 BYAWSATL01)的浏览器导出全流程。
依赖:Playwright(msedge)、FREIGHT_RPA_DSV_USERNAME/PASSWORD、backend/config/shipping_inventory_sources.json。
逻辑:加载 rpa_inventory_source → _download_inventory_with_browser → 输出 Excel 路径。
用法(仓库根目录):
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_smoke.py
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_export_smoke.py DSV360_AWSBI_BYAWSATL01
"""
from __future__ import annotations
import importlib.util
import json
import os
import sys
import tempfile
import traceback
from datetime import datetime
from pathlib import Path
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _load_worker():
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_export_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _build_source_from_config(source_code: str) -> dict:
"""
从 JSON 配置构造 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"))
raw = next(
(item for item in (payload.get("sources") or []) if str(item.get("source_code") or "").upper() == source_code.upper()),
None,
)
if not raw:
raise RuntimeError(f"source_code not found in config: {source_code}")
navigation = dict(raw.get("navigation") or {})
parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)]
site = str(raw.get("site") or "dsv360").strip().lower()
warehouse_id = str(raw.get("warehouse_id") or raw.get("warehouse_code") or "").strip()
query: dict[str, object] = {}
if site == "dsv360":
for key in ("program_group", "program_label", "report_group", "report_name"):
if navigation.get(key):
query[key] = navigation[key]
if warehouse_id:
query["warehouse_code"] = warehouse_id
for parameter in parameters:
name = str(parameter.get("name") or "").strip()
mode = str(parameter.get("mode") or "single").strip().lower()
values = [str(v).strip() for v in (parameter.get("values") or []) if str(v).strip()]
if not values:
continue
if mode == "multi_text":
joined = str(parameter.get("joiner") or ",").join(values)
if name.lower() == "owner":
query["owner_code"] = joined
elif name.lower() == "putawayzone":
query["putaway_zone"] = joined
elif name.lower() == "warehouse":
query["warehouse_code"] = joined
continue
value = values[0]
if name.lower() == "owner":
query["owner_code"] = value
elif name.lower() == "putawayzone":
query["putaway_zone"] = value
elif name.lower() == "warehouse":
query["warehouse_code"] = value
return {
"source_code": str(raw.get("source_code") or source_code).upper(),
"source_type": "dsv360" if site == "dsv360" else site,
"display_name": str(raw.get("display_name") or source_code),
"enabled": bool(raw.get("enabled", True)),
"entry_url": str(raw.get("entry_url") or "https://s360.dbschenker.com/"),
"warehouse_id": warehouse_id,
"warehouse_code": str(raw.get("warehouse_code") or warehouse_id),
"navigation": navigation,
"parameters": parameters,
"query": query,
}
def main() -> int:
source_code = (sys.argv[1] if len(sys.argv) > 1 else "DSV360_AWSBI_BYAWSATL01").strip().upper()
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true")
os.environ.setdefault(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile",
)
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
worker = _load_worker()
if not worker._env("FREIGHT_RPA_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"):
print("[export-smoke] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD")
return 1
source = _build_source_from_config(source_code)
task_no = f"SIF-SMOKE-{datetime.now().strftime('%Y%m%d%H%M%S')}"
trigger = {
"action": "inventory_export",
"task_no": task_no,
"requested_at": datetime.utcnow().isoformat(),
"mode": "smoke",
"attempt": 1,
"rpa_inventory_source": source,
}
drop_dir = Path(tempfile.mkdtemp(prefix=f"dsv_export_{source_code.lower()}_"))
print(f"[export-smoke] source={source_code} warehouse={source.get('warehouse_id')}")
print(f"[export-smoke] query={json.dumps(source.get('query') or {}, ensure_ascii=False)}")
print(f"[export-smoke] drop_dir={drop_dir}")
print("[export-smoke] 正在打开浏览器执行登录 + 报表导出(预计 3~8 分钟)…")
try:
out_file = worker._download_inventory_with_browser(trigger, drop_dir)
size_kb = out_file.stat().st_size / 1024
print(f"[export-smoke] SUCCESS — {out_file} ({size_kb:.1f} KB)")
return 0
except Exception as exc:
print(f"[export-smoke] FAILED — {exc}")
traceback.print_exc()
print("[export-smoke] FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true,浏览器保持打开以便排查。")
return 2
if __name__ == "__main__":
sys.exit(main())
+100
View File
@@ -0,0 +1,100 @@
"""
scripts/rpa/dsv_login_smoke.py
用途:本地手动验证 DSV 360 自动登录(含密码方式第二步、首页 ready)。
依赖:Playwright、FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD。
逻辑:打开可见浏览器 → _ensure_dsv_session → 保持窗口供人工观察,按 Enter 关闭。
用法(仓库根目录):
$env:FREIGHT_RPA_HEADLESS = "false"
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_login_smoke.py
"""
from __future__ import annotations
import importlib.util
import os
import shutil
import sys
import tempfile
import traceback
from pathlib import Path
def _load_worker():
repo_root = Path(__file__).resolve().parents[2]
module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_smoke", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main() -> int:
os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false")
os.environ.setdefault("FREIGHT_RPA_MOCK", "false")
os.environ.setdefault(
"FREIGHT_RPA_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile",
)
# Playwright 自带 Chromium 未安装时,回退到本机 Edge(Windows 开发机常见情况)。
if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"):
os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge")
worker = _load_worker()
username = worker._env("FREIGHT_RPA_DSV_USERNAME")
password = worker._env("FREIGHT_RPA_DSV_PASSWORD")
if not username or not password:
print("[smoke] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD,请先配置环境变量。")
return 1
drop_dir = Path(tempfile.mkdtemp(prefix="dsv_smoke_drop_"))
playwright = context = runtime_profile_dir = None
entry_url = "https://s360.dbschenker.com/"
print(f"[smoke] headless={worker._env('FREIGHT_RPA_HEADLESS', 'false')}")
print(f"[smoke] user={username[:3]}*** entry={entry_url}")
print("[smoke] 正在打开浏览器并执行 DSV 自动登录…")
try:
playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir)
worker._ensure_dsv_session(page, entry_url)
print(f"[smoke] SUCCESS — DSV session ready, url={page.url}")
print("[smoke] 请在浏览器中确认 Reports 导航可见。按 Enter 关闭浏览器…")
try:
input()
except EOFError:
import time
print("[smoke] 非交互终端,保持浏览器 300 秒后自动关闭。")
time.sleep(300)
return 0
except Exception as exc:
print(f"[smoke] FAILED — {exc}")
traceback.print_exc()
print("[smoke] 浏览器将保持打开 120 秒以便排查,按 Enter 提前关闭…")
try:
input()
except EOFError:
import time
time.sleep(120)
return 2
finally:
if context is not None:
try:
context.close()
except Exception:
pass
if playwright is not None:
try:
playwright.stop()
except Exception:
pass
if runtime_profile_dir is not None:
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
shutil.rmtree(drop_dir, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())
+407
View File
@@ -0,0 +1,407 @@
"""
scripts/rpa/dsv_report_parameters.py
用途:填充 DSV 360 SSRS ReportViewer 报表参数(Owner / PutawayZone / Warehouse)。
依赖:Playwright Page/Frame;由 freight_rpa_worker._fill_dsv_filter_if_needed 委托调用。
逻辑:识别 multi-value checkbox 与 ValidValue select,在 report iframe 内操作并等待控件启用。
"""
from __future__ import annotations
import json
import sys
import time
from typing import Any, Callable
# BYAWSATL01 等 3lv 报表在 SSRS 中的默认控件 ID(与页面源码一致)。
_DSV_REPORT_PARAM_DEFAULTS: dict[str, dict[str, str]] = {
"Owner": {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl03_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl03_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl03_divDropDown",
},
"PutawayZone": {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl07_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl07_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl07_divDropDown",
},
"Warehouse": {
"control": "select",
"selector": "#ReportViewerMain_ctl08_ctl17_ddValue",
},
}
def _iter_dsv_report_roots(page: Any) -> list[Any]:
"""返回包含 ReportViewerMain 的 frame;找不到时回退到全部 roots。"""
matched: list[Any] = []
for frame in getattr(page, "frames", []):
try:
if frame.locator("#ReportViewerMain").count() > 0:
matched.append(frame)
except Exception:
continue
if matched:
return matched
return [page, *list(getattr(page, "frames", []))]
def _find_locator(page: Any, selector: str) -> tuple[Any | None, Any | None]:
"""在 report roots 中查找 selector 对应的 locator。"""
for root in _iter_dsv_report_roots(page):
try:
locator = root.locator(selector).first
locator.wait_for(state="attached", timeout=1_000)
return root, locator
except Exception:
continue
return None, None
def _warehouse_select_state(locator: Any, value: str) -> dict[str, Any]:
"""探测 Warehouse select 是否已有目标 option、是否已解除 disabled。"""
try:
result = locator.evaluate(
"""
(select, target) => {
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim().toLowerCase();
const wanted = normalize(target);
const options = Array.from(select.options || []);
const hasTarget = options.some((item) => normalize(item.textContent) === wanted);
const realOptions = options.filter((item) => {
const label = normalize(item.textContent);
return label && label !== '<select a value>' && !label.includes('select a value');
}).length;
return {
hasTarget,
enabled: !select.disabled && !select.classList.contains('aspNetDisabled'),
optionCount: options.length,
realOptionCount: realOptions,
};
}
""",
value,
)
if isinstance(result, dict):
return result
except Exception:
pass
return {"hasTarget": False, "enabled": False, "optionCount": 0, "realOptionCount": 0}
def _apply_select_value_via_script(locator: Any, value: str) -> bool:
"""通过脚本写入 select 值;SSRS 常在 option 已加载但仍保持 aspNetDisabled。"""
try:
return bool(
locator.evaluate(
"""
(select, target) => {
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
const wanted = normalize(target).toLowerCase();
const option = Array.from(select.options).find(
(item) => normalize(item.textContent).toLowerCase() === wanted
);
if (!option) return false;
select.disabled = false;
select.classList.remove('aspNetDisabled');
select.removeAttribute('disabled');
select.value = option.value;
select.dispatchEvent(new Event('input', { bubbles: true }));
select.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
""",
value,
)
)
except Exception:
return False
def _wait_for_warehouse_select_ready(locator: Any, value: str, *, timeout_ms: int) -> tuple[bool, int, dict[str, Any]]:
"""
等待 Warehouse 下拉出现目标 option。
核心逻辑:SSRS 报表参数页会先渲染 Owner/PutawayZone 默认值,Warehouse 的 option 列表
由 ReportViewer 异步拉取;此期间 select 长期保持 aspNetDisabled,肉眼像“卡住不能选”。
"""
started_at = time.monotonic()
deadline = started_at + (timeout_ms / 1000)
last_log_at = 0.0
last_state: dict[str, Any] = {}
while time.monotonic() < deadline:
last_state = _warehouse_select_state(locator, value)
if last_state.get("hasTarget"):
elapsed_ms = int((time.monotonic() - started_at) * 1000)
return True, elapsed_ms, last_state
now = time.monotonic()
if now - last_log_at >= 2.0:
print(
"[dsv-filter] waiting warehouse options "
f"target={value!r} optionCount={last_state.get('optionCount')} "
f"realOptionCount={last_state.get('realOptionCount')} enabled={last_state.get('enabled')}"
)
last_log_at = now
time.sleep(0.2)
elapsed_ms = int((time.monotonic() - started_at) * 1000)
return False, elapsed_ms, last_state
def _wait_until_enabled(locator: Any, *, timeout_ms: int = 15_000) -> bool:
"""等待 SSRS 控件从 aspNetDisabled 变为可操作。"""
deadline = time.monotonic() + (timeout_ms / 1000)
while time.monotonic() < deadline:
try:
disabled = locator.evaluate(
"(node) => Boolean(node.disabled || node.classList.contains('aspNetDisabled'))"
)
if not disabled:
return True
except Exception:
pass
time.sleep(0.25)
return False
def _fill_input_via_script(root: Any, selector: str, value: str) -> bool:
"""
通过脚本解除 disabled 并写入文本框(Owner/PutawayZone 兜底)。
核心逻辑:ReportViewer 初始常把参数控件设为 aspNetDisabled,需先启用再赋值。
"""
try:
return bool(
root.evaluate(
"""
({ selector, value }) => {
const node = document.querySelector(selector);
if (!node) return false;
node.disabled = false;
node.removeAttribute('disabled');
node.classList.remove('aspNetDisabled');
node.readOnly = false;
node.removeAttribute('readonly');
node.value = value;
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
""",
{"selector": selector, "value": value},
)
)
except Exception:
return False
def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, timeout_ms: int) -> bool:
"""
填充 SSRS MultiValueParameterInputControl(Owner / PutawayZone)。
核心逻辑:展开 dropdown → 按 label 勾选/取消 checkbox → 关闭 dropdown。
"""
config = _DSV_REPORT_PARAM_DEFAULTS.get(label, {})
if config.get("control") != "multi_value":
return False
cleaned = [str(item).strip() for item in values if str(item).strip()]
if not cleaned:
return False
_, text_locator = _find_locator(page, config["text"])
if text_locator is not None:
try:
current = str(text_locator.input_value(timeout=2_000) or "").strip()
if current and all(item in current for item in cleaned):
print(f"[dsv-filter] {label} already set text={current!r}")
return True
except Exception:
pass
root, toggle = _find_locator(page, config["toggle"])
if root is not None and toggle is not None:
try:
toggle.click(timeout=timeout_ms, force=True)
time.sleep(0.4)
except Exception:
pass
root, _ = _find_locator(page, config["dropdown"])
if root is None:
return False
desired = {item.casefold() for item in cleaned}
try:
adjusted = root.evaluate(
"""
({ dropdownSelector, desiredValues, restrictToDesired }) => {
const dropdown = document.querySelector(dropdownSelector);
if (!dropdown) return false;
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
const labels = Array.from(dropdown.querySelectorAll('label'));
let changed = false;
for (const labelNode of labels) {
const text = normalize(labelNode.textContent);
if (!text || text === '(Select All)') continue;
let checkbox = null;
const htmlFor = labelNode.getAttribute('for');
if (htmlFor) {
checkbox = document.getElementById(htmlFor);
}
if (!checkbox) {
checkbox = labelNode.previousElementSibling;
}
if (!checkbox || checkbox.type !== 'checkbox') continue;
const shouldCheck = desiredValues.includes(text.toLowerCase());
if (restrictToDesired) {
if (checkbox.checked !== shouldCheck) {
checkbox.click();
changed = true;
}
} else if (shouldCheck && !checkbox.checked) {
checkbox.click();
changed = true;
}
}
return changed || labels.length > 0;
}
""",
{
"dropdownSelector": config["dropdown"],
"desiredValues": list(desired),
"restrictToDesired": label == "PutawayZone",
},
)
if adjusted:
print(f"[dsv-filter] {label} multi_value checkboxes={cleaned!r}")
if toggle is not None:
try:
toggle.click(timeout=2_000, force=True)
except Exception:
pass
return True
except Exception as exc:
print(f"[dsv-filter] {label} multi_value checkbox failed: {exc}", file=sys.stderr)
joined = ", ".join(cleaned)
for root in _iter_dsv_report_roots(page):
if _fill_input_via_script(root, config["text"], joined):
print(f"[dsv-filter] {label} multi_value script text={joined!r}")
return True
return False
def _fill_select_parameter(page: Any, label: str, value: str, selector: str, *, timeout_ms: int) -> bool:
"""
填充 SSRS ValidValueParameterInputControl(Warehouse 等原生 select)。
核心逻辑:目标 option 出现在 DOM 后即用脚本赋值,不必等 Playwright 可见的 enabled 状态。
"""
_, locator = _find_locator(page, selector)
if locator is None:
return False
wait_cap_ms = min(timeout_ms, 45_000) if label == "Warehouse" else timeout_ms
ready, waited_ms, state = _wait_for_warehouse_select_ready(locator, value, timeout_ms=wait_cap_ms)
if ready and _apply_select_value_via_script(locator, value):
mode = "script-after-options" if not state.get("enabled") else "script-after-enabled"
print(
f"[dsv-filter] {label} select {mode} value={value!r} "
f"waitedMs={waited_ms} selector={selector!r}"
)
return True
if waited_ms >= 500:
print(
f"[dsv-filter] {label} warehouse options not ready after {waited_ms}ms; "
f"fallback enabled-wait state={state!r}"
)
enable_started = time.monotonic()
_wait_until_enabled(locator, timeout_ms=min(wait_cap_ms, 15_000))
enable_wait_ms = int((time.monotonic() - enable_started) * 1000)
if enable_wait_ms >= 500:
print(f"[dsv-filter] {label} enabled-waitMs={enable_wait_ms}")
try:
locator.select_option(label=value, timeout=min(timeout_ms, 10_000))
print(f"[dsv-filter] {label} select_option label={value!r} selector={selector!r}")
return True
except Exception:
pass
if _apply_select_value_via_script(locator, value):
print(f"[dsv-filter] {label} select script fallback value={value!r} selector={selector!r}")
return True
return False
def fill_dsv_filter_if_needed(
page: Any,
selector_env: str,
label: str,
value: str | None,
*,
env: Callable[[str, str], str],
browser_timeout_ms: Callable[[], int],
debug_stage: Callable[..., None] | None = None,
) -> None:
"""
按 ReportViewer 控件类型填充 DSV 报表参数。
核心逻辑:优先使用 JSON/页面默认 selector;Warehouse 走 select_option,Owner/PutawayZone 走 checkbox。
"""
text = str(value or "").strip()
if not text:
return
def _debug(stage: str, target: str) -> None:
if debug_stage is not None:
debug_stage(page, stage, target_text=target)
try:
if page.get_by_text(text, exact=False).first.is_visible(timeout=1_500):
print(f"[dsv-filter] {label} already visible text={text!r}")
_debug(f"filter-skip-{label.lower()}", text)
return
except Exception:
pass
timeout_ms = browser_timeout_ms()
defaults = _DSV_REPORT_PARAM_DEFAULTS.get(label, {})
custom_selector = str(env(selector_env) or "").strip()
selector = custom_selector or defaults.get("selector") or defaults.get("text")
if not selector and not defaults:
print(f"[dsv] skip {label} filter; no selector configured")
_debug(f"filter-no-selector-{label.lower()}", text)
return
values = [part.strip() for part in text.split(",") if part.strip()] if label == "PutawayZone" else [text]
if defaults.get("control") == "multi_value" or label in {"Owner", "PutawayZone"}:
if _fill_multi_value_parameter(page, label, values, timeout_ms=timeout_ms):
_debug(f"filter-filled-{label.lower()}", text)
return
select_selector = custom_selector or defaults.get("selector", "")
if defaults.get("control") == "select" or label == "Warehouse" or select_selector.endswith("ddValue"):
if _fill_select_parameter(page, label, text, select_selector, timeout_ms=timeout_ms):
_debug(f"filter-filled-{label.lower()}", text)
return
print(f"[dsv-filter] filling {label} text={text!r} selector={selector!r}")
for root in _iter_dsv_report_roots(page):
if _fill_input_via_script(root, selector, text):
_debug(f"filter-filled-{label.lower()}", text)
return
# 最后回退:Playwright fill(适用于普通文本参数)
_, locator = _find_locator(page, selector)
if locator is not None:
_wait_until_enabled(locator, timeout_ms=timeout_ms)
try:
locator.fill(text, timeout=timeout_ms)
_debug(f"filter-filled-{label.lower()}", text)
return
except Exception as exc:
print(f"[dsv-filter] {label} fill fallback failed: {exc}", file=sys.stderr)
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
_debug(f"filter-failed-{label.lower()}", text)
File diff suppressed because it is too large. Load diff
+230 -13
View File
@@ -1,13 +1,130 @@
<#
scripts/start_local.ps1
用途:本地一键启动 HXOPS 前后端与后台 worker。
依赖:backend venv、frontend npm、.env.shared / .env.dev(worker 与 RPA 读取)。
逻辑:先停止本仓库遗留的 backend/worker/frontend 进程并释放 5052/8881 端口,再分别在新 PowerShell 窗口启动各服务。
#>
param(
[ValidateSet("sqlite", "postgres")]
[string]$DbMode = "sqlite",
[string]$DatabaseUrl = "",
[switch]$SkipInstall,
[switch]$SkipWorker
[switch]$SkipWorker,
[switch]$SkipRpaWorker
)
$ErrorActionPreference = "Stop"
$script:LocalFrontendPort = 8881
$script:LocalBackendPort = 5052
function Stop-ProcessSafe {
param(
[int]$ProcessId,
[string]$Label
)
if ($ProcessId -le 0) {
return
}
$proc = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue
if (-not $proc) {
return
}
Write-Host "[$Label] stopping PID $ProcessId ($($proc.ProcessName))" -ForegroundColor Yellow
Stop-Process -Id $ProcessId -Force -ErrorAction SilentlyContinue
}
function Stop-PortListeners {
param(
[int]$Port,
[string]$Label
)
$pids = @(
Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty OwningProcess -Unique
)
foreach ($processId in $pids) {
Stop-ProcessSafe -ProcessId $processId -Label $Label
}
}
function Stop-StaleHxopsPythonProcesses {
param(
[string]$RepoRoot,
[string]$BackendPath
)
$patterns = @(
[regex]::Escape((Join-Path $BackendPath "run.py")),
[regex]::Escape((Join-Path $BackendPath "worker_kb.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")),
[regex]::Escape((Join-Path $RepoRoot "scripts\rpa\freight_rpa_worker.py"))
)
Get-CimInstance Win32_Process -Filter "Name='python.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
$cmd = $_.CommandLine
if ([string]::IsNullOrWhiteSpace($cmd)) {
return
}
foreach ($pattern in $patterns) {
if ($cmd -match $pattern) {
Stop-ProcessSafe -ProcessId $_.ProcessId -Label "hxops-python"
return
}
}
}
}
function Stop-StaleHxopsFrontendProcesses {
param([string]$FrontendPath)
$frontendPattern = [regex]::Escape($FrontendPath)
Get-CimInstance Win32_Process -Filter "Name='node.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
$cmd = $_.CommandLine
if ([string]::IsNullOrWhiteSpace($cmd)) {
return
}
if ($cmd -match $frontendPattern -and $cmd -match 'vite') {
Stop-ProcessSafe -ProcessId $_.ProcessId -Label "hxops-frontend"
}
}
}
function Stop-LocalHxopsStack {
param(
[string]$RepoRoot,
[string]$BackendPath,
[string]$FrontendPath
)
Write-Host "[cleanup] stopping stale hxops local processes..." -ForegroundColor Yellow
Stop-StaleHxopsPythonProcesses -RepoRoot $RepoRoot -BackendPath $BackendPath
Stop-StaleHxopsFrontendProcesses -FrontendPath $FrontendPath
Stop-PortListeners -Port $script:LocalBackendPort -Label "backend-port"
Stop-PortListeners -Port $script:LocalFrontendPort -Label "frontend-port"
# Vite 端口被占用时可能漂移到 8882+,一并清理本机 node 监听
for ($port = $script:LocalFrontendPort + 1; $port -le ($script:LocalFrontendPort + 10); $port++) {
$pids = @(
Get-NetTCPConnection -LocalPort $port -State Listen -ErrorAction SilentlyContinue |
Where-Object { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName -eq 'node' } |
Select-Object -ExpandProperty OwningProcess -Unique
)
foreach ($processId in $pids) {
Stop-ProcessSafe -ProcessId $processId -Label "stale-vite-$port"
}
}
Start-Sleep -Milliseconds 800
}
function Test-CommandExists {
param([string]$Name)
return $null -ne (Get-Command $Name -ErrorAction SilentlyContinue)
@@ -133,6 +250,62 @@ function Start-BackendWindow {
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
function Get-DatabaseUrlExport {
param(
[string]$Mode,
[string]$DbUrl
)
if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) {
$escaped = $DbUrl.Replace("'", "''")
return "`$env:DATABASE_URL='$escaped'; "
}
return ""
}
function Get-DotEnvExportPrefix {
param([string[]]$Paths)
$exports = @()
foreach ($path in $Paths) {
if (-not (Test-Path $path)) {
continue
}
foreach ($line in Get-Content $path) {
if ($line -match '^\s*#' -or $line -match '^\s*$') {
continue
}
if ($line -match '^\s*([^=]+)=(.*)$') {
$name = $matches[1].Trim()
$value = $matches[2].Trim()
if ($value.Length -ge 2 -and (
($value.StartsWith('"') -and $value.EndsWith('"')) -or
($value.StartsWith("'") -and $value.EndsWith("'"))
)) {
$value = $value.Substring(1, $value.Length - 2)
}
$escaped = $value.Replace("'", "''")
$exports += "`$env:$name='$escaped';"
}
}
}
return ($exports -join ' ')
}
function Start-WorkerWindow {
param(
[string]$Title,
[string]$WorkingDirectory,
[string]$Command,
[string]$EnvPrefix = ""
)
$cmd = "$EnvPrefix Set-Location '$WorkingDirectory'; Write-Host '[$Title] started' -ForegroundColor Cyan; $Command"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
function Start-KbWorkerWindow {
param(
[string]$BackendPath,
@@ -140,14 +313,42 @@ function Start-KbWorkerWindow {
[string]$DbUrl
)
$dbExport = ""
if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) {
$escaped = $DbUrl.Replace("'", "''")
$dbExport = "`$env:DATABASE_URL='$escaped'; "
}
Start-WorkerWindow `
-Title "kb-worker" `
-WorkingDirectory $BackendPath `
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-Command ".\venv\Scripts\python.exe .\worker_kb.py"
}
$cmd = "$dbExport Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\worker_kb.py"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
function Start-ShippingWorkerWindow {
param(
[string]$BackendPath,
[string]$Mode,
[string]$DbUrl
)
Start-WorkerWindow `
-Title "shipping-worker" `
-WorkingDirectory $BackendPath `
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-Command ".\venv\Scripts\python.exe .\workers\worker_shipping_notice.py"
}
function Start-FreightRpaWorkerWindow {
param(
[string]$RepoRoot,
[string]$BackendPath,
[string[]]$EnvFiles
)
$envPrefix = Get-DotEnvExportPrefix -Paths $EnvFiles
$envPrefix += " `$env:HXOPS_API_BASE='http://127.0.0.1:5052'; `$env:FREIGHT_RPA_MOCK='true';"
Start-WorkerWindow `
-Title "freight-rpa-worker" `
-WorkingDirectory $RepoRoot `
-EnvPrefix $envPrefix `
-Command "& '$BackendPath\venv\Scripts\python.exe' .\scripts\rpa\freight_rpa_worker.py"
}
function Start-FrontendWindow {
@@ -169,21 +370,37 @@ $doInstall = -not $SkipInstall.IsPresent
Write-Host "== HXOPS local startup ==" -ForegroundColor Green
Write-Host "mode: $DbMode" -ForegroundColor Green
Stop-LocalHxopsStack -RepoRoot $repoRoot -BackendPath $backendDir -FrontendPath $frontendDir
Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $DatabaseUrl -DoInstall $doInstall
Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall
$envFiles = @(
(Join-Path $repoRoot ".env.shared"),
(Join-Path $repoRoot ".env.dev"),
(Join-Path $repoRoot ".env.local")
)
$windowCount = 2
Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
if (-not $SkipWorker.IsPresent) {
Start-KbWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
Start-ShippingWorkerWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
$windowCount += 2
if (-not $SkipRpaWorker.IsPresent) {
Start-FreightRpaWorkerWindow -RepoRoot $repoRoot -BackendPath $backendDir -EnvFiles $envFiles
$windowCount += 1
}
}
Start-FrontendWindow -FrontendPath $frontendDir
$windowCount += 1
Write-Host ""
if ($SkipWorker.IsPresent) {
Write-Host "Started in two new PowerShell windows." -ForegroundColor Green
}
else {
Write-Host "Started in three new PowerShell windows." -ForegroundColor Green
Write-Host "Started in $windowCount new PowerShell windows." -ForegroundColor Green
if (-not $SkipWorker.IsPresent) {
Write-Host "Workers: kb-worker, shipping-worker$(if (-not $SkipRpaWorker.IsPresent) { ', freight-rpa-worker (mock)' })" -ForegroundColor Green
Write-Host "Schedule worker runs inside backend process (SCHEDULE_WORKER_ENABLED)." -ForegroundColor DarkGray
}
Write-Host "Frontend URL: http://127.0.0.1:8881" -ForegroundColor Green
Write-Host "Backend URL: http://127.0.0.1:5052" -ForegroundColor Green
Write-Host "Default local admin (sqlite/init scripts): admin / Hxit@54321" -ForegroundColor Green