chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑

This commit is contained in:
hugo committed 2026-08-17 19:56:51 +08:00
1 parent 5ef8329bd8
commit 4ec4e57005
183 files changed
+14653 -3936

No files matched your search

+6 -1
View File
@@ -66,6 +66,11 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,Profile 凭据主密钥使用
`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。部署文档和启动脚本只使用上述规范命名。
DSV 库存导出默认每次使用一次性浏览器 Profile。确认只运行单个对应环境 Worker 后,可在
`start_rpa_worker.ps1` 启动命令末尾增加 `-ReuseDsvSession`,使 DSV 专用
`dsv360_session` Profile 跨任务保留登录态;Crane 与上传任务仍不复用。不要同时启动两个
使用同一 WorkerRoot 的 Worker,浏览器会拒绝并发打开同一持久 Profile。
### DSV WMS Upload Tool
已确认 DSV 上传页为 `WMS Upload Tool > Upload`,页面有 `Browse` 文件选择入口和
@@ -1577,4 +1582,4 @@ Worker 按 `worker_connector_type + rpa_profile_code` 分组,确保同一 conn
发货 Excel 上传仍保留原 PoC 行为:`SHIPPING_NOTICE_RPA_WORKER_MOCK=false` 时不会自动上传,需后续实现上传 Driver 或接入 UiPath / Power Automate。
回调 Header:`X-Shipping-Tool-Key: <SHIPPING_NOTICE_TOOL_API_KEY>`。
回调 Header:`X-Shipping-Tool-Key: <SHIPPING_NOTICE_TOOL_API_KEY>`。
+33
View File
@@ -77,6 +77,27 @@ def _wait_for_dsv_app_after_login(
)
def _has_existing_dsv_portal_session(page: Any) -> bool:
"""
轻量判断当前页面是否已是有效 DSV Portal 首页。
核心逻辑:持久化 Browser Profile 恢复时,Portal 首页可能已可见,但旧登录流程仍先
等待用户名控件和认证页渲染。仅当已离开 auth 域且首页业务标记出现时短路;Reports
菜单是否可点击仍由后续首页就绪校验负责,避免把认证中转页误判为已登录。
"""
try:
current_url = str(page.url or "").lower()
except Exception:
return False
if "s360.dbschenker.com" not in current_url or "auth.dbschenker.com" in current_url:
return False
try:
body = str(page.locator("body").inner_text(timeout=1_000) or "").lower()
except Exception:
return False
return any(marker in body for marker in ("home favorites", "recent reports", "favorites"))
def _maybe_auto_login_dsv(page: Any) -> None:
"""
DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。
@@ -111,6 +132,17 @@ def _maybe_auto_login_dsv(page: Any) -> None:
if not username or not password:
return
# [STEP 1] Profile 会话恢复优先于任何登录页等待。否则已在 Portal 首页时会白等
# username selector 的长超时,随后才迟到地发现 existing session。
if _has_existing_dsv_portal_session(page):
print("[dsv-login] existing portal session detected before auth probe")
_report_debug_event(
"E",
"freight_rpa_worker.py:_maybe_auto_login_dsv:existing_portal_session",
"[DEBUG] dsv portal session detected before auth flow",
_collect_dsv_reports_probe(page),
)
return
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=15_000) is not None:
print("[dsv-login] existing session detected")
# #region debug-point E:existing-session
@@ -391,3 +423,4 @@ def _maybe_auto_login_dsv(page: Any) -> None:
# 公开 API
maybe_auto_login_dsv = _maybe_auto_login_dsv
has_existing_dsv_portal_session = _has_existing_dsv_portal_session
+90 -2
View File
@@ -197,7 +197,53 @@ def _dsv_dropdown_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000)
return False
def _click_dsv_menu_item(page: Any, text: str, *, next_text: str = "") -> None:
def _try_dsv_menu_item_fast_path(page: Any, text: str, *, next_text: str = "") -> bool:
"""
尝试一次 DSV 菜单标准点击,并确认预期下级已展开。
核心逻辑:真实页面已验证的菜单通常可由精确文本一次 hover/click 打开;
仅在明确看到 next_text 后才返回成功,避免把点击事件已发送误当作层级已切换。
Args:
page: Playwright Page 对象。
text: 当前菜单文本。
next_text: 点击后应出现的下级文本;为空时只确认点击本身完成。
Returns:
bool: 下一级已确认出现或无需确认时为 True;其余情况为 False。
"""
for container in ("#report-mega-legacy", ".mega-dropdown-menu", ".dropdown-menu"):
try:
locator = page.locator(container).get_by_text(text, exact=True).first
locator.wait_for(state="visible", timeout=1_500)
locator.hover(timeout=1_000)
locator.click(timeout=1_500)
if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500):
return True
except Exception:
continue
return False
def _try_dsv_report_group_fast_path(page: Any, text: str, *, next_text: str = "") -> bool:
"""
尝试一次 Report Group 标准点击,并确认目标报表已展开。
核心逻辑:Report Group 使用精确文本,避免旧逻辑对多个宽泛 selector
分别等待十秒;失败时由兼容路径继续处理 hover 丢失等旧页面结构。
Args:
page: Playwright Page 对象。
text: Report Group 文本。
next_text: 点击后应出现的报表名称。
Returns:
bool: 报表文本确认出现时为 True,否则为 False。
"""
return _try_dsv_menu_item_fast_path(page, text, next_text=next_text)
def _click_dsv_menu_item_compat(page: Any, text: str, *, next_text: str = "") -> None:
"""
点击 DSV 级联菜单项,并在需要时确认下一级目标已经出现。
@@ -320,7 +366,7 @@ def _click_dsv_menu_item(page: Any, text: str, *, next_text: str = "") -> None:
raise RuntimeError(f"DSV menu item was not found: {text}")
def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> None:
def _click_dsv_report_group_compat(page: Any, text: str, *, next_text: str = "") -> None:
"""
点击 DSV Report Group,并在需要时确认目标报表已经出现在菜单中。
@@ -418,6 +464,48 @@ def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> Non
raise RuntimeError(f"DSV report group was not found: {text}")
def _click_dsv_menu_item(page: Any, text: str, *, next_text: str = "") -> None:
"""
点击 DSV 级联菜单,并在标准路径失败后回退全部兼容动作。
核心逻辑:先走一次精确文本 hover/click 快速路径;只有下一级没有被确认时,
才调用原有多 selector、多输入方式的兼容逻辑,兼顾性能和历史页面兼容性。
Args:
page: Playwright Page 对象。
text: 当前菜单文案。
next_text: 预期出现的下一级菜单文案。
"""
text = str(text or "").strip()
if not text:
raise RuntimeError("DSV menu item text is empty")
if _try_dsv_menu_item_fast_path(page, text, next_text=next_text):
print(f"[dsv-navigation] fast-path menu item selected target={text!r}")
return
_click_dsv_menu_item_compat(page, text, next_text=next_text)
def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> None:
"""
点击 DSV Report Group,并在标准路径失败后回退完整兼容链。
核心逻辑:快速路径确认报表名称已出现才结束;否则保留历史多动作策略,
防止旧页面的 hover 状态不稳定时降低导出成功率。
Args:
page: Playwright Page 对象。
text: Report Group 文案。
next_text: 预期出现的报表名称。
"""
text = str(text or "").strip()
if not text:
raise RuntimeError("DSV report group text is empty")
if _try_dsv_report_group_fast_path(page, text, next_text=next_text):
print(f"[dsv-navigation] fast-path report group selected target={text!r}")
return
_click_dsv_report_group_compat(page, text, next_text=next_text)
def _click_dsv_view_report(page: Any) -> None:
"""
点击 SSRS 参数页 View Report。
+149 -61
View File
@@ -26,6 +26,7 @@ from dsv_debug import (
debug_dsv_page_snapshot as _debug_dsv_page_snapshot,
debug_dsv_stage as _debug_dsv_stage,
emit_debug_event as _emit_debug_event,
report_dsv_chain_stage as _report_dsv_chain_stage,
report_debug_event as _report_debug_event,
)
from dsv_export_timeout_diagnostics import build_download_timeout_log as _build_download_timeout_log
@@ -1030,33 +1031,49 @@ def _ensure_dsv_session(page: Any, entry_url: str) -> None:
核心逻辑:登录后 home-not-ready 时,若 session 已在 entry 站点,回 entry 首页重试一次。
"""
if _is_dsv_session_active(page, entry_url):
print("[dsv] session already active on entry site, skip login")
if _is_dsv_in_report_navigation_context(page):
print("[dsv] session active but still in report context, goto entry portal home")
_goto_dsv_entry_url(page, entry_url)
_wait_for_dsv_home_ready(page, timeout_ms=30_000)
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
return
_goto_dsv_entry_url(page, entry_url)
home_not_ready_after_login = False
started_at = time.monotonic()
_report_dsv_chain_stage("session_prepare", "start")
try:
_maybe_auto_login_dsv(page)
except RuntimeError as exc:
if "home page was not ready" not in str(exc):
raise
home_not_ready_after_login = True
print("[dsv] home not ready after login, retry entry reset once", file=sys.stderr)
if _is_dsv_session_active(page, entry_url):
print("[dsv] session already active on entry site, skip login")
if _is_dsv_in_report_navigation_context(page):
print("[dsv] session active but still in report context, goto entry portal home")
_goto_dsv_entry_url(page, entry_url)
_wait_for_dsv_home_ready(page, timeout_ms=30_000)
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
_report_dsv_chain_stage("session_prepare", "end", started_at=started_at)
return
if home_not_ready_after_login:
if not _is_dsv_on_entry_site(page, entry_url):
raise RuntimeError("DSV home page was not ready after login")
_goto_dsv_entry_url(page, entry_url)
home_not_ready_after_login = False
try:
_maybe_auto_login_dsv(page)
except RuntimeError as exc:
if "home page was not ready" not in str(exc):
raise
home_not_ready_after_login = True
print("[dsv] home not ready after login, retry entry reset once", file=sys.stderr)
home_timeout_ms = 30_000 if home_not_ready_after_login else 60_000
_wait_for_dsv_home_ready(page, timeout_ms=home_timeout_ms)
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
if home_not_ready_after_login:
if not _is_dsv_on_entry_site(page, entry_url):
raise RuntimeError("DSV home page was not ready after login")
_goto_dsv_entry_url(page, entry_url)
home_timeout_ms = 30_000 if home_not_ready_after_login else 60_000
_wait_for_dsv_home_ready(page, timeout_ms=home_timeout_ms)
_wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000)
except RuntimeError as exc:
_report_dsv_chain_stage(
"session_prepare", "error", started_at=started_at, extra={"errorType": type(exc).__name__}
)
raise
except Exception as exc:
_report_dsv_chain_stage(
"session_prepare", "error", started_at=started_at, extra={"errorType": type(exc).__name__}
)
raise
else:
_report_dsv_chain_stage("session_prepare", "end", started_at=started_at)
def _reset_dsv_export_entry(page: Any, entry_url: str) -> None:
@@ -1148,57 +1165,96 @@ def _return_to_dsv_report_parameters(page: Any, report_name: str) -> None:
def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
"""从 portal 首页导航至目标报表参数页。"""
"""从 portal 首页导航至目标报表参数页,并记录完整导航耗时。"""
query = source.get("query") if isinstance(source.get("query"), dict) else {}
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
report_name = _dsv_report_name(source)
started_at = time.monotonic()
_report_dsv_chain_stage("report_navigation", "start", extra={"reportName": report_name})
try:
reports_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORTS_SELECTOR")
if reports_selector:
page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True)
else:
_click_dsv_reports_menu(page)
_wait_for_dsv_reports_open(page, timeout_ms=10_000)
reports_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORTS_SELECTOR")
if reports_selector:
page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True)
else:
_click_dsv_reports_menu(page)
_wait_for_dsv_reports_open(page, timeout_ms=10_000)
program_group = str(query.get("program_group") or navigation.get("program_group") or "").strip()
program_label = str(query.get("program_label") or navigation.get("program_label") or "").strip()
report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
program_group = str(query.get("program_group") or navigation.get("program_group") or "").strip()
program_label = str(query.get("program_label") or navigation.get("program_label") or "").strip()
report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
program_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PROGRAM_SELECTOR")
if program_selector:
page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
else:
if program_group and program_group != program_label:
_click_dsv_menu_item(page, program_group, next_text=program_label)
_click_dsv_menu_item(page, program_label, next_text=report_group)
program_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PROGRAM_SELECTOR")
if program_selector:
page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
else:
if program_group and program_group != program_label:
_click_dsv_menu_item(page, program_group, next_text=program_label)
_click_dsv_menu_item(page, program_label, next_text=report_group)
report_group_selector = _env("SHIPPING_NOTICE_RPA_WORKER_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, report_group, next_text=report_name)
report_group_selector = _env("SHIPPING_NOTICE_RPA_WORKER_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, report_group, next_text=report_name)
report_name_selector = _env("SHIPPING_NOTICE_RPA_WORKER_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, report_name)
report_name_selector = _env("SHIPPING_NOTICE_RPA_WORKER_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, report_name)
_wait_for_dsv_report_form_ready(page, report_name)
_wait_for_dsv_report_form_ready(page, report_name)
except Exception as exc:
_report_dsv_chain_stage(
"report_navigation", "error", started_at=started_at,
extra={"reportName": report_name, "errorType": type(exc).__name__},
)
raise
_report_dsv_chain_stage("report_navigation", "end", started_at=started_at, extra={"reportName": report_name})
return report_name
def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> Any:
"""参数页已就绪后:填参 → View Report → 等结果 → 导出 Excel。"""
_fill_report_parameters(page, source)
_click_dsv_view_report(page)
"""参数页已就绪后:填参 → View Report → 等结果 → 导出 Excel,并分别记录阶段耗时。"""
report_name = _dsv_report_name(source)
parameter_started_at = time.monotonic()
_report_dsv_chain_stage("report_parameter_fill", "start", extra={"reportName": report_name})
try:
page.wait_for_load_state("networkidle", timeout=min(_browser_timeout_ms(), 10_000))
except Exception:
pass
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
if not _dsv_report_has_inventory_data_rows(page):
raise NoInventoryDataError("DSV report has no inventory data")
_fill_report_parameters(page, source)
except Exception as exc:
_report_dsv_chain_stage(
"report_parameter_fill", "error", started_at=parameter_started_at,
extra={"reportName": report_name, "errorType": type(exc).__name__},
)
raise
_report_dsv_chain_stage(
"report_parameter_fill", "end", started_at=parameter_started_at, extra={"reportName": report_name}
)
execution_started_at = time.monotonic()
_report_dsv_chain_stage("report_execute_and_download", "start", extra={"reportName": report_name})
result_started_at = time.monotonic()
_report_dsv_chain_stage("report_result_ready", "start", extra={"reportName": report_name})
try:
_click_dsv_view_report(page)
# [STEP 1] DSV 页面会维持长连接;等待 networkidle 不能说明 SSRS 已可导出,
# 反而可能额外消耗十秒。直接等待现有的报表业务就绪条件。
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
if not _dsv_report_has_inventory_data_rows(page):
raise NoInventoryDataError("DSV report has no inventory data")
except Exception as exc:
_report_dsv_chain_stage(
"report_result_ready", "error", started_at=result_started_at,
extra={"reportName": report_name, "errorType": type(exc).__name__},
)
_report_dsv_chain_stage(
"report_execute_and_download", "error", started_at=execution_started_at,
extra={"reportName": report_name, "errorType": type(exc).__name__},
)
raise
_report_dsv_chain_stage(
"report_result_ready", "end", started_at=result_started_at, extra={"reportName": report_name}
)
download_dir = str(source.get("__download_dir") or "").strip()
baseline_names = set()
if download_dir:
@@ -1206,6 +1262,10 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
baseline_names = {path.name for path in Path(download_dir).iterdir() if path.is_file()}
except OSError:
baseline_names = set()
download_started_at = time.monotonic()
_report_dsv_chain_stage("excel_export_and_download", "start", extra={"reportName": report_name})
download_event_started_at = time.monotonic()
_report_dsv_chain_stage("excel_download_event", "start", extra={"reportName": report_name})
try:
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
_click_dsv_export_excel(page)
@@ -1251,8 +1311,36 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
f"using downloaded file from directory because Playwright download event timed out: "
f"{fallback_download.suggested_filename}",
)
_report_dsv_chain_stage(
"excel_export_and_download", "end", started_at=download_started_at,
extra={"reportName": report_name, "downloadMode": "directory_fallback"},
)
_report_dsv_chain_stage(
"report_execute_and_download", "end", started_at=execution_started_at,
extra={"reportName": report_name, "downloadMode": "directory_fallback"},
)
return fallback_download
_report_dsv_chain_stage(
"excel_export_and_download", "error", started_at=download_started_at,
extra={"reportName": report_name, "errorType": type(exc).__name__},
)
_report_dsv_chain_stage(
"report_execute_and_download", "error", started_at=execution_started_at,
extra={"reportName": report_name, "errorType": type(exc).__name__},
)
raise
_report_dsv_chain_stage(
"excel_download_event", "end", started_at=download_event_started_at,
extra={"reportName": report_name, "downloadMode": "playwright"},
)
_report_dsv_chain_stage(
"excel_export_and_download", "end", started_at=download_started_at,
extra={"reportName": report_name, "downloadMode": "playwright"},
)
_report_dsv_chain_stage(
"report_execute_and_download", "end", started_at=execution_started_at,
extra={"reportName": report_name, "downloadMode": "playwright"},
)
return download_info.value
+30 -1
View File
@@ -12,6 +12,7 @@ import json
import os
import socket
import sys
import threading
import time
import urllib.error
import urllib.request
@@ -24,6 +25,8 @@ from rpa_common import env as _env
_RUNTIME_STATUS = "idle"
_LAST_HEARTBEAT_MONO = 0.0
_DEFAULT_SENTINEL_NAME = ".hxops_rpa_shared_mount"
_HEARTBEAT_THREAD: threading.Thread | None = None
_HEARTBEAT_THREAD_LOCK = threading.Lock()
def set_worker_runtime_status(status: str) -> None:
@@ -184,6 +187,32 @@ def post_heartbeat(payload: dict[str, Any]) -> bool:
return False
def _start_heartbeat_request(payload: dict[str, Any]) -> bool:
"""
非阻塞地提交一次心跳 HTTP 请求。
核心逻辑:心跳仅用于 Worker 就绪观测,不能阻塞库存 Trigger 扫描;同一时刻最多
保留一条后台请求。若网络库在底层超时后仍未返回,后续周期跳过新请求而主循环照常继续。
Returns:
bool: 已启动新请求时为 True;已有未完成请求时为 False。
"""
global _HEARTBEAT_THREAD
with _HEARTBEAT_THREAD_LOCK:
if _HEARTBEAT_THREAD is not None and _HEARTBEAT_THREAD.is_alive():
print("[heartbeat] skipped: previous request still in progress", file=sys.stderr)
return False
thread = threading.Thread(
target=post_heartbeat,
args=(payload,),
name="shipping-rpa-heartbeat",
daemon=True,
)
_HEARTBEAT_THREAD = thread
thread.start()
return True
def maybe_send_heartbeat(
*,
trigger_dir: str | Path,
@@ -203,6 +232,6 @@ def maybe_send_heartbeat(
return last_sent_mono
write_shared_mount_sentinel(trigger_dir=trigger_dir)
payload = build_heartbeat_payload(trigger_dir=trigger_dir, drop_dir=drop_dir)
post_heartbeat(payload)
_start_heartbeat_request(payload)
_LAST_HEARTBEAT_MONO = now
return now
+122 -43
View File
@@ -19,6 +19,7 @@ Optional:
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=path/to/sample.xlsx
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE=false
SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge
SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
@@ -446,6 +447,22 @@ def _report_callback_failure(trigger_path: Path, failed_dir: Path, exc: Exceptio
_move_trigger(trigger_path, failed_dir, "callback failed")
def _close_batch_browser_resources(context: Any, playwright: Any, runtime_profile_dir: Path | None) -> None:
"""在正常完成或 Ctrl+C 中断后依序释放批量 RPA 浏览器资源。"""
try:
if context is not None:
context.close()
except BaseException as exc:
print(f"[browser] context close interrupted: {exc}", file=sys.stderr)
try:
if playwright is not None:
playwright.stop()
except BaseException as exc:
print(f"[browser] playwright stop interrupted: {exc}", file=sys.stderr)
if runtime_profile_dir is not None and _should_cleanup_browser_profile(runtime_profile_dir):
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
_INVENTORY_V2_REQUIRED_FIELDS = (
"schema_version", "callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
"lease_token", "candidate_set_id", "execution_id", "gate_id",
@@ -530,36 +547,48 @@ def _validate_inventory_excel(path: Path) -> None:
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)")
started_at = time.monotonic()
try:
from openpyxl import load_workbook
except ImportError as exc:
raise RuntimeError("openpyxl required to validate inventory Excel") from exc
size = path.stat().st_size
if size < _INVENTORY_EXCEL_MIN_BYTES:
raise RuntimeError(f"downloaded inventory Excel is too small ({size} bytes)")
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:
from openpyxl import load_workbook
except ImportError as exc:
raise RuntimeError("openpyxl required to validate inventory Excel") 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()
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()
except Exception:
print(
"[inventory-artifact] stage=excel_structure_validation status=error "
f"elapsedMs={int((time.monotonic() - started_at) * 1000)} path={path.name!r}"
)
raise
print(
"[inventory-artifact] stage=excel_structure_validation status=end "
f"elapsedMs={int((time.monotonic() - started_at) * 1000)} path={path.name!r}"
)
def _save_download(download: Any, drop_dir: Path, task_no: str, source_code: str) -> Path:
@@ -586,7 +615,12 @@ def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dic
source_code = str(source.get("source_code") or "UNKNOWN")
warehouse_id = str(source.get("warehouse_id") or "WH")
dest = drop_dir / _batch_download_name(run_no, source_code, warehouse_id, suffix=suffix)
save_started_at = time.monotonic()
download.save_as(str(dest))
print(
"[inventory-artifact] stage=download_save status=end "
f"elapsedMs={int((time.monotonic() - save_started_at) * 1000)} path={dest.name!r}"
)
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
_validate_inventory_excel(dest)
return dest
@@ -798,26 +832,64 @@ def _export_crane_inventory_source(page: Any, trigger: dict[str, Any], source: d
)
def _open_browser(download_dir: Path):
def _dsv_session_reuse_enabled() -> bool:
"""返回是否显式允许 DSV 库存导出复用受控浏览器会话。"""
return _env("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "false").lower() == "true"
def _dsv_session_profile_dir() -> Path:
"""返回 DSV 专用持久 profile;该目录不得与其他货代任务共用。"""
return _browser_profile_root() / "dsv360_session"
def _should_cleanup_browser_profile(profile_dir: Path) -> bool:
"""
判断关闭浏览器后是否可删除本次 profile。
核心逻辑:仅显式开启的 DSV 固定会话目录需要跨任务保留;其余目录都是
`_open_browser` 创建的一次性运行目录,应由调用方清理。
Args:
profile_dir: 已传给 Playwright persistent context 的 profile 目录。
Returns:
bool: 为 True 时调用方可安全删除该目录。
"""
return profile_dir.resolve() != _dsv_session_profile_dir().resolve()
def _open_browser(download_dir: Path, *, reuse_dsv_session: bool = False):
"""
打开用于库存 RPA 导出的浏览器上下文。
核心逻辑:无论正式执行还是测试执行,都基于 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`
创建一次性的运行时 profile 子目录,再交给 Playwright 的 persistent context。
这样既能保留 Chrome/Edge 可执行文件与下载目录配置,又能避免复用任何已有登录态。
核心逻辑:默认创建一次性的运行时 profile 子目录。仅当调用方明确为 DSV
库存导出请求会话复用,且 `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE=true` 时,
才使用独立的固定 `dsv360_session` 目录;其他货代任务绝不复用该会话。
Args:
download_dir: 当前导出任务的下载目录,浏览器下载结果会先落到这里。
reuse_dsv_session: 仅 DSV 库存调用可传 True;环境开关关闭时仍使用临时目录。
Returns:
tuple: `(playwright, context, page, runtime_profile_dir)`,其中 `runtime_profile_dir`
为本次执行独占的临时 profile 目录,调用方负责在关闭浏览器后清理。
为本次执行使用的 profile 目录。调用方必须用
`_should_cleanup_browser_profile` 决定是否清理。
"""
sync_playwright, _timeout = _require_playwright()
playwright = sync_playwright().start()
profile_root = _browser_profile_root()
profile_root.mkdir(parents=True, exist_ok=True)
runtime_profile_dir = Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
use_reused_dsv_session = reuse_dsv_session and _dsv_session_reuse_enabled()
runtime_profile_dir = (
_dsv_session_profile_dir()
if use_reused_dsv_session
else Path(tempfile.mkdtemp(prefix="run_", dir=str(profile_root)))
)
runtime_profile_dir.mkdir(parents=True, exist_ok=True)
print(
"[browser] profile_mode="
f"{'dsv_session_reuse' if use_reused_dsv_session else 'temporary'}"
)
headless = _env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false").lower() == "true"
channel = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL")
executable_path = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH")
@@ -868,7 +940,10 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
keep_open_on_error = _env("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"
failed = False
try:
playwright, context, page, runtime_profile_dir = _open_browser(drop_dir)
playwright, context, page, runtime_profile_dir = _open_browser(
drop_dir,
reuse_dsv_session=connector_type == "dsv360",
)
with _profile_credentials(source):
if connector_type == "dsv360":
download = _download_dsv360_inventory(page, trigger, source)
@@ -889,7 +964,7 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
context.close()
if playwright is not None:
playwright.stop()
if runtime_profile_dir is not None:
if runtime_profile_dir is not None and _should_cleanup_browser_profile(runtime_profile_dir):
shutil.rmtree(runtime_profile_dir, ignore_errors=True)
@@ -1025,17 +1100,23 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
if not isinstance(source, dict):
identity_errors.append(f"inventory_sources[{index}]")
continue
# Crane 的 Warehouse 由导出 Excel 中 reservation_id + part_number 解析,
# trigger 阶段不存在固定预期库位;其余来源仍必须绑定预期库位。
requires_expected_warehouse = str(
source.get("worker_connector_type") or source.get("connector_type") or ""
).strip().lower() not in {"crane", "crane_footprint"}
identity_errors.extend(
f"inventory_sources[{index}].{key}"
for key in _INVENTORY_V2_REQUIRED_FIELDS
if key not in {"schema_version", "task_no", "callback_id"}
and (key != "expected_warehouse_id" or requires_expected_warehouse)
and (source.get(key) is None or (isinstance(source.get(key), str) and not source.get(key).strip()))
)
if identity_errors:
try:
_post_callback("/api/shipping-notice/rpa/inventory-batch-ready", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": None,
"callback_id": body.get("callback_id"),
"batch_run_no": run_no or None,
"business_status": "rejected",
"status": "rejected",
@@ -1108,7 +1189,10 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
entry_url = str((site_sources[0] or {}).get("entry_url") or (site_sources[0] or {}).get("login_url") or "").strip()
playwright = context = runtime_profile_dir = None
try:
playwright, context, page, runtime_profile_dir = _open_browser(drop_dir)
playwright, context, page, runtime_profile_dir = _open_browser(
drop_dir,
reuse_dsv_session=site == "dsv360",
)
if site not in {"dsv360", "crane_footprint"}:
raise RuntimeError(f"unsupported connector_type: {site}")
export_fn = _export_dsv_inventory_source if site == "dsv360" else _export_crane_inventory_source
@@ -1147,12 +1231,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
for source in site_sources:
results.append({"source_code": source.get("source_code"), "warehouse_id": source.get("warehouse_id"), "status": "failed", "success": False, "error_code": "rpa_profile_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
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)
_close_batch_browser_resources(context, playwright, runtime_profile_dir)
# v2 业务结果必须原样保留逐源身份,后端据此绑定 SourceAttempt;
# Worker 不生成新身份,只从已校验的 trigger source 复制。
+4 -1
View File
@@ -25,7 +25,8 @@ param(
[string]$PythonExe = "python.exe",
[switch]$Mock,
[switch]$Headless
[switch]$Headless,
[switch]$ReuseDsvSession
)
$ErrorActionPreference = "Stop"
@@ -69,6 +70,8 @@ $processVars = [ordered]@{
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20"
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" })
# 仅显式启用时让 DSV 库存任务复用专属 profile;默认继续使用一次性会话。
SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE = $(if ($ReuseDsvSession) { "true" } else { "false" })
SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge"
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $dataRoot "inventory_triggers"
+12 -10
View File
@@ -188,23 +188,25 @@ function Ensure-Backend {
Write-Host "[backend] preparing..." -ForegroundColor Cyan
Set-Location $BackendPath
if (-not (Test-Path ".\venv\Scripts\python.exe")) {
if (-not (Test-Path ".\.venv\Scripts\python.exe")) {
Write-Host "[backend] creating virtualenv..." -ForegroundColor Yellow
if ($PyCmd -like "py *") {
$parts = $PyCmd.Split(" ", 2)
& $parts[0] $parts[1] -m venv venv
& $parts[0] $parts[1] -m venv .venv
}
else {
& $PyCmd -m venv venv
& $PyCmd -m venv .venv
}
}
$venvPy = Join-Path $BackendPath "venv\Scripts\python.exe"
$venvPy = Join-Path $BackendPath ".venv\Scripts\python.exe"
if ($DoInstall) {
Write-Host "[backend] installing python dependencies..." -ForegroundColor Yellow
& $venvPy -m pip install --upgrade pip
& $venvPy -m pip install -r requirements.txt
# XFA 自动标注把 OCR 作为强制视觉交叉证据,shipping Worker 必须安装完整运行时。
& $venvPy -m pip install -r requirements-ocr.txt
}
if ($Mode -eq "sqlite") {
@@ -236,7 +238,7 @@ function Invoke-DbMigrate {
Write-Host "[db-migrate] running flask db upgrade..." -ForegroundColor Cyan
Set-Location $BackendPath
$venvPy = Join-Path $BackendPath "venv\Scripts\python.exe"
$venvPy = Join-Path $BackendPath ".venv\Scripts\python.exe"
$env:FLASK_APP = "run.py"
$env:FLASK_ENV = "development"
@@ -291,7 +293,7 @@ function Start-BackendWindow {
$reloaderEnv = ""
}
$cmd = "$dbExport$reloaderEnv Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\run.py"
$cmd = "$dbExport$reloaderEnv Set-Location '$BackendPath'; .\.venv\Scripts\python.exe .\run.py"
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
}
@@ -394,7 +396,7 @@ function Start-KbWorkerWindow {
-Title "kb-worker (concurrency=$Concurrency)" `
-WorkingDirectory $BackendPath `
-EnvPrefix $envPrefix `
-Command ".\venv\Scripts\python.exe .\worker_kb.py"
-Command ".\.venv\Scripts\python.exe .\worker_kb.py"
}
function Start-ShippingWorkerWindow {
@@ -412,7 +414,7 @@ function Start-ShippingWorkerWindow {
-Title "shipping-worker (concurrency=$Concurrency)" `
-WorkingDirectory $BackendPath `
-EnvPrefix $envPrefix `
-Command ".\venv\Scripts\python.exe .\worker_shipping.py"
-Command ".\.venv\Scripts\python.exe .\worker_shipping.py"
}
function Start-ScheduleWorkerWindow {
@@ -426,7 +428,7 @@ function Start-ScheduleWorkerWindow {
-Title "schedule-worker" `
-WorkingDirectory $BackendPath `
-EnvPrefix (Get-DatabaseUrlExport -Mode $Mode -DbUrl $DbUrl) `
-Command ".\venv\Scripts\python.exe .\workers\worker_scheduler.py"
-Command ".\.venv\Scripts\python.exe .\workers\worker_scheduler.py"
}
function Start-FreightRpaWorkerWindow {
@@ -443,7 +445,7 @@ function Start-FreightRpaWorkerWindow {
-Title "freight-rpa-worker" `
-WorkingDirectory $RepoRoot `
-EnvPrefix $envPrefix `
-Command "& '$BackendPath\venv\Scripts\python.exe' .\scripts\rpa\freight_rpa_worker.py"
-Command "& '$BackendPath\.venv\Scripts\python.exe' .\scripts\rpa\freight_rpa_worker.py"
}
function Start-FrontendWindow {
+1 -1
View File
@@ -10,7 +10,7 @@ $ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$backendDir = Join-Path $repoRoot "backend"
$frontendDir = Join-Path $repoRoot "frontend"
$venvPython = Join-Path $backendDir "venv\Scripts\python.exe"
$venvPython = Join-Path $backendDir ".venv\Scripts\python.exe"
if (-not (Test-Path $venvPython)) { throw "Backend virtualenv not found: $venvPython" }
if (-not (Test-Path $frontendDir)) { throw "Frontend directory not found: $frontendDir" }
+1 -1
View File
@@ -1,7 +1,7 @@
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$backendDir = Join-Path $repoRoot "backend"
$python = Join-Path $backendDir "venv\Scripts\python.exe"
$python = Join-Path $backendDir ".venv\Scripts\python.exe"
function Import-DotEnv {
param([string]$Path)