From 8b1efbedb903014e429ece1c0b539605dd58a183 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Fri, 10 Jul 2026 00:48:27 +0800 Subject: [PATCH] =?UTF-8?q?feat(schedule):=20=E5=A2=9E=E5=8A=A0=E5=BA=93?= =?UTF-8?q?=E5=AD=98=E6=BA=90=E9=80=89=E9=A1=B9=E6=8F=8F=E8=BF=B0=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E4=B8=8E=E7=AB=99=E7=82=B9ID=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/services/schedule/job_options.py | 6 +- .../shipping_inventory_rpa_finalize.py | 5 + .../schedule/shipping_inventory_rpa_job.py | 11 +- .../app/services/shipping_notice/export.py | 21 +- .../shipping_notice/inventory_rpa_workflow.py | 5 +- .../inventory_snapshot_store.py | 57 +- .../shipping_notice/inventory_sources.py | 35 +- backend/app/services/shipping_notice/rpa.py | 2 +- .../config/shipping_inventory_sources.yaml | 199 +- backend/tests/test_crane_navigation.py | 159 + backend/tests/test_crane_report_export.py | 446 ++ backend/tests/test_crane_session.py | 166 + backend/tests/test_dsv_report_parameters.py | 55 + backend/tests/test_freight_rpa_worker.py | 35 +- ...est_freight_rpa_worker_inventory_params.py | 109 +- ...hipping_notice_inventory_snapshot_reuse.py | 70 + ...hipping_notice_inventory_sources_config.py | 63 +- docs/features/shipping-notice/technical.md | 2 +- scripts/rpa/README.md | 61 +- scripts/rpa/crane_export_smoke.py | 115 + scripts/rpa/crane_login_smoke.py | 99 + scripts/rpa/crane_navigation.py | 410 ++ scripts/rpa/crane_report_export.py | 1164 +++++ scripts/rpa/crane_session.py | 382 ++ scripts/rpa/dsv_auth.py | 993 ++++ scripts/rpa/dsv_auth_login_flow.py | 393 ++ scripts/rpa/dsv_debug.py | 346 ++ scripts/rpa/dsv_driver.py | 29 + scripts/rpa/dsv_export_batch_smoke.py | 3 +- scripts/rpa/dsv_export_smoke.py | 10 +- scripts/rpa/dsv_navigation.py | 849 ++++ scripts/rpa/dsv_report_export.py | 1106 +++++ scripts/rpa/dsv_report_parameters.py | 93 +- scripts/rpa/dsv_session.py | 349 ++ scripts/rpa/freight_rpa_worker.py | 4084 +---------------- scripts/rpa/rpa_common.py | 466 ++ scripts/rpa/run_inventory_batch_trigger.py | 216 + 37 files changed, 8488 insertions(+), 4126 deletions(-) create mode 100644 backend/tests/test_crane_navigation.py create mode 100644 backend/tests/test_crane_report_export.py create mode 100644 backend/tests/test_crane_session.py create mode 100644 scripts/rpa/crane_export_smoke.py create mode 100644 scripts/rpa/crane_login_smoke.py create mode 100644 scripts/rpa/crane_navigation.py create mode 100644 scripts/rpa/crane_report_export.py create mode 100644 scripts/rpa/crane_session.py create mode 100644 scripts/rpa/dsv_auth.py create mode 100644 scripts/rpa/dsv_auth_login_flow.py create mode 100644 scripts/rpa/dsv_debug.py create mode 100644 scripts/rpa/dsv_driver.py create mode 100644 scripts/rpa/dsv_navigation.py create mode 100644 scripts/rpa/dsv_report_export.py create mode 100644 scripts/rpa/dsv_session.py create mode 100644 scripts/rpa/rpa_common.py create mode 100644 scripts/rpa/run_inventory_batch_trigger.py diff --git a/backend/app/services/schedule/job_options.py b/backend/app/services/schedule/job_options.py index 64ac205b..14cb49ba 100644 --- a/backend/app/services/schedule/job_options.py +++ b/backend/app/services/schedule/job_options.py @@ -39,7 +39,11 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]: { "label": source.get("display_name") or source.get("source_code"), "value": source.get("source_code"), - "description": f"{source.get('site')} · {source.get('warehouse_id')}", + "description": ( + f"{source.get('source_type')} · " + f"{source.get('site_id') or '-'} · " + f"{source.get('warehouse_id')}" + ), } for source in list_inventory_sources() ] diff --git a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py b/backend/app/services/schedule/shipping_inventory_rpa_finalize.py index 016de131..afa6e189 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_finalize.py +++ b/backend/app/services/schedule/shipping_inventory_rpa_finalize.py @@ -28,6 +28,7 @@ FinalizeScheduleRunResult = dict[str, Any] _INVENTORY_RPA_HEADER_ORDER = [ "source_code", + "site_id", "warehouse_id", "display_name", "inventory_file_no", @@ -36,6 +37,7 @@ _INVENTORY_RPA_HEADER_ORDER = [ ] _INVENTORY_RPA_HEADER_LABELS = { "source_code": "库存源", + "site_id": "站点", "warehouse_id": "仓库", "display_name": "名称", "inventory_file_no": "库存快照号", @@ -139,6 +141,7 @@ def _build_finalize_details( base = pending_by_key.get(key, {}) details.append({ "source_code": code or item.get("source_code"), + "site_id": item.get("site_id") or base.get("site_id"), "warehouse_id": wh or base.get("warehouse_id"), "display_name": base.get("display_name"), "inventory_file_no": item.get("inventory_file_no"), @@ -155,6 +158,7 @@ def _build_finalize_details( base = pending_by_key.get(key, {}) details.append({ "source_code": code or item.get("source_code"), + "site_id": item.get("site_id") or base.get("site_id"), "warehouse_id": wh or base.get("warehouse_id"), "display_name": base.get("display_name"), "inventory_file_no": "", @@ -166,6 +170,7 @@ def _build_finalize_details( continue details.append({ "source_code": base.get("source_code"), + "site_id": base.get("site_id"), "warehouse_id": base.get("warehouse_id"), "display_name": base.get("display_name"), "inventory_file_no": "", diff --git a/backend/app/services/schedule/shipping_inventory_rpa_job.py b/backend/app/services/schedule/shipping_inventory_rpa_job.py index ac77192e..8482a9a9 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_job.py +++ b/backend/app/services/schedule/shipping_inventory_rpa_job.py @@ -52,9 +52,9 @@ def _normalize_filter_tokens(raw: Any) -> set[str]: def _source_identity_tokens(source: dict[str, Any]) -> set[str]: - """收集库存源可用于匹配的标识集合(source_code / warehouse_id / match_aliases)。""" + """收集库存源可用于匹配的标识集合(source_code / site_id / warehouse_id / match_aliases)。""" tokens: set[str] = set() - for key in ("source_code", "warehouse_id", "warehouse_code"): + for key in ("source_code", "site_id", "warehouse_id"): value = str(source.get(key) or "").strip().upper() if value: tokens.add(value) @@ -68,12 +68,14 @@ def _source_identity_tokens(source: dict[str, Any]) -> set[str]: def _extract_wanted_tokens(body_template: dict[str, Any]) -> set[str]: """ 从 api_body_template 提取筛选 token。 - 推荐键:source_codes;兼容:source_code / warehouse_ids / warehouse_id / match_aliases。 + 推荐键:source_codes;兼容:source_code / site_ids / site_id / warehouse_ids / warehouse_id / match_aliases。 """ wanted: set[str] = set() for key in ( "source_codes", "source_code", + "site_ids", + "site_id", "warehouse_ids", "warehouse_id", "match_aliases", @@ -103,7 +105,7 @@ def _resolve_filter_payload(task: ScheduleTask) -> dict[str, Any] | None: def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]: """ 读取 enabled 库存源;job_params / api_body_template 可限定子集。 - 核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / warehouse_id / match_aliases 命中。 + 核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / site_id / warehouse_id / match_aliases 命中。 """ enabled = list_inventory_sources() body_template = _resolve_filter_payload(task) @@ -164,6 +166,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> details = [ { "source_code": item.get("source_code"), + "site_id": item.get("site_id"), "warehouse_id": item.get("warehouse_id"), "display_name": item.get("display_name"), } diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index 6fd417ce..6cfbc55f 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -122,6 +122,24 @@ def _resolve_odm_id(task: ShippingTask) -> str: return "" +def _shipment_warehouse_id(task: ShippingTask) -> str: + """ + 解析发货 Excel Header 的 Warehouse ID。 + 核心逻辑:库存快照入库时按「配置 site_id 优先,否则库存 Excel 的 warehouse id」写入 inv_file.warehouse_id。 + """ + try: + from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link + + snapshot = serialize_inventory_snapshot_link(task) + except Exception: + snapshot = None + if isinstance(snapshot, dict): + value = str(snapshot.get("warehouse_id") or "").strip() + if value: + return value + return "AWSDU" + + def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str: for value in (line.get("po_number"), task.po_number): text = str(value or "").strip() @@ -158,8 +176,7 @@ def _fill_pvmi_template(task: ShippingTask, path: Path) -> None: _clear_sheet_data_rows(detail_ws) _clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW) - if header_ws.cell(DATA_START_ROW, 1).value in (None, ""): - header_ws.cell(DATA_START_ROW, 1).value = "AWSDU" + header_ws.cell(DATA_START_ROW, 1).value = _shipment_warehouse_id(task) if header_ws.cell(DATA_START_ROW, 2).value in (None, ""): header_ws.cell(DATA_START_ROW, 2).value = "n" if header_ws.cell(DATA_START_ROW, 3).value in (None, ""): diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index a2a5e929..c0ddac7a 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -106,7 +106,7 @@ def _try_reuse_inventory_snapshot( 优先复用未过期库存快照,避免重复触发 RPA。 【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。 - 核心逻辑:按 source_code + warehouse_id 查找 ready 快照;命中则 link 并进入映射/匹配。 + 核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入映射/匹配。 retry_rpa 必须跳过缓存强制重新导出。 """ if mode == "retry_rpa": @@ -120,7 +120,7 @@ def _try_reuse_inventory_snapshot( snapshot = find_latest_ready_snapshot( str(rpa_source.get("source_code") or ""), - str(rpa_source.get("warehouse_id") or rpa_source.get("warehouse_code") or ""), + str(rpa_source.get("site_id") or ""), ) if not snapshot: return None @@ -687,6 +687,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: success = bool(item.get("success", False)) source = build_rpa_inventory_source(source_code) or { "source_code": source_code, + "site_id": item.get("site_id"), "warehouse_id": warehouse_id, "source_type": item.get("source_type"), } diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/inventory_snapshot_store.py index c188794d..9fb98545 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_store.py +++ b/backend/app/services/shipping_notice/inventory_snapshot_store.py @@ -14,6 +14,7 @@ from pathlib import Path from typing import Any from flask import current_app +from openpyxl import load_workbook from app import db from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink @@ -28,6 +29,13 @@ from app.services.shipping_notice.inventory_snapshot import read_inventory_schem _SNAPSHOT_STATUS_READY = "ready" _SNAPSHOT_STATUS_FAILED = "failed" _SNAPSHOT_STATUS_EXPIRED = "expired" +_WAREHOUSE_ID_HEADER_ALIASES = { + "warehouseid", + "warehouse", + "warehousecode", + "warehousecodeid", + "whid", +} def inventory_snapshot_ttl_hours() -> int: @@ -112,6 +120,41 @@ def expire_snapshot(inv_file: ShippingInventoryFile, reason: str) -> None: inv_file.updated_at = datetime.utcnow() +def _normalize_header_key(value: Any) -> str: + """将 Excel 表头标准化为可比较 key。""" + return "".join(ch for ch in str(value or "").strip().lower() if ch.isalnum()) + + +def _extract_warehouse_id_from_inventory_excel(path: Path) -> str: + """ + 从库存 Excel 内容中提取 Warehouse ID。 + 核心逻辑:扫描前几行表头,命中 Warehouse ID/WH ID 等列后取其下方第一条非空值。 + """ + if not path or not path.is_file(): + return "" + try: + wb = load_workbook(filename=str(path), data_only=True, read_only=True) + except Exception: + return "" + try: + ws = wb.active + rows = list(ws.iter_rows(min_row=1, max_row=min(ws.max_row or 1, 40), values_only=True)) + finally: + wb.close() + + for row_idx, row in enumerate(rows): + for col_idx, cell in enumerate(row): + if _normalize_header_key(cell) not in _WAREHOUSE_ID_HEADER_ALIASES: + continue + for data_row in rows[row_idx + 1:]: + if col_idx >= len(data_row): + continue + value = str(data_row[col_idx] or "").strip().upper() + if value: + return value + return "" + + def create_inventory_snapshot_from_rpa( *, source: dict[str, Any], @@ -142,13 +185,19 @@ def create_inventory_snapshot_from_rpa( exported_at = datetime.utcnow() inventory_file_no = generate_inventory_file_no() source_code = str(source.get("source_code") or "").strip().upper() - warehouse_id = str(source.get("warehouse_id") or source.get("warehouse_code") or "").strip() - warehouse_code = str(source.get("warehouse_code") or warehouse_id).strip() + configured_site_id = str(source.get("site_id") or "").strip().upper() + export_warehouse_id = str(source.get("warehouse_id") or "").strip().upper() + excel_warehouse_id = "" + warehouse_id = configured_site_id + warehouse_code = warehouse_id if success: path = inventory_file_upload_path(inventory_file_no) path.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(local_path, path) + excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(path) + warehouse_id = configured_site_id or excel_warehouse_id + warehouse_code = warehouse_id preview = read_inventory_schema_preview(path) preview["upload_filename"] = str(source_file_name or Path(local_path).name).strip() or path.name snapshot_status = _SNAPSHOT_STATUS_READY @@ -181,6 +230,10 @@ def create_inventory_snapshot_from_rpa( "query": source.get("query"), "navigation": source.get("navigation"), "parameters": source.get("parameters"), + "site_id": configured_site_id or None, + "export_warehouse_id": export_warehouse_id, + "excel_warehouse_id": excel_warehouse_id or None, + "warehouse_id_source": "site_id" if configured_site_id else ("inventory_excel" if excel_warehouse_id else None), "trigger_type": trigger_type, }, ) diff --git a/backend/app/services/shipping_notice/inventory_sources.py b/backend/app/services/shipping_notice/inventory_sources.py index 3e9e9cdd..00536f6e 100644 --- a/backend/app/services/shipping_notice/inventory_sources.py +++ b/backend/app/services/shipping_notice/inventory_sources.py @@ -16,7 +16,7 @@ from typing import Any import yaml from flask import current_app -_SITE_TO_SOURCE_TYPE = { +_VALID_SOURCE_TYPES = { "dsv360": "dsv360", "crane_footprint": "crane_footprint", } @@ -84,20 +84,20 @@ def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]: """ navigation = dict(source.get("navigation") or {}) query: dict[str, Any] = {} - site = str(source.get("site") or "").strip().lower() + source_type = str(source.get("source_type") or "").strip().lower() - if site == "dsv360": + if source_type == "dsv360": for key in ("program_group", "program_label", "report_group", "report_name"): if navigation.get(key): query[key] = navigation[key] - elif site == "crane_footprint": + elif source_type == "crane_footprint": if navigation.get("report_name"): query["report_name"] = navigation["report_name"] query["project_code"] = navigation.get("project_code") - warehouse_code = str(source.get("warehouse_code") or source.get("warehouse_id") or "").strip() - if warehouse_code: - query["warehouse_code"] = warehouse_code + warehouse_id = str(source.get("warehouse_id") or "").strip() + if warehouse_id: + query["warehouse_code"] = warehouse_id for parameter in source.get("parameters") or []: if not isinstance(parameter, dict): @@ -140,14 +140,14 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, raise InventorySourceConfigError(f"duplicate source_code: {source_code}") seen_codes.add(source_code) - site = str(raw.get("site") or "").strip().lower() - if site not in _SITE_TO_SOURCE_TYPE: - raise InventorySourceConfigError(f"{source_code}: site must be dsv360 or crane_footprint") - - warehouse_id = str(raw.get("warehouse_id") or "").strip() - if not warehouse_id: - raise InventorySourceConfigError(f"{source_code}: warehouse_id is required") + source_type = str(raw.get("source_type") or "").strip().lower() + if source_type not in _VALID_SOURCE_TYPES: + raise InventorySourceConfigError(f"{source_code}: source_type must be dsv360 or crane_footprint") + warehouse_id = str(raw.get("warehouse_id") or "").strip().upper() + site_id = str(raw.get("site_id") or "").strip().upper() + if source_type == "dsv360" and not site_id: + raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360") parameters: list[dict[str, Any]] = [] for item in raw.get("parameters") or []: if not isinstance(item, dict): @@ -163,13 +163,12 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, normalized = { "source_code": source_code, - "source_type": _SITE_TO_SOURCE_TYPE[site], - "site": site, + "source_type": _VALID_SOURCE_TYPES[source_type], + "site_id": site_id, "display_name": str(raw.get("display_name") or source_code).strip(), "enabled": bool(raw.get("enabled", True)), "entry_url": str(raw.get("entry_url") or "").strip(), "warehouse_id": warehouse_id, - "warehouse_code": str(raw.get("warehouse_code") or warehouse_id).strip(), "navigation": dict(raw.get("navigation") or {}), "parameters": parameters, "match_aliases": [ @@ -178,7 +177,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, if str(alias).strip() ], } - if site == "crane_footprint" and raw.get("export"): + if source_type == "crane_footprint" and raw.get("export"): normalized["export"] = dict(raw.get("export") or {}) normalized["query"] = _build_legacy_query(normalized) return normalized diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py index f6d15e13..126fa051 100644 --- a/backend/app/services/shipping_notice/rpa.py +++ b/backend/app/services/shipping_notice/rpa.py @@ -125,8 +125,8 @@ def write_inventory_export_batch_trigger( inventory_sources.append({ "source_code": source.get("source_code"), "source_type": source.get("source_type"), + "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), - "warehouse_code": source.get("warehouse_code"), "entry_url": source.get("entry_url"), "navigation": source.get("navigation") or {}, "parameters": source.get("parameters") or [], diff --git a/backend/config/shipping_inventory_sources.yaml b/backend/config/shipping_inventory_sources.yaml index 81541ca4..b2fd1b75 100644 --- a/backend/config/shipping_inventory_sources.yaml +++ b/backend/config/shipping_inventory_sources.yaml @@ -5,11 +5,11 @@ version: 1 sources: - source_code: DSV360_AWSBI_BYAWSATL01 - enabled: true - site: dsv360 display_name: DSV 360 / Bison / AWSBI / BYAWSATL01 + enabled: true + source_type: dsv360 + site_id: AWSBI warehouse_id: BYAWSATL01 - warehouse_code: BYAWSATL01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -28,10 +28,10 @@ sources: - ATL01 - source_code: DSV360_AWSBI_BYAWSAVP01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSAVP01 warehouse_id: BYAWSAVP01 - warehouse_code: BYAWSAVP01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -49,10 +49,10 @@ sources: - BYAWSAVP01 - source_code: DSV360_AWSBI_BYAWSAZA01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSAZA01 warehouse_id: BYAWSAZA01 - warehouse_code: BYAWSAZA01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -70,10 +70,10 @@ sources: - BYAWSAZA01 - source_code: DSV360_AWSBI_BYAWSCMH01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSCMH01 warehouse_id: BYAWSCMH01 - warehouse_code: BYAWSCMH01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -89,12 +89,13 @@ sources: required: true match_aliases: - BYAWSCMH01 + - CMH - source_code: DSV360_AWSBI_BYAWSCMN01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSCMN01 warehouse_id: BYAWSCMN01 - warehouse_code: BYAWSCMN01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -110,12 +111,13 @@ sources: required: true match_aliases: - BYAWSCMN01 + - CMN - source_code: DSV360_AWSBI_BYAWSEZE01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSEZE01 warehouse_id: BYAWSEZE01 - warehouse_code: BYAWSEZE01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -131,12 +133,13 @@ sources: required: true match_aliases: - BYAWSEZE01 + - EZE - source_code: DSV360_AWSBI_BYAWSFRA01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSFRA01 warehouse_id: BYAWSFRA01 - warehouse_code: BYAWSFRA01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -154,10 +157,10 @@ sources: - BYAWSFRA01 - source_code: DSV360_AWSBI_BYAWSGRU01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSGRU01 warehouse_id: BYAWSGRU01 - warehouse_code: BYAWSGRU01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -175,10 +178,10 @@ sources: - BYAWSGRU01 - source_code: DSV360_AWSBI_BYAWSIAD01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSIAD01 warehouse_id: BYAWSIAD01 - warehouse_code: BYAWSIAD01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -196,10 +199,10 @@ sources: - BYAWSIAD01 - source_code: DSV360_AWSBI_BYAWSJAN01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSJAN01 warehouse_id: BYAWSJAN01 - warehouse_code: BYAWSJAN01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -217,10 +220,10 @@ sources: - BYAWSJAN01 - source_code: DSV360_AWSBI_BYAWSLTN01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSLTN01 warehouse_id: BYAWSLTN01 - warehouse_code: BYAWSLTN01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -238,10 +241,10 @@ sources: - BYAWSLTN01 - source_code: DSV360_AWSBI_BYAWSMEL01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSMEL01 warehouse_id: BYAWSMEL01 - warehouse_code: BYAWSMEL01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -259,10 +262,10 @@ sources: - BYAWSMEL01 - source_code: DSV360_AWSBI_BYAWSNRT01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSNRT01 warehouse_id: BYAWSNRT01 - warehouse_code: BYAWSNRT01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -280,10 +283,10 @@ sources: - BYAWSNRT01 - source_code: DSV360_AWSBI_BYAWSPHX01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSPHX01 warehouse_id: BYAWSPHX01 - warehouse_code: BYAWSPHX01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -301,10 +304,10 @@ sources: - BYAWSPHX01 - source_code: DSV360_AWSBI_BYAWSPNE01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSPNE01 warehouse_id: BYAWSPNE01 - warehouse_code: BYAWSPNE01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -322,10 +325,10 @@ sources: - BYAWSPNE01 - source_code: DSV360_AWSBI_BYAWSPRD01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSPRD01 warehouse_id: BYAWSPRD01 - warehouse_code: BYAWSPRD01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -343,10 +346,10 @@ sources: - BYAWSPRD01 - source_code: DSV360_AWSBI_BYAWSPSC01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSPSC01 warehouse_id: BYAWSPSC01 - warehouse_code: BYAWSPSC01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -364,10 +367,10 @@ sources: - BYAWSPSC01 - source_code: DSV360_AWSBI_BYAWSQRO01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSQRO01 warehouse_id: BYAWSQRO01 - warehouse_code: BYAWSQRO01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -385,10 +388,10 @@ sources: - BYAWSQRO01 - source_code: DSV360_AWSBI_BYAWSRIC01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSRIC01 warehouse_id: BYAWSRIC01 - warehouse_code: BYAWSRIC01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -406,10 +409,10 @@ sources: - BYAWSRIC01 - source_code: DSV360_AWSBI_BYAWSRNO01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSRNO01 warehouse_id: BYAWSRNO01 - warehouse_code: BYAWSRNO01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -427,10 +430,10 @@ sources: - BYAWSRNO01 - source_code: DSV360_AWSBI_BYAWSRUH01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSRUH01 warehouse_id: BYAWSRUH01 - warehouse_code: BYAWSRUH01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -448,10 +451,10 @@ sources: - BYAWSRUH01 - source_code: DSV360_AWSBI_BYAWSSBN01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSSBN01 warehouse_id: BYAWSSBN01 - warehouse_code: BYAWSSBN01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -469,10 +472,10 @@ sources: - BYAWSSBN01 - source_code: DSV360_AWSBI_BYAWSSCL01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSSCL01 warehouse_id: BYAWSSCL01 - warehouse_code: BYAWSSCL01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -490,10 +493,10 @@ sources: - BYAWSSCL01 - source_code: DSV360_AWSBI_BYAWSYYZ01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSYYZ01 warehouse_id: BYAWSYYZ01 - warehouse_code: BYAWSYYZ01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -511,10 +514,10 @@ sources: - BYAWSYYZ01 - source_code: DSV360_AWSBI_BYAWSZAZ01 enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSBI display_name: DSV 360 / Bison / AWSBI / BYAWSZAZ01 warehouse_id: BYAWSZAZ01 - warehouse_code: BYAWSZAZ01 entry_url: https://s360.dbschenker.com/ navigation: program_group: Bison @@ -532,56 +535,39 @@ sources: - BYAWSZAZ01 - source_code: DSV360_AWSCV enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSCV display_name: DSV 360 / Cincinnati / AWSCV - warehouse_id: AWSCV - warehouse_code: AWSCV entry_url: https://s360.dbschenker.com/ navigation: program_group: Cincinnati program_label: AWSCV report_group: Inventory report_name: On Hand Inventory by Location - parameters: - - name: Owner - selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR - mode: single - values: - - CACV-0000000100 - required: true match_aliases: - CINCINNATI - CVG - AWSCV - source_code: DSV360_AWSDU enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSDU display_name: DSV 360 / Dublin / AWSDU - Prod (JDA) - warehouse_id: AWSDU - warehouse_code: AWSDU entry_url: https://s360.dbschenker.com/ navigation: program_group: Dublin program_label: AWSDU - Prod (JDA) report_group: Inventory report_name: On Hand Inventory by Location - parameters: - - name: Owner - selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR - mode: single - values: - - CADU-0000000100 - required: true match_aliases: - DBS DUB - DUB - DUBLIN - source_code: DSV360_AWSAMS enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSAMS display_name: DSV 360 / Moerdijk / AWSAMS - warehouse_id: AWSAMS - warehouse_code: AWSAMS entry_url: https://s360.dbschenker.com/ navigation: program_group: Moerdijk @@ -589,11 +575,16 @@ sources: report_group: Inventory report_name: On Hand Inventory by Location parameters: - - name: Owner - selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR - mode: single + - name: Warehouse + selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR + mode: multi_select + select_all: true + selectors: + text: '#ReportViewerMain_ctl08_ctl17_txtValue' + toggle: '#ReportViewerMain_ctl08_ctl17_ctl01' + dropdown: '#ReportViewerMain_ctl08_ctl17_divDropDown' values: - - CADU-0000000100 + - RTM required: true match_aliases: - MOERDIJK @@ -601,73 +592,45 @@ sources: - AWSAMS - source_code: DSV360_AWSSL enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSSL display_name: DSV 360 / Salt Lake City / AWSSL - warehouse_id: AWSSL - warehouse_code: AWSSL entry_url: https://s360.dbschenker.com/ navigation: program_group: Salt Lake City program_label: AWSSL report_group: Inventory report_name: On Hand Inventory by Location - parameters: - - name: Owner - selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR - mode: single - values: - - CACV-0000000100 - required: true match_aliases: - USLCK - SALT LAKE CITY - SALTLAKECITY - source_code: DSV360_AWSSG enabled: true - site: dsv360 + source_type: dsv360 + site_id: AWSSG display_name: DSV 360 / Singapore / AWSSG - Prod (JDA) - warehouse_id: AWSSG - warehouse_code: AWSSG entry_url: https://s360.dbschenker.com/ navigation: program_group: Singapore program_label: AWSSG - Prod (JDA) report_group: Inventory report_name: On Hand Inventory by Location - parameters: - - name: Owner - selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR - mode: single - values: - - CACV-0000000100 - required: true match_aliases: - SINGAPORE HUB - SINGAPORE - SG -- source_code: CRANE_TZR2 +- source_code: CRANE enabled: true - site: crane_footprint - display_name: Crane FootPrint / Warehouse TZR2 - warehouse_id: TZR2 - warehouse_code: TZR2 + source_type: crane_footprint + display_name: Crane FootPrint entry_url: https://wms-portal.craneww.com/#/on-hand-details-query navigation: report_name: On Hand Details Query - download_mode: file_download - parameters: - - name: Owner - selector_env: FREIGHT_RPA_CRANE_OWNER_SELECTOR - mode: single - values: - - '0000000100' - required: true - - name: Warehouse - selector_env: FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR - mode: single - values: - - TZR2 - required: true + download_mode: scheduled_report + parameters: [] match_aliases: + - TZR - TZR2 - - THAILAND + - TZR3 + diff --git a/backend/tests/test_crane_navigation.py b/backend/tests/test_crane_navigation.py new file mode 100644 index 00000000..7c8f7fc6 --- /dev/null +++ b/backend/tests/test_crane_navigation.py @@ -0,0 +1,159 @@ +"""crane_navigation 报表页导航测试。""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + + +def _load_navigation(): + module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_navigation.py" + spec = importlib.util.spec_from_file_location("crane_navigation_test", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class _FakeLocator: + def __init__(self, *, visible: bool = True) -> None: + self.visible = visible + self.clicked = False + self.hovered = False + + @property + def first(self) -> "_FakeLocator": + return self + + def is_visible(self, timeout: int = 0) -> bool: + return self.visible + + def click(self, timeout: int = 0, force: bool = False) -> None: + self.clicked = True + + def hover(self, timeout: int = 0) -> None: + self.hovered = True + + +class _FakePage: + def __init__(self, *, url: str = "https://wms-portal.craneww.com/#/") -> None: + self.url = url + self.frames: list[_FakePage] = [] + self.goto_calls: list[str] = [] + + def locator(self, selector: str) -> _FakeLocator: + if "on-hand-details-query" in selector or "On Hand Details" in selector: + return _FakeLocator(visible=True) + if "Queries" in selector or "navbar" in selector: + return _FakeLocator(visible=True) + return _FakeLocator(visible=False) + + def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator: + if role == "link" and name in {"On Hand Details", "Queries"}: + return _FakeLocator(visible=True) + return _FakeLocator(visible=False) + + def goto(self, url: str, wait_until: str = "", timeout: int = 0) -> None: + self.goto_calls.append(url) + self.url = url + + +def test_navigate_prefers_dashboard_tile(monkeypatch): + """应优先尝试首页 On Hand Details 卡片。""" + module = _load_navigation() + page = _FakePage() + calls: list[str] = [] + + monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False) + monkeypatch.setattr( + module, + "_click_dashboard_on_hand_details", + lambda *args, **kwargs: calls.append("dashboard") or True, + ) + monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: calls.append("navbar") or True) + monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True) + + mode = module.navigate_to_crane_report( + page, + "https://wms-portal.craneww.com/#/on-hand-details-query", + env=lambda name, default="": default, + browser_timeout_ms=5_000, + ) + + assert mode == "dashboard_tile" + assert calls == ["dashboard"] + assert page.goto_calls == [] + + +def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch): + """首页卡片未进入报表时应回退顶部 Queries 菜单。""" + module = _load_navigation() + page = _FakePage() + wait_calls = {"n": 0} + + monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False) + monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True) + monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True) + + def _wait(page_arg, entry_url, *, browser_timeout_ms): + wait_calls["n"] += 1 + return wait_calls["n"] >= 2 + + monkeypatch.setattr(module, "_wait_for_report_navigation", _wait) + + mode = module.navigate_to_crane_report( + page, + "https://wms-portal.craneww.com/#/on-hand-details-query", + env=lambda name, default="": default, + browser_timeout_ms=5_000, + ) + + assert mode == "navbar_menu" + assert wait_calls["n"] == 2 + + +def test_navigate_uses_direct_goto_as_last_resort(monkeypatch): + """卡片与菜单均失败时应 goto entry_url。""" + module = _load_navigation() + page = _FakePage() + entry = "https://wms-portal.craneww.com/#/on-hand-details-query" + + monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False) + monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True) + monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True) + monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: False) + + with pytest.raises(RuntimeError, match="navigation failed"): + module.navigate_to_crane_report(page, entry, env=lambda n, d="": d, browser_timeout_ms=5_000) + + assert page.goto_calls[0] == entry + assert any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls) + + +def test_is_crane_on_report_route_reads_entry_hash(): + """应从 entry_url hash 判断当前是否已在目标报表路由。""" + module = _load_navigation() + page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query") + entry = "https://wms-portal.craneww.com/#/on-hand-details-query" + assert module.is_crane_on_report_route(page, entry) is True + + +def test_homepage_is_not_report_form_ready(): + """登录后首页 /#/ 不应被误判为报表表单已就绪。""" + module = _load_navigation() + page = _FakePage(url="https://wms-portal.craneww.com/#/") + entry = "https://wms-portal.craneww.com/#/on-hand-details-query" + assert module.is_crane_on_homepage(page) is True + assert module.is_crane_report_form_ready(page, entry) is False + + +def test_report_route_without_controls_is_not_ready(monkeypatch): + """仅有 hash 路由但无 Run Report 控件时仍不算 ready。""" + module = _load_navigation() + page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query") + entry = "https://wms-portal.craneww.com/#/on-hand-details-query" + monkeypatch.setattr(module, "_has_report_form_controls", lambda page_arg: False) + assert module.is_crane_report_form_ready(page, entry) is False diff --git a/backend/tests/test_crane_report_export.py b/backend/tests/test_crane_report_export.py new file mode 100644 index 00000000..1e99ba1a --- /dev/null +++ b/backend/tests/test_crane_report_export.py @@ -0,0 +1,446 @@ +"""crane_report_export 异步报表导出流程测试。""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + + +def _load_export(): + module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_report_export.py" + spec = importlib.util.spec_from_file_location("crane_report_export_test", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_fill_parameters_skips_warehouse(monkeypatch): + """Warehouse 参数应被跳过,不再填写。""" + module = _load_export() + calls: list[tuple[str, str, str]] = [] + + def _fake_select(page, selector_env, label, value): + calls.append((selector_env, label, value)) + + module._fill_crane_report_parameters( + MagicMock(), + { + "parameters": [ + { + "name": "Warehouse", + "selector_env": "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR", + "mode": "single", + "values": ["TZR2"], + }, + { + "name": "Owner", + "selector_env": "FREIGHT_RPA_CRANE_OWNER_SELECTOR", + "mode": "single", + "values": ["OWNER1"], + }, + ] + }, + env=lambda name, default="": default, + browser_timeout_ms=5_000, + select_or_fill=_fake_select, + ) + + assert calls == [("FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")] + + +def test_build_schedule_description_uses_short_uuid_hex(monkeypatch): + """Description 默认取 UUID4 前 12 位 hex,兼顾唯一性与列表可读性。""" + module = _load_export() + monkeypatch.setattr( + module.uuid, + "uuid4", + lambda: module.uuid.UUID("11111111-2222-4333-8444-555555555555"), + ) + text = module._build_schedule_description( + {"source_code": "CRANE_TZR2"}, + {"task_no": "SN-1001"}, + env=lambda name, default="": default, + ) + assert text == "111111112222" + assert len(text) == 12 + + +def test_build_schedule_description_hex_len_env(): + """可通过环境变量调整 Description 长度(8~32)。""" + module = _load_export() + text = module._build_schedule_description( + {"source_code": "CRANE_TZR2"}, + None, + env=lambda name, default="": "16" if name == "FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default, + ) + assert len(text) == 16 + + +def test_export_scheduled_report_flow(monkeypatch): + """scheduled_report 模式应按 Run → Schedule → Scheduled Reports 顺序执行。""" + module = _load_export() + page = MagicMock() + page.url = "https://wms-portal.craneww.com/#/on-hand-details-query" + calls: list[str] = [] + captured: dict[str, str] = {} + + monkeypatch.setattr(module, "_fill_crane_report_parameters", lambda *args, **kwargs: None) + monkeypatch.setattr(module, "_build_schedule_description", lambda *args, **kwargs: "HXOPS-CRANE_TZR2-TEST") + monkeypatch.setattr(module, "_click_run_report", lambda *args, **kwargs: calls.append("run")) + monkeypatch.setattr(module, "_wait_for_run_report_results", lambda *args, **kwargs: calls.append("wait_run")) + + def _schedule(*args, **kwargs): + calls.append("schedule") + + def _confirm(page_arg, description, **kwargs): + calls.append("confirm") + captured["description"] = description + + monkeypatch.setattr(module, "_click_schedule_report", _schedule) + monkeypatch.setattr(module, "_confirm_schedule_report_modal", _confirm) + monkeypatch.setattr(module, "_wait_for_report_submission_complete", lambda *args, **kwargs: calls.append("wait_submitted")) + monkeypatch.setattr(module, "_open_scheduled_reports", lambda *args, **kwargs: calls.append("open_scheduled")) + + def _download(*args, **kwargs): + calls.append("download") + captured["download_description"] = kwargs.get("description", "") + return "download-object" + + monkeypatch.setattr(module, "_wait_and_click_scheduled_download", _download) + + result = module.export_crane_inventory_report( + page, + {"navigation": {"download_mode": "scheduled_report"}, "parameters": [], "source_code": "CRANE_TZR2"}, + trigger={"task_no": "SN-1001"}, + env=lambda name, default="": default, + browser_timeout_ms=5_000, + select_or_fill=lambda *args, **kwargs: None, + click_text=lambda *args, **kwargs: None, + ) + + assert result == "download-object" + assert calls == ["run", "wait_run", "schedule", "confirm", "wait_submitted", "open_scheduled", "download"] + assert captured["description"] == "HXOPS-CRANE_TZR2-TEST" + assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST" + + +def test_should_run_report_before_schedule_defaults_true(): + """默认必须先 Run Report;仅显式 run_before_schedule=false 可关闭。""" + module = _load_export() + assert ( + module._should_run_report_before_schedule( + {"navigation": {}}, + env=lambda name, default="": default, + ) + is True + ) + assert ( + module._should_run_report_before_schedule( + {"navigation": {"run_before_schedule": False}}, + env=lambda name, default="": default, + ) + is False + ) + assert ( + module._should_run_report_before_schedule( + {"navigation": {}}, + env=lambda name, default="": "false" if name == "FREIGHT_RPA_CRANE_RUN_BEFORE_SCHEDULE" else default, + ) + is False + ) + + +def test_is_on_scheduled_reports_page_detects_hash_route(): + """仅 on-hand-details-query 不算 Scheduled Reports 页。""" + module = _load_export() + + class _Page: + def __init__(self, url: str) -> None: + self.url = url + + assert module._is_on_scheduled_reports_page(_Page("https://wms-portal.craneww.com/#/scheduled-reports")) is True + assert module._is_on_scheduled_reports_page(_Page("https://wms-portal.craneww.com/#/on-hand-details-query")) is False + + +def test_find_scheduled_download_waits_until_status_is_download(): + """Description 行末列为 Submitted 时不应返回下载链接。""" + module = _load_export() + + class _Cells: + def __init__(self, texts: list[str]) -> None: + self._texts = texts + + def count(self) -> int: + return len(self._texts) + + def nth(self, index: int) -> _Cell: + return _Cell(self._texts[index]) + + class _Cell: + def __init__(self, text: str, *, visible: bool = False) -> None: + self._text = text + self._visible = visible + + def inner_text(self, timeout: int = 0) -> str: + return self._text + + def is_visible(self, timeout: int = 0) -> bool: + return self._visible + + @property + def first(self): + return self + + class _Row: + def __init__(self, name: str, description: str, status: str, *, submitted: str = "2026/7/9 04:45:45") -> None: + self._description = description + self._status = status + self._cells = _Cells([name, submitted, description, status]) + + def is_visible(self, timeout: int = 0) -> bool: + return True + + def locator(self, selector: str) -> Any: + if selector == "td": + return self._cells + return _Cell("Download", visible=selector.startswith("a")) + + def get_by_role(self, role: str, name: str, exact: bool = False) -> _Cell: + return _Cell("Download", visible=True) + + class _Rows: + def __init__(self, rows: list[_Row]) -> None: + self._rows = rows + + def count(self) -> int: + return len(self._rows) + + def nth(self, index: int) -> _Row: + return self._rows[index] + + class _Page: + def __init__(self, rows: list[_Row]) -> None: + self.frames: list = [] + self._rows = rows + self.url = "https://wms-portal.craneww.com/#/scheduled-reports" + + def locator(self, selector: str) -> _Rows: + return _Rows(self._rows) + + submitted = module._find_scheduled_download_by_description( + _Page([_Row("OnHandDetails.xlsx", "uuid-1", "Submitted")]), + "uuid-1", + env=lambda name, default="": default, + ) + assert submitted is None + + download = module._find_scheduled_download_by_description( + _Page([_Row("OnHandDetails.xlsx", "uuid-2", "Download")]), + "uuid-2", + env=lambda name, default="": default, + ) + assert download is not None + + +def test_find_scheduled_download_skips_wrong_name_and_picks_first_match(): + """应跳过 Name 不符的行,自上而下取首条 OnHandDetails.xlsx + Description 匹配项。""" + module = _load_export() + + class _Cells: + def __init__(self, texts: list[str]) -> None: + self._texts = texts + + def count(self) -> int: + return len(self._texts) + + def nth(self, index: int) -> _Cell: + return _Cell(self._texts[index]) + + class _Cell: + def __init__(self, text: str, *, visible: bool = False) -> None: + self._text = text + self._visible = visible + + def inner_text(self, timeout: int = 0) -> str: + return self._text + + def is_visible(self, timeout: int = 0) -> bool: + return self._visible + + @property + def first(self): + return self + + class _Row: + def __init__(self, name: str, submitted: str, description: str, status: str) -> None: + self._cells = _Cells([name, submitted, description, status]) + + def is_visible(self, timeout: int = 0) -> bool: + return True + + def locator(self, selector: str) -> Any: + if selector == "td": + return self._cells + return _Cell("Download", visible=selector.startswith("a")) + + def get_by_role(self, role: str, name: str, exact: bool = False) -> _Cell: + return _Cell("Download", visible=True) + + class _Rows: + def __init__(self, rows: list[_Row]) -> None: + self._rows = rows + + def count(self) -> int: + return len(self._rows) + + def nth(self, index: int) -> _Row: + return self._rows[index] + + class _Page: + def __init__(self, rows: list[_Row]) -> None: + self.frames: list = [] + self._rows = rows + self.url = "https://wms-portal.craneww.com/#/scheduled-reports" + + def locator(self, selector: str) -> _Rows: + return _Rows(self._rows) + + rows = [ + _Row("OutboundDetails.xlsx", "2026/7/9 04:50:00", "target-uuid", "Download"), + _Row("OnHandDetails.xlsx", "2026/7/9 04:45:45", "other-uuid", "Download"), + _Row("OnHandDetails.xlsx", "2026/7/9 04:40:00", "target-uuid", "Download"), + ] + locator = module._find_scheduled_download_by_description( + _Page(rows), + "target-uuid", + env=lambda name, default="": default, + ) + assert locator is not None + + +def test_probe_scheduled_download_status_returns_submitted_before_download(): + """每轮 poll 应能读到 Submitted;仅 Download 时返回 locator。""" + module = _load_export() + + class _Cells: + def __init__(self, texts: list[str]) -> None: + self._texts = texts + + def count(self) -> int: + return len(self._texts) + + def nth(self, index: int) -> _Cell: + return _Cell(self._texts[index]) + + class _Cell: + def __init__(self, text: str, *, visible: bool = False) -> None: + self._text = text + self._visible = visible + + def inner_text(self, timeout: int = 0) -> str: + return self._text + + def is_visible(self, timeout: int = 0) -> bool: + return self._visible + + @property + def first(self): + return self + + class _Row: + def __init__(self, name: str, description: str, status: str) -> None: + self._cells = _Cells([name, "2026/7/9 04:45:45", description, status]) + + def is_visible(self, timeout: int = 0) -> bool: + return True + + def locator(self, selector: str) -> Any: + if selector == "td": + return self._cells + return _Cell("Download", visible=selector.startswith("a")) + + def get_by_role(self, role: str, name: str, exact: bool = False) -> _Cell: + return _Cell("Download", visible=True) + + class _Rows: + def __init__(self, rows: list[_Row]) -> None: + self._rows = rows + + def count(self) -> int: + return len(self._rows) + + def nth(self, index: int) -> _Row: + return self._rows[index] + + class _Page: + def __init__(self, rows: list[_Row]) -> None: + self.frames: list = [] + self._rows = rows + self.url = "https://wms-portal.craneww.com/#/scheduled-reports" + + def locator(self, selector: str) -> _Rows: + return _Rows(self._rows) + + page = _Page([_Row("OnHandDetails.xlsx", "uuid-1", "Submitted")]) + status, locator = module._probe_scheduled_download_status( + page, + "uuid-1", + env=lambda name, default="": default, + ) + assert status == "Submitted" + assert locator is None + + page_ready = _Page([_Row("OnHandDetails.xlsx", "uuid-2", "Download")]) + status2, locator2 = module._probe_scheduled_download_status( + page_ready, + "uuid-2", + env=lambda name, default="": default, + ) + assert status2 == "Download" + assert locator2 is not None + + +def test_is_crane_login_blocking_ignores_login_flash_when_table_visible(): + """reload 过渡态:登录框闪现但表格仍在时,不应判定为需要重登。""" + module = _load_export() + + class _Rows: + def count(self) -> int: + return 1 + + class _Page: + frames: list = [] + url = "https://wms-portal.craneww.com/#/scheduled-reports" + + def locator(self, selector: str) -> _Rows: + return _Rows() + + page = _Page() + session = module._load_crane_session_module() + original = session.is_crane_login_page + session.is_crane_login_page = lambda _page: True + try: + assert module._is_crane_login_blocking(page) is False + assert module._is_on_scheduled_reports_page(page) is True + finally: + session.is_crane_login_page = original + + +def test_resolve_scheduled_report_file_name_prefers_navigation_config(): + """scheduled_report_file_name 应优先于环境变量默认值。""" + module = _load_export() + name = module._resolve_scheduled_report_file_name( + {"navigation": {"scheduled_report_file_name": "Custom.xlsx"}}, + env=lambda name, default="": default, + ) + assert name == "Custom.xlsx" + + +def test_resolve_download_mode_defaults_to_scheduled_report(): + """未配置 download_mode 时默认走 scheduled_report。""" + module = _load_export() + assert module._resolve_download_mode({"navigation": {}}) == "scheduled_report" diff --git a/backend/tests/test_crane_session.py b/backend/tests/test_crane_session.py new file mode 100644 index 00000000..8bb24ca4 --- /dev/null +++ b/backend/tests/test_crane_session.py @@ -0,0 +1,166 @@ +"""crane_session 登录页识别与自动填写测试。""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path +from unittest.mock import MagicMock + + +def _load_crane_session(): + module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_session.py" + spec = importlib.util.spec_from_file_location("crane_session_test", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class _FakeLocator: + def __init__(self, *, visible: bool = True, enabled: bool = True) -> None: + self.visible = visible + self.enabled = enabled + self.filled: list[str] = [] + self.clicked = False + + @property + def first(self) -> "_FakeLocator": + return self + + def is_visible(self, timeout: int = 0) -> bool: + return self.visible + + def is_enabled(self, timeout: int = 0) -> bool: + return self.enabled + + def fill(self, value: str, timeout: int = 0) -> None: + self.filled.append(value) + + def click(self, timeout: int = 0, force: bool = False) -> None: + self.clicked = True + + def evaluate(self, script: str) -> bool: + return self.enabled + + +class _FakePage: + def __init__(self) -> None: + self.frames: list[_FakePage] = [] + self.url = "https://wms-portal.craneww.com/" + + def locator(self, selector: str) -> _FakeLocator: + lowered = selector.lower() + if "user name" in lowered or "password" in lowered: + return _FakeLocator(visible=True) + if "is-primary" in lowered or "sign in" in lowered: + return _FakeLocator(visible=True, enabled=True) + return _FakeLocator(visible=False) + + def get_by_label(self, label: str, exact: bool = False) -> _FakeLocator: + return _FakeLocator(visible=label in {"User Name", "Password"}) + + def get_by_placeholder(self, placeholder: str, exact: bool = False) -> _FakeLocator: + return _FakeLocator(visible=placeholder.startswith("Enter ")) + + def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator: + return _FakeLocator(visible=role == "button" and name == "Sign in", enabled=True) + + def wait_for_load_state(self, state: str, timeout: int = 0) -> None: + return None + + +def test_is_crane_login_page_detects_username_placeholder(): + """登录页应通过 Enter user name... / Enter password... placeholder 识别。""" + module = _load_crane_session() + page = _FakePage() + assert module.is_crane_login_page(page) is True + + +def test_maybe_auto_login_crane_fills_username_password_and_clicks_sign_in(monkeypatch): + """自动登录应依次填写用户名、密码并点击 Sign in。""" + module = _load_crane_session() + page = _FakePage() + calls: list[tuple[str, str]] = [] + + def _fake_fill( + page_arg, + *, + selector_env, + value, + env, + browser_timeout_ms, + fallback_selectors, + label=None, + placeholder=None, + ): + calls.append((selector_env, value)) + return True + + monkeypatch.setattr(module, "_fill_crane_field", _fake_fill) + login_page_states = iter([True, False]) + monkeypatch.setattr( + module, + "is_crane_login_page", + lambda page_arg: next(login_page_states, False), + ) + monkeypatch.setattr(module, "_click_crane_login_submit", lambda *args, **kwargs: True) + + module.maybe_auto_login_crane( + page, + env=lambda name, default="": { + "FREIGHT_RPA_CRANE_USERNAME": "crane-user", + "FREIGHT_RPA_CRANE_PASSWORD": "crane-pass", + }.get(name, default), + browser_timeout_ms=5_000, + ) + + assert calls == [ + ("FREIGHT_RPA_CRANE_USERNAME_SELECTOR", "crane-user"), + ("FREIGHT_RPA_CRANE_PASSWORD_SELECTOR", "crane-pass"), + ] + + +def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch): + """Sign in 初始 disabled,填写凭据后应能定位到可点击按钮。""" + module = _load_crane_session() + page = _FakePage() + states = iter([False, False, True]) + + def _fake_enabled(locator): + return next(states, True) + + monkeypatch.setattr(module, "_is_crane_button_enabled", _fake_enabled) + + locator = module._find_crane_sign_in_button( + page, + selector_env="FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR", + env=lambda name, default="": default, + browser_timeout_ms=3_000, + ) + + assert locator is not None + assert locator.enabled is True + + +def test_ensure_crane_session_skips_login_when_session_active(monkeypatch): + """batch 内 session 有效时不应重复 goto + login。""" + worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_rpa_worker.py" + spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path) + assert spec and spec.loader + worker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(worker) + + page = MagicMock() + login = MagicMock() + ready = MagicMock() + goto = MagicMock() + monkeypatch.setattr(worker, "_is_crane_session_active", MagicMock(return_value=True)) + monkeypatch.setattr(worker, "_goto_crane_entry_url", goto) + monkeypatch.setattr(worker, "_maybe_auto_login_crane", login) + monkeypatch.setattr(worker, "_wait_for_crane_app_ready", ready) + + worker._ensure_crane_session(page, "https://wms-portal.craneww.com/#/on-hand-details-query") + + goto.assert_not_called() + login.assert_not_called() + ready.assert_called_once() diff --git a/backend/tests/test_dsv_report_parameters.py b/backend/tests/test_dsv_report_parameters.py index ff919c31..36f4315b 100644 --- a/backend/tests/test_dsv_report_parameters.py +++ b/backend/tests/test_dsv_report_parameters.py @@ -112,3 +112,58 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue(): ) assert selected.get("value") == "BYAWSATL01" or selected.get("label") == "BYAWSATL01" + + +def test_fill_dsv_multi_select_parameter_supports_select_all_checkbox_dropdown(): + """AWSAMS Warehouse 这类 checkbox 下拉应支持 select_all 和显式 selector。""" + module = _load_module() + payloads: list[dict[str, object]] = [] + + class _FakeLocator: + first = None + + def __init__(self) -> None: + self.first = self + + def wait_for(self, *args, **kwargs) -> None: + return None + + def input_value(self, timeout: int | None = None) -> str: + return "" + + def click(self, timeout: int | None = None, force: bool = False) -> None: + return None + + class _FakeReportRootLocator: + def count(self) -> int: + return 1 + + class _FakeFrame: + def locator(self, selector: str): + if selector == "#ReportViewerMain": + return _FakeReportRootLocator() + return _FakeLocator() + + def evaluate(self, script: str, payload: dict[str, object]) -> bool: + payloads.append(payload) + return True + + class _FakePage: + frames = [_FakeFrame()] + + ok = module.fill_dsv_multi_select_parameter( + _FakePage(), + "Warehouse", + ["RTM"], + selectors={ + "text": "#ReportViewerMain_ctl08_ctl17_txtValue", + "toggle": "#ReportViewerMain_ctl08_ctl17_ctl01", + "dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown", + }, + select_all=True, + browser_timeout_ms=lambda: 3_000, + ) + + assert ok is True + assert payloads[-1]["dropdownSelector"] == "#ReportViewerMain_ctl08_ctl17_divDropDown" + assert payloads[-1]["selectAll"] is True diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index 4fecbac7..15ffaf0b 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -1164,8 +1164,8 @@ def test_has_dsv_password_upgrade_prompt_does_not_match_generic_not_now_text(): assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is False -def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(): - """已经进入 s360 portal 时,应直接判定没有升级提示,避免在首页做长时间空扫描。""" +def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch): + """portal 首页导航已可用时,应直接判定没有升级提示,避免在稳定首页做无效扫描。""" worker = _load_freight_rpa_worker() locator_calls = {"value": 0} @@ -1175,12 +1175,41 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(): def locator(self, selector: str): locator_calls["value"] += 1 - raise AssertionError("portal page should short-circuit before scanning locators") + raise AssertionError("stable portal home should short-circuit before scanning locators") + + monkeypatch.setattr(worker.dsv_session, "has_dsv_report_nav_usable", lambda page: True) assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is False assert locator_calls["value"] == 0 +def test_has_dsv_password_upgrade_prompt_detects_maybe_later_on_portal(monkeypatch): + """portal 上若升级弹窗挡住首页,仍应识别“也许以后”按钮。""" + worker = _load_freight_rpa_worker() + + class _FakeLocator: + def __init__(self, selector: str) -> None: + self.selector = selector + self.first = self + + def is_visible(self, timeout: int | None = None) -> bool: + return self.selector == 'button.dbs-sims-button-secondary:has-text("也许以后")' + + def inner_text(self, timeout: int | None = None) -> str: + return "" + + class _FakePage: + url = "https://s360.dbschenker.com/main/portal" + frames: list[object] = [] + + def locator(self, selector: str) -> _FakeLocator: + return _FakeLocator(selector) + + monkeypatch.setattr(worker.dsv_session, "has_dsv_report_nav_usable", lambda page: False) + + assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is True + + def test_wait_for_dsv_home_ready_skips_duplicate_upgrade_prompt_check(monkeypatch): """首页已可探测或 app wait 返回后,若无升级提示强特征,不应再次进入升级提示处理。""" worker = _load_freight_rpa_worker() diff --git a/backend/tests/test_freight_rpa_worker_inventory_params.py b/backend/tests/test_freight_rpa_worker_inventory_params.py index ee3e3e79..734e21bb 100644 --- a/backend/tests/test_freight_rpa_worker_inventory_params.py +++ b/backend/tests/test_freight_rpa_worker_inventory_params.py @@ -3,13 +3,25 @@ from __future__ import annotations import importlib.util +import sys from pathlib import Path from unittest.mock import MagicMock def _load_worker(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_rpa_worker.py" - spec = importlib.util.spec_from_file_location("freight_rpa_worker_param_test", module_path) + return _load_rpa_module("freight_rpa_worker") + + +def _load_dsv_report_export(): + return _load_rpa_module("dsv_report_export") + + +def _load_rpa_module(module_name: str): + module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py" + scripts_dir = str(module_path.parent) + if scripts_dir not in sys.path: + sys.path.insert(0, scripts_dir) + spec = importlib.util.spec_from_file_location(f"{module_name}_param_test", module_path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) @@ -18,11 +30,11 @@ def _load_worker(): def test_fill_report_parameter_multi_select(monkeypatch): """multi_select 应对每个值尝试多选填充,而非只取第一个。""" - worker = _load_worker() + worker = _load_dsv_report_export() page = MagicMock() calls: list[tuple[str, str, list[str]]] = [] - def _fake_multi(page_arg, selector_env, label, values): + def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False): calls.append((selector_env, label, list(values))) monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi) @@ -38,6 +50,51 @@ def test_fill_report_parameter_multi_select(monkeypatch): assert calls == [("FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])] +def test_fill_report_parameter_multi_select_with_select_all(monkeypatch): + """select_all 应传入 DSV checkbox 下拉处理,供 AWSAMS Warehouse 全选。""" + worker = _load_dsv_report_export() + page = MagicMock() + calls: list[dict[str, object]] = [] + + def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False): + calls.append( + { + "selector_env": selector_env, + "label": label, + "values": list(values), + "selectors": selectors, + "select_all": select_all, + } + ) + + selectors = { + "text": "#ReportViewerMain_ctl08_ctl17_txtValue", + "toggle": "#ReportViewerMain_ctl08_ctl17_ctl01", + "dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown", + } + monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi) + worker._fill_report_parameter( + page, + { + "name": "Warehouse", + "selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", + "mode": "multi_select", + "select_all": True, + "selectors": selectors, + "values": ["RTM"], + }, + ) + assert calls == [ + { + "selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", + "label": "Warehouse", + "values": ["RTM"], + "selectors": selectors, + "select_all": True, + } + ] + + def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch): """单票 DSV 导出应走与批量相同的 session + export 函数。""" worker = _load_worker() @@ -47,20 +104,40 @@ def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch): "source_code": "DSV360_AWSDU", "parameters": [{"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "selector_env": "X"}], } - monkeypatch.setattr(worker, "_ensure_dsv_session", MagicMock()) export_mock = MagicMock(return_value="download") - monkeypatch.setattr(worker, "_export_dsv_inventory_source", export_mock) + monkeypatch.setattr(worker.dsv_driver, "download_dsv360_inventory", export_mock) result = worker._download_dsv360_inventory(page, {"task_no": "SN-1"}, source) - worker._ensure_dsv_session.assert_called_once_with(page, "https://s360.dbschenker.com/") export_mock.assert_called_once_with(page, {"task_no": "SN-1"}, source) assert result == "download" +def test_dsv_report_has_inventory_data_rows_false_when_table_has_only_three_rows(monkeypatch): + """DSV 报表明细表只有 3 行时应视为无库存数据,不进入导出。""" + worker = _load_dsv_report_export() + frame = MagicMock() + frame.evaluate.return_value = False + monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page: (0, frame, {})) + + assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is False + frame.evaluate.assert_called_once() + + +def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monkeypatch): + """DSV 报表明细表第 4 行后存在非空行时应允许继续导出。""" + worker = _load_dsv_report_export() + frame = MagicMock() + frame.evaluate.return_value = True + monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page: (0, frame, {})) + + assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is True + frame.evaluate.assert_called_once() + + def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch): """批量 navigation 变化时应 goto entry 并检测 session。""" - worker = _load_worker() + worker = _load_dsv_report_export() page = MagicMock() login = MagicMock() home = MagicMock() @@ -79,7 +156,7 @@ def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch): def test_dsv_sources_share_navigation_when_program_report_match(): """同 program/report 导航的 AWSBI 子仓应判定为可复用参数页。""" - worker = _load_worker() + worker = _load_dsv_report_export() nav = { "program_group": "Bison", "program_label": "AWSBI", @@ -93,7 +170,7 @@ def test_dsv_sources_share_navigation_when_program_report_match(): def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches(monkeypatch): """同 navigation 的第二步应 reload 参数页而非 reset 首页。""" - worker = _load_worker() + worker = _load_dsv_report_export() page = MagicMock() ensure = MagicMock() reset = MagicMock() @@ -120,7 +197,7 @@ def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches( def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatch): """program/report 变化时仍应回 portal 首页。""" - worker = _load_worker() + worker = _load_dsv_report_export() page = MagicMock() reset = MagicMock() reuse = MagicMock() @@ -150,7 +227,7 @@ def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatc def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch): """同 entry_url 且 session 有效时 reset 不应再触发 auto_login。""" - worker = _load_worker() + worker = _load_dsv_report_export() page = MagicMock() login = MagicMock() home = MagicMock() @@ -171,7 +248,7 @@ def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch): def test_ensure_dsv_session_skips_login_when_session_active(monkeypatch): """batch 首条前若 session 已有效,ensure 不应 goto + login。""" - worker = _load_worker() + worker = _load_dsv_report_export() page = MagicMock() login = MagicMock() home = MagicMock() @@ -191,7 +268,7 @@ def test_ensure_dsv_session_skips_login_when_session_active(monkeypatch): def test_prepare_dsv_batch_reuses_form_for_different_source_code_same_entry(monkeypatch): """source_code 不同但 navigation/entry_url 一致时,第二步应复用参数页且不 reset 登录。""" - worker = _load_worker() + worker = _load_dsv_report_export() page = MagicMock() ensure = MagicMock() reset = MagicMock() @@ -228,7 +305,7 @@ def test_prepare_dsv_batch_reuses_form_for_different_source_code_same_entry(monk def test_is_dsv_oauth_handshake_url_detects_pingfederate_page(): """authorization.oauth2 应识别为 OAuth 握手中间页。""" - worker = _load_worker() + worker = _load_rpa_module("dsv_auth") url = ( "https://auth.dbschenker.com/as/authorization.oauth2?" "response_type=code&client_id=contract-logistics-360" @@ -240,7 +317,7 @@ def test_is_dsv_oauth_handshake_url_detects_pingfederate_page(): def test_goto_dsv_entry_url_tolerates_domcontentloaded_timeout_on_auth_redirect(monkeypatch): """goto 超时但已跳转到 auth 域时不应抛错。""" - worker = _load_worker() + worker = _load_rpa_module("dsv_session") page = MagicMock() page.url = "https://auth.dbschenker.com/as/authorization.oauth2?response_type=code" diff --git a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py b/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py index 7269c01f..7dc0c76c 100644 --- a/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py +++ b/backend/tests/test_shipping_notice_inventory_snapshot_reuse.py @@ -46,6 +46,76 @@ def test_fresh_snapshot_is_reused(app, tmp_path): assert is_snapshot_fresh(found) +def test_snapshot_uses_site_id_as_matching_warehouse(app, tmp_path): + """DSV 子仓导出入库后,应用 site_id 作为库存匹配与发货 Excel 的 warehouse id。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + from openpyxl import Workbook + + xlsx = tmp_path / "stock.xlsx" + wb = Workbook() + wb.active.append(["sku", "qty"]) + wb.active.append(["A001", 10]) + wb.save(xlsx) + wb.close() + + source = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01") + assert source is not None + assert source["site_id"] == "AWSBI" + assert source["warehouse_id"] == "BYAWSATL01" + + with app.app_context(): + inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True) + task = ShippingTask(task_no="SN-SNAPSHOT-SITE", source_type="manual", process_status="waiting_inventory") + db.session.add(task) + db.session.flush() + link = link_snapshot_to_task(task, inv, reason="reuse_latest") + db.session.commit() + + assert inv.warehouse_id == "AWSBI" + assert (inv.source_query_json or {}).get("export_warehouse_id") == "BYAWSATL01" + assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI") is not None + assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "BYAWSATL01") is None + assert link is not None + assert link.matched_warehouse_id == "AWSBI" + + +def test_snapshot_without_site_id_uses_inventory_excel_warehouse_id(app, tmp_path): + """无配置 site_id 时,快照 warehouse_id 应取库存 Excel 内的 Warehouse ID。""" + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") + + from openpyxl import Workbook + + xlsx = tmp_path / "crane_stock.xlsx" + wb = Workbook() + wb.active.append(["Warehouse ID", "sku", "qty"]) + wb.active.append(["TZR2", "A001", 10]) + wb.save(xlsx) + wb.close() + + source = { + "source_code": "CRANE", + "source_type": "crane_footprint", + "site_id": "", + "warehouse_id": "", + } + + with app.app_context(): + inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True) + task = ShippingTask(task_no="SN-SNAPSHOT-EXCEL-WH", source_type="manual", process_status="waiting_inventory") + db.session.add(task) + db.session.flush() + link = link_snapshot_to_task(task, inv, reason="rpa_callback") + db.session.commit() + + assert inv.warehouse_id == "TZR2" + assert (inv.source_query_json or {}).get("site_id") is None + assert (inv.source_query_json or {}).get("excel_warehouse_id") == "TZR2" + assert (inv.source_query_json or {}).get("warehouse_id_source") == "inventory_excel" + assert link is not None + assert link.matched_warehouse_id == "TZR2" + + def test_expired_snapshot_not_reused(app, tmp_path): """过期快照不应被 find_latest_ready_snapshot 返回。""" app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping") diff --git a/backend/tests/test_shipping_notice_inventory_sources_config.py b/backend/tests/test_shipping_notice_inventory_sources_config.py index 88193b44..78c00085 100644 --- a/backend/tests/test_shipping_notice_inventory_sources_config.py +++ b/backend/tests/test_shipping_notice_inventory_sources_config.py @@ -19,8 +19,9 @@ def test_inventory_sources_yaml_loads(app): reload_inventory_sources_config() source = get_inventory_source("DSV360_AWSDU") assert source is not None - assert source["warehouse_id"] == "AWSDU" assert source["source_type"] == "dsv360" + assert source["site_id"] == "AWSDU" + assert source["warehouse_id"] == "" assert source["query"]["program_label"] @@ -29,6 +30,7 @@ def test_build_rpa_inventory_source_keeps_legacy_query(app): with app.app_context(): payload = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01") assert payload is not None + assert payload["site_id"] == "AWSBI" assert payload["warehouse_id"] == "BYAWSATL01" assert payload["query"]["warehouse_code"] == "BYAWSATL01" assert payload["query"]["program_label"] == "AWSBI" @@ -37,6 +39,23 @@ def test_build_rpa_inventory_source_keeps_legacy_query(app): assert payload["parameters"][0]["name"] == "Warehouse" +def test_awsams_warehouse_uses_multi_select_all(app): + """AWSAMS Warehouse 是 SSRS checkbox 下拉,配置应显式走 multi_select + select_all。""" + with app.app_context(): + reload_inventory_sources_config() + payload = build_rpa_inventory_source("DSV360_AWSAMS") + assert payload is not None + warehouse_param = next(item for item in payload["parameters"] if item["name"] == "Warehouse") + assert warehouse_param["mode"] == "multi_select" + assert warehouse_param["select_all"] is True + assert warehouse_param["values"] == ["RTM"] + assert warehouse_param["selectors"] == { + "text": "#ReportViewerMain_ctl08_ctl17_txtValue", + "toggle": "#ReportViewerMain_ctl08_ctl17_ctl01", + "dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown", + } + + def test_duplicate_source_code_raises(app, tmp_path): """source_code 重复时加载应报错。""" bad = tmp_path / "bad_sources.json" @@ -45,8 +64,8 @@ def test_duplicate_source_code_raises(app, tmp_path): { "version": 1, "sources": [ - {"source_code": "X1", "enabled": true, "site": "dsv360", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []}, - {"source_code": "X1", "enabled": true, "site": "dsv360", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []} + {"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []}, + {"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []} ] } """, @@ -58,6 +77,42 @@ def test_duplicate_source_code_raises(app, tmp_path): reload_inventory_sources_config() +def test_dsv_source_requires_site_id(app, tmp_path): + """DSV 源必须显式配置 site_id,避免把站点和仓库混用。""" + bad = tmp_path / "bad_sources.yaml" + bad.write_text( + """ +version: 1 +sources: +- source_code: DSV360_BAD + enabled: true + source_type: dsv360 + warehouse_id: AWSBI + entry_url: http://x + navigation: {} + parameters: [] + """, + encoding="utf-8", + ) + app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad) + with app.app_context(): + with pytest.raises(InventorySourceConfigError, match="site_id is required"): + reload_inventory_sources_config() + + +def test_build_rpa_inventory_source_crane_has_no_site_or_warehouse_requirement(app): + """Crane 源不要求配置 site_id/warehouse_id,导出走 Schedule Report 异步下载。""" + with app.app_context(): + reload_inventory_sources_config() + payload = build_rpa_inventory_source("CRANE") + assert payload is not None + assert payload["source_type"] == "crane_footprint" + assert payload["site_id"] == "" + assert payload["warehouse_id"] == "" + assert payload["parameters"] == [] + assert payload["navigation"]["download_mode"] == "scheduled_report" + + def test_match_aliases_available_via_list(app): """list_inventory_sources 应包含 match_aliases 供规则匹配。""" with app.app_context(): @@ -65,6 +120,6 @@ def test_match_aliases_available_via_list(app): codes = {item["source_code"] for item in list_inventory_sources()} assert "DSV360_AWSDU" in codes assert "DSV360_AWSBI_BYAWSATL01" in codes - assert "CRANE_TZR2" in codes + assert "CRANE" in codes awsbi_count = sum(1 for item in list_inventory_sources() if str(item.get("source_code", "")).startswith("DSV360_AWSBI_")) assert awsbi_count == 25 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 0eab5c0a..8bb1e0a7 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -3190,7 +3190,7 @@ API 层 ### 5.1 配置文件 - 路径:`backend/config/shipping_inventory_sources.yaml`(环境变量 `SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG`) -- **新增 Warehouse 只改 YAML**,不改 Python;字段含 `source_code`、`site`(`dsv360` / `crane_footprint`)、`warehouse_id`、`navigation`、`parameters`、`match_aliases` +- **新增 Warehouse 只改 YAML**,不改 Python;字段含 `source_code`、`source_type`(`dsv360` / `crane_footprint`)、`site_id`(DSV 必填,如 `AWSBI` / `AWSDBU`;配置后发货 Excel 直接使用该值)、`warehouse_id`(DSV 部分站点需要具体仓库)、`navigation`、`parameters`、`match_aliases`。Crane 可不配置 `site_id`;无 `site_id` 时,发货 Excel 的 Warehouse ID 取实际库存 Excel 内的 Warehouse ID。 - 环境变量: - `SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS`(默认 24) - `SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED`(默认 true) diff --git a/scripts/rpa/README.md b/scripts/rpa/README.md index e0b90e24..5103967c 100644 --- a/scripts/rpa/README.md +++ b/scripts/rpa/README.md @@ -2,6 +2,22 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA 脚本在 Windows 货代终端上运行(或由本 PoC worker 在开发环境模拟)。 +## 模块结构 + +| 文件 | 职责 | +|------|------| +| `freight_rpa_worker.py` | 轮询 trigger、打开浏览器、按 `source_type` 分发、HTTP 回调(~900 行) | +| `rpa_common.py` | 环境变量、通用 Playwright 点击/填充工具 | +| `dsv_driver.py` | DSV 对外入口:`download_dsv360_inventory` | +| `dsv_auth.py` | DSV PingID 分步登录(表单/探测辅助) | +| `dsv_auth_login_flow.py` | DSV 自动登录主编排 `maybe_auto_login_dsv` | +| `dsv_session.py` | DSV portal 壳层检测、首页 ready、entry_url | +| `dsv_navigation.py` | DSV Reports 菜单 → 报表参数页 | +| `dsv_report_export.py` | DSV 填参、View Report、Excel 导出、batch 复用 | +| `dsv_debug.py` | DSV 调试探针与链路日志 | +| `dsv_report_parameters.py` | SSRS 参数控件填充(已有) | +| `crane_session.py` / `crane_report_export.py` | Crane 登录与异步导出 | + ## 目录约定 | 环境变量 | 用途 | @@ -64,9 +80,20 @@ python scripts/rpa/freight_rpa_worker.py | `FREIGHT_RPA_DSV_USERNAME_SELECTOR` | DSV 用户名输入框 | | `FREIGHT_RPA_DSV_PASSWORD_SELECTOR` | DSV 密码输入框 | | `FREIGHT_RPA_DSV_LOGIN_BUTTON_SELECTOR` | DSV 登录按钮 | -| `FREIGHT_RPA_CRANE_USERNAME_SELECTOR` | Crane 用户名输入框 | -| `FREIGHT_RPA_CRANE_PASSWORD_SELECTOR` | Crane 密码输入框 | -| `FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR` | Crane 登录按钮 | +| `FREIGHT_RPA_CRANE_USERNAME_SELECTOR` | Crane 用户名(默认 `input[placeholder="Enter user name..."]`) | +| `FREIGHT_RPA_CRANE_PASSWORD_SELECTOR` | Crane 密码(默认 `input[placeholder="Enter password..."]`) | +| `FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR` | Crane 登录按钮(默认 `button.button.is-primary:has-text("Sign in")`;填写凭据前为 disabled) | +| `FREIGHT_RPA_CRANE_DASHBOARD_REPORT_SELECTOR` | Crane 首页 Queries 区 On Hand Details 卡片(默认 `a.box[href="/on-hand-details-query"]`) | +| `FREIGHT_RPA_CRANE_NAV_QUERIES_SELECTOR` | Crane 顶部 Queries 下拉触发(默认 `a.navbar-link:has-text("Queries")`) | +| `FREIGHT_RPA_CRANE_NAV_REPORT_SELECTOR` | Crane 顶部菜单 On Hand Details 项(默认 `a.navbar-item:has-text("On Hand Details")`) | + +Crane 登录烟测(仅验证 User Name / Password / Sign in): + +```powershell +$env:FREIGHT_RPA_CRANE_USERNAME = "" +$env:FREIGHT_RPA_CRANE_PASSWORD = "" +backend\venv\Scripts\python.exe scripts\rpa\crane_login_smoke.py +``` 若页面出现 MFA、验证码或 SSO 二次确认,worker 会失败并回调错误,需要人工处理后重试。 @@ -75,7 +102,7 @@ python scripts/rpa/freight_rpa_worker.py | source_type | Driver | |-------------|--------| | `dsv360` | 打开 DSV 360,进入 Reports / Program / Inventory 报表并下载 | -| `crane_footprint` | 打开 Crane FootPrint On Hand Details Query,选择 Owner/Project/Warehouse 后下载 | +| `crane_footprint` | 打开 On Hand Details Query → Run Report → Schedule Report → Scheduled Reports 下载 | ### 批量库存导出(`inventory_export_batch`) @@ -86,11 +113,11 @@ python scripts/rpa/freight_rpa_worker.py "action": "inventory_export_batch", "run_no": "RUN20260707030000", "trigger_type": "scheduled", - "inventory_sources": [{ "source_code": "DSV360_AWSDU", "source_type": "dsv360", "warehouse_id": "AWSDU" }] + "inventory_sources": [{ "source_code": "DSV360_AWSBI_BYAWSATL01", "source_type": "dsv360", "site_id": "AWSBI", "warehouse_id": "BYAWSATL01" }] } ``` -Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,**Crane 一次登录**循环各 Warehouse;完成后回调 `POST /api/shipping-notice/rpa/inventory-batch-ready`。 +Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,DSV source 必须包含 `site_id`(如 `AWSBI` / `AWSDBU`),部分站点还需要具体 `warehouse_id`;**Crane 一次登录**循环导出,Crane 不要求 `site_id` 或 `warehouse_id`。无 `site_id` 时,后端会从实际库存 Excel 的 Warehouse ID 列提取发货 Excel 要写入的 Warehouse ID。完成后回调 `POST /api/shipping-notice/rpa/inventory-batch-ready`。 库存源定义见 `backend/config/shipping_inventory_sources.yaml`(新增 Warehouse 只改 YAML)。 @@ -104,11 +131,23 @@ Worker 按 `source_type` 分组:**DSV 一次登录**循环各 Warehouse,**Cr | `FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR` | DSV On Hand Inventory by Location | | `FREIGHT_RPA_DSV_OWNER_SELECTOR` | DSV Owner 输入框 | | `FREIGHT_RPA_DSV_EXPORT_SELECTOR` | DSV 导出按钮 | -| `FREIGHT_RPA_CRANE_OWNER_SELECTOR` | Crane Owner 下拉/输入 | -| `FREIGHT_RPA_CRANE_PROJECT_SELECTOR` | Crane Project 下拉/输入 | -| `FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR` | Crane Warehouse 下拉/输入 | -| `FREIGHT_RPA_CRANE_RUN_SELECTOR` | Crane Run Report 按钮 | -| `FREIGHT_RPA_CRANE_EXPORT_SELECTOR` | Crane 下载按钮 | +| `FREIGHT_RPA_CRANE_RUN_SELECTOR` | Crane Run Report 按钮(默认 `button.button.is-primary:has-text("Run Report")`) | +| `FREIGHT_RPA_CRANE_SCHEDULE_REPORT_SELECTOR` | Crane Schedule Report 按钮(默认 `button:has-text("Schedule Report")`) | +| `FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_SELECTOR` | Schedule Report 弹窗 Description 输入框 | +| `FREIGHT_RPA_CRANE_SCHEDULE_OK_SELECTOR` | Schedule Report 弹窗 Ok 按钮 | +| `FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION` | 覆盖自动生成的 Description | +| `FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN` | Description 十六进制长度(默认 **12**,范围 8~32) | +| `FREIGHT_RPA_CRANE_SCHEDULED_REPORTS_SELECTOR` | Crane Scheduled Reports 入口(默认 `a.has-link[href="#/scheduled-reports"]`) | +| `FREIGHT_RPA_CRANE_SCHEDULED_DOWNLOAD_SELECTOR` | Scheduled Reports 列表中的下载按钮 | +| `FREIGHT_RPA_CRANE_SUBMISSION_COMPLETE_WAIT_MS` | 等待 Report Submitted 提示消失的最长时间(默认 120000) | +| `FREIGHT_RPA_CRANE_SCHEDULED_TABLE_SELECTOR` | Scheduled Reports 表格行选择器 | +| `FREIGHT_RPA_CRANE_SCHEDULED_REPORT_NAME` | Scheduled Reports 目标文件名(Name 列,默认 `OnHandDetails.xlsx`) | +| `FREIGHT_RPA_CRANE_SCHEDULED_REPORT_WAIT_MS` | 等待列表行 Submitted→Download 的最长时间(默认 300000) | +| `FREIGHT_RPA_CRANE_SCHEDULED_REPORT_POLL_SECONDS` | 轮询 Scheduled Reports 间隔秒数(默认 3) | +| `FREIGHT_RPA_CRANE_SCHEDULED_REPORTS_URL` | Scheduled Reports 页面 URL(默认由当前站点 hash 推导) | +| `FREIGHT_RPA_CRANE_OWNER_SELECTOR` | Crane Owner 下拉/输入(可选) | +| `FREIGHT_RPA_CRANE_PROJECT_SELECTOR` | Crane Project 下拉/输入(可选) | +| `FREIGHT_RPA_CRANE_EXPORT_SELECTOR` | Crane 直出下载按钮(仅 `download_mode: file_download` 时使用) | 发货 Excel 上传仍保留原 PoC 行为:`FREIGHT_RPA_MOCK=false` 时不会自动上传,需后续实现上传 Driver 或接入 UiPath / Power Automate。 diff --git a/scripts/rpa/crane_export_smoke.py b/scripts/rpa/crane_export_smoke.py new file mode 100644 index 00000000..39e93a3d --- /dev/null +++ b/scripts/rpa/crane_export_smoke.py @@ -0,0 +1,115 @@ +""" +scripts/rpa/crane_export_smoke.py + +用途:本地手动验证 Crane CRANE 库存源浏览器导出全流程。 +依赖:Playwright、FREIGHT_RPA_CRANE_USERNAME/PASSWORD、shipping_inventory_sources.yaml。 +逻辑:加载 CRANE rpa_inventory_source → _download_inventory_with_browser → 输出 Excel 路径。 + +用法(仓库根目录): + backend\\venv\\Scripts\\python.exe scripts\\rpa\\crane_export_smoke.py +""" +from __future__ import annotations + +import importlib.util +import json +import os +import sys +import tempfile +import traceback +from datetime import datetime +from pathlib import Path + +import yaml + + +def _repo_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def _load_worker(): + module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py" + spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_export_smoke", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _build_source_from_config(source_code: str = "CRANE") -> dict: + """ + 从 YAML 构造 worker 兼容的 rpa_inventory_source。 + 核心逻辑:Crane 走 scheduled_report 异步导出,不依赖 warehouse_id。 + """ + config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.yaml" + payload = yaml.safe_load(config_path.read_text(encoding="utf-8")) + raw = next( + ( + item + for item in (payload.get("sources") or []) + if str(item.get("source_code") or "").upper() == source_code.upper() + ), + None, + ) + if not raw: + raise RuntimeError(f"source_code not found in config: {source_code}") + + return { + "source_code": str(raw.get("source_code") or source_code).upper(), + "source_type": str(raw.get("source_type") or "crane_footprint").strip().lower(), + "display_name": str(raw.get("display_name") or source_code), + "enabled": bool(raw.get("enabled", True)), + "entry_url": str(raw.get("entry_url") or "https://wms-portal.craneww.com/#/on-hand-details-query"), + "navigation": dict(raw.get("navigation") or {}), + "parameters": [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)], + "query": {}, + } + + +def main() -> int: + source_code = (sys.argv[1] if len(sys.argv) > 1 else "CRANE").strip().upper() + os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false") + os.environ.setdefault("FREIGHT_RPA_MOCK", "false") + os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true") + os.environ.setdefault( + "FREIGHT_RPA_BROWSER_PROFILE_DIR", + "backend/data/shipping_notice/freight_rpa/browser_profile", + ) + if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"): + os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge") + + worker = _load_worker() + if not worker._env("FREIGHT_RPA_CRANE_USERNAME") or not worker._env("FREIGHT_RPA_CRANE_PASSWORD"): + print("[crane-export-smoke] 缺少 FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD") + return 1 + + source = _build_source_from_config(source_code) + task_no = f"SIF-SMOKE-{datetime.now().strftime('%Y%m%d%H%M%S')}" + trigger = { + "action": "inventory_export", + "task_no": task_no, + "requested_at": datetime.utcnow().isoformat(), + "mode": "smoke", + "attempt": 1, + "rpa_inventory_source": source, + } + drop_dir = Path(tempfile.mkdtemp(prefix=f"crane_export_{source_code.lower()}_")) + + print(f"[crane-export-smoke] source={source_code}") + print(f"[crane-export-smoke] navigation={json.dumps(source.get('navigation') or {}, ensure_ascii=False)}") + print(f"[crane-export-smoke] drop_dir={drop_dir}") + print("[crane-export-smoke] 正在打开浏览器执行登录 + Run Report + Schedule 异步导出(预计 3~8 分钟)…") + + try: + out_file = worker._download_inventory_with_browser(trigger, drop_dir) + size_kb = out_file.stat().st_size / 1024 + print(f"[crane-export-smoke] SUCCESS — {out_file} ({size_kb:.1f} KB)") + return 0 + except Exception as exc: + print(f"[crane-export-smoke] FAILED — {exc}") + traceback.print_exc() + print("[crane-export-smoke] FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR=true,浏览器保持打开以便排查。") + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/rpa/crane_login_smoke.py b/scripts/rpa/crane_login_smoke.py new file mode 100644 index 00000000..6b68f2a9 --- /dev/null +++ b/scripts/rpa/crane_login_smoke.py @@ -0,0 +1,99 @@ +""" +scripts/rpa/crane_login_smoke.py + +用途:本地手动验证 Crane FootPrint Portal 自动登录。 +依赖:Playwright、FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD。 +逻辑:打开 On Hand Details Query 入口 → maybe_auto_login_crane → 保持窗口供人工确认。 + +用法(仓库根目录): + $env:FREIGHT_RPA_HEADLESS = "false" + backend\\venv\\Scripts\\python.exe scripts\\rpa\\crane_login_smoke.py +""" +from __future__ import annotations + +import importlib.util +import os +import shutil +import sys +import tempfile +import traceback +from pathlib import Path + + +def _load_worker(): + repo_root = Path(__file__).resolve().parents[2] + module_path = repo_root / "scripts" / "rpa" / "freight_rpa_worker.py" + spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_smoke", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def main() -> int: + os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false") + os.environ.setdefault("FREIGHT_RPA_MOCK", "false") + os.environ.setdefault( + "FREIGHT_RPA_BROWSER_PROFILE_DIR", + "backend/data/shipping_notice/freight_rpa/browser_profile", + ) + if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"): + os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge") + + worker = _load_worker() + username = worker._env("FREIGHT_RPA_CRANE_USERNAME") + password = worker._env("FREIGHT_RPA_CRANE_PASSWORD") + if not username or not password: + print("[crane-smoke] 缺少 FREIGHT_RPA_CRANE_USERNAME / FREIGHT_RPA_CRANE_PASSWORD,请先配置环境变量。") + return 1 + + entry_url = "https://wms-portal.craneww.com/#/on-hand-details-query" + drop_dir = Path(tempfile.mkdtemp(prefix="crane_smoke_drop_")) + playwright = context = runtime_profile_dir = None + + print(f"[crane-smoke] headless={worker._env('FREIGHT_RPA_HEADLESS', 'false')}") + print(f"[crane-smoke] user={username[:3]}*** entry={entry_url}") + print("[crane-smoke] 正在打开浏览器并执行 Crane 自动登录…") + + try: + playwright, context, page, runtime_profile_dir = worker._open_browser(drop_dir) + worker._ensure_crane_session(page, entry_url) + print(f"[crane-smoke] SUCCESS — Crane session ready, url={page.url}") + print("[crane-smoke] 请在浏览器中确认 On Hand Details Query 表单可见。按 Enter 关闭浏览器…") + try: + input() + except EOFError: + import time + + print("[crane-smoke] 非交互终端,保持浏览器 300 秒后自动关闭。") + time.sleep(300) + return 0 + except Exception as exc: + print(f"[crane-smoke] FAILED — {exc}") + traceback.print_exc() + print("[crane-smoke] 浏览器将保持打开 120 秒以便排查,按 Enter 提前关闭…") + try: + input() + except EOFError: + import time + + time.sleep(120) + return 2 + finally: + if context is not None: + try: + context.close() + except Exception: + pass + if playwright is not None: + try: + playwright.stop() + except Exception: + pass + if runtime_profile_dir is not None: + shutil.rmtree(runtime_profile_dir, ignore_errors=True) + shutil.rmtree(drop_dir, ignore_errors=True) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/rpa/crane_navigation.py b/scripts/rpa/crane_navigation.py new file mode 100644 index 00000000..2c4a3e67 --- /dev/null +++ b/scripts/rpa/crane_navigation.py @@ -0,0 +1,410 @@ +""" +scripts/rpa/crane_navigation.py + +用途:Crane FootPrint Portal 报表页导航(On Hand Details Query)。 +依赖:Playwright Page;由 crane_session.wait_for_crane_app_ready 在登录后调用。 +逻辑:优先点击首页 Queries 区 On Hand Details 卡片;失败再走顶部 Queries 下拉菜单;最后 goto entry_url。 +""" + +from __future__ import annotations + +import sys +import time +from typing import Any, Callable +from urllib.parse import urlparse + +_ON_HAND_DETAILS_LABEL = "On Hand Details" +_ON_HAND_DETAILS_ROUTE = "on-hand-details-query" + +# 首页 Queries 区大卡片:Vue hash 路由常见 href="#/on-hand-details-query"(非 "/on-hand-details-query") +_CRANE_DASHBOARD_REPORT_TILE_SELECTORS: tuple[str, ...] = ( + 'a[href*="on-hand-details-query"]', + 'a.box[href*="on-hand-details-query"]', + 'a.box.has-text-centered[href*="on-hand-details-query"]', + 'a.box:has-text("On Hand Details")', + 'a:has-text("On Hand Details")', + '.box:has-text("On Hand Details")', +) + +# 顶部导航 Queries 下拉(第二张图) +_CRANE_NAV_QUERIES_MENU_SELECTORS: tuple[str, ...] = ( + 'a.navbar-link:has-text("Queries")', + '.navbar-item.has-dropdown > a.navbar-link', +) + +_CRANE_NAV_ON_HAND_DETAILS_SELECTORS: tuple[str, ...] = ( + '.navbar-dropdown a.navbar-item:has-text("On Hand Details")', + 'a.navbar-item:has-text("On Hand Details")', +) + +# 报表表单就绪信号:必须出现 Run Report 或报表参数字段;首页 Queries 区标题不算 ready +_CRANE_REPORT_FORM_READY_SELECTORS: tuple[str, ...] = ( + 'button:has-text("Run Report")', + '[role="button"]:has-text("Run Report")', + 'text=Choose Warehouse', + 'text=Select Owner', +) + + +def _visible_locator(page: Any, selector: str) -> Any | None: + """在 page 与各 frame 中查找首个可见 locator。""" + for root in (page, *list(getattr(page, "frames", []))): + try: + locator = root.locator(selector).first + if locator.is_visible(timeout=500): + return locator + except Exception: + continue + return None + + +def _report_route_from_entry_url(entry_url: str) -> str: + """从 entry_url hash 提取报表路由片段,默认 on-hand-details-query。""" + parsed = urlparse(str(entry_url or "").strip()) + fragment = (parsed.fragment or "").strip().lstrip("/").lower() + if fragment: + return fragment + return _ON_HAND_DETAILS_ROUTE + + +def _current_url_fragment(page: Any) -> str: + """读取当前页 URL hash 片段(不含 #/ 前缀)。""" + try: + current_url = str(page.url or "") + except Exception: + return "" + parsed = urlparse(current_url) + return (parsed.fragment or "").strip().lstrip("/").lower() + + +def is_crane_on_homepage(page: Any) -> bool: + """ + 判定是否停在 Crane 登录后首页(/#/ 或空 hash)。 + 核心逻辑:首页 Queries 区有 On Hand Details 卡片,但报表表单尚未打开,不能视为 ready。 + """ + fragment = _current_url_fragment(page) + if not fragment or fragment in {"home", "dashboard", "index"}: + return True + return False + + +def is_crane_on_report_route(page: Any, entry_url: str) -> bool: + """当前 URL hash 是否已落在目标报表路由。""" + target_route = _report_route_from_entry_url(entry_url) + fragment = _current_url_fragment(page) + if not fragment: + return False + return target_route in fragment + + +def _has_report_form_controls(page: Any) -> bool: + """Run Report 或报表参数字段是否可见。""" + for selector in _CRANE_REPORT_FORM_READY_SELECTORS: + if _visible_locator(page, selector) is not None: + return True + return False + + +def is_crane_report_form_ready(page: Any, entry_url: str) -> bool: + """ + 判定 On Hand Details Query 报表表单是否已就绪。 + 核心逻辑:首页 /#/ 不算 ready;必须 hash 落在报表路由且出现 Run Report / 参数字段。 + """ + if is_crane_on_homepage(page): + return False + if not is_crane_on_report_route(page, entry_url): + return False + return _has_report_form_controls(page) + + +def _click_visible_locator(locator: Any, *, browser_timeout_ms: int) -> bool: + try: + locator.click(timeout=browser_timeout_ms) + return True + except Exception: + pass + try: + locator.click(timeout=browser_timeout_ms, force=True) + return True + except Exception: + return False + + +def _wait_for_crane_homepage_ready(page: Any, *, browser_timeout_ms: int) -> bool: + """ + 登录后等待首页 Queries 区渲染完成。 + 核心逻辑:On Hand Details 卡片或 Queries 标题出现后再尝试点击,避免 SPA 未挂载时误判失败。 + """ + deadline = time.monotonic() + (min(browser_timeout_ms, 20_000) / 1000) + while time.monotonic() < deadline: + for selector in ( + 'text=On Hand Details', + 'text=Queries', + 'a[href*="on-hand-details-query"]', + '.box:has-text("On Hand Details")', + ): + if _visible_locator(page, selector) is not None: + print("[crane-nav] homepage shell ready") + return True + time.sleep(0.25) + print("[crane-nav] homepage shell not detected before timeout", file=sys.stderr) + return False + + +def _click_by_role_link(page: Any, name: str, *, browser_timeout_ms: int) -> bool: + for root in (page, *list(getattr(page, "frames", []))): + try: + locator = root.get_by_role("link", name=name, exact=False).first + if locator.is_visible(timeout=500): + return _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms) + except Exception: + pass + return False + + +def _click_on_hand_details_tile(page: Any, *, browser_timeout_ms: int) -> bool: + """ + 通过文本语义点击首页 Queries 区的 On Hand Details 卡片。 + 核心逻辑:hash 路由下 tile 可能是 a[href*=#/on-hand-details-query] 或 .box 包裹的 router-link。 + """ + tile_selectors = ( + '.columns .box:has-text("On Hand Details")', + 'section:has-text("Queries") .box:has-text("On Hand Details")', + '.box:has-text("On Hand Details")', + 'a[href*="on-hand-details-query"]', + '[class*="box"]:has-text("On Hand Details")', + ) + for selector in tile_selectors: + locator = _visible_locator(page, selector) + if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): + print(f"[crane-nav] clicked On Hand Details tile selector={selector!r}") + return True + + for root in (page, *list(getattr(page, "frames", []))): + try: + locator = root.get_by_role("link", name=_ON_HAND_DETAILS_LABEL, exact=False).first + if locator.is_visible(timeout=500) and _click_visible_locator( + locator, browser_timeout_ms=browser_timeout_ms + ): + print("[crane-nav] clicked On Hand Details tile via link role") + return True + except Exception: + pass + + for root in (page, *list(getattr(page, "frames", []))): + try: + locator = root.get_by_text(_ON_HAND_DETAILS_LABEL, exact=False).first + if not locator.is_visible(timeout=500): + continue + for candidate in ( + locator.locator("xpath=ancestor-or-self::a[1]"), + locator.locator("xpath=ancestor-or-self::*[contains(@class,'box')][1]"), + locator, + ): + try: + target = candidate.first + if target.is_visible(timeout=300) and _click_visible_locator( + target, browser_timeout_ms=browser_timeout_ms + ): + print("[crane-nav] clicked On Hand Details tile via text locator") + return True + except Exception: + continue + except Exception: + pass + return False + + +def _click_dashboard_on_hand_details( + page: Any, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> bool: + """ + 点击首页 Queries 区域的 On Hand Details 卡片(优先策略)。 + 核心逻辑:先文本语义定位 tile,再匹配 href*=on-hand-details-query 的 hash 路由链接。 + """ + if _click_on_hand_details_tile(page, browser_timeout_ms=browser_timeout_ms): + return True + + selectors = tuple( + item + for item in (env("FREIGHT_RPA_CRANE_DASHBOARD_REPORT_SELECTOR"), *_CRANE_DASHBOARD_REPORT_TILE_SELECTORS) + if item + ) + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): + print(f"[crane-nav] clicked dashboard tile selector={selector!r}") + return True + + if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms): + print("[crane-nav] clicked dashboard tile via link role") + return True + return False + + +def _open_queries_nav_menu(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool: + """展开顶部 Queries 下拉菜单。""" + selectors = tuple( + item for item in (env("FREIGHT_RPA_CRANE_NAV_QUERIES_SELECTOR"), *_CRANE_NAV_QUERIES_MENU_SELECTORS) if item + ) + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is None: + continue + try: + locator.hover(timeout=min(browser_timeout_ms, 5_000)) + except Exception: + pass + if _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): + print(f"[crane-nav] opened Queries menu selector={selector!r}") + return True + + for root in (page, *list(getattr(page, "frames", []))): + try: + locator = root.get_by_role("link", name="Queries", exact=False).first + if not locator.is_visible(timeout=500): + continue + try: + locator.hover(timeout=3_000) + except Exception: + pass + if _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): + print("[crane-nav] opened Queries menu via link role") + return True + except Exception: + pass + return False + + +def _click_navbar_on_hand_details( + page: Any, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> bool: + """ + 通过顶部 Queries 下拉进入 On Hand Details(回退策略)。 + 核心逻辑:先展开 Queries navbar-dropdown,再点 a.navbar-item On Hand Details。 + """ + if not _open_queries_nav_menu(page, env=env, browser_timeout_ms=browser_timeout_ms): + print("[crane-nav] Queries navbar menu not opened", file=sys.stderr) + return False + + time.sleep(0.35) + selectors = tuple( + item for item in (env("FREIGHT_RPA_CRANE_NAV_REPORT_SELECTOR"), *_CRANE_NAV_ON_HAND_DETAILS_SELECTORS) if item + ) + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is not None and _click_visible_locator(locator, browser_timeout_ms=browser_timeout_ms): + print(f"[crane-nav] clicked navbar item selector={selector!r}") + return True + + if _click_by_role_link(page, _ON_HAND_DETAILS_LABEL, browser_timeout_ms=browser_timeout_ms): + print("[crane-nav] clicked navbar On Hand Details via link role") + return True + return False + + +def _wait_for_report_navigation( + page: Any, + entry_url: str, + *, + browser_timeout_ms: int, +) -> bool: + """点击导航后短等待目标路由或表单控件出现。""" + deadline = time.monotonic() + (min(browser_timeout_ms, 15_000) / 1000) + while time.monotonic() < deadline: + if is_crane_report_form_ready(page, entry_url): + return True + time.sleep(0.25) + return False + + +def _navigate_hash_route(page: Any, entry_url: str, *, browser_timeout_ms: int) -> None: + """ + 通过 goto + hash 赋值进入 SPA 报表路由。 + 核心逻辑:登录后常落在 /#/ 首页,仅 goto 完整 entry_url 时 Vue 路由可能不切换。 + """ + target = str(entry_url or "").strip() + if not target: + raise RuntimeError("Crane report navigation failed: entry_url is empty") + + route = _report_route_from_entry_url(entry_url) + parsed = urlparse(target) + base_url = f"{parsed.scheme}://{parsed.netloc}/" + + print(f"[crane-nav] fallback direct goto entry_url={target!r}") + page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms) + if is_crane_on_report_route(page, entry_url) and _has_report_form_controls(page): + return + + print(f"[crane-nav] assigning hash route via SPA base={base_url!r} route={route!r}") + try: + page.goto(base_url, wait_until="domcontentloaded", timeout=browser_timeout_ms) + page.evaluate( + """ + (route) => { + const hash = route.startsWith('/') ? route : `/${route}`; + if (window.location.hash !== `#${hash}`) { + window.location.hash = hash; + } + } + """, + route, + ) + page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms) + try: + page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 10_000)) + except Exception: + pass + except Exception as exc: + print(f"[crane-nav] hash route assignment failed: {exc}", file=sys.stderr) + + +def navigate_to_crane_report( + page: Any, + entry_url: str, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> str: + """ + 导航至 On Hand Details Query 报表页。 + 核心逻辑:[STEP 1] 首页卡片点击 → [STEP 2] 顶部 Queries 菜单 → [STEP 3] 直接 goto entry_url。 + + Returns: + 使用的导航模式:`already_ready` | `dashboard_tile` | `navbar_menu` | `direct_goto`。 + + Raises: + RuntimeError: 三种方式均未能进入报表表单。 + """ + if is_crane_report_form_ready(page, entry_url): + print("[crane-nav] report form already ready, skip navigation") + return "already_ready" + + _wait_for_crane_homepage_ready(page, browser_timeout_ms=browser_timeout_ms) + + # [STEP 1] 首页 Queries 区 On Hand Details 卡片 + if _click_dashboard_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms): + if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms): + return "dashboard_tile" + print("[crane-nav] dashboard tile click did not reach report form, trying navbar", file=sys.stderr) + + # [STEP 2] 顶部 Queries → On Hand Details + if _click_navbar_on_hand_details(page, env=env, browser_timeout_ms=browser_timeout_ms): + if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms): + return "navbar_menu" + print("[crane-nav] navbar navigation did not reach report form, trying direct goto", file=sys.stderr) + + # [STEP 3] 直接打开配置的 entry_url(hash 路由) + _navigate_hash_route(page, entry_url, browser_timeout_ms=browser_timeout_ms) + if _wait_for_report_navigation(page, entry_url, browser_timeout_ms=browser_timeout_ms): + return "direct_goto" + + raise RuntimeError( + "Crane report navigation failed: dashboard tile, navbar menu, and direct goto did not reach report form" + ) diff --git a/scripts/rpa/crane_report_export.py b/scripts/rpa/crane_report_export.py new file mode 100644 index 00000000..52516ee2 --- /dev/null +++ b/scripts/rpa/crane_report_export.py @@ -0,0 +1,1164 @@ +""" +scripts/rpa/crane_report_export.py + +用途:Crane On Hand Details Query 异步报表导出(Run Report → Schedule Report → Scheduled Reports 下载)。 +依赖:Playwright Page;由 freight_rpa_worker._export_crane_inventory_source 委托调用。 +逻辑:必须先 Run Report 产出查询结果,再 Schedule 异步导出;轮询仅在 scheduled-reports 路由进行。 +""" + +from __future__ import annotations + +import sys +import time +import uuid +from typing import Any, Callable +from urllib.parse import urlparse + +# Schedule Report Description 默认取 UUID 前 12 位十六进制(无连字符)。 +# 48 bit ≈ 2.8e14 种组合,单租户 RPA 导出场景碰撞可忽略;页面示例多为 6~8 位人工填写。 +_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT = 12 +_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_MAX = 32 + +_CRANE_RUN_REPORT_SELECTORS: tuple[str, ...] = ( + 'button.button.is-primary.is-small:has-text("Run Report")', + 'button.button.is-primary:has-text("Run Report")', + 'button:has-text("Run Report")', +) + +_CRANE_SCHEDULE_REPORT_SELECTORS: tuple[str, ...] = ( + 'button.button.is-small.ml-2:has-text("Schedule Report")', + 'button:has-text("Schedule Report")', + 'button:has(.material-icons):has-text("Schedule Report")', +) + +_CRANE_SCHEDULED_REPORTS_LINK_SELECTORS: tuple[str, ...] = ( + 'a.has-link[href="#/scheduled-reports"]', + 'a[href="#/scheduled-reports"]', + 'a:has-text("Scheduled Reports")', + 'a.navbar-item:has-text("Scheduled Reports")', +) + +_CRANE_SCHEDULE_MODAL_SELECTORS: tuple[str, ...] = ( + "div.modal.is-active", + "div.modal.px-4.is-active", +) + +_CRANE_SCHEDULE_DESCRIPTION_SELECTORS: tuple[str, ...] = ( + "div.modal-card-body input.input.is-small", + "section.modal-card-body input.input", + "div.modal.is-active input.input", +) + +_CRANE_SCHEDULE_OK_SELECTORS: tuple[str, ...] = ( + 'div.modal-card-body button.button.is-primary:has-text("Ok")', + 'div.modal.is-active button.button.is-primary:has-text("Ok")', + 'section.modal-card-body button.button.is-primary:has-text("Ok")', +) + +_CRANE_SCHEDULED_REPORTS_ROUTE = "scheduled-reports" + +_CRANE_REPORT_SUBMISSION_STATUS_TEXTS: tuple[str, ...] = ( + "Report Submitted", + "Report Creation Status", +) + +_CRANE_SCHEDULED_TABLE_SELECTOR = "table.table.is-fullwidth tbody tr" + +# Scheduled Reports 表列序:Name | Submitted | Description | Download(页面默认按 Submitted 降序)。 +_CRANE_SCHEDULED_COL_NAME = 0 +_CRANE_SCHEDULED_COL_SUBMITTED = 1 +_CRANE_SCHEDULED_COL_DESCRIPTION = 2 +_CRANE_SCHEDULED_COL_DOWNLOAD = 3 +_CRANE_SCHEDULED_REPORT_NAME_DEFAULT = "OnHandDetails.xlsx" +_CRANE_SCHEDULED_SCAN_MAX_ROWS_DEFAULT = 20 +_CRANE_SESSION_MODULE: Any | None = None + + +def _load_crane_session_module() -> Any: + """运行时加载 crane_session(模块级缓存,避免轮询时重复 import)。""" + global _CRANE_SESSION_MODULE + if _CRANE_SESSION_MODULE is not None: + return _CRANE_SESSION_MODULE + + import importlib.util + from pathlib import Path + + module_path = Path(__file__).resolve().parent / "crane_session.py" + spec = importlib.util.spec_from_file_location("crane_session_export_runtime", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + _CRANE_SESSION_MODULE = module + return module + + +def _default_crane_entry_url(source: dict[str, Any] | None) -> str: + """从 source 读取 Crane entry_url。""" + if isinstance(source, dict): + configured = str(source.get("entry_url") or "").strip() + if configured: + return configured + return "https://wms-portal.craneww.com/#/on-hand-details-query" + + +def _is_crane_login_page(page: Any) -> bool: + """当前是否显示 Crane 登录表单(含 hash=scheduled-reports 但 session 已过期的场景)。""" + return bool(_load_crane_session_module().is_crane_login_page(page)) + + +def _scheduled_reports_table_visible(page: Any) -> bool: + """ + Scheduled Reports 表格是否已渲染(不依赖 session 路由判定)。 + 核心逻辑:reload 过渡态可能同时闪登录框与旧表格,以表格可见为准视为仍在列表页。 + """ + table_selector = _CRANE_SCHEDULED_TABLE_SELECTOR + for root in (page, *list(getattr(page, "frames", []))): + try: + rows = root.locator(table_selector) + if rows.count() > 0: + return True + except Exception: + continue + return False + + +def _is_crane_login_blocking(page: Any) -> bool: + """ + 是否处于需要重登的状态。 + 核心逻辑:仅当登录框可见且 Scheduled Reports 表格不可见时才视为 session 失效; + reload /bootstrap 期间登录框可能短暂出现,但表格仍在则不应触发重登。 + """ + if not _is_crane_login_page(page): + return False + if _scheduled_reports_table_visible(page): + return False + return True + + +def _wait_for_scheduled_reports_list_ready( + page: Any, + *, + browser_timeout_ms: int, +) -> bool: + """ + reload/goto 后等待 Scheduled Reports 列表渲染完成。 + 核心逻辑:优先等表格出现;超时后再判断是否真正落在登录页。 + """ + deadline = time.monotonic() + min(browser_timeout_ms / 1000, 15.0) + while time.monotonic() < deadline: + if _scheduled_reports_table_visible(page): + return True + if _is_crane_login_blocking(page): + return False + time.sleep(0.35) + return _scheduled_reports_table_visible(page) + + +def _navigate_to_scheduled_reports_route( + page: Any, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> None: + """直接打开 Scheduled Reports hash 路由(不经过 On Hand Details 首页)。""" + target = _scheduled_reports_url(page, env=env) + print(f"[crane-export] goto scheduled reports url={target!r}", file=sys.stderr) + page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms) + try: + page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 8_000)) + except Exception: + pass + + +def _recover_crane_session_on_scheduled_reports( + page: Any, + entry_url: str, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> None: + """ + 在 Scheduled Reports 等待期间恢复登录态并回到列表页。 + 核心逻辑:重登后不 navigate 到 On Hand Details,直接 goto #/scheduled-reports 继续轮询。 + """ + session = _load_crane_session_module() + if session.is_crane_session_active(page, entry_url) and _is_on_scheduled_reports_page(page): + return + if _is_crane_login_blocking(page): + print("[crane-export] session lost on scheduled reports; re-login and return to list", file=sys.stderr) + session.maybe_auto_login_crane(page, env=env, browser_timeout_ms=browser_timeout_ms) + if not session.is_crane_session_active(page, entry_url): + raise RuntimeError("Crane session lost during scheduled report wait; re-login did not succeed") + if not _is_on_scheduled_reports_page(page): + _navigate_to_scheduled_reports_route(page, env=env, browser_timeout_ms=browser_timeout_ms) + _wait_for_scheduled_reports_list_ready(page, browser_timeout_ms=browser_timeout_ms) + print("[crane-export] session restored; staying on scheduled reports", file=sys.stderr) + + +def _ensure_crane_session_for_export( + page: Any, + entry_url: str, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> None: + """ + 导出等待过程中检测并恢复 Crane 登录态。 + 核心逻辑:列表表格仍可见时不重登;仅 session 真正失效时重登并回到 Scheduled Reports。 + """ + if _scheduled_reports_table_visible(page) and _CRANE_SCHEDULED_REPORTS_ROUTE in _current_url_fragment(page): + return + _recover_crane_session_on_scheduled_reports( + page, + entry_url, + env=env, + browser_timeout_ms=browser_timeout_ms, + ) + + +def _visible_locator(page: Any, selector: str) -> Any | None: + """在 page 与各 frame 中查找首个可见 locator。""" + for root in (page, *list(getattr(page, "frames", []))): + try: + locator = root.locator(selector).first + if locator.is_visible(timeout=500): + return locator + except Exception: + continue + return None + + +def _click_locator(locator: Any, *, browser_timeout_ms: int) -> bool: + try: + locator.click(timeout=browser_timeout_ms) + return True + except Exception: + pass + try: + locator.click(timeout=browser_timeout_ms, force=True) + return True + except Exception: + return False + + +def _click_first_visible( + page: Any, + *, + selector_env: str, + env: Callable[[str, str], str], + fallback_selectors: tuple[str, ...], + role_name: str | None = None, + browser_timeout_ms: int, +) -> bool: + """按环境变量 selector 与 fallback 点击首个可见控件。""" + selectors = tuple(item for item in (env(selector_env), *fallback_selectors) if item) + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is not None and _click_locator(locator, browser_timeout_ms=browser_timeout_ms): + print(f"[crane-export] clicked selector={selector!r}") + return True + + if role_name: + for root in (page, *list(getattr(page, "frames", []))): + try: + locator = root.get_by_role("button", name=role_name, exact=False).first + if locator.is_visible(timeout=500) and _click_locator(locator, browser_timeout_ms=browser_timeout_ms): + print(f"[crane-export] clicked role button name={role_name!r}") + return True + except Exception: + pass + try: + locator = root.get_by_role("link", name=role_name, exact=False).first + if locator.is_visible(timeout=500) and _click_locator(locator, browser_timeout_ms=browser_timeout_ms): + print(f"[crane-export] clicked role link name={role_name!r}") + return True + except Exception: + pass + return False + + +def _fill_crane_report_parameters( + page: Any, + source: dict[str, Any], + *, + env: Callable[[str, str], str], + 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 = str(item.get("selector_env") or "").strip() + 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 + + query = source.get("query") if isinstance(source.get("query"), dict) else {} + if query.get("owner_code"): + select_or_fill(page, "FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code")) + if query.get("project_code"): + select_or_fill(page, "FREIGHT_RPA_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code")) + + +def _click_run_report(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> None: + """点击表单底部 Run Report。""" + if _click_first_visible( + page, + selector_env="FREIGHT_RPA_CRANE_RUN_SELECTOR", + env=env, + fallback_selectors=_CRANE_RUN_REPORT_SELECTORS, + role_name="Run Report", + browser_timeout_ms=browser_timeout_ms, + ): + return + raise RuntimeError("Crane Run Report button not found") + + +def _click_schedule_report(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> None: + """点击右上角 Schedule Report(含 file_download 图标)。""" + if _click_first_visible( + page, + selector_env="FREIGHT_RPA_CRANE_SCHEDULE_REPORT_SELECTOR", + env=env, + fallback_selectors=_CRANE_SCHEDULE_REPORT_SELECTORS, + role_name="Schedule Report", + browser_timeout_ms=browser_timeout_ms, + ): + return + raise RuntimeError("Crane Schedule Report button not found") + + +def _schedule_description_hex_len(env: Callable[[str, str], str]) -> int: + """读取 Description 十六进制长度;默认 12,上限 32(完整 uuid4.hex)。""" + raw = str(env("FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN", "") or "").strip() + if not raw: + return _CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT + try: + length = int(raw) + except ValueError: + return _CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT + return max(8, min(length, _CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_MAX)) + + +def _build_schedule_description( + source: dict[str, Any], + trigger: dict[str, Any] | None, + *, + env: Callable[[str, str], str], +) -> str: + """ + 生成 Schedule Report 弹窗 Description,用于 Scheduled Reports 列表唯一识别。 + 核心逻辑:默认取 UUID4 前 12 位 hex(无连字符);可用 FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION 覆盖。 + """ + override = str(env("FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION", "") or "").strip() + if override: + return override[:120] + + hex_len = _schedule_description_hex_len(env) + return uuid.uuid4().hex[:hex_len] + + +def _wait_for_schedule_modal(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> Any | None: + """等待 Schedule Report 弹窗出现。""" + selectors = tuple( + item for item in (env("FREIGHT_RPA_CRANE_SCHEDULE_MODAL_SELECTOR"), *_CRANE_SCHEDULE_MODAL_SELECTORS) if item + ) + deadline = time.monotonic() + (min(browser_timeout_ms, 15_000) / 1000) + while time.monotonic() < deadline: + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is not None: + return locator + time.sleep(0.25) + return None + + +def _fill_schedule_description( + page: Any, + description: str, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> bool: + """在 Schedule Report 弹窗填写 Description。""" + text = str(description or "").strip() + if not text: + return False + + selectors = tuple( + item for item in (env("FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_SELECTOR"), *_CRANE_SCHEDULE_DESCRIPTION_SELECTORS) + if item + ) + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is not None: + try: + locator.fill(text, timeout=browser_timeout_ms) + print(f"[crane-export] filled schedule description via selector={selector!r}") + return True + except Exception: + pass + + for root in (page, *list(getattr(page, "frames", []))): + try: + locator = root.get_by_label("Description", exact=False).first + if locator.is_visible(timeout=500): + locator.fill(text, timeout=browser_timeout_ms) + print("[crane-export] filled schedule description via label") + return True + except Exception: + pass + return False + + +def _click_schedule_modal_ok(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool: + """点击 Schedule Report 弹窗 Ok 按钮。""" + selectors = tuple(item for item in (env("FREIGHT_RPA_CRANE_SCHEDULE_OK_SELECTOR"), *_CRANE_SCHEDULE_OK_SELECTORS) if item) + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is not None and _click_locator(locator, browser_timeout_ms=browser_timeout_ms): + print(f"[crane-export] clicked schedule modal Ok selector={selector!r}") + return True + + for root in (page, *list(getattr(page, "frames", []))): + try: + modal = root.locator("div.modal.is-active").first + if not modal.is_visible(timeout=500): + continue + locator = modal.get_by_role("button", name="Ok", exact=True).first + if locator.is_visible(timeout=500) and _click_locator(locator, browser_timeout_ms=browser_timeout_ms): + print("[crane-export] clicked schedule modal Ok via role") + return True + except Exception: + pass + return False + + +def _confirm_schedule_report_modal( + page: Any, + description: str, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> None: + """ + 处理 Schedule Report 弹窗:填写 Description → 点击 Ok。 + 核心逻辑:Description 非必填但用于 Scheduled Reports 列表唯一匹配下载项。 + """ + modal = _wait_for_schedule_modal(page, env=env, browser_timeout_ms=browser_timeout_ms) + if modal is None: + print("[crane-export] schedule modal not detected; continue without description", file=sys.stderr) + return + + if not _fill_schedule_description(page, description, env=env, browser_timeout_ms=browser_timeout_ms): + print( + f"[crane-export] failed to fill schedule description={description!r}; continuing", + file=sys.stderr, + ) + if not _click_schedule_modal_ok(page, env=env, browser_timeout_ms=browser_timeout_ms): + raise RuntimeError("Crane Schedule Report modal Ok button not found") + + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if _wait_for_schedule_modal(page, env=env, browser_timeout_ms=1_000) is None: + print(f"[crane-export] schedule modal closed description={description!r}") + return + time.sleep(0.2) + + +def _is_report_submission_status_visible(page: Any) -> bool: + """Ok 后底部是否仍显示 Report Creation Status / Report Submitted 提示。""" + for root in (page, *list(getattr(page, "frames", []))): + for text in _CRANE_REPORT_SUBMISSION_STATUS_TEXTS: + try: + if root.get_by_text(text, exact=False).first.is_visible(timeout=300): + return True + except Exception: + pass + return False + + +def _wait_for_report_submission_complete( + page: Any, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> None: + """ + 等待 Ok 后的 Report Submitted 等待态结束,再进入 Scheduled Reports。 + 核心逻辑:先等提示出现,再等提示消失(或超时后继续并打日志)。 + """ + total_ms = int(env("FREIGHT_RPA_CRANE_SUBMISSION_COMPLETE_WAIT_MS", "45000") or "45000") + appear_ms = min(30_000, total_ms) + deadline = time.monotonic() + (total_ms / 1000) + appear_deadline = time.monotonic() + (appear_ms / 1000) + seen = False + + while time.monotonic() < appear_deadline: + if _is_report_submission_status_visible(page): + seen = True + print("[crane-export] report submission status visible") + break + time.sleep(0.3) + + if not seen: + print("[crane-export] submission status toast not detected; brief settle wait", file=sys.stderr) + time.sleep(2.0) + return + + while time.monotonic() < deadline: + if not _is_report_submission_status_visible(page): + print("[crane-export] report submission status dismissed, ready for Scheduled Reports") + return + time.sleep(0.5) + + print( + "[crane-export] submission status still visible after timeout; proceeding to Scheduled Reports", + file=sys.stderr, + ) + + +def _current_url_fragment(page: Any) -> str: + """读取当前页 URL hash 片段(不含 #/ 前缀)。""" + try: + current_url = str(page.url or "") + except Exception: + return "" + parsed = urlparse(current_url) + return (parsed.fragment or "").strip().lstrip("/").lower() + + +def _is_on_scheduled_reports_page(page: Any) -> bool: + """ + 判定是否已在 Scheduled Reports 列表页。 + 核心逻辑:hash 含 scheduled-reports;表格已渲染则视为在列表页(reload 过渡态不误判)。 + """ + fragment = _current_url_fragment(page) + if not fragment or _CRANE_SCHEDULED_REPORTS_ROUTE not in fragment: + return False + if _scheduled_reports_table_visible(page): + return True + if _is_crane_login_blocking(page): + return False + return True + + +def _scheduled_reports_page_has_expected_table(page: Any) -> bool: + """ + Scheduled Reports 列表是否已渲染。 + 核心逻辑:Crane 表可能无 thead,仅检查标题或 tbody 行即可。 + """ + if _CRANE_SCHEDULED_REPORTS_ROUTE not in _current_url_fragment(page): + return False + if _scheduled_reports_table_visible(page): + return True + for root in (page, *list(getattr(page, "frames", []))): + try: + if root.get_by_text("Scheduled Reports", exact=False).first.is_visible(timeout=300): + return True + except Exception: + continue + return False + + +def _refresh_scheduled_reports_list( + page: Any, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, + entry_url: str, +) -> None: + """ + 从服务端重新拉取 Scheduled Reports 列表。 + 核心逻辑:goto 同一路由刷新数据;reload 后等表格就绪;表格在则不重登,避免闪回登录页。 + """ + fragment = _current_url_fragment(page) + on_route = _CRANE_SCHEDULED_REPORTS_ROUTE in fragment + if not on_route and not _scheduled_reports_table_visible(page): + return + if _is_crane_login_blocking(page): + _recover_crane_session_on_scheduled_reports( + page, + entry_url, + env=env, + browser_timeout_ms=browser_timeout_ms, + ) + return + + target = _scheduled_reports_url(page, env=env) + print("[crane-export] refreshing scheduled reports list from server", file=sys.stderr) + try: + page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms) + except Exception as exc: + print(f"[crane-export] scheduled reports goto refresh failed: {exc}; trying reload", file=sys.stderr) + try: + page.reload(wait_until="domcontentloaded", timeout=browser_timeout_ms) + except Exception as reload_exc: + print(f"[crane-export] scheduled reports reload failed: {reload_exc}", file=sys.stderr) + return + + if not _wait_for_scheduled_reports_list_ready(page, browser_timeout_ms=browser_timeout_ms): + if _is_crane_login_blocking(page): + _recover_crane_session_on_scheduled_reports( + page, + entry_url, + env=env, + browser_timeout_ms=browser_timeout_ms, + ) + + +def _probe_scheduled_download_status( + page: Any, + description: str, + *, + env: Callable[[str, str], str], + expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT, +) -> tuple[str | None, Any | None]: + """ + 查询目标行的当前 Download 列状态,并在可下载时返回链接 locator。 + 核心逻辑:每轮 poll 先读状态;status=Download 时返回 locator 供点击。 + """ + if not _is_on_scheduled_reports_page(page): + return None, None + + text = str(description or "").strip() + report_name = str(expected_report_name or _CRANE_SCHEDULED_REPORT_NAME_DEFAULT).strip() + if not text or not report_name: + return None, None + + table_selector = env("FREIGHT_RPA_CRANE_SCHEDULED_TABLE_SELECTOR") or _CRANE_SCHEDULED_TABLE_SELECTOR + max_rows = int(env("FREIGHT_RPA_CRANE_SCHEDULED_SCAN_MAX_ROWS", str(_CRANE_SCHEDULED_SCAN_MAX_ROWS_DEFAULT)) or "20") + + for root in (page, *list(getattr(page, "frames", []))): + try: + rows = root.locator(table_selector) + count = rows.count() + except Exception: + continue + + for index in range(min(count, max(1, max_rows))): + row = rows.nth(index) + try: + if not row.is_visible(timeout=300): + continue + except Exception: + continue + if not _row_matches_scheduled_report(row, description=text, expected_report_name=report_name): + continue + + submitted_at = _read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_SUBMITTED) + status = _read_scheduled_row_status(row) + status_lower = status.lower() + if status_lower == "failed": + raise RuntimeError(f"Crane scheduled report failed for description={text!r}") + if status_lower != "download": + return status or "Submitted", None + + for selector in ('a:has-text("Download")', 'td a', 'a'): + try: + locator = row.locator(selector).first + if locator.is_visible(timeout=500): + print( + f"[crane-export] row ready name={report_name!r} description={text!r} " + f"submitted={submitted_at!r} status={status!r}" + ) + return status, locator + except Exception: + pass + try: + locator = row.get_by_role("link", name="Download", exact=True).first + if locator.is_visible(timeout=500): + return status, locator + except Exception: + pass + return status, None + + return None, None + + +def _goto_scheduled_reports_hash(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> None: + """ + 通过 SPA hash 路由进入 Scheduled Reports。 + 核心逻辑:Run Report 后仍停在 on-hand-details-query 时,点击链接可能无效,需显式改 hash。 + """ + target = _scheduled_reports_url(page, env=env) + parsed = urlparse(target) + base_url = f"{parsed.scheme}://{parsed.netloc}/" + route = _CRANE_SCHEDULED_REPORTS_ROUTE + + print(f"[crane-export] navigating scheduled reports hash route={route!r}") + try: + current = str(page.url or "").lower() + except Exception: + current = "" + if "craneww.com" in current and not _is_crane_login_blocking(page): + page.evaluate( + """ + (route) => { + const hash = route.startsWith('/') ? route : `/${route}`; + if (window.location.hash !== `#${hash}`) { + window.location.hash = hash; + } + } + """, + route, + ) + page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms) + try: + page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 10_000)) + except Exception: + pass + return + + page.goto(base_url, wait_until="domcontentloaded", timeout=browser_timeout_ms) + page.evaluate( + """ + (route) => { + const hash = route.startsWith('/') ? route : `/${route}`; + if (window.location.hash !== `#${hash}`) { + window.location.hash = hash; + } + } + """, + route, + ) + page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms) + try: + page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 10_000)) + except Exception: + pass + + +def _scheduled_reports_url(page: Any, *, env: Callable[[str, str], str]) -> str: + """构造 Scheduled Reports 页面 URL(用于链接点击失败时 goto)。""" + override = str(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORTS_URL", "") or "").strip() + if override: + return override + try: + current = str(page.url or "").strip() + except Exception: + current = "" + if "://" in current: + base = current.split("#", 1)[0] + return f"{base}#/{_CRANE_SCHEDULED_REPORTS_ROUTE}" + return f"https://wms-portal.craneww.com/#/{_CRANE_SCHEDULED_REPORTS_ROUTE}" + + +def _open_scheduled_reports( + page: Any, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, + entry_url: str = "", +) -> None: + """ + 进入 Scheduled Reports 列表页。 + 核心逻辑:session 过期时先重登;优先点链接;未切换 hash 时用 SPA hash 赋值。 + """ + entry = entry_url or _default_crane_entry_url(None) + _ensure_crane_session_for_export(page, entry, env=env, browser_timeout_ms=browser_timeout_ms) + + if _is_on_scheduled_reports_page(page) and not _is_crane_login_blocking(page): + print("[crane-export] already on scheduled-reports route") + return + + if _scheduled_reports_page_has_expected_table(page): + print("[crane-export] already on scheduled reports page") + return + + if _click_first_visible( + page, + selector_env="FREIGHT_RPA_CRANE_SCHEDULED_REPORTS_SELECTOR", + env=env, + fallback_selectors=_CRANE_SCHEDULED_REPORTS_LINK_SELECTORS, + role_name="Scheduled Reports", + browser_timeout_ms=browser_timeout_ms, + ): + page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms) + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if _is_on_scheduled_reports_page(page): + break + time.sleep(0.25) + if _is_on_scheduled_reports_page(page): + return + + target = _scheduled_reports_url(page, env=env) + print(f"[crane-export] fallback goto scheduled reports url={target!r}") + page.goto(target, wait_until="domcontentloaded", timeout=browser_timeout_ms) + if _is_on_scheduled_reports_page(page): + return + + _goto_scheduled_reports_hash(page, env=env, browser_timeout_ms=browser_timeout_ms) + if not _is_on_scheduled_reports_page(page): + raise RuntimeError( + "Crane scheduled reports navigation failed: still not on scheduled-reports route " + f"(url={page.url!r})" + ) + + +def _read_scheduled_row_cell(row: Any, column_index: int) -> str: + """读取 Scheduled Reports 行指定列文本(Name/Submitted/Description/Download)。""" + try: + cells = row.locator("td") + if cells.count() <= column_index: + return "" + return str(cells.nth(column_index).inner_text(timeout=300) or "").strip() + except Exception: + return "" + + +def _read_scheduled_row_status(row: Any) -> str: + """读取 Scheduled Reports 行 Download 列状态文本(Submitted / Download / Failed)。""" + return _read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_DOWNLOAD) + + +def _resolve_scheduled_report_file_name( + source: dict[str, Any] | None, + *, + env: Callable[[str, str], str], +) -> str: + """ + 解析 Scheduled Reports 目标文件名(Name 列)。 + 核心逻辑:source.navigation.scheduled_report_file_name → 环境变量 → 默认 OnHandDetails.xlsx。 + """ + navigation = source.get("navigation") if isinstance(source, dict) and isinstance(source.get("navigation"), dict) else {} + configured = str( + navigation.get("scheduled_report_file_name") or navigation.get("scheduled_report_name") or "" + ).strip() + if configured: + return configured + env_value = str(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_NAME", _CRANE_SCHEDULED_REPORT_NAME_DEFAULT) or "").strip() + return env_value or _CRANE_SCHEDULED_REPORT_NAME_DEFAULT + + +def _row_matches_scheduled_report( + row: Any, + *, + description: str, + expected_report_name: str, +) -> bool: + """ + 判断行是否为目标导出:Name 精确匹配且 Description 为本次 UUID。 + 核心逻辑:表按 Submitted 降序,自上而下取首条匹配即最近一笔。 + """ + wanted_name = str(expected_report_name or "").strip() + wanted_description = str(description or "").strip() + if not wanted_name or not wanted_description: + return False + + name = _read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_NAME) + if name != wanted_name: + return False + + row_description = _read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_DESCRIPTION) + return row_description == wanted_description + + +def _find_scheduled_download_by_description( + page: Any, + description: str, + *, + env: Callable[[str, str], str], + expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT, +) -> Any | None: + """ + 在 Scheduled Reports 表中定位可点击的 Download 链接。 + 核心逻辑:委托 _probe_scheduled_download_status,仅 status=Download 时返回 locator。 + """ + _status, locator = _probe_scheduled_download_status( + page, + description, + env=env, + expected_report_name=expected_report_name, + ) + return locator + + +def _is_scheduled_download_ready( + page: Any, + *, + env: Callable[[str, str], str], + description: str = "", + expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT, +) -> Any | None: + """在 Scheduled Reports 列表中查找可点击的 Download;须 Name+Description 匹配且状态为 Download。""" + if not description: + return None + return _find_scheduled_download_by_description( + page, + description, + env=env, + expected_report_name=expected_report_name, + ) + + +def _wait_and_click_scheduled_download( + page: Any, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, + description: str = "", + expected_report_name: str = _CRANE_SCHEDULED_REPORT_NAME_DEFAULT, + entry_url: str = "", +) -> Any: + """ + 轮询 Scheduled Reports 直至目标行 Download 列由 Submitted 变为 Download 并点击。 + 核心逻辑:每 2s 读一次状态;每 10s goto 刷新列表;表格可见时不重登,避免闪回登录页。 + """ + entry = entry_url or _default_crane_entry_url(None) + wait_ms = int(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_WAIT_MS", "300000") or "300000") + deadline = time.monotonic() + (wait_ms / 1000) + poll_seconds = float(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_POLL_SECONDS", "2") or "2") + list_refresh_seconds = float( + env( + "FREIGHT_RPA_CRANE_SCHEDULED_REPORT_LIST_REFRESH_SECONDS", + env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_SOFT_REFRESH_SECONDS", "10") or "10", + ) + or "10" + ) + wait_started = time.monotonic() + last_list_refresh = time.monotonic() + poll_index = 0 + last_status = "not_found" + + while time.monotonic() < deadline: + poll_index += 1 + loop_started = time.monotonic() + + if _is_crane_login_blocking(page) or not _is_on_scheduled_reports_page(page): + try: + _recover_crane_session_on_scheduled_reports( + page, + entry, + env=env, + browser_timeout_ms=browser_timeout_ms, + ) + except RuntimeError: + raise + if not _is_on_scheduled_reports_page(page): + try: + _open_scheduled_reports( + page, + env=env, + browser_timeout_ms=browser_timeout_ms, + entry_url=entry, + ) + except Exception as exc: + print(f"[crane-export] reopen scheduled reports failed: {exc}", file=sys.stderr) + last_list_refresh = time.monotonic() + + # [STEP] 每 N 秒刷新列表拉服务端最新状态,再读 Download 列 + if time.monotonic() - last_list_refresh >= list_refresh_seconds: + _refresh_scheduled_reports_list( + page, + env=env, + browser_timeout_ms=browser_timeout_ms, + entry_url=entry, + ) + last_list_refresh = time.monotonic() + + current_status, locator = _probe_scheduled_download_status( + page, + description, + env=env, + expected_report_name=expected_report_name, + ) + if current_status: + last_status = current_status + + if locator is not None: + remaining_ms = max(int((deadline - time.monotonic()) * 1000), 5_000) + click_timeout = min(browser_timeout_ms, remaining_ms) + elapsed = int(time.monotonic() - wait_started) + print( + f"[crane-export] clicking download link name={expected_report_name!r} " + f"description={description!r} status={last_status!r} after~{elapsed}s polls={poll_index}", + file=sys.stderr, + ) + with page.expect_download(timeout=click_timeout) as download_info: + if not _click_locator(locator, browser_timeout_ms=click_timeout): + raise RuntimeError( + f"Crane scheduled report Download link click failed for description={description!r}" + ) + print( + f"[crane-export] download started name={expected_report_name!r} description={description!r}" + ) + return download_info.value + + loop_elapsed_ms = int((time.monotonic() - loop_started) * 1000) + remaining = int(deadline - time.monotonic()) + total_elapsed = int(time.monotonic() - wait_started) + print( + f"[crane-export] poll#{poll_index} elapsed={total_elapsed}s status={last_status!r} " + f"loop={loop_elapsed_ms}ms next_sleep={max(poll_seconds, 1.0)}s remaining~{max(remaining, 0)}s", + file=sys.stderr, + ) + time.sleep(max(poll_seconds, 1.0)) + + raise RuntimeError( + f"Crane scheduled report not ready for download within {wait_ms}ms; " + f"description={description!r}" + ) + + +def _wait_for_run_report_results( + page: Any, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> None: + """ + 等待 Run Report 内联查询完成后再 Schedule。 + 核心逻辑:页面出现「items found」或结果表首行数据即视为 Run 完成;超时后打日志并继续尝试 Schedule。 + """ + wait_ms = int(env("FREIGHT_RPA_CRANE_RUN_REPORT_WAIT_MS", "180000") or "180000") + deadline = time.monotonic() + (wait_ms / 1000) + + while time.monotonic() < deadline: + for root in (page, *list(getattr(page, "frames", []))): + try: + if root.get_by_text("items found", exact=False).first.is_visible(timeout=500): + print("[crane-export] run report finished: items found visible") + return + except Exception: + pass + try: + rows = root.locator("table.table.is-fullwidth tbody tr") + if rows.count() > 0 and rows.first.is_visible(timeout=500): + print("[crane-export] run report finished: result table has rows") + return + except Exception: + pass + time.sleep(0.5) + + print( + "[crane-export] run report results not detected before timeout; proceeding to Schedule Report", + file=sys.stderr, + ) + + +def _should_run_report_before_schedule( + source: dict[str, Any], + *, + env: Callable[[str, str], str], +) -> bool: + """ + scheduled_report 模式是否先点 Run Report。 + 核心逻辑:默认 True(Crane 须先 Run 才有可 Schedule 的查询结果);仅显式配置可关闭。 + """ + navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {} + if navigation.get("run_before_schedule") is False: + return False + return str(env("FREIGHT_RPA_CRANE_RUN_BEFORE_SCHEDULE", "true") or "true").lower() != "false" + + +def export_crane_inventory_report( + page: Any, + source: dict[str, Any], + *, + trigger: dict[str, Any] | None = None, + env: Callable[[str, str], str], + browser_timeout_ms: int, + select_or_fill: Callable[..., None], + click_text: Callable[..., None], +) -> Any: + """ + 导出 Crane 库存报表。 + 核心逻辑:Run Report(等待结果)→ Schedule Report(填 Description)→ Scheduled Reports 按 Description 下载。 + + Args: + page: Playwright 页面。 + source: rpa_inventory_source 配置。 + env: 环境变量读取函数。 + browser_timeout_ms: 浏览器操作超时。 + select_or_fill: worker 提供的下拉/输入填充函数。 + click_text: worker 提供的文本点击函数(file_download 直出模式备用)。 + trigger: inventory_export / batch trigger,用于生成唯一 Description。 + + Returns: + Playwright Download 对象。 + """ + download_mode = _resolve_download_mode(source) + entry_url = _default_crane_entry_url(source) + schedule_description = _build_schedule_description(source, trigger, env=env) + scheduled_report_name = _resolve_scheduled_report_file_name(source, env=env) + _fill_crane_report_parameters( + page, + source, + env=env, + browser_timeout_ms=browser_timeout_ms, + select_or_fill=select_or_fill, + ) + + if download_mode == "file_download": + _click_run_report(page, env=env, browser_timeout_ms=browser_timeout_ms) + export_selector = env("FREIGHT_RPA_CRANE_EXPORT_SELECTOR") + with page.expect_download(timeout=browser_timeout_ms) as download_info: + if export_selector: + page.locator(export_selector).first.click(timeout=browser_timeout_ms) + else: + click_text(page, env("FREIGHT_RPA_CRANE_EXPORT_TEXT", "file_download"), exact=True) + return download_info.value + + # [STEP 1] Run Report:须先产出查询结果,再 Schedule 异步导出 + if _should_run_report_before_schedule(source, env=env): + _click_run_report(page, env=env, browser_timeout_ms=browser_timeout_ms) + _wait_for_run_report_results(page, env=env, browser_timeout_ms=browser_timeout_ms) + else: + print("[crane-export] run_before_schedule disabled; scheduling without inline Run Report", file=sys.stderr) + + # [STEP 2] Schedule Report → 弹窗填写 Description → Ok + _click_schedule_report(page, env=env, browser_timeout_ms=browser_timeout_ms) + _confirm_schedule_report_modal( + page, + schedule_description, + env=env, + browser_timeout_ms=browser_timeout_ms, + ) + _wait_for_report_submission_complete(page, env=env, browser_timeout_ms=browser_timeout_ms) + + # [STEP 3] Scheduled Reports → Name+Description 匹配首行,等待 Submitted→Download 并下载 + _open_scheduled_reports( + page, + env=env, + browser_timeout_ms=browser_timeout_ms, + entry_url=entry_url, + ) + wait_ms = int(env("FREIGHT_RPA_CRANE_SCHEDULED_REPORT_WAIT_MS", "300000") or "300000") + return _wait_and_click_scheduled_download( + page, + env=env, + browser_timeout_ms=browser_timeout_ms, + description=schedule_description, + expected_report_name=scheduled_report_name, + entry_url=entry_url, + ) + + +def _resolve_download_mode(source: dict[str, Any]) -> str: + """从 source.navigation.download_mode 读取导出模式,默认 scheduled_report。""" + navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {} + mode = str(navigation.get("download_mode") or "scheduled_report").strip().lower() + return mode diff --git a/scripts/rpa/crane_session.py b/scripts/rpa/crane_session.py new file mode 100644 index 00000000..9b404a1a --- /dev/null +++ b/scripts/rpa/crane_session.py @@ -0,0 +1,382 @@ +""" +scripts/rpa/crane_session.py + +用途:Crane AWS FootPrint Portal 登录、报表导航与 session 检测。 +依赖:Playwright Page、crane_navigation;由 freight_rpa_worker._ensure_crane_session 委托调用。 +逻辑:识别登录页并自动填写;登录后委托 navigate_to_crane_report 进入 On Hand Details Query。 +""" + +from __future__ import annotations + +import sys +import time +from typing import Any, Callable +from urllib.parse import urlparse + +# Crane FootPrint 登录页(Bulma 表单)实测控件;用户名无 name 属性,靠 placeholder/label 定位。 +_CRANE_USERNAME_SELECTORS: tuple[str, ...] = ( + 'input[placeholder="Enter user name..."]', + 'input[placeholder*="user name" i]', + 'form input.input[type="text"]', + 'input[name="userName"]', + 'input[name="username"]', +) + +_CRANE_PASSWORD_SELECTORS: tuple[str, ...] = ( + 'input[placeholder="Enter password..."]', + 'input.input.is-small.p-2.mt-1[type="password"]', + 'input[placeholder*="password" i]', + 'form input.input[type="password"]', + 'input[type="password"]', +) + +_CRANE_LOGIN_SUBMIT_SELECTORS: tuple[str, ...] = ( + 'button.button.is-primary:has-text("Sign in")', + 'form button.button.is-primary', + 'button.button.is-primary', +) + +_CRANE_LOGIN_SUBMIT_TEXTS: tuple[str, ...] = ("Sign in", "Login", "Log in", "登录") + + +def _load_crane_navigation_module() -> Any: + """运行时加载 crane_navigation,避免与 crane_session 循环 import。""" + import importlib.util + from pathlib import Path + + module_path = Path(__file__).resolve().parent / "crane_navigation.py" + spec = importlib.util.spec_from_file_location("crane_navigation_runtime", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _visible_locator(page: Any, selector: str) -> Any | None: + """在 page 与各 frame 中查找首个可见 locator。""" + for root in (page, *list(getattr(page, "frames", []))): + try: + locator = root.locator(selector).first + if locator.is_visible(timeout=500): + return locator + except Exception: + continue + return None + + +def _dispatch_input_events(locator: Any) -> None: + """触发 input/change 事件,驱动 Vue 表单解除 Sign in 按钮 disabled。""" + try: + locator.evaluate( + """ + (node) => { + node.dispatchEvent(new Event('input', { bubbles: true })); + node.dispatchEvent(new Event('change', { bubbles: true })); + } + """ + ) + except Exception: + pass + + +def _fill_visible_locator(locator: Any, value: str, *, browser_timeout_ms: int) -> bool: + """向已定位控件写入文本,并触发前端校验以启用 Sign in。""" + try: + locator.fill(value, timeout=browser_timeout_ms) + _dispatch_input_events(locator) + return True + except Exception: + pass + try: + locator.click(timeout=3_000) + locator.press("Control+A") + locator.press("Backspace") + locator.type(value, delay=30) + _dispatch_input_events(locator) + return True + except Exception: + return False + + +def _is_crane_button_enabled(locator: Any) -> bool: + """Sign in 初始为 disabled,需等用户名/密码填写后解除。""" + try: + return bool( + locator.evaluate( + """ + (node) => { + if (!node) return false; + const disabled = Boolean(node.disabled); + const ariaDisabled = String(node.getAttribute('aria-disabled') || '').toLowerCase() === 'true'; + const classDisabled = node.classList && node.classList.contains('is-disabled'); + return !disabled && !ariaDisabled && !classDisabled; + } + """ + ) + ) + except Exception: + pass + try: + return locator.is_enabled(timeout=500) + except Exception: + return False + + +def _find_crane_sign_in_button( + page: Any, + *, + selector_env: str, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> Any | None: + """ + 查找已启用的 Sign in 按钮。 + 核心逻辑:页面按钮 class 为 button is-primary,填写凭据前带 disabled 属性。 + """ + selectors = tuple( + item + for item in (env(selector_env), *_CRANE_LOGIN_SUBMIT_SELECTORS, 'button[type="submit"]') + if item + ) + deadline = time.monotonic() + (browser_timeout_ms / 1000) + + while time.monotonic() < deadline: + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is not None and _is_crane_button_enabled(locator): + return locator + + for root in (page, *list(getattr(page, "frames", []))): + for text in _CRANE_LOGIN_SUBMIT_TEXTS: + try: + locator = root.get_by_role("button", name=text, exact=False).first + if locator.is_visible(timeout=500) and _is_crane_button_enabled(locator): + return locator + except Exception: + pass + time.sleep(0.25) + + # 最后再试一次可见按钮(部分环境 disabled 属性更新滞后,但 click 仍有效) + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is not None: + return locator + return None + + +def _fill_crane_field( + page: Any, + *, + selector_env: str, + value: str, + env: Callable[[str, str], str], + browser_timeout_ms: int, + fallback_selectors: tuple[str, ...], + label: str | None = None, + placeholder: str | None = None, +) -> bool: + """ + 填写 Crane 登录字段。 + 核心逻辑:优先环境变量 selector,再试页面实测 fallback,最后用 label/placeholder 语义定位。 + """ + text = str(value or "").strip() + if not text: + return False + + selectors = tuple(item for item in (env(selector_env), *fallback_selectors) if item) + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is not None and _fill_visible_locator(locator, text, browser_timeout_ms=browser_timeout_ms): + print(f"[crane-login] filled field via selector={selector!r}") + return True + + for root in (page, *list(getattr(page, "frames", []))): + if label: + try: + locator = root.get_by_label(label, exact=False).first + if locator.is_visible(timeout=500) and _fill_visible_locator( + locator, text, browser_timeout_ms=browser_timeout_ms + ): + print(f"[crane-login] filled field via label={label!r}") + return True + except Exception: + pass + if placeholder: + try: + locator = root.get_by_placeholder(placeholder, exact=False).first + if locator.is_visible(timeout=500) and _fill_visible_locator( + locator, text, browser_timeout_ms=browser_timeout_ms + ): + print(f"[crane-login] filled field via placeholder={placeholder!r}") + return True + except Exception: + pass + return False + + +def _click_crane_login_submit( + page: Any, + *, + selector_env: str, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> bool: + """ + 点击 Crane Sign in 按钮。 + 核心逻辑:等待 button.button.is-primary 解除 disabled 后再点击。 + """ + locator = _find_crane_sign_in_button( + page, + selector_env=selector_env, + env=env, + browser_timeout_ms=min(browser_timeout_ms, 15_000), + ) + if locator is None: + return False + + try: + locator.click(timeout=browser_timeout_ms) + return True + except Exception: + pass + try: + locator.click(timeout=browser_timeout_ms, force=True) + return True + except Exception: + return False + + +def is_crane_login_page(page: Any) -> bool: + """当前页是否为 Crane FootPrint 登录表单。""" + for selector in ( + 'input[placeholder="Enter user name..."]', + 'input[placeholder="Enter password..."]', + ): + if _visible_locator(page, selector) is not None: + return True + for root in (page, *list(getattr(page, "frames", []))): + try: + if root.get_by_label("User Name", exact=False).first.is_visible(timeout=500): + return True + except Exception: + pass + return False + + +def _crane_entry_host(entry_url: str) -> str: + """从 entry_url 提取 host。""" + parsed = urlparse(str(entry_url or "").strip()) + return (parsed.netloc or "").lower() + + +def is_crane_session_active(page: Any, entry_url: str) -> bool: + """ + 判定浏览器是否已在 Crane portal 维持有效登录态。 + 核心逻辑:仍在 craneww 域且不再显示登录表单,即视为 session 有效。 + """ + host = _crane_entry_host(entry_url) + if not host: + return False + try: + current_url = str(page.url or "").lower() + except Exception: + return False + if host not in current_url: + return False + if is_crane_login_page(page): + return False + return True + + +def wait_for_crane_app_ready( + page: Any, + entry_url: str, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> None: + """ + 登录后导航并等待 Crane 报表表单就绪。 + 核心逻辑:先 navigate_to_crane_report(首页卡片 → 顶部菜单 → goto),再轮询表单控件。 + """ + navigation = _load_crane_navigation_module() + mode = navigation.navigate_to_crane_report( + page, + entry_url, + env=env, + browser_timeout_ms=browser_timeout_ms, + ) + print(f"[crane-nav] navigation mode={mode!r}") + + deadline = time.monotonic() + (browser_timeout_ms / 1000) + while time.monotonic() < deadline: + if navigation.is_crane_report_form_ready(page, entry_url): + print("[crane-login] report form ready") + return + time.sleep(0.5) + + raise RuntimeError("Crane report form did not become ready after navigation; check selectors or permissions") + + +def maybe_auto_login_crane( + page: Any, + *, + env: Callable[[str, str], str], + browser_timeout_ms: int, +) -> None: + """ + Crane FootPrint 自动登录:User Name → Password → Sign in。 + 核心逻辑:页面无登录框则跳过;填写后等待离开登录页并进入报表路由。 + """ + username = env("FREIGHT_RPA_CRANE_USERNAME") + password = env("FREIGHT_RPA_CRANE_PASSWORD") + if not username or not password: + return + + if not is_crane_login_page(page): + print("[crane-login] no login form detected, skip auto login") + return + + user_filled = _fill_crane_field( + page, + selector_env="FREIGHT_RPA_CRANE_USERNAME_SELECTOR", + value=username, + env=env, + browser_timeout_ms=browser_timeout_ms, + fallback_selectors=_CRANE_USERNAME_SELECTORS, + label="User Name", + placeholder="Enter user name...", + ) + password_filled = _fill_crane_field( + page, + selector_env="FREIGHT_RPA_CRANE_PASSWORD_SELECTOR", + value=password, + env=env, + browser_timeout_ms=browser_timeout_ms, + fallback_selectors=_CRANE_PASSWORD_SELECTORS, + label="Password", + placeholder="Enter password...", + ) + if not user_filled and not password_filled: + print("[crane-login] login form visible but fields not filled", file=sys.stderr) + return + if user_filled != password_filled: + raise RuntimeError("CRANE login form partially detected; please configure login selectors") + + if not _click_crane_login_submit( + page, + selector_env="FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR", + env=env, + browser_timeout_ms=browser_timeout_ms, + ): + raise RuntimeError("CRANE login fields detected but Sign in button was not found") + + page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms) + if is_crane_login_page(page): + raise RuntimeError("CRANE login did not complete; MFA/SSO/manual verification may be required") + + # [STEP] 登录后 Crane 常先落到 /#/ 首页,等待 SPA 壳层渲染再进入报表导航 + try: + page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 15_000)) + except Exception: + pass diff --git a/scripts/rpa/dsv_auth.py b/scripts/rpa/dsv_auth.py new file mode 100644 index 00000000..f6767c23 --- /dev/null +++ b/scripts/rpa/dsv_auth.py @@ -0,0 +1,993 @@ +""" +scripts/rpa/dsv_auth.py + +用途:DSV 360 PingID 分步登录(邮箱 → 密码方式 → 密码 → portal)。 +依赖:rpa_common、dsv_debug;登录主编排见 dsv_auth_login_flow。 +逻辑:由 dsv_session / dsv_report_export 在 ensure session 时调用 maybe_auto_login_dsv。 +""" + +from __future__ import annotations + +import sys +import time +from typing import Any, Callable + +from rpa_common import browser_timeout_ms as _browser_timeout_ms +from rpa_common import env as _env +from rpa_common import fill_first_visible_text_input as _fill_first_visible_text_input +from rpa_common import wait_for_visible_selector as _wait_for_visible_selector +from dsv_debug import ( + collect_dsv_reports_probe as _collect_dsv_reports_probe, + debug_dsv_stage as _debug_dsv_stage, + report_debug_event as _report_debug_event, + report_dsv_chain_stage as _report_dsv_chain_stage, +) + + +def _click_dsv_password_method(page: Any) -> bool: + def password_ready() -> bool: + """密码输入框已出现即视为方法页切换成功;兼容轻量探测与通用等待。""" + if _find_dsv_password_locator(page, timeout_ms=250) is not None: + return True + return _wait_for_visible_selector( + page, + "FREIGHT_RPA_DSV_PASSWORD_SELECTOR", + ("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'), + timeout_ms=250, + ) is not None + + def transition_confirmed() -> bool: + deadline = time.monotonic() + 4 + while time.monotonic() < deadline: + if password_ready(): + return True + if not _looks_like_dsv_login_method_page(page): + try: + body_text = page.locator("body").inner_text(timeout=1_000) + except Exception: + body_text = "" + lowered = body_text.lower() + looks_like_password_page = ( + ("输入您的密码" in body_text or "忘记密码" in body_text or "password" in lowered) + and "通行密钥" not in body_text + and "passkey" not in lowered + and "验证失败" not in body_text + and "validation failed" not in lowered + ) + if looks_like_password_page: + time.sleep(0.3) + continue + return False + time.sleep(0.3) + return False + + script_row_click = """ + () => { + const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim(); + const isVisible = (node) => { + const rect = node.getBoundingClientRect(); + const style = window.getComputedStyle(node); + return !(style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0); + }; + const isPasswordMethod = (text) => ( + (text === '密码' || text === 'Password' || text === '输入您的密码并登录。' || text.includes('输入您的密码并登录')) + && !text.includes('忘记密码') + && !text.includes('取消') + && !text.includes('返回') + && !text.includes('通行密钥') + && !text.includes('电子邮件验证码') + && !text.includes('移动应用程序') + && !text.toLowerCase().includes('cancel') + && !text.toLowerCase().includes('back') + && !text.toLowerCase().includes('passkey') + ); + const rows = Array.from(document.querySelectorAll("form[name='mfaForm'] li.mb-2, form[name='mfaForm'] .mb-2, .device-list li.mb-2, .device-list .mb-2")) + .filter((node) => isVisible(node)); + const row = rows.find((node) => isPasswordMethod(textOf(node))); + if (!row) return false; + const target = row.querySelector('.device-continue, button, a, [role="button"], input[type="submit"]') || row; + target.scrollIntoView({ block: 'center', inline: 'center' }); + if (target.tagName === 'FORM') { + if (typeof target.requestSubmit === 'function') target.requestSubmit(); + else target.submit(); + return true; + } + if (typeof target.click === 'function') target.click(); + for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) { + target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window })); + } + return true; + } + """ + for frame in page.frames: + try: + _clicked = frame.evaluate(script_row_click) + if _clicked and transition_confirmed(): + return True + except Exception: + pass + + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + try: + rows = page.locator("form[name='mfaForm'] li.mb-2").all() + for row in rows: + text = row.inner_text(timeout=1_000) + lowered = text.lower() + if ("密码" in text or "Password" in text) and "忘记密码" not in text and "取消" not in text and "返回" not in text and "cancel" not in lowered and "back" not in lowered: + row.scroll_into_view_if_needed(timeout=3_000) + try: + row.click(timeout=3_000, force=True) + except Exception: + row.evaluate( + """ + (node) => { + if (typeof node.click === 'function') node.click(); + node.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); + } + """, + timeout=2_000, + ) + if transition_confirmed(): + return True + except Exception: + pass + time.sleep(0.5) + return False + + +def _submit_dsv_username_form(username_locator: Any) -> bool: + try: + return bool( + username_locator.evaluate( + """ + (node) => { + const form = node.closest('form'); + if (!form) return false; + if (typeof form.requestSubmit === 'function') { + form.requestSubmit(); + } else { + form.submit(); + } + return true; + } + """, + timeout=2_000, + ) + ) + except Exception: + return False + + +def _click_dsv_continue(page: Any, username_locator: Any | None = None) -> bool: + if username_locator is not None: + if _submit_dsv_username_form(username_locator): + return True + try: + username_locator.press("Enter", timeout=3_000) + return True + except Exception: + pass + for selector in ( + 'button:has-text("继续")', + 'button:has-text("Continue")', + 'input[value="继续"]', + 'input[value="Continue"]', + '[role="button"]:has-text("继续")', + '[role="button"]:has-text("Continue")', + 'a:has-text("继续")', + 'a:has-text("Continue")', + '.dbs-sims-button-primary', + 'button[type="submit"]', + 'input[type="submit"]', + ): + for frame in page.frames: + try: + locator = frame.locator(selector).first + locator.wait_for(state="attached", timeout=1_000) + try: + locator.click(timeout=1_000) + except Exception: + locator.click(timeout=1_000, force=True) + return True + except Exception: + pass + for frame in page.frames: + try: + identifier = frame.locator("input#identifier").first + identifier.wait_for(state="attached", timeout=1_000) + identifier.press("Enter", timeout=3_000) + return True + except Exception: + pass + script = """ + () => { + const candidates = Array.from(document.querySelectorAll('body *')).filter((node) => { + const style = window.getComputedStyle(node); + const rect = node.getBoundingClientRect(); + return style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0; + }); + const label = candidates.find((node) => { + const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim(); + return text === '继续' || text === 'Continue' || text.includes('继续') || text.includes('Continue'); + }); + const target = label && (label.closest('button, input, a, [role="button"], .dbs-sims-button-primary, [onclick], form') || label); + if (!target) return false; + target.scrollIntoView({ block: 'center', inline: 'center' }); + if (target.tagName === 'FORM') { + if (typeof target.requestSubmit === 'function') target.requestSubmit(); + else target.submit(); + return true; + } + for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) { + target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window })); + } + return true; + } + """ + for frame in page.frames: + try: + if frame.evaluate(script): + return True + except Exception: + pass + return False + + +def _dsv_locator_can_edit(locator: Any) -> bool: + try: + if locator.is_editable(timeout=1_000): + return True + except Exception: + pass + try: + return bool( + locator.evaluate( + "(node) => !node.disabled && !node.readOnly && node.getAttribute('aria-disabled') !== 'true'", + timeout=1_000, + ) + ) + except Exception: + return False + + +def _dsv_username_has_value(locator: Any) -> bool: + for _ in range(5): + try: + if locator.input_value(timeout=1_000).strip(): + return True + except Exception: + pass + time.sleep(0.2) + return False + + +_DSV_MAYBE_LATER_SELECTORS: tuple[str, ...] = ( + 'button.dbs-sims-button-secondary:has-text("也许以后")', + 'button.dbs-sims-button-secondary:has-text("Maybe later")', + 'button.dbs-sims-button-secondary:has-text("Maybe Later")', + 'button.dbs-sims-button-secondary:has-text("Not now")', + 'button.dbs-sims-button-secondary:has-text("Not Now")', + 'button:has-text("也许以后")', + 'a:has-text("也许以后")', + '[role="button"]:has-text("也许以后")', + 'text=也许以后', + 'button:has-text("Maybe later")', + 'button:has-text("Maybe Later")', + 'a:has-text("Maybe later")', + 'a:has-text("Maybe Later")', + '[role="button"]:has-text("Maybe later")', + '[role="button"]:has-text("Maybe Later")', + 'text=Maybe later', + 'text=Maybe Later', + 'button:has-text("Not now")', + 'button:has-text("Not Now")', + 'a:has-text("Not now")', + 'a:has-text("Not Now")', + 'text=Not now', + 'text=Not Now', +) + +_DSV_PASSWORD_UPGRADE_PROMPT_MARKERS: tuple[str, ...] = ( + "使用密码升级登录", + "升级登录", + "password upgrade", + "upgrade your sign-in", + "sign in with a passkey", + "passkey", +) + + +def _dsv_maybe_later_selector_candidates() -> tuple[str, ...]: + """返回“也许以后 / Maybe later”按钮候选选择器;支持 FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR 覆盖。""" + selector = _env("FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR") + return (selector,) if selector else _DSV_MAYBE_LATER_SELECTORS + + +def _is_dsv_password_upgrade_redirect(page: Any) -> bool: + """ + 判断是否处在点击登录后的密码升级提示地址。 + + 核心逻辑:只有 `auth.dbschenker.com/.../resume/as/authorization.ping` 才需要点击 + “也许以后”;如果登录直接进入 s360 portal,则不做升级提示处理。 + """ + try: + current_url = str(page.url or "").lower() + except Exception: + return False + return "auth.dbschenker.com" in current_url and "/resume/as/authorization.ping" in current_url + + +def _portal_home_nav_already_usable(page: Any) -> bool: + """ + 判断 s360 portal 首页导航是否已可操作。 + + 核心逻辑:仅在 Reports 顶栏已可用时,才跳过升级提示扫描,避免把“弹窗挡住的 portal 页” + 误判为“首页已稳定”。 + """ + current_url = str(getattr(page, "url", "") or "").lower() + if "s360.dbschenker.com" not in current_url or "auth.dbschenker.com" in current_url: + return False + try: + import dsv_session + + return bool(dsv_session.has_dsv_report_nav_usable(page)) + except Exception: + return False + + +def _try_click_dsv_maybe_later_via_js(root: Any) -> bool: + """ + 通过 innerText 匹配点击“也许以后 / Maybe later”按钮。 + + 核心逻辑:Playwright 选择器未命中时(class 变更、文本大小写差异),用 JS 兜底点击 + secondary 按钮,并显式跳过“立即启用 / Enable now”主按钮。 + """ + script = """ + () => { + const labels = ['也许以后', 'maybe later', 'not now']; + const skipLabels = ['立即启用', 'enable now']; + const isVisible = (node) => { + if (!node) return false; + const style = window.getComputedStyle(node); + if (style.visibility === 'hidden' || style.display === 'none') return false; + const rect = node.getBoundingClientRect(); + return rect.width > 0 && rect.height > 0; + }; + const nodes = Array.from(document.querySelectorAll('button, a, [role="button"], .dbs-sims-button-secondary, .dbs-sims-button')); + for (const node of nodes) { + if (!isVisible(node)) continue; + const text = ((node.innerText || node.textContent || '') + '').replace(/\\s+/g, ' ').trim(); + const lowered = text.toLowerCase(); + if (skipLabels.some((label) => lowered.includes(label))) continue; + if (!labels.some((label) => lowered.includes(label))) continue; + node.scrollIntoView({ block: 'center', inline: 'center' }); + if (typeof node.click === 'function') node.click(); + node.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); + return true; + } + return false; + } + """ + try: + return bool(root.evaluate(script, timeout=2_000)) + except Exception: + return False + + +def _has_dsv_password_upgrade_prompt(page: Any, timeout_ms: int = 250) -> bool: + """ + 快速判断 DSV 是否真的出现“也许以后 / Maybe later”升级提示。 + + 核心逻辑:仅检查升级提示的强特征,不把 Verifying compliance 或普通 auth 跳转页 + 误判成升级提示;portal 首页导航已可用时才跳过扫描,弹窗挡屏时仍会继续探测。 + """ + if not _is_dsv_password_upgrade_redirect(page): + return False + if _portal_home_nav_already_usable(page): + return False + candidates = _dsv_maybe_later_selector_candidates() + roots = [page, *getattr(page, "frames", [])] + for root in roots: + for candidate in candidates: + try: + if root.locator(candidate).first.is_visible(timeout=timeout_ms): + return True + except Exception: + continue + try: + body = root.locator("body").inner_text(timeout=timeout_ms).lower() + except Exception: + body = "" + if any(marker.lower() in body for marker in _DSV_PASSWORD_UPGRADE_PROMPT_MARKERS): + if any(label in body for label in ("也许以后", "maybe later", "not now")): + return True + return False + + +def _debug_dsv_login_method_page(page: Any) -> str: + snippets: list[str] = [] + for idx, frame in enumerate(page.frames): + try: + body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500] + except Exception: + body = "" + try: + candidates = frame.evaluate( + """ + () => Array.from(document.querySelectorAll('.device-type, .device-description, li, button, a, [role="button"]')) + .map((node) => ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim()) + .filter(Boolean) + .slice(0, 30) + """, + timeout=1_000, + ) + except Exception: + candidates = [] + if body or candidates: + snippets.append(f"frame[{idx}] body={body!r} candidates={candidates!r}") + return " | ".join(snippets)[:2000] + + +def _fill_dsv_password_page_fields(page: Any, username: str, password: str) -> bool: + filled_password = False + for frame in page.frames: + try: + inputs = frame.locator("input").all() + except Exception: + inputs = [] + for input_locator in inputs: + try: + input_type = str(input_locator.get_attribute("type", timeout=500) or "").lower() + input_name = str(input_locator.get_attribute("name", timeout=500) or "").lower() + input_id = str(input_locator.get_attribute("id", timeout=500) or "").lower() + if not input_locator.is_visible(timeout=500): + continue + if input_type == "password" or "password" in input_name or "password" in input_id: + input_locator.fill(password, timeout=2_000) + filled_password = True + elif input_type in {"", "text", "email"} or "user" in input_name or "identifier" in input_name: + current = str(input_locator.input_value(timeout=500) or "").strip() + if not current: + input_locator.fill(username, timeout=2_000) + except Exception: + pass + return filled_password + + +def _is_dsv_username_page(page: Any) -> bool: + for frame in page.frames: + try: + text = frame.locator("body").inner_text(timeout=500) + except Exception: + text = "" + lowered = text.lower() + method_markers = ("选择登录方法", "choose a sign-on method", "输入您的密码并登录", "password") + if any(marker in text or marker in lowered for marker in method_markers): + continue + if ("电子邮件或SIMS ID或手机号" in text or "e-mail or sims id" in lowered) and ("继续" in text or "continue" in lowered): + return True + return False + + +def _submit_dsv_password_form(page: Any) -> bool: + """ + 提交 DSV 密码登录页。 + + 核心逻辑:优先直接点击可见登录按钮;如果页面使用 Vue/隐藏字段组合提交, + 则退回到 DOM 脚本里触发 `pf.ok` / form submit / Enter,避免“密码已填完但未真正登录”。 + """ + selectors = ( + 'button[name="login"]', + 'button[type="submit"]', + 'input[type="submit"]', + 'input[name="pf.ok"]', + 'button.btn.dbs-sims-button-primary', + 'button.dbs-sims-button-primary', + ) + roots = [page, *getattr(page, "frames", [])] + for selector in selectors: + for root in roots: + try: + button = root.locator(selector).first + button.wait_for(state="visible", timeout=1_000) + button.click(timeout=2_000, force=True) + return True + except Exception: + pass + script = """ + () => { + const visible = (node) => { + const rect = node.getBoundingClientRect(); + const style = window.getComputedStyle(node); + return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0; + }; + const password = Array.from(document.querySelectorAll('input#userpassword, input[name="userpassword"], input#password[name="pf.pass"], input[name="pf.pass"], input[type="password"]')) + .find((node) => !node.disabled); + if (!password) return false; + const form = password.closest('form'); + const scope = form || document; + const submit = scope.querySelector('button[name="login"], button[type="submit"], input[type="submit"], input[name="pf.ok"], button.btn.dbs-sims-button-primary, button.dbs-sims-button-primary') + || Array.from(scope.querySelectorAll('button, input[type="submit"], input[name="pf.ok"], [role="button"], .btn.dbs-sims-button-primary, .dbs-sims-button-primary, .dbs-sims-button')) + .find((node) => { + const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim(); + return text === '登录' || text === 'Login' || text === 'Log in' || text === 'Sign in'; + }) || (form ? form.querySelector('button[name="login"], button[type="submit"], input[type="submit"], input[name="pf.ok"], button:not([type]), .btn.dbs-sims-button-primary, .dbs-sims-button-primary') : null); + if (submit) { + if (visible(submit) && typeof submit.scrollIntoView === 'function') { + submit.scrollIntoView({ block: 'center', inline: 'center' }); + } + submit.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true, pointerType: 'mouse' })); + submit.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window })); + submit.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window })); + submit.click(); + submit.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); + return true; + } + if (form && typeof form.requestSubmit === 'function') { + form.requestSubmit(); + return true; + } + if (form) { + form.submit(); + return true; + } + password.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + return true; + } + """ + for frame in roots: + try: + if frame.evaluate(script, timeout=2_000): + return True + except Exception: + pass + return False + + +def _looks_like_dsv_login_method_page(page: Any) -> bool: + needles = ("选择登录方法", "密码", "Password", "输入您的密码并登录", "Choose a sign-on method") + for frame in page.frames: + try: + text = frame.locator("body").inner_text(timeout=300) + except Exception: + text = "" + lowered = text.lower() + if "real person" in lowered and ("rabbit" in lowered or "scale" in lowered): + continue + if any(needle in text for needle in needles): + return True + return False + + +def _has_dsv_human_check_prompt(page: Any) -> bool: + """快速判断当前页是否出现真人验证提示,避免在普通登录轮询里反复触发重等待。""" + try: + text = page.locator("body").inner_text(timeout=300) + except Exception: + text = "" + lowered = text.lower() + return "real person" in lowered or "rabbit" in lowered or "scale" in lowered or "真人" in text + + +def _wait_for_dsv_login_method_page(page: Any, timeout_ms: int | None = None) -> bool: + wait_ms = timeout_ms if timeout_ms is not None else max(5_000, int(_env("FREIGHT_RPA_DSV_METHOD_PAGE_TIMEOUT_MS", "20000") or "20000")) + deadline = time.monotonic() + (wait_ms / 1000) + while time.monotonic() < deadline: + if "s360.dbschenker.com" in page.url and "auth.dbschenker.com" not in page.url: + return True + if _looks_like_dsv_login_method_page(page): + return True + if _has_dsv_human_check_prompt(page): + _wait_for_dsv_human_check_if_present(page, timeout_ms=2_000) + time.sleep(0.5) + return False + + +def _wait_for_dsv_human_check_if_present(page: Any, timeout_ms: int | None = None) -> None: + wait_ms = timeout_ms if timeout_ms is not None else 300_000 + try: + text = page.locator("body").inner_text(timeout=2_000) + except Exception: + text = "" + lowered = text.lower() + if "real person" not in lowered and "rabbit" not in lowered and "scale" not in lowered and "真人" not in text: + return + print("[dsv-login] human check detected; please click the requested object in the browser") + deadline = time.monotonic() + (wait_ms / 1000) + while time.monotonic() < deadline: + try: + current = page.locator("body").inner_text(timeout=2_000) + except Exception: + current = "" + lowered_current = current.lower() + if "real person" not in lowered_current and "rabbit" not in lowered_current and "scale" not in lowered_current: + print("[dsv-login] human check passed") + return + time.sleep(2) + raise RuntimeError("DSV login human check was not completed in time") + + +def _dsv_login_debug_value(page: Any) -> tuple[str, dict[str, Any]]: + identifier_value = "" + button_state: dict[str, Any] = {} + for frame in page.frames: + if not identifier_value: + try: + identifier_value = frame.locator("input#identifier").first.input_value(timeout=1_000) + except Exception: + pass + if not button_state: + try: + button_state = frame.locator("button[name='login']").first.evaluate( + "(node) => ({ disabled: node.disabled, text: node.textContent, className: node.className })", + timeout=1_000, + ) + except Exception: + pass + if identifier_value or button_state: + break + return identifier_value, button_state + + +def _find_dsv_password_locator(page: Any, timeout_ms: int = 250): + """ + 轻量探测 DSV 密码输入框。 + + 核心逻辑:登录第二/第三步切换期间只需要快速知道“密码框是否已出现”, + 这里避免调用带长轮询的通用选择器等待,减少方法页阶段的有效阻塞。 + """ + selectors = tuple( + item + for item in ( + _env("FREIGHT_RPA_DSV_PASSWORD_SELECTOR"), + "input#userpassword", + 'input[name="userpassword"]', + 'input[name="password"]', + 'input[type="password"]', + ) + if item + ) + for frame in page.frames: + for selector in selectors: + try: + locator = frame.locator(selector).first + if locator.is_visible(timeout=timeout_ms): + return locator + except Exception: + continue + return None + + +def _is_dsv_oauth_handshake_url(url: str) -> bool: + """PingFederate OAuth 握手页:常见为空白 body,需等待 JS 跳转或 reload。""" + current = str(url or "").lower() + return "auth.dbschenker.com" in current and "authorization.oauth2" in current + + +def _is_dsv_auth_ping_url(url: str) -> bool: + """PingFederate 密码阶段 authorization.ping:同样可能出现空白 body。""" + current = str(url or "").lower() + return "auth.dbschenker.com" in current and "authorization.ping" in current + + +def _is_dsv_blank_auth_transition(page: Any) -> bool: + """auth 域 oauth2/ping 中间页中 body 为空。""" + try: + current_url = str(page.url or "").lower() + except Exception: + return False + if not (_is_dsv_oauth_handshake_url(current_url) or _is_dsv_auth_ping_url(current_url)): + return False + try: + body = str(page.locator("body").inner_text(timeout=1_000) or "").strip() + except Exception: + body = "" + return not body + + +def _dsv_login_ready_timeout_ms() -> int: + """DSV 登录表单/跳转就绪的最大等待秒数。""" + return max(60_000, int(_env("FREIGHT_RPA_LOGIN_READY_TIMEOUT_MS", "120000") or "120000")) + + +def _wait_for_dsv_auth_page_ready(page: Any, *, timeout_ms: int | None = None) -> bool: + """ + 等待 DSV auth 域完成 OAuth/Ping 握手并渲染登录表单或跳回 portal。 + + 核心逻辑:authorization.oauth2 / authorization.ping 均可能空白; + 轮询用户名/密码框与 portal 导航,必要时 reload 一次触发 PingFederate 自动提交。 + """ + wait_ms = timeout_ms if timeout_ms is not None else _dsv_login_ready_timeout_ms() + deadline = time.monotonic() + (wait_ms / 1000) + started_at = time.monotonic() + logged_waiting = False + reload_attempted = False + while time.monotonic() < deadline: + current_url = str(page.url or "").lower() + if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url: + if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None: + return True + if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None: + return True + if _wait_for_visible_selector( + page, + "FREIGHT_RPA_DSV_USERNAME_SELECTOR", + _DSV_USERNAME_SELECTORS, + timeout_ms=500, + ) is not None: + return True + if _find_dsv_password_locator(page, timeout_ms=200) is not None: + return True + if _wait_for_dsv_login_method_page(page, timeout_ms=200): + return True + if "auth.dbschenker.com" not in current_url: + return True + try: + body = str(page.locator("body").inner_text(timeout=1_000) or "").strip() + except Exception: + body = "" + if body and not _is_dsv_blank_auth_transition(page): + return True + if not logged_waiting: + print(f"[dsv-login] waiting auth page render url={page.url!r}") + logged_waiting = True + try: + page.wait_for_load_state("load", timeout=2_000) + except Exception: + pass + try: + page.wait_for_load_state("networkidle", timeout=2_000) + except Exception: + pass + if not reload_attempted and (time.monotonic() - started_at) >= 12: + reload_attempted = True + transition = "ping" if _is_dsv_auth_ping_url(current_url) else "oauth" + print(f"[dsv-login] blank auth {transition} transition, reload once") + try: + page.reload(wait_until="commit", timeout=min(wait_ms, 45_000)) + except Exception as exc: + print(f"[dsv-login] auth reload failed: {exc}", file=sys.stderr) + time.sleep(0.35) + print(f"[dsv-login] auth page wait finished url={page.url!r}") + return False + + +def _wait_for_dsv_oauth_handshake(page: Any, *, timeout_ms: int = 45_000) -> None: + """兼容旧调用:委托至 _wait_for_dsv_auth_page_ready。""" + _wait_for_dsv_auth_page_ready(page, timeout_ms=timeout_ms) + + +def _try_fill_dsv_username_locator(locator: Any, username: str) -> bool: + try: + locator.wait_for(state="visible", timeout=1_000) + locator.wait_for(state="attached", timeout=1_000) + if not locator.is_enabled(timeout=1_000): + return False + if not _dsv_locator_can_edit(locator): + return False + locator.click(timeout=2_000) + try: + locator.fill(username, timeout=3_000) + except Exception: + locator.press("Control+A") + locator.press("Backspace") + locator.type(username, delay=30) + if _dsv_username_has_value(locator): + return True + locator.evaluate( + """ + (node, value) => { + node.focus(); + node.value = value; + node.dispatchEvent(new Event('input', { bubbles: true })); + node.dispatchEvent(new Event('change', { bubbles: true })); + } + """, + username, + ) + return _dsv_username_has_value(locator) + except Exception: + return False + + +def _fill_dsv_username(page: Any, username: str, preferred_locator: Any | None = None): + """ + 在 DSV 第一步邮箱页填写账号。 + + 核心逻辑:优先复用已经探测到的输入框,避免“探测到了邮箱框,但二次扫描更窄选择器后又找不到”的失配, + 若复用失败,再按完整候选选择器扫描各 frame。 + """ + if preferred_locator is not None and _try_fill_dsv_username_locator(preferred_locator, username): + return preferred_locator + + timeout_ms = max(5_000, int(_env("FREIGHT_RPA_LOGIN_READY_TIMEOUT_MS", "300000") or "300000")) + deadline = time.monotonic() + (timeout_ms / 1000) + while time.monotonic() < deadline: + for frame in page.frames: + for selector in _DSV_USERNAME_SELECTORS: + try: + locator = frame.locator(selector).first + if _try_fill_dsv_username_locator(locator, username): + return locator + except Exception: + pass + time.sleep(0.5) + return None + + +def _dismiss_dsv_password_upgrade_prompt(page: Any) -> None: + """ + DSV 首次登录后可能提示升级密码登录;RPA 选择“也许以后”继续进入系统。 + """ + started_at = time.monotonic() + # #region debug-point M:upgrade-prompt-entry + _report_debug_event( + "M", + "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:entry", + "[DEBUG] checking dsv password upgrade prompt", + {"url": page.url}, + ) + # #endregion + candidates = _dsv_maybe_later_selector_candidates() + + def _prompt_visible() -> bool: + return _has_dsv_password_upgrade_prompt(page, timeout_ms=250) + + # [STEP 1] 先做轻量探测门;没看到升级提示强特征时,直接跳过, + # 避免在 Verifying compliance / auth 跳转页里做大范围阻塞轮询。 + quick_detect_deadline = time.monotonic() + 5.0 + prompt_detected = _prompt_visible() + while not prompt_detected and time.monotonic() < quick_detect_deadline: + time.sleep(0.2) + prompt_detected = _prompt_visible() + if not prompt_detected: + # #region debug-point M:upgrade-prompt-skip + _report_debug_event( + "M", + "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:skip", + "[DEBUG] dsv password upgrade prompt not shown", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, + ) + # #endregion + return + + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + roots = [page, *getattr(page, "frames", [])] + for root in roots: + for candidate in candidates: + try: + locator = root.locator(candidate).first + locator.wait_for(state="attached", timeout=300) + try: + locator.scroll_into_view_if_needed(timeout=1_000) + except Exception: + pass + try: + locator.click(timeout=1_500, force=True) + except Exception: + locator.evaluate( + """ + (target) => { + target.click(); + target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); + } + """ + ) + time.sleep(1) + if not _prompt_visible(): + print("[dsv-login] password upgrade prompt dismissed") + # #region debug-point M:upgrade-prompt-dismissed + _report_debug_event( + "M", + "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:dismissed", + "[DEBUG] dsv password upgrade prompt dismissed", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "candidate": candidate, "url": page.url}, + ) + # #endregion + try: + page.wait_for_load_state("domcontentloaded", timeout=10_000) + except Exception: + pass + return + except Exception: + continue + if _try_click_dsv_maybe_later_via_js(root): + time.sleep(1) + if not _prompt_visible(): + print("[dsv-login] password upgrade prompt dismissed via js fallback") + _report_debug_event( + "M", + "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:dismissed_js", + "[DEBUG] dsv password upgrade prompt dismissed via js fallback", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, + ) + try: + page.wait_for_load_state("domcontentloaded", timeout=10_000) + except Exception: + pass + return + if not _prompt_visible(): + # #region debug-point M:upgrade-prompt-skip + _report_debug_event( + "M", + "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:skip", + "[DEBUG] dsv password upgrade prompt disappeared before click", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, + ) + # #endregion + return + _debug_dsv_stage(page, "password-upgrade-prompt-still-visible", target_text="Maybe later") + time.sleep(0.4) + # #region debug-point M:upgrade-prompt-timeout + _report_debug_event( + "M", + "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:timeout", + "[DEBUG] dsv password upgrade prompt remained visible until timeout", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, + ) + + +def _dismiss_dsv_password_upgrade_prompt_after_login_redirect(page: Any) -> None: + """ + 登录提交后的条件处理:仅在跳到密码升级 auth resume 页时点击“也许以后”。 + """ + if not _is_dsv_password_upgrade_redirect(page): + _report_debug_event( + "M", + "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt_after_login_redirect:skip", + "[DEBUG] skip password upgrade prompt because login did not redirect to upgrade URL", + {"url": page.url}, + ) + return + try: + page.wait_for_load_state("domcontentloaded", timeout=10_000) + except Exception: + pass + _dismiss_dsv_password_upgrade_prompt(page) + + +_DSV_USERNAME_SELECTORS = ( + "input#identifier", + 'input[name="identifier"]', + 'input[name="username"]', + 'input[name="userName"]', + 'input[name="email"]', + 'input[autocomplete="username"]', + 'input[placeholder="电子邮件或SIMS ID或手机号"]', + 'input[type="email"]', + 'input[type="text"]', +) + +# 公开 API +DSV_USERNAME_SELECTORS = _DSV_USERNAME_SELECTORS +click_dsv_continue = _click_dsv_continue +click_dsv_password_method = _click_dsv_password_method +debug_dsv_login_method_page = _debug_dsv_login_method_page +dismiss_dsv_password_upgrade_prompt = _dismiss_dsv_password_upgrade_prompt +dismiss_dsv_password_upgrade_prompt_after_login_redirect = _dismiss_dsv_password_upgrade_prompt_after_login_redirect +dsv_locator_can_edit = _dsv_locator_can_edit +dsv_login_debug_value = _dsv_login_debug_value +dsv_login_ready_timeout_ms = _dsv_login_ready_timeout_ms +dsv_username_has_value = _dsv_username_has_value +fill_dsv_password_page_fields = _fill_dsv_password_page_fields +fill_dsv_username = _fill_dsv_username +find_dsv_password_locator = _find_dsv_password_locator +has_dsv_human_check_prompt = _has_dsv_human_check_prompt +has_dsv_password_upgrade_prompt = _has_dsv_password_upgrade_prompt +is_dsv_auth_ping_url = _is_dsv_auth_ping_url +is_dsv_blank_auth_transition = _is_dsv_blank_auth_transition +is_dsv_oauth_handshake_url = _is_dsv_oauth_handshake_url +is_dsv_username_page = _is_dsv_username_page +looks_like_dsv_login_method_page = _looks_like_dsv_login_method_page +submit_dsv_password_form = _submit_dsv_password_form +submit_dsv_username_form = _submit_dsv_username_form +try_fill_dsv_username_locator = _try_fill_dsv_username_locator +wait_for_dsv_auth_page_ready = _wait_for_dsv_auth_page_ready +wait_for_dsv_human_check_if_present = _wait_for_dsv_human_check_if_present +wait_for_dsv_login_method_page = _wait_for_dsv_login_method_page +wait_for_dsv_oauth_handshake = _wait_for_dsv_oauth_handshake + +from dsv_auth_login_flow import maybe_auto_login_dsv as _maybe_auto_login_dsv +maybe_auto_login_dsv = _maybe_auto_login_dsv diff --git a/scripts/rpa/dsv_auth_login_flow.py b/scripts/rpa/dsv_auth_login_flow.py new file mode 100644 index 00000000..383cc999 --- /dev/null +++ b/scripts/rpa/dsv_auth_login_flow.py @@ -0,0 +1,393 @@ +""" +scripts/rpa/dsv_auth_login_flow.py + +用途:DSV 360 PingID 自动登录主编排(maybe_auto_login_dsv)。 +依赖:rpa_common、dsv_debug、dsv_auth(表单/探测辅助)、dsv_session(登录后首页 ready)。 +逻辑:由 dsv_auth 在模块末尾 re-export;dsv_report_export ensure 时触发。 +""" + +from __future__ import annotations + +import sys +import time +from typing import Any, Callable + +from rpa_common import browser_timeout_ms as _browser_timeout_ms +from rpa_common import env as _env +from rpa_common import fill_first_visible_text_input as _fill_first_visible_text_input +from rpa_common import wait_for_visible_selector as _wait_for_visible_selector +from dsv_debug import ( + collect_dsv_reports_probe as _collect_dsv_reports_probe, + debug_dsv_stage as _debug_dsv_stage, + report_debug_event as _report_debug_event, + report_dsv_chain_stage as _report_dsv_chain_stage, +) + +import dsv_auth + +# 绑定私有符号,避免 dsv_auth 末尾 re-export 时的循环导入竞态。 +_DSV_USERNAME_SELECTORS = dsv_auth._DSV_USERNAME_SELECTORS +_click_dsv_continue = dsv_auth._click_dsv_continue +_click_dsv_password_method = dsv_auth._click_dsv_password_method +_debug_dsv_login_method_page = dsv_auth._debug_dsv_login_method_page +_dismiss_dsv_password_upgrade_prompt_after_login_redirect = dsv_auth._dismiss_dsv_password_upgrade_prompt_after_login_redirect +_dsv_login_debug_value = dsv_auth._dsv_login_debug_value +_dsv_login_ready_timeout_ms = dsv_auth._dsv_login_ready_timeout_ms +_fill_dsv_password_page_fields = dsv_auth._fill_dsv_password_page_fields +_fill_dsv_username = dsv_auth._fill_dsv_username +_find_dsv_password_locator = dsv_auth._find_dsv_password_locator +_has_dsv_human_check_prompt = dsv_auth._has_dsv_human_check_prompt +_is_dsv_blank_auth_transition = dsv_auth._is_dsv_blank_auth_transition +_is_dsv_oauth_handshake_url = dsv_auth._is_dsv_oauth_handshake_url +_is_dsv_username_page = dsv_auth._is_dsv_username_page +_submit_dsv_password_form = dsv_auth._submit_dsv_password_form +_wait_for_dsv_auth_page_ready = dsv_auth._wait_for_dsv_auth_page_ready +_wait_for_dsv_human_check_if_present = dsv_auth._wait_for_dsv_human_check_if_present +_wait_for_dsv_login_method_page = dsv_auth._wait_for_dsv_login_method_page + + +def _wait_for_dsv_home_ready_after_login( + page: Any, + *, + timeout_ms: int | None = None, + on_portal_shell_seen: Callable[[], None] | None = None, +) -> None: + """登录完成后等待首页 ready;惰性导入 dsv_session 避免循环依赖。""" + import dsv_session + + dsv_session.wait_for_dsv_home_ready( + page, + timeout_ms=timeout_ms, + on_portal_shell_seen=on_portal_shell_seen, + ) + + +def _wait_for_dsv_app_after_login( + page: Any, + timeout_ms: int | None = None, + on_portal_shell_seen: Callable[[], None] | None = None, +) -> bool: + """登录轮询 portal 壳层;委托 dsv_session。""" + import dsv_session + + return dsv_session.wait_for_dsv_app_after_login( + page, + timeout_ms=timeout_ms, + on_portal_shell_seen=on_portal_shell_seen, + ) + + +def _maybe_auto_login_dsv(page: Any) -> None: + """ + DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。 + """ + username = _env("FREIGHT_RPA_DSV_USERNAME") + password = _env("FREIGHT_RPA_DSV_PASSWORD") + auto_login_started_at = time.monotonic() + username_step_started_at = auto_login_started_at + continue_to_method_started_at: float | None = None + method_to_password_started_at: float | None = None + submit_to_home_started_at: float | None = None + portal_shell_seen_at: float | None = None + + def _report_auto_login_substage(name: str, started_at: float | None) -> None: + """记录 auto_login 内部子阶段耗时,帮助定位认证链路具体卡点。""" + if started_at is None: + return + _report_dsv_chain_stage( + f"auto_login.{name}", + "end", + started_at=started_at, + extra={"sinceAutoLoginMs": int((time.monotonic() - auto_login_started_at) * 1000)}, + ) + + def _report_portal_shell_seen() -> None: + """记录 portal 壳层首次可见时间,区分 auth 收尾和首页 ready 的等待。""" + nonlocal portal_shell_seen_at + if portal_shell_seen_at is not None: + return + portal_shell_seen_at = time.monotonic() + _report_auto_login_substage("portal_shell_seen", submit_to_home_started_at) + + if not username or not password: + return + if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=15_000) is not None: + print("[dsv-login] existing session detected") + # #region debug-point E:existing-session + _report_debug_event( + "E", + "freight_rpa_worker.py:_maybe_auto_login_dsv:existing_session", + "[DEBUG] dsv existing session detected before login flow", + _collect_dsv_reports_probe(page), + ) + # #endregion + return + + _wait_for_dsv_auth_page_ready(page) + login_ready_ms = _dsv_login_ready_timeout_ms() + print("[dsv-login] waiting username field") + username_locator = _wait_for_visible_selector( + page, + "FREIGHT_RPA_DSV_USERNAME_SELECTOR", + _DSV_USERNAME_SELECTORS, + timeout_ms=login_ready_ms, + ) + if username_locator is not None: + username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator) + user_filled = username_locator is not None + else: + username_locator = None + user_filled = _fill_first_visible_text_input(page, username) + if not user_filled: + if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=10_000) is not None: + print("[dsv-login] existing session detected") + # #region debug-point E:existing-session-late + _report_debug_event( + "E", + "freight_rpa_worker.py:_maybe_auto_login_dsv:existing_session_late", + "[DEBUG] dsv existing session detected after username probe", + _collect_dsv_reports_probe(page), + ) + # #endregion + return + if _is_dsv_oauth_handshake_url(page.url): + print("[dsv-login] still on blank oauth handshake before giving up, reload once") + try: + page.reload(wait_until="domcontentloaded", timeout=45_000) + except Exception as exc: + print(f"[dsv-login] final oauth reload failed: {exc}", file=sys.stderr) + if _wait_for_dsv_auth_page_ready(page, timeout_ms=30_000): + username_locator = _wait_for_visible_selector( + page, + "FREIGHT_RPA_DSV_USERNAME_SELECTOR", + _DSV_USERNAME_SELECTORS, + timeout_ms=15_000, + ) + if username_locator is not None: + username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator) + if username_locator is not None: + user_filled = True + if not user_filled: + try: + text = page.locator("body").inner_text(timeout=3_000) + except Exception: + text = "" + raise RuntimeError( + "DSV login state is unknown " + f"url={page.url} body={text[:300]!r} " + "(oauth handshake page stayed blank; check network/VPN or complete login manually in browser)" + ) + print("[dsv-login] username filled") + _report_auto_login_substage("username_step", username_step_started_at) + + continue_selector = _env("FREIGHT_RPA_DSV_CONTINUE_BUTTON_SELECTOR") + if continue_selector: + page.locator(continue_selector).first.click(timeout=_browser_timeout_ms(), force=True) + clicked_continue = True + else: + clicked_continue = _click_dsv_continue(page, username_locator) + if not clicked_continue: + identifier_value, button_state = _dsv_login_debug_value(page) + print(f"[dsv-login] continue missing identifier_value={identifier_value!r} button={button_state!r}") + raise RuntimeError("DSV login email step detected but continue button was not found") + print("[dsv-login] continue clicked") + continue_to_method_started_at = time.monotonic() + # #region debug-point E:continue-clicked + _report_debug_event( + "E", + "freight_rpa_worker.py:_maybe_auto_login_dsv:continue_clicked", + "[DEBUG] dsv username step submitted", + _collect_dsv_reports_probe(page), + ) + # #endregion + + print("[dsv-login] waiting password field") + password_locator = None + login_deadline = time.monotonic() + ( + max(60_000, int(_env("FREIGHT_RPA_DSV_PASSWORD_STAGE_TIMEOUT_MS", "120000") or "120000")) / 1000 + ) + password_method_clicked_at = 0.0 + username_retry_allowed_at = time.monotonic() + 6 + while time.monotonic() < login_deadline: + password_locator = _find_dsv_password_locator(page, timeout_ms=250) + if password_locator is not None: + break + if _fill_dsv_password_page_fields(page, username, password): + print("[dsv-login] password filled") + _report_auto_login_substage("continue_to_method", continue_to_method_started_at) + _report_auto_login_substage("method_to_password", method_to_password_started_at) + if not _submit_dsv_password_form(page): + raise RuntimeError("DSV login password step detected but login button was not found") + print("[dsv-login] login clicked") + submit_to_home_started_at = time.monotonic() + page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms()) + _debug_dsv_stage(page, "after-login-click-inline-password", target_text="Reports") + _dismiss_dsv_password_upgrade_prompt_after_login_redirect(page) + if page.locator('input[type="password"]').first.is_visible(timeout=3_000): + raise RuntimeError("DSV login did not complete; password may be invalid or verification is required") + _wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen) + _report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at) + _report_auto_login_substage("password_submit_to_home", submit_to_home_started_at) + print("[dsv-login] login completed") + return + if _has_dsv_human_check_prompt(page): + _wait_for_dsv_human_check_if_present(page, timeout_ms=300_000) + if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen): + _report_auto_login_substage("continue_to_method", continue_to_method_started_at) + _report_auto_login_substage("method_to_password", method_to_password_started_at) + print("[dsv-login] login completed") + # #region debug-point E:login-completed-direct + _report_debug_event( + "E", + "freight_rpa_worker.py:_maybe_auto_login_dsv:login_completed_direct", + "[DEBUG] dsv login completed directly after human check/app wait", + _collect_dsv_reports_probe(page), + ) + # #endregion + return + method_ready = _wait_for_dsv_login_method_page(page, timeout_ms=2_000) + if method_ready: + # #region debug-point E:password-method-page + _report_debug_event( + "E", + "freight_rpa_worker.py:_maybe_auto_login_dsv:password_method_page", + "[DEBUG] dsv password method page detected", + _collect_dsv_reports_probe(page), + ) + # #endregion + if password_method_clicked_at and time.monotonic() - password_method_clicked_at < 2: + time.sleep(1) + continue + password_method_selector = _env("FREIGHT_RPA_DSV_PASSWORD_METHOD_SELECTOR") + if password_method_selector: + page.locator(password_method_selector).first.click(timeout=_browser_timeout_ms(), force=True) + clicked_password_method = True + else: + clicked_password_method = _click_dsv_password_method(page) + if not clicked_password_method: + print(f"[dsv-login] password method debug {_debug_dsv_login_method_page(page)}") + time.sleep(1) + continue + password_method_clicked_at = time.monotonic() + _report_auto_login_substage("continue_to_method", continue_to_method_started_at) + continue_to_method_started_at = None + method_to_password_started_at = password_method_clicked_at + username_retry_allowed_at = max(username_retry_allowed_at, password_method_clicked_at + 4) + print("[dsv-login] password method clicked") + # #region debug-point E:password-method-clicked + _report_debug_event( + "E", + "freight_rpa_worker.py:_maybe_auto_login_dsv:password_method_clicked", + "[DEBUG] dsv password method clicked", + _collect_dsv_reports_probe(page), + ) + # #endregion + continue + # [STEP 2] Continue 刚提交或刚点过“密码”时,先给 PingID 页面一点切换时间, + # 避免方法页尚未稳定时又误判回邮箱页,造成来回重填账号。 + if time.monotonic() >= username_retry_allowed_at and _is_dsv_username_page(page): + username_locator = _fill_dsv_username(page, username) + if username_locator is None and not _fill_first_visible_text_input(page, username): + print(f"[dsv-login] username retry failed {_debug_dsv_login_method_page(page)}") + time.sleep(1) + continue + if _click_dsv_continue(page, username_locator): + print("[dsv-login] username page retried") + username_retry_allowed_at = time.monotonic() + 6 + time.sleep(1) + continue + password_locator = _find_dsv_password_locator(page, timeout_ms=250) + if password_locator is not None: + break + if _is_dsv_blank_auth_transition(page): + _wait_for_dsv_auth_page_ready(page, timeout_ms=5_000) + password_locator = _find_dsv_password_locator(page, timeout_ms=500) + if password_locator is not None: + break + time.sleep(1) + + if password_locator is None: + if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen): + print("[dsv-login] login completed") + # #region debug-point E:login-completed-late + _report_debug_event( + "E", + "freight_rpa_worker.py:_maybe_auto_login_dsv:login_completed_late", + "[DEBUG] dsv login completed after password wait fallback", + _collect_dsv_reports_probe(page), + ) + # #endregion + return + try: + text = page.locator("body").inner_text(timeout=3_000) + except Exception: + text = "" + if not text.strip(): + print(f"[dsv-login] password page still loading url={page.url}") + if _is_dsv_blank_auth_transition(page): + _wait_for_dsv_auth_page_ready(page, timeout_ms=_dsv_login_ready_timeout_ms()) + password_locator = _wait_for_visible_selector( + page, + "FREIGHT_RPA_DSV_PASSWORD_SELECTOR", + ("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'), + timeout_ms=_dsv_login_ready_timeout_ms(), + ) + if password_locator is None: + if not _fill_dsv_password_page_fields(page, username, password): + raise RuntimeError("DSV login password field was not found") + print("[dsv-login] password filled") + _report_auto_login_substage("continue_to_method", continue_to_method_started_at) + _report_auto_login_substage("method_to_password", method_to_password_started_at) + if not _submit_dsv_password_form(page): + raise RuntimeError("DSV login password step detected but login button was not found") + print("[dsv-login] login clicked") + submit_to_home_started_at = time.monotonic() + page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms()) + _debug_dsv_stage(page, "after-login-click-late-password", target_text="Reports") + _dismiss_dsv_password_upgrade_prompt_after_login_redirect(page) + _wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen) + _report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at) + _report_auto_login_substage("password_submit_to_home", submit_to_home_started_at) + print("[dsv-login] login completed") + return + print(f"[dsv-login] password field missing url={page.url} body={text[:300]!r} method_debug={_debug_dsv_login_method_page(page)}") + raise RuntimeError("DSV login password field was not found") + + password_locator.fill(password, timeout=_browser_timeout_ms()) + print("[dsv-login] password filled") + _report_auto_login_substage("continue_to_method", continue_to_method_started_at) + _report_auto_login_substage("method_to_password", method_to_password_started_at) + if not _submit_dsv_password_form(page): + raise RuntimeError("DSV login password step detected but login button was not found") + print("[dsv-login] login clicked") + submit_to_home_started_at = time.monotonic() + # #region debug-point N:login-clicked + _report_debug_event( + "N", + "freight_rpa_worker.py:_maybe_auto_login_dsv:login_clicked", + "[DEBUG] dsv login button submitted", + {"url": page.url}, + ) + # #endregion + + page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms()) + # #region debug-point N:after-domcontentloaded + _report_debug_event( + "N", + "freight_rpa_worker.py:_maybe_auto_login_dsv:after_domcontentloaded", + "[DEBUG] dsv login flow reached domcontentloaded after submit", + {"url": page.url}, + ) + # #endregion + _debug_dsv_stage(page, "after-login-click-password-locator", target_text="Reports") + _dismiss_dsv_password_upgrade_prompt_after_login_redirect(page) + if page.locator('input[type="password"]').first.is_visible(timeout=3_000): + raise RuntimeError("DSV login did not complete; password may be invalid or verification is required") + _wait_for_dsv_home_ready_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen) + _report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at) + _report_auto_login_substage("password_submit_to_home", submit_to_home_started_at) + print("[dsv-login] login completed") + + +# 公开 API +maybe_auto_login_dsv = _maybe_auto_login_dsv diff --git a/scripts/rpa/dsv_debug.py b/scripts/rpa/dsv_debug.py new file mode 100644 index 00000000..b06ee035 --- /dev/null +++ b/scripts/rpa/dsv_debug.py @@ -0,0 +1,346 @@ +""" +scripts/rpa/dsv_debug.py + +用途:DSV 360 RPA 调试探针与链路阶段日志。 +依赖:rpa_common。 +逻辑:供 dsv_session、dsv_navigation、dsv_report_export 调用。 +""" + +from __future__ import annotations + +import json +import sys +import time +import urllib.request +from pathlib import Path +from typing import Any + +from rpa_common import browser_timeout_ms as _browser_timeout_ms +from rpa_common import env as _env + +def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None: + _payload = { + "sessionId": "dsv-export-stall", + "runId": run_id, + "hypothesisId": hypothesis_id, + "location": location, + "msg": msg, + "data": data or {}, + "ts": int(time.time() * 1000), + } + _url = "http://127.0.0.1:7778/event" + _env_file = Path(".dbg/dsv-export-stall.env") + try: + if _env_file.is_file(): + _content = _env_file.read_text(encoding="utf-8") + _url = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SERVER_URL=")), _url) + _payload["sessionId"] = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SESSION_ID=")), _payload["sessionId"]) + urllib.request.urlopen( + urllib.request.Request( + _url, + data=json.dumps(_payload, ensure_ascii=False).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ), + timeout=1.5, + ).read() + except Exception: + pass +def _debug_dsv_page_snapshot(page: Any, *, target_text: str = "") -> str: + """ + 汇总 DSV 当前页面与各 frame 的可见文本快照,便于定位菜单/报表文案漂移。 + + 核心逻辑:采集 page.url、顶层 body 文本、关键菜单容器是否存在,以及各 frame 中 + 可见的链接/按钮/菜单项候选文本;当目标文案找不到时,日志里直接输出“页面上实际看到了什么”。 + + Args: + page: Playwright Page 对象。 + target_text: 当前正在寻找的菜单/报表文案,可为空。 + + Returns: + str: 截断后的页面快照字符串,适合直接输出到 worker 日志。 + """ + focus = str(target_text or "").strip() + try: + page_url = page.url + except Exception: + page_url = "" + snippets = [f"url={page_url!r}"] + try: + body = page.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500] + except Exception: + body = "" + if body: + snippets.append(f"page_body={body!r}") + try: + from dsv_session import has_dsv_report_nav_attached as _has_dsv_report_nav_attached + + report_nav_exists = _has_dsv_report_nav_attached(page) + except Exception: + report_nav_exists = False + snippets.append(f"report_nav_exists={report_nav_exists}") + + candidate_script = """ + (focusText) => { + const normalize = (value) => ((value || '') + '').replace(/\\s+/g, ' ').trim(); + const isVisible = (node) => { + const rect = node.getBoundingClientRect(); + const style = window.getComputedStyle(node); + return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0; + }; + const selectors = [ + '#report-mega-legacy', + '#report-mega-legacy *', + '.mega-dropdown-menu *', + '.dropdown-menu *', + 'a', + 'button', + '[role="button"]', + 'li', + '.nav-link', + '.dropdown-item', + ]; + const focus = normalize(focusText).toLowerCase(); + const values = Array.from(document.querySelectorAll(selectors.join(','))) + .filter((node) => isVisible(node)) + .map((node) => normalize(node.innerText || node.textContent || node.value)) + .filter(Boolean); + const deduped = Array.from(new Set(values)); + const matched = focus + ? deduped.filter((text) => text.toLowerCase().includes(focus)).slice(0, 20) + : []; + return { + matched, + candidates: deduped.slice(0, 40), + }; + } + """ + for idx, frame in enumerate(page.frames): + try: + frame_url = frame.url + except Exception: + frame_url = "" + try: + frame_name = frame.name + except Exception: + frame_name = "" + try: + frame_body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:400] + except Exception: + frame_body = "" + try: + frame_data = frame.evaluate(candidate_script, focus, timeout=1_500) + except Exception: + frame_data = {"matched": [], "candidates": []} + matched = list((frame_data or {}).get("matched") or []) + candidates = list((frame_data or {}).get("candidates") or []) + if frame_body or candidates or matched: + snippets.append( + f"frame[{idx}] name={frame_name!r} url={frame_url!r} body={frame_body!r} matched={matched!r} candidates={candidates!r}" + ) + return " | ".join(snippets)[:5000] + + +def _debug_dsv_stage(page: Any, stage: str, *, target_text: str = "") -> None: + """ + 输出 DSV 关键阶段的运行时快照,用于排查“短暂到页后又跳走”或 DOM 未就绪的问题。 + + 核心逻辑:在登录后等待首页、展开 Reports、选择 Program 等关键节点打印统一格式日志, + 让失败复现时可以按时间顺序观察 URL、标题、body、frame 候选文本是否发生变化。 + + Args: + page: Playwright Page 对象。 + stage: 当前阶段名,例如 `after-login-click`、`wait-app-3s`。 + target_text: 当前关注的菜单或文案目标。 + """ + try: + title = page.title() + except Exception: + title = "" + snapshot = _debug_dsv_page_snapshot(page, target_text=target_text) + print(f"[dsv-stage] stage={stage} title={title!r} {snapshot}") + + +# #region debug-point A:reports-debug-server +def _debug_server_config() -> tuple[str, str]: + """读取 reports-menu-stuck 调试会话配置,未命中时回退默认本地地址。""" + env_path = Path(__file__).resolve().parents[2] / ".dbg" / "reports-menu-stuck.env" + url = "http://127.0.0.1:7778/event" + session_id = "reports-menu-stuck" + try: + content = env_path.read_text(encoding="utf-8") + for line in content.splitlines(): + if line.startswith("DEBUG_SERVER_URL="): + url = line.split("=", 1)[1].strip() or url + elif line.startswith("DEBUG_SESSION_ID="): + session_id = line.split("=", 1)[1].strip() or session_id + except Exception: + pass + return url, session_id + + +def _report_debug_event(hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None: + """向 Debug Server 上报结构化运行时证据;失败时静默,不影响业务流程。""" + try: + url, session_id = _debug_server_config() + payload = { + "sessionId": session_id, + "runId": "pre-fix", + "hypothesisId": hypothesis_id, + "location": location, + "msg": msg, + "data": data or {}, + "ts": int(time.time() * 1000), + } + req = urllib.request.Request( + url, + data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), + headers={"Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(req, timeout=2): + pass + except Exception: + pass + + +def _report_dsv_chain_stage(stage: str, status: str, *, started_at: float | None = None, extra: dict[str, Any] | None = None) -> None: + """ + 统一记录 DSV 主链路各阶段耗时。 + + 核心逻辑:只在主编排链路输出 `start/end/error` 三类探针,不参与任何业务判断, + 让一次真实运行即可回放从登录到导出的完整阶段耗时分布。 + """ + payload = dict(extra or {}) + if started_at is not None: + payload["elapsedMs"] = int((time.monotonic() - started_at) * 1000) + print( + "[dsv-chain] " + f"stage={stage} " + f"status={status} " + + ( + " ".join(f"{key}={payload[key]!r}" for key in sorted(payload)) + if payload + else "" + ) + ) + _report_debug_event( + "T", + f"freight_rpa_worker.py:_download_dsv360_inventory:{stage}:{status}", + "[DEBUG] dsv chain stage probe", + {"stage": stage, "status": status, **payload}, + ) + + +def _collect_dsv_reports_probe(page: Any) -> dict[str, Any]: + """采集 Reports 导航的最小 DOM 证据,帮助判断是否点早、点错或被遮挡。""" + try: + probe = page.evaluate( + """ + () => { + const nav = document.querySelector('#report-mega-legacy'); + const link = nav?.querySelector('a.dropdown-toggle, a.nav-link, a'); + const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim(); + const rectOf = (node) => { + if (!node || !node.getBoundingClientRect) return null; + const r = node.getBoundingClientRect(); + return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) }; + }; + const centerNode = (() => { + const rect = rectOf(link); + if (!rect || rect.width <= 0 || rect.height <= 0) return null; + return document.elementFromPoint(rect.x + Math.max(Math.floor(rect.width / 2), 1), rect.y + Math.max(Math.floor(rect.height / 2), 1)); + })(); + return { + navExists: !!nav, + navClass: nav?.className || '', + navAriaExpanded: nav?.getAttribute('aria-expanded') || '', + linkText: textOf(link), + linkClass: link?.className || '', + linkAriaExpanded: link?.getAttribute('aria-expanded') || '', + linkRect: rectOf(link), + centerTag: centerNode?.tagName || '', + centerText: textOf(centerNode).slice(0, 120), + activeTag: document.activeElement?.tagName || '', + activeText: textOf(document.activeElement).slice(0, 120), + }; + } + """, + ) + except Exception as exc: + probe = {"probe_error": str(exc)[:200]} + try: + probe["url"] = page.url + except Exception: + probe["url"] = "" + try: + from dsv_navigation import is_dsv_reports_menu_open as _is_dsv_reports_menu_open + + probe["menuOpen"] = _is_dsv_reports_menu_open(page) + except Exception as exc: + probe["menuOpen"] = False + probe["menuOpenError"] = str(exc)[:120] + return probe +# #endregion + + +def _collect_dsv_menu_probe(page: Any, target_text: str = "") -> dict[str, Any]: + """采集 Reports 级联菜单当前可见层级,帮助判断下拉是否真的推进到了下一层。""" + target_text = str(target_text or "").strip() + target_literal = json.dumps(target_text) + try: + probe = page.evaluate( + f""" + () => {{ + const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim(); + const nodes = Array.from(document.querySelectorAll( + '#report-mega-legacy a, .mega-dropdown-menu a, .dropdown-menu a, [role="menuitem"], .dropdown-item' + )); + const visible = nodes + .filter((node) => {{ + const rect = node.getBoundingClientRect ? node.getBoundingClientRect() : null; + const style = window.getComputedStyle ? window.getComputedStyle(node) : null; + return rect && rect.width > 0 && rect.height > 0 && style && style.visibility !== 'hidden' && style.display !== 'none'; + }}) + .map((node) => {{ + const rect = node.getBoundingClientRect(); + return {{ + text: textOf(node), + className: node.className || '', + ariaExpanded: node.getAttribute('aria-expanded') || '', + x: Math.round(rect.x), + y: Math.round(rect.y), + }}; + }}) + .filter((item) => item.text) + .slice(0, 40); + const target = {target_literal}; + const matched = target + ? visible.filter((item) => item.text.toLowerCase().includes(target.toLowerCase())).slice(0, 10) + : []; + return {{ + visibleItems: visible, + matchedItems: matched, + bodySnippet: textOf(document.body).slice(0, 600), + activeText: textOf(document.activeElement).slice(0, 120), + }}; + }} + """, + ) + except Exception as exc: + probe = {"probe_error": str(exc)[:200]} + try: + probe["url"] = page.url + except Exception: + probe["url"] = "" + return probe + + +# 公开 API +emit_debug_event = _emit_debug_event +debug_dsv_page_snapshot = _debug_dsv_page_snapshot +debug_dsv_stage = _debug_dsv_stage +debug_server_config = _debug_server_config +report_debug_event = _report_debug_event +report_dsv_chain_stage = _report_dsv_chain_stage +collect_dsv_reports_probe = _collect_dsv_reports_probe +collect_dsv_menu_probe = _collect_dsv_menu_probe diff --git a/scripts/rpa/dsv_driver.py b/scripts/rpa/dsv_driver.py new file mode 100644 index 00000000..2de187ac --- /dev/null +++ b/scripts/rpa/dsv_driver.py @@ -0,0 +1,29 @@ +""" +scripts/rpa/dsv_driver.py + +用途:DSV 360 库存 RPA 对外编排入口(session → 导航 → 导出)。 +依赖:dsv_report_export。 +逻辑:freight_rpa_worker 在 source_type=dsv360 时仅调用本模块公开函数。 +""" + +from __future__ import annotations + +from typing import Any + +from dsv_report_export import ( + ensure_dsv_session, + export_dsv_inventory_source, + prepare_dsv_batch_export_step, +) + + +def download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any: + """ + 单票 trigger 的 DSV 360 导出。 + 核心逻辑:ensure session → 导航至参数页 → 填参并导出 Excel。 + """ + entry_url = str(source.get("entry_url") or "").strip() + if not entry_url: + raise RuntimeError("DSV360 inventory source missing entry_url") + ensure_dsv_session(page, entry_url) + return export_dsv_inventory_source(page, trigger, source) diff --git a/scripts/rpa/dsv_export_batch_smoke.py b/scripts/rpa/dsv_export_batch_smoke.py index 528cf513..3d247a2a 100644 --- a/scripts/rpa/dsv_export_batch_smoke.py +++ b/scripts/rpa/dsv_export_batch_smoke.py @@ -62,7 +62,6 @@ def _with_warehouse(source: dict[str, Any], warehouse: str, *, keep_source_code: if not keep_source_code: cloned["source_code"] = f"DSV360_AWSBI_{wh}" cloned["warehouse_id"] = wh - cloned["warehouse_code"] = wh query = dict(cloned.get("query") or {}) query["warehouse_code"] = wh cloned["query"] = query @@ -115,7 +114,7 @@ def _run_batch_exports(worker: Any, scenario: str, sources: list[dict[str, Any]] previous_source: dict[str, Any] | None = None for index, source in enumerate(sources): code = str(source.get("source_code") or "") - wh = str(source.get("warehouse_id") or source.get("warehouse_code") or "") + wh = str(source.get("warehouse_id") or "") print( f"[batch-smoke] scenario={scenario} step={index + 1}/{len(sources)} " f"source_code={code} warehouse={wh}" diff --git a/scripts/rpa/dsv_export_smoke.py b/scripts/rpa/dsv_export_smoke.py index a9d35d74..2295c7a5 100644 --- a/scripts/rpa/dsv_export_smoke.py +++ b/scripts/rpa/dsv_export_smoke.py @@ -52,11 +52,11 @@ def _build_source_from_config(source_code: str) -> dict: navigation = dict(raw.get("navigation") or {}) parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)] - site = str(raw.get("site") or "dsv360").strip().lower() - warehouse_id = str(raw.get("warehouse_id") or raw.get("warehouse_code") or "").strip() + source_type = str(raw.get("source_type") or "dsv360").strip().lower() + warehouse_id = str(raw.get("warehouse_id") or "").strip() query: dict[str, object] = {} - if site == "dsv360": + if source_type == "dsv360": for key in ("program_group", "program_label", "report_group", "report_name"): if navigation.get(key): query[key] = navigation[key] @@ -88,12 +88,12 @@ def _build_source_from_config(source_code: str) -> dict: return { "source_code": str(raw.get("source_code") or source_code).upper(), - "source_type": "dsv360" if site == "dsv360" else site, + "source_type": source_type, + "site_id": str(raw.get("site_id") or "").strip().upper(), "display_name": str(raw.get("display_name") or source_code), "enabled": bool(raw.get("enabled", True)), "entry_url": str(raw.get("entry_url") or "https://s360.dbschenker.com/"), "warehouse_id": warehouse_id, - "warehouse_code": str(raw.get("warehouse_code") or warehouse_id), "navigation": navigation, "parameters": parameters, "query": query, diff --git a/scripts/rpa/dsv_navigation.py b/scripts/rpa/dsv_navigation.py new file mode 100644 index 00000000..e6255d4d --- /dev/null +++ b/scripts/rpa/dsv_navigation.py @@ -0,0 +1,849 @@ +""" +scripts/rpa/dsv_navigation.py + +用途:DSV 360 Reports 菜单导航至 SSRS 参数页。 +依赖:rpa_common、dsv_debug、dsv_session。 +逻辑:由 dsv_report_export 在填参导出前调用。 +""" + +from __future__ import annotations + +import json +import sys +import time +from typing import Any + +from rpa_common import browser_timeout_ms as _browser_timeout_ms +from rpa_common import env as _env +from rpa_common import wait_for_visible_selector as _wait_for_visible_selector +import dsv_debug +from dsv_debug import ( + collect_dsv_menu_probe as _collect_dsv_menu_probe, + collect_dsv_reports_probe as _collect_dsv_reports_probe, + debug_dsv_page_snapshot as _debug_dsv_page_snapshot, + debug_dsv_stage as _debug_dsv_stage, + report_debug_event as _report_debug_event, +) +import dsv_session +from dsv_session import ( + DSV_REPORTS_NAV_SELECTORS as _DSV_REPORTS_NAV_SELECTORS, + has_dsv_report_nav_attached as _has_dsv_report_nav_attached, + has_dsv_report_nav_usable as _has_dsv_report_nav_usable, + is_dsv_on_portal_home as _is_dsv_on_portal_home, + has_dsv_portal_shell as _has_dsv_portal_shell, + is_dsv_home_ready as _is_dsv_home_ready, + dismiss_dsv_password_upgrade_prompt as _dismiss_dsv_password_upgrade_prompt, + has_dsv_password_upgrade_prompt as _has_dsv_password_upgrade_prompt, + wait_for_dsv_app_after_login as _wait_for_dsv_app_after_login, +) + +def _has_dsv_report_form_shell(page: Any) -> bool: + """ + 判断 DSV 报表参数页的 shell 是否已经挂载完成。 + + 核心逻辑:用户在菜单里选中目标报表后,`View Report` 按钮常常已经可以点击, + 但报表标题文本未必立刻出现在 frame 正文里;此时只要 portal reports 路由和 + SSRS 相关 frame 已出现,就可以认定表单页已基本就绪,避免额外等待标题文本刷出。 + """ + try: + current_url = str(page.url or "").lower() + except Exception: + current_url = "" + if "/main/portal/frame/reports/" in current_url: + return True + for frame in getattr(page, "frames", []): + try: + frame_name = str(frame.name or "").strip().lower() + except Exception: + frame_name = "" + try: + frame_url = str(frame.url or "").strip().lower() + except Exception: + frame_url = "" + if frame_name in {"myiframe", "report-frame"}: + return True + if "/s360reports/ssrs/" in frame_url or "/s360reports/reports/default.aspx" in frame_url: + return True + return False + + +def _dsv_report_submission_started(frame: Any, locator: Any) -> bool: + """ + 判断 View Report 点击后是否已开始提交。 + + 核心逻辑:优先检测按钮是否变为 disabled/隐藏,其次检测 frame 文本里是否出现常见的加载提示, + 避免“程序化 submit 已调用,但页面其实没有开始处理”的误判。 + """ + try: + if not locator.is_visible(timeout=500): + return True + except Exception: + return True + try: + state = locator.evaluate( + """ + (node) => ({ + disabled: Boolean(node.disabled), + ariaDisabled: node.getAttribute('aria-disabled'), + value: node.value || node.textContent || '', + }) + """ + ) + value = str((state or {}).get("value") or "").strip().lower() + if (state or {}).get("disabled") or str((state or {}).get("ariaDisabled") or "").lower() == "true": + return True + if value and value != "view report": + return True + except Exception: + pass + try: + body = frame.locator("body").inner_text(timeout=800).lower() + except Exception: + body = "" + transition_markers = ( + "loading", + "please wait", + "generating", + "processing", + "export", + "save", + "excel", + "no records", + "no data", + ) + return any(marker in body for marker in transition_markers) + + +def _dsv_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool: + """ + 判断当前 DSV 页面或 frame 中是否已经出现目标文案。 + + 核心逻辑:同时扫描顶层页面与各 frame 的可见文本和常见菜单节点, + 用于级联菜单点击后的“下一层已展开”确认,避免只点到一级菜单就误判成功。 + + Args: + page: Playwright Page 对象。 + text: 需要确认出现的目标文案。 + timeout_ms: 单次检查的等待时间,默认 1 秒。 + + Returns: + bool: 找到目标文案时返回 True,否则返回 False。 + """ + normalized = str(text or "").strip().lower() + if not normalized: + return False + selectors = ( + f"text={text}", + f"a:has-text({json.dumps(text)})", + f".dropdown-item:has-text({json.dumps(text)})", + f"button:has-text({json.dumps(text)})", + ) + for root in (page, *page.frames): + for selector in selectors: + try: + if root.locator(selector).first.is_visible(timeout=timeout_ms): + return True + except Exception: + pass + try: + body = root.locator("body").inner_text(timeout=timeout_ms).lower() + except Exception: + body = "" + if normalized in body: + return True + return False + + +def _dsv_dropdown_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool: + """ + 仅判断当前展开的 DSV 下拉菜单中是否出现目标文案。 + + 核心逻辑:主页 `Recent Reports` 也会出现与报表菜单同名的文本; + 这里将确认范围收紧为 `Reports` 级联菜单容器内的可见项,避免把首页正文误判成下一级菜单已展开。 + """ + normalized = str(text or "").strip().lower() + if not normalized: + return False + selectors = ( + f"#report-mega-legacy a.dropdown-item:has-text({json.dumps(text)})", + f".mega-dropdown-menu a.dropdown-item:has-text({json.dumps(text)})", + f".dropdown-menu a.dropdown-item:has-text({json.dumps(text)})", + f"#report-mega-legacy [role='menuitem']:has-text({json.dumps(text)})", + f".mega-dropdown-menu [role='menuitem']:has-text({json.dumps(text)})", + f".dropdown-menu [role='menuitem']:has-text({json.dumps(text)})", + f"#report-mega-legacy a:has-text({json.dumps(text)})", + f".mega-dropdown-menu a:has-text({json.dumps(text)})", + f".dropdown-menu a:has-text({json.dumps(text)})", + ) + for selector in selectors: + try: + if page.locator(selector).first.is_visible(timeout=timeout_ms): + return True + except Exception: + pass + probe = _collect_dsv_menu_probe(page, text) + for item in probe.get("matchedItems") or []: + item_text = str((item or {}).get("text") or "").strip().lower() + if item_text and normalized in item_text: + return True + return False + + +def _click_dsv_menu_item(page: Any, text: str, *, next_text: str = "") -> None: + """ + 点击 DSV 级联菜单项,并在需要时确认下一级目标已经出现。 + + 核心逻辑:对同一菜单项依次尝试 hover/click/force/evaluate/keyboard 等方式; + 若传入 next_text,则只有在页面上真正看到下一级菜单文本后才认为本次点击成功。 + + Args: + page: Playwright Page 对象。 + text: 当前要点击的菜单文案。 + next_text: 预期因本次点击而出现的下一级菜单文案;为空时仅要求当前点击成功。 + """ + text = str(text or "").strip() + if not text: + raise RuntimeError("DSV menu item text is empty") + _report_debug_event( + "F", + "freight_rpa_worker.py:_click_dsv_menu_item:entry", + "[DEBUG] entering dsv menu item selection", + { + "targetText": text, + "nextText": str(next_text or ""), + "elapsedMs": 0, + **_collect_dsv_menu_probe(page, text), + }, + ) + text_literal = json.dumps(text) + deadline = time.monotonic() + 30 + started_at = time.monotonic() + while time.monotonic() < deadline: + for selector in ( + f"#report-mega-legacy a.dropdown-item:has-text({text_literal})", + f".mega-dropdown-menu a.dropdown-item:has-text({text_literal})", + f".dropdown-menu a.dropdown-item:has-text({text_literal})", + f"#report-mega-legacy [role='menuitem']:has-text({text_literal})", + f".mega-dropdown-menu [role='menuitem']:has-text({text_literal})", + f".dropdown-menu [role='menuitem']:has-text({text_literal})", + f"#report-mega-legacy a:has-text({text_literal})", + f".mega-dropdown-menu a:has-text({text_literal})", + f".dropdown-menu a:has-text({text_literal})", + ): + try: + locator = page.locator(selector).first + locator.wait_for(state="visible", timeout=2_000) + for action in ("hover", "click", "force-click", "evaluate", "enter", "space"): + try: + if action == "hover": + locator.hover(timeout=1_500) + time.sleep(0.2) + continue + elif action == "click": + locator.click(timeout=1_500) + elif action == "force-click": + locator.click(timeout=1_500, force=True) + elif action == "evaluate": + locator.evaluate("(node) => node.click()") + elif action == "enter": + locator.press("Enter", timeout=1_500) + else: + locator.press("Space", timeout=1_500) + except Exception: + continue + _report_debug_event( + "F", + "freight_rpa_worker.py:_click_dsv_menu_item:attempt", + "[DEBUG] dsv menu item attempt dispatched", + { + "targetText": text, + "nextText": str(next_text or ""), + "selector": selector, + "action": action, + "elapsedMs": int((time.monotonic() - started_at) * 1000), + **_collect_dsv_menu_probe(page, next_text or text), + }, + ) + if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500): + _report_debug_event( + "F", + "freight_rpa_worker.py:_click_dsv_menu_item:success", + "[DEBUG] dsv menu item selection considered successful", + { + "targetText": text, + "nextText": str(next_text or ""), + "selector": selector, + "action": action, + "elapsedMs": int((time.monotonic() - started_at) * 1000), + **_collect_dsv_menu_probe(page, next_text or text), + }, + ) + return + except Exception: + pass + time.sleep(0.5) + _report_debug_event( + "F", + "freight_rpa_worker.py:_click_dsv_menu_item:failed", + "[DEBUG] dsv menu item selection timed out", + { + "targetText": text, + "nextText": str(next_text or ""), + "elapsedMs": int((time.monotonic() - started_at) * 1000), + **_collect_dsv_menu_probe(page, next_text or text), + }, + ) + print(f"[dsv-debug] menu item missing target={text!r} {_debug_dsv_page_snapshot(page, target_text=text)}") + raise RuntimeError(f"DSV menu item was not found: {text}") + + +def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> None: + """ + 点击 DSV Report Group,并在需要时确认目标报表已经出现在菜单中。 + + 核心逻辑:Report Group 往往位于 Program 的二级菜单下,单次 click 很容易因为 hover 丢失而失效; + 这里在每次尝试后立刻检查 next_text,确保真正进入到报表项层级。 + + Args: + page: Playwright Page 对象。 + text: 当前 report group 文案。 + next_text: 预期出现的报表名称;为空时仅要求当前 group 点击成功。 + """ + text = str(text or "").strip() + if not text: + raise RuntimeError("DSV report group text is empty") + _report_debug_event( + "G", + "freight_rpa_worker.py:_click_dsv_report_group:entry", + "[DEBUG] entering dsv report group selection", + { + "targetText": text, + "nextText": str(next_text or ""), + "elapsedMs": 0, + **_collect_dsv_menu_probe(page, text), + }, + ) + text_literal = json.dumps(text) + started_at = time.monotonic() + for selector in ( + f"#report-mega-legacy :text-is({text_literal})", + f".mega-dropdown-menu :text-is({text_literal})", + f".dropdown-menu :text-is({text_literal})", + ): + try: + locator = page.locator(selector).first + locator.wait_for(state="visible", timeout=10_000) + for action in ("hover", "click", "force-click", "evaluate", "enter", "space"): + try: + if action == "hover": + locator.hover(timeout=1_500) + time.sleep(0.2) + continue + elif action == "click": + locator.click(timeout=1_500) + elif action == "force-click": + locator.click(timeout=1_500, force=True) + elif action == "evaluate": + locator.evaluate("(node) => node.click()") + elif action == "enter": + locator.press("Enter", timeout=1_500) + else: + locator.press("Space", timeout=1_500) + except Exception: + continue + _report_debug_event( + "G", + "freight_rpa_worker.py:_click_dsv_report_group:attempt", + "[DEBUG] dsv report group attempt dispatched", + { + "targetText": text, + "nextText": str(next_text or ""), + "selector": selector, + "action": action, + "elapsedMs": int((time.monotonic() - started_at) * 1000), + **_collect_dsv_menu_probe(page, next_text or text), + }, + ) + if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500): + _report_debug_event( + "G", + "freight_rpa_worker.py:_click_dsv_report_group:success", + "[DEBUG] dsv report group selection considered successful", + { + "targetText": text, + "nextText": str(next_text or ""), + "selector": selector, + "action": action, + "elapsedMs": int((time.monotonic() - started_at) * 1000), + **_collect_dsv_menu_probe(page, next_text or text), + }, + ) + return + except Exception: + pass + _report_debug_event( + "G", + "freight_rpa_worker.py:_click_dsv_report_group:failed", + "[DEBUG] dsv report group selection timed out", + { + "targetText": text, + "nextText": str(next_text or ""), + **_collect_dsv_menu_probe(page, next_text or text), + }, + ) + print(f"[dsv-debug] report group missing target={text!r} {_debug_dsv_page_snapshot(page, target_text=text)}") + raise RuntimeError(f"DSV report group was not found: {text}") + + +def _click_dsv_view_report(page: Any) -> None: + """ + 点击 SSRS 参数页 View Report。 + 核心逻辑:在各 frame 内轮询 ReportViewer 固定控件 ID 与通用按钮选择器,挂载后尝试多种点击方式。 + """ + selectors = ( + "#ReportViewerMain_ctl08_ctl00", + 'input[id^="ReportViewerMain_"][value="View Report"]', + 'input[type="submit"][value="View Report"]', + 'input[value="View Report"]', + 'button:has-text("View Report")', + ) + _debug_dsv_stage(page, "view-report-before-click", target_text="View Report") + wait_ms = max(15_000, int(_env("FREIGHT_RPA_DSV_VIEW_REPORT_WAIT_MS", "30000") or "30000")) + deadline = time.monotonic() + (wait_ms / 1000) + while time.monotonic() < deadline: + for frame in page.frames: + for selector in selectors: + try: + locator = frame.locator(selector).first + locator.wait_for(state="attached", timeout=1_000) + click_attempts = ("click", "enter", "space", "evaluate-click", "request-submit") + for attempt in click_attempts: + try: + try: + locator.scroll_into_view_if_needed(timeout=1_000) + except Exception: + pass + if attempt == "click": + locator.click(timeout=2_000, force=True) + elif attempt == "enter": + locator.press("Enter", timeout=1_500) + elif attempt == "space": + locator.press("Space", timeout=1_500) + elif attempt == "evaluate-click": + locator.evaluate( + """ + (target) => { + target.click(); + target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window })); + target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window })); + target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); + } + """ + ) + else: + locator.evaluate( + """ + (target) => { + if (target.form && typeof target.form.requestSubmit === 'function') { + target.form.requestSubmit(target); + } else if (target.form) { + target.form.submit(); + } else { + target.click(); + } + } + """ + ) + except Exception: + continue + submit_deadline = time.monotonic() + 4 + while time.monotonic() < submit_deadline: + if _dsv_report_submission_started(frame, locator): + print(f"[dsv] view report submitted via selector={selector!r} attempt={attempt}") + _debug_dsv_stage(page, f"view-report-after-click-{attempt}", target_text="View Report") + return + time.sleep(0.3) + except Exception: + pass + time.sleep(0.3) + print(f"[dsv-debug] view report missing {_debug_dsv_page_snapshot(page, target_text='View Report')}") + raise RuntimeError("DSV View Report button was not found") + + +def _is_dsv_reports_menu_open(page: Any) -> bool: + """ + 判断 DSV Reports 下拉是否已真正展开,而不是仅仅点到了导航按钮。 + + 核心逻辑:优先检查 `#report-mega-legacy` 上的 `show/open/aria-expanded` 状态, + 再兜底检查常见下拉容器里是否出现可见菜单项,避免“点击成功但菜单没开”的误判。 + """ + for selector in ( + "#report-mega-legacy.show", + "#report-mega-legacy.open", + "#report-mega-legacy[aria-expanded='true']", + "#report-mega-legacy .mega-dropdown-menu.show", + "#report-mega-legacy .dropdown-menu.show", + ".mega-dropdown-menu.show", + ".dropdown-menu.show", + ): + try: + if page.locator(selector).first.is_visible(timeout=150): + return True + except Exception: + pass + for selector in ( + "#report-mega-legacy .dropdown-item", + ".mega-dropdown-menu a.dropdown-item", + ".dropdown-menu a.dropdown-item", + ): + try: + locator = page.locator(selector).first + if locator.is_visible(timeout=150): + return True + except Exception: + pass + return False + + +def _click_dsv_reports_menu(page: Any) -> None: + started_at = time.monotonic() + # #region debug-point B:reports-click-entry + _report_debug_event( + "B", + "freight_rpa_worker.py:_click_dsv_reports_menu:entry", + "[DEBUG] entering reports click flow", + {"elapsedMs": 0, **_collect_dsv_reports_probe(page)}, + ) + # #endregion + click_selectors = ( + "#report-mega-legacy > a.dropdown-toggle.nav-link", + "#report-mega-legacy a.dropdown-toggle", + "#report-mega-legacy a.nav-link", + "nav a:has-text('Reports')", + "a.nav-link:has-text('Reports')", + ) + click_roots = [page, *list(getattr(page, "frames", []))] + for selector in click_selectors: + for root in click_roots: + try: + locator = root.locator(selector).first + locator.wait_for(state="attached", timeout=5_000) + except Exception: + continue + # [STEP 1] Reports 打开优先走真实 click,避免先 hover 白等一轮再退回 click。 + for action_name in ("click", "evaluate", "enter", "space", "hover"): + try: + locator.scroll_into_view_if_needed(timeout=2_000) + except Exception: + pass + try: + if action_name == "hover": + locator.hover(timeout=2_000) + elif action_name == "click": + locator.click(timeout=2_000, force=True) + elif action_name == "evaluate": + locator.evaluate( + """ + (target) => { + target.click(); + target.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, cancelable: true, view: window })); + target.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true, cancelable: true, view: window })); + target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window })); + target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window })); + target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); + } + """ + ) + elif action_name == "enter": + locator.press("Enter", timeout=1_500) + else: + locator.press("Space", timeout=1_500) + except Exception: + continue + # #region debug-point B:reports-click-attempt + _report_debug_event( + "B", + "freight_rpa_worker.py:_click_dsv_reports_menu:attempt", + "[DEBUG] reports click attempt dispatched", + { + "selector": selector, + "action": action_name, + **_collect_dsv_reports_probe(page), + }, + ) + # #endregion + post_action_wait_seconds = 0.6 if action_name == "hover" else 1.2 + action_deadline = time.monotonic() + post_action_wait_seconds + while time.monotonic() < action_deadline: + if _is_dsv_reports_menu_open(page): + print(f"[dsv] reports expanded via {action_name} selector={selector!r}") + _debug_dsv_stage(page, f"reports-expanded-{action_name}", target_text="Reports") + # #region debug-point D:reports-expanded + _report_debug_event( + "D", + "freight_rpa_worker.py:_click_dsv_reports_menu:expanded", + "[DEBUG] reports menu expanded after click attempt", + { + "selector": selector, + "action": action_name, + "elapsedMs": int((time.monotonic() - started_at) * 1000), + **_collect_dsv_reports_probe(page), + }, + ) + # #endregion + return + time.sleep(0.2) + print(f"[dsv-debug] reports menu missing {_debug_dsv_page_snapshot(page, target_text='Reports')}") + # #region debug-point C:reports-click-failed + _report_debug_event( + "C", + "freight_rpa_worker.py:_click_dsv_reports_menu:failed", + "[DEBUG] reports menu click flow exhausted without expansion", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)}, + ) + # #endregion + raise RuntimeError("DSV Reports menu was not found") +def _wait_for_dsv_reports_nav_stable(page: Any, *, timeout_ms: int | None = None) -> None: + """ + 在首页 ready 之后,继续等待 Reports 导航进入可稳定交互态。 + + 核心逻辑:首页首屏刚渲染完成时,Reports 虽然已经可见,但 hover/click 仍可能被吞掉; + 这里要求导航链接连续多次保持可见,降低“刚进首页就急着点”的误触发概率。 + """ + wait_ms = timeout_ms if timeout_ms is not None else 8_000 + selectors = ( + "#report-mega-legacy > a.dropdown-toggle.nav-link", + "#report-mega-legacy a.dropdown-toggle", + "#report-mega-legacy a.nav-link", + ) + deadline = time.monotonic() + (wait_ms / 1000) + stable_hits = 0 + started_at = time.monotonic() + # #region debug-point L:reports-nav-stable-entry + _report_debug_event( + "L", + "freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:entry", + "[DEBUG] waiting for dsv reports nav stable", + {"timeoutMs": wait_ms, **_collect_dsv_reports_probe(page)}, + ) + # #endregion + while time.monotonic() < deadline: + visible = False + click_roots = [page, *list(getattr(page, "frames", []))] + for selector in selectors: + for root in click_roots: + try: + locator = root.locator(selector).first + if locator.is_visible(timeout=200): + visible = True + break + except Exception: + pass + if visible: + break + if visible: + stable_hits += 1 + if stable_hits >= 3: + # #region debug-point L:reports-nav-stable-success + _report_debug_event( + "L", + "freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:success", + "[DEBUG] dsv reports nav considered stable", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)}, + ) + # #endregion + return + else: + stable_hits = 0 + time.sleep(0.4) + # #region debug-point L:reports-nav-stable-timeout + _report_debug_event( + "L", + "freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:timeout", + "[DEBUG] dsv reports nav did not become stable in time", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)}, + ) + # #endregion + + +def _wait_for_dsv_reports_open(page: Any, *, timeout_ms: int | None = None) -> None: + """ + 等待 Reports 下拉真正展开。 + + 核心逻辑:菜单导航偶发存在 hover/click 已触发但 DOM 尚未展开的情况; + 这里统一以 `_is_dsv_reports_menu_open()` 为成功判据,避免“看起来点了,实际没开”。 + """ + wait_ms = timeout_ms if timeout_ms is not None else 15_000 + deadline = time.monotonic() + (wait_ms / 1000) + while time.monotonic() < deadline: + if _is_dsv_reports_menu_open(page): + _debug_dsv_stage(page, "reports-open-confirmed", target_text="Reports") + # #region debug-point D:reports-open-confirmed + _report_debug_event( + "D", + "freight_rpa_worker.py:_wait_for_dsv_reports_open:confirmed", + "[DEBUG] reports open confirmed", + _collect_dsv_reports_probe(page), + ) + # #endregion + return + time.sleep(0.3) + _debug_dsv_stage(page, "reports-open-timeout", target_text="Reports") + # #region debug-point D:reports-open-timeout + _report_debug_event( + "D", + "freight_rpa_worker.py:_wait_for_dsv_reports_open:timeout", + "[DEBUG] reports open confirmation timed out", + _collect_dsv_reports_probe(page), + ) + # #endregion + raise RuntimeError("DSV Reports menu did not expand") + + +def _wait_for_dsv_report_form_ready(page: Any, report_name: str, *, timeout_ms: int | None = None) -> None: + """ + 等待报表表单页稳定可操作。 + + 核心逻辑:选择 Program / Group / Report 后,不立即假设已进入表单页; + 优先要求 `View Report` 按钮出现,同时满足“报表标题文本已出现”或“报表 shell/frame 已挂载”, + 这样既能避免顺序错乱,也不会因为标题文本稍晚刷新而额外空等数秒。 + """ + wait_ms = timeout_ms if timeout_ms is not None else max( + 60_000, int(_env("FREIGHT_RPA_DSV_REPORT_FORM_TIMEOUT_MS", "60000") or "60000") + ) + deadline = time.monotonic() + (wait_ms / 1000) + started_at = time.monotonic() + normalized_report = str(report_name or "").strip().lower() + last_probe_signature: tuple[bool, bool, bool] | None = None + last_probe_logged_at = 0.0 + _report_debug_event( + "H", + "freight_rpa_worker.py:_wait_for_dsv_report_form_ready:entry", + "[DEBUG] waiting for dsv report form ready", + { + "reportName": str(report_name or ""), + **_collect_dsv_menu_probe(page, report_name or "View Report"), + }, + ) + while time.monotonic() < deadline: + view_report_visible = False + try: + if _wait_for_visible_selector( + page, + "", + ( + 'input[id^="ReportViewerMain_"][value="View Report"]', + 'input[type="submit"][value="View Report"]', + 'input[value="View Report"]', + 'button:has-text("View Report")', + ), + timeout_ms=1_000, + ) is not None: + view_report_visible = True + except Exception: + view_report_visible = False + report_title_visible = False + if normalized_report: + for frame in page.frames: + try: + body = frame.locator("body").inner_text(timeout=500).lower() + except Exception: + body = "" + if normalized_report in body: + report_title_visible = True + break + form_shell_ready = _has_dsv_report_form_shell(page) + probe_signature = (view_report_visible, report_title_visible, form_shell_ready) + now = time.monotonic() + if probe_signature != last_probe_signature or (now - last_probe_logged_at) >= 2.0: + print( + "[dsv-report-form-probe] " + f"elapsedMs={int((now - started_at) * 1000)} " + f"viewReportVisible={view_report_visible} " + f"reportTitleVisible={report_title_visible} " + f"formShellReady={form_shell_ready} " + f"stateChanged={probe_signature != last_probe_signature}" + ) + _report_debug_event( + "H", + "freight_rpa_worker.py:_wait_for_dsv_report_form_ready:probe", + "[DEBUG] dsv report form probe state", + { + "reportName": str(report_name or ""), + "elapsedMs": int((now - started_at) * 1000), + "viewReportVisible": view_report_visible, + "reportTitleVisible": report_title_visible, + "formShellReady": form_shell_ready, + "stateChanged": probe_signature != last_probe_signature, + **_collect_dsv_menu_probe(page, report_name or "View Report"), + }, + ) + last_probe_signature = probe_signature + last_probe_logged_at = now + if form_shell_ready and report_title_visible and not view_report_visible: + remaining_ms = max(0, int((deadline - time.monotonic()) * 1000)) + if remaining_ms > 0: + if _wait_for_visible_selector( + page, + "", + ( + 'input[id^="ReportViewerMain_"][value="View Report"]', + 'input[type="submit"][value="View Report"]', + 'input[value="View Report"]', + 'button:has-text("View Report")', + ), + timeout_ms=min(remaining_ms, 45_000), + ) is not None: + view_report_visible = True + print( + "[dsv-report-form-probe] viewReport appeared after shell+title " + f"elapsedMs={int((time.monotonic() - started_at) * 1000)}" + ) + if view_report_visible and (report_title_visible or form_shell_ready or not normalized_report): + _report_debug_event( + "H", + "freight_rpa_worker.py:_wait_for_dsv_report_form_ready:success", + "[DEBUG] dsv report form became ready", + { + "reportName": str(report_name or ""), + "elapsedMs": int((time.monotonic() - started_at) * 1000), + "viewReportVisible": view_report_visible, + "reportTitleVisible": report_title_visible, + "formShellReady": form_shell_ready, + **_collect_dsv_menu_probe(page, report_name or "View Report"), + }, + ) + _debug_dsv_stage(page, "report-form-ready", target_text=report_name or "View Report") + return + time.sleep(0.5) + _report_debug_event( + "H", + "freight_rpa_worker.py:_wait_for_dsv_report_form_ready:timeout", + "[DEBUG] dsv report form wait timed out", + { + "reportName": str(report_name or ""), + "elapsedMs": int((time.monotonic() - started_at) * 1000), + "viewReportVisible": view_report_visible, + "reportTitleVisible": report_title_visible, + "formShellReady": _has_dsv_report_form_shell(page), + **_collect_dsv_menu_probe(page, report_name or "View Report"), + }, + ) + _debug_dsv_stage(page, "report-form-timeout", target_text=report_name or "View Report") + raise RuntimeError("DSV report form was not ready") + + + +# 公开 API +has_dsv_report_form_shell = _has_dsv_report_form_shell +dsv_report_submission_started = _dsv_report_submission_started +dsv_text_visible = _dsv_text_visible +dsv_dropdown_text_visible = _dsv_dropdown_text_visible +click_dsv_menu_item = _click_dsv_menu_item +click_dsv_report_group = _click_dsv_report_group +click_dsv_view_report = _click_dsv_view_report +is_dsv_reports_menu_open = _is_dsv_reports_menu_open +click_dsv_reports_menu = _click_dsv_reports_menu +wait_for_dsv_reports_nav_stable = _wait_for_dsv_reports_nav_stable +wait_for_dsv_reports_open = _wait_for_dsv_reports_open +wait_for_dsv_report_form_ready = _wait_for_dsv_report_form_ready diff --git a/scripts/rpa/dsv_report_export.py b/scripts/rpa/dsv_report_export.py new file mode 100644 index 00000000..ecc80090 --- /dev/null +++ b/scripts/rpa/dsv_report_export.py @@ -0,0 +1,1106 @@ +""" +scripts/rpa/dsv_report_export.py + +用途:DSV 360 填参、View Report、Excel 导出与 batch 编排。 +依赖:rpa_common、dsv_debug、dsv_navigation、dsv_session、dsv_report_parameters。 +逻辑:worker source_type=dsv360 时委托本模块。 +""" + +from __future__ import annotations + +import importlib.util +import sys +import time +from pathlib import Path +from typing import Any, Callable + +from rpa_common import browser_timeout_ms as _browser_timeout_ms +from rpa_common import click_visible_selector_or_text as _click_visible_selector_or_text +from rpa_common import click_visible_selector_or_text_in_root as _click_visible_selector_or_text_in_root +from rpa_common import env as _env +from rpa_common import visible_locator as _visible_locator +from rpa_common import visible_locator_in_root as _visible_locator_in_root +import dsv_debug +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_debug_event as _report_debug_event, +) +import dsv_navigation +from dsv_navigation import ( + click_dsv_menu_item as _click_dsv_menu_item, + click_dsv_report_group as _click_dsv_report_group, + click_dsv_reports_menu as _click_dsv_reports_menu, + click_dsv_view_report as _click_dsv_view_report, + wait_for_dsv_report_form_ready as _wait_for_dsv_report_form_ready, + wait_for_dsv_reports_nav_stable as _wait_for_dsv_reports_nav_stable, + wait_for_dsv_reports_open as _wait_for_dsv_reports_open, +) +import dsv_session +from dsv_session import ( + goto_dsv_entry_url as _goto_dsv_entry_url, + has_dsv_portal_shell as _has_dsv_portal_shell, + is_dsv_home_ready as _is_dsv_home_ready, + maybe_auto_login_dsv as _maybe_auto_login_dsv, + wait_for_dsv_home_ready as _wait_for_dsv_home_ready, +) + +def _click_dsv_export_excel(page: Any) -> None: + """ + 触发 DSV SSRS ReportViewer 的 Excel 导出。 + + 核心逻辑:结果页经常已经渲染出数据,但顶层页面并不会立即出现稳定的 `Export/Save` + 文案;因此优先在承载报表结果的 frame 内直接调用 ReportViewer 原生 + `exportReport('EXCELOPENXML')`,失败后只在选中的结果 frame 内退回到菜单点击式导出, + 避免误点到 portal 顶层或报表标题 frame 的同名元素。 + """ + # #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)}) + # #endregion + try: + _wait_for_dsv_report_result_ready(page, min(_browser_timeout_ms(), 20_000)) + except TypeError: + _wait_for_dsv_report_result_ready(page) + # #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)}) + # #endregion + + selected_frame = _find_dsv_report_result_frame(page) + # #region debug-point H4:selected-report-frame + if selected_frame is not None: + try: + _selected_name = str(selected_frame[1].name or "") + except Exception: + _selected_name = "" + try: + _selected_url = str(selected_frame[1].url or "") + except Exception: + _selected_url = "" + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:selected-frame", + "[DEBUG] selected report frame before export fallback", + { + "frameIndex": selected_frame[0], + "frameName": _selected_name, + "frameUrl": _selected_url[:300], + "state": selected_frame[2], + }, + ) + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:control-probe", + "[DEBUG] sampled export-related controls in selected report frame", + _probe_dsv_report_export_controls(selected_frame[1]), + ) + else: + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:selected-frame", + "[DEBUG] no report frame selected before export fallback", + {"frameCount": len(page.frames)}, + ) + # #endregion + frame_order: list[tuple[int, Any]] = ( + [(selected_frame[0], selected_frame[1])] + if selected_frame is not None + else list(enumerate(page.frames)) + ) + + for frame_index, frame in frame_order: + try: + direct_exported = bool( + frame.evaluate( + """ + () => { + const visible = (node) => { + if (!node) return false; + const style = window.getComputedStyle(node); + const rect = node.getBoundingClientRect(); + return style && style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0; + }; + if (typeof exportReport === 'function') { + exportReport('EXCELOPENXML'); + return true; + } + const win = window; + if (win && typeof win.exportReport === 'function') { + win.exportReport('EXCELOPENXML'); + return true; + } + const excelLink = Array.from(document.querySelectorAll('a[onclick], button[onclick], input[onclick], [role="button"][onclick]')) + .find((node) => String(node.getAttribute('onclick') || '').includes("EXCELOPENXML") && visible(node)); + if (excelLink) { + excelLink.click(); + return true; + } + const exportSelect = Array.from(document.querySelectorAll('select')) + .find((node) => Array.from(node.options || []).some((option) => { + const text = String(option.text || '').toUpperCase(); + const value = String(option.value || '').toUpperCase(); + return text.includes('EXCEL') || value.includes('EXCELOPENXML'); + })); + if (exportSelect) { + const option = Array.from(exportSelect.options || []).find((item) => { + const text = String(item.text || '').toUpperCase(); + const value = String(item.value || '').toUpperCase(); + return text.includes('EXCEL') || value.includes('EXCELOPENXML'); + }); + if (option) { + exportSelect.value = option.value; + exportSelect.dispatchEvent(new Event('change', { bubbles: true })); + exportSelect.dispatchEvent(new Event('input', { bubbles: true })); + return true; + } + } + return false; + } + """ + ) + ) + # #region debug-point H3:direct-export-attempt + _emit_debug_event( + "pre-fix", + "H3", + "freight_rpa_worker.py:_click_dsv_export_excel:direct-export-attempt", + "[DEBUG] direct export attempt finished", + {"frameIndex": frame_index, "directExported": direct_exported}, + ) + # #endregion + if direct_exported: + return + except Exception: + # #region debug-point H3:direct-export-exception + _emit_debug_event( + "pre-fix", + "H3", + "freight_rpa_worker.py:_click_dsv_export_excel:direct-export-exception", + "[DEBUG] direct export attempt raised exception", + {"frameIndex": frame_index}, + ) + # #endregion + pass + + # #region debug-point H4:direct-export-fallback + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:fallback", + "[DEBUG] direct export not available; fallback to export menu", + {"frameCount": len(page.frames), "selectedFrameIndex": selected_frame[0] if selected_frame else None}, + ) + # #endregion + frame_root = selected_frame[1] if selected_frame else page + export_menu_selector = _env("FREIGHT_RPA_DSV_EXPORT_MENU_SELECTOR") or ",".join( + ( + 'a[title="Export drop down menu"]', + 'button[title="Export drop down menu"]', + '[id$="_ctl04_ctl00_ButtonLink"]', + '[aria-label="Export drop down menu"]', + ) + ) + excel_export_selector = _env("FREIGHT_RPA_DSV_EXCEL_EXPORT_SELECTOR") or ",".join( + ( + 'a[title="Excel"]', + 'button[title="Excel"]', + 'a[onclick*="EXCELOPENXML"]', + 'button[onclick*="EXCELOPENXML"]', + 'a[href*="EXCELOPENXML"]', + ) + ) + legacy_selector = _env("FREIGHT_RPA_DSV_EXPORT_SELECTOR") + if legacy_selector: + locator = _visible_locator_in_root(frame_root, legacy_selector) + if locator is not None: + locator.click(timeout=_browser_timeout_ms()) + else: + page.locator(legacy_selector).first.click(timeout=_browser_timeout_ms()) + else: + export_menu_clicked = _click_visible_selector_or_text_in_root( + frame_root, + export_menu_selector, + ("file_download", "Save", "Export"), + ) or ( + selected_frame is None + and _click_visible_selector_or_text( + page, + "FREIGHT_RPA_DSV_EXPORT_MENU_SELECTOR", + ("file_download", "Save", "Export"), + ) + ) + # #region debug-point H4:export-menu-result + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:export-menu-result", + "[DEBUG] export menu click result", + { + "clicked": export_menu_clicked, + "selectedFrameIndex": selected_frame[0] if selected_frame else None, + }, + ) + # #endregion + if not export_menu_clicked: + snapshot = _debug_dsv_page_snapshot(page, target_text="Export") + # #region debug-point H4:export-menu-missing + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:export-menu-missing", + "[DEBUG] export menu not found in selected frame", + {"selectedFrameIndex": selected_frame[0] if selected_frame else None, "snapshot": snapshot[:2000]}, + ) + # #endregion + print(f"[dsv-debug] export menu missing {snapshot}") + raise RuntimeError("DSV report export menu was not found") + time.sleep(0.5) + + excel_option_clicked = _click_visible_selector_or_text_in_root( + frame_root, + excel_export_selector, + ("Excel", "EXCELOPENXML"), + ) or ( + selected_frame is None + and _click_visible_selector_or_text( + page, + "FREIGHT_RPA_DSV_EXCEL_EXPORT_SELECTOR", + ("Excel", "EXCELOPENXML"), + ) + ) + if not excel_option_clicked: + forced_menu_opened = _force_open_dsv_export_menu(frame_root, export_menu_selector) + # #region debug-point H4:export-menu-force-open + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:export-menu-force-open", + "[DEBUG] forced export menu open attempt finished", + { + "opened": forced_menu_opened, + "selectedFrameIndex": selected_frame[0] if selected_frame else None, + }, + ) + # #endregion + if forced_menu_opened: + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:post-force-control-probe", + "[DEBUG] sampled controls after forced export menu open", + _probe_dsv_report_export_controls(frame_root), + ) + excel_option_clicked = _click_visible_selector_or_text_in_root( + frame_root, + excel_export_selector, + ("Excel", "EXCELOPENXML"), + ) + if excel_option_clicked: + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:excel-option-result", + "[DEBUG] excel option click result", + {"clicked": True, "selector": "post-force-open", "selectedFrameIndex": selected_frame[0] if selected_frame else None}, + ) + return + for excel_selector in ( + 'a.ActiveLink[title="Excel"]', + 'a[title="Excel"]', + 'a[onclick*="EXCELOPENXML"]', + ): + locator = _visible_locator_in_root(frame_root, excel_selector) + if locator is None and selected_frame is None: + locator = _visible_locator(page, excel_selector) + if locator is not None: + locator.click(timeout=3_000, force=True) + # #region debug-point H4:excel-option-result + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:excel-option-result", + "[DEBUG] excel option click result", + {"clicked": True, "selector": excel_selector, "selectedFrameIndex": selected_frame[0] if selected_frame else None}, + ) + # #endregion + return + snapshot = _debug_dsv_page_snapshot(page, target_text="Excel") + # #region debug-point H4:excel-option-missing + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:excel-option-missing", + "[DEBUG] excel option not found after export menu", + {"selectedFrameIndex": selected_frame[0] if selected_frame else None, "snapshot": snapshot[:2000]}, + ) + # #endregion + print(f"[dsv-debug] excel export option missing {snapshot}") + raise RuntimeError("DSV Excel export option was not found") + # #region debug-point H4:excel-option-result + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_dsv_export_excel:excel-option-result", + "[DEBUG] excel option click result", + {"clicked": True, "selector": "fallback-text-or-selector", "selectedFrameIndex": selected_frame[0] if selected_frame else None}, + ) + # #endregion + + +def _get_dsv_report_result_state(frame: Any) -> dict[str, bool]: + """ + 读取 DSV SSRS 结果 frame 的当前状态。 + + 核心逻辑:真实页面里“结果表头已出现”与“报表真正渲染完成”并不同步, + 这里统一抽象为 `asyncWait / exportReady / excelReady / bodyReady / directExportReady` + 五个布尔量,供等待逻辑和导出逻辑复用。 + """ + try: + state = frame.evaluate( + """ + () => { + const visible = (node) => { + if (!node) return false; + const style = window.getComputedStyle(node); + const rect = node.getBoundingClientRect(); + return style && style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0; + }; + const body = String(document.body?.innerText || ''); + const normalizedBody = body.toLowerCase(); + const hasVisible = (selectors) => selectors.some((selector) => + Array.from(document.querySelectorAll(selector)).some((node) => visible(node)) + ); + const exportReady = hasVisible([ + 'a[title="Export"]', + 'button[title="Export"]', + '[aria-label="Export"]', + 'a[title="Save"]', + 'button[title="Save"]', + 'a[onclick*="ShowExport"]', + 'button[onclick*="ShowExport"]', + 'a[onclick*="export"]', + 'button[onclick*="export"]', + ]); + const excelReady = hasVisible([ + 'a[title="Excel"]', + 'button[title="Excel"]', + '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 bodyReady = bodyScore > 0; + const asyncWait = [ + 'loading', + 'please wait', + 'generating', + 'processing', + 'retrieving', + ].some((token) => normalizedBody.includes(token)); + const directExportReady = typeof exportReport === 'function' || + (window && typeof window.exportReport === 'function'); + return { asyncWait, exportReady, excelReady, bodyReady, bodyScore, directExportReady }; + } + """ + ) + except Exception: + state = {} + return { + "asyncWait": bool((state or {}).get("asyncWait")), + "exportReady": bool((state or {}).get("exportReady")), + "excelReady": bool((state or {}).get("excelReady")), + "bodyReady": bool((state or {}).get("bodyReady")), + "bodyScore": int((state or {}).get("bodyScore") or (3 if (state or {}).get("bodyReady") else 0)), + "directExportReady": bool((state or {}).get("directExportReady")), + } + + +def _probe_dsv_report_export_controls(frame: Any) -> dict[str, Any]: + """ + 采集 DSV SSRS 结果 frame 内的导出相关控件特征。 + + 核心逻辑:真实页面的导出入口未必直接显示为 Export/Save 文案,因此在运行时 + 抽样可见 a/button/input/select/option,记录 title/aria-label/value/onclick 等属性, + 用于后续基于真实 DOM 证据收敛选择器。 + """ + try: + return frame.evaluate( + """ + () => { + const visible = (node) => { + if (!node) return false; + const style = window.getComputedStyle(node); + const rect = node.getBoundingClientRect(); + return style && style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0; + }; + const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim(); + const pick = (node) => ({ + tag: String(node.tagName || '').toLowerCase(), + id: String(node.id || ''), + name: String(node.getAttribute('name') || ''), + title: String(node.getAttribute('title') || ''), + ariaLabel: String(node.getAttribute('aria-label') || ''), + value: String(node.getAttribute('value') || ''), + text: textOf(node).slice(0, 120), + onclick: String(node.getAttribute('onclick') || '').slice(0, 200), + href: String(node.getAttribute('href') || '').slice(0, 200), + }); + const controls = Array.from(document.querySelectorAll('a, button, input, select, option, img, span[title], div[title]')) + .filter((node) => visible(node) || node.tagName === 'OPTION') + .map((node) => pick(node)) + .filter((item) => item.text || item.title || item.ariaLabel || item.value || item.onclick || item.href || item.id || item.name) + .slice(0, 80); + const exportHints = controls.filter((item) => { + const haystack = [item.text, item.title, item.ariaLabel, item.value, item.onclick, item.href, item.id, item.name] + .join(' ') + .toLowerCase(); + return ['export', 'excel', 'openxml', 'save', 'csv', 'download', 'page width', 'whole page', 'find', 'next'].some((token) => haystack.includes(token)); + }).slice(0, 40); + const windowKeys = Object.keys(window || {}) + .filter((key) => /export|reportviewer|rv|excel/i.test(key)) + .slice(0, 40); + return { + exportHints, + windowKeys, + bodySnippet: textOf(document.body).slice(0, 600), + }; + } + """ + ) + except Exception as exc: + return {"probeError": str(exc)[:300]} + + +def _force_open_dsv_export_menu(root: Any, export_menu_selector: str) -> bool: + """ + 在 SSRS ReportViewer 中强制展开导出下拉菜单。 + + 核心逻辑:真实 DSV 页面里 `Export drop down menu` 按钮即便 locator.click 成功, + 也可能没有真正把下拉层渲染出来;这里补一轮 force click + JS mouse 事件 + 键盘事件, + 尽量把 ReportViewer 的导出菜单显式展开。 + """ + locator = _visible_locator_in_root(root, export_menu_selector) + if locator is None: + return False + try: + locator.click(timeout=2_000, force=True) + time.sleep(0.3) + return True + except Exception: + pass + try: + locator.evaluate( + """ + (node) => { + const fire = (type) => node.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window })); + fire('mouseover'); + fire('mouseenter'); + fire('mousedown'); + fire('mouseup'); + fire('click'); + } + """ + ) + time.sleep(0.3) + return True + except Exception: + pass + for key in ("Enter", " ", "ArrowDown"): + try: + locator.press(key, timeout=1_500) + time.sleep(0.2) + return True + except Exception: + pass + return False + + +def _find_dsv_report_result_frame(page: Any) -> tuple[int, Any, dict[str, Any]] | None: + """ + 选择真正承载 SSRS 报表结果表格的 frame。 + + 核心逻辑:首页/最近报表等 frame 也可能包含报表名文本,因此不能只看 `bodyReady`; + 这里先按 frame 身份硬匹配 `report-frame` / `.../S360Reports/Reports/Default.aspx`, + 命中后即使正文仍在 loading,也要持续盯住它等待;只有完全识别不到目标 frame 时, + 才退回到 `bodyScore` 启发式排序。 + """ + 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) + try: + frame_name = str(frame.name or "").strip().lower() + except Exception: + frame_name = "" + try: + frame_url = str(frame.url or "").strip().lower() + except Exception: + frame_url = "" + + identity_rank = 0 + if frame_name == "report-frame": + identity_rank = 2 + elif "/s360reports/reports/default.aspx" in frame_url: + identity_rank = 1 + + if identity_rank > 0: + hard_matches.append( + ( + frame_index, + frame, + state, + ( + identity_rank, + 1 if state["bodyReady"] else 0, + int(state["bodyScore"]), + 1 if state["excelReady"] else 0, + 1 if state["exportReady"] else 0, + ), + ) + ) + continue + + if not state["bodyReady"]: + continue + heuristic_matches.append( + ( + frame_index, + frame, + state, + ( + int(state["bodyScore"]), + 1 if state["excelReady"] else 0, + 1 if state["exportReady"] else 0, + 1 if state["directExportReady"] else 0, + ), + ) + ) + + if hard_matches: + best_hard = max(hard_matches, key=lambda item: item[3]) + return (best_hard[0], best_hard[1], best_hard[2]) + + if heuristic_matches: + best_heuristic = max(heuristic_matches, key=lambda item: item[3]) + return (best_heuristic[0], best_heuristic[1], best_heuristic[2]) + + return None + + +def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int) -> None: + """ + 等待 DSV 报表结果区进入“可导出”状态。 + + 核心逻辑:DSV 报表页点击 View Report 后,真实结果和导出工具栏都渲染在 frame 里, + 顶层页面未必能立即看到 `Export` 文案;因此这里改为轮询读取 frame 状态。 + 只要“目标结果 frame 的异步加载已结束 + 报表正文已出现”就允许继续尝试导出,因为真实站点上 + 导出能力有时直到点击工具栏/调用原生导出函数时才真正显式出现。 + """ + 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)}) + # #endregion + while time.monotonic() < deadline: + selected = _find_dsv_report_result_frame(page) + if selected is not None: + frame_index, _frame, state = selected + if state["bodyReady"] and not state["asyncWait"]: + # #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}, + ) + # #endregion + _debug_dsv_stage(page, "wait-report-ready-state", target_text="Export") + return + elapsed_second = int(deadline - time.monotonic()) + if elapsed_second != last_stage_second and elapsed_second % 3 == 0: + # #region debug-point H2:wait-report-poll + _emit_debug_event( + "pre-fix", + "H2", + "freight_rpa_worker.py:_wait_for_dsv_report_result_ready:poll", + "[DEBUG] report result still waiting", + {"secondsRemaining": elapsed_second, "frameCount": len(page.frames)}, + ) + # #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)}) + # #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: + """ + 向后兼容的包装器。 + + 核心逻辑:历史调用点仍使用 `_wait_dsv_report_ready`; + 实际实现统一委托给 `_wait_for_dsv_report_result_ready`,避免测试和主流程再次分叉。 + """ + _wait_for_dsv_report_result_ready(page, timeout_ms) + + +def _dsv_report_has_inventory_data_rows(page: Any) -> bool: + """ + 判断 DSV 库存报表结果页是否存在真实库存明细行。 + + 核心逻辑:只检查包含库存表头的 SSRS 明细表,不统计整页 `tr`。 + 当前报表无数据时该表通常只有 3 行;有数据时第 4 行开始出现明细行。 + """ + selected = _find_dsv_report_result_frame(page) + if selected is None: + return False + _frame_index, frame, _state = selected + try: + return bool( + frame.evaluate( + """ + () => { + const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim(); + const tables = Array.from(document.querySelectorAll('table')); + for (const table of tables) { + const text = normalize(table.innerText); + const isInventoryTable = + text.includes('Supplier ID') && + text.includes('AWS Sku') && + text.includes('Qty Available'); + if (!isInventoryTable) continue; + + const rows = Array.from(table.querySelectorAll('tbody > tr')); + if (rows.length <= 3) return false; + + const dataRows = rows.slice(3).filter((row) => { + const cells = Array.from(row.querySelectorAll('td')); + const line = normalize(cells.map((cell) => cell.innerText || '').join(' ')); + return line.length > 0; + }); + return dataRows.length > 0; + } + return false; + } + """ + ) + ) + except Exception as exc: + print(f"[dsv-report] inventory data row probe failed: {exc}", file=sys.stderr) + return False + + +def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: str | None) -> None: + """委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。""" + 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) + module.fill_dsv_filter_if_needed( + page, + selector_env, + label, + value, + env=_env, + browser_timeout_ms=_browser_timeout_ms, + debug_stage=_debug_dsv_stage, + ) + + +def _fill_dsv_multi_select( + page: Any, + selector_env: str, + label: str, + values: list[str], + *, + selectors: dict[str, str] | None = None, + select_all: bool = False, +) -> None: + """ + 填充 DSV 报表多选控件(multi_select)。 + 核心逻辑:显式配置 SSRS checkbox 下拉时委托 dsv_report_parameters; + 否则优先 select_option 多值,失败则展开控件后逐条点击 option/checkbox。 + """ + 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, + ): + return + selector = _env(selector_env) + if selector: + locator = page.locator(selector).first + try: + locator.select_option(label=cleaned, timeout=_browser_timeout_ms()) + print(f"[dsv-filter] {label} multi_select via select_option labels={cleaned!r}") + return + except Exception: + pass + try: + locator.select_option(value=cleaned, timeout=_browser_timeout_ms()) + print(f"[dsv-filter] {label} multi_select via select_option values={cleaned!r}") + return + except Exception: + pass + try: + locator.click(timeout=_browser_timeout_ms()) + for value in cleaned: + option = page.get_by_role("option", name=value).first + if option.is_visible(timeout=2_000): + option.click(timeout=_browser_timeout_ms()) + continue + page.get_by_text(value, exact=False).first.click(timeout=_browser_timeout_ms()) + print(f"[dsv-filter] {label} multi_select via click options={cleaned!r}") + return + 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) + + +def _fill_report_parameter(page: Any, parameter: dict[str, Any]) -> None: + """按 JSON parameters 配置填充 DSV 报表参数(single / multi_text / multi_select)。""" + if not isinstance(parameter, dict): + return + name = str(parameter.get("name") or "").strip() + mode = str(parameter.get("mode") or "single").strip().lower() + selector_env = str(parameter.get("selector_env") or "").strip() + values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()] + if not name or not values: + return + if mode == "multi_text": + joiner = str(parameter.get("joiner") or ",") + _fill_dsv_filter_if_needed(page, selector_env, name, joiner.join(values)) + return + if mode == "multi_select": + selectors = parameter.get("selectors") if isinstance(parameter.get("selectors"), dict) else None + _fill_dsv_multi_select( + page, + selector_env, + name, + values, + selectors=selectors, + select_all=bool(parameter.get("select_all", False)), + ) + return + _fill_dsv_filter_if_needed(page, selector_env, name, values[0]) + + +def _fill_report_parameters(page: Any, source: dict[str, Any]) -> None: + """填充 source.parameters;无 parameters 时回退 query 字段。""" + parameters = source.get("parameters") + if isinstance(parameters, list) and parameters: + for item in parameters: + _fill_report_parameter(page, item) + return + query = source.get("query") if isinstance(source.get("query"), dict) else {} + _fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code")) + _fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone")) + _fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code")) + + +def _dsv_entry_url_host(entry_url: str) -> str: + """从 entry_url 提取 host,用于判断当前 page 是否仍在同一 DSV 站点。""" + from urllib.parse import urlparse + + parsed = urlparse(str(entry_url or "").strip()) + return (parsed.netloc or "").lower() + + +def _is_dsv_on_entry_site(page: Any, entry_url: str) -> bool: + """当前 tab 是否已在目标 entry_url 对应 portal 域(非 auth 跳转页)。""" + host = _dsv_entry_url_host(entry_url) + if not host: + return False + try: + current_url = str(page.url or "").lower() + except Exception: + return False + if "auth.dbschenker.com" in current_url: + return False + return host in current_url + + +def _is_dsv_session_active(page: Any, entry_url: str) -> bool: + """ + 判定浏览器是否已在同一 entry_url 站点维持有效登录态。 + + 核心逻辑:batch 内 source_code 不同但 entry_url 一致时,后续步骤不应重复 OAuth; + 首页、portal 壳层、或 SSRS 参数页均视为 session 仍有效。 + """ + if not _is_dsv_on_entry_site(page, entry_url): + return False + if _is_dsv_home_ready(page) or _has_dsv_portal_shell(page): + return True + for frame in page.frames: + try: + frame_url = str(frame.url or "").lower() + except Exception: + frame_url = "" + if "/s360reports/reports/default.aspx" in frame_url: + return True + try: + if frame.locator("#ReportViewerMain").count() > 0: + return True + except Exception: + continue + return False + + +def _ensure_dsv_session(page: Any, entry_url: str) -> None: + """DSV 360 一次登录并等待首页/Reports 导航就绪。""" + if _is_dsv_session_active(page, entry_url): + print("[dsv] session already active on entry site, skip login") + _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) + _maybe_auto_login_dsv(page) + _wait_for_dsv_home_ready(page, timeout_ms=60_000) + _wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000) + + +def _reset_dsv_export_entry(page: Any, entry_url: str) -> None: + """ + 批量导出中 navigation 变化时回到 portal 首页。 + 核心逻辑:同 entry_url 且 session 仍有效时不重复登录,仅回首页待命; + 同 navigation 连续导出请改用 _return_to_dsv_report_parameters。 + """ + print("[dsv] reset export entry before next source") + if _is_dsv_session_active(page, entry_url): + print("[dsv] same entry_url session active, skip re-login") + if not _is_dsv_home_ready(page): + _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) + _maybe_auto_login_dsv(page) + _wait_for_dsv_home_ready(page, timeout_ms=30_000) + _wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000) + + +def _dsv_navigation_signature(source: dict[str, Any]) -> tuple[str, str, str, str]: + """提取 DSV 报表 navigation 四元组,用于判断批量导出是否可复用参数页。""" + query = source.get("query") if isinstance(source.get("query"), dict) else {} + navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {} + return ( + str(query.get("program_group") or navigation.get("program_group") or "").strip(), + str(query.get("program_label") or navigation.get("program_label") or "").strip(), + str(query.get("report_group") or navigation.get("report_group") or "").strip(), + str(query.get("report_name") or navigation.get("report_name") or "").strip(), + ) + + +def _dsv_sources_share_navigation(previous: dict[str, Any] | None, current: dict[str, Any]) -> bool: + """连续 source 的 program/report 导航一致时,可跳过 portal 首页重进。""" + if not previous: + return False + prev_sig = _dsv_navigation_signature(previous) + curr_sig = _dsv_navigation_signature(current) + return bool(prev_sig == curr_sig and all(prev_sig)) + + +def _dsv_report_name(source: dict[str, Any]) -> str: + """从 source 解析报表名称。""" + query = source.get("query") if isinstance(source.get("query"), dict) else {} + navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {} + return str(query.get("report_name") or navigation.get("report_name") or "On Hand Inventory by Location") + + +def _find_dsv_report_parameter_frame(page: Any) -> Any | None: + """定位承载 SSRS ReportViewer 参数区的 report-frame。""" + for frame in page.frames: + try: + frame_url = str(frame.url or "").lower() + except Exception: + frame_url = "" + if "/s360reports/reports/default.aspx" in frame_url: + return frame + try: + if frame.locator("#ReportViewerMain").count() > 0: + return frame + except Exception: + continue + return None + + +def _return_to_dsv_report_parameters(page: Any, report_name: str) -> None: + """ + 导出完成后回到同一报表的参数页,仅改 Warehouse 后再次 View Report。 + 核心逻辑:reload report-frame 的 Default.aspx URL,避免 batch 同 navigation 时回 portal 首页。 + """ + frame = _find_dsv_report_parameter_frame(page) + if frame is None: + raise RuntimeError("DSV report parameter frame not found for reuse") + try: + report_url = str(frame.url or "").strip() + except Exception: + report_url = "" + if not report_url: + raise RuntimeError("DSV report parameter frame has empty url") + print("[dsv] reuse report parameter form via report-frame reload") + frame.goto(report_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) + try: + page.wait_for_load_state("networkidle", timeout=min(_browser_timeout_ms(), 8_000)) + except Exception: + pass + _wait_for_dsv_report_form_ready(page, report_name) + + +def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str: + """从 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) + + reports_selector = _env("FREIGHT_RPA_DSV_REPORTS_SELECTOR") + if reports_selector: + page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True) + else: + _click_dsv_reports_menu(page) + _wait_for_dsv_reports_open(page, timeout_ms=10_000) + + program_selector = _env("FREIGHT_RPA_DSV_PROGRAM_SELECTOR") + program_label = str(query.get("program_label") or navigation.get("program_label") or "") + if program_selector: + page.locator(program_selector).first.click(timeout=_browser_timeout_ms()) + else: + _click_dsv_menu_item(page, program_label, next_text=str(query.get("report_group") or navigation.get("report_group") or "Inventory")) + + report_group_selector = _env("FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR") + report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory") + 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("FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR") + if report_name_selector: + page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms()) + else: + _click_dsv_menu_item(page, report_name) + + _wait_for_dsv_report_form_ready(page, 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) + 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 RuntimeError("DSV report has no inventory data") + with page.expect_download(timeout=_browser_timeout_ms()) as download_info: + _click_dsv_export_excel(page) + return download_info.value + + +def _prepare_dsv_batch_export_step( + page: Any, + entry_url: str, + previous_source: dict[str, Any] | None, + source: dict[str, Any], + *, + index: int, +) -> bool: + """ + 批量导出单步前置:首条登录;同 navigation 复用参数页;否则回首页重导航。 + 同 entry_url 的 batch 内仅 index=0 可能触发完整登录,后续步骤 session 有效则跳过 OAuth。 + + Returns: + True 表示参数页已就绪且可 skip 完整菜单导航。 + """ + if index == 0: + _ensure_dsv_session(page, entry_url) + return False + if _dsv_sources_share_navigation(previous_source, source): + report_name = _dsv_report_name(source) + try: + _return_to_dsv_report_parameters(page, report_name) + print( + "[dsv-batch] reuse parameter form " + f"navigation={_dsv_navigation_signature(source)!r}" + ) + return True + except Exception as exc: + print(f"[dsv-batch] parameter reuse failed, fallback home reset: {exc}", file=sys.stderr) + _reset_dsv_export_entry(page, entry_url) + return False + + +def _export_dsv_inventory_source( + page: Any, + trigger: dict[str, Any], + source: dict[str, Any], + *, + skip_navigation: bool = False, +) -> Any: + """在已登录 DSV session 上导出单个 Warehouse 库存。""" + if not skip_navigation: + _navigate_dsv_to_report_form(page, source) + return _run_dsv_inventory_export_from_form(page, source) + + +# 公开 API +click_dsv_export_excel = _click_dsv_export_excel +get_dsv_report_result_state = _get_dsv_report_result_state +probe_dsv_report_export_controls = _probe_dsv_report_export_controls +force_open_dsv_export_menu = _force_open_dsv_export_menu +find_dsv_report_result_frame = _find_dsv_report_result_frame +wait_for_dsv_report_result_ready = _wait_for_dsv_report_result_ready +wait_dsv_report_ready = _wait_dsv_report_ready +dsv_report_has_inventory_data_rows = _dsv_report_has_inventory_data_rows +fill_dsv_filter_if_needed = _fill_dsv_filter_if_needed +fill_dsv_multi_select = _fill_dsv_multi_select +fill_report_parameter = _fill_report_parameter +fill_report_parameters = _fill_report_parameters +dsv_entry_url_host = _dsv_entry_url_host +is_dsv_on_entry_site = _is_dsv_on_entry_site +is_dsv_session_active = _is_dsv_session_active +ensure_dsv_session = _ensure_dsv_session +reset_dsv_export_entry = _reset_dsv_export_entry +dsv_navigation_signature = _dsv_navigation_signature +dsv_sources_share_navigation = _dsv_sources_share_navigation +dsv_report_name = _dsv_report_name +find_dsv_report_parameter_frame = _find_dsv_report_parameter_frame +return_to_dsv_report_parameters = _return_to_dsv_report_parameters +navigate_dsv_to_report_form = _navigate_dsv_to_report_form +run_dsv_inventory_export_from_form = _run_dsv_inventory_export_from_form +prepare_dsv_batch_export_step = _prepare_dsv_batch_export_step +export_dsv_inventory_source = _export_dsv_inventory_source diff --git a/scripts/rpa/dsv_report_parameters.py b/scripts/rpa/dsv_report_parameters.py index 8ab264db..147aec77 100644 --- a/scripts/rpa/dsv_report_parameters.py +++ b/scripts/rpa/dsv_report_parameters.py @@ -195,20 +195,28 @@ def _fill_input_via_script(root: Any, selector: str, value: str) -> bool: return False -def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, timeout_ms: int) -> bool: +def _fill_multi_value_parameter( + page: Any, + label: str, + values: list[str], + *, + timeout_ms: int, + config_override: dict[str, str] | None = None, + select_all: bool = False, +) -> bool: """ 填充 SSRS MultiValueParameterInputControl(Owner / PutawayZone)。 核心逻辑:展开 dropdown → 按 label 勾选/取消 checkbox → 关闭 dropdown。 """ - config = _DSV_REPORT_PARAM_DEFAULTS.get(label, {}) + 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()] - if not cleaned: + if not cleaned and not select_all: return False _, text_locator = _find_locator(page, config["text"]) - if text_locator is not None: + 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): @@ -233,15 +241,17 @@ def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, tim try: adjusted = root.evaluate( """ - ({ dropdownSelector, desiredValues, restrictToDesired }) => { + ({ dropdownSelector, desiredValues, restrictToDesired, selectAll }) => { const dropdown = document.querySelector(dropdownSelector); if (!dropdown) return false; const normalize = (text) => (text || '').replace(/\\s+/g, ' ').trim(); const labels = Array.from(dropdown.querySelectorAll('label')); let changed = false; + let selectAllClicked = false; + const entries = []; for (const labelNode of labels) { const text = normalize(labelNode.textContent); - if (!text || text === '(Select All)') continue; + if (!text) continue; let checkbox = null; const htmlFor = labelNode.getAttribute('for'); if (htmlFor) { @@ -251,14 +261,37 @@ def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, tim checkbox = labelNode.previousElementSibling; } if (!checkbox || checkbox.type !== 'checkbox') continue; - const shouldCheck = desiredValues.includes(text.toLowerCase()); - if (restrictToDesired) { - if (checkbox.checked !== shouldCheck) { + const isSelectAll = text === '(Select All)' || text.toLowerCase().includes('select all'); + entries.push({ text, checkbox, isSelectAll }); + if (selectAll && isSelectAll) { + if (!checkbox.checked) { checkbox.click(); changed = true; } - } else if (shouldCheck && !checkbox.checked) { - checkbox.click(); + selectAllClicked = true; + } + } + if (selectAll && !selectAllClicked) { + for (const entry of entries) { + if (!entry.isSelectAll && !entry.checkbox.checked) { + entry.checkbox.click(); + changed = true; + } + } + } + if (selectAll) { + return changed || entries.length > 0; + } + for (const entry of entries) { + if (entry.isSelectAll) continue; + const shouldCheck = desiredValues.includes(text.toLowerCase()); + if (restrictToDesired) { + if (entry.checkbox.checked !== shouldCheck) { + entry.checkbox.click(); + changed = true; + } + } else if (shouldCheck && !entry.checkbox.checked) { + entry.checkbox.click(); changed = true; } } @@ -269,10 +302,14 @@ def _fill_multi_value_parameter(page: Any, label: str, values: list[str], *, tim "dropdownSelector": config["dropdown"], "desiredValues": list(desired), "restrictToDesired": label == "PutawayZone", + "selectAll": select_all, }, ) if adjusted: - print(f"[dsv-filter] {label} multi_value checkboxes={cleaned!r}") + if select_all: + print(f"[dsv-filter] {label} multi_value select_all") + else: + print(f"[dsv-filter] {label} multi_value checkboxes={cleaned!r}") if toggle is not None: try: toggle.click(timeout=2_000, force=True) @@ -405,3 +442,35 @@ def fill_dsv_filter_if_needed( print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr) _debug(f"filter-failed-{label.lower()}", text) + + +def fill_dsv_multi_select_parameter( + page: Any, + label: str, + values: list[str], + *, + selectors: dict[str, str] | None = None, + select_all: bool = False, + browser_timeout_ms: Callable[[], int], +) -> bool: + """ + 填充由 YAML `mode: multi_select` 显式声明的 SSRS checkbox 下拉参数。 + 【AI 触发时机】:当 DSV 报表参数不是原生 select,而是 `txtValue + divDropDown + checkbox` + 组合控件时调用;例如 AWSAMS 的 Warehouse 下拉需要全选。 + """ + config_override = {"control": "multi_value"} + if selectors: + for key in ("text", "toggle", "dropdown"): + value = str(selectors.get(key) or "").strip() + if value: + config_override[key] = value + if not all(config_override.get(key) for key in ("text", "toggle", "dropdown")): + return False + return _fill_multi_value_parameter( + page, + label, + values, + timeout_ms=browser_timeout_ms(), + config_override=config_override, + select_all=select_all, + ) diff --git a/scripts/rpa/dsv_session.py b/scripts/rpa/dsv_session.py new file mode 100644 index 00000000..5ff26fce --- /dev/null +++ b/scripts/rpa/dsv_session.py @@ -0,0 +1,349 @@ +""" +scripts/rpa/dsv_session.py + +用途:DSV 360 portal 壳层检测、首页 Reports 导航就绪与 entry_url 打开。 +依赖:rpa_common、dsv_debug、dsv_auth(升级提示与登录后回调)。 +逻辑:dsv_navigation / dsv_debug 探针;dsv_report_export 在 ensure 前检测 session。 +""" + +from __future__ import annotations + +import sys +import time +from typing import Any, Callable + +from rpa_common import browser_timeout_ms as _browser_timeout_ms +from rpa_common import env as _env +from rpa_common import wait_for_visible_selector as _wait_for_visible_selector +import dsv_debug +from dsv_debug import ( + collect_dsv_reports_probe as _collect_dsv_reports_probe, + debug_dsv_stage as _debug_dsv_stage, + report_debug_event as _report_debug_event, +) + + +_DSV_REPORTS_NAV_SELECTORS: tuple[str, ...] = ( + "#report-mega-legacy", + "#report-mega-legacy > a.dropdown-toggle.nav-link", + "#report-mega-legacy a.dropdown-toggle", + "#report-mega-legacy a.nav-link", + "nav a:has-text('Reports')", + "a.nav-link:has-text('Reports')", +) + +def _iter_dsv_report_nav_locators(page: Any): + """在所有 frame 与顶层 page 中查找 Reports 顶栏相关 locator。""" + roots = [page, *list(getattr(page, "frames", []))] + for root in roots: + for selector in _DSV_REPORTS_NAV_SELECTORS: + try: + locator = root.locator(selector).first + if locator.count() > 0: + yield root, selector, locator + except Exception: + continue + +def _has_dsv_report_nav_attached(page: Any) -> bool: + """Reports 顶栏 DOM 是否已挂载(跨 frame + 文本 fallback)。""" + return next(_iter_dsv_report_nav_locators(page), None) is not None + +def _has_dsv_report_nav_usable(page: Any) -> bool: + """ + Reports 导航是否已可用于后续点击。 + 核心逻辑:用户肉眼看到首页时,顶栏 Reports 可能已 visible 但 #report-mega-legacy 计数仍为 0; + 因此同时接受 attached 与短超时 visible 探测。 + """ + for _, _, locator in _iter_dsv_report_nav_locators(page): + try: + if locator.is_visible(timeout=200): + return True + except Exception: + pass + return _has_dsv_report_nav_attached(page) + +def _is_dsv_on_portal_home(page: Any) -> bool: + """URL 已在 portal 且主页面已出现 Home/Favorites/Recent Reports 等内容。""" + try: + current_url = str(page.url or "").lower() + except Exception: + current_url = "" + if "auth.dbschenker.com" in current_url: + return False + if "s360.dbschenker.com" not in current_url: + return False + try: + body = str(page.locator("body").inner_text(timeout=1_000) or "").lower() + except Exception: + body = "" + return any(marker in body for marker in ("home favorites", "recent reports", "favorites")) + +def _wait_for_dsv_app_after_login( + page: Any, + timeout_ms: int | None = None, + on_portal_shell_seen: Callable[[], None] | None = None, +) -> bool: + """ + 等待 DSV 从登录链路切回 portal 壳层。 + + 核心逻辑:`Verifying compliance` 这类认证过渡页并不代表首页导航已经可操作; + 这里单独识别 auth/合规过渡态,避免在该阶段反复用长超时探测 `#report-mega-legacy`, + 从而把“认证收尾慢”和“Reports 菜单慢”混在一起。 + """ + import dsv_auth + + wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms() + deadline = time.monotonic() + (wait_ms / 1000) + last_debug_at = 0.0 + started_at = time.monotonic() + # #region debug-point J:wait-app-entry + _report_debug_event( + "J", + "freight_rpa_worker.py:_wait_for_dsv_app_after_login:entry", + "[DEBUG] waiting for dsv app shell after login", + {"timeoutMs": wait_ms, "url": page.url}, + ) + # #endregion + _debug_dsv_stage(page, "wait-app-start", target_text="Reports") + last_portal_home_log_at = 0.0 + portal_shell_callback_fired = False + while time.monotonic() < deadline: + now = time.monotonic() + current_url = str(page.url or "").lower() + auth_transition = False + try: + current_title = str(page.title() or "").lower() + except Exception: + current_title = "" + auth_transition = "auth.dbschenker.com" in current_url or "verifying compliance" in current_title + if now - last_debug_at >= 3: + elapsed = int((time.monotonic() - started_at) * 1000) + _debug_dsv_stage(page, f"wait-app-{elapsed // 1000}s", target_text="Reports") + last_debug_at = now + if _has_dsv_report_nav_usable(page): + if on_portal_shell_seen is not None: + on_portal_shell_seen() + _debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports") + _report_debug_event( + "J", + "freight_rpa_worker.py:_wait_for_dsv_app_after_login:success", + "[DEBUG] dsv reports nav usable after login", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, + ) + return True + if not auth_transition and _wait_for_visible_selector( + page, + "", + _DSV_REPORTS_NAV_SELECTORS, + timeout_ms=400, + ) is not None: + if on_portal_shell_seen is not None: + on_portal_shell_seen() + _debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports") + _report_debug_event( + "J", + "freight_rpa_worker.py:_wait_for_dsv_app_after_login:success", + "[DEBUG] dsv reports nav visible after login", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, + ) + return True + on_portal_home = _is_dsv_on_portal_home(page) + if on_portal_home and not auth_transition: + if on_portal_shell_seen is not None and not portal_shell_callback_fired: + on_portal_shell_seen() + portal_shell_callback_fired = True + if now - last_portal_home_log_at >= 2.0: + print( + "[dsv-home] portal home visible, waiting Reports nav " + f"elapsedMs={int((time.monotonic() - started_at) * 1000)} " + f"report_nav_attached={_has_dsv_report_nav_attached(page)} url={page.url!r}" + ) + last_portal_home_log_at = now + elif _has_dsv_portal_shell(page) and on_portal_shell_seen is not None and not portal_shell_callback_fired: + on_portal_shell_seen() + portal_shell_callback_fired = True + if auth_transition: + if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=250): + dsv_auth.dismiss_dsv_password_upgrade_prompt(page) + continue + # [STEP] 合规/认证过渡页仅用轻量短超时探测 Reports 导航,避免与首页长轮询混淆。 + _wait_for_visible_selector( + page, + "", + _DSV_REPORTS_NAV_SELECTORS, + timeout_ms=400, + ) + time.sleep(0.25) + continue + if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url: + if not _has_dsv_report_nav_usable(page) and dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=250): + dsv_auth.dismiss_dsv_password_upgrade_prompt(page) + continue + try: + page.wait_for_load_state("domcontentloaded", timeout=1_500) + except Exception: + pass + time.sleep(0.5) + _debug_dsv_stage(page, "wait-app-timeout", target_text="Reports") + # #region debug-point J:wait-app-timeout + _report_debug_event( + "J", + "freight_rpa_worker.py:_wait_for_dsv_app_after_login:timeout", + "[DEBUG] dsv app shell wait timed out", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, + ) + # #endregion + return False + +def _has_dsv_portal_shell(page: Any) -> bool: + """ + 判断 DSV portal 内容壳层是否已出现。 + + 核心逻辑:dashboard iframe 的欢迎语/Recent Reports 往往先于顶栏 `#report-mega-legacy` + 渲染完成;此函数用于记录 portal_shell_seen 时间点,但不应单独作为 home-ready 判据。 + """ + if _has_dsv_report_nav_attached(page): + return True + portal_markers = ("home favorites", "recent reports", "360 — your contract logistics portal") + roots = [page, *getattr(page, "frames", [])] + for root in roots: + try: + body = str(root.locator("body").inner_text(timeout=1_000) or "").lower() + except Exception: + body = "" + if any(marker in body for marker in portal_markers): + return True + return False + +def _is_dsv_home_ready(page: Any) -> bool: + """ + 判断 DSV 是否已经稳定进入首页导航态。 + + 核心逻辑:必须离开认证域名,且 Reports 导航已可用(跨 frame 探测); + 用户肉眼已在 portal 首页时,不再仅依赖顶层 #report-mega-legacy 计数。 + """ + if "auth.dbschenker.com" in page.url: + return False + return _has_dsv_report_nav_usable(page) + +def _wait_for_dsv_home_ready( + page: Any, + *, + timeout_ms: int | None = None, + on_portal_shell_seen: Callable[[], None] | None = None, +) -> None: + """ + 等待 DSV 首页真正稳定可操作。 + + 核心逻辑:登录和升级提示都可能导致页面短暂回跳;这里统一要求首页导航稳定出现, + 失败则直接在“首页阶段”报错,避免主流程跳步到 Reports/View Report。 + """ + import dsv_auth + + wait_ms = timeout_ms if timeout_ms is not None else 60_000 + started_at = time.monotonic() + # #region debug-point K:home-wait-entry + _report_debug_event( + "K", + "freight_rpa_worker.py:_wait_for_dsv_home_ready:entry", + "[DEBUG] entering dsv home ready wait", + {"timeoutMs": wait_ms, "url": page.url, **_collect_dsv_reports_probe(page)}, + ) + # #endregion + if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150): + dsv_auth.dismiss_dsv_password_upgrade_prompt(page) + if _is_dsv_home_ready(page): + if on_portal_shell_seen is not None: + on_portal_shell_seen() + _debug_dsv_stage(page, "home-ready", target_text="Reports") + # #region debug-point A:home-ready + _report_debug_event( + "A", + "freight_rpa_worker.py:_wait_for_dsv_home_ready:ready", + "[DEBUG] dsv home considered ready before wait loop", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)}, + ) + # #endregion + return + if _wait_for_dsv_app_after_login(page, timeout_ms=wait_ms, on_portal_shell_seen=on_portal_shell_seen): + if dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=150): + dsv_auth.dismiss_dsv_password_upgrade_prompt(page) + if _is_dsv_home_ready(page): + if on_portal_shell_seen is not None: + on_portal_shell_seen() + _debug_dsv_stage(page, "home-ready-after-wait", target_text="Reports") + # #region debug-point A:home-ready-after-wait + _report_debug_event( + "A", + "freight_rpa_worker.py:_wait_for_dsv_home_ready:ready_after_wait", + "[DEBUG] dsv home considered ready after app wait", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)}, + ) + # #endregion + return + _debug_dsv_stage(page, "home-not-ready", target_text="Reports") + # #region debug-point A:home-not-ready + _report_debug_event( + "A", + "freight_rpa_worker.py:_wait_for_dsv_home_ready:timeout", + "[DEBUG] dsv home was not ready before reports click", + {"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)}, + ) + # #endregion + raise RuntimeError("DSV home page was not ready after login") + +def _goto_dsv_entry_url(page: Any, entry_url: str) -> None: + """ + 打开 DSV entry_url;domcontentloaded 超时时若已跳转到 auth/portal 则继续。 + + 核心逻辑:s360 -> auth 重定向链可能超过单次 goto 默认超时,不应因此中断 batch。 + """ + try: + page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) + except Exception as exc: + message = str(exc).lower() + if "timeout" not in message: + raise + try: + current_url = str(page.url or "").lower() + except Exception: + current_url = "" + if any(token in current_url for token in ("auth.dbschenker.com", "s360.dbschenker.com")): + print( + "[dsv] entry goto domcontentloaded timeout, continue auth redirect " + f"url={page.url!r}" + ) + return + raise + + +# 公开 API +DSV_REPORTS_NAV_SELECTORS = _DSV_REPORTS_NAV_SELECTORS +goto_dsv_entry_url = _goto_dsv_entry_url +has_dsv_portal_shell = _has_dsv_portal_shell +has_dsv_report_nav_attached = _has_dsv_report_nav_attached +has_dsv_report_nav_usable = _has_dsv_report_nav_usable +is_dsv_home_ready = _is_dsv_home_ready +is_dsv_on_portal_home = _is_dsv_on_portal_home +iter_dsv_report_nav_locators = _iter_dsv_report_nav_locators +wait_for_dsv_app_after_login = _wait_for_dsv_app_after_login +wait_for_dsv_home_ready = _wait_for_dsv_home_ready + +# 向后兼容:登录 API 仍可从 dsv_session 引用 +from dsv_auth import ( # noqa: E402 + DSV_USERNAME_SELECTORS, + click_dsv_continue, + click_dsv_password_method, + dismiss_dsv_password_upgrade_prompt, + fill_dsv_password_page_fields, + fill_dsv_username, + find_dsv_password_locator, + has_dsv_human_check_prompt, + has_dsv_password_upgrade_prompt, + is_dsv_username_page, + looks_like_dsv_login_method_page, + maybe_auto_login_dsv, + submit_dsv_password_form, + wait_for_dsv_human_check_if_present, + wait_for_dsv_login_method_page, +) diff --git a/scripts/rpa/freight_rpa_worker.py b/scripts/rpa/freight_rpa_worker.py index 0c49137e..d0fdd93c 100644 --- a/scripts/rpa/freight_rpa_worker.py +++ b/scripts/rpa/freight_rpa_worker.py @@ -1,8 +1,8 @@ """ Freight RPA worker (PoC). -Polls trigger JSON files written by hxops and reports results back via Tool API callbacks. -Set FREIGHT_RPA_MOCK=true to simulate export/upload without a real freight UI. +轮询 trigger JSON → 按 source_type 调用 DSV/Crane driver → 回调 hxops Tool API。 +DSV 逻辑见 dsv_driver / dsv_session / dsv_navigation / dsv_report_export;Crane 见 crane_*。 Usage: python scripts/rpa/freight_rpa_worker.py @@ -43,6 +43,60 @@ from datetime import datetime from pathlib import Path from typing import Any, Callable, TextIO +import sys as _sys +_RPA_DIR = Path(__file__).resolve().parent +if str(_RPA_DIR) not in _sys.path: + _sys.path.insert(0, str(_RPA_DIR)) + +from rpa_common import ( # noqa: E402 + browser_timeout_ms as _browser_timeout_ms, + click_text as _click_text, + env as _env, + select_or_fill as _select_or_fill, + wait_for_visible_selector as _wait_for_visible_selector, +) +import dsv_debug # noqa: E402 +import dsv_driver # noqa: E402 +import dsv_navigation # noqa: E402 +import dsv_report_export # noqa: E402 +import dsv_session # noqa: E402 + +# 测试与 smoke 向后兼容 re-export +_maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv +_fill_dsv_username = dsv_session.fill_dsv_username +_click_dsv_continue = dsv_session.click_dsv_continue +_click_dsv_password_method = dsv_session.click_dsv_password_method +_fill_dsv_password_page_fields = dsv_session.fill_dsv_password_page_fields +_wait_for_dsv_human_check_if_present = dsv_session.wait_for_dsv_human_check_if_present +_wait_for_dsv_app_after_login = dsv_session.wait_for_dsv_app_after_login +_wait_for_dsv_login_method_page = dsv_session.wait_for_dsv_login_method_page +_is_dsv_username_page = dsv_session.is_dsv_username_page +_find_dsv_password_locator = dsv_session.find_dsv_password_locator +_submit_dsv_password_form = dsv_session.submit_dsv_password_form +_dismiss_dsv_password_upgrade_prompt = dsv_session.dismiss_dsv_password_upgrade_prompt +_wait_for_dsv_home_ready = dsv_session.wait_for_dsv_home_ready +_report_dsv_chain_stage = dsv_debug.report_dsv_chain_stage +_report_debug_event = dsv_debug.report_debug_event +_collect_dsv_reports_probe = dsv_debug.collect_dsv_reports_probe +_debug_dsv_stage = dsv_debug.debug_dsv_stage +_emit_debug_event = dsv_debug.emit_debug_event +_looks_like_dsv_login_method_page = dsv_session.looks_like_dsv_login_method_page +_has_dsv_human_check_prompt = dsv_session.has_dsv_human_check_prompt +_wait_for_dsv_reports_nav_stable = dsv_navigation.wait_for_dsv_reports_nav_stable +_ensure_dsv_session = dsv_report_export.ensure_dsv_session +_export_dsv_inventory_source = dsv_report_export.export_dsv_inventory_source +_prepare_dsv_batch_export_step = dsv_report_export.prepare_dsv_batch_export_step +_fill_dsv_filter_if_needed = dsv_report_export.fill_dsv_filter_if_needed +_click_dsv_reports_menu = dsv_navigation.click_dsv_reports_menu +_wait_for_dsv_report_form_ready = dsv_navigation.wait_for_dsv_report_form_ready +_click_dsv_view_report = dsv_navigation.click_dsv_view_report +_click_dsv_export_excel = dsv_report_export.click_dsv_export_excel +_wait_for_dsv_report_result_ready = dsv_report_export.wait_for_dsv_report_result_ready +_find_dsv_report_result_frame = dsv_report_export.find_dsv_report_result_frame +_get_dsv_report_result_state = dsv_report_export.get_dsv_report_result_state +_is_dsv_home_ready = dsv_session.is_dsv_home_ready +_has_dsv_password_upgrade_prompt = dsv_session.has_dsv_password_upgrade_prompt + try: from openpyxl import Workbook except ImportError: @@ -359,3569 +413,14 @@ def _require_playwright(): return sync_playwright, PlaywrightTimeoutError -def _browser_timeout_ms() -> int: - return max(5_000, int(_env("FREIGHT_RPA_BROWSER_TIMEOUT_MS", "60000") or "60000")) # #region debug-point H1:debug-reporter -def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None: - _payload = { - "sessionId": "dsv-export-stall", - "runId": run_id, - "hypothesisId": hypothesis_id, - "location": location, - "msg": msg, - "data": data or {}, - "ts": int(time.time() * 1000), - } - _url = "http://127.0.0.1:7778/event" - _env_file = Path(".dbg/dsv-export-stall.env") - try: - if _env_file.is_file(): - _content = _env_file.read_text(encoding="utf-8") - _url = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SERVER_URL=")), _url) - _payload["sessionId"] = next((line.split("=", 1)[1] for line in _content.splitlines() if line.startswith("DEBUG_SESSION_ID=")), _payload["sessionId"]) - urllib.request.urlopen( - urllib.request.Request( - _url, - data=json.dumps(_payload, ensure_ascii=False).encode("utf-8"), - headers={"Content-Type": "application/json"}, - ), - timeout=1.5, - ).read() - except Exception: - pass # #endregion -def _click_text(page: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> None: - timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms() - text_literal = json.dumps(text) - for selector in ( - f"a.dropdown-item:has-text({text_literal})", - f".dropdown-item:has-text({text_literal})", - f"button:has-text({text_literal})", - f'[role="button"]:has-text({text_literal})', - f"a:has-text({text_literal})", - f"li:has-text({text_literal})", - f"div.device-type:has-text({text_literal})", - ): - locator = page.locator(selector).first - try: - locator.click(timeout=3_000) - return - except Exception: - pass - try: - locator.click(timeout=3_000, force=True) - return - except Exception: - pass - for role in ("button", "link"): - try: - page.get_by_role(role, name=text, exact=exact).first.click(timeout=3_000) - return - except Exception: - pass - locator = page.get_by_text(text, exact=False).first - try: - locator.click(timeout=min(timeout, 3_000)) - return - except Exception: - pass - locator.click(timeout=min(timeout, 3_000), force=True) - - -def _click_selector_or_text(page: Any, selector_env: str, fallback_text: str | None = None) -> None: - selector = _env(selector_env) - if selector: - page.locator(selector).first.click(timeout=_browser_timeout_ms()) - return - if selector_env == "FREIGHT_RPA_DSV_VIEW_REPORT_SELECTOR": - for view_selector in ( - 'input[type="submit"][value="View Report"]', - 'button:has-text("View Report")', - '.btn:has-text("View Report")', - 'input[value="View Report"]', - '[role="button"]:has-text("View Report")', - ): - try: - locator = page.locator(view_selector).first - locator.wait_for(state="visible", timeout=30_000) - locator.evaluate("(node) => node.click()") - return - except Exception: - pass - if fallback_text: - _click_text(page, fallback_text, exact=True) - return - raise RuntimeError(f"Missing selector env: {selector_env}") - - -def _fill_selector_or_label(page: Any, selector_env: str, label: str, value: str | None) -> None: - text = str(value or "").strip() - if not text: - return - selector = _env(selector_env) - locator = page.locator(selector).first if selector else page.get_by_label(label).first - try: - current = str(locator.input_value(timeout=3_000) or "").strip() - if current == text: - return - except Exception: - pass - locator.fill(text, timeout=_browser_timeout_ms()) - - -def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: str | None) -> None: - """委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。""" - import importlib.util - from pathlib import Path - - 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) - module.fill_dsv_filter_if_needed( - page, - selector_env, - label, - value, - env=_env, - browser_timeout_ms=_browser_timeout_ms, - debug_stage=_debug_dsv_stage, - ) - - -def _select_or_fill(page: Any, selector_env: str, label: str, value: str | None) -> None: - text = str(value or "").strip() - if not text: - return - selector = _env(selector_env) - locator = page.locator(selector).first if selector else page.get_by_label(label) - try: - locator.select_option(label=text, timeout=_browser_timeout_ms()) - return - except Exception: - pass - try: - locator.select_option(value=text, timeout=_browser_timeout_ms()) - return - except Exception: - pass - locator.fill(text, timeout=_browser_timeout_ms()) - - -def _visible_locator(page: Any, selector: str | None): - if not selector: - return None - for frame in page.frames: - locator = frame.locator(selector).first - try: - return locator if locator.is_visible(timeout=1_000) else None - except Exception: - pass - return None - - -def _visible_locator_in_root(root: Any, selector: str | None): - if not selector: - return None - try: - locator = root.locator(selector).first - return locator if locator.is_visible(timeout=1_000) else None - except Exception: - return None - - -def _click_text_in_root(root: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> bool: - timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms() - text_literal = json.dumps(text) - for selector in ( - f'a.dropdown-item:has-text({text_literal})', - f'.dropdown-item:has-text({text_literal})', - f'button:has-text({text_literal})', - f'[role="button"]:has-text({text_literal})', - f'a:has-text({text_literal})', - f'li:has-text({text_literal})', - f'span:has-text({text_literal})', - ): - try: - locator = root.locator(selector).first - locator.click(timeout=min(timeout, 3_000)) - return True - except Exception: - pass - try: - locator = root.locator(selector).first - locator.click(timeout=min(timeout, 3_000), force=True) - return True - except Exception: - pass - for role in ("button", "link"): - try: - root.get_by_role(role, name=text, exact=exact).first.click(timeout=min(timeout, 3_000)) - return True - except Exception: - pass - try: - root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000)) - return True - except Exception: - pass - try: - root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000), force=True) - return True - except Exception: - return False - - -def _click_visible_selector_or_text_in_root(root: Any, selector: str | None, fallback_texts: tuple[str, ...]) -> bool: - locator = _visible_locator_in_root(root, selector) - if locator is not None: - # #region debug-point H4:root-selector-click-attempt - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-attempt", - "[DEBUG] attempting selector click in selected root", - {"selector": selector or "", "fallbackTexts": list(fallback_texts)}, - ) - # #endregion - try: - locator.click(timeout=_browser_timeout_ms()) - # #region debug-point H4:root-selector-click-success - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-success", - "[DEBUG] selector click succeeded in selected root", - {"selector": selector or ""}, - ) - # #endregion - return True - except Exception as exc: - # #region debug-point H4:root-selector-click-error - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-error", - "[DEBUG] selector click failed in selected root", - {"selector": selector or "", "error": str(exc)[:300]}, - ) - # #endregion - for text in fallback_texts: - # #region debug-point H4:root-text-click-attempt - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-attempt", - "[DEBUG] attempting text click in selected root", - {"text": text, "selector": selector or ""}, - ) - # #endregion - clicked = _click_text_in_root(root, text, exact=True, timeout_ms=3_000) - # #region debug-point H4:root-text-click-result - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-result", - "[DEBUG] text click result in selected root", - {"text": text, "clicked": clicked, "selector": selector or ""}, - ) - # #endregion - if clicked: - return True - return False - - -def _fill_login_field(page: Any, selector_env: str, value_env: str, fallback_selectors: tuple[str, ...]) -> bool: - value = _env(value_env) - if not value: - return False - selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item) - for selector in selectors: - locator = _visible_locator(page, selector) - if locator is None: - continue - locator.fill(value, timeout=_browser_timeout_ms()) - return True - return False - - -def _fill_first_visible_text_input(page: Any, value: str) -> bool: - for selector in ( - 'input:not([type])', - 'input[type="text"]', - 'input[type="email"]', - 'input', - ): - for frame in page.frames: - try: - inputs = frame.locator(selector).all() - except Exception: - inputs = [] - for locator in inputs: - try: - if not locator.is_visible(timeout=500) or not _dsv_locator_can_edit(locator): - continue - locator.fill(value, timeout=2_000) - if locator.input_value(timeout=1_000).strip(): - return True - except Exception: - pass - return False - - -def _click_login_submit(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool: - selector = _env(selector_env) - locator = _visible_locator(page, selector) - if locator is not None: - locator.click(timeout=_browser_timeout_ms()) - return True - for text in fallback_texts: - try: - page.get_by_role("button", name=text).click(timeout=3_000) - return True - except Exception: - pass - try: - page.get_by_text(text, exact=True).click(timeout=3_000) - return True - except Exception: - pass - return False - - -def _click_visible_selector_or_text(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool: - selector = _env(selector_env) - locator = _visible_locator(page, selector) - if locator is not None: - locator.click(timeout=_browser_timeout_ms()) - return True - if any(text in {"登录", "Login", "Log in", "Sign in"} for text in fallback_texts): - for submit_selector in ( - 'button[type="submit"]', - 'input[type="submit"]', - "#signOnButton", - ".btn-primary", - ): - locator = _visible_locator(page, submit_selector) - if locator is None: - continue - locator.click(timeout=3_000, force=True) - return True - for text in fallback_texts: - try: - _click_text(page, text, exact=True, timeout_ms=3_000) - return True - except Exception: - pass - return False - - -def _debug_dsv_page_snapshot(page: Any, *, target_text: str = "") -> str: - """ - 汇总 DSV 当前页面与各 frame 的可见文本快照,便于定位菜单/报表文案漂移。 - - 核心逻辑:采集 page.url、顶层 body 文本、关键菜单容器是否存在,以及各 frame 中 - 可见的链接/按钮/菜单项候选文本;当目标文案找不到时,日志里直接输出“页面上实际看到了什么”。 - - Args: - page: Playwright Page 对象。 - target_text: 当前正在寻找的菜单/报表文案,可为空。 - - Returns: - str: 截断后的页面快照字符串,适合直接输出到 worker 日志。 - """ - focus = str(target_text or "").strip() - try: - page_url = page.url - except Exception: - page_url = "" - snippets = [f"url={page_url!r}"] - try: - body = page.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500] - except Exception: - body = "" - if body: - snippets.append(f"page_body={body!r}") - try: - report_nav_exists = _has_dsv_report_nav_attached(page) - except Exception: - report_nav_exists = False - snippets.append(f"report_nav_exists={report_nav_exists}") - - candidate_script = """ - (focusText) => { - const normalize = (value) => ((value || '') + '').replace(/\\s+/g, ' ').trim(); - const isVisible = (node) => { - const rect = node.getBoundingClientRect(); - const style = window.getComputedStyle(node); - return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0; - }; - const selectors = [ - '#report-mega-legacy', - '#report-mega-legacy *', - '.mega-dropdown-menu *', - '.dropdown-menu *', - 'a', - 'button', - '[role="button"]', - 'li', - '.nav-link', - '.dropdown-item', - ]; - const focus = normalize(focusText).toLowerCase(); - const values = Array.from(document.querySelectorAll(selectors.join(','))) - .filter((node) => isVisible(node)) - .map((node) => normalize(node.innerText || node.textContent || node.value)) - .filter(Boolean); - const deduped = Array.from(new Set(values)); - const matched = focus - ? deduped.filter((text) => text.toLowerCase().includes(focus)).slice(0, 20) - : []; - return { - matched, - candidates: deduped.slice(0, 40), - }; - } - """ - for idx, frame in enumerate(page.frames): - try: - frame_url = frame.url - except Exception: - frame_url = "" - try: - frame_name = frame.name - except Exception: - frame_name = "" - try: - frame_body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:400] - except Exception: - frame_body = "" - try: - frame_data = frame.evaluate(candidate_script, focus, timeout=1_500) - except Exception: - frame_data = {"matched": [], "candidates": []} - matched = list((frame_data or {}).get("matched") or []) - candidates = list((frame_data or {}).get("candidates") or []) - if frame_body or candidates or matched: - snippets.append( - f"frame[{idx}] name={frame_name!r} url={frame_url!r} body={frame_body!r} matched={matched!r} candidates={candidates!r}" - ) - return " | ".join(snippets)[:5000] - - -def _debug_dsv_stage(page: Any, stage: str, *, target_text: str = "") -> None: - """ - 输出 DSV 关键阶段的运行时快照,用于排查“短暂到页后又跳走”或 DOM 未就绪的问题。 - - 核心逻辑:在登录后等待首页、展开 Reports、选择 Program 等关键节点打印统一格式日志, - 让失败复现时可以按时间顺序观察 URL、标题、body、frame 候选文本是否发生变化。 - - Args: - page: Playwright Page 对象。 - stage: 当前阶段名,例如 `after-login-click`、`wait-app-3s`。 - target_text: 当前关注的菜单或文案目标。 - """ - try: - title = page.title() - except Exception: - title = "" - snapshot = _debug_dsv_page_snapshot(page, target_text=target_text) - print(f"[dsv-stage] stage={stage} title={title!r} {snapshot}") - - -# #region debug-point A:reports-debug-server -def _debug_server_config() -> tuple[str, str]: - """读取 reports-menu-stuck 调试会话配置,未命中时回退默认本地地址。""" - env_path = Path(__file__).resolve().parents[2] / ".dbg" / "reports-menu-stuck.env" - url = "http://127.0.0.1:7778/event" - session_id = "reports-menu-stuck" - try: - content = env_path.read_text(encoding="utf-8") - for line in content.splitlines(): - if line.startswith("DEBUG_SERVER_URL="): - url = line.split("=", 1)[1].strip() or url - elif line.startswith("DEBUG_SESSION_ID="): - session_id = line.split("=", 1)[1].strip() or session_id - except Exception: - pass - return url, session_id - - -def _report_debug_event(hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None: - """向 Debug Server 上报结构化运行时证据;失败时静默,不影响业务流程。""" - try: - url, session_id = _debug_server_config() - payload = { - "sessionId": session_id, - "runId": "pre-fix", - "hypothesisId": hypothesis_id, - "location": location, - "msg": msg, - "data": data or {}, - "ts": int(time.time() * 1000), - } - req = urllib.request.Request( - url, - data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), - headers={"Content-Type": "application/json"}, - method="POST", - ) - with urllib.request.urlopen(req, timeout=2): - pass - except Exception: - pass - - -def _report_dsv_chain_stage(stage: str, status: str, *, started_at: float | None = None, extra: dict[str, Any] | None = None) -> None: - """ - 统一记录 DSV 主链路各阶段耗时。 - - 核心逻辑:只在主编排链路输出 `start/end/error` 三类探针,不参与任何业务判断, - 让一次真实运行即可回放从登录到导出的完整阶段耗时分布。 - """ - payload = dict(extra or {}) - if started_at is not None: - payload["elapsedMs"] = int((time.monotonic() - started_at) * 1000) - print( - "[dsv-chain] " - f"stage={stage} " - f"status={status} " - + ( - " ".join(f"{key}={payload[key]!r}" for key in sorted(payload)) - if payload - else "" - ) - ) - _report_debug_event( - "T", - f"freight_rpa_worker.py:_download_dsv360_inventory:{stage}:{status}", - "[DEBUG] dsv chain stage probe", - {"stage": stage, "status": status, **payload}, - ) - - -def _collect_dsv_reports_probe(page: Any) -> dict[str, Any]: - """采集 Reports 导航的最小 DOM 证据,帮助判断是否点早、点错或被遮挡。""" - try: - probe = page.evaluate( - """ - () => { - const nav = document.querySelector('#report-mega-legacy'); - const link = nav?.querySelector('a.dropdown-toggle, a.nav-link, a'); - const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim(); - const rectOf = (node) => { - if (!node || !node.getBoundingClientRect) return null; - const r = node.getBoundingClientRect(); - return { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) }; - }; - const centerNode = (() => { - const rect = rectOf(link); - if (!rect || rect.width <= 0 || rect.height <= 0) return null; - return document.elementFromPoint(rect.x + Math.max(Math.floor(rect.width / 2), 1), rect.y + Math.max(Math.floor(rect.height / 2), 1)); - })(); - return { - navExists: !!nav, - navClass: nav?.className || '', - navAriaExpanded: nav?.getAttribute('aria-expanded') || '', - linkText: textOf(link), - linkClass: link?.className || '', - linkAriaExpanded: link?.getAttribute('aria-expanded') || '', - linkRect: rectOf(link), - centerTag: centerNode?.tagName || '', - centerText: textOf(centerNode).slice(0, 120), - activeTag: document.activeElement?.tagName || '', - activeText: textOf(document.activeElement).slice(0, 120), - }; - } - """, - ) - except Exception as exc: - probe = {"probe_error": str(exc)[:200]} - try: - probe["url"] = page.url - except Exception: - probe["url"] = "" - try: - probe["menuOpen"] = _is_dsv_reports_menu_open(page) - except Exception as exc: - probe["menuOpen"] = False - probe["menuOpenError"] = str(exc)[:120] - return probe -# #endregion - - -def _collect_dsv_menu_probe(page: Any, target_text: str = "") -> dict[str, Any]: - """采集 Reports 级联菜单当前可见层级,帮助判断下拉是否真的推进到了下一层。""" - target_text = str(target_text or "").strip() - target_literal = json.dumps(target_text) - try: - probe = page.evaluate( - f""" - () => {{ - const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim(); - const nodes = Array.from(document.querySelectorAll( - '#report-mega-legacy a, .mega-dropdown-menu a, .dropdown-menu a, [role="menuitem"], .dropdown-item' - )); - const visible = nodes - .filter((node) => {{ - const rect = node.getBoundingClientRect ? node.getBoundingClientRect() : null; - const style = window.getComputedStyle ? window.getComputedStyle(node) : null; - return rect && rect.width > 0 && rect.height > 0 && style && style.visibility !== 'hidden' && style.display !== 'none'; - }}) - .map((node) => {{ - const rect = node.getBoundingClientRect(); - return {{ - text: textOf(node), - className: node.className || '', - ariaExpanded: node.getAttribute('aria-expanded') || '', - x: Math.round(rect.x), - y: Math.round(rect.y), - }}; - }}) - .filter((item) => item.text) - .slice(0, 40); - const target = {target_literal}; - const matched = target - ? visible.filter((item) => item.text.toLowerCase().includes(target.toLowerCase())).slice(0, 10) - : []; - return {{ - visibleItems: visible, - matchedItems: matched, - bodySnippet: textOf(document.body).slice(0, 600), - activeText: textOf(document.activeElement).slice(0, 120), - }}; - }} - """, - ) - except Exception as exc: - probe = {"probe_error": str(exc)[:200]} - try: - probe["url"] = page.url - except Exception: - probe["url"] = "" - return probe - - -def _click_dsv_export_excel(page: Any) -> None: - """ - 触发 DSV SSRS ReportViewer 的 Excel 导出。 - - 核心逻辑:结果页经常已经渲染出数据,但顶层页面并不会立即出现稳定的 `Export/Save` - 文案;因此优先在承载报表结果的 frame 内直接调用 ReportViewer 原生 - `exportReport('EXCELOPENXML')`,失败后只在选中的结果 frame 内退回到菜单点击式导出, - 避免误点到 portal 顶层或报表标题 frame 的同名元素。 - """ - # #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)}) - # #endregion - try: - _wait_for_dsv_report_result_ready(page, min(_browser_timeout_ms(), 20_000)) - except TypeError: - _wait_for_dsv_report_result_ready(page) - # #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)}) - # #endregion - - selected_frame = _find_dsv_report_result_frame(page) - # #region debug-point H4:selected-report-frame - if selected_frame is not None: - try: - _selected_name = str(selected_frame[1].name or "") - except Exception: - _selected_name = "" - try: - _selected_url = str(selected_frame[1].url or "") - except Exception: - _selected_url = "" - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:selected-frame", - "[DEBUG] selected report frame before export fallback", - { - "frameIndex": selected_frame[0], - "frameName": _selected_name, - "frameUrl": _selected_url[:300], - "state": selected_frame[2], - }, - ) - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:control-probe", - "[DEBUG] sampled export-related controls in selected report frame", - _probe_dsv_report_export_controls(selected_frame[1]), - ) - else: - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:selected-frame", - "[DEBUG] no report frame selected before export fallback", - {"frameCount": len(page.frames)}, - ) - # #endregion - frame_order: list[tuple[int, Any]] = ( - [(selected_frame[0], selected_frame[1])] - if selected_frame is not None - else list(enumerate(page.frames)) - ) - - for frame_index, frame in frame_order: - try: - direct_exported = bool( - frame.evaluate( - """ - () => { - const visible = (node) => { - if (!node) return false; - const style = window.getComputedStyle(node); - const rect = node.getBoundingClientRect(); - return style && style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0; - }; - if (typeof exportReport === 'function') { - exportReport('EXCELOPENXML'); - return true; - } - const win = window; - if (win && typeof win.exportReport === 'function') { - win.exportReport('EXCELOPENXML'); - return true; - } - const excelLink = Array.from(document.querySelectorAll('a[onclick], button[onclick], input[onclick], [role="button"][onclick]')) - .find((node) => String(node.getAttribute('onclick') || '').includes("EXCELOPENXML") && visible(node)); - if (excelLink) { - excelLink.click(); - return true; - } - const exportSelect = Array.from(document.querySelectorAll('select')) - .find((node) => Array.from(node.options || []).some((option) => { - const text = String(option.text || '').toUpperCase(); - const value = String(option.value || '').toUpperCase(); - return text.includes('EXCEL') || value.includes('EXCELOPENXML'); - })); - if (exportSelect) { - const option = Array.from(exportSelect.options || []).find((item) => { - const text = String(item.text || '').toUpperCase(); - const value = String(item.value || '').toUpperCase(); - return text.includes('EXCEL') || value.includes('EXCELOPENXML'); - }); - if (option) { - exportSelect.value = option.value; - exportSelect.dispatchEvent(new Event('change', { bubbles: true })); - exportSelect.dispatchEvent(new Event('input', { bubbles: true })); - return true; - } - } - return false; - } - """ - ) - ) - # #region debug-point H3:direct-export-attempt - _emit_debug_event( - "pre-fix", - "H3", - "freight_rpa_worker.py:_click_dsv_export_excel:direct-export-attempt", - "[DEBUG] direct export attempt finished", - {"frameIndex": frame_index, "directExported": direct_exported}, - ) - # #endregion - if direct_exported: - return - except Exception: - # #region debug-point H3:direct-export-exception - _emit_debug_event( - "pre-fix", - "H3", - "freight_rpa_worker.py:_click_dsv_export_excel:direct-export-exception", - "[DEBUG] direct export attempt raised exception", - {"frameIndex": frame_index}, - ) - # #endregion - pass - - # #region debug-point H4:direct-export-fallback - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:fallback", - "[DEBUG] direct export not available; fallback to export menu", - {"frameCount": len(page.frames), "selectedFrameIndex": selected_frame[0] if selected_frame else None}, - ) - # #endregion - frame_root = selected_frame[1] if selected_frame else page - export_menu_selector = _env("FREIGHT_RPA_DSV_EXPORT_MENU_SELECTOR") or ",".join( - ( - 'a[title="Export drop down menu"]', - 'button[title="Export drop down menu"]', - '[id$="_ctl04_ctl00_ButtonLink"]', - '[aria-label="Export drop down menu"]', - ) - ) - excel_export_selector = _env("FREIGHT_RPA_DSV_EXCEL_EXPORT_SELECTOR") or ",".join( - ( - 'a[title="Excel"]', - 'button[title="Excel"]', - 'a[onclick*="EXCELOPENXML"]', - 'button[onclick*="EXCELOPENXML"]', - 'a[href*="EXCELOPENXML"]', - ) - ) - legacy_selector = _env("FREIGHT_RPA_DSV_EXPORT_SELECTOR") - if legacy_selector: - locator = _visible_locator_in_root(frame_root, legacy_selector) - if locator is not None: - locator.click(timeout=_browser_timeout_ms()) - else: - page.locator(legacy_selector).first.click(timeout=_browser_timeout_ms()) - else: - export_menu_clicked = _click_visible_selector_or_text_in_root( - frame_root, - export_menu_selector, - ("file_download", "Save", "Export"), - ) or ( - selected_frame is None - and _click_visible_selector_or_text( - page, - "FREIGHT_RPA_DSV_EXPORT_MENU_SELECTOR", - ("file_download", "Save", "Export"), - ) - ) - # #region debug-point H4:export-menu-result - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:export-menu-result", - "[DEBUG] export menu click result", - { - "clicked": export_menu_clicked, - "selectedFrameIndex": selected_frame[0] if selected_frame else None, - }, - ) - # #endregion - if not export_menu_clicked: - snapshot = _debug_dsv_page_snapshot(page, target_text="Export") - # #region debug-point H4:export-menu-missing - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:export-menu-missing", - "[DEBUG] export menu not found in selected frame", - {"selectedFrameIndex": selected_frame[0] if selected_frame else None, "snapshot": snapshot[:2000]}, - ) - # #endregion - print(f"[dsv-debug] export menu missing {snapshot}") - raise RuntimeError("DSV report export menu was not found") - time.sleep(0.5) - - excel_option_clicked = _click_visible_selector_or_text_in_root( - frame_root, - excel_export_selector, - ("Excel", "EXCELOPENXML"), - ) or ( - selected_frame is None - and _click_visible_selector_or_text( - page, - "FREIGHT_RPA_DSV_EXCEL_EXPORT_SELECTOR", - ("Excel", "EXCELOPENXML"), - ) - ) - if not excel_option_clicked: - forced_menu_opened = _force_open_dsv_export_menu(frame_root, export_menu_selector) - # #region debug-point H4:export-menu-force-open - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:export-menu-force-open", - "[DEBUG] forced export menu open attempt finished", - { - "opened": forced_menu_opened, - "selectedFrameIndex": selected_frame[0] if selected_frame else None, - }, - ) - # #endregion - if forced_menu_opened: - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:post-force-control-probe", - "[DEBUG] sampled controls after forced export menu open", - _probe_dsv_report_export_controls(frame_root), - ) - excel_option_clicked = _click_visible_selector_or_text_in_root( - frame_root, - excel_export_selector, - ("Excel", "EXCELOPENXML"), - ) - if excel_option_clicked: - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:excel-option-result", - "[DEBUG] excel option click result", - {"clicked": True, "selector": "post-force-open", "selectedFrameIndex": selected_frame[0] if selected_frame else None}, - ) - return - for excel_selector in ( - 'a.ActiveLink[title="Excel"]', - 'a[title="Excel"]', - 'a[onclick*="EXCELOPENXML"]', - ): - locator = _visible_locator_in_root(frame_root, excel_selector) - if locator is None and selected_frame is None: - locator = _visible_locator(page, excel_selector) - if locator is not None: - locator.click(timeout=3_000, force=True) - # #region debug-point H4:excel-option-result - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:excel-option-result", - "[DEBUG] excel option click result", - {"clicked": True, "selector": excel_selector, "selectedFrameIndex": selected_frame[0] if selected_frame else None}, - ) - # #endregion - return - snapshot = _debug_dsv_page_snapshot(page, target_text="Excel") - # #region debug-point H4:excel-option-missing - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:excel-option-missing", - "[DEBUG] excel option not found after export menu", - {"selectedFrameIndex": selected_frame[0] if selected_frame else None, "snapshot": snapshot[:2000]}, - ) - # #endregion - print(f"[dsv-debug] excel export option missing {snapshot}") - raise RuntimeError("DSV Excel export option was not found") - # #region debug-point H4:excel-option-result - _emit_debug_event( - "pre-fix", - "H4", - "freight_rpa_worker.py:_click_dsv_export_excel:excel-option-result", - "[DEBUG] excel option click result", - {"clicked": True, "selector": "fallback-text-or-selector", "selectedFrameIndex": selected_frame[0] if selected_frame else None}, - ) - # #endregion - - -def _get_dsv_report_result_state(frame: Any) -> dict[str, bool]: - """ - 读取 DSV SSRS 结果 frame 的当前状态。 - - 核心逻辑:真实页面里“结果表头已出现”与“报表真正渲染完成”并不同步, - 这里统一抽象为 `asyncWait / exportReady / excelReady / bodyReady / directExportReady` - 五个布尔量,供等待逻辑和导出逻辑复用。 - """ - try: - state = frame.evaluate( - """ - () => { - const visible = (node) => { - if (!node) return false; - const style = window.getComputedStyle(node); - const rect = node.getBoundingClientRect(); - return style && style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0; - }; - const body = String(document.body?.innerText || ''); - const normalizedBody = body.toLowerCase(); - const hasVisible = (selectors) => selectors.some((selector) => - Array.from(document.querySelectorAll(selector)).some((node) => visible(node)) - ); - const exportReady = hasVisible([ - 'a[title="Export"]', - 'button[title="Export"]', - '[aria-label="Export"]', - 'a[title="Save"]', - 'button[title="Save"]', - 'a[onclick*="ShowExport"]', - 'button[onclick*="ShowExport"]', - 'a[onclick*="export"]', - 'button[onclick*="export"]', - ]); - const excelReady = hasVisible([ - 'a[title="Excel"]', - 'button[title="Excel"]', - '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 bodyReady = bodyScore > 0; - const asyncWait = [ - 'loading', - 'please wait', - 'generating', - 'processing', - 'retrieving', - ].some((token) => normalizedBody.includes(token)); - const directExportReady = typeof exportReport === 'function' || - (window && typeof window.exportReport === 'function'); - return { asyncWait, exportReady, excelReady, bodyReady, bodyScore, directExportReady }; - } - """ - ) - except Exception: - state = {} - return { - "asyncWait": bool((state or {}).get("asyncWait")), - "exportReady": bool((state or {}).get("exportReady")), - "excelReady": bool((state or {}).get("excelReady")), - "bodyReady": bool((state or {}).get("bodyReady")), - "bodyScore": int((state or {}).get("bodyScore") or (3 if (state or {}).get("bodyReady") else 0)), - "directExportReady": bool((state or {}).get("directExportReady")), - } - - -def _probe_dsv_report_export_controls(frame: Any) -> dict[str, Any]: - """ - 采集 DSV SSRS 结果 frame 内的导出相关控件特征。 - - 核心逻辑:真实页面的导出入口未必直接显示为 Export/Save 文案,因此在运行时 - 抽样可见 a/button/input/select/option,记录 title/aria-label/value/onclick 等属性, - 用于后续基于真实 DOM 证据收敛选择器。 - """ - try: - return frame.evaluate( - """ - () => { - const visible = (node) => { - if (!node) return false; - const style = window.getComputedStyle(node); - const rect = node.getBoundingClientRect(); - return style && style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0; - }; - const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim(); - const pick = (node) => ({ - tag: String(node.tagName || '').toLowerCase(), - id: String(node.id || ''), - name: String(node.getAttribute('name') || ''), - title: String(node.getAttribute('title') || ''), - ariaLabel: String(node.getAttribute('aria-label') || ''), - value: String(node.getAttribute('value') || ''), - text: textOf(node).slice(0, 120), - onclick: String(node.getAttribute('onclick') || '').slice(0, 200), - href: String(node.getAttribute('href') || '').slice(0, 200), - }); - const controls = Array.from(document.querySelectorAll('a, button, input, select, option, img, span[title], div[title]')) - .filter((node) => visible(node) || node.tagName === 'OPTION') - .map((node) => pick(node)) - .filter((item) => item.text || item.title || item.ariaLabel || item.value || item.onclick || item.href || item.id || item.name) - .slice(0, 80); - const exportHints = controls.filter((item) => { - const haystack = [item.text, item.title, item.ariaLabel, item.value, item.onclick, item.href, item.id, item.name] - .join(' ') - .toLowerCase(); - return ['export', 'excel', 'openxml', 'save', 'csv', 'download', 'page width', 'whole page', 'find', 'next'].some((token) => haystack.includes(token)); - }).slice(0, 40); - const windowKeys = Object.keys(window || {}) - .filter((key) => /export|reportviewer|rv|excel/i.test(key)) - .slice(0, 40); - return { - exportHints, - windowKeys, - bodySnippet: textOf(document.body).slice(0, 600), - }; - } - """ - ) - except Exception as exc: - return {"probeError": str(exc)[:300]} - - -def _force_open_dsv_export_menu(root: Any, export_menu_selector: str) -> bool: - """ - 在 SSRS ReportViewer 中强制展开导出下拉菜单。 - - 核心逻辑:真实 DSV 页面里 `Export drop down menu` 按钮即便 locator.click 成功, - 也可能没有真正把下拉层渲染出来;这里补一轮 force click + JS mouse 事件 + 键盘事件, - 尽量把 ReportViewer 的导出菜单显式展开。 - """ - locator = _visible_locator_in_root(root, export_menu_selector) - if locator is None: - return False - try: - locator.click(timeout=2_000, force=True) - time.sleep(0.3) - return True - except Exception: - pass - try: - locator.evaluate( - """ - (node) => { - const fire = (type) => node.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window })); - fire('mouseover'); - fire('mouseenter'); - fire('mousedown'); - fire('mouseup'); - fire('click'); - } - """ - ) - time.sleep(0.3) - return True - except Exception: - pass - for key in ("Enter", " ", "ArrowDown"): - try: - locator.press(key, timeout=1_500) - time.sleep(0.2) - return True - except Exception: - pass - return False - - -def _find_dsv_report_result_frame(page: Any) -> tuple[int, Any, dict[str, Any]] | None: - """ - 选择真正承载 SSRS 报表结果表格的 frame。 - - 核心逻辑:首页/最近报表等 frame 也可能包含报表名文本,因此不能只看 `bodyReady`; - 这里先按 frame 身份硬匹配 `report-frame` / `.../S360Reports/Reports/Default.aspx`, - 命中后即使正文仍在 loading,也要持续盯住它等待;只有完全识别不到目标 frame 时, - 才退回到 `bodyScore` 启发式排序。 - """ - 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) - try: - frame_name = str(frame.name or "").strip().lower() - except Exception: - frame_name = "" - try: - frame_url = str(frame.url or "").strip().lower() - except Exception: - frame_url = "" - - identity_rank = 0 - if frame_name == "report-frame": - identity_rank = 2 - elif "/s360reports/reports/default.aspx" in frame_url: - identity_rank = 1 - - if identity_rank > 0: - hard_matches.append( - ( - frame_index, - frame, - state, - ( - identity_rank, - 1 if state["bodyReady"] else 0, - int(state["bodyScore"]), - 1 if state["excelReady"] else 0, - 1 if state["exportReady"] else 0, - ), - ) - ) - continue - - if not state["bodyReady"]: - continue - heuristic_matches.append( - ( - frame_index, - frame, - state, - ( - int(state["bodyScore"]), - 1 if state["excelReady"] else 0, - 1 if state["exportReady"] else 0, - 1 if state["directExportReady"] else 0, - ), - ) - ) - - if hard_matches: - best_hard = max(hard_matches, key=lambda item: item[3]) - return (best_hard[0], best_hard[1], best_hard[2]) - - if heuristic_matches: - best_heuristic = max(heuristic_matches, key=lambda item: item[3]) - return (best_heuristic[0], best_heuristic[1], best_heuristic[2]) - - return None - - -def _wait_for_dsv_report_result_ready(page: Any, timeout_ms: int) -> None: - """ - 等待 DSV 报表结果区进入“可导出”状态。 - - 核心逻辑:DSV 报表页点击 View Report 后,真实结果和导出工具栏都渲染在 frame 里, - 顶层页面未必能立即看到 `Export` 文案;因此这里改为轮询读取 frame 状态。 - 只要“目标结果 frame 的异步加载已结束 + 报表正文已出现”就允许继续尝试导出,因为真实站点上 - 导出能力有时直到点击工具栏/调用原生导出函数时才真正显式出现。 - """ - 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)}) - # #endregion - while time.monotonic() < deadline: - selected = _find_dsv_report_result_frame(page) - if selected is not None: - frame_index, _frame, state = selected - if state["bodyReady"] and not state["asyncWait"]: - # #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}, - ) - # #endregion - _debug_dsv_stage(page, "wait-report-ready-state", target_text="Export") - return - elapsed_second = int(deadline - time.monotonic()) - if elapsed_second != last_stage_second and elapsed_second % 3 == 0: - # #region debug-point H2:wait-report-poll - _emit_debug_event( - "pre-fix", - "H2", - "freight_rpa_worker.py:_wait_for_dsv_report_result_ready:poll", - "[DEBUG] report result still waiting", - {"secondsRemaining": elapsed_second, "frameCount": len(page.frames)}, - ) - # #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)}) - # #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: - """ - 向后兼容的包装器。 - - 核心逻辑:历史调用点仍使用 `_wait_dsv_report_ready`; - 实际实现统一委托给 `_wait_for_dsv_report_result_ready`,避免测试和主流程再次分叉。 - """ - _wait_for_dsv_report_result_ready(page, timeout_ms) - - -def _has_dsv_report_form_shell(page: Any) -> bool: - """ - 判断 DSV 报表参数页的 shell 是否已经挂载完成。 - - 核心逻辑:用户在菜单里选中目标报表后,`View Report` 按钮常常已经可以点击, - 但报表标题文本未必立刻出现在 frame 正文里;此时只要 portal reports 路由和 - SSRS 相关 frame 已出现,就可以认定表单页已基本就绪,避免额外等待标题文本刷出。 - """ - try: - current_url = str(page.url or "").lower() - except Exception: - current_url = "" - if "/main/portal/frame/reports/" in current_url: - return True - for frame in getattr(page, "frames", []): - try: - frame_name = str(frame.name or "").strip().lower() - except Exception: - frame_name = "" - try: - frame_url = str(frame.url or "").strip().lower() - except Exception: - frame_url = "" - if frame_name in {"myiframe", "report-frame"}: - return True - if "/s360reports/ssrs/" in frame_url or "/s360reports/reports/default.aspx" in frame_url: - return True - return False - - -def _dsv_report_submission_started(frame: Any, locator: Any) -> bool: - """ - 判断 View Report 点击后是否已开始提交。 - - 核心逻辑:优先检测按钮是否变为 disabled/隐藏,其次检测 frame 文本里是否出现常见的加载提示, - 避免“程序化 submit 已调用,但页面其实没有开始处理”的误判。 - """ - try: - if not locator.is_visible(timeout=500): - return True - except Exception: - return True - try: - state = locator.evaluate( - """ - (node) => ({ - disabled: Boolean(node.disabled), - ariaDisabled: node.getAttribute('aria-disabled'), - value: node.value || node.textContent || '', - }) - """ - ) - value = str((state or {}).get("value") or "").strip().lower() - if (state or {}).get("disabled") or str((state or {}).get("ariaDisabled") or "").lower() == "true": - return True - if value and value != "view report": - return True - except Exception: - pass - try: - body = frame.locator("body").inner_text(timeout=800).lower() - except Exception: - body = "" - transition_markers = ( - "loading", - "please wait", - "generating", - "processing", - "export", - "save", - "excel", - "no records", - "no data", - ) - return any(marker in body for marker in transition_markers) - - -def _dsv_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool: - """ - 判断当前 DSV 页面或 frame 中是否已经出现目标文案。 - - 核心逻辑:同时扫描顶层页面与各 frame 的可见文本和常见菜单节点, - 用于级联菜单点击后的“下一层已展开”确认,避免只点到一级菜单就误判成功。 - - Args: - page: Playwright Page 对象。 - text: 需要确认出现的目标文案。 - timeout_ms: 单次检查的等待时间,默认 1 秒。 - - Returns: - bool: 找到目标文案时返回 True,否则返回 False。 - """ - normalized = str(text or "").strip().lower() - if not normalized: - return False - selectors = ( - f"text={text}", - f"a:has-text({json.dumps(text)})", - f".dropdown-item:has-text({json.dumps(text)})", - f"button:has-text({json.dumps(text)})", - ) - for root in (page, *page.frames): - for selector in selectors: - try: - if root.locator(selector).first.is_visible(timeout=timeout_ms): - return True - except Exception: - pass - try: - body = root.locator("body").inner_text(timeout=timeout_ms).lower() - except Exception: - body = "" - if normalized in body: - return True - return False - - -def _dsv_dropdown_text_visible(page: Any, text: str, *, timeout_ms: int = 1_000) -> bool: - """ - 仅判断当前展开的 DSV 下拉菜单中是否出现目标文案。 - - 核心逻辑:主页 `Recent Reports` 也会出现与报表菜单同名的文本; - 这里将确认范围收紧为 `Reports` 级联菜单容器内的可见项,避免把首页正文误判成下一级菜单已展开。 - """ - normalized = str(text or "").strip().lower() - if not normalized: - return False - selectors = ( - f"#report-mega-legacy a.dropdown-item:has-text({json.dumps(text)})", - f".mega-dropdown-menu a.dropdown-item:has-text({json.dumps(text)})", - f".dropdown-menu a.dropdown-item:has-text({json.dumps(text)})", - f"#report-mega-legacy [role='menuitem']:has-text({json.dumps(text)})", - f".mega-dropdown-menu [role='menuitem']:has-text({json.dumps(text)})", - f".dropdown-menu [role='menuitem']:has-text({json.dumps(text)})", - f"#report-mega-legacy a:has-text({json.dumps(text)})", - f".mega-dropdown-menu a:has-text({json.dumps(text)})", - f".dropdown-menu a:has-text({json.dumps(text)})", - ) - for selector in selectors: - try: - if page.locator(selector).first.is_visible(timeout=timeout_ms): - return True - except Exception: - pass - probe = _collect_dsv_menu_probe(page, text) - for item in probe.get("matchedItems") or []: - item_text = str((item or {}).get("text") or "").strip().lower() - if item_text and normalized in item_text: - return True - return False - - -def _click_dsv_menu_item(page: Any, text: str, *, next_text: str = "") -> None: - """ - 点击 DSV 级联菜单项,并在需要时确认下一级目标已经出现。 - - 核心逻辑:对同一菜单项依次尝试 hover/click/force/evaluate/keyboard 等方式; - 若传入 next_text,则只有在页面上真正看到下一级菜单文本后才认为本次点击成功。 - - Args: - page: Playwright Page 对象。 - text: 当前要点击的菜单文案。 - next_text: 预期因本次点击而出现的下一级菜单文案;为空时仅要求当前点击成功。 - """ - text = str(text or "").strip() - if not text: - raise RuntimeError("DSV menu item text is empty") - _report_debug_event( - "F", - "freight_rpa_worker.py:_click_dsv_menu_item:entry", - "[DEBUG] entering dsv menu item selection", - { - "targetText": text, - "nextText": str(next_text or ""), - "elapsedMs": 0, - **_collect_dsv_menu_probe(page, text), - }, - ) - text_literal = json.dumps(text) - deadline = time.monotonic() + 30 - started_at = time.monotonic() - while time.monotonic() < deadline: - for selector in ( - f"#report-mega-legacy a.dropdown-item:has-text({text_literal})", - f".mega-dropdown-menu a.dropdown-item:has-text({text_literal})", - f".dropdown-menu a.dropdown-item:has-text({text_literal})", - f"#report-mega-legacy [role='menuitem']:has-text({text_literal})", - f".mega-dropdown-menu [role='menuitem']:has-text({text_literal})", - f".dropdown-menu [role='menuitem']:has-text({text_literal})", - f"#report-mega-legacy a:has-text({text_literal})", - f".mega-dropdown-menu a:has-text({text_literal})", - f".dropdown-menu a:has-text({text_literal})", - ): - try: - locator = page.locator(selector).first - locator.wait_for(state="visible", timeout=2_000) - for action in ("hover", "click", "force-click", "evaluate", "enter", "space"): - try: - if action == "hover": - locator.hover(timeout=1_500) - time.sleep(0.2) - continue - elif action == "click": - locator.click(timeout=1_500) - elif action == "force-click": - locator.click(timeout=1_500, force=True) - elif action == "evaluate": - locator.evaluate("(node) => node.click()") - elif action == "enter": - locator.press("Enter", timeout=1_500) - else: - locator.press("Space", timeout=1_500) - except Exception: - continue - _report_debug_event( - "F", - "freight_rpa_worker.py:_click_dsv_menu_item:attempt", - "[DEBUG] dsv menu item attempt dispatched", - { - "targetText": text, - "nextText": str(next_text or ""), - "selector": selector, - "action": action, - "elapsedMs": int((time.monotonic() - started_at) * 1000), - **_collect_dsv_menu_probe(page, next_text or text), - }, - ) - if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500): - _report_debug_event( - "F", - "freight_rpa_worker.py:_click_dsv_menu_item:success", - "[DEBUG] dsv menu item selection considered successful", - { - "targetText": text, - "nextText": str(next_text or ""), - "selector": selector, - "action": action, - "elapsedMs": int((time.monotonic() - started_at) * 1000), - **_collect_dsv_menu_probe(page, next_text or text), - }, - ) - return - except Exception: - pass - time.sleep(0.5) - _report_debug_event( - "F", - "freight_rpa_worker.py:_click_dsv_menu_item:failed", - "[DEBUG] dsv menu item selection timed out", - { - "targetText": text, - "nextText": str(next_text or ""), - "elapsedMs": int((time.monotonic() - started_at) * 1000), - **_collect_dsv_menu_probe(page, next_text or text), - }, - ) - print(f"[dsv-debug] menu item missing target={text!r} {_debug_dsv_page_snapshot(page, target_text=text)}") - raise RuntimeError(f"DSV menu item was not found: {text}") - - -def _click_dsv_report_group(page: Any, text: str, *, next_text: str = "") -> None: - """ - 点击 DSV Report Group,并在需要时确认目标报表已经出现在菜单中。 - - 核心逻辑:Report Group 往往位于 Program 的二级菜单下,单次 click 很容易因为 hover 丢失而失效; - 这里在每次尝试后立刻检查 next_text,确保真正进入到报表项层级。 - - Args: - page: Playwright Page 对象。 - text: 当前 report group 文案。 - next_text: 预期出现的报表名称;为空时仅要求当前 group 点击成功。 - """ - text = str(text or "").strip() - if not text: - raise RuntimeError("DSV report group text is empty") - _report_debug_event( - "G", - "freight_rpa_worker.py:_click_dsv_report_group:entry", - "[DEBUG] entering dsv report group selection", - { - "targetText": text, - "nextText": str(next_text or ""), - "elapsedMs": 0, - **_collect_dsv_menu_probe(page, text), - }, - ) - text_literal = json.dumps(text) - started_at = time.monotonic() - for selector in ( - f"#report-mega-legacy :text-is({text_literal})", - f".mega-dropdown-menu :text-is({text_literal})", - f".dropdown-menu :text-is({text_literal})", - ): - try: - locator = page.locator(selector).first - locator.wait_for(state="visible", timeout=10_000) - for action in ("hover", "click", "force-click", "evaluate", "enter", "space"): - try: - if action == "hover": - locator.hover(timeout=1_500) - time.sleep(0.2) - continue - elif action == "click": - locator.click(timeout=1_500) - elif action == "force-click": - locator.click(timeout=1_500, force=True) - elif action == "evaluate": - locator.evaluate("(node) => node.click()") - elif action == "enter": - locator.press("Enter", timeout=1_500) - else: - locator.press("Space", timeout=1_500) - except Exception: - continue - _report_debug_event( - "G", - "freight_rpa_worker.py:_click_dsv_report_group:attempt", - "[DEBUG] dsv report group attempt dispatched", - { - "targetText": text, - "nextText": str(next_text or ""), - "selector": selector, - "action": action, - "elapsedMs": int((time.monotonic() - started_at) * 1000), - **_collect_dsv_menu_probe(page, next_text or text), - }, - ) - if not next_text or _dsv_dropdown_text_visible(page, next_text, timeout_ms=1_500): - _report_debug_event( - "G", - "freight_rpa_worker.py:_click_dsv_report_group:success", - "[DEBUG] dsv report group selection considered successful", - { - "targetText": text, - "nextText": str(next_text or ""), - "selector": selector, - "action": action, - "elapsedMs": int((time.monotonic() - started_at) * 1000), - **_collect_dsv_menu_probe(page, next_text or text), - }, - ) - return - except Exception: - pass - _report_debug_event( - "G", - "freight_rpa_worker.py:_click_dsv_report_group:failed", - "[DEBUG] dsv report group selection timed out", - { - "targetText": text, - "nextText": str(next_text or ""), - **_collect_dsv_menu_probe(page, next_text or text), - }, - ) - print(f"[dsv-debug] report group missing target={text!r} {_debug_dsv_page_snapshot(page, target_text=text)}") - raise RuntimeError(f"DSV report group was not found: {text}") - - -def _click_dsv_view_report(page: Any) -> None: - """ - 点击 SSRS 参数页 View Report。 - 核心逻辑:在各 frame 内轮询 ReportViewer 固定控件 ID 与通用按钮选择器,挂载后尝试多种点击方式。 - """ - selectors = ( - "#ReportViewerMain_ctl08_ctl00", - 'input[id^="ReportViewerMain_"][value="View Report"]', - 'input[type="submit"][value="View Report"]', - 'input[value="View Report"]', - 'button:has-text("View Report")', - ) - _debug_dsv_stage(page, "view-report-before-click", target_text="View Report") - wait_ms = max(15_000, int(_env("FREIGHT_RPA_DSV_VIEW_REPORT_WAIT_MS", "30000") or "30000")) - deadline = time.monotonic() + (wait_ms / 1000) - while time.monotonic() < deadline: - for frame in page.frames: - for selector in selectors: - try: - locator = frame.locator(selector).first - locator.wait_for(state="attached", timeout=1_000) - click_attempts = ("click", "enter", "space", "evaluate-click", "request-submit") - for attempt in click_attempts: - try: - try: - locator.scroll_into_view_if_needed(timeout=1_000) - except Exception: - pass - if attempt == "click": - locator.click(timeout=2_000, force=True) - elif attempt == "enter": - locator.press("Enter", timeout=1_500) - elif attempt == "space": - locator.press("Space", timeout=1_500) - elif attempt == "evaluate-click": - locator.evaluate( - """ - (target) => { - target.click(); - target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window })); - target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window })); - target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); - } - """ - ) - else: - locator.evaluate( - """ - (target) => { - if (target.form && typeof target.form.requestSubmit === 'function') { - target.form.requestSubmit(target); - } else if (target.form) { - target.form.submit(); - } else { - target.click(); - } - } - """ - ) - except Exception: - continue - submit_deadline = time.monotonic() + 4 - while time.monotonic() < submit_deadline: - if _dsv_report_submission_started(frame, locator): - print(f"[dsv] view report submitted via selector={selector!r} attempt={attempt}") - _debug_dsv_stage(page, f"view-report-after-click-{attempt}", target_text="View Report") - return - time.sleep(0.3) - except Exception: - pass - time.sleep(0.3) - print(f"[dsv-debug] view report missing {_debug_dsv_page_snapshot(page, target_text='View Report')}") - raise RuntimeError("DSV View Report button was not found") - - -def _is_dsv_reports_menu_open(page: Any) -> bool: - """ - 判断 DSV Reports 下拉是否已真正展开,而不是仅仅点到了导航按钮。 - - 核心逻辑:优先检查 `#report-mega-legacy` 上的 `show/open/aria-expanded` 状态, - 再兜底检查常见下拉容器里是否出现可见菜单项,避免“点击成功但菜单没开”的误判。 - """ - for selector in ( - "#report-mega-legacy.show", - "#report-mega-legacy.open", - "#report-mega-legacy[aria-expanded='true']", - "#report-mega-legacy .mega-dropdown-menu.show", - "#report-mega-legacy .dropdown-menu.show", - ".mega-dropdown-menu.show", - ".dropdown-menu.show", - ): - try: - if page.locator(selector).first.is_visible(timeout=150): - return True - except Exception: - pass - for selector in ( - "#report-mega-legacy .dropdown-item", - ".mega-dropdown-menu a.dropdown-item", - ".dropdown-menu a.dropdown-item", - ): - try: - locator = page.locator(selector).first - if locator.is_visible(timeout=150): - return True - except Exception: - pass - return False - - -def _click_dsv_reports_menu(page: Any) -> None: - started_at = time.monotonic() - # #region debug-point B:reports-click-entry - _report_debug_event( - "B", - "freight_rpa_worker.py:_click_dsv_reports_menu:entry", - "[DEBUG] entering reports click flow", - {"elapsedMs": 0, **_collect_dsv_reports_probe(page)}, - ) - # #endregion - click_selectors = ( - "#report-mega-legacy > a.dropdown-toggle.nav-link", - "#report-mega-legacy a.dropdown-toggle", - "#report-mega-legacy a.nav-link", - "nav a:has-text('Reports')", - "a.nav-link:has-text('Reports')", - ) - click_roots = [page, *list(getattr(page, "frames", []))] - for selector in click_selectors: - for root in click_roots: - try: - locator = root.locator(selector).first - locator.wait_for(state="attached", timeout=5_000) - except Exception: - continue - # [STEP 1] Reports 打开优先走真实 click,避免先 hover 白等一轮再退回 click。 - for action_name in ("click", "evaluate", "enter", "space", "hover"): - try: - locator.scroll_into_view_if_needed(timeout=2_000) - except Exception: - pass - try: - if action_name == "hover": - locator.hover(timeout=2_000) - elif action_name == "click": - locator.click(timeout=2_000, force=True) - elif action_name == "evaluate": - locator.evaluate( - """ - (target) => { - target.click(); - target.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, cancelable: true, view: window })); - target.dispatchEvent(new MouseEvent('mouseenter', { bubbles: true, cancelable: true, view: window })); - target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window })); - target.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window })); - target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); - } - """ - ) - elif action_name == "enter": - locator.press("Enter", timeout=1_500) - else: - locator.press("Space", timeout=1_500) - except Exception: - continue - # #region debug-point B:reports-click-attempt - _report_debug_event( - "B", - "freight_rpa_worker.py:_click_dsv_reports_menu:attempt", - "[DEBUG] reports click attempt dispatched", - { - "selector": selector, - "action": action_name, - **_collect_dsv_reports_probe(page), - }, - ) - # #endregion - post_action_wait_seconds = 0.6 if action_name == "hover" else 1.2 - action_deadline = time.monotonic() + post_action_wait_seconds - while time.monotonic() < action_deadline: - if _is_dsv_reports_menu_open(page): - print(f"[dsv] reports expanded via {action_name} selector={selector!r}") - _debug_dsv_stage(page, f"reports-expanded-{action_name}", target_text="Reports") - # #region debug-point D:reports-expanded - _report_debug_event( - "D", - "freight_rpa_worker.py:_click_dsv_reports_menu:expanded", - "[DEBUG] reports menu expanded after click attempt", - { - "selector": selector, - "action": action_name, - "elapsedMs": int((time.monotonic() - started_at) * 1000), - **_collect_dsv_reports_probe(page), - }, - ) - # #endregion - return - time.sleep(0.2) - print(f"[dsv-debug] reports menu missing {_debug_dsv_page_snapshot(page, target_text='Reports')}") - # #region debug-point C:reports-click-failed - _report_debug_event( - "C", - "freight_rpa_worker.py:_click_dsv_reports_menu:failed", - "[DEBUG] reports menu click flow exhausted without expansion", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)}, - ) - # #endregion - raise RuntimeError("DSV Reports menu was not found") - - -def _click_dsv_password_method(page: Any) -> bool: - def password_ready() -> bool: - """密码输入框已出现即视为方法页切换成功;兼容轻量探测与通用等待。""" - if _find_dsv_password_locator(page, timeout_ms=250) is not None: - return True - return _wait_for_visible_selector( - page, - "FREIGHT_RPA_DSV_PASSWORD_SELECTOR", - ("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'), - timeout_ms=250, - ) is not None - - def transition_confirmed() -> bool: - deadline = time.monotonic() + 4 - while time.monotonic() < deadline: - if password_ready(): - return True - if not _looks_like_dsv_login_method_page(page): - try: - body_text = page.locator("body").inner_text(timeout=1_000) - except Exception: - body_text = "" - lowered = body_text.lower() - looks_like_password_page = ( - ("输入您的密码" in body_text or "忘记密码" in body_text or "password" in lowered) - and "通行密钥" not in body_text - and "passkey" not in lowered - and "验证失败" not in body_text - and "validation failed" not in lowered - ) - if looks_like_password_page: - time.sleep(0.3) - continue - return False - time.sleep(0.3) - return False - - script_row_click = """ - () => { - const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim(); - const isVisible = (node) => { - const rect = node.getBoundingClientRect(); - const style = window.getComputedStyle(node); - return !(style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0); - }; - const isPasswordMethod = (text) => ( - (text === '密码' || text === 'Password' || text === '输入您的密码并登录。' || text.includes('输入您的密码并登录')) - && !text.includes('忘记密码') - && !text.includes('取消') - && !text.includes('返回') - && !text.includes('通行密钥') - && !text.includes('电子邮件码') - && !text.includes('移动应用程序') - && !text.toLowerCase().includes('cancel') - && !text.toLowerCase().includes('back') - && !text.toLowerCase().includes('passkey') - ); - const rows = Array.from(document.querySelectorAll("form[name='mfaForm'] li.mb-2, form[name='mfaForm'] .mb-2, .device-list li.mb-2, .device-list .mb-2")) - .filter((node) => isVisible(node)); - const row = rows.find((node) => isPasswordMethod(textOf(node))); - if (!row) return false; - const target = row.querySelector('.device-continue, button, a, [role="button"], input[type="submit"]') || row; - target.scrollIntoView({ block: 'center', inline: 'center' }); - if (target.tagName === 'FORM') { - if (typeof target.requestSubmit === 'function') target.requestSubmit(); - else target.submit(); - return true; - } - if (typeof target.click === 'function') target.click(); - for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) { - target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window })); - } - return true; - } - """ - for frame in page.frames: - try: - _clicked = frame.evaluate(script_row_click) - if _clicked and transition_confirmed(): - return True - except Exception: - pass - - deadline = time.monotonic() + 10 - while time.monotonic() < deadline: - try: - rows = page.locator("form[name='mfaForm'] li.mb-2").all() - for row in rows: - text = row.inner_text(timeout=1_000) - lowered = text.lower() - if ("密码" in text or "Password" in text) and "忘记密码" not in text and "取消" not in text and "返回" not in text and "cancel" not in lowered and "back" not in lowered: - row.scroll_into_view_if_needed(timeout=3_000) - try: - row.click(timeout=3_000, force=True) - except Exception: - row.evaluate( - """ - (node) => { - if (typeof node.click === 'function') node.click(); - node.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); - } - """, - timeout=2_000, - ) - if transition_confirmed(): - return True - except Exception: - pass - time.sleep(0.5) - return False - - -def _submit_dsv_username_form(username_locator: Any) -> bool: - try: - return bool( - username_locator.evaluate( - """ - (node) => { - const form = node.closest('form'); - if (!form) return false; - if (typeof form.requestSubmit === 'function') { - form.requestSubmit(); - } else { - form.submit(); - } - return true; - } - """, - timeout=2_000, - ) - ) - except Exception: - return False - - -def _click_dsv_continue(page: Any, username_locator: Any | None = None) -> bool: - if username_locator is not None: - if _submit_dsv_username_form(username_locator): - return True - try: - username_locator.press("Enter", timeout=3_000) - return True - except Exception: - pass - for selector in ( - 'button:has-text("继续")', - 'button:has-text("Continue")', - 'input[value="继续"]', - 'input[value="Continue"]', - '[role="button"]:has-text("继续")', - '[role="button"]:has-text("Continue")', - 'a:has-text("继续")', - 'a:has-text("Continue")', - '.dbs-sims-button-primary', - 'button[type="submit"]', - 'input[type="submit"]', - ): - for frame in page.frames: - try: - locator = frame.locator(selector).first - locator.wait_for(state="attached", timeout=1_000) - try: - locator.click(timeout=1_000) - except Exception: - locator.click(timeout=1_000, force=True) - return True - except Exception: - pass - for frame in page.frames: - try: - identifier = frame.locator("input#identifier").first - identifier.wait_for(state="attached", timeout=1_000) - identifier.press("Enter", timeout=3_000) - return True - except Exception: - pass - script = """ - () => { - const candidates = Array.from(document.querySelectorAll('body *')).filter((node) => { - const style = window.getComputedStyle(node); - const rect = node.getBoundingClientRect(); - return style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0; - }); - const label = candidates.find((node) => { - const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim(); - return text === '继续' || text === 'Continue' || text.includes('继续') || text.includes('Continue'); - }); - const target = label && (label.closest('button, input, a, [role="button"], .dbs-sims-button-primary, [onclick], form') || label); - if (!target) return false; - target.scrollIntoView({ block: 'center', inline: 'center' }); - if (target.tagName === 'FORM') { - if (typeof target.requestSubmit === 'function') target.requestSubmit(); - else target.submit(); - return true; - } - for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) { - target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window })); - } - return true; - } - """ - for frame in page.frames: - try: - if frame.evaluate(script): - return True - except Exception: - pass - return False - - -def _dsv_locator_can_edit(locator: Any) -> bool: - try: - if locator.is_editable(timeout=1_000): - return True - except Exception: - pass - try: - return bool( - locator.evaluate( - "(node) => !node.disabled && !node.readOnly && node.getAttribute('aria-disabled') !== 'true'", - timeout=1_000, - ) - ) - except Exception: - return False - - -def _dsv_username_has_value(locator: Any) -> bool: - for _ in range(5): - try: - if locator.input_value(timeout=1_000).strip(): - return True - except Exception: - pass - time.sleep(0.2) - return False - - -_DSV_REPORTS_NAV_SELECTORS: tuple[str, ...] = ( - "#report-mega-legacy", - "#report-mega-legacy > a.dropdown-toggle.nav-link", - "#report-mega-legacy a.dropdown-toggle", - "#report-mega-legacy a.nav-link", - "nav a:has-text('Reports')", - "a.nav-link:has-text('Reports')", -) - - -def _iter_dsv_report_nav_locators(page: Any): - """在所有 frame 与顶层 page 中查找 Reports 顶栏相关 locator。""" - roots = [page, *list(getattr(page, "frames", []))] - for root in roots: - for selector in _DSV_REPORTS_NAV_SELECTORS: - try: - locator = root.locator(selector).first - if locator.count() > 0: - yield root, selector, locator - except Exception: - continue - - -def _has_dsv_report_nav_attached(page: Any) -> bool: - """Reports 顶栏 DOM 是否已挂载(跨 frame + 文本 fallback)。""" - return next(_iter_dsv_report_nav_locators(page), None) is not None - - -def _has_dsv_report_nav_usable(page: Any) -> bool: - """ - Reports 导航是否已可用于后续点击。 - 核心逻辑:用户肉眼看到首页时,顶栏 Reports 可能已 visible 但 #report-mega-legacy 计数仍为 0; - 因此同时接受 attached 与短超时 visible 探测。 - """ - for _, _, locator in _iter_dsv_report_nav_locators(page): - try: - if locator.is_visible(timeout=200): - return True - except Exception: - pass - return _has_dsv_report_nav_attached(page) - - -def _is_dsv_on_portal_home(page: Any) -> bool: - """URL 已在 portal 且主页面已出现 Home/Favorites/Recent Reports 等内容。""" - try: - current_url = str(page.url or "").lower() - except Exception: - current_url = "" - if "auth.dbschenker.com" in current_url: - return False - if "s360.dbschenker.com" not in current_url: - return False - try: - body = str(page.locator("body").inner_text(timeout=1_000) or "").lower() - except Exception: - body = "" - return any(marker in body for marker in ("home favorites", "recent reports", "favorites")) - - -def _wait_for_dsv_app_after_login( - page: Any, - timeout_ms: int | None = None, - on_portal_shell_seen: Callable[[], None] | None = None, -) -> bool: - """ - 等待 DSV 从登录链路切回 portal 壳层。 - - 核心逻辑:`Verifying compliance` 这类认证过渡页并不代表首页导航已经可操作; - 这里单独识别 auth/合规过渡态,避免在该阶段反复用长超时探测 `#report-mega-legacy`, - 从而把“认证收尾慢”和“Reports 菜单慢”混在一起。 - """ - wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms() - deadline = time.monotonic() + (wait_ms / 1000) - last_debug_at = 0.0 - started_at = time.monotonic() - # #region debug-point J:wait-app-entry - _report_debug_event( - "J", - "freight_rpa_worker.py:_wait_for_dsv_app_after_login:entry", - "[DEBUG] waiting for dsv app shell after login", - {"timeoutMs": wait_ms, "url": page.url}, - ) - # #endregion - _debug_dsv_stage(page, "wait-app-start", target_text="Reports") - last_portal_home_log_at = 0.0 - portal_shell_callback_fired = False - while time.monotonic() < deadline: - now = time.monotonic() - current_url = str(page.url or "").lower() - auth_transition = False - try: - current_title = str(page.title() or "").lower() - except Exception: - current_title = "" - auth_transition = "auth.dbschenker.com" in current_url or "verifying compliance" in current_title - if now - last_debug_at >= 3: - elapsed = int((time.monotonic() - started_at) * 1000) - _debug_dsv_stage(page, f"wait-app-{elapsed // 1000}s", target_text="Reports") - last_debug_at = now - if _has_dsv_report_nav_usable(page): - if on_portal_shell_seen is not None: - on_portal_shell_seen() - _debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports") - _report_debug_event( - "J", - "freight_rpa_worker.py:_wait_for_dsv_app_after_login:success", - "[DEBUG] dsv reports nav usable after login", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, - ) - return True - if not auth_transition and _wait_for_visible_selector( - page, - "", - _DSV_REPORTS_NAV_SELECTORS, - timeout_ms=400, - ) is not None: - if on_portal_shell_seen is not None: - on_portal_shell_seen() - _debug_dsv_stage(page, "wait-app-nav-found", target_text="Reports") - _report_debug_event( - "J", - "freight_rpa_worker.py:_wait_for_dsv_app_after_login:success", - "[DEBUG] dsv reports nav visible after login", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, - ) - return True - on_portal_home = _is_dsv_on_portal_home(page) - if on_portal_home and not auth_transition: - if on_portal_shell_seen is not None and not portal_shell_callback_fired: - on_portal_shell_seen() - portal_shell_callback_fired = True - if now - last_portal_home_log_at >= 2.0: - print( - "[dsv-home] portal home visible, waiting Reports nav " - f"elapsedMs={int((time.monotonic() - started_at) * 1000)} " - f"report_nav_attached={_has_dsv_report_nav_attached(page)} url={page.url!r}" - ) - last_portal_home_log_at = now - elif _has_dsv_portal_shell(page) and on_portal_shell_seen is not None and not portal_shell_callback_fired: - on_portal_shell_seen() - portal_shell_callback_fired = True - if auth_transition: - if _has_dsv_password_upgrade_prompt(page, timeout_ms=250): - _dismiss_dsv_password_upgrade_prompt(page) - continue - # [STEP] 合规/认证过渡页仅用轻量短超时探测 Reports 导航,避免与首页长轮询混淆。 - _wait_for_visible_selector( - page, - "", - _DSV_REPORTS_NAV_SELECTORS, - timeout_ms=400, - ) - time.sleep(0.25) - continue - if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url: - try: - page.wait_for_load_state("domcontentloaded", timeout=1_500) - except Exception: - pass - time.sleep(0.5) - _debug_dsv_stage(page, "wait-app-timeout", target_text="Reports") - # #region debug-point J:wait-app-timeout - _report_debug_event( - "J", - "freight_rpa_worker.py:_wait_for_dsv_app_after_login:timeout", - "[DEBUG] dsv app shell wait timed out", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, - ) - # #endregion - return False - - -def _has_dsv_portal_shell(page: Any) -> bool: - """ - 判断 DSV portal 内容壳层是否已出现。 - - 核心逻辑:dashboard iframe 的欢迎语/Recent Reports 往往先于顶栏 `#report-mega-legacy` - 渲染完成;此函数用于记录 portal_shell_seen 时间点,但不应单独作为 home-ready 判据。 - """ - if _has_dsv_report_nav_attached(page): - return True - portal_markers = ("home favorites", "recent reports", "360 — your contract logistics portal") - roots = [page, *getattr(page, "frames", [])] - for root in roots: - try: - body = str(root.locator("body").inner_text(timeout=1_000) or "").lower() - except Exception: - body = "" - if any(marker in body for marker in portal_markers): - return True - return False - - -def _is_dsv_home_ready(page: Any) -> bool: - """ - 判断 DSV 是否已经稳定进入首页导航态。 - - 核心逻辑:必须离开认证域名,且 Reports 导航已可用(跨 frame 探测); - 用户肉眼已在 portal 首页时,不再仅依赖顶层 #report-mega-legacy 计数。 - """ - if "auth.dbschenker.com" in page.url: - return False - return _has_dsv_report_nav_usable(page) - - -def _wait_for_dsv_home_ready( - page: Any, - *, - timeout_ms: int | None = None, - on_portal_shell_seen: Callable[[], None] | None = None, -) -> None: - """ - 等待 DSV 首页真正稳定可操作。 - - 核心逻辑:登录和升级提示都可能导致页面短暂回跳;这里统一要求首页导航稳定出现, - 失败则直接在“首页阶段”报错,避免主流程跳步到 Reports/View Report。 - """ - wait_ms = timeout_ms if timeout_ms is not None else 60_000 - started_at = time.monotonic() - # #region debug-point K:home-wait-entry - _report_debug_event( - "K", - "freight_rpa_worker.py:_wait_for_dsv_home_ready:entry", - "[DEBUG] entering dsv home ready wait", - {"timeoutMs": wait_ms, "url": page.url, **_collect_dsv_reports_probe(page)}, - ) - # #endregion - if _has_dsv_password_upgrade_prompt(page, timeout_ms=150): - _dismiss_dsv_password_upgrade_prompt(page) - if _is_dsv_home_ready(page): - if on_portal_shell_seen is not None: - on_portal_shell_seen() - _debug_dsv_stage(page, "home-ready", target_text="Reports") - # #region debug-point A:home-ready - _report_debug_event( - "A", - "freight_rpa_worker.py:_wait_for_dsv_home_ready:ready", - "[DEBUG] dsv home considered ready before wait loop", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)}, - ) - # #endregion - return - if _wait_for_dsv_app_after_login(page, timeout_ms=wait_ms, on_portal_shell_seen=on_portal_shell_seen): - if _has_dsv_password_upgrade_prompt(page, timeout_ms=150): - _dismiss_dsv_password_upgrade_prompt(page) - if _is_dsv_home_ready(page): - if on_portal_shell_seen is not None: - on_portal_shell_seen() - _debug_dsv_stage(page, "home-ready-after-wait", target_text="Reports") - # #region debug-point A:home-ready-after-wait - _report_debug_event( - "A", - "freight_rpa_worker.py:_wait_for_dsv_home_ready:ready_after_wait", - "[DEBUG] dsv home considered ready after app wait", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)}, - ) - # #endregion - return - _debug_dsv_stage(page, "home-not-ready", target_text="Reports") - # #region debug-point A:home-not-ready - _report_debug_event( - "A", - "freight_rpa_worker.py:_wait_for_dsv_home_ready:timeout", - "[DEBUG] dsv home was not ready before reports click", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), **_collect_dsv_reports_probe(page)}, - ) - # #endregion - raise RuntimeError("DSV home page was not ready after login") - - -def _wait_for_dsv_reports_nav_stable(page: Any, *, timeout_ms: int | None = None) -> None: - """ - 在首页 ready 之后,继续等待 Reports 导航进入可稳定交互态。 - - 核心逻辑:首页首屏刚渲染完成时,Reports 虽然已经可见,但 hover/click 仍可能被吞掉; - 这里要求导航链接连续多次保持可见,降低“刚进首页就急着点”的误触发概率。 - """ - wait_ms = timeout_ms if timeout_ms is not None else 8_000 - selectors = ( - "#report-mega-legacy > a.dropdown-toggle.nav-link", - "#report-mega-legacy a.dropdown-toggle", - "#report-mega-legacy a.nav-link", - ) - deadline = time.monotonic() + (wait_ms / 1000) - stable_hits = 0 - started_at = time.monotonic() - # #region debug-point L:reports-nav-stable-entry - _report_debug_event( - "L", - "freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:entry", - "[DEBUG] waiting for dsv reports nav stable", - {"timeoutMs": wait_ms, **_collect_dsv_reports_probe(page)}, - ) - # #endregion - while time.monotonic() < deadline: - visible = False - click_roots = [page, *list(getattr(page, "frames", []))] - for selector in selectors: - for root in click_roots: - try: - locator = root.locator(selector).first - if locator.is_visible(timeout=200): - visible = True - break - except Exception: - pass - if visible: - break - if visible: - stable_hits += 1 - if stable_hits >= 3: - # #region debug-point L:reports-nav-stable-success - _report_debug_event( - "L", - "freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:success", - "[DEBUG] dsv reports nav considered stable", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)}, - ) - # #endregion - return - else: - stable_hits = 0 - time.sleep(0.4) - # #region debug-point L:reports-nav-stable-timeout - _report_debug_event( - "L", - "freight_rpa_worker.py:_wait_for_dsv_reports_nav_stable:timeout", - "[DEBUG] dsv reports nav did not become stable in time", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), "stableHits": stable_hits, **_collect_dsv_reports_probe(page)}, - ) - # #endregion - - -def _wait_for_dsv_reports_open(page: Any, *, timeout_ms: int | None = None) -> None: - """ - 等待 Reports 下拉真正展开。 - - 核心逻辑:菜单导航偶发存在 hover/click 已触发但 DOM 尚未展开的情况; - 这里统一以 `_is_dsv_reports_menu_open()` 为成功判据,避免“看起来点了,实际没开”。 - """ - wait_ms = timeout_ms if timeout_ms is not None else 15_000 - deadline = time.monotonic() + (wait_ms / 1000) - while time.monotonic() < deadline: - if _is_dsv_reports_menu_open(page): - _debug_dsv_stage(page, "reports-open-confirmed", target_text="Reports") - # #region debug-point D:reports-open-confirmed - _report_debug_event( - "D", - "freight_rpa_worker.py:_wait_for_dsv_reports_open:confirmed", - "[DEBUG] reports open confirmed", - _collect_dsv_reports_probe(page), - ) - # #endregion - return - time.sleep(0.3) - _debug_dsv_stage(page, "reports-open-timeout", target_text="Reports") - # #region debug-point D:reports-open-timeout - _report_debug_event( - "D", - "freight_rpa_worker.py:_wait_for_dsv_reports_open:timeout", - "[DEBUG] reports open confirmation timed out", - _collect_dsv_reports_probe(page), - ) - # #endregion - raise RuntimeError("DSV Reports menu did not expand") - - -def _wait_for_dsv_report_form_ready(page: Any, report_name: str, *, timeout_ms: int | None = None) -> None: - """ - 等待报表表单页稳定可操作。 - - 核心逻辑:选择 Program / Group / Report 后,不立即假设已进入表单页; - 优先要求 `View Report` 按钮出现,同时满足“报表标题文本已出现”或“报表 shell/frame 已挂载”, - 这样既能避免顺序错乱,也不会因为标题文本稍晚刷新而额外空等数秒。 - """ - wait_ms = timeout_ms if timeout_ms is not None else max( - 60_000, int(_env("FREIGHT_RPA_DSV_REPORT_FORM_TIMEOUT_MS", "60000") or "60000") - ) - deadline = time.monotonic() + (wait_ms / 1000) - started_at = time.monotonic() - normalized_report = str(report_name or "").strip().lower() - last_probe_signature: tuple[bool, bool, bool] | None = None - last_probe_logged_at = 0.0 - _report_debug_event( - "H", - "freight_rpa_worker.py:_wait_for_dsv_report_form_ready:entry", - "[DEBUG] waiting for dsv report form ready", - { - "reportName": str(report_name or ""), - **_collect_dsv_menu_probe(page, report_name or "View Report"), - }, - ) - while time.monotonic() < deadline: - view_report_visible = False - try: - if _wait_for_visible_selector( - page, - "", - ( - 'input[id^="ReportViewerMain_"][value="View Report"]', - 'input[type="submit"][value="View Report"]', - 'input[value="View Report"]', - 'button:has-text("View Report")', - ), - timeout_ms=1_000, - ) is not None: - view_report_visible = True - except Exception: - view_report_visible = False - report_title_visible = False - if normalized_report: - for frame in page.frames: - try: - body = frame.locator("body").inner_text(timeout=500).lower() - except Exception: - body = "" - if normalized_report in body: - report_title_visible = True - break - form_shell_ready = _has_dsv_report_form_shell(page) - probe_signature = (view_report_visible, report_title_visible, form_shell_ready) - now = time.monotonic() - if probe_signature != last_probe_signature or (now - last_probe_logged_at) >= 2.0: - print( - "[dsv-report-form-probe] " - f"elapsedMs={int((now - started_at) * 1000)} " - f"viewReportVisible={view_report_visible} " - f"reportTitleVisible={report_title_visible} " - f"formShellReady={form_shell_ready} " - f"stateChanged={probe_signature != last_probe_signature}" - ) - _report_debug_event( - "H", - "freight_rpa_worker.py:_wait_for_dsv_report_form_ready:probe", - "[DEBUG] dsv report form probe state", - { - "reportName": str(report_name or ""), - "elapsedMs": int((now - started_at) * 1000), - "viewReportVisible": view_report_visible, - "reportTitleVisible": report_title_visible, - "formShellReady": form_shell_ready, - "stateChanged": probe_signature != last_probe_signature, - **_collect_dsv_menu_probe(page, report_name or "View Report"), - }, - ) - last_probe_signature = probe_signature - last_probe_logged_at = now - if form_shell_ready and report_title_visible and not view_report_visible: - remaining_ms = max(0, int((deadline - time.monotonic()) * 1000)) - if remaining_ms > 0: - if _wait_for_visible_selector( - page, - "", - ( - 'input[id^="ReportViewerMain_"][value="View Report"]', - 'input[type="submit"][value="View Report"]', - 'input[value="View Report"]', - 'button:has-text("View Report")', - ), - timeout_ms=min(remaining_ms, 45_000), - ) is not None: - view_report_visible = True - print( - "[dsv-report-form-probe] viewReport appeared after shell+title " - f"elapsedMs={int((time.monotonic() - started_at) * 1000)}" - ) - if view_report_visible and (report_title_visible or form_shell_ready or not normalized_report): - _report_debug_event( - "H", - "freight_rpa_worker.py:_wait_for_dsv_report_form_ready:success", - "[DEBUG] dsv report form became ready", - { - "reportName": str(report_name or ""), - "elapsedMs": int((time.monotonic() - started_at) * 1000), - "viewReportVisible": view_report_visible, - "reportTitleVisible": report_title_visible, - "formShellReady": form_shell_ready, - **_collect_dsv_menu_probe(page, report_name or "View Report"), - }, - ) - _debug_dsv_stage(page, "report-form-ready", target_text=report_name or "View Report") - return - time.sleep(0.5) - _report_debug_event( - "H", - "freight_rpa_worker.py:_wait_for_dsv_report_form_ready:timeout", - "[DEBUG] dsv report form wait timed out", - { - "reportName": str(report_name or ""), - "elapsedMs": int((time.monotonic() - started_at) * 1000), - "viewReportVisible": view_report_visible, - "reportTitleVisible": report_title_visible, - "formShellReady": _has_dsv_report_form_shell(page), - **_collect_dsv_menu_probe(page, report_name or "View Report"), - }, - ) - _debug_dsv_stage(page, "report-form-timeout", target_text=report_name or "View Report") - raise RuntimeError("DSV report form was not ready") - - -def _has_dsv_password_upgrade_prompt(page: Any, timeout_ms: int = 250) -> bool: - """ - 快速判断 DSV 是否真的出现“也许以后 / Maybe later”升级提示。 - - 核心逻辑:仅检查升级提示的强特征,不把 Verifying compliance 或普通 auth 跳转页 - 误判成升级提示,避免触发长时间的无效轮询。 - """ - current_url = str(getattr(page, "url", "") or "").lower() - if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url: - return False - selector = _env("FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR") - candidates = (selector,) if selector else ( - 'button.dbs-sims-button-secondary:has-text("也许以后")', - 'button.dbs-sims-button-secondary:has-text("Maybe later")', - 'button.dbs-sims-button-secondary:has-text("Not now")', - 'button:has-text("也许以后")', - 'a:has-text("也许以后")', - 'text=也许以后', - 'button:has-text("Maybe later")', - 'a:has-text("Maybe later")', - 'text=Maybe later', - 'button:has-text("Not now")', - 'a:has-text("Not now")', - 'text=Not now', - ) - prompt_markers = ( - "使用密码升级登录", - "升级登录", - "password upgrade", - "upgrade your sign-in", - ) - roots = [page, *getattr(page, "frames", [])] - for root in roots: - try: - body = root.locator("body").inner_text(timeout=timeout_ms).lower() - except Exception: - body = "" - if any(marker.lower() in body for marker in prompt_markers): - return True - for candidate in candidates: - try: - if root.locator(candidate).first.is_visible(timeout=timeout_ms): - return True - except Exception: - continue - return False - - -def _debug_dsv_login_method_page(page: Any) -> str: - snippets: list[str] = [] - for idx, frame in enumerate(page.frames): - try: - body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500] - except Exception: - body = "" - try: - candidates = frame.evaluate( - """ - () => Array.from(document.querySelectorAll('.device-type, .device-description, li, button, a, [role="button"]')) - .map((node) => ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim()) - .filter(Boolean) - .slice(0, 30) - """, - timeout=1_000, - ) - except Exception: - candidates = [] - if body or candidates: - snippets.append(f"frame[{idx}] body={body!r} candidates={candidates!r}") - return " | ".join(snippets)[:2000] - - -def _fill_dsv_password_page_fields(page: Any, username: str, password: str) -> bool: - filled_password = False - for frame in page.frames: - try: - inputs = frame.locator("input").all() - except Exception: - inputs = [] - for input_locator in inputs: - try: - input_type = str(input_locator.get_attribute("type", timeout=500) or "").lower() - input_name = str(input_locator.get_attribute("name", timeout=500) or "").lower() - input_id = str(input_locator.get_attribute("id", timeout=500) or "").lower() - if not input_locator.is_visible(timeout=500): - continue - if input_type == "password" or "password" in input_name or "password" in input_id: - input_locator.fill(password, timeout=2_000) - filled_password = True - elif input_type in {"", "text", "email"} or "user" in input_name or "identifier" in input_name: - current = str(input_locator.input_value(timeout=500) or "").strip() - if not current: - input_locator.fill(username, timeout=2_000) - except Exception: - pass - return filled_password - - -def _is_dsv_username_page(page: Any) -> bool: - for frame in page.frames: - try: - text = frame.locator("body").inner_text(timeout=500) - except Exception: - text = "" - lowered = text.lower() - method_markers = ("选择登录方法", "choose a sign-on method", "输入您的密码并登录", "password") - if any(marker in text or marker in lowered for marker in method_markers): - continue - if ("电子邮箱或SIMS ID或手机号" in text or "e-mail or sims id" in lowered) and ("继续" in text or "continue" in lowered): - return True - return False - - -def _submit_dsv_password_form(page: Any) -> bool: - """ - 提交 DSV 密码登录页。 - - 核心逻辑:优先直接点击可见登录按钮;如果页面使用 Vue/隐藏字段组合提交, - 则退回到 DOM 脚本里触发 `pf.ok` / form submit / Enter,避免“密码已填完但未真正登录”。 - """ - selectors = ( - 'button[name="login"]', - 'button[type="submit"]', - 'input[type="submit"]', - 'input[name="pf.ok"]', - 'button.btn.dbs-sims-button-primary', - 'button.dbs-sims-button-primary', - ) - roots = [page, *getattr(page, "frames", [])] - for selector in selectors: - for root in roots: - try: - button = root.locator(selector).first - button.wait_for(state="visible", timeout=1_000) - button.click(timeout=2_000, force=True) - return True - except Exception: - pass - script = """ - () => { - const visible = (node) => { - const rect = node.getBoundingClientRect(); - const style = window.getComputedStyle(node); - return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0; - }; - const password = Array.from(document.querySelectorAll('input#userpassword, input[name="userpassword"], input#password[name="pf.pass"], input[name="pf.pass"], input[type="password"]')) - .find((node) => !node.disabled); - if (!password) return false; - const form = password.closest('form'); - const scope = form || document; - const submit = scope.querySelector('button[name="login"], button[type="submit"], input[type="submit"], input[name="pf.ok"], button.btn.dbs-sims-button-primary, button.dbs-sims-button-primary') - || Array.from(scope.querySelectorAll('button, input[type="submit"], input[name="pf.ok"], [role="button"], .btn.dbs-sims-button-primary, .dbs-sims-button-primary, .dbs-sims-button')) - .find((node) => { - const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim(); - return text === '登录' || text === 'Login' || text === 'Log in' || text === 'Sign in'; - }) || (form ? form.querySelector('button[name="login"], button[type="submit"], input[type="submit"], input[name="pf.ok"], button:not([type]), .btn.dbs-sims-button-primary, .dbs-sims-button-primary') : null); - if (submit) { - if (visible(submit) && typeof submit.scrollIntoView === 'function') { - submit.scrollIntoView({ block: 'center', inline: 'center' }); - } - submit.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true, pointerType: 'mouse' })); - submit.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window })); - submit.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window })); - submit.click(); - submit.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); - return true; - } - if (form && typeof form.requestSubmit === 'function') { - form.requestSubmit(); - return true; - } - if (form) { - form.submit(); - return true; - } - password.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); - return true; - } - """ - for frame in roots: - try: - if frame.evaluate(script, timeout=2_000): - return True - except Exception: - pass - return False - - -def _looks_like_dsv_login_method_page(page: Any) -> bool: - needles = ("选择登录方法", "密码", "Password", "输入您的密码并登录", "Choose a sign-on method") - for frame in page.frames: - try: - text = frame.locator("body").inner_text(timeout=300) - except Exception: - text = "" - lowered = text.lower() - if "real person" in lowered and ("rabbit" in lowered or "scale" in lowered): - continue - if any(needle in text for needle in needles): - return True - return False - - -def _has_dsv_human_check_prompt(page: Any) -> bool: - """快速判断当前页是否出现真人验证提示,避免在普通登录轮询里反复触发重等待。""" - try: - text = page.locator("body").inner_text(timeout=300) - except Exception: - text = "" - lowered = text.lower() - return "real person" in lowered or "rabbit" in lowered or "scale" in lowered or "真人" in text - - -def _wait_for_dsv_login_method_page(page: Any, timeout_ms: int | None = None) -> bool: - wait_ms = timeout_ms if timeout_ms is not None else max(5_000, int(_env("FREIGHT_RPA_DSV_METHOD_PAGE_TIMEOUT_MS", "20000") or "20000")) - deadline = time.monotonic() + (wait_ms / 1000) - while time.monotonic() < deadline: - if "s360.dbschenker.com" in page.url and "auth.dbschenker.com" not in page.url: - return True - if _looks_like_dsv_login_method_page(page): - return True - if _has_dsv_human_check_prompt(page): - _wait_for_dsv_human_check_if_present(page, timeout_ms=2_000) - time.sleep(0.5) - return False - - -def _wait_for_dsv_human_check_if_present(page: Any, timeout_ms: int | None = None) -> None: - wait_ms = timeout_ms if timeout_ms is not None else 300_000 - try: - text = page.locator("body").inner_text(timeout=2_000) - except Exception: - text = "" - lowered = text.lower() - if "real person" not in lowered and "rabbit" not in lowered and "scale" not in lowered and "真人" not in text: - return - print("[dsv-login] human check detected; please click the requested object in the browser") - deadline = time.monotonic() + (wait_ms / 1000) - while time.monotonic() < deadline: - try: - current = page.locator("body").inner_text(timeout=2_000) - except Exception: - current = "" - lowered_current = current.lower() - if "real person" not in lowered_current and "rabbit" not in lowered_current and "scale" not in lowered_current: - print("[dsv-login] human check passed") - return - time.sleep(2) - raise RuntimeError("DSV login human check was not completed in time") - - -def _dsv_login_debug_value(page: Any) -> tuple[str, dict[str, Any]]: - identifier_value = "" - button_state: dict[str, Any] = {} - for frame in page.frames: - if not identifier_value: - try: - identifier_value = frame.locator("input#identifier").first.input_value(timeout=1_000) - except Exception: - pass - if not button_state: - try: - button_state = frame.locator("button[name='login']").first.evaluate( - "(node) => ({ disabled: node.disabled, text: node.textContent, className: node.className })", - timeout=1_000, - ) - except Exception: - pass - if identifier_value or button_state: - break - return identifier_value, button_state - - -def _find_dsv_password_locator(page: Any, timeout_ms: int = 250): - """ - 轻量探测 DSV 密码输入框。 - - 核心逻辑:登录第二步/第三步切换期间只需要快速知道“密码框是否已出现”, - 这里避免调用带长轮询的通用选择器等待,减少方法页阶段的无效阻塞。 - """ - selectors = tuple( - item - for item in ( - _env("FREIGHT_RPA_DSV_PASSWORD_SELECTOR"), - "input#userpassword", - 'input[name="userpassword"]', - 'input[name="password"]', - 'input[type="password"]', - ) - if item - ) - for frame in page.frames: - for selector in selectors: - try: - locator = frame.locator(selector).first - if locator.is_visible(timeout=timeout_ms): - return locator - except Exception: - continue - return None - - -_DSV_USERNAME_SELECTORS = ( - "input#identifier", - 'input[name="identifier"]', - 'input[name="username"]', - 'input[name="userName"]', - 'input[name="email"]', - 'input[autocomplete="username"]', - 'input[placeholder="电子邮箱或SIMS ID或手机号"]', - 'input[type="email"]', - 'input[type="text"]', -) - - -def _is_dsv_oauth_handshake_url(url: str) -> bool: - """PingFederate OAuth 握手页:常见为空白 body,需等待 JS 跳转或 reload。""" - current = str(url or "").lower() - return "auth.dbschenker.com" in current and "authorization.oauth2" in current - - -def _is_dsv_auth_ping_url(url: str) -> bool: - """PingFederate 密码阶段 authorization.ping:同样可能出现空白 body。""" - current = str(url or "").lower() - return "auth.dbschenker.com" in current and "authorization.ping" in current - - -def _is_dsv_blank_auth_transition(page: Any) -> bool: - """auth 域 oauth2/ping 中间页且 body 为空。""" - try: - current_url = str(page.url or "").lower() - except Exception: - return False - if not (_is_dsv_oauth_handshake_url(current_url) or _is_dsv_auth_ping_url(current_url)): - return False - try: - body = str(page.locator("body").inner_text(timeout=1_000) or "").strip() - except Exception: - body = "" - return not body - - -def _dsv_login_ready_timeout_ms() -> int: - """DSV 登录表单/跳转就绪的最大等待毫秒数。""" - return max(60_000, int(_env("FREIGHT_RPA_LOGIN_READY_TIMEOUT_MS", "120000") or "120000")) - - -def _wait_for_dsv_auth_page_ready(page: Any, *, timeout_ms: int | None = None) -> bool: - """ - 等待 DSV auth 域完成 OAuth/Ping 握手并渲染登录表单或跳回 portal。 - - 核心逻辑:authorization.oauth2 / authorization.ping 均可能空白; - 轮询用户名/密码框、portal 导航,必要时 reload 一次触发 PingFederate 自动提交。 - """ - wait_ms = timeout_ms if timeout_ms is not None else _dsv_login_ready_timeout_ms() - deadline = time.monotonic() + (wait_ms / 1000) - started_at = time.monotonic() - logged_waiting = False - reload_attempted = False - while time.monotonic() < deadline: - current_url = str(page.url or "").lower() - if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url: - if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None: - return True - if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None: - return True - if _wait_for_visible_selector( - page, - "FREIGHT_RPA_DSV_USERNAME_SELECTOR", - _DSV_USERNAME_SELECTORS, - timeout_ms=500, - ) is not None: - return True - if _find_dsv_password_locator(page, timeout_ms=200) is not None: - return True - if _wait_for_dsv_login_method_page(page, timeout_ms=200): - return True - if "auth.dbschenker.com" not in current_url: - return True - try: - body = str(page.locator("body").inner_text(timeout=1_000) or "").strip() - except Exception: - body = "" - if body and not _is_dsv_blank_auth_transition(page): - return True - if not logged_waiting: - print(f"[dsv-login] waiting auth page render url={page.url!r}") - logged_waiting = True - try: - page.wait_for_load_state("load", timeout=2_000) - except Exception: - pass - try: - page.wait_for_load_state("networkidle", timeout=2_000) - except Exception: - pass - if not reload_attempted and (time.monotonic() - started_at) >= 12: - reload_attempted = True - transition = "ping" if _is_dsv_auth_ping_url(current_url) else "oauth" - print(f"[dsv-login] blank auth {transition} transition, reload once") - try: - page.reload(wait_until="commit", timeout=min(wait_ms, 45_000)) - except Exception as exc: - print(f"[dsv-login] auth reload failed: {exc}", file=sys.stderr) - time.sleep(0.35) - print(f"[dsv-login] auth page wait finished url={page.url!r}") - return False - - -def _wait_for_dsv_oauth_handshake(page: Any, *, timeout_ms: int = 45_000) -> None: - """兼容旧调用:委托至 _wait_for_dsv_auth_page_ready。""" - _wait_for_dsv_auth_page_ready(page, timeout_ms=timeout_ms) - - -def _goto_dsv_entry_url(page: Any, entry_url: str) -> None: - """ - 打开 DSV entry_url;domcontentloaded 超时时若已跳转到 auth/portal 则继续。 - - 核心逻辑:s360 -> auth 重定向链可能超过单次 goto 默认超时,不应因此中断 batch。 - """ - try: - page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) - except Exception as exc: - message = str(exc).lower() - if "timeout" not in message: - raise - try: - current_url = str(page.url or "").lower() - except Exception: - current_url = "" - if any(token in current_url for token in ("auth.dbschenker.com", "s360.dbschenker.com")): - print( - "[dsv] entry goto domcontentloaded timeout, continue auth redirect " - f"url={page.url!r}" - ) - return - raise - - -def _try_fill_dsv_username_locator(locator: Any, username: str) -> bool: - try: - locator.wait_for(state="visible", timeout=1_000) - locator.wait_for(state="attached", timeout=1_000) - if not locator.is_enabled(timeout=1_000): - return False - if not _dsv_locator_can_edit(locator): - return False - locator.click(timeout=2_000) - try: - locator.fill(username, timeout=3_000) - except Exception: - locator.press("Control+A") - locator.press("Backspace") - locator.type(username, delay=30) - if _dsv_username_has_value(locator): - return True - locator.evaluate( - """ - (node, value) => { - node.focus(); - node.value = value; - node.dispatchEvent(new Event('input', { bubbles: true })); - node.dispatchEvent(new Event('change', { bubbles: true })); - } - """, - username, - ) - return _dsv_username_has_value(locator) - except Exception: - return False - - -def _fill_dsv_username(page: Any, username: str, preferred_locator: Any | None = None): - """ - 向 DSV 第一步邮箱页填写账号。 - - 核心逻辑:优先复用已经探测到的输入框,避免“检测到了邮箱框,但二次扫描更窄选择器后又找不到”的失配; - 若复用失败,再按完整候选选择器扫描各 frame。 - """ - if preferred_locator is not None and _try_fill_dsv_username_locator(preferred_locator, username): - return preferred_locator - - timeout_ms = max(5_000, int(_env("FREIGHT_RPA_LOGIN_READY_TIMEOUT_MS", "300000") or "300000")) - deadline = time.monotonic() + (timeout_ms / 1000) - while time.monotonic() < deadline: - for frame in page.frames: - for selector in _DSV_USERNAME_SELECTORS: - try: - locator = frame.locator(selector).first - if _try_fill_dsv_username_locator(locator, username): - return locator - except Exception: - pass - time.sleep(0.5) - return None - - -def _wait_for_visible_selector( - page: Any, - selector_env: str, - fallback_selectors: tuple[str, ...], - *, - timeout_ms: int | None = None, -): - selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item) - wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms() - deadline = time.monotonic() + (wait_ms / 1000) - while time.monotonic() < deadline: - for selector in selectors: - for frame in page.frames: - locator = frame.locator(selector).first - try: - if locator.is_visible(timeout=1_000): - return locator - except Exception: - pass - time.sleep(0.5) - return None - - -def _maybe_auto_login(page: Any, prefix: str) -> None: - """ - 如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。 - """ - username_env = f"FREIGHT_RPA_{prefix}_USERNAME" - password_env = f"FREIGHT_RPA_{prefix}_PASSWORD" - if not _env(username_env) or not _env(password_env): - return - - user_filled = _fill_login_field( - page, - f"FREIGHT_RPA_{prefix}_USERNAME_SELECTOR", - username_env, - ( - 'input[name="username"]', - 'input[name="userName"]', - 'input[name="email"]', - 'input[type="email"]', - 'input[type="text"]', - ), - ) - password_filled = _fill_login_field( - page, - f"FREIGHT_RPA_{prefix}_PASSWORD_SELECTOR", - password_env, - ('input[name="password"]', 'input[type="password"]'), - ) - if not user_filled and not password_filled: - return - if user_filled != password_filled: - raise RuntimeError(f"{prefix} login form partially detected; please configure login selectors") - - if not _click_login_submit( - page, - f"FREIGHT_RPA_{prefix}_LOGIN_BUTTON_SELECTOR", - ("Sign in", "Login", "Log in", "登录"), - ): - raise RuntimeError(f"{prefix} login fields detected but submit button was not found") - - page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms()) - if page.locator('input[type="password"]').first.is_visible(timeout=3_000): - raise RuntimeError(f"{prefix} login did not complete; MFA/SSO/manual verification may be required") - - -def _maybe_auto_login_dsv(page: Any) -> None: - """ - DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。 - """ - username = _env("FREIGHT_RPA_DSV_USERNAME") - password = _env("FREIGHT_RPA_DSV_PASSWORD") - auto_login_started_at = time.monotonic() - username_step_started_at = auto_login_started_at - continue_to_method_started_at: float | None = None - method_to_password_started_at: float | None = None - submit_to_home_started_at: float | None = None - portal_shell_seen_at: float | None = None - - def _report_auto_login_substage(name: str, started_at: float | None) -> None: - """记录 auto_login 内部子阶段耗时,帮助定位认证链路具体卡点。""" - if started_at is None: - return - _report_dsv_chain_stage( - f"auto_login.{name}", - "end", - started_at=started_at, - extra={"sinceAutoLoginMs": int((time.monotonic() - auto_login_started_at) * 1000)}, - ) - - def _report_portal_shell_seen() -> None: - """记录 portal 壳层首次可见时间,区分 auth 收尾和首页 ready 的等待。""" - nonlocal portal_shell_seen_at - if portal_shell_seen_at is not None: - return - portal_shell_seen_at = time.monotonic() - _report_auto_login_substage("portal_shell_seen", submit_to_home_started_at) - - if not username or not password: - return - if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=15_000) is not None: - print("[dsv-login] existing session detected") - # #region debug-point E:existing-session - _report_debug_event( - "E", - "freight_rpa_worker.py:_maybe_auto_login_dsv:existing_session", - "[DEBUG] dsv existing session detected before login flow", - _collect_dsv_reports_probe(page), - ) - # #endregion - return - - _wait_for_dsv_auth_page_ready(page) - login_ready_ms = _dsv_login_ready_timeout_ms() - print("[dsv-login] waiting username field") - username_locator = _wait_for_visible_selector( - page, - "FREIGHT_RPA_DSV_USERNAME_SELECTOR", - _DSV_USERNAME_SELECTORS, - timeout_ms=login_ready_ms, - ) - if username_locator is not None: - username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator) - user_filled = username_locator is not None - else: - username_locator = None - user_filled = _fill_first_visible_text_input(page, username) - if not user_filled: - if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=10_000) is not None: - print("[dsv-login] existing session detected") - # #region debug-point E:existing-session-late - _report_debug_event( - "E", - "freight_rpa_worker.py:_maybe_auto_login_dsv:existing_session_late", - "[DEBUG] dsv existing session detected after username probe", - _collect_dsv_reports_probe(page), - ) - # #endregion - return - if _is_dsv_oauth_handshake_url(page.url): - print("[dsv-login] still on blank oauth handshake before giving up, reload once") - try: - page.reload(wait_until="domcontentloaded", timeout=45_000) - except Exception as exc: - print(f"[dsv-login] final oauth reload failed: {exc}", file=sys.stderr) - if _wait_for_dsv_auth_page_ready(page, timeout_ms=30_000): - username_locator = _wait_for_visible_selector( - page, - "FREIGHT_RPA_DSV_USERNAME_SELECTOR", - _DSV_USERNAME_SELECTORS, - timeout_ms=15_000, - ) - if username_locator is not None: - username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator) - if username_locator is not None: - user_filled = True - if not user_filled: - try: - text = page.locator("body").inner_text(timeout=3_000) - except Exception: - text = "" - raise RuntimeError( - "DSV login state is unknown " - f"url={page.url} body={text[:300]!r} " - "(oauth handshake page stayed blank; check network/VPN or complete login manually in browser)" - ) - print("[dsv-login] username filled") - _report_auto_login_substage("username_step", username_step_started_at) - - continue_selector = _env("FREIGHT_RPA_DSV_CONTINUE_BUTTON_SELECTOR") - if continue_selector: - page.locator(continue_selector).first.click(timeout=_browser_timeout_ms(), force=True) - clicked_continue = True - else: - clicked_continue = _click_dsv_continue(page, username_locator) - if not clicked_continue: - identifier_value, button_state = _dsv_login_debug_value(page) - print(f"[dsv-login] continue missing identifier_value={identifier_value!r} button={button_state!r}") - raise RuntimeError("DSV login email step detected but continue button was not found") - print("[dsv-login] continue clicked") - continue_to_method_started_at = time.monotonic() - # #region debug-point E:continue-clicked - _report_debug_event( - "E", - "freight_rpa_worker.py:_maybe_auto_login_dsv:continue_clicked", - "[DEBUG] dsv username step submitted", - _collect_dsv_reports_probe(page), - ) - # #endregion - - print("[dsv-login] waiting password field") - password_locator = None - login_deadline = time.monotonic() + ( - max(60_000, int(_env("FREIGHT_RPA_DSV_PASSWORD_STAGE_TIMEOUT_MS", "120000") or "120000")) / 1000 - ) - password_method_clicked_at = 0.0 - username_retry_allowed_at = time.monotonic() + 6 - while time.monotonic() < login_deadline: - password_locator = _find_dsv_password_locator(page, timeout_ms=250) - if password_locator is not None: - break - if _fill_dsv_password_page_fields(page, username, password): - print("[dsv-login] password filled") - _report_auto_login_substage("continue_to_method", continue_to_method_started_at) - _report_auto_login_substage("method_to_password", method_to_password_started_at) - if not _submit_dsv_password_form(page): - raise RuntimeError("DSV login password step detected but login button was not found") - print("[dsv-login] login clicked") - submit_to_home_started_at = time.monotonic() - page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms()) - _debug_dsv_stage(page, "after-login-click-inline-password", target_text="Reports") - _dismiss_dsv_password_upgrade_prompt(page) - if page.locator('input[type="password"]').first.is_visible(timeout=3_000): - raise RuntimeError("DSV login did not complete; password may be invalid or verification is required") - _wait_for_dsv_home_ready(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen) - _report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at) - _report_auto_login_substage("password_submit_to_home", submit_to_home_started_at) - print("[dsv-login] login completed") - return - if _has_dsv_human_check_prompt(page): - _wait_for_dsv_human_check_if_present(page, timeout_ms=300_000) - if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen): - _report_auto_login_substage("continue_to_method", continue_to_method_started_at) - _report_auto_login_substage("method_to_password", method_to_password_started_at) - print("[dsv-login] login completed") - # #region debug-point E:login-completed-direct - _report_debug_event( - "E", - "freight_rpa_worker.py:_maybe_auto_login_dsv:login_completed_direct", - "[DEBUG] dsv login completed directly after human check/app wait", - _collect_dsv_reports_probe(page), - ) - # #endregion - return - method_ready = _wait_for_dsv_login_method_page(page, timeout_ms=2_000) - if method_ready: - # #region debug-point E:password-method-page - _report_debug_event( - "E", - "freight_rpa_worker.py:_maybe_auto_login_dsv:password_method_page", - "[DEBUG] dsv password method page detected", - _collect_dsv_reports_probe(page), - ) - # #endregion - if password_method_clicked_at and time.monotonic() - password_method_clicked_at < 2: - time.sleep(1) - continue - password_method_selector = _env("FREIGHT_RPA_DSV_PASSWORD_METHOD_SELECTOR") - if password_method_selector: - page.locator(password_method_selector).first.click(timeout=_browser_timeout_ms(), force=True) - clicked_password_method = True - else: - clicked_password_method = _click_dsv_password_method(page) - if not clicked_password_method: - print(f"[dsv-login] password method debug {_debug_dsv_login_method_page(page)}") - time.sleep(1) - continue - password_method_clicked_at = time.monotonic() - _report_auto_login_substage("continue_to_method", continue_to_method_started_at) - continue_to_method_started_at = None - method_to_password_started_at = password_method_clicked_at - username_retry_allowed_at = max(username_retry_allowed_at, password_method_clicked_at + 4) - print("[dsv-login] password method clicked") - # #region debug-point E:password-method-clicked - _report_debug_event( - "E", - "freight_rpa_worker.py:_maybe_auto_login_dsv:password_method_clicked", - "[DEBUG] dsv password method clicked", - _collect_dsv_reports_probe(page), - ) - # #endregion - continue - # [STEP 2] Continue 刚提交或刚点过“密码”时,先给 PingID 页面一点切换时间, - # 避免方法页尚未稳定时又误判回邮箱页,造成来回重填账号。 - if time.monotonic() >= username_retry_allowed_at and _is_dsv_username_page(page): - username_locator = _fill_dsv_username(page, username) - if username_locator is None and not _fill_first_visible_text_input(page, username): - print(f"[dsv-login] username retry failed {_debug_dsv_login_method_page(page)}") - time.sleep(1) - continue - if _click_dsv_continue(page, username_locator): - print("[dsv-login] username page retried") - username_retry_allowed_at = time.monotonic() + 6 - time.sleep(1) - continue - password_locator = _find_dsv_password_locator(page, timeout_ms=250) - if password_locator is not None: - break - if _is_dsv_blank_auth_transition(page): - _wait_for_dsv_auth_page_ready(page, timeout_ms=5_000) - password_locator = _find_dsv_password_locator(page, timeout_ms=500) - if password_locator is not None: - break - time.sleep(1) - - if password_locator is None: - if "s360.dbschenker.com" in page.url and _wait_for_dsv_app_after_login(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen): - print("[dsv-login] login completed") - # #region debug-point E:login-completed-late - _report_debug_event( - "E", - "freight_rpa_worker.py:_maybe_auto_login_dsv:login_completed_late", - "[DEBUG] dsv login completed after password wait fallback", - _collect_dsv_reports_probe(page), - ) - # #endregion - return - try: - text = page.locator("body").inner_text(timeout=3_000) - except Exception: - text = "" - if not text.strip(): - print(f"[dsv-login] password page still loading url={page.url}") - if _is_dsv_blank_auth_transition(page): - _wait_for_dsv_auth_page_ready(page, timeout_ms=_dsv_login_ready_timeout_ms()) - password_locator = _wait_for_visible_selector( - page, - "FREIGHT_RPA_DSV_PASSWORD_SELECTOR", - ("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'), - timeout_ms=_dsv_login_ready_timeout_ms(), - ) - if password_locator is None: - if not _fill_dsv_password_page_fields(page, username, password): - raise RuntimeError("DSV login password field was not found") - print("[dsv-login] password filled") - _report_auto_login_substage("continue_to_method", continue_to_method_started_at) - _report_auto_login_substage("method_to_password", method_to_password_started_at) - if not _submit_dsv_password_form(page): - raise RuntimeError("DSV login password step detected but login button was not found") - print("[dsv-login] login clicked") - submit_to_home_started_at = time.monotonic() - page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms()) - _debug_dsv_stage(page, "after-login-click-late-password", target_text="Reports") - _dismiss_dsv_password_upgrade_prompt(page) - _wait_for_dsv_home_ready(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen) - _report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at) - _report_auto_login_substage("password_submit_to_home", submit_to_home_started_at) - print("[dsv-login] login completed") - return - print(f"[dsv-login] password field missing url={page.url} body={text[:300]!r} method_debug={_debug_dsv_login_method_page(page)}") - raise RuntimeError("DSV login password field was not found") - - password_locator.fill(password, timeout=_browser_timeout_ms()) - print("[dsv-login] password filled") - _report_auto_login_substage("continue_to_method", continue_to_method_started_at) - _report_auto_login_substage("method_to_password", method_to_password_started_at) - if not _submit_dsv_password_form(page): - raise RuntimeError("DSV login password step detected but login button was not found") - print("[dsv-login] login clicked") - submit_to_home_started_at = time.monotonic() - # #region debug-point N:login-clicked - _report_debug_event( - "N", - "freight_rpa_worker.py:_maybe_auto_login_dsv:login_clicked", - "[DEBUG] dsv login button submitted", - {"url": page.url}, - ) - # #endregion - - page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms()) - # #region debug-point N:after-domcontentloaded - _report_debug_event( - "N", - "freight_rpa_worker.py:_maybe_auto_login_dsv:after_domcontentloaded", - "[DEBUG] dsv login flow reached domcontentloaded after submit", - {"url": page.url}, - ) - # #endregion - _debug_dsv_stage(page, "after-login-click-password-locator", target_text="Reports") - _dismiss_dsv_password_upgrade_prompt(page) - if page.locator('input[type="password"]').first.is_visible(timeout=3_000): - raise RuntimeError("DSV login did not complete; password may be invalid or verification is required") - _wait_for_dsv_home_ready(page, timeout_ms=60_000, on_portal_shell_seen=_report_portal_shell_seen) - _report_auto_login_substage("portal_shell_to_home_ready", portal_shell_seen_at) - _report_auto_login_substage("password_submit_to_home", submit_to_home_started_at) - print("[dsv-login] login completed") - - -def _dismiss_dsv_password_upgrade_prompt(page: Any) -> None: - """ - DSV 首次登录后可能提示升级密码登录;RPA 选择“也许以后”继续进入系统。 - """ - started_at = time.monotonic() - # #region debug-point M:upgrade-prompt-entry - _report_debug_event( - "M", - "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:entry", - "[DEBUG] checking dsv password upgrade prompt", - {"url": page.url}, - ) - # #endregion - selector = _env("FREIGHT_RPA_DSV_MAYBE_LATER_SELECTOR") - if selector: - candidates = (selector,) - else: - candidates = ( - 'button.dbs-sims-button-secondary:has-text("也许以后")', - 'button.dbs-sims-button-secondary:has-text("Maybe later")', - 'button.dbs-sims-button-secondary:has-text("Not now")', - 'button:has-text("也许以后")', - 'a:has-text("也许以后")', - 'text=也许以后', - 'button:has-text("Maybe later")', - 'a:has-text("Maybe later")', - 'text=Maybe later', - 'button:has-text("Not now")', - 'a:has-text("Not now")', - 'text=Not now', - ) - def _prompt_visible() -> bool: - return _has_dsv_password_upgrade_prompt(page, timeout_ms=250) - - # [STEP 1] 先做一次轻量探测门;没看到升级提示强特征时,直接跳过, - # 避免在 Verifying compliance / auth 跳转页里做大范围阻塞轮询。 - quick_detect_deadline = time.monotonic() + 2.5 - prompt_detected = _prompt_visible() - while not prompt_detected and time.monotonic() < quick_detect_deadline: - time.sleep(0.2) - prompt_detected = _prompt_visible() - if not prompt_detected: - # #region debug-point M:upgrade-prompt-skip - _report_debug_event( - "M", - "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:skip", - "[DEBUG] dsv password upgrade prompt not shown", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, - ) - # #endregion - return - - deadline = time.monotonic() + 8 - while time.monotonic() < deadline: - roots = [page, *getattr(page, "frames", [])] - for root in roots: - for candidate in candidates: - try: - locator = root.locator(candidate).first - locator.wait_for(state="attached", timeout=300) - try: - locator.scroll_into_view_if_needed(timeout=1_000) - except Exception: - pass - try: - locator.click(timeout=1_500, force=True) - except Exception: - locator.evaluate( - """ - (target) => { - target.click(); - target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); - } - """ - ) - time.sleep(1) - if not _prompt_visible(): - print("[dsv-login] password upgrade prompt dismissed") - # #region debug-point M:upgrade-prompt-dismissed - _report_debug_event( - "M", - "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:dismissed", - "[DEBUG] dsv password upgrade prompt dismissed", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), "candidate": candidate, "url": page.url}, - ) - # #endregion - try: - page.wait_for_load_state("domcontentloaded", timeout=10_000) - except Exception: - pass - return - except Exception: - continue - if not _prompt_visible(): - # #region debug-point M:upgrade-prompt-skip - _report_debug_event( - "M", - "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:skip", - "[DEBUG] dsv password upgrade prompt disappeared before click", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, - ) - # #endregion - return - _debug_dsv_stage(page, "password-upgrade-prompt-still-visible", target_text="Maybe later") - time.sleep(0.4) - # #region debug-point M:upgrade-prompt-timeout - _report_debug_event( - "M", - "freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:timeout", - "[DEBUG] dsv password upgrade prompt remained visible until timeout", - {"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url}, - ) - # #endregion - - _INVENTORY_EXCEL_MIN_BYTES = 512 _INVENTORY_EXCEL_HEADER_MARKERS = ( "on hand inventory", @@ -3994,7 +493,7 @@ def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dic suggested = str(download.suggested_filename or "") suffix = Path(suggested).suffix or ".xlsx" source_code = str(source.get("source_code") or "UNKNOWN") - warehouse_id = str(source.get("warehouse_id") or source.get("warehouse_code") or "WH") + warehouse_id = str(source.get("warehouse_id") or "WH") dest = drop_dir / _batch_download_name(run_no, source_code, warehouse_id, suffix=suffix) download.save_as(str(dest)) if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}: @@ -4002,389 +501,129 @@ def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dic return dest -def _fill_dsv_multi_select(page: Any, selector_env: str, label: str, values: list[str]) -> None: +def _validate_inventory_source_for_rpa(source: dict[str, Any]) -> None: """ - 填充 DSV 报表多选控件(multi_select)。 - 核心逻辑:优先 select_option 多值;失败则展开控件后逐条点击 option/checkbox。 + 校验单个库存 RPA source 的最小定位条件。 + 核心逻辑:DSV 必须有 site_id;Crane 只需要 source_type 即可分发,warehouse id 由库存 Excel 结果决定。 """ - cleaned = [str(item).strip() for item in values if str(item).strip()] - if not cleaned: - return - selector = _env(selector_env) - if selector: - locator = page.locator(selector).first - try: - locator.select_option(label=cleaned, timeout=_browser_timeout_ms()) - print(f"[dsv-filter] {label} multi_select via select_option labels={cleaned!r}") - return - except Exception: - pass - try: - locator.select_option(value=cleaned, timeout=_browser_timeout_ms()) - print(f"[dsv-filter] {label} multi_select via select_option values={cleaned!r}") - return - except Exception: - pass - try: - locator.click(timeout=_browser_timeout_ms()) - for value in cleaned: - option = page.get_by_role("option", name=value).first - if option.is_visible(timeout=2_000): - option.click(timeout=_browser_timeout_ms()) - continue - page.get_by_text(value, exact=False).first.click(timeout=_browser_timeout_ms()) - print(f"[dsv-filter] {label} multi_select via click options={cleaned!r}") - return - 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) + source_type = str(source.get("source_type") or "").strip() + source_code = str(source.get("source_code") or "").strip() or "UNKNOWN" + site_id = str(source.get("site_id") or "").strip() + if source_type not in {"dsv360", "crane_footprint"}: + raise RuntimeError(f"{source_code}: source_type must be dsv360 or crane_footprint") + if source_type == "dsv360" and not site_id: + raise RuntimeError(f"{source_code}: site_id is required for dsv360") -def _fill_report_parameter(page: Any, parameter: dict[str, Any]) -> None: - """按 JSON parameters 配置填充 DSV 报表参数(single / multi_text / multi_select)。""" - if not isinstance(parameter, dict): - return - name = str(parameter.get("name") or "").strip() - mode = str(parameter.get("mode") or "single").strip().lower() - selector_env = str(parameter.get("selector_env") or "").strip() - values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()] - if not name or not values: - return - if mode == "multi_text": - joiner = str(parameter.get("joiner") or ",") - _fill_dsv_filter_if_needed(page, selector_env, name, joiner.join(values)) - return - if mode == "multi_select": - _fill_dsv_multi_select(page, selector_env, name, values) - return - _fill_dsv_filter_if_needed(page, selector_env, name, values[0]) -def _fill_report_parameters(page: Any, source: dict[str, Any]) -> None: - """填充 source.parameters;无 parameters 时回退 query 字段。""" - parameters = source.get("parameters") - if isinstance(parameters, list) and parameters: - for item in parameters: - _fill_report_parameter(page, item) - return - query = source.get("query") if isinstance(source.get("query"), dict) else {} - _fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code")) - _fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone")) - _fill_dsv_filter_if_needed(page, "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code")) +def _load_crane_session_module() -> Any: + """运行时加载 crane_session,避免 freight_rpa_worker 继续膨胀。""" + import importlib.util + from pathlib import Path + + module_path = Path(__file__).resolve().parent / "crane_session.py" + spec = importlib.util.spec_from_file_location("crane_session_runtime", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module -def _dsv_entry_url_host(entry_url: str) -> str: - """从 entry_url 提取 host,用于判断当前 page 是否仍在同一 DSV 站点。""" - from urllib.parse import urlparse - - parsed = urlparse(str(entry_url or "").strip()) - return (parsed.netloc or "").lower() - - -def _is_dsv_on_entry_site(page: Any, entry_url: str) -> bool: - """当前 tab 是否已在目标 entry_url 对应 portal 域(非 auth 跳转页)。""" - host = _dsv_entry_url_host(entry_url) - if not host: - return False - try: - current_url = str(page.url or "").lower() - except Exception: - return False - if "auth.dbschenker.com" in current_url: - return False - return host in current_url - - -def _is_dsv_session_active(page: Any, entry_url: str) -> bool: - """ - 判定浏览器是否已在同一 entry_url 站点维持有效登录态。 - - 核心逻辑:batch 内 source_code 不同但 entry_url 一致时,后续步骤不应重复 OAuth; - 首页、portal 壳层、或 SSRS 参数页均视为 session 仍有效。 - """ - if not _is_dsv_on_entry_site(page, entry_url): - return False - if _is_dsv_home_ready(page) or _has_dsv_portal_shell(page): - return True - for frame in page.frames: - try: - frame_url = str(frame.url or "").lower() - except Exception: - frame_url = "" - if "/s360reports/reports/default.aspx" in frame_url: - return True - try: - if frame.locator("#ReportViewerMain").count() > 0: - return True - except Exception: - continue - return False - - -def _ensure_dsv_session(page: Any, entry_url: str) -> None: - """DSV 360 一次登录并等待首页/Reports 导航就绪。""" - if _is_dsv_session_active(page, entry_url): - print("[dsv] session already active on entry site, skip login") - _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) - _maybe_auto_login_dsv(page) - _wait_for_dsv_home_ready(page, timeout_ms=60_000) - _wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000) - - -def _reset_dsv_export_entry(page: Any, entry_url: str) -> None: - """ - 批量导出中 navigation 变化时回到 portal 首页。 - 核心逻辑:同 entry_url 且 session 仍有效时不重复登录,仅回首页待命; - 同 navigation 连续导出请改用 _return_to_dsv_report_parameters。 - """ - print("[dsv] reset export entry before next source") - if _is_dsv_session_active(page, entry_url): - print("[dsv] same entry_url session active, skip re-login") - if not _is_dsv_home_ready(page): - _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) - _maybe_auto_login_dsv(page) - _wait_for_dsv_home_ready(page, timeout_ms=30_000) - _wait_for_dsv_reports_nav_stable(page, timeout_ms=8_000) - - -def _dsv_navigation_signature(source: dict[str, Any]) -> tuple[str, str, str, str]: - """提取 DSV 报表 navigation 四元组,用于判断批量导出是否可复用参数页。""" - query = source.get("query") if isinstance(source.get("query"), dict) else {} - navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {} - return ( - str(query.get("program_group") or navigation.get("program_group") or "").strip(), - str(query.get("program_label") or navigation.get("program_label") or "").strip(), - str(query.get("report_group") or navigation.get("report_group") or "").strip(), - str(query.get("report_name") or navigation.get("report_name") or "").strip(), +def _maybe_auto_login_crane(page: Any) -> None: + """Crane FootPrint 登录:User Name / Password / Sign in(见 crane_session.py)。""" + module = _load_crane_session_module() + module.maybe_auto_login_crane( + page, + env=_env, + browser_timeout_ms=_browser_timeout_ms(), ) -def _dsv_sources_share_navigation(previous: dict[str, Any] | None, current: dict[str, Any]) -> bool: - """连续 source 的 program/report 导航一致时,可跳过 portal 首页重进。""" - if not previous: - return False - prev_sig = _dsv_navigation_signature(previous) - curr_sig = _dsv_navigation_signature(current) - return bool(prev_sig == curr_sig and all(prev_sig)) +def _is_crane_session_active(page: Any, entry_url: str) -> bool: + """判定 Crane portal 是否已登录且无需重复填写登录表单。""" + module = _load_crane_session_module() + return bool(module.is_crane_session_active(page, entry_url)) -def _dsv_report_name(source: dict[str, Any]) -> str: - """从 source 解析报表名称。""" - query = source.get("query") if isinstance(source.get("query"), dict) else {} - navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {} - return str(query.get("report_name") or navigation.get("report_name") or "On Hand Inventory by Location") +def _wait_for_crane_app_ready(page: Any, entry_url: str) -> None: + """登录后等待 On Hand Details Query 等目标路由就绪。""" + module = _load_crane_session_module() + module.wait_for_crane_app_ready( + page, + entry_url, + env=_env, + browser_timeout_ms=_browser_timeout_ms(), + ) -def _find_dsv_report_parameter_frame(page: Any) -> Any | None: - """定位承载 SSRS ReportViewer 参数区的 report-frame。""" - for frame in page.frames: - try: - frame_url = str(frame.url or "").lower() - except Exception: - frame_url = "" - if "/s360reports/reports/default.aspx" in frame_url: - return frame - try: - if frame.locator("#ReportViewerMain").count() > 0: - return frame - except Exception: - continue - return None - - -def _return_to_dsv_report_parameters(page: Any, report_name: str) -> None: - """ - 导出完成后回到同一报表的参数页,仅改 Warehouse 后再次 View Report。 - 核心逻辑:reload report-frame 的 Default.aspx URL,避免 batch 同 navigation 时回 portal 首页。 - """ - frame = _find_dsv_report_parameter_frame(page) - if frame is None: - raise RuntimeError("DSV report parameter frame not found for reuse") - try: - report_url = str(frame.url or "").strip() - except Exception: - report_url = "" - if not report_url: - raise RuntimeError("DSV report parameter frame has empty url") - print("[dsv] reuse report parameter form via report-frame reload") - frame.goto(report_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) - try: - page.wait_for_load_state("networkidle", timeout=min(_browser_timeout_ms(), 8_000)) - except Exception: - pass - _wait_for_dsv_report_form_ready(page, report_name) - - -def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str: - """从 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) - - reports_selector = _env("FREIGHT_RPA_DSV_REPORTS_SELECTOR") - if reports_selector: - page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True) - else: - _click_dsv_reports_menu(page) - _wait_for_dsv_reports_open(page, timeout_ms=10_000) - - program_selector = _env("FREIGHT_RPA_DSV_PROGRAM_SELECTOR") - program_label = str(query.get("program_label") or navigation.get("program_label") or "") - if program_selector: - page.locator(program_selector).first.click(timeout=_browser_timeout_ms()) - else: - _click_dsv_menu_item(page, program_label, next_text=str(query.get("report_group") or navigation.get("report_group") or "Inventory")) - - report_group_selector = _env("FREIGHT_RPA_DSV_REPORT_GROUP_SELECTOR") - report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory") - 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("FREIGHT_RPA_DSV_REPORT_NAME_SELECTOR") - if report_name_selector: - page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms()) - else: - _click_dsv_menu_item(page, report_name) - - _wait_for_dsv_report_form_ready(page, 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) - 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()) - with page.expect_download(timeout=_browser_timeout_ms()) as download_info: - _click_dsv_export_excel(page) - return download_info.value - - -def _prepare_dsv_batch_export_step( - page: Any, - entry_url: str, - previous_source: dict[str, Any] | None, - source: dict[str, Any], - *, - index: int, -) -> bool: - """ - 批量导出单步前置:首条登录;同 navigation 复用参数页;否则回首页重导航。 - 同 entry_url 的 batch 内仅 index=0 可能触发完整登录,后续步骤 session 有效则跳过 OAuth。 - - Returns: - True 表示参数页已就绪且可 skip 完整菜单导航。 - """ - if index == 0: - _ensure_dsv_session(page, entry_url) - return False - if _dsv_sources_share_navigation(previous_source, source): - report_name = _dsv_report_name(source) - try: - _return_to_dsv_report_parameters(page, report_name) - print( - "[dsv-batch] reuse parameter form " - f"navigation={_dsv_navigation_signature(source)!r}" - ) - return True - except Exception as exc: - print(f"[dsv-batch] parameter reuse failed, fallback home reset: {exc}", file=sys.stderr) - _reset_dsv_export_entry(page, entry_url) - return False - - -def _export_dsv_inventory_source( - page: Any, - trigger: dict[str, Any], - source: dict[str, Any], - *, - skip_navigation: bool = False, -) -> Any: - """在已登录 DSV session 上导出单个 Warehouse 库存。""" - if not skip_navigation: - _navigate_dsv_to_report_form(page, source) - return _run_dsv_inventory_export_from_form(page, source) +def _goto_crane_entry_url(page: Any, entry_url: str) -> None: + """打开 Crane 报表入口;已在目标站点且 session 有效时可跳过 goto。""" + if _is_crane_session_active(page, entry_url): + print("[crane] session already active on entry site, skip goto") + _wait_for_crane_app_ready(page, entry_url) + return + page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) def _ensure_crane_session(page: Any, entry_url: str) -> None: - """Crane FootPrint 一次登录。""" - page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) - _maybe_auto_login(page, "CRANE") + """ + Crane FootPrint 一次登录并等待报表页就绪。 + 核心逻辑:session 已有效时仅等待报表路由,不重复填写登录表单。 + """ + if _is_crane_session_active(page, entry_url): + print("[crane] session already active on entry site, skip login") + _wait_for_crane_app_ready(page, entry_url) + return + _goto_crane_entry_url(page, entry_url) + _maybe_auto_login_crane(page) + _wait_for_crane_app_ready(page, entry_url) def _reset_crane_export_entry(page: Any, entry_url: str) -> None: - """批量导出中每个 Crane source 前回到报表表单入口。""" + """ + 批量导出中每个 Crane source 前回到报表表单入口。 + 核心逻辑:同 entry_url 且 session 仍有效时仅 reload 路由,不重复登录。 + """ print("[crane] reset export entry before next source") + if _is_crane_session_active(page, entry_url): + print("[crane] same entry_url session active, skip re-login") + page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) + _wait_for_crane_app_ready(page, entry_url) + return page.goto(entry_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms()) - _maybe_auto_login(page, "CRANE") + _maybe_auto_login_crane(page) + _wait_for_crane_app_ready(page, entry_url) -def _fill_crane_report_parameter(page: Any, parameter: dict[str, Any]) -> None: - """按 JSON parameters 填充 Crane 报表参数。""" - if not isinstance(parameter, dict): - return - name = str(parameter.get("name") or "").strip().lower() - mode = str(parameter.get("mode") or "single").strip().lower() - selector_env = str(parameter.get("selector_env") or "").strip() - values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()] - if not values: - return - label_map = { - "owner": "Select Owner...", - "project": "Select Project...", - "warehouse": "Choose Warehouse ..", - } - label = label_map.get(name, name) - if mode == "multi_select": - for value in values: - _select_or_fill(page, selector_env, label, value) - return - if mode == "multi_text": - joiner = str(parameter.get("joiner") or ",") - _select_or_fill(page, selector_env, label, joiner.join(values)) - return - _select_or_fill(page, selector_env, label, values[0]) +def _load_crane_report_export_module() -> Any: + """运行时加载 crane_report_export。""" + import importlib.util + from pathlib import Path - -def _fill_crane_report_parameters(page: Any, source: dict[str, Any]) -> None: - """填充 Crane source.parameters;无 parameters 时回退 query。""" - parameters = source.get("parameters") - if isinstance(parameters, list) and parameters: - for item in parameters: - _fill_crane_report_parameter(page, item) - return - query = source.get("query") if isinstance(source.get("query"), dict) else {} - _select_or_fill(page, "FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code")) - _select_or_fill(page, "FREIGHT_RPA_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code")) - _select_or_fill(page, "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR", "Choose Warehouse ..", query.get("warehouse_code")) + module_path = Path(__file__).resolve().parent / "crane_report_export.py" + spec = importlib.util.spec_from_file_location("crane_report_export_runtime", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module def _export_crane_inventory_source(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any: - """在已登录 Crane session 上导出单个 Warehouse 库存。""" - _fill_crane_report_parameters(page, source) - _click_selector_or_text(page, "FREIGHT_RPA_CRANE_RUN_SELECTOR", "Run Report") - export_selector = _env("FREIGHT_RPA_CRANE_EXPORT_SELECTOR") - export_text = _env("FREIGHT_RPA_CRANE_EXPORT_TEXT", "file_download") - with page.expect_download(timeout=_browser_timeout_ms()) as download_info: - if export_selector: - page.locator(export_selector).first.click(timeout=_browser_timeout_ms()) - else: - _click_text(page, export_text, exact=True) - return download_info.value + """ + 在已登录 Crane session 上导出库存。 + 核心逻辑:Run Report → Schedule Report → Scheduled Reports 异步下载(不填 Warehouse)。 + """ + module = _load_crane_report_export_module() + return module.export_crane_inventory_report( + page, + source, + trigger=trigger, + env=_env, + browser_timeout_ms=_browser_timeout_ms(), + select_or_fill=_select_or_fill, + click_text=_click_text, + ) def _open_browser(download_dir: Path): @@ -4429,15 +668,8 @@ def _open_browser(download_dir: Path): def _download_dsv360_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any: - """ - 单票 trigger 的 DSV 360 导出。 - 核心逻辑:与批量导出共用 _ensure_dsv_session + _export_dsv_inventory_source,确保 parameters/Warehouse 一致。 - """ - entry_url = str(source.get("entry_url") or "").strip() - if not entry_url: - raise RuntimeError("DSV360 inventory source missing entry_url") - _ensure_dsv_session(page, entry_url) - return _export_dsv_inventory_source(page, trigger, source) + """单票 DSV 360 导出;委托 dsv_driver。""" + return dsv_driver.download_dsv360_inventory(page, trigger, source) def _download_crane_inventory(page: Any, trigger: dict[str, Any], source: dict[str, Any]) -> Any: @@ -4456,8 +688,7 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) -> raise RuntimeError("inventory trigger missing rpa_inventory_source") source_type = str(source.get("source_type") or "").strip() source_code = str(source.get("source_code") or "").strip() or source_type or "UNKNOWN" - if not source_type: - raise RuntimeError("inventory source missing source_type") + _validate_inventory_source_for_rpa(source) playwright = context = runtime_profile_dir = None keep_open_on_error = _env("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true" @@ -4509,6 +740,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe out_file = _write_sample_inventory(drop_dir, task_stub) results.append({ "source_code": source.get("source_code"), + "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), "success": True, "file_path": str(out_file), @@ -4519,7 +751,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe for source in sources: if not isinstance(source, dict): continue - site = str(source.get("source_type") or "").strip() or "dsv360" + site = str(source.get("source_type") or "").strip() grouped.setdefault(site, []).append(source) for site, site_sources in grouped.items(): @@ -4535,6 +767,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"), + "site_id": source.get("site_id"), "warehouse_id": source.get("warehouse_id"), "success": False, "error_message": f"unsupported source_type: {site}", @@ -4545,6 +778,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe code = str(source.get("source_code") or "") wh = str(source.get("warehouse_id") or "") try: + _validate_inventory_source_for_rpa(source) skip_navigation = False if site == "dsv360": skip_navigation = _prepare_dsv_batch_export_step( @@ -4563,6 +797,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe out_file = _save_batch_download(download, drop_dir, run_no, source) results.append({ "source_code": code, + "site_id": source.get("site_id"), "warehouse_id": wh, "success": True, "file_path": str(out_file), @@ -4572,6 +807,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe except Exception as exc: results.append({ "source_code": code, + "site_id": source.get("site_id"), "warehouse_id": wh, "success": False, "error_message": str(exc), diff --git a/scripts/rpa/rpa_common.py b/scripts/rpa/rpa_common.py new file mode 100644 index 00000000..f6187018 --- /dev/null +++ b/scripts/rpa/rpa_common.py @@ -0,0 +1,466 @@ +""" +scripts/rpa/rpa_common.py + +用途:RPA worker 与 DSV/Crane driver 共用的浏览器与环境变量工具。 +依赖:标准库、Playwright(运行时)。 +逻辑:由 freight_rpa_worker、dsv_*、crane_* 导入。 +""" + +from __future__ import annotations + +import json +import os +import sys +import time +import urllib.request +from pathlib import Path +from typing import Any, TextIO + + +def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None: + """惰性委托 dsv_debug.emit_debug_event,避免 rpa_common ↔ dsv_debug 循环导入。""" + try: + from dsv_debug import emit_debug_event + + emit_debug_event(run_id, hypothesis_id, location, msg, data) + except Exception: + return + + +def _env(name: str, default: str = "") -> str: + """ + 读取 RPA 环境变量,并兼容 .env 中常见的外层单双引号写法。 + + 核心逻辑:先读取原始环境变量并去除首尾空白;若值整体被同种引号包裹, + 再剥离最外层一对引号,避免账号密码把引号一并输入到第三方登录页。 + + Args: + name: 环境变量名。 + default: 未设置时的默认值。 + + Returns: + str: 去除空白与外层成对引号后的环境变量值。 + """ + value = str(os.getenv(name) or default).strip() + if len(value) >= 2 and ( + (value.startswith('"') and value.endswith('"')) + or (value.startswith("'") and value.endswith("'")) + ): + return value[1:-1] + return value + + +def _browser_timeout_ms() -> int: + return max(5_000, int(_env("FREIGHT_RPA_BROWSER_TIMEOUT_MS", "60000") or "60000")) + +def _click_text(page: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> None: + timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms() + text_literal = json.dumps(text) + for selector in ( + f"a.dropdown-item:has-text({text_literal})", + f".dropdown-item:has-text({text_literal})", + f"button:has-text({text_literal})", + f'[role="button"]:has-text({text_literal})', + f"a:has-text({text_literal})", + f"li:has-text({text_literal})", + f"div.device-type:has-text({text_literal})", + ): + locator = page.locator(selector).first + try: + locator.click(timeout=3_000) + return + except Exception: + pass + try: + locator.click(timeout=3_000, force=True) + return + except Exception: + pass + for role in ("button", "link"): + try: + page.get_by_role(role, name=text, exact=exact).first.click(timeout=3_000) + return + except Exception: + pass + locator = page.get_by_text(text, exact=False).first + try: + locator.click(timeout=min(timeout, 3_000)) + return + except Exception: + pass + locator.click(timeout=min(timeout, 3_000), force=True) + + +def _click_selector_or_text(page: Any, selector_env: str, fallback_text: str | None = None) -> None: + selector = _env(selector_env) + if selector: + page.locator(selector).first.click(timeout=_browser_timeout_ms()) + return + if selector_env == "FREIGHT_RPA_DSV_VIEW_REPORT_SELECTOR": + for view_selector in ( + 'input[type="submit"][value="View Report"]', + 'button:has-text("View Report")', + '.btn:has-text("View Report")', + 'input[value="View Report"]', + '[role="button"]:has-text("View Report")', + ): + try: + locator = page.locator(view_selector).first + locator.wait_for(state="visible", timeout=30_000) + locator.evaluate("(node) => node.click()") + return + except Exception: + pass + if fallback_text: + _click_text(page, fallback_text, exact=True) + return + raise RuntimeError(f"Missing selector env: {selector_env}") + + +def _fill_selector_or_label(page: Any, selector_env: str, label: str, value: str | None) -> None: + text = str(value or "").strip() + if not text: + return + selector = _env(selector_env) + locator = page.locator(selector).first if selector else page.get_by_label(label).first + try: + current = str(locator.input_value(timeout=3_000) or "").strip() + if current == text: + return + except Exception: + pass + locator.fill(text, timeout=_browser_timeout_ms()) + + +def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: str | None) -> None: + """委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。""" + import importlib.util + from pathlib import Path + + 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) + module.fill_dsv_filter_if_needed( + page, + selector_env, + label, + value, + env=_env, + browser_timeout_ms=_browser_timeout_ms, + debug_stage=_debug_dsv_stage, + ) + + +def _select_or_fill(page: Any, selector_env: str, label: str, value: str | None) -> None: + text = str(value or "").strip() + if not text: + return + selector = _env(selector_env) + locator = page.locator(selector).first if selector else page.get_by_label(label) + try: + locator.select_option(label=text, timeout=_browser_timeout_ms()) + return + except Exception: + pass + try: + locator.select_option(value=text, timeout=_browser_timeout_ms()) + return + except Exception: + pass + locator.fill(text, timeout=_browser_timeout_ms()) + + +def _visible_locator(page: Any, selector: str | None): + if not selector: + return None + for frame in page.frames: + locator = frame.locator(selector).first + try: + return locator if locator.is_visible(timeout=1_000) else None + except Exception: + pass + return None + + +def _visible_locator_in_root(root: Any, selector: str | None): + if not selector: + return None + try: + locator = root.locator(selector).first + return locator if locator.is_visible(timeout=1_000) else None + except Exception: + return None + + +def _click_text_in_root(root: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> bool: + timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms() + text_literal = json.dumps(text) + for selector in ( + f'a.dropdown-item:has-text({text_literal})', + f'.dropdown-item:has-text({text_literal})', + f'button:has-text({text_literal})', + f'[role="button"]:has-text({text_literal})', + f'a:has-text({text_literal})', + f'li:has-text({text_literal})', + f'span:has-text({text_literal})', + ): + try: + locator = root.locator(selector).first + locator.click(timeout=min(timeout, 3_000)) + return True + except Exception: + pass + try: + locator = root.locator(selector).first + locator.click(timeout=min(timeout, 3_000), force=True) + return True + except Exception: + pass + for role in ("button", "link"): + try: + root.get_by_role(role, name=text, exact=exact).first.click(timeout=min(timeout, 3_000)) + return True + except Exception: + pass + try: + root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000)) + return True + except Exception: + pass + try: + root.get_by_text(text, exact=False).first.click(timeout=min(timeout, 3_000), force=True) + return True + except Exception: + return False + + +def _click_visible_selector_or_text_in_root(root: Any, selector: str | None, fallback_texts: tuple[str, ...]) -> bool: + locator = _visible_locator_in_root(root, selector) + if locator is not None: + # #region debug-point H4:root-selector-click-attempt + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-attempt", + "[DEBUG] attempting selector click in selected root", + {"selector": selector or "", "fallbackTexts": list(fallback_texts)}, + ) + # #endregion + try: + locator.click(timeout=_browser_timeout_ms()) + # #region debug-point H4:root-selector-click-success + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-success", + "[DEBUG] selector click succeeded in selected root", + {"selector": selector or ""}, + ) + # #endregion + return True + except Exception as exc: + # #region debug-point H4:root-selector-click-error + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:selector-error", + "[DEBUG] selector click failed in selected root", + {"selector": selector or "", "error": str(exc)[:300]}, + ) + # #endregion + for text in fallback_texts: + # #region debug-point H4:root-text-click-attempt + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-attempt", + "[DEBUG] attempting text click in selected root", + {"text": text, "selector": selector or ""}, + ) + # #endregion + clicked = _click_text_in_root(root, text, exact=True, timeout_ms=3_000) + # #region debug-point H4:root-text-click-result + _emit_debug_event( + "pre-fix", + "H4", + "freight_rpa_worker.py:_click_visible_selector_or_text_in_root:text-result", + "[DEBUG] text click result in selected root", + {"text": text, "clicked": clicked, "selector": selector or ""}, + ) + # #endregion + if clicked: + return True + return False + + +def _fill_login_field(page: Any, selector_env: str, value_env: str, fallback_selectors: tuple[str, ...]) -> bool: + value = _env(value_env) + if not value: + return False + selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item) + for selector in selectors: + locator = _visible_locator(page, selector) + if locator is None: + continue + locator.fill(value, timeout=_browser_timeout_ms()) + return True + return False + + +def _fill_first_visible_text_input(page: Any, value: str) -> bool: + for selector in ( + 'input:not([type])', + 'input[type="text"]', + 'input[type="email"]', + 'input', + ): + for frame in page.frames: + try: + inputs = frame.locator(selector).all() + except Exception: + inputs = [] + for locator in inputs: + try: + if not locator.is_visible(timeout=500) or not _dsv_locator_can_edit(locator): + continue + locator.fill(value, timeout=2_000) + if locator.input_value(timeout=1_000).strip(): + return True + except Exception: + pass + return False + + +def _click_login_submit(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool: + selector = _env(selector_env) + locator = _visible_locator(page, selector) + if locator is not None: + locator.click(timeout=_browser_timeout_ms()) + return True + for text in fallback_texts: + try: + page.get_by_role("button", name=text).click(timeout=3_000) + return True + except Exception: + pass + try: + page.get_by_text(text, exact=True).click(timeout=3_000) + return True + except Exception: + pass + return False + + +def _click_visible_selector_or_text(page: Any, selector_env: str, fallback_texts: tuple[str, ...]) -> bool: + selector = _env(selector_env) + locator = _visible_locator(page, selector) + if locator is not None: + locator.click(timeout=_browser_timeout_ms()) + return True + if any(text in {"登录", "Login", "Log in", "Sign in"} for text in fallback_texts): + for submit_selector in ( + 'button[type="submit"]', + 'input[type="submit"]', + "#signOnButton", + ".btn-primary", + ): + locator = _visible_locator(page, submit_selector) + if locator is None: + continue + locator.click(timeout=3_000, force=True) + return True + for text in fallback_texts: + try: + _click_text(page, text, exact=True, timeout_ms=3_000) + return True + except Exception: + pass + return False +def _wait_for_visible_selector( + page: Any, + selector_env: str, + fallback_selectors: tuple[str, ...], + *, + timeout_ms: int | None = None, +): + selectors = tuple(item for item in (_env(selector_env), *fallback_selectors) if item) + wait_ms = timeout_ms if timeout_ms is not None else _browser_timeout_ms() + deadline = time.monotonic() + (wait_ms / 1000) + while time.monotonic() < deadline: + for selector in selectors: + for frame in page.frames: + locator = frame.locator(selector).first + try: + if locator.is_visible(timeout=1_000): + return locator + except Exception: + pass + time.sleep(0.5) + return None + + +def _maybe_auto_login(page: Any, prefix: str) -> None: + """ + 如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。 + """ + username_env = f"FREIGHT_RPA_{prefix}_USERNAME" + password_env = f"FREIGHT_RPA_{prefix}_PASSWORD" + if not _env(username_env) or not _env(password_env): + return + + user_filled = _fill_login_field( + page, + f"FREIGHT_RPA_{prefix}_USERNAME_SELECTOR", + username_env, + ( + 'input[name="username"]', + 'input[name="userName"]', + 'input[name="email"]', + 'input[type="email"]', + 'input[type="text"]', + ), + ) + password_filled = _fill_login_field( + page, + f"FREIGHT_RPA_{prefix}_PASSWORD_SELECTOR", + password_env, + ('input[name="password"]', 'input[type="password"]'), + ) + if not user_filled and not password_filled: + return + if user_filled != password_filled: + raise RuntimeError(f"{prefix} login form partially detected; please configure login selectors") + + if not _click_login_submit( + page, + f"FREIGHT_RPA_{prefix}_LOGIN_BUTTON_SELECTOR", + ("Sign in", "Login", "Log in", "登录"), + ): + raise RuntimeError(f"{prefix} login fields detected but submit button was not found") + + page.wait_for_load_state("domcontentloaded", timeout=_browser_timeout_ms()) + if page.locator('input[type="password"]').first.is_visible(timeout=3_000): + raise RuntimeError(f"{prefix} login did not complete; MFA/SSO/manual verification may be required") + + + +# 公开 API +env = _env +browser_timeout_ms = _browser_timeout_ms +click_text = _click_text +click_selector_or_text = _click_selector_or_text +fill_selector_or_label = _fill_selector_or_label +fill_dsv_filter_if_needed = _fill_dsv_filter_if_needed +select_or_fill = _select_or_fill +visible_locator = _visible_locator +visible_locator_in_root = _visible_locator_in_root +click_text_in_root = _click_text_in_root +click_visible_selector_or_text_in_root = _click_visible_selector_or_text_in_root +fill_login_field = _fill_login_field +fill_first_visible_text_input = _fill_first_visible_text_input +click_login_submit = _click_login_submit +click_visible_selector_or_text = _click_visible_selector_or_text +wait_for_visible_selector = _wait_for_visible_selector +maybe_auto_login = _maybe_auto_login diff --git a/scripts/rpa/run_inventory_batch_trigger.py b/scripts/rpa/run_inventory_batch_trigger.py new file mode 100644 index 00000000..9e876b1c --- /dev/null +++ b/scripts/rpa/run_inventory_batch_trigger.py @@ -0,0 +1,216 @@ +""" +scripts/rpa/run_inventory_batch_trigger.py + +用途:用指定 inventory_export_batch_*.json 直接跑一次真实浏览器批量导出(不启动 worker 轮询)。 +依赖:Playwright、freight_rpa_worker、FREIGHT_RPA_* 凭据与 HXOPS_API_BASE/SHIPPING_NOTICE_TOOL_API_KEY。 +逻辑:委托 freight_rpa_worker._handle_inventory_batch_trigger 处理 trigger 并回调后端。 + +用法(仓库根目录): + backend\\venv\\Scripts\\python.exe scripts\\rpa\\run_inventory_batch_trigger.py backend\\data\\shipping_notice\\freight_rpa\\inventory_triggers\\inventory_export_batch_RUN2026070912002659A5.json +""" +from __future__ import annotations + +import importlib.util +import json +import os +import sys +from pathlib import Path +from typing import Any + +import yaml + + +def _repo_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def _load_dotenv_dev() -> None: + """从 .env.dev 注入缺失的 SHIPPING_NOTICE / FREIGHT 目录变量(不覆盖已有 env)。""" + env_path = _repo_root() / ".env.dev" + if not env_path.is_file(): + return + for raw_line in env_path.read_text(encoding="utf-8").splitlines(): + line = raw_line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, value = line.partition("=") + key = key.strip() + value = value.strip().strip('"').strip("'") + if key and key not in os.environ: + os.environ[key] = value + + +def _load_worker(): + module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py" + spec = importlib.util.spec_from_file_location("freight_rpa_worker_batch_runner", module_path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _inventory_sources_config() -> dict[str, dict[str, Any]]: + """ + 读取 shipping_inventory_sources.yaml,按 source_code 索引。 + 核心逻辑:供 enrich 补全旧 trigger 缺失的 site_id / navigation 等字段。 + """ + config_path = _repo_root() / "backend" / "config" / "shipping_inventory_sources.yaml" + payload = yaml.safe_load(config_path.read_text(encoding="utf-8")) + indexed: dict[str, dict[str, Any]] = {} + for item in payload.get("sources") or []: + if not isinstance(item, dict): + continue + code = str(item.get("source_code") or "").strip().upper() + if code: + indexed[code] = item + return indexed + + +def _build_query_from_yaml(raw: dict[str, Any]) -> dict[str, Any]: + """复用 dsv_export_smoke 口径,从 YAML 构造 worker 兼容 query。""" + navigation = dict(raw.get("navigation") or {}) + parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)] + source_type = str(raw.get("source_type") or "dsv360").strip().lower() + warehouse_id = str(raw.get("warehouse_id") or "").strip() + query: dict[str, Any] = {} + if source_type == "dsv360": + for key in ("program_group", "program_label", "report_group", "report_name"): + if navigation.get(key): + query[key] = navigation[key] + if warehouse_id: + query["warehouse_code"] = warehouse_id + for parameter in parameters: + name = str(parameter.get("name") or "").strip() + mode = str(parameter.get("mode") or "single").strip().lower() + values = [str(v).strip() for v in (parameter.get("values") or []) if str(v).strip()] + if not values: + continue + if mode == "multi_text": + joined = str(parameter.get("joiner") or ",").join(values) + if name.lower() == "owner": + query["owner_code"] = joined + elif name.lower() == "putawayzone": + query["putaway_zone"] = joined + elif name.lower() == "warehouse": + query["warehouse_code"] = joined + continue + value = values[0] + if name.lower() == "owner": + query["owner_code"] = value + elif name.lower() == "putawayzone": + query["putaway_zone"] = value + elif name.lower() == "warehouse": + query["warehouse_code"] = value + return query + + +def _build_rpa_source_from_yaml(source_code: str) -> dict[str, Any] | None: + """从 YAML 构造完整 rpa_inventory_source;找不到 source_code 时返回 None。""" + raw = _inventory_sources_config().get(source_code.strip().upper()) + if not raw: + return None + navigation = dict(raw.get("navigation") or {}) + parameters = [dict(item) for item in (raw.get("parameters") or []) if isinstance(item, dict)] + return { + "source_code": str(raw.get("source_code") or source_code).upper(), + "source_type": str(raw.get("source_type") or "dsv360").strip().lower(), + "site_id": str(raw.get("site_id") or "").strip().upper() or None, + "warehouse_id": str(raw.get("warehouse_id") or "").strip(), + "entry_url": str(raw.get("entry_url") or ""), + "navigation": navigation, + "parameters": parameters, + "query": _build_query_from_yaml(raw), + } + + +def _enrich_trigger_sources(trigger_path: Path) -> None: + """ + 用 YAML 补全 trigger 中 inventory_sources 的缺失字段(如 site_id)。 + 核心逻辑:旧排程 trigger 可能缺 site_id;以 YAML 为准 merge,保留 trigger 已有 query 覆盖。 + """ + body = json.loads(trigger_path.read_text(encoding="utf-8")) + sources = body.get("inventory_sources") or [] + if not isinstance(sources, list): + return + enriched: list[dict[str, Any]] = [] + changed = False + for source in sources: + if not isinstance(source, dict): + continue + code = str(source.get("source_code") or "").strip().upper() + baseline = _build_rpa_source_from_yaml(code) if code else None + if baseline: + merged = {**baseline, **{k: v for k, v in source.items() if v not in (None, "", {}, [])}} + if not merged.get("query") and baseline.get("query"): + merged["query"] = baseline["query"] + elif baseline.get("query"): + merged["query"] = {**baseline["query"], **(source.get("query") or {})} + if merged != source: + changed = True + enriched.append(merged) + else: + enriched.append(source) + if not changed: + return + body["inventory_sources"] = enriched + trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8") + print(f"[batch-run] 已从 YAML 补全 trigger 字段: {', '.join(str(s.get('source_code')) for s in enriched)}") + + +def main() -> int: + if len(sys.argv) < 2: + print("用法: python scripts/rpa/run_inventory_batch_trigger.py ") + return 1 + + trigger_path = Path(sys.argv[1]).expanduser() + if not trigger_path.is_file(): + trigger_path = _repo_root() / sys.argv[1] + if not trigger_path.is_file(): + print(f"[batch-run] trigger 不存在: {sys.argv[1]}") + return 1 + + _load_dotenv_dev() + os.environ.setdefault("FREIGHT_RPA_MOCK", "false") + os.environ.setdefault("FREIGHT_RPA_HEADLESS", "false") + os.environ.setdefault("FREIGHT_RPA_KEEP_BROWSER_OPEN_ON_ERROR", "true") + os.environ.setdefault( + "FREIGHT_RPA_BROWSER_PROFILE_DIR", + "backend/data/shipping_notice/freight_rpa/browser_profile", + ) + if not os.environ.get("FREIGHT_RPA_BROWSER_CHANNEL") and not os.environ.get("FREIGHT_RPA_BROWSER_EXECUTABLE_PATH"): + os.environ.setdefault("FREIGHT_RPA_BROWSER_CHANNEL", "msedge") + os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052") + + repo = _repo_root() + drop_dir = Path(os.environ.get("FREIGHT_INVENTORY_DROP_DIR") or "backend/data/shipping_notice/freight_rpa/inventory_drop") + if not drop_dir.is_absolute(): + drop_dir = repo / drop_dir + processed_dir = trigger_path.parent / "processed" + processed_dir.mkdir(parents=True, exist_ok=True) + drop_dir.mkdir(parents=True, exist_ok=True) + + worker = _load_worker() + if not worker._env("FREIGHT_RPA_DSV_USERNAME") or not worker._env("FREIGHT_RPA_DSV_PASSWORD"): + print("[batch-run] 缺少 FREIGHT_RPA_DSV_USERNAME / FREIGHT_RPA_DSV_PASSWORD") + return 1 + if not worker._env("SHIPPING_NOTICE_TOOL_API_KEY"): + print("[batch-run] 缺少 SHIPPING_NOTICE_TOOL_API_KEY(或 INTEGRATION_API_KEY)") + return 1 + + _enrich_trigger_sources(trigger_path) + + print(f"[batch-run] trigger={trigger_path}") + print(f"[batch-run] drop_dir={drop_dir}") + print(f"[batch-run] mock={worker._env('FREIGHT_RPA_MOCK', 'false')} headless={worker._env('FREIGHT_RPA_HEADLESS', 'false')}") + crane_ready = bool(worker._env("FREIGHT_RPA_CRANE_USERNAME") and worker._env("FREIGHT_RPA_CRANE_PASSWORD")) + if not crane_ready: + print("[batch-run] 提示: 未配置 FREIGHT_RPA_CRANE_USERNAME/PASSWORD,Crane 源预计失败") + print("[batch-run] 正在打开浏览器执行批量导出(DSV + Crane,预计 5~15 分钟)…") + + worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) + print("[batch-run] 完成,请查看 inventory_drop 目录与 worker 日志。") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())