diff --git a/.env.dev b/.env.dev index e2c41d2d..0b0cf072 100644 --- a/.env.dev +++ b/.env.dev @@ -135,29 +135,29 @@ SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 -SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 -SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 -SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 +FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 +FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3 +FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30 SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx -# RPA 目录(相对 backend/ 根目录) -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers -SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=data/shipping_notice/freight_receipt_rpa/receipt_drop -SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/shipping_notice/freight_receipt_rpa/receipt_triggers -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers -SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile +# RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局) +FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop +FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers +FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop +FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers +FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile # AWS 库存列映射(可选 JSON 字符串) # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} -# 本地 RPA(scripts/rpa/freight_rpa_worker.py) -SHIPPING_NOTICE_RPA_WORKER_MOCK=false +# 本地 RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py) +FREIGHT_RPA_WORKER_MOCK=false # 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis -SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false -SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true +FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false +FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true # 企微心跳告警总开关(默认关闭;需要时改为 true) -SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false -# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 -# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY= +FREIGHT_RPA_WORKER_ALERT_ENABLED=false +# FREIGHT_RPA_WORKER_POLL_SECONDS=3 +# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY= # --- 10. 运维、告警与维护工具 --- # 设备维保助手后端工具调用密钥 MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu diff --git a/.env.prod b/.env.prod index 7970fb43..274ae926 100644 --- a/.env.prod +++ b/.env.prod @@ -135,22 +135,23 @@ SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03 # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致) -SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data -SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 -SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 +FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data +FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 +FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 # 企微心跳告警总开关(默认关闭;需要时改为 true) -SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false +FREIGHT_RPA_WORKER_ALERT_ENABLED=false # 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微 -SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= -SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true -SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 -SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers -SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_drop -SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_triggers -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers +FREIGHT_RPA_WORKER_ALERT_USERNAMES= +FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true +FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 +FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 +# RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局) +FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop +FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers +FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop +FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers # 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod diff --git a/.env.shared b/.env.shared index e24123c2..a50676a3 100644 --- a/.env.shared +++ b/.env.shared @@ -270,7 +270,7 @@ SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=30 SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800 # RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。 # 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。 -SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE= +FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE= # 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。 # L7 验收完成前禁止开启通用解析与通用自动冻结。 # 通用确定性解析:仅 no_special_profile_feature / 无漂移 no_match 可进入。 @@ -300,9 +300,9 @@ SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095 # 货代上传 RPA:默认关闭;具备 Worker/凭据/共享目录与隔离校验后再在环境文件显式设 true。 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false # Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs. -SHIPPING_NOTICE_RPA_WORKER_MOCK=false +FREIGHT_RPA_WORKER_MOCK=false # 企微心跳告警总开关(默认关闭;需要时在环境文件改为 true) -SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false +FREIGHT_RPA_WORKER_ALERT_ENABLED=false # 固资履历共享盘 FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001 diff --git a/.env.test b/.env.test index 19fcf7cf..397ef822 100644 --- a/.env.test +++ b/.env.test @@ -152,35 +152,35 @@ SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐) -SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data -SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 -SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 -SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 -SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 +FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data +FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 +FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3 +FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30 +FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 # 企微心跳告警总开关(默认关闭;需要时改为 true) -SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false +FREIGHT_RPA_WORKER_ALERT_ENABLED=false # 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微 # 两者皆无则告警只写日志、不会发企微 -SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= -SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true +FREIGHT_RPA_WORKER_ALERT_USERNAMES= +FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true # 企微发送中短锁秒数(发送失败过期后可重试,默认 120) -SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 -SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 +FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 +FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx -SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns= -# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享) -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers -SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop -SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers +FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns= +# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局) +FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop +FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers +FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop +FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers # AWS 库存列映射(可选 JSON 字符串) # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} -# 本地 Mock RPA(scripts/rpa/inventory/inventory_rpa_worker.py,可选) -# SHIPPING_NOTICE_RPA_WORKER_MOCK=true -# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 -# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY= +# 本地 Mock RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py,可选) +# FREIGHT_RPA_WORKER_MOCK=true +# FREIGHT_RPA_WORKER_POLL_SECONDS=3 +# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY= # 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test diff --git a/AGENTS.md b/AGENTS.md index 317f2733..d8e60414 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,7 +163,7 @@ docker compose logs -f hxops-backend - **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。 - **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。 - **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。 -- **RPA 命名空间(强制)**:货代发货通知 RPA 统一使用 `SHIPPING_NOTICE_RPA_*`。后端业务参数使用 `SHIPPING_NOTICE_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `SHIPPING_NOTICE_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,平台凭据主密钥使用 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`;历史名称只能存在于兼容映射和迁移说明中。 +- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `inventory/`、`receipt/`、`common/` 分域(common 仅放跨 Worker 共享物,如 browser_profile)。 - **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。 - **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。 diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 965ac847..a0b72804 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -8,7 +8,6 @@ backend/app/core/config/settings.py 旧路径 app.config 为兼容 shim。 """ import os -import warnings from pathlib import Path from dotenv import dotenv_values @@ -16,18 +15,6 @@ from dotenv import dotenv_values _BACKEND_DIR = Path(__file__).resolve().parents[3] _ROOT_DIR = _BACKEND_DIR.parent -_WARNED_LEGACY_RPA_ENV: set[str] = set() - -_RPA_LEGACY_TO_CANONICAL = { - 'SHIPPING_RPA_CREDENTIAL_KEY': 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY', - 'FREIGHT_INVENTORY_DROP_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', - 'FREIGHT_RPA_INVENTORY_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', - 'FREIGHT_UPLOAD_QUEUE_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR', - 'FREIGHT_RPA_UPLOAD_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR', - 'FREIGHT_RPA_BROWSER_PROFILE_DIR': 'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR', - 'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR': 'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', - 'FREIGHT_RPA_MOCK': 'SHIPPING_NOTICE_RPA_WORKER_MOCK', -} def _normalize_env_name(raw: str | None) -> str: @@ -90,47 +77,15 @@ def _backend_path(env_key: str, *parts: str) -> str: return resolve_backend_relative_path(os.getenv(env_key), default) -def _rpa_env(canonical_name: str, default: str | None = None) -> str | None: +def _rpa_data_path(env_key: str, *parts: str) -> str: """ - 读取 Shipping Notice RPA 配置,并在迁移期兼容历史环境变量名。 + 解析 RPA 数据目录环境变量,未配置时回落到 `backend/data` 默认路径。 - 核心逻辑:优先读取 `SHIPPING_NOTICE_RPA_*`;仅在新变量缺失时读取映射的 - 历史变量,并按进程对每个旧名称最多发出一次弃用警告。 + 核心逻辑:直接读取规范环境变量名(FREIGHT_RPA_*);历史 + SHIPPING_NOTICE_RPA_* 前缀已于 2026-09-18 废弃,不提供别名兼容。 Args: - canonical_name: 统一后的规范环境变量名。 - default: 新旧变量均未设置时返回的默认值。 - - Returns: - str | None: 环境变量值或默认值。 - """ - value = os.getenv(canonical_name) - if value is not None: - return value - legacy_name = next( - (legacy for legacy, canonical in _RPA_LEGACY_TO_CANONICAL.items() if canonical == canonical_name), - None, - ) - if legacy_name: - value = os.getenv(legacy_name) - if value is not None: - if legacy_name not in _WARNED_LEGACY_RPA_ENV: - warnings.warn( - f'{legacy_name} is deprecated; use {canonical_name}', - DeprecationWarning, - stacklevel=2, - ) - _WARNED_LEGACY_RPA_ENV.add(legacy_name) - return value - return default - - -def _rpa_data_path(canonical_name: str, *parts: str) -> str: - """ - 解析 RPA 数据目录,并兼容历史环境变量名称。 - - Args: - canonical_name: 统一后的 RPA 目录环境变量名。 + env_key: 规范 RPA 目录环境变量名。 *parts: 未配置时相对 `backend/data` 的默认路径片段。 Returns: @@ -139,7 +94,7 @@ def _rpa_data_path(canonical_name: str, *parts: str) -> str: from app.path_utils import resolve_backend_relative_path default = _BACKEND_DIR.joinpath('data', *parts) - return resolve_backend_relative_path(_rpa_env(canonical_name), default) + return resolve_backend_relative_path(os.getenv(env_key), default) class Config: @@ -310,9 +265,7 @@ class Config: # 货代发货通知 Agent Tool API SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY') # RPA Profile 凭据字段的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。 - SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = _rpa_env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') - # 兼容仍从 Flask config 读取旧属性的扩展;新代码禁止继续使用该属性。 - SHIPPING_RPA_CREDENTIAL_KEY = SHIPPING_NOTICE_RPA_CREDENTIAL_KEY + FREIGHT_RPA_CREDENTIAL_KEY = os.getenv('FREIGHT_RPA_CREDENTIAL_KEY') # 文件检核 Chatflow Tool API FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY') @@ -425,46 +378,46 @@ class Config: SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = ( os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true' ) - SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int( - os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900' + FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int( + os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900' ) - SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS = int( - os.getenv('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS') or '900' + FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int( + os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900' ) - SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int( - os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90' + FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int( + os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90' ) - SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = ( - os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true' + FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED = ( + os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true' ) - SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = ( - os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower() + FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = ( + os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower() in {'1', 'true', 'yes', 'on'} - if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS') + if os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS') else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'} ) - SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = ( - os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true' + FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = ( + os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true' ) - SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip() - SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = ( - os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip() + FREIGHT_RPA_SHARED_SCOPE_ID = os.getenv('FREIGHT_RPA_SHARED_SCOPE_ID', '').strip() + FREIGHT_RPA_SHARED_SENTINEL_NAME = ( + os.getenv('FREIGHT_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip() or '.hxops_rpa_shared_mount' ) - SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = ( - os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true' + FREIGHT_RPA_WORKER_ALERT_ENABLED = ( + os.getenv('FREIGHT_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true' ) - SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int( - os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800' + FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int( + os.getenv('FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800' ) - SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv( - 'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', '' + FREIGHT_RPA_WORKER_ALERT_USERNAMES = os.getenv( + 'FREIGHT_RPA_WORKER_ALERT_USERNAMES', '' ).strip() - SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = ( - os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true' + FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN = ( + os.getenv('FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true' ) - SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int( - os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120' + FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int( + os.getenv('FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120' ) SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true' SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true' @@ -481,9 +434,9 @@ class Config: ) # Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback) SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true' - SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3') - SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int( - os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30' + FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS') or '3') + FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS = int( + os.getenv('FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS') or '30' ) SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int( os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000' @@ -496,39 +449,32 @@ class Config: ) SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS') FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP') - SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path( - 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', 'shipping_notice', 'freight_rpa', 'inventory_drop' + # RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。 + FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop' ) - SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path( - 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'inventory_triggers' + FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers' ) - SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path( - 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_drop' + FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop' ) - SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path( - 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_triggers' + FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers' ) - SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path( - 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR', 'shipping_notice', 'freight_rpa', 'upload_queue' + FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'inventory', 'upload_queue' ) - SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path( - 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'upload_triggers' + FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path( + 'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'inventory', 'upload_triggers' ) - SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path( - 'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR', 'shipping_notice', 'freight_rpa', 'browser_profile' + FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path( + 'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile' ) - SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path( - 'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', 'shipping_notice', 'freight_rpa', 'inventory_archives' + FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path( + 'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives' ) - SHIPPING_NOTICE_RPA_WORKER_MOCK = _rpa_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false') - # 旧 Flask config 属性仅用于过渡期测试和外部扩展兼容。 - FREIGHT_INVENTORY_DROP_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR - FREIGHT_RPA_INVENTORY_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR - FREIGHT_UPLOAD_QUEUE_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR - FREIGHT_RPA_UPLOAD_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR - FREIGHT_RPA_BROWSER_PROFILE_DIR = SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR - FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR - FREIGHT_RPA_MOCK = SHIPPING_NOTICE_RPA_WORKER_MOCK + FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false') # WeCom (企业微信) 登录配置 WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true' @@ -787,8 +733,8 @@ class DevelopmentConfig(Config): SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = True # 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用) - SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False - SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True + FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False + FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True # XFA 拆分确认 JTI:仅单进程 development 允许内存消费;test/prod 多 Worker 必须 Redis XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True @@ -808,8 +754,8 @@ class TestingConfig(Config): FIXED_ASSETS_SYNC_ENABLED = False FIXED_ASSETS_EXPORT_TO_DOCS = False ENV_NAME = 'dev' - SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False - SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True + FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False + FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True # pytest 单进程:允许内存 JTI;生产语义由 ProductionConfig 关闭 XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True diff --git a/backend/app/services/in_transit_transfer/receipt_callback_bridge.py b/backend/app/services/in_transit_transfer/receipt_callback_bridge.py index 7565de10..79d7ddc1 100644 --- a/backend/app/services/in_transit_transfer/receipt_callback_bridge.py +++ b/backend/app/services/in_transit_transfer/receipt_callback_bridge.py @@ -68,7 +68,7 @@ def recover_stale_waiting_source_jobs() -> int: from flask import current_app try: - timeout = max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900))) + timeout = max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900))) except (TypeError, ValueError): timeout = 900 cutoff = datetime.utcnow() - timedelta(seconds=timeout) diff --git a/backend/app/services/schedule/freight_receipt_rpa_finalize.py b/backend/app/services/schedule/freight_receipt_rpa_finalize.py index 9a17b57b..5ffaa84b 100644 --- a/backend/app/services/schedule/freight_receipt_rpa_finalize.py +++ b/backend/app/services/schedule/freight_receipt_rpa_finalize.py @@ -79,7 +79,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict: def _receipt_timeout_seconds() -> int: """读取收料回调等待上限;超时只标记失败,不会自动重试或重发。""" try: - return max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900))) + return max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900))) except (TypeError, ValueError): return 900 diff --git a/backend/app/services/schedule/shipping_inventory_rpa_archive.py b/backend/app/services/schedule/shipping_inventory_rpa_archive.py index bfe3acf8..71514c39 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_archive.py +++ b/backend/app/services/schedule/shipping_inventory_rpa_archive.py @@ -39,14 +39,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = { def get_inventory_archive_dir() -> str: """返回库存 RPA 原始 ZIP 归档根目录(自动创建)。""" archive_dir = Path( - current_app.config.get("SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR") + current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR") if current_app else "" ) if not str(archive_dir): from app.core.config.settings import Config - archive_dir = Path(Config.SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR) + archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR) archive_dir.mkdir(parents=True, exist_ok=True) return str(archive_dir) @@ -251,7 +251,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool: """ 校验归档 ZIP 路径是否安全可下载。 - 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内。 + 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。 """ resolved = zip_path.resolve() if resolved.suffix.lower() != ".zip": @@ -272,7 +272,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]: 解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。 核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、 - 且真实路径位于 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。 + 且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。 Returns: tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。 diff --git a/backend/app/services/schedule/shipping_inventory_rpa_job.py b/backend/app/services/schedule/shipping_inventory_rpa_job.py index a7d729fa..8447d2be 100644 --- a/backend/app/services/schedule/shipping_inventory_rpa_job.py +++ b/backend/app/services/schedule/shipping_inventory_rpa_job.py @@ -19,7 +19,10 @@ from app.models import ScheduleRun, ScheduleTask from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger -from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE +from app.services.shipping_notice.rpa_worker_heartbeat import ( + RPA_WORKER_OFFLINE_MESSAGE, + assert_inventory_rpa_worker_ready, +) ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]] @@ -121,6 +124,8 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}" try: + # 写 trigger 前强制就绪检查:worker 离线立即 failed,不进入 awaiting_rpa_callback。 + assert_inventory_rpa_worker_ready() trigger_path = write_inventory_export_batch_trigger( run_no, sources, diff --git a/backend/app/services/shipping_notice/credential_crypto.py b/backend/app/services/shipping_notice/credential_crypto.py index 59f5a577..812c17c1 100644 --- a/backend/app/services/shipping_notice/credential_crypto.py +++ b/backend/app/services/shipping_notice/credential_crypto.py @@ -26,17 +26,17 @@ def _fernet() -> Fernet: Raises: ServiceUnavailableError: 未配置或配置了无效的主密钥。 """ - key = str(current_app.config.get('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') or '').strip() + key = str(current_app.config.get('FREIGHT_RPA_CREDENTIAL_KEY') or '').strip() if not key: raise ServiceUnavailableError( - 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is not configured', + 'FREIGHT_RPA_CREDENTIAL_KEY is not configured', code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING', ) try: return Fernet(key.encode('ascii')) except (ValueError, UnicodeEncodeError) as exc: raise ServiceUnavailableError( - 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is invalid', + 'FREIGHT_RPA_CREDENTIAL_KEY is invalid', code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID', ) from exc diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index 89c16b54..4c85580e 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -420,7 +420,7 @@ def _auto_upload_enabled() -> bool: def _rpa_upload_timeout_seconds() -> int: """货代上传 RPA 等待回调超时秒数。""" try: - return max(int(current_app.config.get('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or 30), 1) + return max(int(current_app.config.get('FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS') or 30), 1) except (TypeError, ValueError): return 30 diff --git a/backend/app/services/shipping_notice/inventory_configuration_test.py b/backend/app/services/shipping_notice/inventory_configuration_test.py index 61e8188e..f002e823 100644 --- a/backend/app/services/shipping_notice/inventory_configuration_test.py +++ b/backend/app/services/shipping_notice/inventory_configuration_test.py @@ -219,7 +219,7 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None: 同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站 等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。 """ - timeout = max(1, int(current_app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'])) + timeout = max(1, int(current_app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'])) runs = ShippingInventoryConfigurationTestRun.query.filter( ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), @@ -357,7 +357,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]: db.session.commit() return _payload(run) # Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到 - # SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。 + # FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。 raw_file_path = str(payload.get('file_path') or '').strip() path: Path | None = None from app.services.shipping_notice.rpa import inventory_drop_dir diff --git a/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py b/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py index 6fcadb51..2abe00d4 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py +++ b/backend/app/services/shipping_notice/inventory_rpa_callback_cleanup.py @@ -56,11 +56,11 @@ def callback_quarantine_dir() -> Path | None: def callback_cleanup_max_attempts() -> int: - """cleanup job 最大重试次数(SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。""" + """cleanup job 最大重试次数(FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。""" try: return max( 1, - int(current_app.config.get("SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS), + int(current_app.config.get("FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS), ) except (TypeError, ValueError): return _DEFAULT_MAX_CLEANUP_ATTEMPTS diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index 22973069..c0943cf7 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -117,7 +117,7 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: scheduled_at = next_inventory_rpa_recheck_at(task) if scheduled_at is None: recheck_seconds = max( - float(current_app.config.get('SHIPPING_NOTICE_RPA_WAIT_RECHECK_SECONDS', 10) or 10), + float(current_app.config.get('FREIGHT_RPA_WAIT_RECHECK_SECONDS', 10) or 10), 1, ) scheduled_at = datetime.utcnow() + timedelta(seconds=recheck_seconds) diff --git a/backend/app/services/shipping_notice/receipt_report_storage.py b/backend/app/services/shipping_notice/receipt_report_storage.py index 8c26f8e4..5722af8a 100644 --- a/backend/app/services/shipping_notice/receipt_report_storage.py +++ b/backend/app/services/shipping_notice/receipt_report_storage.py @@ -26,7 +26,7 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve def _read_receipt_callback_file(file_path: str) -> bytes: """只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。""" - configured_root = str(current_app.config.get('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip() + configured_root = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip() if not configured_root: raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') root = Path(configured_root).resolve() diff --git a/backend/app/services/shipping_notice/receipt_rpa.py b/backend/app/services/shipping_notice/receipt_rpa.py index 559b2511..c8e153ad 100644 --- a/backend/app/services/shipping_notice/receipt_rpa.py +++ b/backend/app/services/shipping_notice/receipt_rpa.py @@ -14,7 +14,7 @@ from flask import current_app def receipt_trigger_dir() -> Path | None: """返回收料专用 trigger 目录;绝不回落到库存 trigger 目录。""" - value = str(current_app.config.get('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR') or '').strip() + value = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR') or '').strip() return Path(value) if value else None diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py index 1c08cb35..8d36cfc4 100644 --- a/backend/app/services/shipping_notice/rpa.py +++ b/backend/app/services/shipping_notice/rpa.py @@ -37,7 +37,7 @@ def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | b mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower() if mode in {"browser", "mock"}: return _runtime_summary(mode) - raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") or "false").strip().lower() + raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower() return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser") @@ -49,8 +49,8 @@ def _path(key: str) -> Path | None: def inventory_drop_dir() -> Path | None: - """RPA 库存 Excel 落盘目录(SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR)。""" - return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR") + """RPA 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR)。""" + return _path("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR") def inventory_processed_dir() -> Path | None: @@ -63,7 +63,7 @@ def inventory_processed_dir() -> Path | None: def inventory_trigger_dir() -> Path | None: """RPA 库存导出触发 JSON 目录。""" - return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR") + return _path("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR") def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None: @@ -82,12 +82,12 @@ def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None: def upload_queue_dir() -> Path | None: """货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。""" - return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR") + return _path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR") def upload_trigger_dir() -> Path | None: """RPA 货代上传触发 JSON 目录。""" - return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR") + return _path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR") def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None: diff --git a/backend/app/services/shipping_notice/rpa_attempts.py b/backend/app/services/shipping_notice/rpa_attempts.py index f1e29ad7..9e6f950c 100644 --- a/backend/app/services/shipping_notice/rpa_attempts.py +++ b/backend/app/services/shipping_notice/rpa_attempts.py @@ -86,8 +86,8 @@ def upload_rpa_attempts(task: ShippingNotice | None) -> int: def max_rpa_upload_attempts() -> int: - """RPA 货代上传最大重试次数(环境变量 SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS)。""" - value = os.getenv("SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS") + """RPA 货代上传最大重试次数(环境变量 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS)。""" + value = os.getenv("FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS") if value is None or not str(value).strip(): return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS try: diff --git a/backend/app/services/shipping_notice/rpa_worker_heartbeat.py b/backend/app/services/shipping_notice/rpa_worker_heartbeat.py index ce40b372..3d6aee30 100644 --- a/backend/app/services/shipping_notice/rpa_worker_heartbeat.py +++ b/backend/app/services/shipping_notice/rpa_worker_heartbeat.py @@ -39,6 +39,7 @@ _MEMORY_LOCK = threading.Lock() _REASON_USER_HINTS: dict[str, str] = { "no_worker_heartbeat": "未收到任何 Worker 心跳", + "heartbeat_store_process_local": "未配置 REDIS_URL(或 Redis 不可达),心跳存储为本进程内存,跨进程不可见;请配置 REDIS_URL 或设 FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED=false 跳过心跳检查", "heartbeat_storage_unavailable": "心跳存储不可用(Redis)", "trigger_dir_not_configured": "后端未配置 trigger 目录", "trigger_dir_not_accessible": "trigger 目录不存在或不可访问", @@ -48,7 +49,7 @@ _REASON_USER_HINTS: dict[str, str] = { "environment_mismatch": "Worker 环境与后端环境不一致", "missing_inventory_export_capability": "Worker 未声明 inventory_export 能力", "missing_freight_upload_capability": "Worker 未声明 freight_upload 能力", - "credential_key_missing": "未配置 SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", + "credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY", "upload_queue_dir_not_configured": "未配置货代上传队列目录", "upload_queue_dir_not_accessible": "货代上传队列目录不可访问", "callback_api_base_missing": "未配置 Worker 回调可达的 API 基址", @@ -91,9 +92,9 @@ def _config_str(key: str, default: str = "") -> str: def _heartbeat_ttl_seconds() -> int: raw = 90 if current_app: - raw = int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or 90) + raw = int(current_app.config.get("FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or 90) else: - raw = int(os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or "90") + raw = int(os.getenv("FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS") or "90") return max(60, raw) @@ -101,16 +102,16 @@ def _heartbeat_check_required() -> bool: """Mock RPA 或显式关闭时跳过 worker 心跳就绪检查。""" if rpa_runtime_mode().get("mock"): return False - return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED", True) + return _config_bool("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED", True) def _heartbeat_redis_required() -> bool: """test/prod 默认要求 Redis;dev 仅显式开启时要求。""" - explicit = os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS") + explicit = os.getenv("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS") if explicit is not None and str(explicit).strip() != "": - return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS", False) + return _config_bool("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS", False) if current_app: - configured = current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS") + configured = current_app.config.get("FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS") if configured is not None: return bool(configured) env_name = resolve_backend_rpa_environment() @@ -118,7 +119,7 @@ def _heartbeat_redis_required() -> bool: def _heartbeat_allow_memory_fallback() -> bool: - return _config_bool("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK", False) + return _config_bool("FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK", False) def resolve_backend_rpa_environment() -> str: @@ -131,7 +132,7 @@ def resolve_backend_rpa_environment() -> str: def shared_scope_id() -> str: """共享 SMB 目录逻辑标识(如 hxops-rpa-test-data),用于跨平台路径对齐。""" - explicit = _config_str("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "") + explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "") if explicit: return explicit trigger_dir = inventory_trigger_dir() @@ -145,7 +146,7 @@ def shared_scope_id() -> str: def shared_sentinel_name() -> str: - return _config_str("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME", ".hxops_rpa_shared_mount") + return _config_str("FREIGHT_RPA_SHARED_SENTINEL_NAME", ".hxops_rpa_shared_mount") def _shared_mount_check_required() -> bool: @@ -208,9 +209,21 @@ def _memory_list_workers() -> list[dict[str, Any]]: def reset_rpa_worker_heartbeat_state_for_tests() -> None: - """单测隔离:清空进程内内存心跳缓存。""" + """单测隔离:清空进程内内存心跳缓存,并尽力清除 Redis 中的持久心跳记录。""" with _MEMORY_LOCK: _MEMORY_STORE.clear() + try: + client = _redis_client() + if client is None: + return + worker_ids = list(client.smembers(_REDIS_INDEX_KEY) or []) + stale_worker_keys = [f"{_REDIS_WORKER_KEY_PREFIX}{worker_id}" for worker_id in worker_ids] + if stale_worker_keys: + client.delete(*stale_worker_keys) + client.delete(_REDIS_INDEX_KEY) + except Exception: + # 隔离辅助尽力而为:Redis 不可用时内存清空已足够单测运行。 + pass def _redis_store_worker(worker: dict[str, Any]) -> bool: @@ -517,6 +530,10 @@ def _check_rpa_worker_ready_for_capability( if not workers and "heartbeat_storage_unavailable" not in reasons: reasons.append("no_worker_heartbeat") + if _redis_client() is None and not eligible_workers: + # 无 Redis 时心跳存储为本进程内存:写方(API 进程收 Worker POST)与读方(排程/告警进程) + # 互不可见,本地排程必然命中 no_worker_heartbeat;追加原因码提示存储模式与本地测试姿势。 + reasons.append("heartbeat_store_process_local") mount_block_tokens = { "trigger_dir_not_configured", @@ -583,7 +600,7 @@ def _freight_upload_config_reasons() -> list[str]: from app.services.shipping_notice.rpa import upload_queue_dir, upload_trigger_dir reasons: list[str] = [] - credential_key = _config_str("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", "") + credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "") if not credential_key: reasons.append("credential_key_missing") diff --git a/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py b/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py index a8d97339..05648d55 100644 --- a/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py +++ b/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py @@ -46,28 +46,28 @@ def _config_bool(key: str, default: bool) -> bool: def _alert_enabled() -> bool: if not _heartbeat_check_required(): return False - return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED", False) + return _config_bool("FREIGHT_RPA_WORKER_ALERT_ENABLED", False) def _alert_cooldown_seconds() -> int: - return max(300, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS") or 1800)) + return max(300, int(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS") or 1800)) def _send_lock_seconds() -> int: """企微发送中的短锁 TTL;发送失败过期后可重试,不进入长冷却。""" - return max(60, int(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS") or 120)) + return max(60, int(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS") or 120)) def _alert_fallback_admin_enabled() -> bool: - return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN", True) + return _config_bool("FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN", True) def _alert_recipients() -> list[User]: """ 解析告警接收人。 - 核心逻辑:优先 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。 + 核心逻辑:优先 FREIGHT_RPA_WORKER_ALERT_USERNAMES;未配置时可选回退已绑企微的 admin。 """ - raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES") or "").strip() + raw = str(current_app.config.get("FREIGHT_RPA_WORKER_ALERT_USERNAMES") or "").strip() names = [part.strip() for part in raw.split(",") if part.strip()] if raw else [] if names: users = ( @@ -105,7 +105,7 @@ def _log_recipient_gap_once() -> None: return _RECIPIENT_GAP_LOGGED = True logger.warning( - "[rpa-heartbeat-alert] no wecom recipients: set SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES " + "[rpa-heartbeat-alert] no wecom recipients: set FREIGHT_RPA_WORKER_ALERT_USERNAMES " "or bind wecom_userid for at least one admin (FALLBACK_ADMIN=true)" ) diff --git a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py index 1578e8e0..7c9ec858 100644 --- a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py +++ b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py @@ -36,7 +36,7 @@ def shipping_recovery_tick() -> int: # 根据最新 Attempt/Gate 状态刷新按钮与阻断原因。 inventory_timeout_seconds = max(int(getattr( current_app.config, - 'SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS', + 'FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS', 900, ) or 900), 1) inventory_scan_count = _scan_stale_inventory_attempts( diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index a5e811f2..c27d86b9 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -83,7 +83,7 @@ def auto_rpa_inventory_enabled() -> bool: def rpa_inventory_timeout_seconds() -> int: """RPA 库存导出等待超时秒数。""" - return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 900, min_value=5) + return cfg_int("FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS", 900, min_value=5) def auto_mapping_allow_llm() -> bool: diff --git a/backend/config/shipping_inventory_sources.yaml b/backend/config/shipping_inventory_sources.yaml index 72969833..f8f961c0 100644 --- a/backend/config/shipping_inventory_sources.yaml +++ b/backend/config/shipping_inventory_sources.yaml @@ -19,7 +19,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSATL01 @@ -41,7 +41,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSAVP01 @@ -62,7 +62,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSAZA01 @@ -83,7 +83,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSCMH01 @@ -105,7 +105,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSCMN01 @@ -127,7 +127,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSEZE01 @@ -149,7 +149,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSFRA01 @@ -170,7 +170,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSGRU01 @@ -191,7 +191,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSIAD01 @@ -212,7 +212,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSJAN01 @@ -233,7 +233,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSLTN01 @@ -254,7 +254,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSMEL01 @@ -275,7 +275,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSNRT01 @@ -296,7 +296,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSPHX01 @@ -317,7 +317,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSPNE01 @@ -338,7 +338,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSPRD01 @@ -359,7 +359,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSPSC01 @@ -380,7 +380,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSQRO01 @@ -401,7 +401,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSRIC01 @@ -422,7 +422,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSRNO01 @@ -443,7 +443,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSRUH01 @@ -464,7 +464,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSSBN01 @@ -485,7 +485,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSSCL01 @@ -506,7 +506,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSYYZ01 @@ -527,7 +527,7 @@ sources: report_name: On Hand Inventory By Location 3lv parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: single values: - BYAWSZAZ01 @@ -580,7 +580,7 @@ sources: report_name: On Hand Inventory by Location parameters: - name: Warehouse - selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR + selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR mode: multi_select select_all: true selectors: diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index b30a99e5..1f64540b 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -85,8 +85,8 @@ def _shipping_notice_stable_auto_config(request, monkeypatch): return app = request.getfixturevalue("app") tmp_path = request.getfixturevalue("tmp_path") - app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue") - app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str( + app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue") + app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str( tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers" ) if request.node.get_closest_marker("auto_rpa"): @@ -108,9 +108,9 @@ def _shipping_notice_stable_auto_config(request, monkeypatch): app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False app.config["ENV_NAME"] = "dev" - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = False - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests reset_rpa_worker_heartbeat_state_for_tests() diff --git a/backend/tests/services/admin/test_shipping_inventory_service.py b/backend/tests/services/admin/test_shipping_inventory_service.py index d57a2e90..6cddcc3f 100644 --- a/backend/tests/services/admin/test_shipping_inventory_service.py +++ b/backend/tests/services/admin/test_shipping_inventory_service.py @@ -158,7 +158,7 @@ def _published_route_field_id() -> str: def test_profile_credentials_are_not_returned(app): """Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) assert payload['password_configured'] is True @@ -169,7 +169,7 @@ def test_profile_credentials_are_not_returned(app): def test_profile_rejects_page_operation_configuration(app): """货代登录连接不得保存报表路径、selector 或下载策略,防止连接越界成为业务配置源。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): payload = _profile_data() payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}} @@ -180,7 +180,7 @@ def test_profile_rejects_page_operation_configuration(app): def test_multiple_dbs_profiles_bind_independent_sources(app): """同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None) second = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None) @@ -192,7 +192,7 @@ def test_multiple_dbs_profiles_bind_independent_sources(app): def test_source_rejects_profile_connector_mismatch(app): """库存源不能绑定不同 Driver 的 Profile。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None) with pytest.raises(ValidationError) as exc_info: @@ -202,7 +202,7 @@ def test_source_rejects_profile_connector_mismatch(app): def test_disabled_source_can_be_saved_before_profile_and_template_binding(app): """禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None) payload = _source_data(login['id'], code='DRAFT_SOURCE') @@ -227,7 +227,7 @@ def test_disabled_source_can_be_saved_before_profile_and_template_binding(app): def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app): """普通保存只能保留停用站点;独立启用动作必须返回尚未完成的测试步骤。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None) payload = _source_data(login['id'], code='ACTIVATION_SOURCE') @@ -250,7 +250,7 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app): def test_activation_status_exposes_structured_checks_without_duplicate_test_blocks(app): """未测试站点应显示后续验证步骤,但只由测试门禁阻断,避免管理员面对重复待办。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None) payload = { @@ -279,7 +279,7 @@ def test_activation_status_exposes_structured_checks_without_duplicate_test_bloc def test_enabled_source_rejects_disabled_rpa_profile(app): """启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile( {**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None, @@ -291,7 +291,7 @@ def test_enabled_source_rejects_disabled_rpa_profile(app): def test_dbs_source_persists_report_path_parameters_and_aliases(app): """数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) @@ -303,11 +303,11 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app): def test_source_rejects_driver_selector_in_business_parameters(app): """业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) payload = _source_data(profile['id']) - payload['query_parameters_json'][0]['selector_env'] = 'SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR' + payload['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR' with pytest.raises(ValidationError) as exc_info: shipping_inventory_service.save_source(payload, actor_id=None) assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID' @@ -315,7 +315,7 @@ def test_source_rejects_driver_selector_in_business_parameters(app): def test_crane_source_rejects_dbs_report_path(app): """动态仓 Crane 库存源不得误填 DBS 四级报表路径。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None) payload = _source_data(profile['id'], code='CRANE', connector_type='crane') @@ -328,7 +328,7 @@ def test_crane_source_rejects_dbs_report_path(app): def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app): """停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7) payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE') @@ -357,7 +357,7 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app): """批量绑定必须先全量预检;已启用站点阻断时其余站点不能部分写入。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None) disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED') @@ -380,7 +380,7 @@ def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app): def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app): """直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None) payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE') @@ -407,7 +407,7 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app def test_published_rule_cannot_be_mutated_in_place(app): """发布规则必须依靠新版本演进,避免改写历史任务依据。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None) source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None) @@ -469,7 +469,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app): def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app): """未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None) shipping_inventory_service.delete_profile(unused['id']) @@ -500,7 +500,7 @@ def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app): def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app): """发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None) source = shipping_inventory_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None) @@ -535,7 +535,7 @@ def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app): def test_active_default_external_mapping_is_unique_per_source(app): """同一库存源只能有一条启用的默认外部系统映射。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) @@ -550,7 +550,7 @@ def test_active_default_external_mapping_is_unique_per_source(app): def test_external_mapping_normalizes_freight_warehouse_identity(app): """配置端小写货代仓应与库存行大写 Warehouse 使用同一精确映射身份。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None) @@ -564,7 +564,7 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app): def test_upload_config_change_does_not_bump_rpa_profile_version(app): """连接级上传配置(upload_config_json)变更不递增 config_version。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) base_version = profile['config_version'] diff --git a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py index 231a0b6c..8a0ed9d6 100644 --- a/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py +++ b/backend/tests/services/in_transit_transfer/test_receipt_trigger_service.py @@ -104,7 +104,7 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p """deps 默认触发器必须真写 trigger 文件,不得只查配置就返回 ok=True(B1 断线根因)。""" from app.services.in_transit_transfer.deps import _DefaultRpaTrigger - monkeypatch.setitem(app.config, 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path)) + monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path)) outcome = _DefaultRpaTrigger().trigger( source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file", ) diff --git a/backend/tests/test_crane_navigation.py b/backend/tests/test_crane_navigation.py index 82523458..78138059 100644 --- a/backend/tests/test_crane_navigation.py +++ b/backend/tests/test_crane_navigation.py @@ -10,7 +10,7 @@ import pytest def _load_navigation(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_navigation.py" + module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "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) diff --git a/backend/tests/test_crane_report_export.py b/backend/tests/test_crane_report_export.py index 4daaa733..be182bbf 100644 --- a/backend/tests/test_crane_report_export.py +++ b/backend/tests/test_crane_report_export.py @@ -10,7 +10,7 @@ import pytest def _load_export(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_report_export.py" + module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "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) @@ -47,7 +47,7 @@ def test_fill_parameters_skips_warehouse(monkeypatch): select_or_fill=_fake_select, ) - assert calls == [("SHIPPING_NOTICE_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")] + assert calls == [("FREIGHT_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")] def test_build_schedule_description_uses_short_uuid_hex(monkeypatch): @@ -73,7 +73,7 @@ def test_build_schedule_description_hex_len_env(): text = module._build_schedule_description( {"source_code": "CRANE_TZR2"}, None, - env=lambda name, default="": "16" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default, + env=lambda name, default="": "16" if name == "FREIGHT_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default, ) assert len(text) == 16 @@ -148,7 +148,7 @@ def test_should_run_report_before_schedule_uses_driver_environment_only(): assert ( module._should_run_report_before_schedule( {"navigation": {}}, - env=lambda name, default="": "false" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default, + env=lambda name, default="": "false" if name == "FREIGHT_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default, ) is False ) @@ -444,7 +444,7 @@ def test_resolve_download_mode_uses_driver_environment_only(): """下载模式只能由 Driver 环境变量决定。""" module = _load_export() assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report" - assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download" + assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "FREIGHT_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download" def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch): diff --git a/backend/tests/test_crane_session.py b/backend/tests/test_crane_session.py index f6e3c398..73c226a8 100644 --- a/backend/tests/test_crane_session.py +++ b/backend/tests/test_crane_session.py @@ -8,7 +8,7 @@ from unittest.mock import MagicMock def _load_crane_session(): - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_session.py" + module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "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) @@ -108,15 +108,15 @@ def test_maybe_auto_login_crane_fills_username_password_and_clicks_sign_in(monke module.maybe_auto_login_crane( page, env=lambda name, default="": { - "SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME": "crane-user", - "SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD": "crane-pass", + "FREIGHT_RPA_WORKER_CRANE_USERNAME": "crane-user", + "FREIGHT_RPA_WORKER_CRANE_PASSWORD": "crane-pass", }.get(name, default), browser_timeout_ms=5_000, ) assert calls == [ - ("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"), - ("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"), + ("FREIGHT_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"), + ("FREIGHT_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"), ] @@ -133,7 +133,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch): locator = module._find_crane_sign_in_button( page, - selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR", + selector_env="FREIGHT_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR", env=lambda name, default="": default, browser_timeout_ms=3_000, ) @@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch): def test_ensure_crane_session_skips_login_when_session_active(monkeypatch): """batch 内 session 有效时不应重复 goto + login。""" - worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py" + worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_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) diff --git a/backend/tests/test_dsv_report_parameters.py b/backend/tests/test_dsv_report_parameters.py index eae5a371..7b38e7ff 100644 --- a/backend/tests/test_dsv_report_parameters.py +++ b/backend/tests/test_dsv_report_parameters.py @@ -1,4 +1,4 @@ -"""scripts/rpa/dsv_report_parameters.py 单元测试。""" +"""scripts/freight_rpa/dsv_report_parameters.py 单元测试。""" from __future__ import annotations @@ -7,7 +7,7 @@ from pathlib import Path def _load_module(): - path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_parameters.py" + path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_parameters.py" spec = importlib.util.spec_from_file_location("dsv_report_parameters_test", path) assert spec and spec.loader module = importlib.util.module_from_spec(spec) @@ -43,7 +43,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input(): module.fill_dsv_filter_if_needed( _FakePage(), - "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", + "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", "CADU-0000000100", env=lambda name, default="": default, @@ -104,7 +104,7 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue(): module.fill_dsv_filter_if_needed( _FakePage(), - "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", "BYAWSATL01", env=lambda name, default="": default, @@ -290,7 +290,7 @@ def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value(): module.fill_dsv_filter_if_needed( _FakePage(), - "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", "RTM", env=lambda name, default="": default, diff --git a/backend/tests/test_freight_receipt_rpa_callback.py b/backend/tests/test_freight_receipt_rpa_callback.py index f78f1396..6346e4a1 100644 --- a/backend/tests/test_freight_receipt_rpa_callback.py +++ b/backend/tests/test_freight_receipt_rpa_callback.py @@ -99,7 +99,7 @@ def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path): with app.app_context(): allowed_root = tmp_path / 'receipt-drop' allowed_root.mkdir() - app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root) + app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root) outside = tmp_path / 'outside.xlsx' outside.write_bytes(b'not-a-real-xlsx') diff --git a/backend/tests/test_freight_receipt_rpa_schedule.py b/backend/tests/test_freight_receipt_rpa_schedule.py index 3ac92183..624d9d34 100644 --- a/backend/tests/test_freight_receipt_rpa_schedule.py +++ b/backend/tests/test_freight_receipt_rpa_schedule.py @@ -76,7 +76,7 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app): from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs with app.app_context(): - app.config['SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60 + app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60 source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one() task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *') db.session.add(task); db.session.flush() @@ -100,7 +100,7 @@ def test_receipt_trigger_is_published_atomically(app, tmp_path): from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger with app.app_context(): - app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path) + app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path) written = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'receipt:atomic'}]) assert written is not None diff --git a/backend/tests/test_freight_receipt_worker_contract.py b/backend/tests/test_freight_receipt_worker_contract.py index 2a263f73..5569a347 100644 --- a/backend/tests/test_freight_receipt_worker_contract.py +++ b/backend/tests/test_freight_receipt_worker_contract.py @@ -7,18 +7,18 @@ from pathlib import Path def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract(): """收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。""" - text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') - assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text - assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + assert 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text + assert 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR' in text assert 'shipping_receipt_rpa.v1' in text assert '/api/shipping-notice/rpa/receipt-batch-ready' in text assert 'freight_rpa_worker' not in text - assert 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text + assert 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text def test_receipt_crane_driver_forces_inbound_details_match_name(): """收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。""" - root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' + root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' receipt_driver = (root / 'receipt' / 'receipt_crane_export.py').read_text(encoding='utf-8') crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8') assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver @@ -27,7 +27,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name(): def test_receipt_crane_driver_forces_inbound_details_entry_route(): """复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。""" - root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' + root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' module_path = root / 'receipt' / 'receipt_crane_export.py' sys.path.insert(0, str(root)) spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path) @@ -45,7 +45,7 @@ def test_receipt_crane_driver_forces_inbound_details_entry_route(): def test_receipt_worker_uses_common_trigger_consumer(): """收料 Worker 必须复用公共 claim/归档原语,不再自建目录搬移实现。""" - text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') assert 'claim_trigger' in text assert 'archive_trigger' in text assert "path.replace(claimed)" not in text # 领取逻辑收敛到公共模块 @@ -53,7 +53,7 @@ def test_receipt_worker_uses_common_trigger_consumer(): def test_receipt_worker_logs_full_lifecycle_and_banner(): """收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。""" - text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') assert 'configure_file_logging' in text assert 'maybe_rotate_open_log' in text assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段 @@ -64,7 +64,36 @@ def test_receipt_worker_logs_full_lifecycle_and_banner(): def test_receipt_worker_reports_heartbeat_with_dedicated_identity(): """收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。""" - text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text - ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8') - assert 'SHIPPING_NOTICE_RPA_WORKER_ID' in ps1 and '-receipt' in ps1 + ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8') + assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-receipt' in ps1 + + +def test_receipt_register_script_mirrors_inventory_with_distinct_identity(): + """收料计划任务注册脚本与库存同构(AtLogOn+Interactive+headless),任务名独立可同机并存。""" + root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' + receipt = (root / 'receipt' / 'register_receipt_worker_tasks.ps1').read_text(encoding='utf-8') + inventory = (root / 'inventory' / 'register_inventory_worker_tasks.ps1').read_text(encoding='utf-8') + # [断言意图] 任务名赋值行必须指向 Receipt;docstring 允许提及库存任务名(并排设计说明),功能段不得引用 + assert '$TestTask = "HXOPS Receipt RPA Worker TEST"' in receipt + assert '$ProdTask = "HXOPS Receipt RPA Worker PROD"' in receipt + assert 'HXOPS Inventory RPA Worker TEST' in inventory and 'HXOPS Receipt RPA Worker' not in inventory + # [断言意图] 动作必须指向收料启动脚本,且不得把库存启动脚本带进收料注册 + assert 'start_receipt_worker.ps1' in receipt and 'start_inventory_worker.ps1' not in receipt + # [断言意图] 形状约束与库存同款:AtLogOn + Interactive + headless + 隐藏控制台 + assert 'AtLogOn' in receipt and 'Interactive' in receipt and 'Headless' in receipt and 'WindowStyle Hidden' in receipt + + +def test_receipt_worker_supports_opt_in_session_reuse(): + """收料 Worker 支持可选跨批次会话复用:ps1 注入开关,worker 按 env 切换持久/一次性 Profile。""" + text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8') + # [断言意图] 开关经 env 读取(默认 false 保持一次性 Profile 行为不变) + assert "env('FREIGHT_RPA_WORKER_SESSION_REUSE', 'false')" in text + # [断言意图] 复用模式使用持久 receipt_session 目录,且该目录不做批次后删除(跨批次复用登录态) + assert "profile_root / 'receipt_session'" in text + assert 'not reuse_session' in text + ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8') + # [断言意图] 启动脚本提供 -SessionReuse 开关并注入对应 env + assert '[switch]$SessionReuse' in ps1 + assert 'FREIGHT_RPA_WORKER_SESSION_REUSE' in ps1 diff --git a/backend/tests/test_freight_rpa_heartbeat.py b/backend/tests/test_freight_rpa_heartbeat.py index 6004c911..6a9bc4de 100644 --- a/backend/tests/test_freight_rpa_heartbeat.py +++ b/backend/tests/test_freight_rpa_heartbeat.py @@ -10,7 +10,7 @@ from pathlib import Path def _load_freight_rpa_heartbeat_module(): - rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "rpa" + rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" if str(rpa_dir) not in sys.path: sys.path.insert(0, str(rpa_dir)) module_path = rpa_dir / "common" / "rpa_heartbeat.py" @@ -24,7 +24,7 @@ def _load_freight_rpa_heartbeat_module(): def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch): module = _load_freight_rpa_heartbeat_module() - monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data") + monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data") payload = module.build_heartbeat_payload( trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers", drop_dir=r"C:\HxopsRpaTest\data\inventory_drop", @@ -35,15 +35,15 @@ def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch): def test_resolve_shared_scope_id_from_trigger_path(monkeypatch): module = _load_freight_rpa_heartbeat_module() - monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False) - monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False) + monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False) + monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False) monkeypatch.setenv( - "SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR", + "FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR", r"C:\HxopsRpaTest\data\inventory_triggers", ) assert module._resolve_shared_scope_id() == "" monkeypatch.setenv( - "SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR", + "FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR", r"C:\mount\hxops-rpa-test-data\inventory_triggers", ) assert module._resolve_shared_scope_id() == "hxops-rpa-test-data" @@ -54,7 +54,7 @@ def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch): trigger_dir = tmp_path / "inventory_triggers" trigger_dir.mkdir() - monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data") + monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data") module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01") sentinel = trigger_dir / ".hxops_rpa_shared_mount" @@ -78,7 +78,7 @@ def test_maybe_send_heartbeat_does_not_block_trigger_loop_when_http_stalls(tmp_p return False monkeypatch.setattr(module, "post_heartbeat", stalled_post) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "15") + monkeypatch.setenv("FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS", "15") started = time.monotonic() sent_at = module.maybe_send_heartbeat( trigger_dir=tmp_path, diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index 92f60f01..8d3bb74d 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -1,4 +1,4 @@ -"""scripts/rpa/freight_rpa_worker.py tests. +"""scripts/freight_rpa/freight_rpa_worker.py tests. 覆盖货代 RPA worker 对真实库存导出 trigger JSON 的消费路径: 1. 读取 inventory_export_SN-20260629-2EDADC77.json。 @@ -15,6 +15,7 @@ import os import re import sys import time +import warnings from pathlib import Path import pytest @@ -27,7 +28,7 @@ def _repo_root() -> Path: def _load_freight_rpa_worker(): - module_path = _repo_root() / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py" + module_path = _repo_root() / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py" spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path) assert spec is not None assert spec.loader is not None @@ -162,7 +163,7 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch, "inventory_sources": [source], }), encoding="utf-8") callbacks: list[tuple[str, dict]] = [] - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true") monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body))) worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) @@ -216,7 +217,7 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_ "inventory_sources": [source], }), encoding="utf-8") callbacks: list[tuple[str, dict]] = [] - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true") monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body))) worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) @@ -300,7 +301,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp }], }), encoding="utf-8") callbacks: list[tuple[str, dict]] = [] - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true") monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body))) worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) @@ -359,7 +360,7 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm }], }), encoding="utf-8") callbacks: list[tuple[str, dict]] = [] - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true") monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body))) worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) @@ -432,11 +433,11 @@ def test_env_strips_wrapping_quotes(monkeypatch): """RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。""" worker = _load_freight_rpa_worker() - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", '"user@example.com"') - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "'secret-pass'") + monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", '"user@example.com"') + monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "'secret-pass'") - assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "user@example.com" - assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "secret-pass" + assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "user@example.com" + assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "secret-pass" def test_worker_accepts_business_connector_without_site_id(): @@ -511,7 +512,7 @@ def test_dsv_sso_blank_transition_refreshes_once_before_portal_wait(monkeypatch) clock['value'] += 3.0 return clock['value'] - monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000') + monkeypatch.setenv('FREIGHT_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000') monkeypatch.setattr(session.time, 'monotonic', monotonic) monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None) monkeypatch.setattr(session, '_debug_dsv_stage', lambda *_args, **_kwargs: None) @@ -533,7 +534,7 @@ def test_dsv_sso_return_timeout_is_explicit(monkeypatch): worker = _load_freight_rpa_worker() session = worker.dsv_session import dsv_auth - monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000') + monkeypatch.setenv('FREIGHT_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000') class _Page: url = 'https://auth.dbschenker.com/as/authorization.ping' @@ -569,9 +570,9 @@ def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch): worker = _load_freight_rpa_worker() key = Fernet.generate_key() cipher = Fernet(key) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", key.decode("ascii")) - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", raising=False) - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", raising=False) + monkeypatch.setenv("FREIGHT_RPA_CREDENTIAL_KEY", key.decode("ascii")) + monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_USERNAME", raising=False) + monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", raising=False) monkeypatch.delenv("FREIGHT_RPA_DSV_USERNAME", raising=False) monkeypatch.delenv("FREIGHT_RPA_DSV_PASSWORD", raising=False) source = { @@ -582,39 +583,35 @@ def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch): }, } with worker._profile_credentials(source): - assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "test-user" - assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "test-password" - assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "" - assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "" + assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "test-user" + assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "test-password" + assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "" + assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "" -def test_worker_prefers_canonical_rpa_env_over_legacy_name(monkeypatch): - """新旧 RPA 变量同时存在时必须使用统一的新命名空间,避免旧部署值覆盖新配置。""" +def test_worker_ignores_legacy_rpa_name_without_compat(monkeypatch): + """无兼容层:历史旧名(FREIGHT_RPA_MOCK)不作为 FREIGHT_RPA_WORKER_MOCK 的回退,也不发弃用警告。""" worker = _load_freight_rpa_worker() - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") + monkeypatch.delenv("FREIGHT_RPA_WORKER_MOCK", raising=False) monkeypatch.setenv("FREIGHT_RPA_MOCK", "true") - assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "false" - - -def test_worker_reads_legacy_rpa_env_during_migration(monkeypatch): - """规范变量缺失时允许读取旧名称,保障 Windows Worker 分阶段迁移不中断。""" - worker = _load_freight_rpa_worker() - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", raising=False) - monkeypatch.setenv("FREIGHT_RPA_MOCK", "true") - - with pytest.warns(DeprecationWarning, match="FREIGHT_RPA_MOCK is deprecated"): - assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "true" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + # 断言 1:仅设置历史旧名时,规范名直读为空、带默认值读回默认值(旧名不被咨询)。 + assert worker._env("FREIGHT_RPA_WORKER_MOCK") == "" + assert worker._env("FREIGHT_RPA_WORKER_MOCK", "false") == "false" + # 断言 2:读取过程不产生任何 DeprecationWarning(兼容层已删除)。 + assert not any(issubclass(item.category, DeprecationWarning) for item in caught) def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys): - """配置 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。""" + """配置 FREIGHT_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。""" # 等价迁移:文件日志实现已提取至公共 worker_logging 模块,本用例改测公共接口。 worker_logging = _load_worker_logging() log_path = tmp_path / "logs" / "worker.log" timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(log_path)) + monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_FILE", str(log_path)) original_stdout = sys.stdout original_stderr = sys.stderr @@ -645,15 +642,15 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path): - """日志超过 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。""" + """日志超过 FREIGHT_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。""" # 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。 worker_logging = _load_worker_logging() log_path = tmp_path / "worker.log" log_path.write_text("current-log", encoding="utf-8") Path(f"{log_path}.1").write_text("old-1", encoding="utf-8") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2") + monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1") + monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2") worker_logging.rotate_log_file_if_needed(log_path) @@ -669,8 +666,8 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp log_path = tmp_path / "worker.log" log_path.write_text("current-log", encoding="utf-8") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0") + monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1") + monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "0") worker_logging.rotate_log_file_if_needed(log_path) @@ -678,13 +675,13 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp def _load_worker_logging(): - """加载 scripts/rpa/common/worker_logging.py 供单测直接断言。 + """加载 scripts/freight_rpa/common/worker_logging.py 供单测直接断言。 历史背景:文件日志实现(tee/轮转/时间戳)原内置于 inventory_rpa_worker.py, 已提取为公共模块;Worker 内部私有名(_configure_file_logging 等)已删除, 日志行为用例统一改测公共接口,行为断言保持等价。 """ - common_dir = _repo_root() / "scripts" / "rpa" / "common" + common_dir = _repo_root() / "scripts" / "freight_rpa" / "common" if str(common_dir) not in sys.path: sys.path.insert(0, str(common_dir)) module_path = common_dir / "worker_logging.py" @@ -700,8 +697,8 @@ def _load_worker_logging(): def _load_worker_disk_cleanup(): - """加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。""" - module_path = _repo_root() / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py" + """加载 scripts/freight_rpa/common/worker_disk_cleanup.py 供单测直接断言。""" + module_path = _repo_root() / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py" spec = importlib.util.spec_from_file_location("worker_disk_cleanup_under_test", module_path) assert spec is not None assert spec.loader is not None @@ -787,8 +784,8 @@ def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypat (orphan_run / "Cookies").write_text("drop", encoding="utf-8") os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600))) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "7") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") + monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "7") + monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") stats = cleanup.run_worker_disk_cleanup( inventory_trigger_dir=inv_trigger, @@ -835,8 +832,8 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path orphan_run.mkdir() os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600))) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "0") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") + monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "0") + monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") cleanup.run_worker_disk_cleanup( inventory_trigger_dir=inv_trigger, @@ -881,8 +878,8 @@ def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path): assert stats.deleted_dirs == 1 -def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch): - """未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。""" +def test_open_browser_uses_freight_rpa_common_profile_fallback(monkeypatch): + """未配置 profile 根目录时,应回退到 freight_rpa/common 布局的 browser_profile。""" worker = _load_freight_rpa_worker() observed: dict[str, object] = {} @@ -906,12 +903,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch): def start(self): return _FakePlaywright() - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true") - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False) - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False) + monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False) + monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false") + monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "true") + monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", raising=False) + monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) temp_roots: list[Path] = [] @@ -930,7 +926,8 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch): assert context is not None assert page is not None - expected_root = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile" + # 断言意图:bare-run 默认值必须等于 freight_rpa 三层布局的 common/browser_profile + expected_root = _repo_root() / "backend" / "data" / "freight_rpa" / "common" / "browser_profile" assert temp_roots == [expected_root] assert runtime_profile_dir == expected_root / "run_unit" assert runtime_profile_dir.parent == expected_root @@ -946,7 +943,7 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa """profile 根目录配置为 data/shipping_notice 时,应按 backend 根目录解析。""" worker = _load_freight_rpa_worker() monkeypatch.setenv( - "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", + "FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", "data/shipping_notice/freight_rpa/browser_profile", ) @@ -955,30 +952,32 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa assert worker._browser_profile_root() == expected.resolve() -def test_browser_profile_root_remaps_legacy_freight_rpa_path(monkeypatch): - """本机残留旧 profile 路径时,应强制迁到 shipping_notice 命名空间。""" +def test_browser_profile_root_keeps_freight_rpa_layout_without_remap(monkeypatch, capsys): + """profile 配置为 freight_rpa 布局路径时,应按字面解析:不改写、不告警(无兼容层红线)。""" worker = _load_freight_rpa_worker() monkeypatch.setenv( - "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", - "backend/data/freight_rpa/browser_profile", + "FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", + "data/freight_rpa/browser_profile", ) - expected = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile" + # 断言意图:迁移期 remap 已删除,旧布局形状的配置值必须原样落到 backend 根下 + expected = _repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile" assert worker._browser_profile_root() == expected.resolve() + # 断言意图:不得再输出 legacy 改写告警 + assert "legacy" not in capsys.readouterr().out -def test_browser_profile_root_remaps_absolute_legacy_freight_rpa_path(monkeypatch): - """本机环境变量保存绝对旧路径时,也应迁到 shipping_notice 命名空间。""" +def test_browser_profile_root_keeps_absolute_freight_rpa_layout_without_remap(monkeypatch, capsys): + """绝对 freight_rpa 路径同样按字面解析,证明 remap 分支已完全移除。""" worker = _load_freight_rpa_worker() - monkeypatch.setenv( - "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", - str(_repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"), - ) + profile_dir = _repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile" + monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(profile_dir)) - expected = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile" - - assert worker._browser_profile_root() == expected.resolve() + # 断言意图:绝对路径不再被强制迁往 shipping_notice 命名空间 + assert worker._browser_profile_root() == profile_dir.resolve() + # 断言意图:不得再输出 legacy 改写告警 + assert "legacy" not in capsys.readouterr().out def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path): @@ -1002,7 +1001,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path out_file.write_bytes(b"fake inventory content") return out_file - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false") monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser) monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) @@ -1060,8 +1059,8 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat processed_dir = trigger_dir / "processed" callbacks: list[tuple[str, dict]] = [] - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true") - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY", raising=False) + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true") + monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY", raising=False) monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir) @@ -1122,7 +1121,7 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p def raise_no_inventory(_trigger: dict, _drop: Path): raise worker.NoInventoryDataError("DSV report has no inventory data") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false") monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory) monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) @@ -1187,7 +1186,7 @@ def test_real_upload_requires_connection_config_enabled(monkeypatch, tmp_path): worker = _load_freight_rpa_worker() workbook = tmp_path / "shipment.xlsx" workbook.write_bytes(b"test") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true") with pytest.raises(RuntimeError, match="not enabled for this connection"): worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={"upload_config_json": {"enabled": False}}) @@ -1198,8 +1197,8 @@ def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path): worker = _load_freight_rpa_worker() workbook = tmp_path / "shipment.xlsx" workbook.write_bytes(b"test") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true") events: list[tuple[str, object]] = [] class _Locator: @@ -1245,7 +1244,7 @@ def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path): runtime_profile = tmp_path / "profile" runtime_profile.mkdir() monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url))) - monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile)) + monkeypatch.setattr(worker, "_open_browser", lambda _dir, **_kwargs: (_Playwright(), _Context(), _Page(), runtime_profile)) def fake_result(_page, filename): return {"reference": "", "success_evidence": {"kind": "dsv_upload_success_dom", "selector": ".alert.alert-success", "filename": filename, "reference": None, "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "
", "dom_sha256": "abc"}} @@ -1275,8 +1274,8 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path): worker = _load_freight_rpa_worker() workbook = tmp_path / "shipment.xlsx" workbook.write_bytes(b"test") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true") events: list[tuple[str, object]] = [] class _Locator: @@ -1314,7 +1313,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path): runtime_profile = tmp_path / "profile" runtime_profile.mkdir() monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url))) - monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile)) + monkeypatch.setattr(worker, "_open_browser", lambda _dir, **_kwargs: (_Playwright(), _Context(), _Page(), runtime_profile)) monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda _page, _filename: {"reference": "", "success_evidence": {}}) assert worker._upload_shipment_with_browser( @@ -1406,7 +1405,7 @@ def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch): return clock["value"] monkeypatch.setattr(worker.time, "monotonic", monotonic) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000") + monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000") with pytest.raises(RuntimeError, match="did not confirm a green success status"): worker._wait_for_dsv_upload_history_receipt(_Page(), "shipment.xlsx") @@ -1542,7 +1541,7 @@ def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path): "task_no": "SN-UPLOAD-FAIL", "file_path": str(queue_file), "attempt_id": 8, "callback_id": "rpa:8", }), encoding="utf-8") callbacks: list[tuple[str, dict]] = [] - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false") monkeypatch.setattr(worker, "_upload_shipment_with_browser", lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("success marker missing"))) monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) @@ -1565,7 +1564,7 @@ def test_upload_empty_queue_path_reports_failed_callback(monkeypatch, tmp_path): "task_no": "SN-UPLOAD-EMPTY", "attempt_id": 9, "callback_id": "rpa:9", }), encoding="utf-8") callbacks: list[tuple[str, dict]] = [] - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false") monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) worker._handle_upload_trigger(trigger_path, trigger_dir / "processed") @@ -1631,12 +1630,11 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat def start(self): return _FakePlaywright() - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge") - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False) + monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) + monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false") + monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false") + monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", "msedge") + monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) _playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads") @@ -1679,9 +1677,8 @@ def test_open_browser_reuses_session_profile_per_connector_and_rpa_profile(monke def start(self): return _FakePlaywright() - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true") - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False) + monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) + monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true") monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) _playwright, context, page, profile_dir = worker._open_browser( @@ -1723,8 +1720,8 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo def start(self): return _FakePlaywright() - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true") + monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) + monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true") monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) _playwright, context, page, profile_dir = worker._open_browser( @@ -2230,7 +2227,7 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch): def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch): """登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。""" - module_path = _repo_root() / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_export.py" + module_path = _repo_root() / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_export.py" spec = importlib.util.spec_from_file_location("dsv_report_export_retry_test", module_path) assert spec is not None and spec.loader is not None dsv_report_export = importlib.util.module_from_spec(spec) @@ -2430,7 +2427,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input(): worker._fill_dsv_filter_if_needed( _FakePage(), - "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", + "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", "CADU-0000000100", ) @@ -2466,7 +2463,7 @@ def test_fill_dsv_filter_if_needed_accepts_report_name_kwarg(): worker._fill_dsv_filter_if_needed( _FakePage(), - "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", + "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", "CADU-0000000100", report_name="On Hand Inventory by Location", @@ -2622,26 +2619,26 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_ """ 手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。 - 默认跳过;仅当 SHIPPING_NOTICE_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码: - - SHIPPING_NOTICE_RPA_WORKER_MOCK=false - - SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false(建议首次调试) - - SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录> - - SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD + 默认跳过;仅当 FREIGHT_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码: + - FREIGHT_RPA_WORKER_MOCK=false + - FREIGHT_RPA_WORKER_HEADLESS=false(建议首次调试) + - FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录> + - FREIGHT_RPA_WORKER_DSV_USERNAME / FREIGHT_RPA_WORKER_DSV_PASSWORD """ - if str(os.getenv("SHIPPING_NOTICE_RPA_WORKER_E2E") or "").strip().lower() != "true": - pytest.skip("set SHIPPING_NOTICE_RPA_WORKER_E2E=true to run real freight RPA export") + if str(os.getenv("FREIGHT_RPA_WORKER_E2E") or "").strip().lower() != "true": + pytest.skip("set FREIGHT_RPA_WORKER_E2E=true to run real freight RPA export") worker = _load_freight_rpa_worker() trigger = _build_inventory_export_trigger("SN-20260629-2EDADC77") drop_dir = tmp_path / "drop" drop_dir.mkdir() - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") - if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS"): - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") - if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR"): + monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false") + if not os.getenv("FREIGHT_RPA_WORKER_HEADLESS"): + monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false") + if not os.getenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR"): monkeypatch.setenv( - "SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", + "FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "browser_profile"), ) @@ -2651,3 +2648,45 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_ assert out_file.parent == drop_dir assert out_file.suffix.lower() in {".xlsx", ".xls", ".csv"} assert out_file.stat().st_size > 0 + + +def test_ensure_dsv_session_continues_auto_login_after_goto_abort(monkeypatch): + """未登录时 goto 被 SSO 重定向以 ERR_ABORTED 中止:应继续自动登录,而不是判死整个源。""" + module_path = _repo_root() / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_export.py" + spec = importlib.util.spec_from_file_location("dsv_report_export_abort_test", module_path) + assert spec is not None and spec.loader is not None + dsv_report_export = importlib.util.module_from_spec(spec) + spec.loader.exec_module(dsv_report_export) + + class _FakeGotoAbort(Exception): + pass + + login_calls: list[str] = [] + goto_calls: list[str] = [] + + monkeypatch.setattr(dsv_report_export, "_is_dsv_session_active", lambda page, entry_url: False) + monkeypatch.setattr( + dsv_report_export, + "_goto_dsv_entry_url", + lambda page, entry_url: (goto_calls.append(entry_url), (_ for _ in ()).throw(_FakeGotoAbort("Page.goto: net::ERR_ABORTED at https://s360.dbschenker.com/main/portal")))[0], + ) + monkeypatch.setattr( + dsv_report_export, + "_maybe_auto_login_dsv", + lambda page: login_calls.append("login"), + ) + monkeypatch.setattr(dsv_report_export, "_is_dsv_on_entry_site", lambda page, entry_url: True) + monkeypatch.setattr( + dsv_report_export, + "_wait_for_dsv_home_ready", + lambda page, timeout_ms=None: None, + ) + monkeypatch.setattr(dsv_report_export, "_wait_for_dsv_reports_nav_stable", lambda page, timeout_ms=None: None) + + entry_url = "https://s360.dbschenker.com/" + dsv_report_export._ensure_dsv_session(object(), entry_url) + + # [断言意图] goto 被中止后必须继续自动登录(正是未登录才会被 SSO 重定向打断); + # 登录成功后直接等待首页就绪,不重复 goto entry(该二次跳转仅在 home-not-ready 分支出现) + assert goto_calls == [entry_url] + assert login_calls == ["login"] diff --git a/backend/tests/test_freight_rpa_worker_inventory_params.py b/backend/tests/test_freight_rpa_worker_inventory_params.py index 0804a083..7bfff083 100644 --- a/backend/tests/test_freight_rpa_worker_inventory_params.py +++ b/backend/tests/test_freight_rpa_worker_inventory_params.py @@ -34,7 +34,7 @@ _RPA_MODULE_PATHS = { def _load_rpa_module(module_name: str): rel = _RPA_MODULE_PATHS.get(module_name, f"{module_name}.py") - module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / rel + module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / rel scripts_dir = str(module_path.parent) if scripts_dir not in sys.path: sys.path.insert(0, scripts_dir) @@ -59,12 +59,12 @@ def test_fill_report_parameter_multi_select(monkeypatch): page, { "name": "Warehouse", - "selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "mode": "multi_select", "values": ["WH1", "WH2"], }, ) - assert calls == [("SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])] + assert calls == [("FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])] def test_fill_report_parameter_multi_select_with_select_all(monkeypatch): @@ -96,7 +96,7 @@ def test_fill_report_parameter_multi_select_with_select_all(monkeypatch): ) assert calls == [ { - "selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "label": "Warehouse", "values": ["RTM"], "selectors": None, @@ -136,7 +136,7 @@ def test_fill_report_parameter_multi_select_jda_report_passes_template_selectors ) assert calls == [ { - "selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", + "selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "label": "Warehouse", "values": ["RTM"], "selectors": None, @@ -418,8 +418,8 @@ def test_dsv_existing_portal_session_skips_all_auth_probes(monkeypatch): """持久化 Profile 已恢复 Portal 时,不得先等待用户名或认证页面。""" flow = _load_dsv_auth_login_flow() page = MagicMock() - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "user") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "password") + monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", "user") + monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "password") selector_wait = MagicMock() auth_ready = MagicMock() monkeypatch.setattr(flow, "_has_existing_dsv_portal_session", lambda _page: True) diff --git a/backend/tests/test_internal_jobs_registry.py b/backend/tests/test_internal_jobs_registry.py index 5abdfe5e..5e51ad34 100644 --- a/backend/tests/test_internal_jobs_registry.py +++ b/backend/tests/test_internal_jobs_registry.py @@ -9,7 +9,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat """POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): from app import db diff --git a/backend/tests/test_inventory_configuration_test.py b/backend/tests/test_inventory_configuration_test.py index d6b37079..64c44738 100644 --- a/backend/tests/test_inventory_configuration_test.py +++ b/backend/tests/test_inventory_configuration_test.py @@ -126,7 +126,7 @@ def _published_template(*, code: str) -> ShippingExcelTemplate: def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path): """测试文件只能生成测试分析,重复发起复用运行,禁止创建生产库存快照。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -150,8 +150,8 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app, drop_dir = tmp_path / 'inventory_drop' drop_dir.mkdir() app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') - app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir) + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir) with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -170,7 +170,7 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app, def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path): """已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -211,7 +211,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend def test_empty_configuration_export_without_published_profile_is_rejected(app): """没有受控解析定义时,空结果不能被用作站点可用性的替代证据。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -228,7 +228,7 @@ def test_empty_configuration_export_without_published_profile_is_rejected(app): def test_configuration_test_automatically_verifies_compatible_bound_profile(app, tmp_path): """当前绑定方案的核心栏位仍在时,历史无关列缺失也必须直接成为验证证据。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -248,7 +248,7 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app, def test_verified_current_profile_automatically_enables_ready_source(app, tmp_path): """当前解析验证通过且必要条件齐全时,站点无需人工确认即可自动启用。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -270,7 +270,7 @@ def test_verified_current_profile_automatically_enables_ready_source(app, tmp_pa def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path): """解析测试通过不绕过发货模板门禁,条件不完整的站点必须保持停用。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -291,7 +291,7 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path): """固定仓查询成功但无库存时,也能在完整门禁下自动启用站点。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -314,7 +314,7 @@ def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path): def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path): """同连接站点一次投递,混合成功、空库存及失败后仍独立汇总为部分失败。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ) as write_trigger: @@ -356,7 +356,7 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, def test_retry_batch_only_retriggers_failed_sites(app, tmp_path): """批次重试只新建失败站点运行,成功和空库存结果不会被重复导出。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -378,7 +378,7 @@ def test_retry_batch_only_retriggers_failed_sites(app, tmp_path): def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app, tmp_path): """配置变更后的旧批次回调必须失效,未知运行号不能污染同批次状态。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -406,7 +406,7 @@ def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app, def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path): """页面刷新只能恢复仍在执行的批次,已结束批次不会反复占用进度面板。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -428,7 +428,7 @@ def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path): def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path): """Worker 领取回调只更新本批次当前运行,终态运行不得被重新打开。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -461,7 +461,7 @@ def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path) def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_path): """重开配置抽屉只能恢复当前版本测试;站点改动后可发起独立新测试而不复用旧运行。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -482,8 +482,8 @@ def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_ def test_configuration_test_timeout_marks_run_failed(app, tmp_path): """RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') - app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1 + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1 with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -511,8 +511,8 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path): def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path): """同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') - app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10 + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10 with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -538,7 +538,7 @@ def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, t def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path): """确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -581,7 +581,7 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path): """连接凭据或登录配置变更后,旧测试不得继续作为当前库存站点的启用证据。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -611,7 +611,7 @@ def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path): def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path): """正式运行中的站点不能发起测试;站点配置变化后旧测试不得绑定。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): @@ -654,7 +654,7 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path): """失败回调和非推荐方案均不得产生生产快照或修改站点解析方案。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(), patch( 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', ): diff --git a/backend/tests/test_inventory_parsing_profile.py b/backend/tests/test_inventory_parsing_profile.py index bd5f6db5..2e906fc2 100644 --- a/backend/tests/test_inventory_parsing_profile.py +++ b/backend/tests/test_inventory_parsing_profile.py @@ -114,7 +114,7 @@ def _excel_template_id() -> int: def test_published_parsing_profile_can_be_shared_by_sources(app): """同一 published Profile 应可绑定多个库存源,避免重复维护相同模板。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): parsing = _published_profile() login = shipping_inventory_service.save_profile({ @@ -132,7 +132,7 @@ def test_published_parsing_profile_can_be_shared_by_sources(app): def test_source_rejects_draft_parsing_profile(app): """库存源只能绑定 published Profile,避免运行期读取可变草稿。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None) field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) @@ -175,7 +175,7 @@ def test_csv_parsing_profile_rejects_worksheet_configuration(app): def test_new_published_version_does_not_retire_bound_version(app): """发布新版本不得使现有库存源绑定的旧 published 版本失效。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): first = _published_profile() field_id = order_schema_service.get_state()['fields'][0]['id'] @@ -195,7 +195,7 @@ def test_new_published_version_does_not_retire_bound_version(app): def test_referenced_published_profile_cannot_be_retired(app): """已绑定库存源的解析 Profile 必须先迁移 Source,不能直接退役。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): parsing = _published_profile() login = shipping_inventory_service.save_profile({ diff --git a/backend/tests/test_inventory_rpa_download_save_fallback.py b/backend/tests/test_inventory_rpa_download_save_fallback.py index 2aca0357..cb34b6e2 100644 --- a/backend/tests/test_inventory_rpa_download_save_fallback.py +++ b/backend/tests/test_inventory_rpa_download_save_fallback.py @@ -12,7 +12,7 @@ from pathlib import Path def _load_worker(): module_path = ( - Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py" + Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py" ) scripts_dir = str(module_path.parent) if scripts_dir not in sys.path: diff --git a/backend/tests/test_rpa_trigger_consumer.py b/backend/tests/test_rpa_trigger_consumer.py index 0c4036ff..658b1b0f 100644 --- a/backend/tests/test_rpa_trigger_consumer.py +++ b/backend/tests/test_rpa_trigger_consumer.py @@ -13,7 +13,7 @@ from pathlib import Path import pytest -sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common")) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common")) from trigger_consumer import archive_trigger, claim_trigger # noqa: E402 @@ -64,7 +64,7 @@ def test_archive_rejects_bad_outcome_and_unclaimed_path(tmp_path): def test_inventory_worker_scans_with_claim(tmp_path): """库存 Worker 扫描必须先领取(processing/),不得原地消费根目录文件。""" - root = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" + root = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" text = (root / "inventory_rpa_worker.py").read_text(encoding="utf-8") assert "claim_trigger" in text # 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent @@ -73,7 +73,7 @@ def test_inventory_worker_scans_with_claim(tmp_path): def test_receipt_worker_runs_periodic_disk_cleanup(): """收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。""" - receipt = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8") + receipt = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8") assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt - cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8") + cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8") assert '"receipt_"' in cleanup or "'receipt_'" in cleanup diff --git a/backend/tests/test_rpa_worker_heartbeat.py b/backend/tests/test_rpa_worker_heartbeat.py index a81c9baf..50515b58 100644 --- a/backend/tests/test_rpa_worker_heartbeat.py +++ b/backend/tests/test_rpa_worker_heartbeat.py @@ -67,12 +67,12 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d trigger_dir.mkdir() _write_shared_sentinel(trigger_dir, scope_id=scope_id) app.config["ENV_NAME"] = "test" - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) - app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True + app.config["FREIGHT_RPA_WORKER_MOCK"] = "false" return trigger_dir @@ -132,11 +132,11 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path): trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() app.config["ENV_NAME"] = "test" - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) - app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data" - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data" + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True + app.config["FREIGHT_RPA_WORKER_MOCK"] = "false" with app.app_context(): record_rpa_worker_heartbeat( @@ -154,9 +154,9 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa """生产策略要求 Redis 时,写入失败应抛存储不可用。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False monkeypatch.setattr( "app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker", lambda _worker: False, @@ -169,23 +169,35 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa assert exc_info.value.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE -def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path): +def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch): """fail-fast 应附带 reasons 详情供排程日志与运维定位。""" + from app.services.shipping_notice.rpa_worker_heartbeat import ( + reset_rpa_worker_heartbeat_state_for_tests, + ) + + # 隔离:强制无 Redis 分支(_redis_client 为模块级单例,config 置空不可靠,须 monkeypatch); + # 并清空心跳存储,确保走 no_worker_heartbeat + 进程内存储原因码。 + from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module + monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None) + reset_rpa_worker_heartbeat_state_for_tests() trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data") app.config["ENV_NAME"] = "test" - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) - app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data" - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data" + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True + app.config["FREIGHT_RPA_WORKER_MOCK"] = "false" with app.app_context(): with pytest.raises(ServiceUnavailableError) as exc_info: assert_inventory_rpa_worker_ready() assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE - assert "no_worker_heartbeat" in (exc_info.value.details or {}).get("reasons", []) + reasons = (exc_info.value.details or {}).get("reasons", []) + assert "no_worker_heartbeat" in reasons + # [断言意图] 无 Redis 时心跳存储为本进程内存,必须给出原因码与本地测试指引 + assert "heartbeat_store_process_local" in reasons assert (exc_info.value.details or {}).get("detail_message") @@ -194,7 +206,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path, import time as time_module trigger_dir = _enable_prod_like_checks(app, tmp_path) - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90 + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90 base_now = time_module.time() with app.app_context(): @@ -218,7 +230,7 @@ def test_rpa_heartbeat_api_records_worker(client, app, tmp_path): trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key" - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve())) res = client.post( @@ -258,11 +270,19 @@ def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path): assert res.status_code == 401 -def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path): +def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypatch): """排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。""" from app import db from app.models import ScheduleRun, ScheduleTask, User from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule + from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module + from app.services.shipping_notice.rpa_worker_heartbeat import ( + reset_rpa_worker_heartbeat_state_for_tests, + ) + + # 隔离:强制无 Redis 分支(防真实心跳/单例缓存混入测试窗口)并清空存储,锁定离线 fail-fast 分支。 + monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None) + reset_rpa_worker_heartbeat_state_for_tests() trigger_dir = _enable_prod_like_checks(app, tmp_path) @@ -304,8 +324,8 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_path, monkeypatch): """Redis 读取异常应报 heartbeat_storage_unavailable,而非 no_worker_heartbeat。""" trigger_dir = _enable_prod_like_checks(app, tmp_path) - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False class BrokenRedis: def smembers(self, _key): @@ -327,8 +347,8 @@ def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_pat def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch): """test/prod Redis 策略:写入+读取成功时应 ready。""" trigger_dir = _enable_prod_like_checks(app, tmp_path) - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False bucket: dict[str, Any] = {"index": set()} class FakeRedis: @@ -370,8 +390,8 @@ def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path) trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers" trigger_dir.mkdir(parents=True) _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data") - app.config.pop("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", None) - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None) + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): assert shared_scope_id() == "hxops-rpa-test-data" @@ -385,15 +405,15 @@ def _enable_freight_upload_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-t upload_queue.mkdir() _write_shared_sentinel(upload_trigger, scope_id=scope_id) app.config["ENV_NAME"] = "test" - app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger) - app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue) - app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id - app.config["SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE=" + app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger) + app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue) + app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id + app.config["FREIGHT_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE=" app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052" - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True + app.config["FREIGHT_RPA_WORKER_MOCK"] = "false" return upload_trigger @@ -437,7 +457,7 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path): _enable_freight_upload_checks(app, tmp_path) # 去掉凭据主密钥:即使 Redis 残留心跳,静态配置缺失也必须阻断。 - app.config.pop("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", None) + app.config.pop("FREIGHT_RPA_CREDENTIAL_KEY", None) reset_rpa_worker_heartbeat_state_for_tests() with app.app_context(): with pytest.raises(ServiceUnavailableError) as exc_info: diff --git a/backend/tests/test_rpa_worker_heartbeat_alert.py b/backend/tests/test_rpa_worker_heartbeat_alert.py index 0a8de07e..7d9fe64f 100644 --- a/backend/tests/test_rpa_worker_heartbeat_alert.py +++ b/backend/tests/test_rpa_worker_heartbeat_alert.py @@ -32,16 +32,16 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() app.config["ENV_NAME"] = "test" - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) - app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False - app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600 - app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = "" - app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True - app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True + app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False + app.config["FREIGHT_RPA_WORKER_ALERT_ENABLED"] = True + app.config["FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600 + app.config["FREIGHT_RPA_WORKER_ALERT_USERNAMES"] = "" + app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True + app.config["FREIGHT_RPA_WORKER_MOCK"] = "false" return trigger_dir @@ -188,7 +188,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch import logging _enable_alert_checks(app, tmp_path) - app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True + app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True monkeypatch.setattr( "app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready", @@ -214,7 +214,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatch): """显式配置的用户名优先于 admin 回退。""" _enable_alert_checks(app, tmp_path) - app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = "oncall_user" + app.config["FREIGHT_RPA_WORKER_ALERT_USERNAMES"] = "oncall_user" with app.app_context(): from app import db @@ -325,7 +325,7 @@ def test_concurrent_first_claim_integrity_error_does_not_claim(app, monkeypatch) def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch): """过期 sending 锁且 sending_target=offline 时,Worker 恢复后应发送恢复通知。""" _enable_alert_checks(app, tmp_path) - app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS"] = 60 + app.config["FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS"] = 60 stale_sending = { "status": _STATUS_SENDING, diff --git a/backend/tests/test_rpa_worker_logging.py b/backend/tests/test_rpa_worker_logging.py index 7b43250d..ed943d77 100644 --- a/backend/tests/test_rpa_worker_logging.py +++ b/backend/tests/test_rpa_worker_logging.py @@ -2,7 +2,7 @@ 用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、 按大小轮转滚动备份、shutdown 恢复标准流。 -依赖:标准库 + scripts/rpa/common/worker_logging。 +依赖:标准库 + scripts/freight_rpa/common/worker_logging。 逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。 """ @@ -13,7 +13,7 @@ from pathlib import Path import pytest -sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "common")) +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common")) from worker_logging import ( # noqa: E402 WorkerLogTee, @@ -50,8 +50,8 @@ def test_tee_writes_timestamped_lines_to_both_streams(tmp_path, capsys): def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch): """超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。""" - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "10") - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2") + monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "10") + monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2") path = tmp_path / "worker.log" for round_no in range(3): path.write_text(f"round-{round_no}-padding", encoding="utf-8") @@ -65,7 +65,7 @@ def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch): def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monkeypatch, capsys): """configure 启用落盘、print 双写;shutdown 恢复标准流且不再写文件。""" - monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log")) + monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_FILE", str(tmp_path / "logs" / "worker.log")) enabled = configure_file_logging() assert enabled == tmp_path / "logs" / "worker.log" assert enabled.parent.is_dir() # 日志目录自动创建 @@ -80,5 +80,5 @@ def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monk def test_configure_without_env_is_noop(monkeypatch): """未配置 LOG_FILE 时 configure 返回 None 且不改标准流。""" - monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", raising=False) + monkeypatch.delenv("FREIGHT_RPA_WORKER_LOG_FILE", raising=False) assert configure_file_logging() is None diff --git a/backend/tests/test_shipping_inventory_configuration.py b/backend/tests/test_shipping_inventory_configuration.py index 55d9cf57..aaa37cae 100644 --- a/backend/tests/test_shipping_inventory_configuration.py +++ b/backend/tests/test_shipping_inventory_configuration.py @@ -135,7 +135,7 @@ def _confirm_direct_rpa_task_customer(task: ShippingOrderTask) -> None: def test_encrypt_credential_round_trip_requires_runtime_key(app): """凭据必须依赖环境主密钥加密,且可在受控运行时回读。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') with app.app_context(): ciphertext = encrypt_credential('not-a-real-password') assert ciphertext != 'not-a-real-password' @@ -144,7 +144,7 @@ def test_encrypt_credential_round_trip_requires_runtime_key(app): def test_encrypt_credential_rejects_missing_runtime_key(app): """关键加密主密钥缺失时拒绝写入凭据,避免产生不可恢复密文。""" - app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = '' + app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = '' with app.app_context(), pytest.raises(ServiceUnavailableError): encrypt_credential('not-a-real-password') diff --git a/backend/tests/test_shipping_notice_inventory_rpa_archive.py b/backend/tests/test_shipping_notice_inventory_rpa_archive.py index ca02bcfc..d907b2af 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_archive.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_archive.py @@ -130,7 +130,7 @@ def test_serialize_run_reads_inventory_raw_zip_available_from_summary(app): def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path): """finalize 预生成应落盘 ZIP 并返回 summary 字段。""" archive_dir = tmp_path / "inventory_archives" - app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) xlsx = tmp_path / "inventory.xlsx" xlsx.write_bytes(b"fake-xlsx-content") @@ -176,7 +176,7 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path): """无可读快照时不生成 ZIP。""" archive_dir = tmp_path / "inventory_archives" - app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) with app.app_context(): run = _make_inventory_run_with_created( @@ -193,7 +193,7 @@ def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_fi def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp_path): """created 有记录但磁盘文件缺失时不应生成 ZIP。""" archive_dir = tmp_path / "inventory_archives" - app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) with app.app_context(): run = _make_inventory_run_with_created( @@ -219,7 +219,7 @@ def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path): """下载解析应返回归档路径与建议文件名。""" archive_dir = tmp_path / "inventory_archives" - app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) xlsx = tmp_path / "inventory.xlsx" xlsx.write_bytes(b"fake-xlsx-content") @@ -262,7 +262,7 @@ def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app): def test_resolve_inventory_raw_zip_download_rejects_path_outside_archive_dir(app, tmp_path): """summary 指向归档目录外的真实文件时必须 404。""" archive_dir = tmp_path / "inventory_archives" - app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) outside_zip = tmp_path / "outside.zip" outside_zip.write_bytes(b"fake-zip") @@ -286,7 +286,7 @@ def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path """summary 指向非 .zip 后缀文件时必须 404。""" archive_dir = tmp_path / "inventory_archives" archive_dir.mkdir(parents=True) - app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) fake_file = archive_dir / "RUN-ARCH-RESOLVE-BAD.txt" fake_file.write_bytes(b"not-a-zip") @@ -414,7 +414,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke app.config["WECOM_NOTIFY_ENABLED"] = True app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com" app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/" - app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives") + app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives") user = User( username="wecom_jump_user", @@ -482,7 +482,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename( ): """admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。""" archive_dir = tmp_path / "inventory_archives" - app.config["SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) + app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir) xlsx = tmp_path / "inventory.xlsx" xlsx.write_bytes(b"fake-xlsx-content") diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 4cb10a37..347896a3 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -641,7 +641,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_mixed.xlsx" @@ -683,7 +683,7 @@ def test_rpa_snapshot_persists_confirmed_profile_mapping(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory-mapping-confirmed.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -769,7 +769,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "batch_task_success.xlsx" @@ -854,7 +854,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) with app.app_context(): task = ShippingOrderTask( @@ -981,7 +981,7 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot drop_dir = tmp_path / "drop" drop_dir.mkdir() app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) sample = drop_dir / "crane-multi-warehouse.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("CRANE-WH").getvalue()) @@ -1054,7 +1054,7 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva drop_dir = tmp_path / "drop" drop_dir.mkdir() app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) sample = drop_dir / "crane-unresolved-link.xlsx" sample.write_bytes( inventory_xlsx_with_warehouse( @@ -1301,7 +1301,7 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "orphan_task.xlsx" with open(sample, "wb") as handle: @@ -1398,7 +1398,7 @@ def test_inventory_trigger_writes_without_online_worker(app, tmp_path, monkeypat with app.app_context(): trigger_dir = tmp_path / 'inventory_triggers' - app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR'] = str(trigger_dir) + app.config['FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR'] = str(trigger_dir) monkeypatch.setattr( 'app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready', lambda: (_ for _ in ()).throw(AssertionError('trigger write must not require worker heartbeat')), @@ -1515,7 +1515,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "reuse_ingest_fail.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -1587,7 +1587,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") run_no = "RUN-REUSE-MISMATCH" @@ -1642,7 +1642,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path, drop_dir = tmp_path / "drop" drop_dir.mkdir(parents=True, exist_ok=True) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) sample_a = drop_dir / "task_a.xlsx" sample_b = drop_dir / "task_b.xlsx" sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -1714,7 +1714,7 @@ def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path, drop_dir = tmp_path / "drop" drop_dir.mkdir(parents=True, exist_ok=True) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) sample = drop_dir / "failed_before_confirm.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) callback_calls: list[dict] = [] @@ -1775,7 +1775,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m drop_dir = tmp_path / "drop" drop_dir.mkdir() app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) sample = drop_dir / "shared.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) run_no = "RUN-SHARED-LINK" @@ -1851,7 +1851,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "post_commit.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -1894,7 +1894,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "promote_fail.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -1988,7 +1988,7 @@ def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "move_fail.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -2027,7 +2027,7 @@ def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, m drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "quarantine_fail.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -2156,7 +2156,7 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat processed_dir = tmp_path / "processed" drop_dir.mkdir() processed_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir) quarantine = drop_dir / ".hxops_quarantine" diff --git a/backend/tests/test_shipping_notice_inventory_schedule.py b/backend/tests/test_shipping_notice_inventory_schedule.py index 0acaaa9e..07e39fd6 100644 --- a/backend/tests/test_shipping_notice_inventory_schedule.py +++ b/backend/tests/test_shipping_notice_inventory_schedule.py @@ -103,7 +103,7 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path): """排程 executor 应写入 inventory_export_batch trigger。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): task = _make_inventory_schedule_task( @@ -135,7 +135,7 @@ def test_run_task_now_defers_inventory_rpa_until_callback(app, tmp_path): """run_task_now 写 trigger 后应保持 running 且 awaiting_rpa=true。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): task = _make_inventory_schedule_task( @@ -157,7 +157,7 @@ def test_deferred_run_sets_started_at_when_missing(app, tmp_path): """复用无 started_at 的 run 时,defer 应补写 started_at,避免立即超时回收。""" trigger_dir = tmp_path / "triggers" trigger_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): task = _make_inventory_schedule_task( @@ -244,7 +244,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch) """全部 source 成功但 Excel 导出失败时应降为 partial_failed 并写入 error_message。""" drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_excel_fail.xlsx" @@ -309,7 +309,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp """finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。""" drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_fail_finalize.xlsx" @@ -373,7 +373,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path): drop_dir.mkdir() processed_dir = drop_dir / "processed" processed_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_sample.xlsx" @@ -516,7 +516,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path): """回调结果少于触发源数时,排程应 partial_failed。""" drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "inventory_partial.xlsx" @@ -851,7 +851,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path): drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "missing_warehouse.xlsx" _write_sample_inventory(sample, "AWSDU") @@ -881,7 +881,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "retry_snapshot.xlsx" _write_sample_inventory(sample, "AWSDU") @@ -944,7 +944,7 @@ def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, mon drop_dir = tmp_path / "drop" drop_dir.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") sample = drop_dir / "retry_move.xlsx" _write_sample_inventory(sample, "AWSDU") diff --git a/backend/tests/test_shipping_notice_rpa_trigger_for_task.py b/backend/tests/test_shipping_notice_rpa_trigger_for_task.py index 0ec271e8..8de99331 100644 --- a/backend/tests/test_shipping_notice_rpa_trigger_for_task.py +++ b/backend/tests/test_shipping_notice_rpa_trigger_for_task.py @@ -14,7 +14,7 @@ from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch): """batch 开启时单票按需应写 inventory_export_batch trigger。""" trigger_dir = tmp_path / "triggers" - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config.pop("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", None) monkeypatch.setenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true") @@ -55,7 +55,7 @@ def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path): from app.core.errors import ValidationError trigger_dir = tmp_path / "triggers" - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}} @@ -71,7 +71,7 @@ def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_p from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger trigger_dir = tmp_path / "triggers" - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) with app.app_context(): path = write_inventory_export_batch_trigger("RUN-DBS", [{ "source_code": "UNKNOWN_FOR_TEST", "connector_type": "dbs", "rpa_profile_code": "DBS_TEST", @@ -92,7 +92,7 @@ def test_batch_trigger_writes_explicit_v2_callback_identity(app, tmp_path): from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger trigger_dir = tmp_path / "triggers" - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True source = { "source_code": "DBS", diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index cc4dfa20..e1333e05 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -459,8 +459,8 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt headers = _tool_headers(app) trigger = tmp_path / "inventory_triggers" trigger.mkdir() - app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) - app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1 + app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) + app.config["FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1 monkeypatch.setattr( "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready", lambda: None, diff --git a/docker-compose.yml b/docker-compose.yml index d6a9b598..35421fe9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -172,8 +172,6 @@ services: - SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS=${SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS:-7200} - KB_STORAGE_ROOT=${KB_STORAGE_ROOT:-/app/data/kb} - SHIPPING_NOTICE_STORAGE_ROOT=${SHIPPING_NOTICE_STORAGE_ROOT:-/app/data/shipping_notice} - - FREIGHT_INVENTORY_DROP_DIR=${FREIGHT_INVENTORY_DROP_DIR:-/app/data/shipping_notice/freight_rpa/inventory_drop} - - FREIGHT_RPA_INVENTORY_TRIGGER_DIR=${FREIGHT_RPA_INVENTORY_TRIGGER_DIR:-/app/data/shipping_notice/freight_rpa/inventory_triggers} # 立账凭证检核:周批在 schedule-worker 内执行 - VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-} - VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-} @@ -265,7 +263,7 @@ services: - FLASK_APP=${FLASK_APP:-run.py} - FLASK_ENV=${FLASK_ENV} - REDIS_URL=${REDIS_URL:-redis://kb-redis:6379/0} - - SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=${SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR:-} + - FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=${FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR:-} - IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=${IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY:-2} - IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=${IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY:-2} - IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=${IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY:-1} diff --git a/docs/convention/env_loading_priority.md b/docs/convention/env_loading_priority.md index 75dc803b..a15e6782 100644 --- a/docs/convention/env_loading_priority.md +++ b/docs/convention/env_loading_priority.md @@ -62,10 +62,10 @@ - 新增变量同步更新对应 env 文件和本文档。 - 继续清理对 `backend/.env` 的历史依赖。 -## 7. Shipping Notice RPA 命名空间 +## 7. 货代 RPA(FREIGHT_RPA)命名空间 -- 后端业务参数:`SHIPPING_NOTICE_RPA_<配置项>`。 -- 后端与 Windows Worker 共享目录、共享 scope、哨兵:`SHIPPING_NOTICE_RPA_SHARED_<配置项>`。 -- Windows Worker 自身运行、浏览器、Driver、日志与账号参数:`SHIPPING_NOTICE_RPA_WORKER_<配置项>`。 -- RPA Profile 凭据 Fernet 主密钥:`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。 -- 禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史变量仅作为迁移期 fallback;新名称优先,完成所有环境迁移后删除旧名称。 +- 后端业务参数:`FREIGHT_RPA_<配置项>`。 +- 后端与 Windows Worker 共享目录、共享 scope、哨兵:`FREIGHT_RPA_SHARED_<配置项>`。 +- Windows Worker 自身运行、浏览器、Driver、日志与账号参数:`FREIGHT_RPA_WORKER_<配置项>`。 +- RPA Profile 凭据 Fernet 主密钥:`FREIGHT_RPA_CREDENTIAL_KEY`。 +- 禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,不设兼容层,禁止再新增或引用。 diff --git a/docs/features/in-transit-transfer/technical.md b/docs/features/in-transit-transfer/technical.md index 8ee235be..84c91fd1 100644 --- a/docs/features/in-transit-transfer/technical.md +++ b/docs/features/in-transit-transfer/technical.md @@ -35,7 +35,7 @@ | `IN_TRANSIT_TRANSFER_ERP_ENDPOINT` / `_USERNAME` / `_PASSWORD` / `_DEFAULT_ORG` | 空 | ERP SOAP 地址与凭据(WSDL 冻结前留空=fail-closed) | | `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` | hxops-transfer | 归档 bucket | | `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | MinIO 连接(复用既有变量) | -| `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` | 既有 | 收料 RPA trigger 目录(复用收料链路) | +| `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` | 既有 | 收料 RPA trigger 目录(复用收料链路) | > 凭据纪律:ERP/MinIO 凭据只存在于环境/Secret;不得写入代码、日志、DOM、Excel 或 API 响应。 diff --git a/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md b/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md index ec7ffe94..09f2424d 100644 --- a/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md +++ b/docs/features/shipping-notice/2026-08-19-freight-receipt-rpa-minimal.md @@ -12,7 +12,7 @@ ## Global Constraints -- 禁止修改 `scripts/rpa/inventory/inventory_rpa_worker.py`、`shipping_inventory_rpa.v2`、`/api/shipping-notice/rpa/inventory-*` 与库存入库/匹配服务。 +- 禁止修改 `scripts/freight_rpa/inventory/inventory_rpa_worker.py`、`shipping_inventory_rpa.v2`、`/api/shipping-notice/rpa/inventory-*` 与库存入库/匹配服务。 - 首版不实现库存和收料间的登录会话复用、同 Profile 互斥锁或跨排程协调;运维上错开使用同一 Profile 的排程时间。 - 收料 Worker 在单次排程内以 `connector_type + rpa_profile_id + login_url` 分组,每个分组登录一次、串行处理其全部单元。 - DBS 每个收料配置 Warehouse 展开一条单元;报表日期固定不传。Crane 每站点创建 `Inbound Details`,通过本次唯一 Description 轮询并下载。 @@ -88,15 +88,15 @@ ### Task 4: 实现独立 DBS/Crane 收料 Windows Worker **Files:** -- Create: `scripts/rpa/receipt/receipt_rpa_worker.py` -- Create: `scripts/rpa/receipt/receipt_dbs_export.py` -- Create: `scripts/rpa/receipt/receipt_crane_export.py` -- Create: `scripts/rpa/receipt/start_receipt_worker.ps1` -- Modify: `scripts/rpa/README.md` +- Create: `scripts/freight_rpa/receipt/receipt_rpa_worker.py` +- Create: `scripts/freight_rpa/receipt/receipt_dbs_export.py` +- Create: `scripts/freight_rpa/receipt/receipt_crane_export.py` +- Create: `scripts/freight_rpa/receipt/start_receipt_worker.ps1` +- Modify: `scripts/freight_rpa/README.md` - Test: `backend/tests/test_freight_receipt_worker_contract.py` **Interfaces:** -- 只扫描 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR`,只写 `...RECEIPT_DROP_DIR`,只调用 receipt callback。 +- 只扫描 `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR`,只写 `...RECEIPT_DROP_DIR`,只调用 receipt callback。 - DBS driver 复用受验证的登录/导航/参数/下载工具;Crane driver 复用会话和异步报表能力,但固定收料报表名。 - [x] 写失败 mock 测试:拒绝非 v1 trigger;DBS 不传日期但填 Warehouse/受控条件;Crane 每单元生成唯一 Description 且只下载匹配项;callback 失败只移动 receipt trigger 至 `failed/`,不触碰 inventory 目录。 diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 2b60593a..45d7dba5 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -1729,10 +1729,10 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 # RPA 目录 -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers +FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop +FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers ## 字段资产库与 Schema 契约(目标态) @@ -1831,9 +1831,9 @@ GET /api/admin/shipping-order-schema/published-contract - **Dify 手动配置说明**:本阶段无需新增、修改或重新导入 Dify Tool/OpenAPI,也无需修改画布或 Prompt。库存站点测试、结构检查、方案确认和启用均由管理端调用 HXOPS Admin API 完成;Dify 不读取或判断 `activation.checks`。 - `GET /api/admin/shipping-notice/sources/{id}/test-export/latest` 只返回**当前站点配置和当前 RPA Profile 配置版本**对应的最近测试,无记录时返回 `null`。管理端打开站点抽屉时读取该接口恢复测试状态,只有 `awaiting_rpa / processing` 才轮询运行详情;关闭抽屉立即停止轮询。重复发起测试仅复用同一版本的运行任务,配置变更后的旧运行不会阻止新测试。 - 批量测试创建时各站点先处于 `awaiting_rpa / waiting_worker`。Windows Worker 实际领取某个站点前,会向 `POST /api/shipping-notice/rpa/inventory-configuration-test-batch-progress` 回调该站点的 `validation_run_no` 与受控阶段 `rpa_exporting`;后端仅允许将当前批次的非终态运行写为 `processing / rpa_exporting`。因此管理端可以区分“尚未被 Worker 领取”和“RPA 正在登录并导出”;最终成功、无库存或失败仍必须通过原有 `inventory-configuration-test-batch-ready` 回调确认,进度回调不得覆盖终态。同一 Profile 仍只登录一次,但每个 DSV 站点使用新的页面并复用同一 browser context 的登录 Cookie,避免上一站报表 iframe、下载菜单或等待状态污染下一站。 -- 测试运行超过 `SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS`(默认 900 秒)仍未完成时,服务端在读取或再次发起测试时将其收口为 `failed / failed`,提示“等待 RPA Worker 超时,请重新测试”。同一 Worker 队列中的批量站点按队列站点数线性扩展等待窗口,避免后排站点尚未领取就按单站时限误判超时;单站测试仍使用原始等待窗口。超时、版本不一致和重复/迟到回调都不能更新当前站点绑定或放行启用。**Dify 手动配置说明**:此恢复与轮询机制不要求修改 Dify 画布、Tool 或 Prompt;Dify 不读取此管理端状态接口。 -- **DSV SSO 回跳优化(2026-07)**:密码提交后,Worker 将 `auth.dbschenker.com` 的授权回跳与 Portal Reports 菜单加载分开计时。空白 `authorization.ping/oauth2` 中转页停留 `SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS`(默认 12000)后只刷新一次;超过 `SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS`(默认 90000)仍未回到 Portal 时,明确报 `DSV SSO authorization return timed out`,不再伪装为库存测试超时。Portal 壳层出现后仅轮询 Reports 导航,避免反复读取整页与 iframe。Dify 无需修改配置。 -- **DSV 性能证据与快速路径(2026-08)**:库存导出 Worker 以 `[dsv-chain]` 输出不含凭据和查询参数的 `session_prepare`、`report_navigation`、`report_parameter_fill`、`report_execute_and_download`,并将最后一段拆为 `report_result_ready` 与 `excel_export_and_download` 的 `start/end/error` 与 `elapsedMs`;登录内层继续输出 `auto_login.*` 子阶段,Warehouse option 等待继续输出 `waitedMs`。- 提交 View Report 后直接等待 SSRS 业务就绪条件,不以可能被长连接阻塞的 `networkidle` 作为前置条件。result_ready(分页/工具栏)之后**明细行是异步渲染**的:worker 用 `_wait_dsv_report_inventory_rows` 做条件轮询(1s 间隔、上限 45s)等待真实数据行,而非单次快照,避免"分页已出、行未渲染"被误判为无库存数据(2026-08-26 真实案例:160 页报表被单次探针误判 skip)。Excel 下载等待窗口按实测放宽:`expect_download` 使用 `SHIPPING_NOTICE_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS`(默认 240s,SSRS 生成 34s~90s+ 波动),目录兜底 60s;禁止复用全局 60s 浏览器超时作为下载等待(2026-08-26 多次 `Timeout 60000ms exceeded while waiting for event "download"` 根因)。Reports 级联菜单先走一次精确文本的 hover/click 快速路径,只有未确认下一级已展开时才退回原多 selector、多动作兼容链;不得因优化删除回退逻辑。一次真实运行据此区分认证/首页、报表菜单/参数页、参数异步加载、SSRS 结果与 Excel 导出下载耗时。 +- 测试运行超过 `FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS`(默认 900 秒)仍未完成时,服务端在读取或再次发起测试时将其收口为 `failed / failed`,提示“等待 RPA Worker 超时,请重新测试”。同一 Worker 队列中的批量站点按队列站点数线性扩展等待窗口,避免后排站点尚未领取就按单站时限误判超时;单站测试仍使用原始等待窗口。超时、版本不一致和重复/迟到回调都不能更新当前站点绑定或放行启用。**Dify 手动配置说明**:此恢复与轮询机制不要求修改 Dify 画布、Tool 或 Prompt;Dify 不读取此管理端状态接口。 +- **DSV SSO 回跳优化(2026-07)**:密码提交后,Worker 将 `auth.dbschenker.com` 的授权回跳与 Portal Reports 菜单加载分开计时。空白 `authorization.ping/oauth2` 中转页停留 `FREIGHT_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS`(默认 12000)后只刷新一次;超过 `FREIGHT_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS`(默认 90000)仍未回到 Portal 时,明确报 `DSV SSO authorization return timed out`,不再伪装为库存测试超时。Portal 壳层出现后仅轮询 Reports 导航,避免反复读取整页与 iframe。Dify 无需修改配置。 +- **DSV 性能证据与快速路径(2026-08)**:库存导出 Worker 以 `[dsv-chain]` 输出不含凭据和查询参数的 `session_prepare`、`report_navigation`、`report_parameter_fill`、`report_execute_and_download`,并将最后一段拆为 `report_result_ready` 与 `excel_export_and_download` 的 `start/end/error` 与 `elapsedMs`;登录内层继续输出 `auto_login.*` 子阶段,Warehouse option 等待继续输出 `waitedMs`。- 提交 View Report 后直接等待 SSRS 业务就绪条件,不以可能被长连接阻塞的 `networkidle` 作为前置条件。result_ready(分页/工具栏)之后**明细行是异步渲染**的:worker 用 `_wait_dsv_report_inventory_rows` 做条件轮询(1s 间隔、上限 45s)等待真实数据行,而非单次快照,避免"分页已出、行未渲染"被误判为无库存数据(2026-08-26 真实案例:160 页报表被单次探针误判 skip)。Excel 下载等待窗口按实测放宽:`expect_download` 使用 `FREIGHT_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS`(默认 240s,SSRS 生成 34s~90s+ 波动),目录兜底 60s;禁止复用全局 60s 浏览器超时作为下载等待(2026-08-26 多次 `Timeout 60000ms exceeded while waiting for event "download"` 根因)。Reports 级联菜单先走一次精确文本的 hover/click 快速路径,只有未确认下一级已展开时才退回原多 selector、多动作兼容链;不得因优化删除回退逻辑。一次真实运行据此区分认证/首页、报表菜单/参数页、参数异步加载、SSRS 结果与 Excel 导出下载耗时。 - 多个 Inventory Source 可绑定同一个 published Profile;同模板只维护一份。存在少量列差异时创建新 Profile 版本或新 Profile,不在 Source 中复制完整映射。 - 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。 - 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingInventoryExternalMapping`,绝不自动创建映射。 @@ -1859,7 +1859,7 @@ GET /api/admin/shipping-order-schema/published-contract - **DSV 初始值**:`enabled=true`,`entry_url=https://s360.dbschenker.com/main/portal/frame/WMSUpload2`,`file_input_selector=input#file2`,`submit_mode=auto_after_file`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。 - **Crane 初始值**:`enabled=false`(提交按钮、成功提示或上传历史记录的稳定选择器尚未确认,仅有文件选择器不代表可安全自动提交),`entry_url=https://wms-portal.craneww.com/#/shipping-order-upload`,`file_input_selector=input[name="OrderFileUpload"]`,`submit_mode=click_submit`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。管理员完成页面验证并补全提交/成功判定字段后才可 `enabled=true`。 - **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期;不维护 `upload_config_version`(无发布流、无并发编辑审批、无历史回放需求)。每个 trigger 固化本次 upload_config 快照即可保证“这次上传用了什么”;需要审计关联时对快照计算 `config_hash`(sha256)。 -- **Worker 保留两个受控 Adapter**:`DsvUploadAdapter`(DSV 入口、文件选择与结果判定)与 `CraneUploadAdapter`(Crane 入口、文件选择、提交与结果判定),**不再根据环境变量拼接 DSV/Crane 页面动作**。用连接 `login_url` 登录后访问 `upload_config.entry_url` 进入上传页;`upload_config` 决定“该连接使用哪个已支持的受控流程及其页面参数”,浏览器动作与安全边界由代码负责;Worker 上传与最终提交的全局开关(`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留,但不再承载页面参数。 +- **Worker 保留两个受控 Adapter**:`DsvUploadAdapter`(DSV 入口、文件选择与结果判定)与 `CraneUploadAdapter`(Crane 入口、文件选择、提交与结果判定),**不再根据环境变量拼接 DSV/Crane 页面动作**。用连接 `login_url` 登录后访问 `upload_config.entry_url` 进入上传页;`upload_config` 决定“该连接使用哪个已支持的受控流程及其页面参数”,浏览器动作与安全边界由代码负责;Worker 上传与最终提交的全局开关(`FREIGHT_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留,但不再承载页面参数。 - **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及 `upload_config_json` → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger(复用“临时文件 + fsync + os.replace”,携带 `schema_version / task_no / attempt_id / artifact_id / callback_id / connector_type / upload_config 快照 / upload_config_hash / login_url / credential_envelope`)→ Windows Worker 取 trigger → 按 `connector_type` 进入 DSV/Crane Adapter → 登录、打开 entry_url、选择 Excel、提交 → 以受控页面选择器判定 → 回调。 - **结果三态**:`success`(取得可核验成功证据)、`failed`(明确页面失败、浏览器错误、超时或回调失败)、`unknown`(已可能提交但无法确认外部系统结果)。`unknown` 必须转人工处理,禁止自动重试以避免重复上传;成功/失败/未知、页面证据摘要与脱敏错误写入现有 Upload Attempt 与货代审计事件。 @@ -1950,7 +1950,7 @@ GET /api/admin/shipping-order-schema/published-contract # SHIPPING_NOTICE_TASK_EXECUTION_MODE=worker # RPA 库存导出等待超时(秒,默认 900;DSV 实际链路建议至少 900) -# SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 +# FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 # 发货 worker 轮询间隔(秒) # SHIPPING_NOTICE_WORKER_POLL_SECONDS=2 @@ -1970,8 +1970,8 @@ GET /api/admin/shipping-order-schema/published-contract ```powershell $env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key" -$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true" -python scripts/rpa/inventory/inventory_rpa_worker.py +$env:FREIGHT_RPA_WORKER_MOCK = "true" +python scripts/freight_rpa/inventory/inventory_rpa_worker.py ``` ### 1.5 库存导出 RPA 共享部署(Windows RPA + Ubuntu 后端) @@ -2024,7 +2024,7 @@ Ubuntu 后端写 Linux 挂载路径,Windows RPA worker 读 Windows 本地路 ```powershell foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { New-Item -ItemType Directory -Force $root - New-Item -ItemType Directory -Force "$root\scripts\rpa" + New-Item -ItemType Directory -Force "$root\scripts\freight_rpa" New-Item -ItemType Directory -Force "$root\backend\config" New-Item -ItemType Directory -Force "$root\data\inventory_triggers" @@ -2039,24 +2039,24 @@ foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { 从项目仓库复制以下文件到 Windows RPA 主机: ```text -scripts\rpa\inventory\inventory_rpa_worker.py -scripts\rpa\connectors\dsv\dsv_report_parameters.py -scripts\rpa\connectors\dsv\dsv_login_smoke.py -scripts\rpa\inventory\run_inventory_batch_trigger.py +scripts\freight_rpa\inventory\inventory_rpa_worker.py +scripts\freight_rpa\connectors\dsv\dsv_report_parameters.py +scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py +scripts\freight_rpa\inventory\run_inventory_batch_trigger.py ``` 放置为: ```text -C:\HxopsRpaTest\scripts\rpa\inventory\inventory_rpa_worker.py -C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_report_parameters.py -C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_login_smoke.py -C:\HxopsRpaTest\scripts\rpa\inventory\run_inventory_batch_trigger.py +C:\HxopsRpaTest\scripts\freight_rpa\inventory\inventory_rpa_worker.py +C:\HxopsRpaTest\scripts\freight_rpa\connectors\dsv\dsv_report_parameters.py +C:\HxopsRpaTest\scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py +C:\HxopsRpaTest\scripts\freight_rpa\inventory\run_inventory_batch_trigger.py -C:\HxopsRpaProd\scripts\rpa\inventory\inventory_rpa_worker.py -C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_report_parameters.py -C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_login_smoke.py -C:\HxopsRpaProd\scripts\rpa\inventory\run_inventory_batch_trigger.py +C:\HxopsRpaProd\scripts\freight_rpa\inventory\inventory_rpa_worker.py +C:\HxopsRpaProd\scripts\freight_rpa\connectors\dsv\dsv_report_parameters.py +C:\HxopsRpaProd\scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py +C:\HxopsRpaProd\scripts\freight_rpa\inventory\run_inventory_batch_trigger.py ``` 不要复制 `.env*`、密码文件、`backend\data` 旧运行数据、浏览器 profile、旧 trigger / processed / failed 文件。 @@ -2104,14 +2104,14 @@ python -m playwright install chromium ``` **默认使用 Playwright 捆绑 Chromium**(上一步已 `playwright install chromium`)。 -勿设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`:Edge 152 + 持久 Profile +勿设置 `FREIGHT_RPA_WORKER_BROWSER_CHANNEL=msedge`:Edge 152 + 持久 Profile 在 Excel 下载时会原生崩溃(`Download.save_as: TargetClosed` / 残留 `.crdownload`)。 #### 1.5.5 Windows RPA 主机:临时环境变量与登录测试 先在 PowerShell 当前窗口配置临时环境变量,确认链路可用后再改成永久环境变量: -> `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 是 RPA Profile 凭据的 Fernet 主密钥。 +> `FREIGHT_RPA_CREDENTIAL_KEY` 是 RPA Profile 凭据的 Fernet 主密钥。 > Windows Worker 与对应 test/prod 后端必须使用同一个值,否则 Worker 无法解密 > 后端下发的 Profile 密文。该值必须从 Jenkins/Secret 管理器或受控运维渠道注入, > 禁止写入仓库、命令历史、截图或日志。 @@ -2121,61 +2121,61 @@ cd C:\HxopsRpaTest $env:HXOPS_API_BASE = "http://测试后端地址:端口" $env:SHIPPING_NOTICE_TOOL_API_KEY = "请替换为测试环境SHIPPING_NOTICE_TOOL_API_KEY" -# SHIPPING_NOTICE_RPA_CREDENTIAL_KEY 由受控 Secret 工具注入当前进程; +# FREIGHT_RPA_CREDENTIAL_KEY 由受控 Secret 工具注入当前进程; # Secret 由 new_rpa_worker_secret.ps1 安全交互创建。 -$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" -$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" +$env:FREIGHT_RPA_WORKER_MOCK = "false" +$env:FREIGHT_RPA_WORKER_HEADLESS = "false" # 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。 -$env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" +$env:FREIGHT_RPA_WORKER_POLL_SECONDS = "3" -$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\inventory_triggers" -$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = "C:\HxopsRpaTest\data\inventory_drop" -$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = "C:\HxopsRpaTest\data\upload_triggers" -$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = "C:\HxopsRpaTest\data\upload_queue" -$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\browser_profile" -$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log" -$env:SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760" -$env:SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5" -$env:SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7" -$env:SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600" -$env:SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24" +$env:FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\inventory_triggers" +$env:FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = "C:\HxopsRpaTest\data\inventory_drop" +$env:FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = "C:\HxopsRpaTest\data\upload_triggers" +$env:FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = "C:\HxopsRpaTest\data\upload_queue" +$env:FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\browser_profile" +$env:FREIGHT_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log" +$env:FREIGHT_RPA_WORKER_LOG_MAX_BYTES = "10485760" +$env:FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = "5" +$env:FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = "7" +$env:FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600" +$env:FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24" -$env:SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号" -$env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码" +$env:FREIGHT_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号" +$env:FREIGHT_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码" -$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME = "请替换为Crane账号" -$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "请替换为Crane密码" +$env:FREIGHT_RPA_WORKER_CRANE_USERNAME = "请替换为Crane账号" +$env:FREIGHT_RPA_WORKER_CRANE_PASSWORD = "请替换为Crane密码" -# 心跳与共享 scope(test/prod 必填;与 Ubuntu SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID 一致) -$env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "test" -$env:SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = "hxops-rpa-test-data" -$env:SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20" +# 心跳与共享 scope(test/prod 必填;与 Ubuntu FREIGHT_RPA_SHARED_SCOPE_ID 一致) +$env:FREIGHT_RPA_WORKER_ENVIRONMENT = "test" +$env:FREIGHT_RPA_SHARED_SCOPE_ID = "hxops-rpa-test-data" +$env:FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = "20" ``` -正式环境测试时,将 `C:\HxopsRpaTest` 改为 `C:\HxopsRpaProd`,`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` 改为 `prod`,`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` 改为 `hxops-rpa-prod-data`,并把 `HXOPS_API_BASE`、`SHIPPING_NOTICE_TOOL_API_KEY` 改为正式后端对应值。 +正式环境测试时,将 `C:\HxopsRpaTest` 改为 `C:\HxopsRpaProd`,`FREIGHT_RPA_WORKER_ENVIRONMENT` 改为 `prod`,`FREIGHT_RPA_SHARED_SCOPE_ID` 改为 `hxops-rpa-prod-data`,并把 `HXOPS_API_BASE`、`SHIPPING_NOTICE_TOOL_API_KEY` 改为正式后端对应值。 #### 1.5.5a RPA Worker 心跳、共享 scope 与哨兵 -test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是否匹配、共享目录是否有效。Windows Worker 需周期性 `POST /api/shipping-notice/rpa/heartbeat`,并在**库存 trigger 共享目录**(`SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR`,如 `...\inventory_triggers`)写入哨兵文件 `.hxops_rpa_shared_mount`(默认文件名,可由 `SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME` 覆盖)。 +test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是否匹配、共享目录是否有效。Windows Worker 需周期性 `POST /api/shipping-notice/rpa/heartbeat`,并在**库存 trigger 共享目录**(`FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR`,如 `...\inventory_triggers`)写入哨兵文件 `.hxops_rpa_shared_mount`(默认文件名,可由 `FREIGHT_RPA_SHARED_SENTINEL_NAME` 覆盖)。 | 侧 | 变量 | 测试示例 | 正式示例 | | --- | --- | --- | --- | -| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` | -| Windows RPA | `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` | -| Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` | `prod` | -| Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 | -| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS` | `90`(默认) | `90` | -| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED` | `false`(默认关闭企微心跳告警) | 同左;需要时改为 `true` | -| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` | 逗号分隔 HXOPS 用户名(**部署前建议显式填写**) | 同左 | -| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` | -| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS` | `120`(企微发送中短锁,失败后可重试) | `120` | +| Ubuntu 后端 | `FREIGHT_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` | +| Windows RPA | `FREIGHT_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` | +| Windows RPA | `FREIGHT_RPA_WORKER_ENVIRONMENT` | `test` | `prod` | +| Windows RPA | `FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 | +| Ubuntu 后端 | `FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS` | `90`(默认) | `90` | +| Ubuntu 后端 | `FREIGHT_RPA_WORKER_ALERT_ENABLED` | `false`(默认关闭企微心跳告警) | 同左;需要时改为 `true` | +| Ubuntu 后端 | `FREIGHT_RPA_WORKER_ALERT_USERNAMES` | 逗号分隔 HXOPS 用户名(**部署前建议显式填写**) | 同左 | +| Ubuntu 后端 | `FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` | +| Ubuntu 后端 | `FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS` | `120`(企微发送中短锁,失败后可重试) | `120` | -**告警接收人部署检查**:`SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` 留空时,仅当存在 `role=admin` 且已绑定 `wecom_userid` 的用户才会真正收到企微通知;否则只写 warning。上线前请二选一:填写运维用户名,或确认至少一名 admin 已完成企微绑定。 +**告警接收人部署检查**:`FREIGHT_RPA_WORKER_ALERT_USERNAMES` 留空时,仅当存在 `role=admin` 且已绑定 `wecom_userid` 的用户才会真正收到企微通知;否则只写 warning。上线前请二选一:填写运维用户名,或确认至少一名 admin 已完成企微绑定。 **多进程去重**:告警冷却状态以 `app_settings` 为权威源,Redis 仅作缓存同步;DB 不可读写时才回退 Redis/进程内内存 claim。 -**为何必须显式配置 scope**:Windows 标准路径 `C:\HxopsRpaTest\data\...` 不含 `hxops-rpa-test-data` 字样,后端无法从路径推导 scope;漏配 `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` 时 Worker 不写哨兵,就绪检查报 `shared_sentinel_missing`。 +**为何必须显式配置 scope**:Windows 标准路径 `C:\HxopsRpaTest\data\...` 不含 `hxops-rpa-test-data` 字样,后端无法从路径推导 scope;漏配 `FREIGHT_RPA_SHARED_SCOPE_ID` 时 Worker 不写哨兵,就绪检查报 `shared_sentinel_missing`。 Worker 启动后验证哨兵(测试环境示例): @@ -2191,12 +2191,12 @@ cat /mnt/hxops-rpa-test-data/inventory_triggers/.hxops_rpa_shared_mount 管理端 `GET /api/admin/rpa-workers/status` 可查看最后心跳;Worker 离线时触发库存 RPA 会立即失败(fail-fast),不再空等 900s。排程管理工作台的「RPA Worker 在线」徽标对该接口做 **10s 前台轮询**(仅库存排程工作台模式,后台标签页暂停、请求未返回时跳过);执行记录列表按**历史查询**处理,仅切任务/点查询/重置时加载,不做定时自动刷新。 -心跳存储:test/prod 默认要求 **Redis**(`SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true`)。Redis 不可用时触发与排程会报 `RPA.HEARTBEAT_STORAGE_UNAVAILABLE`;仅当 `SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=true` 时,调度器才会按冷却发送企微「心跳存储异常」告警(默认关闭)。 +心跳存储:test/prod 默认要求 **Redis**(`FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true`)。Redis 不可用时触发与排程会报 `RPA.HEARTBEAT_STORAGE_UNAVAILABLE`;仅当 `FREIGHT_RPA_WORKER_ALERT_ENABLED=true` 时,调度器才会按冷却发送企微「心跳存储异常」告警(默认关闭)。 先验证 DSV 登录: ```powershell -python scripts\rpa\connectors\dsv\dsv_login_smoke.py +python scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py ``` 成功时会看到: @@ -2208,7 +2208,7 @@ SUCCESS — DSV session ready 库存 RPA 必须由 HXOPS 管理端的 Inventory Source + RPA Profile 生成 trigger;如需人工联调,选取已生成的 trigger,执行: ```powershell -python scripts\rpa\inventory\run_inventory_batch_trigger.py +python scripts\freight_rpa\inventory\run_inventory_batch_trigger.py ``` 该入口不会读取 YAML 或本地账号密码,Profile 的密文凭据和页面操作均由平台生成的 trigger 提供。 @@ -2350,24 +2350,24 @@ SHIPPING_NOTICE_TOOL_API_KEY=请替换为强随机ASCII密钥 SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true -SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 +FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers -SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers -SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue +FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers +FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue -# Worker 心跳与共享 scope(与 Windows SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID 一致) -SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data -SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 -SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true +# Worker 心跳与共享 scope(与 Windows FREIGHT_RPA_SHARED_SCOPE_ID 一致) +FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data +FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 +FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true # 企微心跳告警默认关闭;需要时改为 true -SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false +FREIGHT_RPA_WORKER_ALERT_ENABLED=false # 逗号分隔已绑企微的 HXOPS 用户名;留空且 FALLBACK_ADMIN=true 时通知 admin -SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= -SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true -SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 +FREIGHT_RPA_WORKER_ALERT_USERNAMES= +FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true +FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 ``` 正式环境只把路径改为 `/mnt/hxops-rpa-prod-data/...`,并使用正式环境的 `SHIPPING_NOTICE_TOOL_API_KEY`。 @@ -2393,15 +2393,15 @@ volumes: 同一 Windows 用户通过两个独立计划任务同时运行 test/prod。每个任务调用 `start_rpa_worker.ps1`,只给对应 Worker 子进程注入环境变量;Secret 使用当前用户 DPAPI 文件保存,不写入用户级或机器级环境变量。 -库存导出默认复用浏览器 Profile:按 `connector_type + rpa_profile_code` 使用独立目录 `{connector}__{profile}_session`,长期保留(`SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`,默认开启)。本地不以 TTL 强制清空;站点侧会话失效时回落现有登录流程。上传任务保持一次性 Profile。同一 WorkerRoot 只运行一个库存 Worker(串行消费 trigger,浏览器并发上限为 1)。关闭复用可传启动参数 `-NoSessionReuse`;旧参数 `-ReuseDsvSession` 仍兼容。 +库存导出默认复用浏览器 Profile:按 `connector_type + rpa_profile_code` 使用独立目录 `{connector}__{profile}_session`,长期保留(`FREIGHT_RPA_WORKER_SESSION_REUSE`,默认开启)。本地不以 TTL 强制清空;站点侧会话失效时回落现有登录流程。上传任务保持一次性 Profile。同一 WorkerRoot 只运行一个库存 Worker(串行消费 trigger,浏览器并发上限为 1)。关闭复用可传启动参数 `-NoSessionReuse`(旧参数 `-ReuseDsvSession` 已于 2026-09-18 移除)。 -Worker 本机磁盘保留(`SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7 天;每小时一轮):清理 trigger `processed/failed`、drop 归档与隔离目录、过期 drop 根导出文件、upload_queue 残留、日志备份,以及超过 24h 的孤儿 `run_*` 临时 Profile;会话 Profile 与进行中的 trigger 根 JSON、`.cleanup_queue` 不删。运行中日志同时按 `LOG_MAX_BYTES` 轮转,避免常驻进程单文件无限增长。 +Worker 本机磁盘保留(`FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7 天;每小时一轮):清理 trigger `processed/failed`、drop 归档与隔离目录、过期 drop 根导出文件、upload_queue 残留、日志备份,以及超过 24h 的孤儿 `run_*` 临时 Profile;会话 Profile 与进行中的 trigger 根 JSON、`.cleanup_queue` 不删。运行中日志同时按 `LOG_MAX_BYTES` 轮转,避免常驻进程单文件无限增长。 Windows 如禁止运行 `.ps1`,仅对单次 Secret 创建使用临时 Bypass: ```powershell -powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1" -Environment test -powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1" -Environment prod +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaTest\scripts\freight_rpa\common\new_rpa_worker_secret.ps1" -Environment test +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\HxopsRpaProd\scripts\freight_rpa\common\new_rpa_worker_secret.ps1" -Environment prod ``` 若文件来自网络或压缩包并被标记为阻止,先执行 `Unblock-File`。也可用 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` 仅放行当前窗口。禁止永久设置 `Unrestricted` 或修改 `LocalMachine` 策略。 @@ -2412,13 +2412,13 @@ Windows PowerShell 5.1 读取无 BOM UTF-8 脚本时可能出现中文变乱和 ```powershell cd C:\HxopsRpaTest -.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test -.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment prod +.\scripts\freight_rpa\common\new_rpa_worker_secret.ps1 -Environment test +.\scripts\freight_rpa\common\new_rpa_worker_secret.ps1 -Environment prod ``` 默认 Secret 路径为 `C:\HxopsRpaSecrets\test.xml` 与 `prod.xml`。文件不得进入仓库、SMB 共享、日志或其他 Windows 用户目录。 -DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Profile 中配置。后端将加密凭据作为 trigger 的 `credential_envelope` 发送给 Worker,Worker 只用 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 解密,不从 Windows Secret 文件重新录入。 +DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Profile 中配置。后端将加密凭据作为 trigger 的 `credential_envelope` 发送给 Worker,Worker 只用 `FREIGHT_RPA_CREDENTIAL_KEY` 解密,不从 Windows Secret 文件重新录入。 手工启动 test: @@ -2426,7 +2426,7 @@ DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Prof ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` - "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" ` + "C:\HxopsRpaTest\scripts\freight_rpa\inventory\start_inventory_worker.ps1" ` -Environment test ` -ApiBase "http://:<端口>" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -2436,8 +2436,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` 若脚本来自网络或压缩包,先确认路径并按需解除文件阻止: ```powershell -Test-Path "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" -Unblock-File "C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1" +Test-Path "C:\HxopsRpaTest\scripts\freight_rpa\inventory\start_inventory_worker.ps1" +Unblock-File "C:\HxopsRpaTest\scripts\freight_rpa\inventory\start_inventory_worker.ps1" ``` `-ApiBase` 必须是 HXOPS 测试业务后端地址。`HXOPS_TOOLS_API_BASE`(例如 `:8890`)是 Tool API,不能填入 Worker 的 `-ApiBase`。如果使用 `http://192.168.100.192:5052`,必须先确认该地址确实是测试后端并可从 Windows Worker 访问: @@ -2452,7 +2452,7 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing 连通性确认后,也可以使用仓库原始命令: ```powershell -.\scripts\rpa\inventory\start_inventory_worker.ps1 ` +.\scripts\freight_rpa\inventory\start_inventory_worker.ps1 ` -Environment test ` -ApiBase "http://测试后端:端口" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -2462,18 +2462,18 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing 手工启动 prod: ```powershell -C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1 ` +C:\HxopsRpaProd\scripts\freight_rpa\inventory\start_inventory_worker.ps1 ` -Environment prod ` -ApiBase "http://正式后端:端口" ` -WorkerRoot "C:\HxopsRpaProd" ` -SecretFile "C:\HxopsRpaSecrets\prod.xml" ``` -后台任务必须使用 `AtLogOn + Interactive`,并分别绑定 test/prod 的 WorkerRoot、ApiBase 和 SecretFile。完整任务计划命令、重启策略和日常启停见 `scripts/rpa/README.md` 的“Windows RPA 主机后台常驻与任务计划(同一用户双环境)”。 +后台任务必须使用 `AtLogOn + Interactive`,并分别绑定 test/prod 的 WorkerRoot、ApiBase 和 SecretFile。完整任务计划命令、重启策略和日常启停见 `scripts/freight_rpa/README.md` 的“Windows RPA 主机后台常驻与任务计划(同一用户双环境)”。 #### 1.5.11 端到端验证 1. Windows 手工打开 Edge,确认能访问 DSV/Crane。 -2. Windows 执行 `python scripts\rpa\connectors\dsv\dsv_login_smoke.py`。 +2. Windows 执行 `python scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py`。 3. 在管理端创建一个库存 RPA trigger,确认其包含 Source、Profile 和密文凭据。 4. Ubuntu 执行 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test_from_ubuntu.txt`,Windows 确认 `C:\HxopsRpaTest\data\inventory_triggers` 能看到。 5. Windows 按当前方案执行 `start_rpa_worker.ps1`;不要直接运行 `freight_rpa_worker.py`。 @@ -2488,7 +2488,7 @@ C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1 ` #### 1.5.12 常见问题 - Ubuntu `smbclient` 能访问,但后端写失败:用 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test.txt` 测试后端服务用户权限,检查挂载参数中的 `uid/gid` 与 Windows 共享/NTFS 权限。 -- Windows worker 没反应:确认 worker 正在运行,测试环境 `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR` 指向 `C:\HxopsRpaTest\data\inventory_triggers`,正式环境指向 `C:\HxopsRpaProd\data\inventory_triggers`,且后端真的把 JSON 写到了对应共享目录。 +- Windows worker 没反应:确认 worker 正在运行,测试环境 `FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR` 指向 `C:\HxopsRpaTest\data\inventory_triggers`,正式环境指向 `C:\HxopsRpaProd\data\inventory_triggers`,且后端真的把 JSON 写到了对应共享目录。 - worker 回调失败:确认 Windows 能访问 `HXOPS_API_BASE`,`SHIPPING_NOTICE_TOOL_API_KEY` 与后端一致,Ubuntu 防火墙允许 Windows 访问 HXOPS 端口。 - DSV/Crane 登录失败:先用 Windows Edge 手工登录,再跑 `dsv_login_smoke.py`;重点检查 MFA/验证码/SSO、企业代理、证书、账号密码。 - Ubuntu 重启后目录空了:执行 `sudo mount -a`,检查 `/etc/fstab`、网络是否已就绪、Windows 共享是否可访问。 @@ -2500,7 +2500,7 @@ C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1 ` | 运行位置 | 适用目的 | 后端目录/环境 | Worker 目录与环境 | 禁止混用 | | --- | --- | --- | --- | --- | -| Windows 本地 | 开发机联调、测试导出 | 当前项目 `backend/data/shipping_notice/freight_rpa/*`;本地后端 | 当前项目 `scripts/rpa/`;`dev` | 不连接 test/prod 共享目录,不使用 test/prod Key 或凭据 | +| Windows 本地 | 开发机联调、测试导出 | 当前项目 `backend/data/shipping_notice/freight_rpa/*`;本地后端 | 当前项目 `scripts/freight_rpa/`;`dev` | 不连接 test/prod 共享目录,不使用 test/prod Key 或凭据 | | Linux 测试服务器 | 测试环境库存导出 | `/mnt/hxops-rpa-test-data/*`;`.env.test` | Windows `C:\HxopsRpaTest`;`test` | 不得使用 `prod` scope、目录、API Base 或 Key | | Linux 正式服务器 | 已验收的正式库存导出 | `/mnt/hxops-rpa-prod-data/*`;`.env.prod` | Windows `C:\HxopsRpaProd`;`prod` | 不得使用 `test` scope、目录、API Base 或 Key | @@ -2518,7 +2518,7 @@ python -m pip install playwright python -m playwright install chromium ``` -在同一个 PowerShell 窗口中设置本地目录。`SHIPPING_NOTICE_TOOL_API_KEY` 和 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 请从本机受控 Secret 来源注入;真实库存导出需要后者解密平台下发的 RPA Profile 凭据。若只是验证 Worker 扫描、回调与文件流转,可把 `SHIPPING_NOTICE_RPA_WORKER_MOCK` 临时设为 `true`。 +在同一个 PowerShell 窗口中设置本地目录。`SHIPPING_NOTICE_TOOL_API_KEY` 和 `FREIGHT_RPA_CREDENTIAL_KEY` 请从本机受控 Secret 来源注入;真实库存导出需要后者解密平台下发的 RPA Profile 凭据。若只是验证 Worker 扫描、回调与文件流转,可把 `FREIGHT_RPA_WORKER_MOCK` 临时设为 `true`。 ```powershell $repoRoot = (Get-Location).Path @@ -2527,21 +2527,21 @@ $rpaDataRoot = Join-Path $repoRoot "backend\data\shipping_notice\freight_rpa" $env:HXOPS_API_BASE = "http://127.0.0.1:5052" # 由受控 Secret 渠道注入;禁止在此处粘贴真实值。 $env:SHIPPING_NOTICE_TOOL_API_KEY = "<本地 Tool API Key>" -$env:SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = "<本地 RPA 凭据主密钥>" +$env:FREIGHT_RPA_CREDENTIAL_KEY = "<本地 RPA 凭据主密钥>" -$env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "dev" -$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" -$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" +$env:FREIGHT_RPA_WORKER_ENVIRONMENT = "dev" +$env:FREIGHT_RPA_WORKER_MOCK = "false" +$env:FREIGHT_RPA_WORKER_HEADLESS = "false" # 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。 -$env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" -$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers" -$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory_drop" -$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaDataRoot "upload_triggers" -$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "upload_queue" -$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile" -$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log" +$env:FREIGHT_RPA_WORKER_POLL_SECONDS = "3" +$env:FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers" +$env:FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory_drop" +$env:FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaDataRoot "upload_triggers" +$env:FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "upload_queue" +$env:FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile" +$env:FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log" -\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" +\.\scripts\freight_rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase ":<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` 启动成功后,控制台会输出 `[freight_rpa_worker] started`,并持续轮询 trigger。另开一个 PowerShell 可检查日志和哨兵;本地未配置 shared scope 时不要求哨兵包含 test/prod scope: @@ -2580,7 +2580,7 @@ docker compose --env-file .env.test exec -T hxops-shipping-worker \ sh -lc 'mountpoint -q /mnt/hxops-rpa-test-data && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers' ``` -随后在 Windows RPA 主机按 `1.5.5` 的 test 参数启动 Worker(`C:\HxopsRpaTest`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=test`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data`)。确认 Windows 和 Linux 均能看到 `.hxops_rpa_shared_mount`,并在管理端的 RPA Worker 状态页确认 test Worker 在线后,再发起库存站点测试导出。 +随后在 Windows RPA 主机按 `1.5.5` 的 test 参数启动 Worker(`C:\HxopsRpaTest`、`FREIGHT_RPA_WORKER_ENVIRONMENT=test`、`FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data`)。确认 Windows 和 Linux 均能看到 `.hxops_rpa_shared_mount`,并在管理端的 RPA Worker 状态页确认 test Worker 在线后,再发起库存站点测试导出。 需要停止测试环境的 RPA 服务时,先停止/取消新的测试导出,再在 Windows Worker 前台窗口按 `Ctrl+C`(或停止其既有计划任务),最后执行: @@ -2618,7 +2618,7 @@ docker compose --env-file .env.prod exec -T hxops-shipping-worker \ sh -lc 'mountpoint -q /mnt/hxops-rpa-prod-data && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers' ``` -再在 Windows RPA 主机启动正式 Worker:`C:\HxopsRpaProd`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=prod`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data`。必须先验证哨兵内容、管理端 Worker 在线状态以及一笔受控正式导出,才允许启用正式排程。真实上传由配置驱动的 Playwright 流程执行:DSV 已确认从 Portal 首页 `My Applications > Upload Tool`(回退 `Apps > Upload Tool`)进入 `WMS Upload Tool > Upload`,由 `SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` 指定受控 Portal 入口;`Browse` 的真实文件 input 是 `#file2`,选择文件后的真实提交控件为 `button.upload-button:has-text("Process File")`,DSV 默认使用这两个 selector。成功证据来自 `History`:同名文件行必须同时具有绿色 `em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #`;该参考仅作为受信 RPA 成功回调的外部参考,不要求人工录入或上传回执。其他站点使用受控上传 URL;必须设置文件/提交/成功 selector,并保持 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false`、`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false`,直到测试环境完成非生产 dry-run 且确认成功标识语义。缺少配置、浏览器异常或未出现成功标识均回调失败,绝不把文件已选择视为上传成功。CRANE 上传页尚未确认,Worker 必须失败而不得复用 DSV 路径。由于尚未获得货代真实提交测试授权,生产仍须保持 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`,以人工按业务单号确认已上传作为受控降级路径。 +再在 Windows RPA 主机启动正式 Worker:`C:\HxopsRpaProd`、`FREIGHT_RPA_WORKER_ENVIRONMENT=prod`、`FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data`。必须先验证哨兵内容、管理端 Worker 在线状态以及一笔受控正式导出,才允许启用正式排程。真实上传由配置驱动的 Playwright 流程执行:DSV 已确认从 Portal 首页 `My Applications > Upload Tool`(回退 `Apps > Upload Tool`)进入 `WMS Upload Tool > Upload`,由 `FREIGHT_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` 指定受控 Portal 入口;`Browse` 的真实文件 input 是 `#file2`,选择文件后的真实提交控件为 `button.upload-button:has-text("Process File")`,DSV 默认使用这两个 selector。成功证据来自 `History`:同名文件行必须同时具有绿色 `em.fa.fa-circle.success-color.status-icon` 和非空 `Reference #`;该参考仅作为受信 RPA 成功回调的外部参考,不要求人工录入或上传回执。其他站点使用受控上传 URL;必须设置文件/提交/成功 selector,并保持 `FREIGHT_RPA_WORKER_UPLOAD_ENABLED=false`、`FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false`,直到测试环境完成非生产 dry-run 且确认成功标识语义。缺少配置、浏览器异常或未出现成功标识均回调失败,绝不把文件已选择视为上传成功。CRANE 上传页尚未确认,Worker 必须失败而不得复用 DSV 路径。由于尚未获得货代真实提交测试授权,生产仍须保持 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`,以人工按业务单号确认已上传作为受控降级路径。 计划维护或紧急停止时,先暂停正式库存 RPA 排程并等待/处理运行中的 trigger,再停止 Windows prod Worker,最后按需停止容器: @@ -2954,7 +2954,7 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui > 本节是收料报表 RPA(独立 Windows Worker)的部署手册,章节结构与 `1.5` 库存导出 RPA 对应。安全提示与 `1.5` 相同:示例中的 IP、账号、密码、API Key 均为占位符,请在各环境本地替换为实际值,**禁止将真实密码/密钥写入仓库或提交到 Git**。 > 前置条件:已按 `1.5.2` 至 `1.5.10` 完成同一台 Windows RPA 主机、`hxops-rpa-test-data` / `hxops-rpa-prod-data` SMB 共享、Ubuntu 挂载与后端容器挂载。收料**不新建共享、不新建挂载**,只在既有共享下增加专用子目录、独立 Worker 与独立回调。 -> Worker 脚本层速查另见 [scripts/rpa/README.md](../../../scripts/rpa/README.md) 顶部「收料 RPA(独立 Worker)」;本节是部署权威来源。 +> Worker 脚本层速查另见 [scripts/freight_rpa/README.md](../../../scripts/freight_rpa/README.md) 顶部「收料 RPA(独立 Worker)」;本节是部署权威来源。 #### 1.9.1 与库存 RPA 的边界和目录规划 @@ -2968,25 +2968,25 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui | 项 | 库存 RPA | 收料 RPA | | --- | --- | --- | -| Worker | `scripts\rpa\inventory\inventory_rpa_worker.py` | `scripts\rpa\receipt\receipt_rpa_worker.py` | +| Worker | `scripts\freight_rpa\inventory\inventory_rpa_worker.py` | `scripts\freight_rpa\receipt\receipt_rpa_worker.py` | | 启动脚本 | `inventory\start_inventory_worker.ps1` | `receipt\start_receipt_worker.ps1` | -| trigger 目录 | `data\inventory_triggers` | `data\freight_receipt_rpa\receipt_triggers` | -| drop 目录 | `data\inventory_drop` | `data\freight_receipt_rpa\receipt_drop` | +| trigger 目录 | `freight_rpa\inventory\triggers` | `freight_rpa\receipt\triggers` | +| drop 目录 | `freight_rpa\inventory\drop` | `freight_rpa\receipt\drop` | | 回调端点 | `/api/shipping-notice/rpa/inventory-batch-ready` | `/api/shipping-notice/rpa/receipt-batch-ready` | -| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | 心跳已接:以 `<主机名>-receipt` 独立身份周期上报(ps1 注入 `SHIPPING_NOTICE_RPA_WORKER_ID`);仍不写 `.hxops_rpa_shared_mount` 哨兵,触发前无 fail-fast 在线检查 | +| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | 心跳已接:以 `<主机名>-receipt` 独立身份周期上报(ps1 注入 `FREIGHT_RPA_WORKER_ID`);仍不写 `.hxops_rpa_shared_mount` 哨兵,触发前无 fail-fast 在线检查 | | 结果归属 | 库存快照/库存匹配 | MinIO 原样归档 + 企微投递,绝不进入库存链路 | 路径对应关系(测试环境;正式环境把 `Test` / `test-data` 换成 `Prod` / `prod-data`): ```text -Windows RPA:C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_triggers -Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers +Windows RPA:C:\HxopsRpaTest\freight_rpa\receipt\triggers +Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers -Windows RPA:C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_drop -Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop +Windows RPA:C:\HxopsRpaTest\freight_rpa\receipt\drop +Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop ``` -浏览器 Profile:收料 Worker 在 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`(收料启动脚本默认指向 `\data\shipping_notice\freight_rpa\browser_profile`)下,为每个 `connector + profile + login_url` 分组创建 `receipt_*` 临时目录,组处理完立即删除;不保留跨排程登录会话。与库存 Worker 的 `run_*` 一次性 Profile、`{connector}__{profile}_session` 长期会话目录互不影响。 +浏览器 Profile:收料 Worker 在 `FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR`(收料启动脚本默认指向 `\freight_rpa\common\browser_profile`)下,为每个 `connector + profile + login_url` 分组创建 `receipt_*` 临时目录,组处理完立即删除;不保留跨排程登录会话。与库存 Worker 的 `run_*` 一次性 Profile、`{connector}__{profile}_session` 长期会话目录互不影响。 #### 1.9.2 Windows RPA 主机:部署收料 Worker @@ -2994,13 +2994,13 @@ Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop ```powershell foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { - New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\receipt_triggers" - New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\receipt_drop" - New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\logs" + New-Item -ItemType Directory -Force "$root\freight_rpa\receipt\triggers" + New-Item -ItemType Directory -Force "$root\freight_rpa\receipt\drop" + New-Item -ItemType Directory -Force "$root\freight_rpa\receipt\logs" } ``` -`receipt_rpa_worker.py` 启动时按「所在目录必须同时存在 `connectors/`、`common/`、`inventory/`、`receipt/` 子目录」定位 RPA 根目录,因此必须复制**整个** `scripts\rpa`(首次部署 `1.5.2` 已覆盖;升级时同样整目录同步,保持 Worker、driver 与公共模块同一版本),不能只复制 `receipt\` 子目录。 +`receipt_rpa_worker.py` 启动时按「所在目录必须同时存在 `connectors/`、`common/`、`inventory/`、`receipt/` 子目录」定位 RPA 根目录,因此必须复制**整个** `scripts\freight_rpa`(首次部署 `1.5.2` 已覆盖;升级时同样整目录同步,保持 Worker、driver 与公共模块同一版本),不能只复制 `receipt\` 子目录。 依赖与 `1.5.4` 相同,另需 `cryptography`(解密 RPA Profile 加密凭据;库存 Worker 同样依赖,新增部署时两个 Worker 一起补齐): @@ -3014,7 +3014,7 @@ Secret 复用 `1.5.10` 创建的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`。 ```powershell powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` - "C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1" ` + "C:\HxopsRpaTest\scripts\freight_rpa\receipt\start_receipt_worker.ps1" ` -Environment test ` -ApiBase "http://:<端口>" ` -WorkerRoot "C:\HxopsRpaTest" ` @@ -3023,15 +3023,17 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` 启动成功会输出 `[freight_receipt_rpa_worker] started` 独立行,后跟缩进字段块(` mock=...`、` api_base=...`、` trigger_dir=...`、` drop_dir=...`、` log=...` 等,完整字段以 `receipt_rpa_worker.py` 启动 banner 为准),随后轮询 `receipt_triggers` 下完整的 `.json` 触发文件。执行策略拦截、`Unblock-File`、UTF-8 BOM 要求均与 `1.5.10` 相同(`start_receipt_worker.ps1` 同样必须保持 UTF-8 BOM,从仓库原样复制)。 -启动脚本同时自动注入两个 Worker 运行变量:`SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`(ps1 自动设为 `data\freight_receipt_rpa\logs\worker.log`,文件日志带时间戳并按大小轮转,无需手工配置)与 `SHIPPING_NOTICE_RPA_WORKER_ID=<主机名>-receipt`(独立心跳身份,监控端按此身份出独立收料卡片,不与库存 Worker 的 `<主机名>-` 混淆)。收料 Worker 的文件日志、启动 banner、心跳上报与周期磁盘保留清理(含共享 Profile 的孤儿 `receipt_*`)能力均已与库存 Worker 对齐;两个 Worker 禁止共写同一日志文件,各自由启动脚本指向各自根目录下的 `logs\worker.log`。 +启动脚本同时自动注入两个 Worker 运行变量:`FREIGHT_RPA_WORKER_LOG_FILE`(ps1 自动设为 `freight_rpa\receipt\logs\worker.log`,文件日志带时间戳并按大小轮转,无需手工配置)与 `FREIGHT_RPA_WORKER_ID=<主机名>-receipt`(独立心跳身份,监控端按此身份出独立收料卡片,不与库存 Worker 的 `<主机名>-inventory` 混淆;两个身份均由各自 ps1 注入 `FREIGHT_RPA_WORKER_ID`,重启不漂移)。收料 Worker 的文件日志、启动 banner、心跳上报与周期磁盘保留清理(含共享 Profile 的孤儿 `receipt_*`)能力均已与库存 Worker 对齐;两个 Worker 禁止共写同一日志文件,各自由启动脚本指向各自域目录(库存 `inventory\logs`、收料 `receipt\logs`)下的 `worker.log`。 -后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,仅把动作换成收料启动脚本。收料 Worker 由启动脚本注入 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`,文件日志写入 `data\freight_receipt_rpa\logs\worker.log`(tee 控制台、带时间戳、按大小轮转);计划任务仍可用 `cmd.exe` 包装对控制台输出做重定向留档: +后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,注册脚本已交付:`scripts reight_rpa +eceipt +egister_receipt_worker_tasks.ps1`(test/prod 双任务,任务名 `HXOPS Receipt RPA Worker TEST/PROD`,与库存注册脚本同构、相互独立)。收料 Worker 由启动脚本注入 `FREIGHT_RPA_WORKER_LOG_FILE`,文件日志写入 `freight_rpa\receipt\logs\worker.log`(tee 控制台、带时间戳、按大小轮转);计划任务仍可用 `cmd.exe` 包装对控制台输出做重定向留档: ```powershell $TestApiBase = "http://:<端口>" $ReceiptAction = New-ScheduledTaskAction ` -Execute "cmd.exe" ` - -Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\data\freight_receipt_rpa\logs\receipt_console_output.log"" 2>&1" ` + -Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\freight_rpa\receipt\start_receipt_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\freight_rpa\receipt\logs\receipt_console_output.log"" 2>&1" ` -WorkingDirectory "C:\HxopsRpaTest" # $Trigger / $Principal / $Settings 与 1.5.10 的库存任务完全一致: # AtLogOn + Interactive;RestartCount 10、RestartInterval 1 分钟、ExecutionTimeLimit 0、MultipleInstances IgnoreNew。 @@ -3045,14 +3047,14 @@ Register-ScheduledTask -TaskName "HXOPS Receipt RPA Worker TEST" -Action $Receip `.env.test` 在 `1.5.9` 基础上追加(正式环境把路径换成 `/mnt/hxops-rpa-prod-data/...`): ```env -# 收料 RPA 共享目录(与 Windows Worker 的 data\freight_receipt_rpa 属同一 SMB 共享的子路径) -SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers -SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop +# 收料 RPA 共享目录(与 Windows Worker 的 freight_rpa\receipt 属同一 SMB 共享的子路径) +FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers +FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop # 收料排程等待回调超时(秒);超时回收为 RPA.RECEIPT_CALLBACK_TIMEOUT,不自动重试 -SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900 +FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=900 ``` -> ⚠️ **最容易漏的一步**:不配置这两个目录变量时,后端默认写容器本地 `backend/data/shipping_notice/freight_receipt_rpa/*`,Windows 共享盘永远看不到 trigger,单元会一直等到超时回收。 +> ⚠️ **最容易漏的一步**:不配置这两个目录变量时,后端默认写容器本地 `backend/data/freight_rpa/receipt/*`,Windows 共享盘永远看不到 trigger,单元会一直等到超时回收。 容器 bind mount **无需新增**:收料目录位于既有 `/mnt/hxops-rpa-*data` 共享的子路径下,`hxops-backend`、`hxops-schedule-worker` 按 `1.5.9` 挂载后即已覆盖;修改 `.env` 后按惯例重建相关容器。 @@ -3062,14 +3064,14 @@ SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900 - 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。 - 企微逐文件推送与汇总发给排程任务配置的接收人(`notify_user_ids` + `notify_enabled`),接收人必须已完成企微绑定,否则投递记 `WECOM_USER_UNBOUND` 失败。 -排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `data\freight_receipt_rpa\logs\worker.log` 巡检。 +排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `freight_rpa\receipt\logs\worker.log` 巡检。 #### 1.9.4 端到端验证 1. 管理端「货代管理 → 库存站点」抽屉为目标站点配置收料卡(与库存同构):DBS 必须在查询条件中维护 Warehouse 条件(支持多值,每个 Warehouse 展开一个单元);报表日期不得出现在查询条件中。Crane 固定 `Inbound Details`,拒绝查询条件。收料无独立开关,站点启用即参与收料排程。 2. 链路演练(不依赖真实货代网站):以 `-Mock` 启动收料 Worker → 排程管理手工执行一次「货代收料 RPA」→ 确认回调、MinIO 归档、企微投递全链路成功后停止 Mock Worker。 3. 真实链路:启动真实收料 Worker 并触发排程,依次确认: - - `ls /mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers` 出现 `receipt_export_batch_{run_no}.json`; + - `ls /mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers` 出现 `receipt_export_batch_{run_no}.json`; - Worker 领取后文件进入同目录 `processing/`,全部单元处理完进入 `processed/`(契约级失败进 `failed/`); - `receipt_drop` 出现 `receipt_{callback_id}_{时间戳}.xlsx`; - 回调 `/api/shipping-notice/rpa/receipt-batch-ready` 成功,单元 `success`,MinIO 出现归档对象; @@ -3079,25 +3081,25 @@ SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900 #### 1.9.5 常见问题 -- trigger 长时间无人消费:收料 Worker 未启动;两端 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` 不一致;或后端未配置变量、写到了容器本地默认路径(见 `1.9.3` 的告警)。 +- trigger 长时间无人消费:收料 Worker 未启动;两端 `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` 不一致;或后端未配置变量、写到了容器本地默认路径(见 `1.9.3` 的告警)。 - 回调 401/403:Worker `X-Integration-Key` 与该环境 `SHIPPING_NOTICE_TOOL_API_KEY` 不一致,或 `-ApiBase` 未按 `1.5.10` 的网关口径填写。 - 回调报 `SHIPPING.RECEIPT_CALLBACK_FILE_INVALID`:`file_path` 不在收料 drop 根内、非 `.xlsx`、空文件或超过 `FILE_ASSET_MAX_SIZE_MB`;多为收料/库存目录串用所致。 -- 单元长期 `awaiting_rpa`、排程停在 `awaiting_receipt_rpa_callback`:Worker 停止或崩溃;超过 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 由回收逻辑置 `RPA.RECEIPT_CALLBACK_TIMEOUT`,**不自动重试**,需管理员带原因重试或等下一轮 Cron。 -- DBS/Crane 登录或导出失败:先在 Windows 手工登录确认 MFA/SSO/代理;Crane 无论 Profile 首页保存为何,Worker 均强制进入 `#/inbound-details-query` 用页面默认条件执行;确认 Profile 已启用且 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 两端一致(否则无法解密凭据)。 +- 单元长期 `awaiting_rpa`、排程停在 `awaiting_receipt_rpa_callback`:Worker 停止或崩溃;超过 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS` 由回收逻辑置 `RPA.RECEIPT_CALLBACK_TIMEOUT`,**不自动重试**,需管理员带原因重试或等下一轮 Cron。 +- DBS/Crane 登录或导出失败:先在 Windows 手工登录确认 MFA/SSO/代理;Crane 无论 Profile 首页保存为何,Worker 均强制进入 `#/inbound-details-query` 用页面默认条件执行;确认 Profile 已启用且 `FREIGHT_RPA_CREDENTIAL_KEY` 两端一致(否则无法解密凭据)。 - `receipt_drop` 磁盘占用增长:收料 Worker 已启用周期磁盘保留清理(启动 + 周期各一轮,清收料 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`receipt_*`);如需更早释放仍可人工清理,建议保留最近几天便于排障。 -- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `data\freight_receipt_rpa\logs\worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。 +- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `freight_rpa\receipt\logs\worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。 #### 1.9.6 收料 RPA 三环境速查 | 运行位置 | 后端目录/环境 | Worker 目录与环境 | 说明 | | --- | --- | --- | --- | -| Windows 本地联调 | 本地后端;默认 `backend/data/shipping_notice/freight_receipt_rpa/*` | 当前项目 `scripts/rpa/receipt/`;`dev` | 不连 test/prod、不用 test/prod Key;`-Mock` 可全链路演练 | -| Linux 测试服务器 | `/mnt/hxops-rpa-test-data/freight_receipt_rpa/*`;`.env.test` | `C:\HxopsRpaTest\data\freight_receipt_rpa`;`test` | 与库存测试共用同一 SMB 共享与挂载 | -| Linux 正式服务器 | `/mnt/hxops-rpa-prod-data/freight_receipt_rpa/*`;`.env.prod` | `C:\HxopsRpaProd\data\freight_receipt_rpa`;`prod` | 测试真实链路验收通过后再开启正式排程 | -| `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` | dev `data/shipping_notice/freight_receipt_rpa/receipt_triggers`;test `/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers`;prod `/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_triggers` | 与后端同一物理目录(test `C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_triggers`;prod `C:\HxopsRpaProd\data\freight_receipt_rpa\receipt_triggers`) | 本地联调两端默认一致,无需配置 | -| `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR` | dev `data/shipping_notice/freight_receipt_rpa/receipt_drop`;test `/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop`;prod `/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_drop` | 与后端同一物理目录(test `C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_drop`;prod `C:\HxopsRpaProd\data\freight_receipt_rpa\receipt_drop`) | 本地联调两端默认一致,无需配置 | +| Windows 本地联调 | 本地后端;默认 `backend/data/freight_rpa/receipt/*` | 当前项目 `scripts/freight_rpa/receipt/`;`dev` | 不连 test/prod、不用 test/prod Key;`-Mock` 可全链路演练 | +| Linux 测试服务器 | `/mnt/hxops-rpa-test-data/freight_rpa/receipt/*`;`.env.test` | `C:\HxopsRpaTest\freight_rpa\receipt`;`test` | 与库存测试共用同一 SMB 共享与挂载 | +| Linux 正式服务器 | `/mnt/hxops-rpa-prod-data/freight_rpa/receipt/*`;`.env.prod` | `C:\HxopsRpaProd\freight_rpa\receipt`;`prod` | 测试真实链路验收通过后再开启正式排程 | +| `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` | dev `data/freight_rpa/receipt/triggers`;test `/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers`;prod `/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers` | 与后端同一物理目录(test `C:\HxopsRpaTest\freight_rpa\receipt\triggers`;prod `C:\HxopsRpaProd\freight_rpa\receipt\triggers`) | 本地联调两端默认一致,无需配置 | +| `FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR` | dev `data/freight_rpa/receipt/drop`;test `/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop`;prod `/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop` | 与后端同一物理目录(test `C:\HxopsRpaTest\freight_rpa\receipt\drop`;prod `C:\HxopsRpaProd\freight_rpa\receipt\drop`) | 本地联调两端默认一致,无需配置 | -收料 trigger/drop 目录必须与 Windows 收料 Worker 上 `start_receipt_worker.ps1` 读取的同名变量指向**同一物理目录**;目录内子结构(processing/processed/failed)由统一契约管理,见 `scripts/rpa/README.md`。 +收料 trigger/drop 目录必须与 Windows 收料 Worker 上 `start_receipt_worker.ps1` 读取的同名变量指向**同一物理目录**;目录内子结构(processing/processed/failed)由统一契约管理,见 `scripts/freight_rpa/README.md`。 Windows 本地联调(项目根目录 PowerShell;本地后端默认目录与 Worker 指向一致,无需配置目录变量): @@ -3107,14 +3109,14 @@ Windows 本地联调(项目根目录 PowerShell;本地后端默认目录与 # 走完整 trigger 消费 → 回调 → 归档 → 企微链路)。 $env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:SHIPPING_NOTICE_TOOL_API_KEY = "<与本地后端一致>" -$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true" -$receiptRoot = Join-Path (Get-Location).Path "backend\data\shipping_notice\freight_receipt_rpa" -$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $receiptRoot "receipt_triggers" -$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $receiptRoot "receipt_drop" -python scripts/rpa/receipt/receipt_rpa_worker.py +$env:FREIGHT_RPA_WORKER_MOCK = "true" +$receiptRoot = Join-Path (Get-Location).Path "backend\data\freight_rpa" +$env:FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $receiptRoot "receipt\triggers" +$env:FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $receiptRoot "receipt\drop" +python scripts/freight_rpa/receipt/receipt_rpa_worker.py ``` -真实本地导出(`MOCK=false`)还需受控注入 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 并设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`;排程下发的真实 trigger 均含加密凭据,Mock 消费真实 trigger 时同样需要该密钥。也可改用启动脚本 `.\scripts\rpa\receipt\start_receipt_worker.ps1 -Environment test -ApiBase "http://127.0.0.1:5052" ...`(需先按 `1.5.10` 生成本地 Secret 文件)。 +真实本地导出(`MOCK=false`)还需受控注入 `FREIGHT_RPA_CREDENTIAL_KEY` 并设置 `FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR`;排程下发的真实 trigger 均含加密凭据,Mock 消费真实 trigger 时同样需要该密钥。也可改用启动脚本 `.\scripts\freight_rpa\receipt\start_receipt_worker.ps1 -Environment test -ApiBase "http://127.0.0.1:5052" ...`(需先按 `1.5.10` 生成本地 Secret 文件)。 *** @@ -3416,7 +3418,7 @@ API 层 | `backend/tests/test_shipping_inventory_routing_engine.py` | 通用路由规则引擎单测 | | `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 | | `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 | -| `scripts/rpa/inventory/inventory_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | +| `scripts/freight_rpa/inventory/inventory_rpa_worker.py` | 开发态 RPA worker(支持单条/批量 inventory_export) | --- @@ -3454,7 +3456,7 @@ API 层 - **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充 - **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值) - **报表控件模板**(2026-08-26):同一参数名在不同报表的 SSRS 控件长相不同(`On Hand Inventory By Location 3lv` 的 Warehouse 是原生 select `ddValue`,JDA 版 `On Hand Inventory by Location` 是 txtValue/toggle/divDropDown 多选框下拉)。控件差异由 Worker 按归一化报表名登记在 `dsv_report_parameters._DSV_REPORT_PARAM_TEMPLATES`,填参时把 `report_name` 透传到模块解析;`selector_env/selectors` 继续不进入数据库,未登记报表回退参数名默认值。填参失败会输出参数区控件探针日志(`[dsv-filter] ... control probe`),便于定位控件 ID/类型漂移。 -- Worker:`scripts/rpa/inventory/inventory_rpa_worker.py` → `_handle_inventory_batch_trigger` +- Worker:`scripts/freight_rpa/inventory/inventory_rpa_worker.py` → `_handle_inventory_batch_trigger` - **DOM 假空兜底**(2026-09-09):`result_ready` 后 DOM 明细行探测仅作加速;无行时重试一次 View Report,仍无行则继续 Excel 导出。真空只在落盘 Excel「有 Supplier ID/AWS Sku 表头但无明细」时记 `NoInventoryDataError`/`no_inventory_data`,避免 Salt Lake 等慢报表假 skip。 - 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready` - **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts//`、创建 `shipping_inventory_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。 @@ -3739,7 +3741,7 @@ DBS 每个 Warehouse 单独导出且不填报表日期。**Warehouse 即逐仓 ### 可靠性、补偿与审计边界 - trigger 采用“同目录临时文件写完、`fsync` 后 `os.replace` 原子发布”方式;收料 Worker 只能 claim 完整的 `.json`,不得读取半写入 trigger。 -- `awaiting_receipt_rpa` 运行受 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 `900`,可由部署配置覆盖)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。 +- `awaiting_receipt_rpa` 运行受 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 `900`,可由部署配置覆盖)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。 - Worker 启动及常规扫描均回收超时运行,避免服务或 Worker 重启后运行永久占用排程状态。 - 空结果、Worker 失败、归档成功、对象删除失败、企微文件/汇总投递成功或失败、管理员查看失败单元、人工重试和重发均写追加式 `ShippingAuditEvent`。审计包含操作人/时间/对象、结果、脱敏原因或错误码、变更前后状态;不得写入密码、Cookie、令牌、对象存储定位或浏览器会话。 - 管理员失败单元查询仅返回运行诊断所需的站点、Warehouse、状态、错误码/脱敏错误和时间;接收人不拥有该查询、配置、重试或重发权限。 diff --git a/docs/superpowers/plans/2026-09-18-freight-rpa-namespace-and-layout.md b/docs/superpowers/plans/2026-09-18-freight-rpa-namespace-and-layout.md new file mode 100644 index 00000000..a61f6011 --- /dev/null +++ b/docs/superpowers/plans/2026-09-18-freight-rpa-namespace-and-layout.md @@ -0,0 +1,319 @@ +# FREIGHT_RPA 命名空间恢复 + rpa 统一目录布局 实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** ① 环境变量命名空间从 `SHIPPING_NOTICE_RPA_*` 一刀切恢复为 `FREIGHT_RPA_*`(删除全部兼容/弃用告警机制);② 运行期数据目录统一为独立的 `freight_rpa/{inventory, receipt, common}` 三层布局(dev 后端默认、test/prod 挂载、Worker ps1 三侧一致)。 + +**Architecture:** 命名迁移是**纯机械前缀替换**(`SHIPPING_NOTICE_RPA_` → `FREIGHT_RPA_`,全部 ~130 个键一致适用,无逐键判断);布局变更是**纯值替换**(键名不变的部分)+ 少量新增行。替换范围按目录白名单圈定,历史计划文档(`docs/superpowers/plans/2026-09-17-*`、`2026-09-18-receipt-worker-parity-hardening.md`)作为历史记录**不改**。 + +**Tech Stack:** bash/grep/sed 机械替换 + pytest 回归;无新依赖、无数据库/迁移、无前端改动。 + +**Spec:** 用户 2026-09-18 三决策——①日志各域自带 `logs/`;②`common/browser_profile` 共享根;③`FREIGHT_RPA_*` 恢复原名、取消兼容层。 + +## Global Constraints + +- 🔴 **本次是一次经用户批准的红线修订**:AGENTS.md §8.1 原文「货代发货通知 RPA 统一使用 SHIPPING_NOTICE_RPA_*…禁止新增 FREIGHT_RPA_*」必须先行改写为新规则(Task 1),后续任务才实施替换。除该节外 AGENTS.md 其余内容不动。 +- 环境变量名映射规则(唯一规则,全量适用):`SHIPPING_NOTICE_RPA_` → `FREIGHT_RPA_`(保留 `SHARED_`/`WORKER_` 等二级前缀;原历史名 `FREIGHT_INVENTORY_DROP_DIR` 这类缺 RPA 的旧名**不恢复**,随兼容层一起删除)。 +- `SHIPPING_NOTICE_TOOL_API_KEY`、`INTEGRATION_API_KEY` 不在 `SHIPPING_NOTICE_RPA_` 前缀内,**不改**。 +- 新目录布局值(Task 4 唯一依据,`` 见下): + - `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` = `/inventory/triggers` + - `FREIGHT_RPA_INVENTORY_DROP_DIR` = `/inventory/drop` + - `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` = `/inventory/upload_triggers` + - `FREIGHT_RPA_UPLOAD_QUEUE_DIR` = `/inventory/upload_queue` + - `FREIGHT_RPA_INVENTORY_ARCHIVE_DIR` = `/inventory/archives` + - `FREIGHT_RPA_RECEIPT_TRIGGER_DIR` = `/receipt/triggers` + - `FREIGHT_RPA_RECEIPT_DROP_DIR` = `/receipt/drop` + - `FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR` = `/common/browser_profile`(键名保留 `WORKER_` 二级前缀——它由各 Worker 的 ps1 注入;**值**为共享根,即"同名变量、共享取值") + - Worker 日志(ps1 注入)= `/inventory/logs/worker.log` / `/receipt/logs/worker.log` + - ``:dev 后端默认 = `backend/data/rpa`;test = `/mnt/hxops-rpa-test-data/rpa`;prod = `/mnt/hxops-rpa-prod-data/rpa`;Worker ps1 = `\rpa` +- 完成判据(硬校验):替换范围内 `grep -r "SHIPPING_NOTICE_RPA_"` 命中为 0(白名单见 Task 6);全量相关 pytest 仅已知既有基线失败。 +- Conventional Commits:`(): <中文祈使句>`;本次多为 `refactor(rpa)` / `chore(rpa)` / `docs(rpa)`。 +- 工作树含用户并行在途改动:提交只 `git add` 各任务明确列出的文件。 + +--- + +### Task 1: AGENTS.md §8.1 规则先行改写(治理前置) + +**Files:** +- Modify: `AGENTS.md`(§8.1「RPA 命名空间(强制)」一条 + §8.1 内涉及该命名空间的句子) + +**Interfaces:** +- Produces: 新规则文本,作为后续所有替换任务的授权依据。 + +- [ ] **Step 1: 改写规则** + +将 §8.1 中原条目: + +> **RPA 命名空间(强制)**:货代发货通知 RPA 统一使用 `SHIPPING_NOTICE_RPA_*`。后端业务参数使用 `SHIPPING_NOTICE_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `SHIPPING_NOTICE_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,平台凭据主密钥使用 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`;历史名称只能存在于兼容映射和迁移说明中。 + +改为: + +> **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `inventory/`、`receipt/`、`common/` 分域(common 仅放跨 Worker 共享物,如 browser_profile)。 + +- [ ] **Step 2: 自查** AGENTS.md 内其余 `SHIPPING_NOTICE_RPA_` 字样(如 §8.1 环境变量文件排序、其他节引用)一并改为 `FREIGHT_RPA_` 口径;全文 grep 该前缀应仅剩本新规则中「历史名称」一句。 + +- [ ] **Step 3: 提交** + +```bash +git add AGENTS.md +git commit -m "docs(agnts): rpa命名空间红线修订为freight_rpa并废历史前缀" +``` + +> 注意:commitlint scope 用 `agnts`(AGENTS.md 无既有 scope 惯例时可改 `docs`,以 hook 通过为准;若 `agnts` 被拒改用 `chore`)。 + +--- + +### Task 2: 全仓机械前缀替换(代码/测试/脚本/配置/env/当前文档) + +**Files:** +- Modify(替换范围内所有含 `SHIPPING_NOTICE_RPA_` 的文件): `backend/app/**`、`backend/tests/**`、`backend/config/**`、`scripts/**`、`scripts/rpa/README.md`、`docs/features/shipping-notice/technical.md`、`.env.shared`、`.env.dev`、`.env.test`、`.env.prod` +- 不改: `docs/superpowers/plans/**`(历史记录)、`.engramory-memory/**`(结尾任务统一更新)、`AGENTS.md`(Task 1 已改) + +**Interfaces:** +- Produces: 全仓 `SHIPPING_NOTICE_RPA_` 前缀清零(白名单外);新前缀 `FREIGHT_RPA_`。Task 3 的布局值变更、Task 4 的 ps1 值变更建立在其上。 + +- [ ] **Step 1: 圈定替换清单并执行** + +```bash +cd /d/Workspace/HxProjects/hxops +grep -rl "SHIPPING_NOTICE_RPA_" \ + backend/app backend/tests backend/config scripts \ + .env.shared .env.dev .env.test .env.prod \ + scripts/rpa/README.md docs/features/shipping-notice/technical.md \ + | xargs sed -i 's/SHIPPING_NOTICE_RPA_/FREIGHT_RPA_/g' +``` + +> 范围刻意**不含** `backend/migrations` 与 `docs/superpowers/plans`(前者避免误 add 用户未跟踪迁移文件,后者是历史记录);若替换后 grep 发现 migrations 有命中,单独报告控制器裁决。 + +- [ ] **Step 2: 残留校验** + +```bash +grep -rn "SHIPPING_NOTICE_RPA_" backend/app backend/tests backend/config scripts .env.shared .env.dev .env.test .env.prod docs/features/shipping-notice/technical.md +``` + +Expected: 零命中。 + +- [ ] **Step 3: 语义抽查(防机械替换误伤)** + +人工抽查以下高风险点(替换应语义正确,因为它们读写的正是同一批变量): +1. `scripts/freight_rpa/common/rpa_common.py` 的 `_RPA_LEGACY_TO_CANONICAL`/`_legacy_rpa_env_name`/DeprecationWarning 逻辑——替换后其中出现的 `FREIGHT_RPA_*` 字样属于**待删除死代码**(Task 3 删除;本任务不删,保持"先纯替换后清理"的边界清晰)。抽查确认替换后这些常量值变成了自映射(如 `"FREIGHT_RPA_WORKER_ID": "FREIGHT_RPA_WORKER_ID"`)——**记录位置即可,不修**。 +2. `backend/tests` 中静态契约断言(如 `test_freight_receipt_worker_contract.py` 断言 `'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text`)与 worker 源文本一致。 +3. `backend/app/core/config/settings.py` 顶部历史别名映射同样变成自映射死表——记录位置,Task 3 删除。 + +- [ ] **Step 4: 回归** + +Run: `cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py tests/test_rpa_worker_logging.py tests/test_rpa_trigger_consumer.py tests/test_freight_rpa_worker.py tests/test_rpa_worker_heartbeat.py tests/services/in_transit_transfer` +Expected: 除已知既有基线失败(`reuse_session`×2、heartbeat fail-fast×2)外全绿。 + +- [ ] **Step 5: 提交** + +```bash +git add backend/app backend/tests backend/config scripts .env.shared .env.dev .env.test .env.prod +git commit -m "refactor(rpa): 环境变量命名空间恢复为freight_rpa前缀" +``` + +> 提交前必须 `git status` 逐目录确认:这些目录内**只有本任务的前缀替换改动**、无用户未提交的在途文件——若有混入,改用显式文件清单 `git add`(以替换清单输出为准),绝不 `git add -A` 目录。`backend/migrations` 不在提交范围。 + +--- + +### Task 3: 删除兼容层死代码 + +**Files:** +- Modify: `scripts/freight_rpa/common/rpa_common.py`(删 `_RPA_LEGACY_TO_CANONICAL`、`_WARNED_LEGACY_RPA_ENV`、`_legacy_rpa_env_name`、`_canonical_rpa_env_name`、`_env` 内的回退与告警逻辑——`_env` 退化为:读 `os.getenv(name)` → strip → 去外层成对引号) +- Modify: `backend/app/core/config/settings.py`(删顶部历史别名映射表/相关过渡代码——即 Task 2 Step 3.3 记录的自映射死表与任何 `deprecated` 过渡注释块) +- Test: `backend/tests/test_rpa_worker_logging.py` 等既有测试全量回归(无新增测试——行为即"旧名不再生效",由回归保证未误删在用逻辑) + +**Interfaces:** +- Produces: `rpa_common._env(name, default)` 语义 = 直读规范名;全仓无 `SHIPPING_NOTICE_RPA_` 兼容逻辑。 + +- [ ] **Step 1: 删除 rpa_common 兼容机制** + +`_env` 目标形态(保留 strip 与引号处理,删除 canonical/legacy 查找与 warnings): + +```python +def _env(name: str, default: str = "") -> str: + """ + 读取 RPA 环境变量,并去除首尾空白与最外层成对引号。 + + 核心逻辑:直接读取规范名称;历史 SHIPPING_NOTICE_RPA_* 前缀已于 + 2026-09-18 一刀切废弃,不再提供任何别名兼容。 + + Args: + name: 规范环境变量名(FREIGHT_RPA_*)。 + default: 未设置时的默认值。 + + Returns: + str: 去除空白与外层成对引号后的环境变量值。 + """ + value = str(os.getenv(name, default) 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 +``` + +同时删除 `_RPA_LEGACY_TO_CANONICAL`、`_WARNED_LEGACY_RPA_ENV`、`_canonical_rpa_env_name`、`_legacy_rpa_env_name` 及文件顶部相应 `import warnings`(若仅此处使用)。 + +- [ ] **Step 2: 删除 settings.py 过渡死表** + +按 Task 2 Step 3.3 记录的位置,删除自映射/历史别名表与「旧 Flask config 属性仅用于过渡期测试和外部扩展兼容」类过渡块(`settings.py` 中存在此类注释块,grep `deprecated|过渡|legacy` 定位);**Config 属性名已在 Task 2 随前缀替换更新,此处不新增任何别名**。 + +- [ ] **Step 3: 回归** + +Run: `cd backend && python -m pytest -q tests/test_freight_receipt_worker_contract.py tests/test_freight_rpa_worker.py tests/test_freight_rpa_worker_inventory_params.py tests/test_rpa_worker_heartbeat.py tests/test_rpa_worker_logging.py tests/test_rpa_trigger_consumer.py tests/services/in_transit_transfer` +Expected: 除已知既有基线失败外全绿。 + +- [ ] **Step 4: 提交** + +```bash +git add scripts/freight_rpa/common/rpa_common.py backend/app/core/config/settings.py +git commit -m "refactor(rpa): 删除环境变量历史别名兼容层" +``` + +--- + +### Task 4: 统一 `freight_rpa/{inventory,receipt,common}` 布局值 + +**Files:** +- Modify: `backend/app/core/config/settings.py`(RPA 目录默认值) +- Modify: `.env.shared` / `.env.dev` / `.env.test` / `.env.prod`(RPA 目录值) +- Modify: `scripts/freight_rpa/inventory/start_inventory_worker.ps1`、`scripts/freight_rpa/receipt/start_receipt_worker.ps1`(目录值 + 修失实注释) +- Modify: `scripts/rpa/README.md`、`docs/features/shipping-notice/technical.md`(路径表述,跟随 Task 6 统一校对亦可) + +**Interfaces:** +- Consumes: Global Constraints 的新布局值表(唯一依据)。 +- Produces: 三侧(后端默认 / env / ps1)目录值一致指向 `freight_rpa/{inventory,receipt,common}` 布局。 + +- [ ] **Step 1: settings.py 默认值** + +`_rpa_data_path` 各处默认从 `shipping_notice/freight_rpa/...`、`shipping_notice/freight_receipt_rpa/...` 改为(保持 `_rpa_data_path` 机制不变): +- INVENTORY_TRIGGER → `freight_rpa/inventory/triggers`;INVENTORY_DROP → `freight_rpa/inventory/drop` +- UPLOAD_TRIGGER → `freight_rpa/inventory/upload_triggers`;UPLOAD_QUEUE → `freight_rpa/inventory/upload_queue` +- INVENTORY_ARCHIVE → `freight_rpa/inventory/archives` +- RECEIPT_TRIGGER → `freight_rpa/receipt/triggers`;RECEIPT_DROP → `freight_rpa/receipt/drop` +- WORKER_BROWSER_PROFILE_DIR → `freight_rpa/common/browser_profile`(键名保留 `WORKER_` 前缀,值为共享根) + +- [ ] **Step 2: 四个 env 文件值** + +按新布局表更新 `.env.shared`(如有对应键)、`.env.dev`(相对 `data/…` 改 `freight_rpa/…` 形态,如 `data/freight_rpa/inventory/triggers`)、`.env.test`/`.env.prod`(`/mnt/hxops-rpa-{env}-data/freight_rpa/...`)。只改值与必要注释,不动键序/其他变量。 + +- [ ] **Step 3: 两个 ps1** + +库存 ps1(`$rpaRoot = Join-Path $WorkerRoot "freight_rpa"`): + +```powershell +$rpaRoot = Join-Path $WorkerRoot "freight_rpa" +# … +FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaRoot "inventory\triggers" +FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaRoot "inventory\drop" +FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaRoot "inventory\upload_triggers" +FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaRoot "inventory\upload_queue" +FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot "common\browser_profile" +FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot "inventory\logs\worker.log" +``` + +收料 ps1(`$rpaRoot = Join-Path $WorkerRoot 'freight_rpa'`): + +```powershell +FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $rpaRoot 'receipt\triggers' +FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $rpaRoot 'receipt\drop' +FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot 'common\browser_profile' +FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot 'receipt\logs\worker.log' +``` + +同时把收料 ps1 中「浏览器 Profile 目录复用既有标准变量(与库存 RPA Worker 一致)…」注释改为准确表述: + +```powershell + # 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile(各自在其中创建隔离的一次性子目录)。 +``` + +- [ ] **Step 4: 校验** + +Run: `cd backend && python -c "from app import create_app; app=create_app(); print(app.config['FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR']); print(app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR']); print(app.config['FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR'])"` +Expected: 三个 dev 值均为 `…\backend\data\rpa\{inventory\triggers, receipt\triggers, common\browser_profile}`。 + +- [ ] **Step 5: 提交** + +```bash +git add backend/app/core/config/settings.py .env.shared .env.dev .env.test .env.prod scripts/freight_rpa/inventory/start_inventory_worker.ps1 scripts/freight_rpa/receipt/start_receipt_worker.ps1 +git commit -m "chore(rpa): 运行期数据目录统一为rpa三层布局" +``` + +--- + +### Task 5: 文档同步(README / technical.md / AGENTS 排序节校对) + +**Files:** +- Modify: `scripts/rpa/README.md`、`docs/features/shipping-notice/technical.md`(路径表/部署增量中所有目录表述改为新布局;Task 2 已换前缀,此处统一路径形态与补 `common/` 语义) + +- [ ] **Step 1: README 部署方式全节走查(用户明确要求:布局变化导致部署方式变化,README 必须调整到位)** + +不止换键名前缀——对「部署、启动与停止手册」整节按新布局重写走查: +1. 目录结构示例全部改为 `freight_rpa/{inventory,receipt,common}` 三层(WorkerRoot 下不再有平铺的 `data\inventory_triggers` 等)。 +2. 新增「从旧布局升级」小节:旧 `data\inventory_triggers`、`data\freight_receipt_rpa\` 等目录废弃,未上线环境直接删旧建新;ps1 重新注入新路径,Worker 代码零变更。 +3. 磁盘清理、巡检示例(schtasks 重定向路径)、排障路径中的 `logs\...` 全部对齐 `rpa\<域>\logs\worker.log`。 +4. 补一句「目录布局:`freight_rpa/{inventory,receipt,common}`,common 仅放跨 Worker 共享物(browser_profile)」。 +5. 每处修改对照两个 ps1 的实际 `Join-Path` 值核实(以代码为准,不凭记忆)。 +6. 工作树中已有未提交的部署参数调整(ps1 LOG/WORKER_ID/DISK 参数、README 身份行、technical.md 身份句)——**与本次改动一并落,不单独提交**(用户 2026-09-18 指示)。 +- [ ] **Step 2: technical.md §1.9**:收料/库存部署增量中的路径全部按新布局校对(含 §1.9.3 巡检示例路径、§1.9.5 排障路径、挂载映射表);grep `freight_receipt_rpa\|freight_rpa\` 确认仅剩历史小节或零命中。 +- [ ] **Step 3: 提交** + +```bash +git add scripts/rpa/README.md docs/features/shipping-notice/technical.md +git commit -m "docs(rpa): 同步rpa三层目录布局与部署路径" +``` + +--- + +### Task 6: 全量回归 + 硬校验 + 本机验收清单 + +**Files:** 无新改动(发现回题回对应任务修) + +- [ ] **Step 1: 替换面硬校验** + +```bash +grep -rn "SHIPPING_NOTICE_RPA_" backend/app backend/tests backend/config backend/migrations scripts .env.shared .env.dev .env.test .env.prod docs/features/shipping-notice/technical.md scripts/rpa/README.md AGENTS.md | grep -v "历史名称" | wc -l +``` +Expected: 0。 + +- [ ] **Step 2: 全量相关回归** + +Run: `cd backend && python -m pytest -q tests/test_rpa_worker_logging.py tests/test_rpa_trigger_consumer.py tests/test_freight_receipt_worker_contract.py tests/test_freight_rpa_worker.py tests/test_freight_rpa_worker_inventory_params.py tests/test_rpa_worker_heartbeat.py tests/test_inventory_rpa_download_save_fallback.py tests/test_freight_receipt_rpa_callback.py tests/test_freight_receipt_rpa_schedule.py tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py tests/jobs/test_in_transit_transfer_jobs.py` +Expected: 除已知既有基线失败外全绿;py_compile 四个 worker/common 文件通过。 + +- [ ] **Step 3: 执行记录写入本文件末尾**;本机人工验收(新 env 名设值、旧 `SHIPPING_NOTICE_RPA_*` 本机残留 env 清除——旧名已不生效不会再被读取)。 + +## 明确不做 + +- 不改 `SHIPPING_NOTICE_TOOL_API_KEY` / `INTEGRATION_API_KEY`(非 RPA 前缀)。 +- 不迁移任何旧目录数据(未上线,旧目录删除由运维执行)。 +- 不给 `SHIPPING_NOTICE_RPA_*` 留任何别名/告警(用户决策:取消兼容)。 +- 不改历史计划文档与 .engramory 记忆中的历史名(记忆在收尾任务统一更新指针)。 + + +--- + +## 执行记录(2026-09-18,Subagent-Driven Development) + +**结果:6 个任务全部完成 + 最终全分支审查「With fixes」→ 修复波 `229c76e0a` → 复审 all findings addressed。** + +提交清单(base `95488db65`,6 个提交;用户并行提交 `95488db65` 等不在本计划内): +`1f102902a` AGENTS 红线修订 → `e5cf302de` 全仓前缀替换(70 文件)→ `fef72176d` 删兼容层 → `6b5db9c30` freight_rpa 三层布局值 → `620b8e141` 部署配置与权威文档同步 → `229c76e0a` 死插值与旧默认值清理。 + +回归:Task 6 全量 sweep 379 passed / 4 failed(全部既有基线)/ 1 skipped;硬校验旧前缀功能性残留 0(仅 2 处"已废弃"说明注释属白名单意图);py_compile 通过。 + +执行中的裁定修正: +1. 根目录段 `rpa` → `freight_rpa`(用户现场指令,计划与 AGENTS.md 已同步)。 +2. T2 范围外的活配置/活文档残留(docker-compose.yml、env_loading_priority.md、tec.md、in-transit technical.md)由 T5 收口(合并阻塞级)。 +3. 终审两项 Important(compose 死插值、库存 Worker 旧布局默认+反向重映射)由 `229c76e0a` 修复波收口。 + +**待人工完成(Task 6 Step 3 本机验收):** +1. 清除 shell/系统环境变量中所有旧 `SHIPPING_NOTICE_RPA_*` 值(已无兼容层,旧名不再被读取);按新名设置:`FREIGHT_RPA_SHARED_{INVENTORY,RECEIPT}_*` 目录、`FREIGHT_RPA_WORKER_LOG_FILE`、`FREIGHT_RPA_BROWSER_PROFILE_DIR` 等(或直接用两个 ps1 启动)。 +2. 裸跑两 Worker 确认 banner 目录为 `freight_rpa\{inventory,receipt,common}\...` 新布局;日志落 `freight_rpa/<域>/logs/worker.log`。 +3. 管理端确认两张独立心跳卡片:`<主机名>-inventory`、`<主机名>-receipt`。 +4. 部署主机按 README「从旧布局升级」小节删旧建新目录(`rpa/{inventory,receipt,common}` → 注意实际根段为 `freight_rpa`)。 +5. 后续跟进任务(已登记,不阻塞):technical.md §1.5.4–§1.5.11 约 33 行旧布局残留 + §1.2 示例值 + README §2.2 跨引用 + 升级表补 `data\shipping_notice reight_rparowser_profile` 旧收料 Profile 变体(technical.md 整体未提交,收口时一并入库);`.env` 历史 Fernet 凭据轮转工单。 + +> **基线失败后续(2026-09-18)**:上述 4 个既有基线失败已全部修复——`reuse_session`×2(过期测试桩签名)、heartbeat fail-fast×2(`no_worker_heartbeat` 测试隔离 + 排程 readiness 门禁接线)。提交 `5dca2a3af`、`b1213ffef`,修复后相关套件 139 passed / 1 skipped / 0 failed。 diff --git a/docs/tec.md b/docs/tec.md index 46353878..6864f992 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -1514,7 +1514,7 @@ RecoveryPlan → Gate Attempt → Job → Worker/RPA → 幂等回调 → `run_t # 货代收料 RPA 独立架构(2026-08) -`freight-receipt-rpa` 写入 `shipping_receipt_rpa.v1` trigger,仅由 `freight_receipt_rpa_worker.py` 消费。它使用专属 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` 和 `...RECEIPT_DROP_DIR`,不得与库存 Worker 共享目录或 callback。trigger 先写同目录临时文件、`fsync` 后以 `os.replace` 原子发布,避免 Worker 读取半截 JSON。Worker 在单次排程内按 `connector_type + rpa_profile_id + login_url` 分组并登录一次,串行导出;密文凭据仅在冻结 trigger 内传递并在 Worker 短暂解密。callback 仅允许读取 receipt drop 根内的 `.xlsx`,校验 SHA-256/大小后归档 MinIO。收料表与 `shipping_inventory_files` 无关联。 +`freight-receipt-rpa` 写入 `shipping_receipt_rpa.v1` trigger,仅由 `freight_receipt_rpa_worker.py` 消费。它使用专属 `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` 和 `...RECEIPT_DROP_DIR`,不得与库存 Worker 共享目录或 callback。trigger 先写同目录临时文件、`fsync` 后以 `os.replace` 原子发布,避免 Worker 读取半截 JSON。Worker 在单次排程内按 `connector_type + rpa_profile_id + login_url` 分组并登录一次,串行导出;密文凭据仅在冻结 trigger 内传递并在 Worker 短暂解密。callback 仅允许读取 receipt drop 根内的 `.xlsx`,校验 SHA-256/大小后归档 MinIO。收料表与 `shipping_inventory_files` 无关联。 下载接口为 `GET /api/workspace/receipt-report-files/{file_id}/download`(管理员或排程接收人);`GET /api/workspace/receipt-report-files` 仅列出当前用户有权读取的脱敏归档元数据,并在授权过滤后施加 limit。管理员可通过 `GET /api/admin/receipt-rpa-units?status=failed` 定位失败单元,并以 `POST /api/admin/receipt-rpa-units/{unit_id}/retry`(必填原因)或 `POST /api/admin/receipt-report-files/{file_id}/resend` 补偿。运行等待 callback 超时会被 Worker 启动和周期扫描收口为失败,绝不自动重试;管理员补偿创建新单元,保留旧单元。管理员在既有库存站点抽屉通过独立 `GET/PUT /api/admin/shipping-notice/sources/{source_id}/receipt-report-config` 维护收料配置,不能改写库存 Source 字段:DBS 维护路径/条件/Warehouse,Crane 固定 `Inbound Details`,拒绝 Warehouse 和查询条件;Worker 无论 Profile 登录 URL 的原 hash 均强制进入 `#/inbound-details-query` 并直接使用页面默认条件。所有入口写含前后状态快照的 `ShippingAuditEvent`;三年期满仅删除对象、保留文件事实与审计。 diff --git a/scripts/rpa/README.md b/scripts/freight_rpa/README.md similarity index 58% rename from scripts/rpa/README.md rename to scripts/freight_rpa/README.md index 227fd512..625a5dbd 100644 --- a/scripts/rpa/README.md +++ b/scripts/freight_rpa/README.md @@ -4,14 +4,14 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA ## 收料 RPA(独立 Worker) -收料使用 `scripts\rpa\receipt\receipt_rpa_worker.py` 与 `scripts\rpa\receipt\start_receipt_worker.ps1`,仅消费 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR`,仅写 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR`,只回调 `/api/shipping-notice/rpa/receipt-batch-ready`。它可以与库存 Worker 同时运行,但收料专用目录(trigger、drop、日志,以及启动脚本默认分开的浏览器 Profile 根)绝不能改回与库存共用。 +收料使用 `scripts\freight_rpa\receipt\receipt_rpa_worker.py` 与 `scripts\freight_rpa\receipt\start_receipt_worker.ps1`,仅消费 `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR`,仅写 `FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR`,只回调 `/api/shipping-notice/rpa/receipt-batch-ready`。它可以与库存 Worker 同时运行,但收料专用目录(trigger、drop、日志,以及启动脚本默认分开的浏览器 Profile 根)绝不能改回与库存共用。 部署手册(本地联调 + Windows RPA 主机 + Ubuntu 后端)见 `docs/features/shipping-notice/technical.md` §1.9;本节只作脚本速查。 启动示例: ```powershell -.\scripts\rpa\receipt\start_receipt_worker.ps1 -Environment test -ApiBase "http://" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" +.\scripts\freight_rpa\receipt\start_receipt_worker.ps1 -Environment test -ApiBase "http://" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" ``` 收料 Worker 在同一排程内按 Profile 登录一次后串行处理单元;DBS 每个 Warehouse 导出一个文件且不传报表日期,Crane 无论 Profile 登录地址保存为门户首页还是其他页面,都会强制进入 `#/inbound-details-query`,不填写 Warehouse 或查询条件,直接使用页面默认条件生成/等待唯一 Description 对应的 `Inbound Details` 文件。不要把收料 trigger 手工复制到库存目录或反向复制。 @@ -55,53 +55,55 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA | `receipt/receipt_crane_export.py` | Crane 收料报表导出适配器(强制 Inbound Details) | | `receipt/receipt_dbs_export.py` | DBS 收料报表导出适配器(按 Warehouse) | | `receipt/start_receipt_worker.ps1` | 启动收料 Worker 的 PowerShell 启动脚本(原 `start_receipt_rpa_worker.ps1`) | +| `receipt/register_receipt_worker_tasks.ps1` | 注册 test/prod 收料 Worker 后台计划任务(headless + hidden,任务名与库存注册脚本相互独立) | ## 目录约定 +> **目录布局**:RPA 运行期数据统一存放在 `\freight_rpa\{inventory,receipt,common}` 三层(后端 dev 默认对应 `backend/data/freight_rpa/...`,test/prod 对应 SMB 挂载下的 `freight_rpa/...` 子路径);`common` 仅放跨 Worker 共享物(`browser_profile`)。 | 环境变量 | 用途 | | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | -| `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{task_no}.json` 或 `inventory_export_batch_{run_no}.json`,RPA 读取后导库存 | -| `SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest | -| `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` | -| `SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel | -| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED` | 真实上传浏览器自动化总开关,默认 `false` | -| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT` | 最终提交二次确认,默认 `false` | -| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL` | 非 DSV 站点的已审核上传页面 URL(仅由受控环境变量注入) | -| `SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` | DSV Portal 入口;Worker 复用登录态,优先 `My Applications > Upload Tool`,再退回 `Apps > Upload Tool` | -| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR` | 文件输入框 CSS selector | -| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR` | 提交按钮 CSS selector | -| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR` | 成功状态 CSS selector;未出现不得回调成功 | -| `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR` | 可选的货代回执号 CSS selector | -| `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | 与后端 `SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` 一致;Worker 在 **inventory_triggers** 目录写哨兵 `.hxops_rpa_shared_mount` | -| `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` / `prod`,须与后端 `ENV_NAME` 一致 | -| `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | 心跳间隔(默认 20s),test/prod 触发前检查依赖在线心跳 | -| `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` | Profile 凭据 Fernet 主密钥;必须与对应环境后端一致,只能由 Secret 渠道或部署脚本安全注入 | -| `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE` | 库存导出是否复用浏览器登录 Profile,默认 `true`;上传任务不受影响;站点会话失效时自动重登 | -| `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` | Worker 文件日志路径(stdout/stderr tee) | -| `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES` | 单日志文件大小上限(默认 10MB);启动与周期清理时按大小轮转 | -| `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT` | 日志备份个数(默认 5) | -| `SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS` | 本机归档保留天数(默认 7);`<=0` 禁用按天清理。覆盖 trigger `processed/failed`、drop 归档/隔离、upload_queue、日志备份 | -| `SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS` | 磁盘清理周期秒数(默认 3600);Worker 启动时会立即清一轮 | -| `SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS` | 孤儿临时 `run_*` Profile 最大存活小时(默认 24);`*_session` 会话 Profile 永不删除 | +| `FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{task_no}.json` 或 `inventory_export_batch_{run_no}.json`,RPA 读取后导库存 | +| `FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest | +| `FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` | +| `FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel | +| `FREIGHT_RPA_WORKER_UPLOAD_ENABLED` | 真实上传浏览器自动化总开关,默认 `false` | +| `FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT` | 最终提交二次确认,默认 `false` | +| `FREIGHT_RPA_WORKER_UPLOAD_URL` | 非 DSV 站点的已审核上传页面 URL(仅由受控环境变量注入) | +| `FREIGHT_RPA_WORKER_DSV_UPLOAD_ENTRY_URL` | DSV Portal 入口;Worker 复用登录态,优先 `My Applications > Upload Tool`,再退回 `Apps > Upload Tool` | +| `FREIGHT_RPA_WORKER_UPLOAD_FILE_SELECTOR` | 文件输入框 CSS selector | +| `FREIGHT_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR` | 提交按钮 CSS selector | +| `FREIGHT_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR` | 成功状态 CSS selector;未出现不得回调成功 | +| `FREIGHT_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR` | 可选的货代回执号 CSS selector | +| `FREIGHT_RPA_SHARED_SCOPE_ID` | 与后端 `FREIGHT_RPA_SHARED_SCOPE_ID` 一致;Worker 在 **freight_rpa\inventory\triggers** 目录写哨兵 `.hxops_rpa_shared_mount` | +| `FREIGHT_RPA_WORKER_ENVIRONMENT` | `test` / `prod`,须与后端 `ENV_NAME` 一致 | +| `FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS` | 心跳间隔(默认 20s),test/prod 触发前检查依赖在线心跳 | +| `FREIGHT_RPA_CREDENTIAL_KEY` | Profile 凭据 Fernet 主密钥;必须与对应环境后端一致,只能由 Secret 渠道或部署脚本安全注入 | +| `FREIGHT_RPA_WORKER_SESSION_REUSE` | 库存导出是否复用浏览器登录 Profile,默认 `true`;上传任务不受影响;站点会话失效时自动重登 | +| `FREIGHT_RPA_WORKER_LOG_FILE` | Worker 文件日志路径(stdout/stderr tee) | +| `FREIGHT_RPA_WORKER_LOG_MAX_BYTES` | 单日志文件大小上限(默认 10MB);启动与周期清理时按大小轮转 | +| `FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT` | 日志备份个数(默认 5) | +| `FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS` | 本机归档保留天数(默认 7);`<=0` 禁用按天清理。覆盖 trigger `processed/failed`、drop 归档/隔离、upload_queue、日志备份 | +| `FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS` | 磁盘清理周期秒数(默认 3600);Worker 启动时会立即清一轮 | +| `FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS` | 孤儿临时 `run_*` Profile 最大存活小时(默认 24);`*_session` 会话 Profile 永不删除 | -新部署只使用 `new_rpa_worker_secret.ps1` + `start_rpa_worker.ps1`:Secret 由 DPAPI 保护,环境变量只注入对应 Worker 子进程。 +新部署只使用 `new_rpa_worker_secret.ps1` + `start_inventory_worker.ps1`:Secret 由 DPAPI 保护,环境变量只注入对应 Worker 子进程。 -统一命名规则:共享目录与 scope 使用 `SHIPPING_NOTICE_RPA_SHARED_*`,Windows Worker -运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,Profile 凭据主密钥使用 -`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。部署文档和启动脚本只使用上述规范命名。 +统一命名规则:共享目录与 scope 使用 `FREIGHT_RPA_SHARED_*`,Windows Worker +运行参数使用 `FREIGHT_RPA_WORKER_*`,Profile 凭据主密钥使用 +`FREIGHT_RPA_CREDENTIAL_KEY`。部署文档和启动脚本只使用上述规范命名。 DSV/Crane 库存导出默认复用浏览器 Profile(按 `connector + rpa_profile_code` 隔离目录, 长期保留)。同一 WorkerRoot 只跑一个 Worker,任务串行消费;是否免登取决于货代站点会话 是否仍有效,失效时回落现有登录流程。上传任务保持一次性 Profile。若需强制每次全新登录, -启动时加 `-NoSessionReuse`。旧参数 `-ReuseDsvSession` / `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE` -仍兼容,但请改用 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`。 +启动时加 `-NoSessionReuse`。旧参数 `-ReuseDsvSession` / `FREIGHT_RPA_WORKER_DSV_SESSION_REUSE` +已于 2026-09-18 移除,请统一使用 `-ReuseSession` / `FREIGHT_RPA_WORKER_SESSION_REUSE`。 -Worker 默认启用本机磁盘保留清理(`scripts/rpa/common/worker_disk_cleanup.py`):启动与每小时 +Worker 默认启用本机磁盘保留清理(`scripts/freight_rpa/common/worker_disk_cleanup.py`):启动与每小时 清理超过保留期的 `processed/failed` trigger、drop 归档(含 `processed` / `.hxops_quarantine` / `.cleanup_failed`)、过期 drop 根导出文件、upload_queue 残留、 日志备份,以及超过 24h 的孤儿 `run_*` 临时 Profile。**不删除**进行中的 trigger 根 JSON、 @@ -110,11 +112,11 @@ Worker 默认启用本机磁盘保留清理(`scripts/rpa/common/worker_disk_cl 已确认 DSV 上传页为 `WMS Upload Tool > Upload`,页面有 `Browse` 文件选择入口和 `History` 查询入口。`Browse` 的真实 DOM 是 ``,因此 -DSV Worker 默认使用 `#file2`,也可用 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR` +DSV Worker 默认使用 `#file2`,也可用 `FREIGHT_RPA_WORKER_UPLOAD_FILE_SELECTOR` 覆盖。选择文件后出现的真实提交控件为 `