Merge branch 'hugo-auto-transfer' into dev

# Conflicts:
#	backend/app/api/shipping_notice_tools.py
This commit is contained in:
hugo committed 2026-09-30 00:34:28 +08:00
commit 6cf71679b7
143 files changed
+10145 -2132

No files matched your search

+11 -1
View File
@@ -66,7 +66,17 @@ def _env(name: str, default: str = "") -> str:
def _browser_timeout_ms() -> int:
return max(5_000, int(_env("FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS", "60000") or "60000"))
"""
读取 Playwright/DSV 操作默认超时(毫秒)。
核心逻辑:环境变量 ``FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS``,未设置时默认
120000(2 分钟)。下限钳制为 5000,避免误配成过短值。库存与收料共用:
含 View Report 后的 result_ready 轮询、page.goto、元素点击等。
Returns:
int: 超时毫秒数,至少 5000。
"""
return max(5_000, int(_env("FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS", "120000") or "120000"))
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()
+10 -5
View File
@@ -3,7 +3,8 @@ scripts/freight_rpa/common/rpa_heartbeat.py
用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
依赖:rpa_common.env、urllib、socket。
逻辑:由 freight_rpa_worker 主循环按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;同步写入共享目录哨兵文件。
逻辑:由库存/收料 Worker 主循环或守护线程按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;
库存声明 inventory_export,收料声明 receipt_export;库存侧可写共享目录哨兵。
"""
from __future__ import annotations
@@ -134,18 +135,22 @@ def build_heartbeat_payload(
) -> dict[str, Any]:
"""
组装心跳 payload。
核心逻辑:capabilities 含 inventory_export;Worker 开启上传时附加 freight_upload;
shared_scope_id 用于跨平台路径对齐与环境隔离。
核心逻辑:库存 Worker 声明 inventory_export;收料 Worker(worker_id 以 -receipt
结尾,或 trigger_dir 路径含 /receipt/)声明 receipt_export;开启上传时附加 freight_upload。
"""
hostname = socket.gethostname()
capabilities = ["inventory_export"]
worker_id = _resolve_worker_id(hostname)
trigger_norm = str(trigger_dir or "").replace("\\", "/").lower()
is_receipt = str(worker_id).lower().endswith("-receipt") or "/receipt/" in f"/{trigger_norm}/"
capabilities = ["receipt_export" if is_receipt else "inventory_export"]
upload_enabled = str(_env("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in {
"1", "true", "yes", "on",
}
if upload_enabled:
capabilities.append("freight_upload")
return {
"worker_id": _resolve_worker_id(hostname),
"worker_id": worker_id,
"hostname": hostname,
"environment": _resolve_worker_environment(),
"capabilities": capabilities,
@@ -3,8 +3,8 @@ scripts/freight_rpa/crane_report_export.py
用途:Crane On Hand Details Query 异步报表导出(Run Report → Schedule Report → Scheduled Reports 下载)。
依赖:Playwright Page、download_artifact_fallback;由 inventory_rpa_worker._export_crane_inventory_source 委托调用。
逻辑:必须先 Run Report 产出查询结果,再 Schedule 异步导出;轮询仅在 scheduled-reports 路由进行;
expect_download 超时时按下载目录新文件做短窗口兜底(与 DSV 同模块,窗口更短)。
逻辑:不填写页面查询条件;必须先 Run Report 产出查询结果,再 Schedule 异步导出;
轮询仅在 scheduled-reports 路由进行;expect_download 超时时按下载目录新文件做短窗口兜底。
"""
from __future__ import annotations
@@ -311,38 +311,16 @@ def _fill_crane_report_parameters(
browser_timeout_ms: int,
select_or_fill: Callable[..., None],
) -> None:
"""按 source.parameters 填充可选报表参数(Owner/Project);Warehouse 已废弃不再填写。"""
parameters = source.get("parameters")
if isinstance(parameters, list) and parameters:
label_map = {
"owner": "Select Owner...",
"project": "Select Project...",
}
for item in parameters:
if not isinstance(item, dict):
continue
name = str(item.get("name") or "").strip().lower()
if name == "warehouse":
print("[crane-export] skip Warehouse parameter (not required)")
continue
mode = str(item.get("mode") or "single").strip().lower()
selector_env = _crane_parameter_selector_env(name)
values = [str(v).strip() for v in (item.get("values") or []) if str(v).strip()]
if not values:
continue
label = label_map.get(name, str(item.get("name") or ""))
if mode == "multi_text":
joiner = str(item.get("joiner") or ",")
select_or_fill(page, selector_env, label, joiner.join(values))
continue
select_or_fill(page, selector_env, label, values[0])
return
"""
Crane 报表不填写页面查询条件。
核心逻辑:On Hand / Inbound Details 默认条件即可 Run Report;历史透传的
Owner/Project/Warehouse 会干扰实机默认态,一律忽略(库存与收料同口径)。
"""
parameters = source.get("parameters")
query = source.get("query") if isinstance(source.get("query"), dict) else {}
if query.get("owner_code"):
select_or_fill(page, "FREIGHT_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code"))
if query.get("project_code"):
select_or_fill(page, "FREIGHT_RPA_WORKER_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code"))
if (isinstance(parameters, list) and parameters) or query.get("owner_code") or query.get("project_code"):
print("[crane-export] skip report query parameters (not required)")
def _crane_parameter_selector_env(parameter_name: str) -> str:
@@ -3,8 +3,9 @@ scripts/freight_rpa/dsv_report_export.py
用途:DSV 360 填参、View Report、Excel 导出与 batch 编排。
依赖:rpa_common、dsv_debug、dsv_navigation、dsv_session、dsv_report_parameters。
逻辑:worker connector_type=dsv360 时委托本模块;DOM 明细行探测仅作加速,
无行时重试 View Report 一次后仍导出,真空由落盘 Excel 判定。
逻辑:worker connector_type=dsv360 / 收料 DBS 时委托本模块;按 export_kind 分流
库存/收料的结果就绪正文标记与明细行探针(结构可参考,字段不复用);
DOM 明细行探测仅作加速,无行时重试 View Report 一次后仍导出,真空由落盘 Excel 判定。
"""
from __future__ import annotations
@@ -85,7 +86,60 @@ class DsvReportProcessingError(RuntimeError):
"""
def _click_dsv_export_excel(page: Any) -> None:
# 库存结果正文标记(On Hand Inventory…);收料不得复用本列表的库存专用项。
_DSV_INVENTORY_BODY_MARKERS: tuple[str, ...] = (
"on hand inventory by location",
"supplier id",
"sku description",
"page width",
"whole page",
"carton id",
"location (%)",
"pallet id",
"warehouse",
)
# Receipt Detail 专用正文标记(AWSRTM 实机列头,2026-09-28);可与库存共享 UI 词,不含库存专用语义。
_DSV_RECEIPT_BODY_MARKERS: tuple[str, ...] = (
"receipt detail",
"external asn",
"wms receipt",
"qty expected",
"qty received",
"date received",
"asn status",
"check in time",
"customs entry",
"page width",
"whole page",
)
def _dsv_export_kind(source: dict[str, Any] | None = None, *, kind: str | None = None) -> str:
"""
解析导出语义:inventory | receipt。
核心逻辑:显式 kind / source.__export_kind__ 优先;否则按报表名含 receipt detail 推断。
"""
explicit = str(kind or "").strip().lower()
if explicit in {"inventory", "receipt"}:
return explicit
if isinstance(source, dict):
flagged = str(source.get("__export_kind__") or "").strip().lower()
if flagged in {"inventory", "receipt"}:
return flagged
report = _dsv_report_name(source).casefold()
if "receipt detail" in report:
return "receipt"
return "inventory"
def _dsv_body_markers_for_kind(kind: str) -> tuple[str, ...]:
"""按 export_kind 返回结果正文标记;收料与库存字段列表分离。"""
return _DSV_RECEIPT_BODY_MARKERS if kind == "receipt" else _DSV_INVENTORY_BODY_MARKERS
def _click_dsv_export_excel(page: Any, *, kind: str = "inventory") -> None:
"""
触发 DSV SSRS ReportViewer 的 Excel 导出。
@@ -93,19 +147,21 @@ def _click_dsv_export_excel(page: Any) -> None:
文案;因此优先在承载报表结果的 frame 内直接调用 ReportViewer 原生
`exportReport('EXCELOPENXML')`,失败后只在选中的结果 frame 内退回到菜单点击式导出,
避免误点到 portal 顶层或报表标题 frame 的同名元素。
kind 须与 View Report 等待阶段一致,避免收料结果被库存正文标记误判未就绪。
"""
export_kind = _dsv_export_kind(kind=kind)
# #region debug-point H2:export-click-entry
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_click_dsv_export_excel:entry", "[DEBUG] enter export click path", {"frameCount": len(page.frames)})
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_click_dsv_export_excel:entry", "[DEBUG] enter export click path", {"frameCount": len(page.frames), "exportKind": export_kind})
# #endregion
try:
_wait_for_dsv_report_result_ready(page, min(_browser_timeout_ms(), 20_000))
_wait_for_dsv_report_result_ready(page, min(_browser_timeout_ms(), 20_000), kind=export_kind)
except TypeError:
_wait_for_dsv_report_result_ready(page)
_wait_for_dsv_report_result_ready(page, kind=export_kind)
# #region debug-point H2:export-click-after-wait
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_click_dsv_export_excel:after-wait", "[DEBUG] export path passed wait_for_dsv_report_result_ready", {"frameCount": len(page.frames)})
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_click_dsv_export_excel:after-wait", "[DEBUG] export path passed wait_for_dsv_report_result_ready", {"frameCount": len(page.frames), "exportKind": export_kind})
# #endregion
selected_frame = _find_dsv_report_result_frame(page)
selected_frame = _find_dsv_report_result_frame(page, kind=export_kind)
# #region debug-point H4:selected-report-frame
if selected_frame is not None:
try:
@@ -389,19 +445,23 @@ def _click_dsv_export_excel(page: Any) -> None:
# #endregion
def _get_dsv_report_result_state(frame: Any) -> dict[str, bool]:
def _get_dsv_report_result_state(frame: Any, *, kind: str = "inventory") -> dict[str, bool]:
"""
读取 DSV SSRS 结果 frame 的当前状态。
核心逻辑:真实页面里“结果表头已出现”与“报表真正渲染完成”并不同步,
这里统一抽象为 `asyncWait / processingError / exportReady / excelReady / bodyReady / directExportReady`
布尔量,供等待逻辑和导出逻辑复用;SSRS 服务端错误页视为终态(processingError),
不再命中 asyncWait,避免错误文案里的 "processing" 让等待逻辑误判为加载中。
布尔量,供等待逻辑和导出逻辑复用;SSRS 服务端错误页视为终态(processingError)。
asyncWait 只认可见的 ``#ReportViewerMain_AsyncWait``(或 ``.WaitControlBackground``),
禁止用 body 全文含 loading——日历 iframe 隐藏 Loading 文案会假阳性拖满超时(2026-09-28)。
bodyMarkers 按 export_kind 分流:库存用 On Hand… 字段,收料用 Receipt Detail 列头。
"""
export_kind = _dsv_export_kind(kind=kind)
body_markers = list(_dsv_body_markers_for_kind(export_kind))
try:
state = frame.evaluate(
"""
() => {
(bodyMarkers) => {
const visible = (node) => {
if (!node) return false;
const style = window.getComputedStyle(node);
@@ -430,18 +490,8 @@ def _get_dsv_report_result_state(frame: Any) -> dict[str, bool]:
'a[onclick*="EXCELOPENXML"]',
'button[onclick*="EXCELOPENXML"]',
]);
const bodyMarkers = [
'on hand inventory by location',
'supplier id',
'sku description',
'page width',
'whole page',
'carton id',
'location (%)',
'pallet id',
'warehouse',
];
const bodyScore = bodyMarkers.filter((token) => normalizedBody.includes(token)).length;
const markers = Array.isArray(bodyMarkers) ? bodyMarkers : [];
const bodyScore = markers.filter((token) => normalizedBody.includes(token)).length;
const bodyReady = bodyScore > 0;
const processingError = [
'rsprocessingaborted',
@@ -449,19 +499,28 @@ def _get_dsv_report_result_state(frame: Any) -> dict[str, bool]:
'rsreportexecutionerror',
'an error has occurred during report',
].some((token) => normalizedBody.includes(token));
const asyncWait = !processingError && [
'loading',
'please wait',
'generating',
'processing',
'retrieving',
].some((token) => normalizedBody.includes(token));
// View Report 后 SSRS 遮罩:消失=渲染完;不得扫 body「loading」假阳性。
const asyncWaitNode = document.querySelector('#ReportViewerMain_AsyncWait')
|| document.querySelector('div.WaitControlBackground');
const asyncWait = !processingError && visible(asyncWaitNode);
const directExportReady = typeof exportReport === 'function' ||
(window && typeof window.exportReport === 'function');
return { asyncWait, processingError, exportReady, excelReady, bodyReady, bodyScore, directExportReady };
}
"""
""",
body_markers,
)
except TypeError:
# 单测 FakeFrame.evaluate(script) 不接第二参时,退回无 markers 的空状态由调用方 mock 决定。
try:
state = frame.evaluate(
"""
() => ({ asyncWait: false, processingError: false, exportReady: false,
excelReady: false, bodyReady: false, bodyScore: 0, directExportReady: false })
"""
)
except Exception:
state = {}
except Exception:
state = {}
return {
@@ -575,19 +634,20 @@ def _force_open_dsv_export_menu(root: Any, export_menu_selector: str) -> bool:
return False
def _find_dsv_report_result_frame(page: Any) -> tuple[int, Any, dict[str, Any]] | None:
def _find_dsv_report_result_frame(page: Any, *, kind: str = "inventory") -> tuple[int, Any, dict[str, Any]] | None:
"""
选择真正承载 SSRS 报表结果表格的 frame。
核心逻辑:首页/最近报表等 frame 也可能包含报表名文本,因此不能只看 `bodyReady`;
这里先按 frame 身份硬匹配 `report-frame` / `.../S360Reports/Reports/Default.aspx`,
命中后即使正文仍在 loading,也要持续盯住它等待;只有完全识别不到目标 frame 时,
才退回到 `bodyScore` 启发式排序。
才退回到 `bodyScore` 启发式排序。kind 决定正文标记(库存 vs 收料)。
"""
export_kind = _dsv_export_kind(kind=kind)
hard_matches: list[tuple[int, Any, dict[str, Any], tuple[int, int, int, int, int]]] = []
heuristic_matches: list[tuple[int, Any, dict[str, Any], tuple[int, int, int, int]]] = []
for frame_index, frame in enumerate(page.frames):
state = _get_dsv_report_result_state(frame)
state = _get_dsv_report_result_state(frame, kind=export_kind)
try:
frame_name = str(frame.name or "").strip().lower()
except Exception:
@@ -647,24 +707,27 @@ def _find_dsv_report_result_frame(page: Any) -> tuple[int, Any, dict[str, Any]]
return None
def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int) -> None:
def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int, *, kind: str = "inventory") -> None:
"""
等待 DSV 报表结果区进入“可导出”状态。
核心逻辑:DSV 报表页点击 View Report 后,真实结果和导出工具栏都渲染在 frame 里,
顶层页面未必能立即看到 `Export` 文案;因此这里改为轮询读取 frame 状态。
只要“目标结果 frame 的异步加载已结束 + 报表正文已出现”就允许继续尝试导出,因为真实站点上
导出能力有时直到点击工具栏/调用原生导出函数时才真正显式出现。
异步加载以可见 ``#ReportViewerMain_AsyncWait`` 消失为准(非纯超时、非 body「loading」扫词)。
库存:异步加载结束 + 库存正文标记出现即可继续。
收料:异步加载结束 +(收料正文标记或 Export/Save 工具栏)即可继续——Receipt Detail
与库存列头不同,不得用库存 bodyMarkers 卡死。
轮询中一旦确认 SSRS 服务端处理错误(rsProcessingAborted 等)即快速失败抛
DsvReportProcessingError,不再空等超时(AWSRTM 2026-09-20 生产故障暴露)。
"""
export_kind = _dsv_export_kind(kind=kind)
deadline = time.monotonic() + max(timeout_ms / 1000, 1)
last_stage_second = -1
# #region debug-point H2:wait-report-entry
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_wait_for_dsv_report_result_ready:entry", "[DEBUG] start wait_for_dsv_report_result_ready", {"timeoutMs": timeout_ms, "frameCount": len(page.frames)})
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_wait_for_dsv_report_result_ready:entry", "[DEBUG] start wait_for_dsv_report_result_ready", {"timeoutMs": timeout_ms, "frameCount": len(page.frames), "exportKind": export_kind})
# #endregion
while time.monotonic() < deadline:
selected = _find_dsv_report_result_frame(page)
selected = _find_dsv_report_result_frame(page, kind=export_kind)
if selected is not None:
frame_index, _frame, state = selected
if state.get("processingError"):
@@ -674,7 +737,7 @@ def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int) -> None:
"H2",
"freight_rpa_worker.py:_wait_for_dsv_report_result_ready:processing-error",
"[DEBUG] ssrs report processing error detected",
{"frameIndex": frame_index, **state},
{"frameIndex": frame_index, "exportKind": export_kind, **state},
)
_debug_dsv_stage(page, "wait-report-processing-error", target_text="Export")
raise DsvReportProcessingError(
@@ -682,14 +745,18 @@ def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int) -> None:
"(rsProcessingAborted/rsDataSetExecutionError); "
f"frameIndex={frame_index}"
)
if state["bodyReady"] and not state["asyncWait"]:
ready = bool(state["bodyReady"] and not state["asyncWait"])
if export_kind == "receipt":
# 收料:Export 工具栏或 Receipt Detail 正文均可作为就绪信号。
ready = (not state["asyncWait"]) and (state["bodyReady"] or state["exportReady"])
if ready:
# #region debug-point H2:wait-report-ready
_emit_debug_event(
"pre-fix",
"H2",
"freight_rpa_worker.py:_wait_for_dsv_report_result_ready:ready",
"[DEBUG] report result considered ready",
{"frameIndex": frame_index, **state},
{"frameIndex": frame_index, "exportKind": export_kind, **state},
)
# #endregion
_debug_dsv_stage(page, "wait-report-ready-state", target_text="Export")
@@ -702,27 +769,27 @@ def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int) -> None:
"H2",
"freight_rpa_worker.py:_wait_for_dsv_report_result_ready:poll",
"[DEBUG] report result still waiting",
{"secondsRemaining": elapsed_second, "frameCount": len(page.frames)},
{"secondsRemaining": elapsed_second, "frameCount": len(page.frames), "exportKind": export_kind},
)
# #endregion
_debug_dsv_stage(page, "wait-report-polling", target_text="Export")
last_stage_second = elapsed_second
time.sleep(1)
# #region debug-point H2:wait-report-timeout
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_wait_for_dsv_report_result_ready:timeout", "[DEBUG] report result wait timed out", {"timeoutMs": timeout_ms, "frameCount": len(page.frames)})
_emit_debug_event("pre-fix", "H2", "freight_rpa_worker.py:_wait_for_dsv_report_result_ready:timeout", "[DEBUG] report result wait timed out", {"timeoutMs": timeout_ms, "frameCount": len(page.frames), "exportKind": export_kind})
# #endregion
_debug_dsv_stage(page, "wait-report-timeout", target_text="Export")
raise RuntimeError("DSV report result did not become exportable before timeout")
def _wait_dsv_report_ready(page: Any, *, timeout_ms: int) -> None:
def _wait_dsv_report_ready(page: Any, *, timeout_ms: int, kind: str = "inventory") -> None:
"""
向后兼容的包装器。
核心逻辑:历史调用点仍使用 `_wait_dsv_report_ready`;
实际实现统一委托给 `_wait_for_dsv_report_result_ready`,避免测试和主流程再次分叉。
"""
_wait_for_dsv_report_result_ready(page, timeout_ms)
_wait_for_dsv_report_result_ready(page, timeout_ms, kind=kind)
_DSV_INVENTORY_DATA_ROWS_PROBE_JS = """
@@ -880,7 +947,7 @@ def _dsv_report_has_inventory_data_rows(page: Any) -> bool:
`tbody > tr`;忽略 `height=0`、列头行与 rsviewer 元数据行;明细行须含 AWS Sku
或 Supplier ID + Qty 组合,避免 PutawayZone 的 BBU/DAMAGE 被误判为库存。
"""
selected = _find_dsv_report_result_frame(page)
selected = _find_dsv_report_result_frame(page, kind="inventory")
if selected is None:
return False
_frame_index, frame, _state = selected
@@ -924,7 +991,7 @@ def _ensure_dsv_inventory_rows_or_export_fallback(page: Any, *, report_name: str
file=sys.stderr,
)
_click_dsv_view_report(page)
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms(), kind="inventory")
if _wait_dsv_report_inventory_rows(page, timeout_ms=row_wait_ms):
return
@@ -935,6 +1002,161 @@ def _ensure_dsv_inventory_rows_or_export_fallback(page: Any, *, report_name: str
)
# Receipt Detail 明细行探针:表头看 External ASN / WMS Receipt / Qty Expected|Received,不用库存 Qty Available。
_DSV_RECEIPT_DATA_ROWS_PROBE_JS = """
() => {
const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim();
const PARAMETER_ROOT_SELECTORS = [
'#ReportViewerMain_ctl08',
'#ParameterTable_ReportViewerMain_ctl08',
'#ParametersGridReportViewerMain_ctl08',
'[id$="_divDropDown"]',
].join(', ');
const REPORT_ROOT_SELECTORS = [
'#Report_table',
'span#Report_table',
'#VisibleReportContentReportViewerMain_ctl13',
'#ReportViewerMain_ctl13_ReportArea',
'#ReportViewerMain_ctl13',
].join(', ');
const isInsideParameterArea = (node) => !!(node && node.closest && node.closest(PARAMETER_ROOT_SELECTORS));
const isHiddenRow = (row) => {
const heightAttr = String(row.getAttribute('height') || '').trim().toLowerCase();
if (heightAttr === '0' || heightAttr === '0px') return true;
try {
const style = window.getComputedStyle(row);
if (style.display === 'none' || style.visibility === 'hidden') return true;
if (row.offsetHeight === 0 && parseFloat(style.height || '0') === 0) return true;
} catch (_err) { return false; }
return false;
};
const isReceiptTableText = (text) => (
(text.includes('External ASN') && text.includes('WMS Receipt')) ||
(text.includes('Qty Expected') && text.includes('Qty Received')) ||
(text.includes('Date Received') && text.includes('AWS Sku'))
);
const isReceiptHeaderRow = (row) => {
const line = normalize(row.innerText || '');
return (
(line.includes('External ASN') && line.includes('WMS Receipt')) ||
(line.includes('Qty Expected') && line.includes('Qty Received'))
);
};
const isReportMetadataRow = (row) => {
const line = normalize(row.innerText || '');
if (!line) return true;
if (/created\\s+.+(by|rsviewer)/i.test(line)) return true;
if (/rsviewer\\s+v\\d/i.test(line)) return true;
if (/receipt detail/i.test(line) && line.length < 80) return true;
return false;
};
const isReceiptDetailRow = (row) => {
if (isHiddenRow(row) || isReceiptHeaderRow(row) || isReportMetadataRow(row)) return false;
const cells = Array.from(row.querySelectorAll(':scope > td, :scope > th'));
if (!cells.length) return false;
const texts = cells.map((cell) => normalize(cell.innerText || '')).filter(Boolean);
if (!texts.length) return false;
const hasAwsSku = texts.some((value) => /^[0-9A-Z]{2,}-[0-9A-Z._-]{4,}$/i.test(value));
const hasAsnOrReceipt = texts.some((value) =>
/^(RTM|ASN|BKG)[0-9A-Z_-]+$/i.test(value) || /^0{0,}\\d{8,}$/.test(value.replace(/,/g, ''))
);
const hasQtyLike = texts.some((value) => /^-?\\d+(\\.\\d+)?$/.test(value.replace(/,/g, '')));
return (hasAwsSku && hasQtyLike) || (hasAsnOrReceipt && hasQtyLike) || (hasAwsSku && hasAsnOrReceipt);
};
const directBodyRows = (table) => {
const rows = [];
for (const tbody of Array.from(table.tBodies || [])) {
if (tbody.parentElement !== table) continue;
rows.push(...Array.from(tbody.children).filter((node) => node.tagName === 'TR'));
}
return rows;
};
const tableHasReceiptDetailRows = (table) => {
if (isInsideParameterArea(table)) return false;
const text = normalize(table.innerText || '');
if (!isReceiptTableText(text)) return false;
const rows = directBodyRows(table).filter((row) => !isHiddenRow(row));
const headerIdx = rows.findIndex(isReceiptHeaderRow);
if (headerIdx >= 0) return rows.slice(headerIdx + 1).some(isReceiptDetailRow);
return rows.some(isReceiptDetailRow);
};
const seen = new Set();
const tables = [];
const push = (table) => {
if (!table || seen.has(table) || isInsideParameterArea(table)) return;
seen.add(table);
tables.push(table);
};
document.querySelectorAll('#Report_table table, span#Report_table > table').forEach(push);
if (!tables.length) {
for (const root of document.querySelectorAll(REPORT_ROOT_SELECTORS)) {
if (isInsideParameterArea(root)) continue;
root.querySelectorAll('table').forEach((table) => {
if (isInsideParameterArea(table)) return;
if (isReceiptTableText(normalize(table.innerText || ''))) push(table);
});
}
}
return tables.some(tableHasReceiptDetailRows);
}
"""
def _dsv_report_has_receipt_data_rows(page: Any) -> bool:
"""
判断 Receipt Detail 结果页是否已出现收料明细行。
核心逻辑:结构对齐库存行探针,但表头/明细字段用 External ASN、WMS Receipt、
Qty Expected/Received 等收料列,禁止复用 Qty Available 库存判定。
"""
selected = _find_dsv_report_result_frame(page, kind="receipt")
if selected is None:
return False
_frame_index, frame, _state = selected
try:
return bool(frame.evaluate(_DSV_RECEIPT_DATA_ROWS_PROBE_JS))
except Exception as exc:
print(f"[dsv-report] receipt data row probe failed: {exc}", file=sys.stderr)
return False
def _wait_dsv_report_receipt_rows(page: Any, *, timeout_ms: int) -> bool:
"""条件轮询等待 Receipt Detail 明细行;超时返回 False,交由导出+Excel 判空。"""
deadline = time.monotonic() + max(1.0, timeout_ms / 1000)
while time.monotonic() < deadline:
if _dsv_report_has_receipt_data_rows(page):
return True
time.sleep(1.0)
return False
def _ensure_dsv_receipt_rows_or_export_fallback(page: Any, *, report_name: str) -> None:
"""
收料 DOM 有行则继续;无行重试一次 View Report,仍无行也不抛空——交给 Excel 判空。
核心逻辑:与库存兜底同构,但就绪等待与行探针均走 receipt kind。
"""
row_wait_ms = min(_browser_timeout_ms(), 45_000)
if _wait_dsv_report_receipt_rows(page, timeout_ms=row_wait_ms):
return
print(
f"[dsv-report] receipt rows not visible after ready reportName={report_name!r}; "
"retry View Report once",
file=sys.stderr,
)
_click_dsv_view_report(page)
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms(), kind="receipt")
if _wait_dsv_report_receipt_rows(page, timeout_ms=row_wait_ms):
return
print(
f"[dsv-report] receipt rows still missing after View Report retry "
f"reportName={report_name!r}; proceed to Excel export fallback",
file=sys.stderr,
)
def _fill_dsv_filter_if_needed(
page: Any,
selector_env: str,
@@ -942,6 +1164,7 @@ def _fill_dsv_filter_if_needed(
value: str | None,
*,
report_name: str | None = None,
program_label: str | None = None,
) -> None:
"""委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。
@@ -951,6 +1174,7 @@ def _fill_dsv_filter_if_needed(
label: 参数名。
value: 参数值。
report_name: 报表名;透传给 dsv_report_parameters 按报表模板解析控件。
program_label: 业务标签(如 AWSRTM);同名报表的站点控件覆盖。
"""
module_path = Path(__file__).resolve().parent / "dsv_report_parameters.py"
spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path)
@@ -966,6 +1190,7 @@ def _fill_dsv_filter_if_needed(
browser_timeout_ms=_browser_timeout_ms,
debug_stage=_debug_dsv_stage,
report_name=report_name,
program_label=program_label,
)
@@ -978,32 +1203,35 @@ def _fill_dsv_multi_select(
selectors: dict[str, str] | None = None,
select_all: bool = False,
report_name: str | None = None,
program_label: str | None = None,
) -> None:
"""
填充 DSV 报表多选控件(multi_select)。
核心逻辑:显式配置 SSRS checkbox 下拉时委托 dsv_report_parameters;
核心逻辑:优先委托 dsv_report_parameters(报表模板 / 显式 selectors);
否则优先 select_option 多值,失败则展开控件后逐条点击 option/checkbox。
report_name 用于按报表模板解析控件(同参数名在不同报表控件长相不同)。
report_name + program_label 用于按站点模板解析控件(如 Receipt Detail@AWSRTM)。
"""
cleaned = [str(item).strip() for item in values if str(item).strip()]
if not cleaned and not select_all:
return
if selectors or select_all:
module_path = Path(__file__).resolve().parent / "dsv_report_parameters.py"
spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if module.fill_dsv_multi_select_parameter(
page,
label,
cleaned,
selectors=selectors,
select_all=select_all,
browser_timeout_ms=_browser_timeout_ms,
report_name=report_name,
):
return
module_path = Path(__file__).resolve().parent / "dsv_report_parameters.py"
spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# [STEP] 始终先尝试模板/selectors 多选路径(含 AWSRTM Warehouse multi_value),
# 不再要求必须带 select_all 才进入——否则管理端配 multi_select+具体值时永远不走 checkbox。
if module.fill_dsv_multi_select_parameter(
page,
label,
cleaned,
selectors=selectors,
select_all=select_all,
browser_timeout_ms=_browser_timeout_ms,
report_name=report_name,
program_label=program_label,
):
return
selector = _env(selector_env)
if selector:
locator = page.locator(selector).first
@@ -1032,14 +1260,23 @@ def _fill_dsv_multi_select(
except Exception as exc:
print(f"[dsv-filter] {label} multi_select click fallback failed: {exc}", file=sys.stderr)
for value in cleaned:
_fill_dsv_filter_if_needed(page, selector_env, label, value, report_name=report_name)
_fill_dsv_filter_if_needed(
page, selector_env, label, value,
report_name=report_name, program_label=program_label,
)
def _fill_report_parameter(page: Any, parameter: dict[str, Any], *, report_name: str | None = None) -> None:
"""按库存源业务参数填充 DSV 报表条件(single / multi_text / multi_select)。
def _fill_report_parameter(
page: Any,
parameter: dict[str, Any],
*,
report_name: str | None = None,
program_label: str | None = None,
) -> None:
"""按库存源/收料配置填充 DSV 报表条件(single / multi_text / multi_select)。
核心逻辑:selector 从 Driver 内部参数名映射获取,不允许库存源配置携带页面实现细节;
report_name 交给 dsv_report_parameters 按报表模板解析控件类型(3lv select vs JDA multi_value)。
report_name + program_label 交给 dsv_report_parameters 按报表/站点模板解析控件类型。
"""
if not isinstance(parameter, dict):
return
@@ -1051,7 +1288,10 @@ def _fill_report_parameter(page: Any, parameter: dict[str, Any], *, report_name:
return
if mode == "multi_text":
joiner = str(parameter.get("joiner") or ",")
_fill_dsv_filter_if_needed(page, selector_env, name, joiner.join(values), report_name=report_name)
_fill_dsv_filter_if_needed(
page, selector_env, name, joiner.join(values),
report_name=report_name, program_label=program_label,
)
return
if mode == "multi_select":
_fill_dsv_multi_select(
@@ -1062,9 +1302,13 @@ def _fill_report_parameter(page: Any, parameter: dict[str, Any], *, report_name:
selectors=None,
select_all=bool(parameter.get("select_all", False)),
report_name=report_name,
program_label=program_label,
)
return
_fill_dsv_filter_if_needed(page, selector_env, name, values[0], report_name=report_name)
_fill_dsv_filter_if_needed(
page, selector_env, name, values[0],
report_name=report_name, program_label=program_label,
)
def _dsv_parameter_selector_env(parameter_name: str) -> str:
@@ -1080,18 +1324,41 @@ def _dsv_parameter_selector_env(parameter_name: str) -> str:
}.get(normalized, "")
def _dsv_program_label(source: dict[str, Any]) -> str:
"""从 source.navigation / report_path_json 解析 program_label(如 AWSRTM)。"""
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
report_path = source.get("report_path_json") if isinstance(source.get("report_path_json"), dict) else {}
return str(
navigation.get("program_label")
or report_path.get("program_label")
or ""
).strip()
def _fill_report_parameters(page: Any, source: dict[str, Any]) -> None:
"""填充 source.parameters;无 parameters 时回退 query 字段。"""
report_name = _dsv_report_name(source)
program_label = _dsv_program_label(source)
parameters = source.get("parameters")
if isinstance(parameters, list) and parameters:
for item in parameters:
_fill_report_parameter(page, item, report_name=report_name)
_fill_report_parameter(
page, item, report_name=report_name, program_label=program_label,
)
return
query = source.get("query") if isinstance(source.get("query"), dict) else {}
_fill_dsv_filter_if_needed(page, "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"), report_name=report_name)
_fill_dsv_filter_if_needed(page, "FREIGHT_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"), report_name=report_name)
_fill_dsv_filter_if_needed(page, "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code"), report_name=report_name)
_fill_dsv_filter_if_needed(
page, "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"),
report_name=report_name, program_label=program_label,
)
_fill_dsv_filter_if_needed(
page, "FREIGHT_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"),
report_name=report_name, program_label=program_label,
)
_fill_dsv_filter_if_needed(
page, "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code"),
report_name=report_name, program_label=program_label,
)
def _dsv_entry_url_host(entry_url: str) -> str:
@@ -1369,44 +1636,50 @@ def _dsv_download_wait_ms() -> int:
def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> Any:
"""参数页已就绪后:填参 → View Report → 等结果 → 导出 Excel,并分别记录阶段耗时。"""
report_name = _dsv_report_name(source)
export_kind = _dsv_export_kind(source)
parameter_started_at = time.monotonic()
_report_dsv_chain_stage("report_parameter_fill", "start", extra={"reportName": report_name})
_report_dsv_chain_stage("report_parameter_fill", "start", extra={"reportName": report_name, "exportKind": export_kind})
try:
_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__},
extra={"reportName": report_name, "exportKind": export_kind, "errorType": type(exc).__name__},
)
raise
_report_dsv_chain_stage(
"report_parameter_fill", "end", started_at=parameter_started_at, extra={"reportName": report_name}
"report_parameter_fill", "end", started_at=parameter_started_at,
extra={"reportName": report_name, "exportKind": export_kind},
)
execution_started_at = time.monotonic()
_report_dsv_chain_stage("report_execute_and_download", "start", extra={"reportName": report_name})
_report_dsv_chain_stage("report_execute_and_download", "start", extra={"reportName": report_name, "exportKind": export_kind})
result_started_at = time.monotonic()
_report_dsv_chain_stage("report_result_ready", "start", extra={"reportName": report_name})
_report_dsv_chain_stage("report_result_ready", "start", extra={"reportName": report_name, "exportKind": export_kind})
try:
_click_dsv_view_report(page)
# [STEP 1] DSV 页面会维持长连接;等待 networkidle 不能说明 SSRS 已可导出,
# 反而可能额外消耗十秒。直接等待现有的报表业务就绪条件。
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
# 反而可能额外消耗十秒。直接等待现有的报表业务就绪条件(库存/收料分流)。
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms(), kind=export_kind)
# [STEP 2] DOM 明细行仅作加速;无行时重试 View Report,仍无则继续导出,
# 真空由落盘 Excel 判定(避免慢渲染假空 skip)。
_ensure_dsv_inventory_rows_or_export_fallback(page, report_name=report_name)
# 真空由落盘 Excel 判定(避免慢渲染假空 skip)。收料用 Receipt Detail 行探针。
if export_kind == "receipt":
_ensure_dsv_receipt_rows_or_export_fallback(page, report_name=report_name)
else:
_ensure_dsv_inventory_rows_or_export_fallback(page, report_name=report_name)
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__},
extra={"reportName": report_name, "exportKind": export_kind, "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__},
extra={"reportName": report_name, "exportKind": export_kind, "errorType": type(exc).__name__},
)
raise
_report_dsv_chain_stage(
"report_result_ready", "end", started_at=result_started_at, extra={"reportName": report_name}
"report_result_ready", "end", started_at=result_started_at,
extra={"reportName": report_name, "exportKind": export_kind},
)
download_dir = str(source.get("__download_dir") or "").strip()
baseline_names = set()
@@ -1416,14 +1689,14 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
except OSError:
baseline_names = set()
download_started_at = time.monotonic()
_report_dsv_chain_stage("excel_export_and_download", "start", extra={"reportName": report_name})
_report_dsv_chain_stage("excel_export_and_download", "start", extra={"reportName": report_name, "exportKind": export_kind})
download_event_started_at = time.monotonic()
_report_dsv_chain_stage("excel_download_event", "start", extra={"reportName": report_name})
_report_dsv_chain_stage("excel_download_event", "start", extra={"reportName": report_name, "exportKind": export_kind})
try:
with page.expect_download(timeout=_dsv_download_wait_ms()) as download_info:
_click_dsv_export_excel(page)
_click_dsv_export_excel(page, kind=export_kind)
except Exception as exc:
selected = _find_dsv_report_result_frame(page)
selected = _find_dsv_report_result_frame(page, kind=export_kind)
selected_frame_index = selected[0] if selected is not None else None
selected_frame = selected[1] if selected is not None else None
selected_frame_name = ""
@@ -1437,7 +1710,11 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
selected_frame_url = str(selected_frame.url or "")
except Exception:
selected_frame_url = ""
report_state = _get_dsv_report_result_state(selected_frame) if selected_frame is not None else {}
report_state = (
_get_dsv_report_result_state(selected_frame, kind=export_kind)
if selected_frame is not None
else {}
)
export_controls = _probe_dsv_report_export_controls(selected_frame) if selected_frame is not None else {}
print(
_build_download_timeout_log(
@@ -1558,6 +1835,11 @@ wait_dsv_report_ready = _wait_dsv_report_ready
dsv_report_has_inventory_data_rows = _dsv_report_has_inventory_data_rows
wait_dsv_report_inventory_rows = _wait_dsv_report_inventory_rows
ensure_dsv_inventory_rows_or_export_fallback = _ensure_dsv_inventory_rows_or_export_fallback
dsv_report_has_receipt_data_rows = _dsv_report_has_receipt_data_rows
wait_dsv_report_receipt_rows = _wait_dsv_report_receipt_rows
ensure_dsv_receipt_rows_or_export_fallback = _ensure_dsv_receipt_rows_or_export_fallback
dsv_export_kind = _dsv_export_kind
dsv_body_markers_for_kind = _dsv_body_markers_for_kind
fill_dsv_filter_if_needed = _fill_dsv_filter_if_needed
fill_dsv_multi_select = _fill_dsv_multi_select
fill_report_parameter = _fill_report_parameter
@@ -2,8 +2,11 @@
scripts/freight_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 内操作并等待控件启用。
依赖:Playwright Page/Frame;由 dsv_report_export.fill_report_parameters 委托调用。
逻辑:识别 multi-value checkbox 与 ValidValue select,在 report iframe 内操作并等待控件启用;
控件 ID 按报表名模板解析(含库存 3lv/JDA 与收料 Receipt Detail);
同名报表可用 `报表名@program_label` 覆盖站点差异(如 Receipt Detail@AWSRTM → ctl29 multi_value);
模板命中时整表替换默认控件,禁止默认 ctl17_ddValue 污染 multi_value 回退路径。
"""
from __future__ import annotations
@@ -43,7 +46,12 @@ def _normalize_report_name(report_name: str) -> str:
# - 3lv 版(On Hand Inventory By Location 3lv,Bison/AWSBI):Warehouse 是原生 select(ddValue);
# - JDA 版(On Hand Inventory by Location,Moerdijk 等):Warehouse 是 txtValue + toggle + divDropDown
# 组成的多选框下拉(multi_value),历史 YAML 为该源配置的 selectors 即源于此。
# 模板按"归一化报表名"精确匹配;未命中时回退 _DSV_REPORT_PARAM_DEFAULTS(保持旧行为)。
# - Receipt Detail(Bison/AWSBI 收料):Warehouse 亦为原生 select,但控件位是 ctl27(非库存 ctl17);
# 父容器 data-parametername=p_dns_cd_wh(2026-09-28 实机 DOM 核对)。
# - Receipt Detail@AWSRTM(Moerdijk 收料):Warehouse 与库存 JDA 同构为 multi_value,控件位 ctl29
# (2026-09-28 实机:txtValue + glyphui-downarrow + divDropDown)。
# 模板按"归一化报表名"精确匹配;可用 `报表名@program_label` 覆盖站点差异;
# 未命中时回退 _DSV_REPORT_PARAM_DEFAULTS(保持旧行为)。
_DSV_REPORT_PARAM_TEMPLATES: dict[str, dict[str, dict[str, str]]] = {
"on hand inventory by location 3lv": {
"Warehouse": {
@@ -59,24 +67,54 @@ _DSV_REPORT_PARAM_TEMPLATES: dict[str, dict[str, dict[str, str]]] = {
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
},
},
"receipt detail": {
"Warehouse": {
"control": "select",
# 实机:#ReportViewerMain_ctl08_ctl27[data-parametername=p_dns_cd_wh] > select#..._ddValue
"selector": "#ReportViewerMain_ctl08_ctl27_ddValue",
},
},
"receipt detail@awsrtm": {
"Warehouse": {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl29_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl29_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl29_divDropDown",
},
},
}
def resolve_parameter_controls(report_name: str | None, label: str) -> dict[str, str]:
def resolve_parameter_controls(
report_name: str | None,
label: str,
*,
program_label: str | None = None,
) -> dict[str, str]:
"""
按(报表名, 参数名)解析 SSRS 控件配置;报表模板优先,未命中返回空 dict。
按(报表名[, program_label], 参数名)解析 SSRS 控件配置;站点覆盖优先。
核心逻辑:先查 `归一化报表名@program_label`(如 receipt detail@awsrtm),
再查裸报表名;均未命中返回空 dict,由调用方回退参数名默认值。
Args:
report_name: 当前报表名(如 navigation.report_name),允许为空。
label: 参数名(Owner / PutawayZone / Warehouse)。
program_label: 可选业务标签(如 AWSRTM),用于同名报表的站点控件差异。
Returns:
dict[str, str]: 控件配置(control/selector 或 control/text/toggle/dropdown);
报表未登记时为空 dict,由调用方回退参数名默认值。
报表未登记时为空 dict。
"""
key = _normalize_report_name(report_name)
program = _normalize_report_name(program_label)
label_key = str(label or "").strip()
if key and program:
qualified = _DSV_REPORT_PARAM_TEMPLATES.get(f"{key}@{program}") or {}
if label_key in qualified:
return dict(qualified[label_key])
template = _DSV_REPORT_PARAM_TEMPLATES.get(key) or {}
return dict(template.get(str(label or "").strip()) or {})
return dict(template.get(label_key) or {})
def _iter_dsv_report_roots(page: Any) -> list[Any]:
@@ -250,10 +288,17 @@ def _fill_multi_value_parameter(
select_all: bool = False,
) -> bool:
"""
填充 SSRS MultiValueParameterInputControl(Owner / PutawayZone)。
核心逻辑:展开 dropdown → 按 label 勾选/取消 checkbox → 关闭 dropdown。
填充 SSRS MultiValueParameterInputControl(Owner / PutawayZone / Warehouse)。
核心逻辑:展开 dropdown → 取消 (Select All) → 按 label 勾选目标 checkbox
(触发 OnValidValueClick 以写入 HiddenIndices)→ 关闭 dropdown;
最后核对 txtValue 是否已包含目标值。
"""
config = {**_DSV_REPORT_PARAM_DEFAULTS.get(label, {}), **(config_override or {})}
# 覆盖优先且整表采用:避免默认 Warehouse.selector=ctl17_ddValue 残留进 multi_value 配置。
if config_override and config_override.get("control") == "multi_value":
config = dict(config_override)
else:
config = {**_DSV_REPORT_PARAM_DEFAULTS.get(label, {}), **(config_override or {})}
if config.get("control") != "multi_value":
return False
cleaned = [str(item).strip() for item in values if str(item).strip()]
@@ -264,7 +309,7 @@ def _fill_multi_value_parameter(
if text_locator is not None and not select_all:
try:
current = str(text_locator.input_value(timeout=2_000) or "").strip()
if current and all(item in current for item in cleaned):
if current and all(item.casefold() in current.casefold() for item in cleaned):
print(f"[dsv-filter] {label} already set text={current!r}")
return True
except Exception:
@@ -278,11 +323,26 @@ def _fill_multi_value_parameter(
except Exception:
pass
root, _ = _find_locator(page, config["dropdown"])
# dropdown 在导航重试后可能晚于 form-ready 出现;比通用 _find_locator(1s) 稍长等待。
root, dropdown_locator = None, None
dropdown_deadline = time.monotonic() + min(8.0, max(2.0, timeout_ms / 1000))
while time.monotonic() < dropdown_deadline:
root, dropdown_locator = _find_locator(page, config["dropdown"])
if root is not None and dropdown_locator is not None:
break
time.sleep(0.25)
if root is None:
print(
f"[dsv-filter] {label} multi_value dropdown not found "
f"selector={config.get('dropdown')!r}",
file=sys.stderr,
)
return False
desired = {item.casefold() for item in cleaned}
# Warehouse / PutawayZone:精确勾选目标项;先清 (Select All),否则 HiddenIndices 不更新、
# txtValue 栏位看起来勾了但提交仍空(AWSRTM Receipt Detail ctl29 实机)。
restrict_to_desired = label in {"PutawayZone", "Warehouse"} or not select_all
try:
adjusted = root.evaluate(
"""
@@ -295,8 +355,8 @@ def _fill_multi_value_parameter(
let selectAllClicked = false;
const entries = [];
for (const labelNode of labels) {
const text = normalize(labelNode.textContent);
if (!text) continue;
const entryText = normalize(labelNode.textContent);
if (!entryText) continue;
let checkbox = null;
const htmlFor = labelNode.getAttribute('for');
if (htmlFor) {
@@ -306,8 +366,8 @@ def _fill_multi_value_parameter(
checkbox = labelNode.previousElementSibling;
}
if (!checkbox || checkbox.type !== 'checkbox') continue;
const isSelectAll = text === '(Select All)' || text.toLowerCase().includes('select all');
entries.push({ text, checkbox, isSelectAll });
const isSelectAll = entryText === '(Select All)' || entryText.toLowerCase().includes('select all');
entries.push({ text: entryText, checkbox, isSelectAll });
if (selectAll && isSelectAll) {
if (!checkbox.checked) {
checkbox.click();
@@ -327,9 +387,17 @@ def _fill_multi_value_parameter(
if (selectAll) {
return changed || entries.length > 0;
}
// [STEP] 非全选:先取消 (Select All),再按 entry.text 精确勾选(禁止引用外层错误 text)。
for (const entry of entries) {
if (!entry.isSelectAll) continue;
if (entry.checkbox.checked) {
entry.checkbox.click();
changed = true;
}
}
for (const entry of entries) {
if (entry.isSelectAll) continue;
const shouldCheck = desiredValues.includes(text.toLowerCase());
const shouldCheck = desiredValues.includes(entry.text.toLowerCase());
if (restrictToDesired) {
if (entry.checkbox.checked !== shouldCheck) {
entry.checkbox.click();
@@ -340,13 +408,16 @@ def _fill_multi_value_parameter(
changed = true;
}
}
return changed || labels.length > 0;
return changed || entries.some((entry) => {
if (entry.isSelectAll) return false;
return desiredValues.includes(entry.text.toLowerCase()) && entry.checkbox.checked;
});
}
""",
{
"dropdownSelector": config["dropdown"],
"desiredValues": list(desired),
"restrictToDesired": label == "PutawayZone",
"restrictToDesired": restrict_to_desired,
"selectAll": select_all,
},
)
@@ -360,7 +431,23 @@ def _fill_multi_value_parameter(
toggle.click(timeout=2_000, force=True)
except Exception:
pass
return True
# [STEP] 关闭下拉后核对栏位文本;勾选成功但 txtValue 未写入则视为失败并走兜底。
if text_locator is not None and not select_all:
try:
time.sleep(0.3)
current = str(text_locator.input_value(timeout=2_000) or "").strip()
if current and all(item.casefold() in current.casefold() for item in cleaned):
print(f"[dsv-filter] {label} multi_value confirmed text={current!r}")
return True
print(
f"[dsv-filter] {label} multi_value txtValue not committed "
f"expected={cleaned!r} actual={current!r}",
file=sys.stderr,
)
except Exception as exc:
print(f"[dsv-filter] {label} multi_value txtValue verify failed: {exc}", file=sys.stderr)
else:
return True
except Exception as exc:
print(f"[dsv-filter] {label} multi_value checkbox failed: {exc}", file=sys.stderr)
@@ -471,12 +558,14 @@ def fill_dsv_filter_if_needed(
browser_timeout_ms: Callable[[], int],
debug_stage: Callable[..., None] | None = None,
report_name: str | None = None,
program_label: str | None = None,
) -> None:
"""
按 ReportViewer 控件类型填充 DSV 报表参数。
核心逻辑:优先使用 JSON/页面默认 selector;Warehouse 走 select_option,Owner/PutawayZone 走 checkbox。
报表模板(_DSV_REPORT_PARAM_TEMPLATES)登记了同类报表的控件差异:传入 report_name 时,
先按模板选择 multi_value/select;未命中的报表回退参数名默认值(旧行为)。
核心逻辑:报表模板(report_name + program_label)命中时整表替换默认控件;
multi_value(如 Receipt Detail@AWSRTM Warehouse=ctl29)优先勾选 checkbox,
失败时只回退同模板 txtValue,禁止残留默认 ctl17_ddValue 误走库存 select。
"""
text = str(value or "").strip()
if not text:
@@ -488,20 +577,32 @@ def fill_dsv_filter_if_needed(
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
# Warehouse 等参数值常出现在下拉选项文本中;仅凭页面可见会误判「已填充」而跳过勾选,
# 导致 txtValue/HiddenIndices 仍空(AWSRTM Receipt Detail)。此类参数走控件路径自检。
if label not in {"Warehouse", "Owner", "PutawayZone"}:
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 = dict(_DSV_REPORT_PARAM_DEFAULTS.get(label, {}))
# 报表模板优先:同一参数名在不同报表的控件长相不同(3lv select vs JDA multi_value)。
template_controls = resolve_parameter_controls(report_name, label)
# 报表模板优先:同一参数名在不同报表/站点的控件长相不同(3lv select vs JDA/AWSRTM multi_value)。
# [STEP] 模板命中时整表替换默认控件,禁止 update 残留默认 Warehouse.selector=ctl17_ddValue;
# 否则 multi_value 偶发未就绪时会误走库存默认 select(AWSRTM Receipt Detail 2026-09-29)。
template_controls = resolve_parameter_controls(
report_name, label, program_label=program_label,
)
if template_controls:
defaults.update(template_controls)
defaults = dict(template_controls)
else:
defaults = dict(_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")
# multi_value 只用 text;select 用 selector。禁止用默认 ddValue 盖住模板 txtValue。
if defaults.get("control") == "multi_value":
selector = defaults.get("text") or ""
else:
selector = custom_selector or defaults.get("selector") or defaults.get("text") or ""
if not selector and not defaults:
print(f"[dsv] skip {label} filter; no selector configured")
@@ -518,14 +619,25 @@ def fill_dsv_filter_if_needed(
_debug(f"filter-filled-{label.lower()}", text)
return
# [STEP 2] 原生 select 路径:模板为 select 或未登记时继续旧行为(ddValue + 选项等待/脚本赋值)。
select_selector = custom_selector or defaults.get("selector", "")
if select_selector and (defaults.get("control") == "select" or select_selector.endswith("ddValue")):
if _fill_select_parameter(page, label, text, select_selector, timeout_ms=timeout_ms):
# [STEP 2] 仅当控件类型确认为 select 时走 ddValue;禁止用 endswith(ddValue) 盖过 multi_value。
if defaults.get("control") == "select":
select_selector = custom_selector or defaults.get("selector", "")
if select_selector and _fill_select_parameter(
page, label, text, select_selector, timeout_ms=timeout_ms,
):
_debug(f"filter-filled-{label.lower()}", text)
return
# [STEP 3] 文本输入/脚本兜底:适用于普通文本参数与多选控件的输入框。
if not selector:
print(
f"[dsv-filter] {label} control probe: "
f"{json.dumps(_probe_report_parameter_controls(page), ensure_ascii=False)[:1500]}",
file=sys.stderr,
)
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
_debug(f"filter-failed-{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):
@@ -562,15 +674,18 @@ def fill_dsv_multi_select_parameter(
select_all: bool = False,
browser_timeout_ms: Callable[[], int],
report_name: str | None = None,
program_label: str | None = None,
) -> bool:
"""
填充由 YAML `mode: multi_select` 显式声明的 SSRS checkbox 下拉参数。
【AI 触发时机】:当 DSV 报表参数不是原生 select,而是 `txtValue + divDropDown + checkbox`
组合控件时调用;例如 AWSAMS 的 Warehouse 下拉需要全选。
核心逻辑:selectors 缺省时按报表模板(report_name)解析控件;两者都没有则返回 False。
组合控件时调用;例如 AWSAMS / AWSRTM 的 Warehouse 下拉需要多选或全选。
核心逻辑:selectors 缺省时按报表模板(report_name + program_label)解析控件;两者都没有则返回 False。
"""
config_override = {"control": "multi_value"}
effective_selectors = selectors or (resolve_parameter_controls(report_name, label) or None)
effective_selectors = selectors or (
resolve_parameter_controls(report_name, label, program_label=program_label) or None
)
if effective_selectors:
for key in ("text", "toggle", "dropdown"):
value = str(effective_selectors.get(key) or "").strip()
@@ -1,4 +1,11 @@
"""Crane 收料报表导出适配器。"""
"""
scripts/freight_rpa/receipt/receipt_crane_export.py
用途:Crane 收料报表导出适配器——固定 Inbound Details,委托共享 crane_report_export。
依赖:crane_report_export、crane_session。
逻辑:receipt_rpa_worker 按 connector_type=crane 调用;写入 __download_dir 供共享
driver 在 Playwright 未返回 Download 时做目录兜底。
"""
from __future__ import annotations
@@ -36,7 +43,12 @@ def export_receipt_report(
page: Any, unit: dict[str, Any], *, env: Callable[[str, str], str], browser_timeout_ms: int,
select_or_fill: Callable[..., None], click_text: Callable[..., None], first_in_profile: bool,
) -> Any:
"""创建并下载唯一 Description 对应的 Crane Inbound Details 文件,禁止按最新历史文件选择。"""
"""
创建并下载唯一 Description 对应的 Crane Inbound Details 文件。
核心逻辑:固定 scheduled_report_name=Inbound Details;把 unit.__download_dir
写入 source,供共享 crane_report_export 目录兜底(对齐库存)。
"""
report_path = dict(unit.get('report_path_json') or {})
if str(report_path.get('report_name') or '').strip() != 'Inbound Details':
raise RuntimeError('Crane receipt report must be Inbound Details')
@@ -50,6 +62,8 @@ def export_receipt_report(
source = {
'entry_url': entry_url,
'scheduled_report_name': 'Inbound Details',
# 与库存/DBS 同构:供 crane_report_export 在 Playwright 未返回 Download 时目录兜底。
'__download_dir': str(unit.get('__download_dir') or ''),
}
return crane_report_export.export_crane_inventory_report(
page, source, trigger={'callback_id': unit.get('callback_id')}, env=env,
@@ -1,4 +1,14 @@
"""DBS 收料报表导出适配器。"""
"""
scripts/freight_rpa/receipt/receipt_dbs_export.py
用途:DBS 收料报表导出适配器——把 unit 转成与库存同构的 DSV source,再委托共享导出驱动。
依赖:connectors/dsv/dsv_report_export。
逻辑:receipt_rpa_worker 按 connector_type=dbs 调用;批内会话/导航复用由 Worker
调用 prepare_dsv_batch_export_step 完成;本模块只负责 source 组装与单次导出。
source 写入 __export_kind__=receipt,共享驱动用 Receipt Detail 就绪/行探针。
query_parameters 原样下发;仅当 unit.warehouse_id 有值时追加单值 Warehouse
(兼容旧 trigger);空条件表示使用页面默认,不强制 Warehouse。
"""
from __future__ import annotations
@@ -22,21 +32,68 @@ from typing import Any
import dsv_report_export
def export_receipt_report(page: Any, unit: dict[str, Any], *, entry_url: str, first_in_profile: bool) -> Any:
"""在既有 DBS 登录态内执行收料路径、Warehouse 与受控非日期条件。"""
source = {
def build_receipt_dsv_source(unit: dict[str, Any], *, entry_url: str) -> dict[str, Any]:
"""
将收料 unit 组装为共享 dsv_report_export 可消费的 source。
核心逻辑:report_path_json → navigation(驱动只读 navigation/query);
parameters 取自 query_parameters_json;有 warehouse_id 时追加单值 Warehouse。
Args:
unit: 收料 trigger 单元(含 report_path_json / query_parameters_json 等)。
entry_url: 该 Profile 分组的登录入口 URL。
Returns:
与库存 trigger source 同构的 dict,可供 prepare_dsv_batch_export_step 与导出使用。
"""
report_path = dict(unit.get('report_path_json') or {})
source: dict[str, Any] = {
'entry_url': entry_url,
'report_path_json': dict(unit.get('report_path_json') or {}),
'report_path_json': report_path,
# 与库存 trigger 同构:Source.report_path_json → navigation,供菜单导航使用。
'navigation': report_path,
'parameters': list(unit.get('query_parameters_json') or []),
'__download_dir': str(unit.get('__download_dir') or ''),
# 显式标记收料导出:共享 dsv_report_export 用 Receipt Detail 就绪/行探针,不用库存字段。
'__export_kind__': 'receipt',
}
# 兼容旧 trigger:仅当排程曾写入 warehouse_id 时追加,避免与参数里已有 Warehouse 双写需由旧载荷保证互斥。
warehouse_id = str(unit.get('warehouse_id') or '').strip()
if not warehouse_id:
raise RuntimeError('DBS receipt unit requires warehouse_id')
source['parameters'].append({
'name': 'Warehouse', 'mode': 'single', 'values': [warehouse_id],
'required': True, 'select_all': False,
})
if first_in_profile:
dsv_report_export.ensure_dsv_session(page, entry_url)
return dsv_report_export.export_dsv_inventory_source(page, {'action': 'receipt_export_batch'}, source)
if warehouse_id:
source['parameters'].append({
'name': 'Warehouse', 'mode': 'single', 'values': [warehouse_id],
'required': True, 'select_all': False,
})
return source
def export_receipt_report(
page: Any,
unit: dict[str, Any],
*,
entry_url: str,
skip_navigation: bool = False,
) -> Any:
"""
在既有 DBS 登录态内执行收料路径与受控非日期条件。
核心逻辑:组装 source 后委托 export_dsv_inventory_source;会话登录与参数页复用
由 Worker 侧 prepare_dsv_batch_export_step 完成。skip_navigation=True 时跳过菜单导航,
直接在已就绪的参数页填参导出(同导航批内复用)。
Args:
page: 当前 Playwright Page(批内复用同一 tab,禁止每源 new_page)。
unit: 收料 trigger 单元。
entry_url: 登录入口 URL。
skip_navigation: 为 True 时跳过报表菜单导航(参数页已由 prepare 就绪)。
Returns:
Playwright Download 对象。
"""
source = build_receipt_dsv_source(unit, entry_url=entry_url)
return dsv_report_export.export_dsv_inventory_source(
page,
{'action': 'receipt_export_batch'},
source,
skip_navigation=skip_navigation,
)
@@ -0,0 +1,106 @@
"""
scripts/freight_rpa/receipt/receipt_excel_empty.py
用途:收料 Excel「有表头无明细」判空(真相源,对齐库存 Excel 判空)。
依赖:openpyxl(运行期可选;缺失时不强制 empty)。
逻辑:receipt_rpa_worker 落盘校验后调用;标题行(如 AWS Receipt Detail)
不得当成表头,否则真表头会被误判为明细导致假 success。
"""
from __future__ import annotations
from pathlib import Path
class NoReceiptDataError(RuntimeError):
"""收料报表可打开且有表头,但无业务明细行(合法 empty / no_receipt_data)。"""
def _normalize_row_joined(row: tuple | list) -> str:
"""
将一行单元格规范为小写比较串。
核心逻辑:换行压成空格(SSRS 表头常为 External\\nASN #),去空白后用 | 拼接。
"""
parts: list[str] = []
for cell in row:
if cell is None:
continue
text = ' '.join(str(cell).replace('\n', ' ').replace('\r', ' ').split()).strip()
if text:
parts.append(text.lower())
return ' | '.join(parts)
def is_receipt_excel_header_row(joined: str) -> bool:
"""
判断是否为收料列标题行(非报表标题行)。
核心逻辑:要求 External ASN / WMS Receipt / Supplier ID+AWS Sku 等组合特征;
单独含 receipt(如「AWS Receipt Detail」)不得命中。
"""
if not joined:
return False
if 'external asn' in joined and (
'wms receipt' in joined
or 'aws sku' in joined
or 'supplier id' in joined
or 'supplier' in joined
):
return True
if 'warehouse' in joined and 'external asn' in joined:
return True
if 'supplier id' in joined and 'aws sku' in joined:
return True
return False
def receipt_excel_has_detail_rows(path: Path) -> bool | None:
"""
判断收料 Excel 列标题之后是否有明细行。
核心逻辑:先定位严格表头行,再扫描其后非空行;无法识别表头时返回 None
(不强制 empty,由结构校验兜底)。
Returns:
True: 有明细;False: 有表头无明细;None: 未识别表头形态。
"""
try:
from openpyxl import load_workbook
except ImportError:
return None
try:
workbook = load_workbook(path, read_only=True, data_only=True)
except Exception:
return None
try:
worksheet = workbook.active
if worksheet is None:
return None
header_idx: int | None = None
for idx, row in enumerate(worksheet.iter_rows(max_row=120, values_only=True), start=1):
joined = _normalize_row_joined(row or ())
if not joined:
continue
if header_idx is None:
if is_receipt_excel_header_row(joined):
header_idx = idx
continue
if idx > header_idx:
return True
if header_idx is None:
return None
return False
finally:
workbook.close()
def enforce_receipt_excel_not_empty(path: Path) -> None:
"""
有表头无明细时记为无收料(NoReceiptDataError → empty / no_receipt_data)。
Raises:
NoReceiptDataError: 可识别表头但无业务行;message 固定为 no_receipt_data。
"""
if receipt_excel_has_detail_rows(path) is False:
raise NoReceiptDataError('no_receipt_data')
+534 -44
View File
@@ -1,4 +1,13 @@
"""独立货代收料 RPA Worker:仅消费 receipt trigger,不触及库存 Worker 的目录或 callback。"""
"""
scripts/freight_rpa/receipt/receipt_rpa_worker.py
用途:独立货代收料 RPA Worker——仅消费 receipt trigger,不触及库存 Worker 的目录或 callback。
依赖:rpa_common、trigger_consumer、rpa_heartbeat、download_artifact_fallback、
receipt_excel_empty、receipt_dbs_export、receipt_crane_export、connectors/dsv/dsv_report_export。
逻辑:排程写入 receipt trigger → 本进程领取并按 connector/profile 分组串行导出 →
导出重试只覆盖落盘/校验(对齐库存);有表头无明细 → empty/no_receipt_data;
成功后先轻量 batch-progress 再 ready 归档回调;ready 超时不得重新下载。
"""
from __future__ import annotations
@@ -33,12 +42,35 @@ if _RPA_ROOT is not None:
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
from download_artifact_fallback import wait_for_new_download_file as _wait_for_new_download_file # noqa: E402
import rpa_heartbeat # noqa: E402
import worker_logging # noqa: E402
import worker_disk_cleanup # noqa: E402
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
import dsv_report_export # noqa: E402
import receipt_crane_export # noqa: E402
import receipt_dbs_export # noqa: E402
from receipt_excel_empty import ( # noqa: E402
NoReceiptDataError,
enforce_receipt_excel_not_empty as _enforce_receipt_excel_not_empty,
)
_EXPORT_UNIT_MAX_ATTEMPTS = 2
_EXPORT_UNIT_RETRY_WAIT_SECONDS = 30
_RECEIPT_EXCEL_MIN_BYTES = 512
# 结构校验可用较宽标记;「有表头无明细」判空见 receipt_excel_empty(禁止用单字 receipt 当表头)。
_RECEIPT_EXCEL_HEADER_MARKERS = (
'receipt',
'inbound',
'asn',
'po number',
'po #',
'supplier id',
'aws sku',
'sku',
'quantity',
'received',
)
def _backend_dir() -> Path:
@@ -66,20 +98,61 @@ def _require_dir(variable: str) -> Path:
return path
def _post_callback(payload: dict[str, Any]) -> None:
"""向独立收料 callback 上报一个单元结果,认证密钥从进程 Secret 注入。"""
def _post_rpa(path: str, payload: dict[str, Any], *, timeout: int = 30) -> None:
"""向 HXOPS 收料 RPA API 上报;认证密钥从进程 Secret 注入。"""
key = env('SHIPPING_NOTICE_TOOL_API_KEY') or env('INTEGRATION_API_KEY')
if not key:
raise RuntimeError('Missing SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY')
base = env('HXOPS_API_BASE', 'http://127.0.0.1:5052').rstrip('/')
request = urllib.request.Request(
f'{base}/api/shipping-notice/rpa/receipt-batch-ready',
f'{base}{path}',
data=json.dumps(payload, ensure_ascii=False).encode('utf-8'), method='POST',
headers={'Content-Type': 'application/json', 'X-Integration-Key': key},
)
with urllib.request.urlopen(request, timeout=30) as response:
with urllib.request.urlopen(request, timeout=timeout) as response:
if response.status < 200 or response.status >= 300:
raise RuntimeError(f'receipt callback failed: HTTP {response.status}')
raise RuntimeError(f'receipt rpa callback failed: HTTP {response.status} path={path}')
def _post_callback(payload: dict[str, Any]) -> None:
"""向独立收料 callback 上报一个单元终态结果。"""
_post_rpa('/api/shipping-notice/rpa/receipt-batch-ready', payload)
def _mark_unit_processing(unit: dict[str, Any]) -> None:
"""开始导出前标记 processing;失败不影响导出主链路。"""
try:
_post_rpa(
'/api/shipping-notice/rpa/receipt-unit-progress',
{
'schema_version': 'shipping_receipt_rpa.v1',
'callback_id': unit.get('callback_id'),
'status': 'processing',
},
)
except Exception as exc:
print(f'[receipt-unit] processing progress failed: {exc}', file=_sys.stderr)
def _emit_batch_progress(body: dict[str, Any], counts: dict[str, int]) -> None:
"""每完成一笔导出回传累计进度(对齐库存 inventory-batch-progress)。"""
schedule_run_id = body.get('schedule_run_id')
if schedule_run_id is None:
return
try:
_post_rpa(
'/api/shipping-notice/rpa/receipt-batch-progress',
{
'schema_version': 'shipping_receipt_rpa.v1',
'schedule_run_id': schedule_run_id,
'batch_run_no': body.get('batch_run_no') or body.get('run_no'),
'success_count': int(counts.get('success') or 0),
'skipped_count': int(counts.get('empty') or 0),
'failed_count': int(counts.get('failed') or 0),
},
)
except Exception as exc:
print(f'[receipt-batch] progress callback failed: {exc}', file=_sys.stderr)
@contextmanager
@@ -116,25 +189,73 @@ def _profile_credentials(unit: dict[str, Any]):
os.environ[name] = old_value
def _open_browser(download_dir: Path, reuse_session: bool = False):
def _session_reuse_enabled() -> bool:
"""
收料是否复用持久浏览器 Profile。
核心逻辑:对齐库存——未设置或空值时默认开启;仅显式 false 时关闭。
"""
raw = env('FREIGHT_RPA_WORKER_SESSION_REUSE')
if raw is None or str(raw).strip() == '':
return True
return str(raw).strip().strip("\"'").lower() == 'true'
def _sanitize_profile_dir_segment(value: str) -> str:
"""将 connector / profile_code 收成可作目录名的安全片段。"""
text = str(value or '').strip()
cleaned = ''.join(ch if (ch.isalnum() or ch in '-_') else '_' for ch in text)
return (cleaned[:96] or 'default')
def _session_profile_dir(connector_type: str, profile_code: str = '') -> Path:
"""
按 connector + RPA Profile 隔离的持久收料会话目录。
核心逻辑:形如 `{connector}__{profile_code}_session`(dbs/crane 与库存 dsv360/crane_footprint
命名空间分离,避免串 Cookie);禁止所有收料源共用单一 receipt_session。
"""
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
connector = _sanitize_profile_dir_segment(connector_type or 'unknown')
code = _sanitize_profile_dir_segment(profile_code)
return profile_root / f'{connector}__{code}_session'
def _open_browser(
download_dir: Path,
*,
reuse_session: bool = False,
connector_type: str = '',
profile_code: str = '',
):
"""为一个 receipt Profile 分组创建浏览器上下文,组内登录一次、串行导出。
reuse_session=False(默认):一次性临时 Profile(receipt_* 前缀),批次结束即删,隔离最干净。
reuse_session=True:持久会话 Profile(receipt_session),跨批次复用登录态,适用于同日重跑/重试;
持久目录命中磁盘清理的 *_session 豁免规则,不会被孤儿清理删除。
reuse_session=True 且 SESSION_REUSE 开启:持久 `{connector}__{profile}_session`;
否则一次性临时 Profile(receipt_* 前缀),批次结束即删。
"""
try:
from playwright.sync_api import sync_playwright
except ImportError as exc:
raise RuntimeError('Playwright is required for real receipt RPA') from exc
profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
if reuse_session:
runtime_profile = profile_root / 'receipt_session'
use_reused = bool(reuse_session) and _session_reuse_enabled() and bool(connector_type)
if use_reused:
runtime_profile = _session_profile_dir(connector_type, profile_code)
runtime_profile.mkdir(parents=True, exist_ok=True)
profile_mode = 'session_reuse'
else:
runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root)))
profile_mode = 'temporary'
print(
f'[browser] profile_mode={profile_mode} connector={connector_type or "-"} '
f'profile={profile_code or "-"} dir={runtime_profile.name!r}'
)
playwright = sync_playwright().start()
options: dict[str, Any] = {'headless': env('FREIGHT_RPA_WORKER_HEADLESS', 'false').lower() == 'true', 'accept_downloads': True, 'downloads_path': str(download_dir)}
options: dict[str, Any] = {
'headless': env('FREIGHT_RPA_WORKER_HEADLESS', 'false').lower() == 'true',
'accept_downloads': True,
'downloads_path': str(download_dir),
}
channel = env('FREIGHT_RPA_WORKER_BROWSER_CHANNEL')
if channel:
options['channel'] = channel
@@ -144,19 +265,183 @@ def _open_browser(download_dir: Path, reuse_session: bool = False):
return playwright, context, page, runtime_profile
def _save_download(download: Any, drop_dir: Path, unit: dict[str, Any]) -> Path:
"""保存本单元下载文件到 receipt drop 并计算 callback 需要的身份。"""
def _open_clean_batch_page(context: Any, current_page: Any | None) -> Any:
"""
在同一登录上下文中切换到干净页面,隔离上一站的 DSV 报表状态。
核心逻辑:对齐库存 Worker——新开空白页并关闭旧页;Cookie 仍在 context 内,
仅用于会话准备失败后的一次完整登录重试,禁止作为常态「每源新开空白页」。
Args:
context: 已建立登录态的 Playwright browser context。
current_page: 上一站页面;关闭以避免报表 iframe / 下载菜单残留。
Returns:
可重新进入收料报表的空白页面。
"""
next_page = context.new_page()
next_page.set_default_timeout(browser_timeout_ms())
if current_page is not None:
try:
current_page.close()
except Exception as exc:
print(f'[receipt-batch] close previous page failed: {exc}', file=_sys.stderr)
return next_page
def _download_dir_baseline_names(drop_dir: Path) -> set[str]:
"""
导出前拍摄下载目录已有文件名,供目录兜底识别「本次新文件」。
核心逻辑:仅收集普通文件名;目录不可读时返回空集合(对齐库存)。
"""
try:
return {path.name for path in drop_dir.iterdir() if path.is_file()}
except OSError:
return set()
def _is_playwright_target_closed_error(exc: BaseException) -> bool:
"""判断是否为 Playwright 页面/上下文已关闭导致的落盘失败。"""
message = str(exc).lower()
return 'has been closed' in message or 'target closed' in message or 'targetclosed' in message
def _persist_download_to_dest(
download: Any,
dest: Path,
*,
drop_dir: Path,
baseline_names: set[str] | None = None,
fallback_timeout_seconds: float = 60.0,
) -> None:
"""
将 Playwright Download 落到规范路径;浏览器已关闭时走 downloads_path 目录兜底。
核心逻辑:对齐库存 `_persist_download_to_dest`——先 save_as,TargetClosed
再按 baseline 等待稳定新文件后搬迁。
"""
try:
download.save_as(str(dest))
return
except Exception as exc:
if not _is_playwright_target_closed_error(exc):
raise
print(
f'[receipt-artifact] stage=download_save status=fallback '
f'reason=browser_closed path={dest.name!r}',
file=_sys.stderr,
)
artifact = _wait_for_new_download_file(
download_dir=drop_dir,
baseline_names=set(baseline_names or ()),
timeout_seconds=fallback_timeout_seconds,
)
if artifact is None:
raise
artifact.save_as(str(dest))
def _receipt_download_name(
batch_run_no: str,
source_code: str,
warehouse_id: str | None,
*,
suffix: str = '.xlsx',
) -> str:
"""
收料落盘文件名,对齐库存 `_batch_download_name`。
核心逻辑:`receipt_{run}_{source}_{wh}_{stamp}.xlsx`;空仓用 NA。
不写入 callback_id(关联仍靠 callback JSON)。
Args:
batch_run_no: trigger 顶层批次号。
source_code: 库存源编码(辨识用)。
warehouse_id: 可选仓码;空则 NA。
suffix: 扩展名,默认 .xlsx。
Returns:
安全化后的文件名(不含目录)。
"""
safe_run = ''.join(ch for ch in str(batch_run_no or '') if ch.isalnum() or ch in {'-', '_'}) or 'receipt'
safe_source = ''.join(ch for ch in str(source_code or '') if ch.isalnum() or ch in {'-', '_'}) or 'UNKNOWN'
safe_wh = ''.join(ch for ch in str(warehouse_id or '') if ch.isalnum() or ch in {'-', '_'}) or 'NA'
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S')
return f'receipt_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'
def _save_download(
download: Any,
drop_dir: Path,
unit: dict[str, Any],
*,
batch_run_no: str,
baseline_names: set[str] | None = None,
fallback_timeout_seconds: float = 60.0,
) -> Path:
"""
保存本单元下载文件到 receipt drop;必要时在浏览器关闭后走目录兜底。
核心逻辑:按 run+source(+仓) 命名后 `_persist_download_to_dest`;空文件拒绝。
"""
suffix = Path(str(download.suggested_filename or '')).suffix.lower() or '.xlsx'
if suffix != '.xlsx':
raise RuntimeError('receipt report download must be xlsx')
safe_callback = ''.join(ch for ch in str(unit['callback_id']) if ch.isalnum() or ch in {'-', '_'})
target = drop_dir / f'receipt_{safe_callback}_{datetime.utcnow():%Y%m%d%H%M%S}.xlsx'
download.save_as(str(target))
target = drop_dir / _receipt_download_name(
batch_run_no,
str(unit.get('source_code') or ''),
unit.get('warehouse_id'),
suffix=suffix,
)
_persist_download_to_dest(
download,
target,
drop_dir=drop_dir,
baseline_names=baseline_names,
fallback_timeout_seconds=fallback_timeout_seconds,
)
if target.stat().st_size <= 0:
raise RuntimeError('receipt report download is empty')
return target
def _validate_receipt_excel(path: Path) -> None:
"""
校验收料 Excel 可打开且具备报表基本结构。
核心逻辑:对齐库存 `_validate_inventory_excel`——拒过小/HTML 伪装文件;
前几行或 sheet 标题须含收料报表特征,避免错误页当 success 归档。
"""
size = path.stat().st_size
if size < _RECEIPT_EXCEL_MIN_BYTES:
raise RuntimeError(f'downloaded receipt Excel is too small ({size} bytes)')
try:
from openpyxl import load_workbook
except ImportError as exc:
raise RuntimeError('openpyxl required to validate receipt 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 _RECEIPT_EXCEL_HEADER_MARKERS):
if 'receipt' not in title and 'inbound' not in title:
raise RuntimeError('downloaded file is not valid Excel: missing receipt report headers')
finally:
workbook.close()
def _validate_unit(unit: dict[str, Any]) -> None:
"""拒绝不完整或非 v1 单元,日期参数永不传入 DBS/Crane driver。"""
for key in ('callback_id', 'source_code', 'connector_type', 'rpa_profile_code', 'login_url'):
@@ -175,58 +460,263 @@ def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.RECEIPT_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
def _report_empty(unit: dict[str, Any], exc: NoReceiptDataError) -> None:
"""无业务明细的合法结果:回调 empty + no_receipt_data(后端 finalize 计 skipped)。"""
print(f'[receipt-unit] empty source={unit.get("source_code")} callback={unit.get("callback_id")} message={str(exc)[:200]}')
_post_callback({
'schema_version': 'shipping_receipt_rpa.v1',
'callback_id': unit.get('callback_id'),
'status': 'empty',
'error_code': 'no_receipt_data',
'error_message': str(exc)[:2000] or 'no_receipt_data',
})
def _is_login_session_error(exc: BaseException) -> bool:
"""登录/会话类偶发异常可干净页重试;凭据校验类不重试。"""
message = str(exc).lower()
login_related = any(token in message for token in ('login', 'session', 'oauth'))
credential_mismatch = any(token in message for token in ('invalid', 'verification'))
return login_related and not credential_mismatch
def _export_unit_download(
*,
connector: str,
unit: dict[str, Any],
group: list[dict[str, Any]],
index: int,
login_url: str,
page: Any,
context: Any,
drop_dir: Path,
) -> tuple[Any, Any]:
"""
导出单个收料单元的 Playwright Download;必要时干净页重试会话。
Returns:
(download, page):download 为 Playwright Download;page 可能已切换为干净页。
"""
unit['__download_dir'] = str(drop_dir)
if connector == 'dbs':
source = receipt_dbs_export.build_receipt_dsv_source(unit, entry_url=login_url)
previous_unit = group[index - 1] if index > 0 else None
previous_source = (
receipt_dbs_export.build_receipt_dsv_source(previous_unit, entry_url=login_url)
if previous_unit is not None else None
)
skip_navigation = False
try:
skip_navigation = bool(
dsv_report_export.prepare_dsv_batch_export_step(
page, login_url, previous_source, source, index=index,
)
)
except Exception as exc:
if not _is_login_session_error(exc):
raise
print(
f'[receipt-batch] dbs session prepare failed for {unit.get("source_code")}, '
f'retry with clean page: {exc}',
file=_sys.stderr,
)
page = _open_clean_batch_page(context, page)
skip_navigation = bool(
dsv_report_export.prepare_dsv_batch_export_step(
page, login_url, None, source, index=0,
)
)
download = receipt_dbs_export.export_receipt_report(
page, unit, entry_url=login_url, skip_navigation=skip_navigation,
)
return download, page
first_in_profile = index == 0
try:
download = receipt_crane_export.export_receipt_report(
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
select_or_fill=select_or_fill, click_text=click_text,
first_in_profile=first_in_profile,
)
return download, page
except Exception as exc:
# Crane 无 DBS 式 prepare 步骤:导出期登录/会话失败时干净页 + 强制首源登录重试一次。
if not _is_login_session_error(exc):
raise
print(
f'[receipt-batch] crane session failed for {unit.get("source_code")}, '
f'retry with clean page: {exc}',
file=_sys.stderr,
)
page = _open_clean_batch_page(context, page)
download = receipt_crane_export.export_receipt_report(
page, unit, env=env, browser_timeout_ms=browser_timeout_ms(),
select_or_fill=select_or_fill, click_text=click_text,
first_in_profile=True,
)
return download, page
def _write_mock_receipt_excel(path: Path) -> None:
"""Mock 模式写出带表头+一行明细的合法收料 Excel,便于走校验与 success 回调。"""
from openpyxl import Workbook
workbook = Workbook()
sheet = workbook.active
sheet.title = 'ReceiptDetail'
sheet.append(['ASN', 'PO Number', 'AWS Sku', 'Quantity Received'])
sheet.append(['ASN-MOCK-1', 'PO-1', 'SKU-1', 1])
workbook.save(path)
workbook.close()
def _post_unit_ready(unit: dict[str, Any], output: Path) -> None:
"""落盘成功后上报 receipt-batch-ready(归档);调用方须放在导出重试之外。"""
_post_callback({
'schema_version': 'shipping_receipt_rpa.v1',
'callback_id': unit['callback_id'],
'status': 'success',
'file_path': str(output),
'original_filename': output.name,
'sha256': hashlib.sha256(output.read_bytes()).hexdigest(),
})
def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
"""按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 收料单元。"""
"""
按 connector/profile/login URL 分组,单次登录后串行处理全部 DBS/Crane 收料单元。
核心逻辑:DBS 与库存对齐——同 Profile 组内复用同一 tab;导出失败批次内最多重试 2 次,
**重试只覆盖导出/落盘/校验**(对齐库存 record_result 前段)。落盘成功后先轻量
``receipt-batch-progress``(管理端实时笔数),再调 ``receipt-batch-ready`` 归档;
ready/empty/failed 回调失败不得触发重新下载(2026-09-28 偶发同源双文件根因)。
"""
units = body.get('units')
if body.get('schema_version') != 'shipping_receipt_rpa.v1' or body.get('action') != 'receipt_export_batch' or not isinstance(units, list) or not units:
raise RuntimeError('invalid receipt trigger contract')
batch_run_no = str(body.get('batch_run_no') or body.get('run_no') or 'receipt').strip() or 'receipt'
grouped: dict[tuple[str, str, str], list[dict[str, Any]]] = {}
for item in units:
if not isinstance(item, dict):
raise RuntimeError('receipt unit must be object')
_validate_unit(item)
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
for (connector, _profile, login_url), group in grouped.items():
print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}')
progress_counts = {'success': 0, 'empty': 0, 'failed': 0}
for (connector, profile_code, login_url), group in grouped.items():
print(f'[receipt-batch] connector={connector} profile={profile_code} units={len(group)}')
mock = env('FREIGHT_RPA_WORKER_MOCK', 'false').lower() == 'true'
reuse_session = env('FREIGHT_RPA_WORKER_SESSION_REUSE', 'false').lower() == 'true'
reuse_session = _session_reuse_enabled()
resources = (None, None, None, None)
try:
if not mock:
resources = _open_browser(drop_dir, reuse_session=reuse_session)
resources = _open_browser(
drop_dir,
reuse_session=reuse_session,
connector_type=connector,
profile_code=profile_code,
)
playwright, context, page, profile_dir = resources
with _profile_credentials(group[0]):
for index, unit in enumerate(group):
try:
if mock:
from openpyxl import Workbook
mock_path = drop_dir / f"receipt_{unit['callback_id'].replace(':', '_')}.xlsx"
workbook = Workbook(); workbook.active.append(['Receipt RPA mock']); workbook.save(mock_path); workbook.close()
output = mock_path
else:
unit['__download_dir'] = str(drop_dir)
if connector == 'dbs':
if index:
page = context.new_page(); page.set_default_timeout(browser_timeout_ms())
download = receipt_dbs_export.export_receipt_report(page, unit, entry_url=login_url, first_in_profile=index == 0)
_mark_unit_processing(unit)
output: Path | None = None
terminal: tuple[str, BaseException] | None = None
# [RETRY] 仅导出/落盘/校验;ready 回调禁止进入本循环。
for attempt in range(1, _EXPORT_UNIT_MAX_ATTEMPTS + 1):
try:
if mock:
mock_path = drop_dir / _receipt_download_name(
batch_run_no,
str(unit.get('source_code') or ''),
unit.get('warehouse_id'),
)
_write_mock_receipt_excel(mock_path)
output = mock_path
else:
download = receipt_crane_export.export_receipt_report(page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), select_or_fill=select_or_fill, click_text=click_text, first_in_profile=index == 0)
output = _save_download(download, drop_dir, unit)
baseline_names = _download_dir_baseline_names(drop_dir)
download, page = _export_unit_download(
connector=connector,
unit=unit,
group=group,
index=index,
login_url=login_url,
page=page,
context=context,
drop_dir=drop_dir,
)
output = _save_download(
download, drop_dir, unit, batch_run_no=batch_run_no,
baseline_names=baseline_names,
)
_validate_receipt_excel(output)
_enforce_receipt_excel_not_empty(output)
break
except NoReceiptDataError as exc:
terminal = ('empty', exc)
output = None
break
except Exception as exc:
if attempt < _EXPORT_UNIT_MAX_ATTEMPTS:
print(
f'[receipt-batch] export failed {unit.get("source_code")} '
f'(attempt {attempt}/{_EXPORT_UNIT_MAX_ATTEMPTS}), '
f'retry in {_EXPORT_UNIT_RETRY_WAIT_SECONDS}s: {exc}',
file=_sys.stderr,
)
time.sleep(_EXPORT_UNIT_RETRY_WAIT_SECONDS)
continue
terminal = ('failed', exc)
output = None
# [STEP] 导出循环外:轻量 progress + 终态回调(对齐库存 progress / 批末 ready)
if terminal is not None and terminal[0] == 'empty':
try:
_report_empty(unit, terminal[1]) # type: ignore[arg-type]
except Exception as callback_exc:
print(
f'[receipt-unit] empty callback failed source={unit.get("source_code")}: {callback_exc}',
file=_sys.stderr,
)
progress_counts['empty'] += 1
_emit_batch_progress(body, progress_counts)
continue
if terminal is not None and terminal[0] == 'failed':
try:
_report_failure(unit, terminal[1]) # type: ignore[arg-type]
except Exception as callback_exc:
print(
f'[receipt-unit] failed callback failed source={unit.get("source_code")}: {callback_exc}',
file=_sys.stderr,
)
progress_counts['failed'] += 1
_emit_batch_progress(body, progress_counts)
continue
if output is None:
continue
print(
f'[receipt-unit] success source={unit["source_code"]} '
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
)
progress_counts['success'] += 1
_emit_batch_progress(body, progress_counts)
try:
_post_unit_ready(unit, output)
except Exception as callback_exc:
# 文件已落盘:回调超时只打日志,禁止回到导出重试(同源双文件根因)。
# 不调用 failed 回调,避免晚到的 ready 与 failed 竞态;人工可按 drop 文件补档。
print(
f'[receipt-unit] success source={unit["source_code"]} '
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
f'[receipt-unit] ready callback failed source={unit.get("source_code")} '
f'file={output.name}: {callback_exc}',
file=_sys.stderr,
)
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit['callback_id'], 'status': 'success', 'file_path': str(output), 'original_filename': output.name, 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()})
except Exception as exc:
_report_failure(unit, exc)
finally:
playwright, context, _page, profile_dir = resources
if context is not None:
context.close()
if playwright is not None:
playwright.stop()
# 会话复用模式保留 receipt_session 持久目录(命中清理豁免),仅一次性模式即删。
if profile_dir is not None and not reuse_session:
# 会话复用模式保留 {connector}__{profile}_session;一次性临时目录批次后删除。
if profile_dir is not None and not (reuse_session and _session_reuse_enabled()):
shutil.rmtree(profile_dir, ignore_errors=True)
@@ -5,7 +5,8 @@
.DESCRIPTION
只设置 Process 级环境变量和 receipt 专用目录;可与库存 Worker 并行运行,
二者不共享 trigger、drop 或日志目录;浏览器 Profile 共用 common/browser_profile
根(各自在其中创建隔离的一次性子目录)。
根(各自按 connector+profile 隔离会话目录)。
默认开启会话复用(SESSION_REUSE,对齐库存);需要每次全新登录时传 -NoSessionReuse。
#>
param(
[Parameter(Mandatory = $true)][ValidateSet('test', 'prod')][string]$Environment,
@@ -15,7 +16,9 @@ param(
[string]$PythonExe = 'python.exe',
[switch]$Mock,
[switch]$Headless,
# 可选跨批次会话复用:持久 receipt_session Profile(同日重跑/重试免登录);默认一次性临时 Profile。
# 默认开启收料会话复用;仅在需要强制每次全新登录时传 -NoSessionReuse。
[switch]$NoSessionReuse,
# 兼容旧文档:显式开启复用(现在默认已开启)。
[switch]$SessionReuse
)
@@ -35,8 +38,12 @@ $secret = Import-Clixml -LiteralPath $SecretFile
foreach ($required in @('ToolApiKey', 'CredentialKey')) {
if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" }
}
# freight_rpa 三层布局根:$WorkerRoot\data\freight_rpa\{inventory,receipt,common}(data 即 SMB 共享 hxops-rpa-*-data 的根,代码包 scripts 不进共享)。
# freight_rpa 三层布局根:$WorkerRoot\data\freight_rpa\{inventory,receipt,common}
$rpaRoot = Join-Path $WorkerRoot 'data\freight_rpa'
$sessionReuse = if ($NoSessionReuse) { 'false' } else { 'true' }
if ($SessionReuse -and $NoSessionReuse) {
Write-Warning '同时指定 -SessionReuse 与 -NoSessionReuse 时以 -NoSessionReuse 为准'
}
$processVars = [ordered]@{
HXOPS_API_BASE = $ApiBase
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
@@ -44,7 +51,7 @@ $processVars = [ordered]@{
FREIGHT_RPA_WORKER_ENVIRONMENT = $Environment
FREIGHT_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
FREIGHT_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
FREIGHT_RPA_WORKER_SESSION_REUSE = $(if ($SessionReuse) { 'true' } else { 'false' })
FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
FREIGHT_RPA_WORKER_POLL_SECONDS = '3'
FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot 'receipt\logs\worker.log'
@@ -55,7 +62,7 @@ $processVars = [ordered]@{
FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = '20'
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $rpaRoot 'receipt\triggers'
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $rpaRoot 'receipt\drop'
# 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile(各自在其中创建隔离的一次性子目录)。
# 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile;会话按 connector+profile 分目录。
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot 'common\browser_profile'
# 本机磁盘保留:与库存 Worker 同参(归档 trigger/drop、日志备份、孤儿 run_*/receipt_* Profile)。
FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = '7'
@@ -64,7 +71,7 @@ $processVars = [ordered]@{
}
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
try {
Write-Host "Starting receipt RPA Worker: environment=$Environment root=$WorkerRoot"
Write-Host "Starting receipt RPA Worker: environment=$Environment root=$WorkerRoot sessionReuse=$sessionReuse"
& $PythonExe $workerScript
exit $LASTEXITCODE
}