Merge branch 'hugo-shipping-notice' into test

This commit is contained in:
hugo committed 2026-09-19 16:08:52 +08:00
commit 76583c4e5a
98 files changed
+2202 -1475

No files matched your search

+18 -18
View File
@@ -135,29 +135,29 @@ SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03 SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(相对 backend/ 根目录) # RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=data/shipping_notice/freight_receipt_rpa/receipt_drop FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/shipping_notice/freight_receipt_rpa/receipt_triggers FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
# AWS 库存列映射(可选 JSON 字符串) # AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 RPA(scripts/rpa/freight_rpa_worker.py) # 本地 RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py)
SHIPPING_NOTICE_RPA_WORKER_MOCK=false FREIGHT_RPA_WORKER_MOCK=false
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis # 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
# 企微心跳告警总开关(默认关闭;需要时改为 true) # 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 # FREIGHT_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY= # FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
# --- 10. 运维、告警与维护工具 --- # --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥 # 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+15 -14
View File
@@ -135,22 +135,23 @@ SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03 SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致) # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true) # 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微 # 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= FREIGHT_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop # RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_drop FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_receipt_rpa/receipt_triggers FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_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 访问) # 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
+3 -3
View File
@@ -270,7 +270,7 @@ SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=30
SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800 SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。 # RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。 # 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE= FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
# 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。 # 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。
# L7 验收完成前禁止开启通用解析与通用自动冻结。 # L7 验收完成前禁止开启通用解析与通用自动冻结。
# 通用确定性解析:仅 no_special_profile_feature / 无漂移 no_match 可进入。 # 通用确定性解析:仅 no_special_profile_feature / 无漂移 no_match 可进入。
@@ -300,9 +300,9 @@ SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 货代上传 RPA:默认关闭;具备 Worker/凭据/共享目录与隔离校验后再在环境文件显式设 true。 # 货代上传 RPA:默认关闭;具备 Worker/凭据/共享目录与隔离校验后再在环境文件显式设 true。
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs. # 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) # 企微心跳告警总开关(默认关闭;需要时在环境文件改为 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_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001 FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
+22 -22
View File
@@ -152,35 +152,35 @@ SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03 SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐) # 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true) # 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微 # 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
# 两者皆无则告警只写日志、不会发企微 # 两者皆无则告警只写日志、不会发企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= FREIGHT_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120) # 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600 FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns= FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享) # RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers
# AWS 库存列映射(可选 JSON 字符串) # AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 Mock RPA(scripts/rpa/inventory/inventory_rpa_worker.py,可选) # 本地 Mock RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py,可选)
# SHIPPING_NOTICE_RPA_WORKER_MOCK=true # FREIGHT_RPA_WORKER_MOCK=true
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 # FREIGHT_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY= # FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问) # 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
+1 -1
View File
@@ -163,7 +163,7 @@ docker compose logs -f hxops-backend
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。 - **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。 - **章节内组织**:先按业务域及子域聚合(如 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`)置于该数据源首位。 - **数据库连接固定顺序**:`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` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。 - **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。 - **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
+19 -4
View File
@@ -154,6 +154,21 @@ def _require_formal_notice(task: Any) -> ShippingNotice:
return task return task
def _require_editable_task(task: Any) -> Any:
"""订单编辑写接口的实体守卫:正式 Notice 或建单前 OT 均可。
核心逻辑:订单字段/行的编辑权限由服务层状态制闸门裁决
(Excel ready 硬冻结 + 活动 Attempt 忙碌锁 + Schema 反向锁),
与实体类型无关——通知准备阶段(Notice 未建)编辑履约字段是受支持场景。
"""
if not isinstance(task, (ShippingNotice, ShippingOrderTask)):
raise ValidationError(
'Formal shipping notice is required for this operation',
code='SHIPPING.FORMAL_NOTICE_REQUIRED',
)
return task
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks(): def workspace_shipping_tasks():
"""分页列出当前用户可见的发货任务,可按处理状态过滤。""" """分页列出当前用户可见的发货任务,可按处理状态过滤。"""
@@ -660,7 +675,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
task = _require_formal_notice(task) task = _require_editable_task(task)
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
fields = data.get('fields') fields = data.get('fields')
if not isinstance(fields, dict) or not fields: if not isinstance(fields, dict) or not fields:
@@ -707,7 +722,7 @@ def workspace_update_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
task = _require_formal_notice(task) task = _require_editable_task(task)
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
try: try:
line_index = int(data.get('line_index')) line_index = int(data.get('line_index'))
@@ -796,7 +811,7 @@ def workspace_add_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
task = _require_formal_notice(task) task = _require_editable_task(task)
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
line = data.get('line') line = data.get('line')
if not isinstance(line, dict) or not line: if not isinstance(line, dict) or not line:
@@ -822,7 +837,7 @@ def workspace_remove_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
task = _require_formal_notice(task) task = _require_editable_task(task)
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
try: try:
line_index = int(data.get('line_index')) line_index = int(data.get('line_index'))
+58 -112
View File
@@ -8,7 +8,6 @@ backend/app/core/config/settings.py
旧路径 app.config 为兼容 shim。 旧路径 app.config 为兼容 shim。
""" """
import os import os
import warnings
from pathlib import Path from pathlib import Path
from dotenv import dotenv_values from dotenv import dotenv_values
@@ -16,18 +15,6 @@ from dotenv import dotenv_values
_BACKEND_DIR = Path(__file__).resolve().parents[3] _BACKEND_DIR = Path(__file__).resolve().parents[3]
_ROOT_DIR = _BACKEND_DIR.parent _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: 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) 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: Args:
canonical_name: 统一后的规范环境变量名。 env_key: 规范 RPA 目录环境变量名。
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 目录环境变量名。
*parts: 未配置时相对 `backend/data` 的默认路径片段。 *parts: 未配置时相对 `backend/data` 的默认路径片段。
Returns: Returns:
@@ -139,7 +94,7 @@ def _rpa_data_path(canonical_name: str, *parts: str) -> str:
from app.path_utils import resolve_backend_relative_path from app.path_utils import resolve_backend_relative_path
default = _BACKEND_DIR.joinpath('data', *parts) 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: class Config:
@@ -310,9 +265,7 @@ class Config:
# 货代发货通知 Agent Tool API # 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY') SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# RPA Profile 凭据字段的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。 # RPA Profile 凭据字段的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = _rpa_env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') FREIGHT_RPA_CREDENTIAL_KEY = os.getenv('FREIGHT_RPA_CREDENTIAL_KEY')
# 兼容仍从 Flask config 读取旧属性的扩展;新代码禁止继续使用该属性。
SHIPPING_RPA_CREDENTIAL_KEY = SHIPPING_NOTICE_RPA_CREDENTIAL_KEY
# 文件检核 Chatflow Tool API # 文件检核 Chatflow Tool API
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY') FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
@@ -425,46 +378,46 @@ class Config:
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = ( SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true' os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
) )
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int( FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900' os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
) )
SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS = int( FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS') or '900' os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
) )
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int( FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90' os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
) )
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = ( FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true' os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
) )
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = ( FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower() os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
in {'1', 'true', 'yes', 'on'} 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'} else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
) )
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = ( FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true' 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() FREIGHT_RPA_SHARED_SCOPE_ID = os.getenv('FREIGHT_RPA_SHARED_SCOPE_ID', '').strip()
SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = ( FREIGHT_RPA_SHARED_SENTINEL_NAME = (
os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip() os.getenv('FREIGHT_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
or '.hxops_rpa_shared_mount' or '.hxops_rpa_shared_mount'
) )
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = ( FREIGHT_RPA_WORKER_ALERT_ENABLED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true' os.getenv('FREIGHT_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
) )
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int( FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800' os.getenv('FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
) )
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv( FREIGHT_RPA_WORKER_ALERT_USERNAMES = os.getenv(
'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', '' 'FREIGHT_RPA_WORKER_ALERT_USERNAMES', ''
).strip() ).strip()
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = ( FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true' os.getenv('FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
) )
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int( FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120' 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_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' 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) # 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_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') FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int( FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30' os.getenv('FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
) )
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int( SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000' 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') SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP') FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path( # RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', 'shipping_notice', 'freight_rpa', 'inventory_drop' 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( FREIGHT_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', 'freight_rpa', 'inventory', 'triggers'
) )
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path( FREIGHT_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', 'freight_rpa', 'receipt', 'drop'
) )
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path( FREIGHT_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', 'freight_rpa', 'receipt', 'triggers'
) )
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path( FREIGHT_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', 'freight_rpa', 'inventory', 'upload_queue'
) )
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path( FREIGHT_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', 'freight_rpa', 'inventory', 'upload_triggers'
) )
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path( FREIGHT_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', 'freight_rpa', 'common', 'browser_profile'
) )
SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path( FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', 'shipping_notice', 'freight_rpa', 'inventory_archives' 'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
) )
SHIPPING_NOTICE_RPA_WORKER_MOCK = _rpa_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false') FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_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
# WeCom (企业微信) 登录配置 # WeCom (企业微信) 登录配置
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true' WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
@@ -789,8 +735,8 @@ class DevelopmentConfig(Config):
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = True ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = True
# 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用) # 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# XFA 拆分确认 JTI:仅单进程 development 允许内存消费;test/prod 多 Worker 必须 Redis # XFA 拆分确认 JTI:仅单进程 development 允许内存消费;test/prod 多 Worker 必须 Redis
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
@@ -810,8 +756,8 @@ class TestingConfig(Config):
FIXED_ASSETS_SYNC_ENABLED = False FIXED_ASSETS_SYNC_ENABLED = False
FIXED_ASSETS_EXPORT_TO_DOCS = False FIXED_ASSETS_EXPORT_TO_DOCS = False
ENV_NAME = 'dev' ENV_NAME = 'dev'
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# pytest 单进程:允许内存 JTI;生产语义由 ProductionConfig 关闭 # pytest 单进程:允许内存 JTI;生产语义由 ProductionConfig 关闭
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
@@ -68,7 +68,7 @@ def recover_stale_waiting_source_jobs() -> int:
from flask import current_app from flask import current_app
try: 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): except (TypeError, ValueError):
timeout = 900 timeout = 900
cutoff = datetime.utcnow() - timedelta(seconds=timeout) cutoff = datetime.utcnow() - timedelta(seconds=timeout)
@@ -79,7 +79,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
def _receipt_timeout_seconds() -> int: def _receipt_timeout_seconds() -> int:
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。""" """读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
try: 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): except (TypeError, ValueError):
return 900 return 900
@@ -39,14 +39,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
def get_inventory_archive_dir() -> str: def get_inventory_archive_dir() -> str:
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。""" """返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
archive_dir = Path( 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 if current_app
else "" else ""
) )
if not str(archive_dir): if not str(archive_dir):
from app.core.config.settings import Config 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) archive_dir.mkdir(parents=True, exist_ok=True)
return str(archive_dir) return str(archive_dir)
@@ -251,7 +251,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
""" """
校验归档 ZIP 路径是否安全可下载。 校验归档 ZIP 路径是否安全可下载。
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内。 核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
""" """
resolved = zip_path.resolve() resolved = zip_path.resolve()
if resolved.suffix.lower() != ".zip": if resolved.suffix.lower() != ".zip":
@@ -272,7 +272,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。 解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、 核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
且真实路径位于 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。 且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
Returns: Returns:
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。 tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
@@ -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.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.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 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]]] 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')}" run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
try: try:
# 写 trigger 前强制就绪检查:worker 离线立即 failed,不进入 awaiting_rpa_callback。
assert_inventory_rpa_worker_ready()
trigger_path = write_inventory_export_batch_trigger( trigger_path = write_inventory_export_batch_trigger(
run_no, run_no,
sources, sources,
@@ -26,17 +26,17 @@ def _fernet() -> Fernet:
Raises: Raises:
ServiceUnavailableError: 未配置或配置了无效的主密钥。 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: if not key:
raise ServiceUnavailableError( raise ServiceUnavailableError(
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is not configured', 'FREIGHT_RPA_CREDENTIAL_KEY is not configured',
code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING', code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING',
) )
try: try:
return Fernet(key.encode('ascii')) return Fernet(key.encode('ascii'))
except (ValueError, UnicodeEncodeError) as exc: except (ValueError, UnicodeEncodeError) as exc:
raise ServiceUnavailableError( raise ServiceUnavailableError(
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is invalid', 'FREIGHT_RPA_CREDENTIAL_KEY is invalid',
code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID', code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
) from exc ) from exc
@@ -420,7 +420,7 @@ def _auto_upload_enabled() -> bool:
def _rpa_upload_timeout_seconds() -> int: def _rpa_upload_timeout_seconds() -> int:
"""货代上传 RPA 等待回调超时秒数。""" """货代上传 RPA 等待回调超时秒数。"""
try: 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): except (TypeError, ValueError):
return 30 return 30
@@ -219,7 +219,7 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站 同一 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( runs = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
@@ -357,7 +357,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
db.session.commit() db.session.commit()
return _payload(run) return _payload(run)
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到 # 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() raw_file_path = str(payload.get('file_path') or '').strip()
path: Path | None = None path: Path | None = None
from app.services.shipping_notice.rpa import inventory_drop_dir from app.services.shipping_notice.rpa import inventory_drop_dir
@@ -56,11 +56,11 @@ def callback_quarantine_dir() -> Path | None:
def callback_cleanup_max_attempts() -> int: def callback_cleanup_max_attempts() -> int:
"""cleanup job 最大重试次数(SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。""" """cleanup job 最大重试次数(FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
try: try:
return max( return max(
1, 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): except (TypeError, ValueError):
return _DEFAULT_MAX_CLEANUP_ATTEMPTS return _DEFAULT_MAX_CLEANUP_ATTEMPTS
@@ -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) scheduled_at = next_inventory_rpa_recheck_at(task)
if scheduled_at is None: if scheduled_at is None:
recheck_seconds = max( 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, 1,
) )
scheduled_at = datetime.utcnow() + timedelta(seconds=recheck_seconds) scheduled_at = datetime.utcnow() + timedelta(seconds=recheck_seconds)
@@ -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: def _read_receipt_callback_file(file_path: str) -> bytes:
"""只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。""" """只读取收料专用 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: if not configured_root:
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
root = Path(configured_root).resolve() root = Path(configured_root).resolve()
@@ -14,7 +14,7 @@ from flask import current_app
def receipt_trigger_dir() -> Path | None: def receipt_trigger_dir() -> Path | None:
"""返回收料专用 trigger 目录;绝不回落到库存 trigger 目录。""" """返回收料专用 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 return Path(value) if value else None
+6 -6
View File
@@ -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() mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
if mode in {"browser", "mock"}: if mode in {"browser", "mock"}:
return _runtime_summary(mode) 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") 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: def inventory_drop_dir() -> Path | None:
"""RPA 库存 Excel 落盘目录(SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR)。""" """RPA 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR)。"""
return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR") return _path("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR")
def inventory_processed_dir() -> Path | None: def inventory_processed_dir() -> Path | None:
@@ -63,7 +63,7 @@ def inventory_processed_dir() -> Path | None:
def inventory_trigger_dir() -> Path | None: def inventory_trigger_dir() -> Path | None:
"""RPA 库存导出触发 JSON 目录。""" """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: 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: def upload_queue_dir() -> Path | None:
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。""" """货代上传 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: def upload_trigger_dir() -> Path | None:
"""RPA 货代上传触发 JSON 目录。""" """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: def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
@@ -86,8 +86,8 @@ def upload_rpa_attempts(task: ShippingNotice | None) -> int:
def max_rpa_upload_attempts() -> int: def max_rpa_upload_attempts() -> int:
"""RPA 货代上传最大重试次数(环境变量 SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS)。""" """RPA 货代上传最大重试次数(环境变量 FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS)。"""
value = os.getenv("SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS") value = os.getenv("FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS")
if value is None or not str(value).strip(): if value is None or not str(value).strip():
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
try: try:
@@ -39,6 +39,7 @@ _MEMORY_LOCK = threading.Lock()
_REASON_USER_HINTS: dict[str, str] = { _REASON_USER_HINTS: dict[str, str] = {
"no_worker_heartbeat": "未收到任何 Worker 心跳", "no_worker_heartbeat": "未收到任何 Worker 心跳",
"heartbeat_store_process_local": "未配置 REDIS_URL(或 Redis 不可达),心跳存储为本进程内存,跨进程不可见;请配置 REDIS_URL 或设 FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED=false 跳过心跳检查",
"heartbeat_storage_unavailable": "心跳存储不可用(Redis)", "heartbeat_storage_unavailable": "心跳存储不可用(Redis)",
"trigger_dir_not_configured": "后端未配置 trigger 目录", "trigger_dir_not_configured": "后端未配置 trigger 目录",
"trigger_dir_not_accessible": "trigger 目录不存在或不可访问", "trigger_dir_not_accessible": "trigger 目录不存在或不可访问",
@@ -48,7 +49,7 @@ _REASON_USER_HINTS: dict[str, str] = {
"environment_mismatch": "Worker 环境与后端环境不一致", "environment_mismatch": "Worker 环境与后端环境不一致",
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力", "missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力", "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_configured": "未配置货代上传队列目录",
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问", "upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
"callback_api_base_missing": "未配置 Worker 回调可达的 API 基址", "callback_api_base_missing": "未配置 Worker 回调可达的 API 基址",
@@ -91,9 +92,9 @@ def _config_str(key: str, default: str = "") -> str:
def _heartbeat_ttl_seconds() -> int: def _heartbeat_ttl_seconds() -> int:
raw = 90 raw = 90
if current_app: 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: 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) return max(60, raw)
@@ -101,16 +102,16 @@ def _heartbeat_check_required() -> bool:
"""Mock RPA 或显式关闭时跳过 worker 心跳就绪检查。""" """Mock RPA 或显式关闭时跳过 worker 心跳就绪检查。"""
if rpa_runtime_mode().get("mock"): if rpa_runtime_mode().get("mock"):
return False 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: def _heartbeat_redis_required() -> bool:
"""test/prod 默认要求 Redis;dev 仅显式开启时要求。""" """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() != "": 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: 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: if configured is not None:
return bool(configured) return bool(configured)
env_name = resolve_backend_rpa_environment() env_name = resolve_backend_rpa_environment()
@@ -118,7 +119,7 @@ def _heartbeat_redis_required() -> bool:
def _heartbeat_allow_memory_fallback() -> 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: def resolve_backend_rpa_environment() -> str:
@@ -131,7 +132,7 @@ def resolve_backend_rpa_environment() -> str:
def shared_scope_id() -> str: def shared_scope_id() -> str:
"""共享 SMB 目录逻辑标识(如 hxops-rpa-test-data),用于跨平台路径对齐。""" """共享 SMB 目录逻辑标识(如 hxops-rpa-test-data),用于跨平台路径对齐。"""
explicit = _config_str("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "") explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "")
if explicit: if explicit:
return explicit return explicit
trigger_dir = inventory_trigger_dir() trigger_dir = inventory_trigger_dir()
@@ -145,7 +146,7 @@ def shared_scope_id() -> str:
def shared_sentinel_name() -> 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: 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: def reset_rpa_worker_heartbeat_state_for_tests() -> None:
"""单测隔离:清空进程内内存心跳缓存。""" """单测隔离:清空进程内内存心跳缓存,并尽力清除 Redis 中的持久心跳记录。"""
with _MEMORY_LOCK: with _MEMORY_LOCK:
_MEMORY_STORE.clear() _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: 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: if not workers and "heartbeat_storage_unavailable" not in reasons:
reasons.append("no_worker_heartbeat") 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 = { mount_block_tokens = {
"trigger_dir_not_configured", "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 from app.services.shipping_notice.rpa import upload_queue_dir, upload_trigger_dir
reasons: list[str] = [] reasons: list[str] = []
credential_key = _config_str("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", "") credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "")
if not credential_key: if not credential_key:
reasons.append("credential_key_missing") reasons.append("credential_key_missing")
@@ -46,28 +46,28 @@ def _config_bool(key: str, default: bool) -> bool:
def _alert_enabled() -> bool: def _alert_enabled() -> bool:
if not _heartbeat_check_required(): if not _heartbeat_check_required():
return False 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: 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: def _send_lock_seconds() -> int:
"""企微发送中的短锁 TTL;发送失败过期后可重试,不进入长冷却。""" """企微发送中的短锁 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: 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]: 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 [] names = [part.strip() for part in raw.split(",") if part.strip()] if raw else []
if names: if names:
users = ( users = (
@@ -105,7 +105,7 @@ def _log_recipient_gap_once() -> None:
return return
_RECIPIENT_GAP_LOGGED = True _RECIPIENT_GAP_LOGGED = True
logger.warning( 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)" "or bind wecom_userid for at least one admin (FALLBACK_ADMIN=true)"
) )
@@ -36,7 +36,7 @@ def shipping_recovery_tick() -> int:
# 根据最新 Attempt/Gate 状态刷新按钮与阻断原因。 # 根据最新 Attempt/Gate 状态刷新按钮与阻断原因。
inventory_timeout_seconds = max(int(getattr( inventory_timeout_seconds = max(int(getattr(
current_app.config, current_app.config,
'SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS', 'FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS',
900, 900,
) or 900), 1) ) or 900), 1)
inventory_scan_count = _scan_stale_inventory_attempts( inventory_scan_count = _scan_stale_inventory_attempts(
@@ -83,7 +83,7 @@ def auto_rpa_inventory_enabled() -> bool:
def rpa_inventory_timeout_seconds() -> int: def rpa_inventory_timeout_seconds() -> int:
"""RPA 库存导出等待超时秒数。""" """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: def auto_mapping_allow_llm() -> bool:
+26 -26
View File
@@ -19,7 +19,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSATL01 - BYAWSATL01
@@ -41,7 +41,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSAVP01 - BYAWSAVP01
@@ -62,7 +62,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSAZA01 - BYAWSAZA01
@@ -83,7 +83,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSCMH01 - BYAWSCMH01
@@ -105,7 +105,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSCMN01 - BYAWSCMN01
@@ -127,7 +127,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSEZE01 - BYAWSEZE01
@@ -149,7 +149,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSFRA01 - BYAWSFRA01
@@ -170,7 +170,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSGRU01 - BYAWSGRU01
@@ -191,7 +191,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSIAD01 - BYAWSIAD01
@@ -212,7 +212,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSJAN01 - BYAWSJAN01
@@ -233,7 +233,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSLTN01 - BYAWSLTN01
@@ -254,7 +254,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSMEL01 - BYAWSMEL01
@@ -275,7 +275,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSNRT01 - BYAWSNRT01
@@ -296,7 +296,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSPHX01 - BYAWSPHX01
@@ -317,7 +317,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSPNE01 - BYAWSPNE01
@@ -338,7 +338,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSPRD01 - BYAWSPRD01
@@ -359,7 +359,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSPSC01 - BYAWSPSC01
@@ -380,7 +380,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSQRO01 - BYAWSQRO01
@@ -401,7 +401,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSRIC01 - BYAWSRIC01
@@ -422,7 +422,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSRNO01 - BYAWSRNO01
@@ -443,7 +443,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSRUH01 - BYAWSRUH01
@@ -464,7 +464,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSSBN01 - BYAWSSBN01
@@ -485,7 +485,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSSCL01 - BYAWSSCL01
@@ -506,7 +506,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSYYZ01 - BYAWSYYZ01
@@ -527,7 +527,7 @@ sources:
report_name: On Hand Inventory By Location 3lv report_name: On Hand Inventory By Location 3lv
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: single mode: single
values: values:
- BYAWSZAZ01 - BYAWSZAZ01
@@ -580,7 +580,7 @@ sources:
report_name: On Hand Inventory by Location report_name: On Hand Inventory by Location
parameters: parameters:
- name: Warehouse - name: Warehouse
selector_env: SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR selector_env: FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR
mode: multi_select mode: multi_select
select_all: true select_all: true
selectors: selectors:
+5 -5
View File
@@ -85,8 +85,8 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
return return
app = request.getfixturevalue("app") app = request.getfixturevalue("app")
tmp_path = request.getfixturevalue("tmp_path") 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["FREIGHT_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_TRIGGER_DIR"] = str(
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers" tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
) )
if request.node.get_closest_marker("auto_rpa"): 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_AUTO_UPLOAD_ENABLED"] = False
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
app.config["ENV_NAME"] = "dev" app.config["ENV_NAME"] = "dev"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True 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 from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
reset_rpa_worker_heartbeat_state_for_tests() reset_rpa_worker_heartbeat_state_for_tests()
@@ -158,7 +158,7 @@ def _published_route_field_id() -> str:
def test_profile_credentials_are_not_returned(app): def test_profile_credentials_are_not_returned(app):
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。""" """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(): with app.app_context():
payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
assert payload['password_configured'] is True 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): def test_profile_rejects_page_operation_configuration(app):
"""货代登录连接不得保存报表路径、selector 或下载策略,防止连接越界成为业务配置源。""" """货代登录连接不得保存报表路径、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(): with app.app_context():
payload = _profile_data() payload = _profile_data()
payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}} 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): def test_multiple_dbs_profiles_bind_independent_sources(app):
"""同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。""" """同一 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(): with app.app_context():
first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None) 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) 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): def test_source_rejects_profile_connector_mismatch(app):
"""库存源不能绑定不同 Driver 的 Profile。""" """库存源不能绑定不同 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(): with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None) profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
with pytest.raises(ValidationError) as exc_info: 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): def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
"""禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。""" """禁用库存源允许分步配置;启用时必须补齐 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(): with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None) login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='DRAFT_SOURCE') 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): 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(): with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None) login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='ACTIVATION_SOURCE') 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): 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(): with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None) login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
payload = { 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): 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(): with app.app_context():
profile = shipping_inventory_service.save_profile( profile = shipping_inventory_service.save_profile(
{**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None, {**_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): def test_dbs_source_persists_report_path_parameters_and_aliases(app):
"""数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。""" """数据库库存源必须承载 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(): with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), 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): def test_source_rejects_driver_selector_in_business_parameters(app):
"""业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。""" """业务参数不得保存 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(): with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
payload = _source_data(profile['id']) 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: with pytest.raises(ValidationError) as exc_info:
shipping_inventory_service.save_source(payload, actor_id=None) shipping_inventory_service.save_source(payload, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID' 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): def test_crane_source_rejects_dbs_report_path(app):
"""动态仓 Crane 库存源不得误填 DBS 四级报表路径。""" """动态仓 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(): with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None) 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') 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): 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(): with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7) login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE') 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): 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(): with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None) 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') 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): 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(): with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None) login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE') 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): 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(): with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None) 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) 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): 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(): with app.app_context():
unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None) unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
shipping_inventory_service.delete_profile(unused['id']) 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): def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
"""发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。""" """发布只校验 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(): with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None) 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) 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): 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(): with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), 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): def test_external_mapping_normalizes_freight_warehouse_identity(app):
"""配置端小写货代仓应与库存行大写 Warehouse 使用同一精确映射身份。""" """配置端小写货代仓应与库存行大写 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(): with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
source = shipping_inventory_service.save_source(_source_data(profile['id']), 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): def test_upload_config_change_does_not_bump_rpa_profile_version(app):
"""连接级上传配置(upload_config_json)变更不递增 config_version。""" """连接级上传配置(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(): with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None) profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
base_version = profile['config_version'] base_version = profile['config_version']
@@ -104,7 +104,7 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
"""deps 默认触发器必须真写 trigger 文件,不得只查配置就返回 ok=True(B1 断线根因)。""" """deps 默认触发器必须真写 trigger 文件,不得只查配置就返回 ok=True(B1 断线根因)。"""
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger 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( outcome = _DefaultRpaTrigger().trigger(
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file", source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
) )
+1 -1
View File
@@ -10,7 +10,7 @@ import pytest
def _load_navigation(): 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) spec = importlib.util.spec_from_file_location("crane_navigation_test", module_path)
assert spec and spec.loader assert spec and spec.loader
module = importlib.util.module_from_spec(spec) module = importlib.util.module_from_spec(spec)
+36 -5
View File
@@ -10,7 +10,7 @@ import pytest
def _load_export(): 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) spec = importlib.util.spec_from_file_location("crane_report_export_test", module_path)
assert spec and spec.loader assert spec and spec.loader
module = importlib.util.module_from_spec(spec) module = importlib.util.module_from_spec(spec)
@@ -47,7 +47,7 @@ def test_fill_parameters_skips_warehouse(monkeypatch):
select_or_fill=_fake_select, 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): 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( text = module._build_schedule_description(
{"source_code": "CRANE_TZR2"}, {"source_code": "CRANE_TZR2"},
None, 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 assert len(text) == 16
@@ -148,7 +148,7 @@ def test_should_run_report_before_schedule_uses_driver_environment_only():
assert ( assert (
module._should_run_report_before_schedule( module._should_run_report_before_schedule(
{"navigation": {}}, {"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 is False
) )
@@ -444,7 +444,7 @@ def test_resolve_download_mode_uses_driver_environment_only():
"""下载模式只能由 Driver 环境变量决定。""" """下载模式只能由 Driver 环境变量决定。"""
module = _load_export() 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({"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): def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch):
@@ -596,3 +596,34 @@ def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_p
download_dir=str(tmp_path), download_dir=str(tmp_path),
) )
assert fallback_called["value"] is False assert fallback_called["value"] is False
def test_row_matches_scheduled_report_normalizes_name_form(monkeypatch):
"""行名 InboundDetails.xlsx 与期望名 Inbound Details 应规范化后相等(收料轮询 not found 根因)。"""
module = _load_export()
texts = ["InboundDetails.xlsx", "2026/9/18 22:02:53", "accf9483fabe", "Download"]
class _Cell:
def __init__(self, text):
self._text = text
def inner_text(self, timeout=None):
return self._text
cells = MagicMock()
cells.count.return_value = len(texts)
cells.nth.side_effect = lambda i: _Cell(texts[i])
row = MagicMock()
row.locator.return_value = cells
row.is_visible.return_value = True
assert module._row_matches_scheduled_report(
row, description="accf9483fabe", expected_report_name="Inbound Details"
) is True
# [断言意图] 描述不一致时不得匹配(唯一性由 UUID 保证)
assert module._row_matches_scheduled_report(
row, description="other", expected_report_name="Inbound Details"
) is False
assert module._row_matches_scheduled_report(
row, description="accf9483fabe", expected_report_name="OnHandDetails.xlsx"
) is False
+7 -7
View File
@@ -8,7 +8,7 @@ from unittest.mock import MagicMock
def _load_crane_session(): 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) spec = importlib.util.spec_from_file_location("crane_session_test", module_path)
assert spec and spec.loader assert spec and spec.loader
module = importlib.util.module_from_spec(spec) 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( module.maybe_auto_login_crane(
page, page,
env=lambda name, default="": { env=lambda name, default="": {
"SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME": "crane-user", "FREIGHT_RPA_WORKER_CRANE_USERNAME": "crane-user",
"SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD": "crane-pass", "FREIGHT_RPA_WORKER_CRANE_PASSWORD": "crane-pass",
}.get(name, default), }.get(name, default),
browser_timeout_ms=5_000, browser_timeout_ms=5_000,
) )
assert calls == [ assert calls == [
("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"), ("FREIGHT_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"),
("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"), ("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( locator = module._find_crane_sign_in_button(
page, 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, env=lambda name, default="": default,
browser_timeout_ms=3_000, 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): def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
"""batch 内 session 有效时不应重复 goto + login。""" """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) spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
assert spec and spec.loader assert spec and spec.loader
worker = importlib.util.module_from_spec(spec) worker = importlib.util.module_from_spec(spec)
+5 -5
View File
@@ -1,4 +1,4 @@
"""scripts/rpa/dsv_report_parameters.py 单元测试。""" """scripts/freight_rpa/dsv_report_parameters.py 单元测试。"""
from __future__ import annotations from __future__ import annotations
@@ -7,7 +7,7 @@ from pathlib import Path
def _load_module(): 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) spec = importlib.util.spec_from_file_location("dsv_report_parameters_test", path)
assert spec and spec.loader assert spec and spec.loader
module = importlib.util.module_from_spec(spec) 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( module.fill_dsv_filter_if_needed(
_FakePage(), _FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
"Owner", "Owner",
"CADU-0000000100", "CADU-0000000100",
env=lambda name, default="": default, env=lambda name, default="": default,
@@ -104,7 +104,7 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue():
module.fill_dsv_filter_if_needed( module.fill_dsv_filter_if_needed(
_FakePage(), _FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse", "Warehouse",
"BYAWSATL01", "BYAWSATL01",
env=lambda name, default="": default, 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( module.fill_dsv_filter_if_needed(
_FakePage(), _FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse", "Warehouse",
"RTM", "RTM",
env=lambda name, default="": default, env=lambda name, default="": default,
@@ -99,7 +99,7 @@ def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
with app.app_context(): with app.app_context():
allowed_root = tmp_path / 'receipt-drop' allowed_root = tmp_path / 'receipt-drop'
allowed_root.mkdir() 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 = tmp_path / 'outside.xlsx'
outside.write_bytes(b'not-a-real-xlsx') outside.write_bytes(b'not-a-real-xlsx')
@@ -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 from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
with app.app_context(): 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() 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 * * *') 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() 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 from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
with app.app_context(): 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'}]) written = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'receipt:atomic'}])
assert written is not None assert written is not None
@@ -7,18 +7,18 @@ from pathlib import Path
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract(): def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。""" """收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
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 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text assert 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text assert 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR' in text
assert 'shipping_receipt_rpa.v1' in text assert 'shipping_receipt_rpa.v1' in text
assert '/api/shipping-notice/rpa/receipt-batch-ready' in text assert '/api/shipping-notice/rpa/receipt-batch-ready' in text
assert 'freight_rpa_worker' not 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(): def test_receipt_crane_driver_forces_inbound_details_match_name():
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。""" """收料 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') 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') crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8')
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver 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(): def test_receipt_crane_driver_forces_inbound_details_entry_route():
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。""" """复用 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' module_path = root / 'receipt' / 'receipt_crane_export.py'
sys.path.insert(0, str(root)) sys.path.insert(0, str(root))
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path) 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(): def test_receipt_worker_uses_common_trigger_consumer():
"""收料 Worker 必须复用公共 claim/归档原语,不再自建目录搬移实现。""" """收料 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 'claim_trigger' in text
assert 'archive_trigger' in text assert 'archive_trigger' in text
assert "path.replace(claimed)" not 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(): def test_receipt_worker_logs_full_lifecycle_and_banner():
"""收料 Worker 必须启用文件日志、完整启动 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 'configure_file_logging' in text
assert 'maybe_rotate_open_log' in text assert 'maybe_rotate_open_log' in text
assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段 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(): def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
"""收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。""" """收料 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 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') ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
assert 'SHIPPING_NOTICE_RPA_WORKER_ID' in ps1 and '-receipt' in ps1 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
+8 -8
View File
@@ -10,7 +10,7 @@ from pathlib import Path
def _load_freight_rpa_heartbeat_module(): 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: if str(rpa_dir) not in sys.path:
sys.path.insert(0, str(rpa_dir)) sys.path.insert(0, str(rpa_dir))
module_path = rpa_dir / "common" / "rpa_heartbeat.py" 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): def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
module = _load_freight_rpa_heartbeat_module() 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( payload = module.build_heartbeat_payload(
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers", trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
drop_dir=r"C:\HxopsRpaTest\data\inventory_drop", 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): def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
module = _load_freight_rpa_heartbeat_module() module = _load_freight_rpa_heartbeat_module()
monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False) monkeypatch.delenv("FREIGHT_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.setenv( monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR", "FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
r"C:\HxopsRpaTest\data\inventory_triggers", r"C:\HxopsRpaTest\data\inventory_triggers",
) )
assert module._resolve_shared_scope_id() == "" assert module._resolve_shared_scope_id() == ""
monkeypatch.setenv( monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR", "FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
r"C:\mount\hxops-rpa-test-data\inventory_triggers", r"C:\mount\hxops-rpa-test-data\inventory_triggers",
) )
assert module._resolve_shared_scope_id() == "hxops-rpa-test-data" 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 = tmp_path / "inventory_triggers"
trigger_dir.mkdir() 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") module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01")
sentinel = trigger_dir / ".hxops_rpa_shared_mount" 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 return False
monkeypatch.setattr(module, "post_heartbeat", stalled_post) 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() started = time.monotonic()
sent_at = module.maybe_send_heartbeat( sent_at = module.maybe_send_heartbeat(
trigger_dir=tmp_path, trigger_dir=tmp_path,
+151 -112
View File
@@ -1,4 +1,4 @@
"""scripts/rpa/freight_rpa_worker.py tests. """scripts/freight_rpa/freight_rpa_worker.py tests.
覆盖货代 RPA worker 对真实库存导出 trigger JSON 的消费路径: 覆盖货代 RPA worker 对真实库存导出 trigger JSON 的消费路径:
1. 读取 inventory_export_SN-20260629-2EDADC77.json。 1. 读取 inventory_export_SN-20260629-2EDADC77.json。
@@ -15,6 +15,7 @@ import os
import re import re
import sys import sys
import time import time
import warnings
from pathlib import Path from pathlib import Path
import pytest import pytest
@@ -27,7 +28,7 @@ def _repo_root() -> Path:
def _load_freight_rpa_worker(): 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) spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path)
assert spec is not None assert spec is not None
assert spec.loader 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], "inventory_sources": [source],
}), encoding="utf-8") }), encoding="utf-8")
callbacks: list[tuple[str, dict]] = [] 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))) monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) 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], "inventory_sources": [source],
}), encoding="utf-8") }), encoding="utf-8")
callbacks: list[tuple[str, dict]] = [] 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))) monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) 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") }), encoding="utf-8")
callbacks: list[tuple[str, dict]] = [] 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))) monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) 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") }), encoding="utf-8")
callbacks: list[tuple[str, dict]] = [] 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))) monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
@@ -432,11 +433,11 @@ def test_env_strips_wrapping_quotes(monkeypatch):
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。""" """RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
worker = _load_freight_rpa_worker() worker = _load_freight_rpa_worker()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", '"user@example.com"') monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", '"user@example.com"')
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "'secret-pass'") monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "'secret-pass'")
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "user@example.com" assert worker._env("FREIGHT_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_PASSWORD") == "secret-pass"
def test_worker_accepts_business_connector_without_site_id(): 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 clock['value'] += 3.0
return clock['value'] 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, 'monotonic', monotonic)
monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None) monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None)
monkeypatch.setattr(session, '_debug_dsv_stage', lambda *_args, **_kwargs: 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() worker = _load_freight_rpa_worker()
session = worker.dsv_session session = worker.dsv_session
import dsv_auth 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: class _Page:
url = 'https://auth.dbschenker.com/as/authorization.ping' 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() worker = _load_freight_rpa_worker()
key = Fernet.generate_key() key = Fernet.generate_key()
cipher = Fernet(key) cipher = Fernet(key)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", key.decode("ascii")) monkeypatch.setenv("FREIGHT_RPA_CREDENTIAL_KEY", key.decode("ascii"))
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", raising=False) monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_USERNAME", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", raising=False) monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", raising=False)
monkeypatch.delenv("FREIGHT_RPA_DSV_USERNAME", raising=False) monkeypatch.delenv("FREIGHT_RPA_DSV_USERNAME", raising=False)
monkeypatch.delenv("FREIGHT_RPA_DSV_PASSWORD", raising=False) monkeypatch.delenv("FREIGHT_RPA_DSV_PASSWORD", raising=False)
source = { source = {
@@ -582,39 +583,35 @@ def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
}, },
} }
with worker._profile_credentials(source): with worker._profile_credentials(source):
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "test-user" assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "test-user"
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "test-password" assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "test-password"
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "" assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == ""
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "" assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == ""
def test_worker_prefers_canonical_rpa_env_over_legacy_name(monkeypatch): def test_worker_ignores_legacy_rpa_name_without_compat(monkeypatch):
"""新旧 RPA 变量同时存在时必须使用统一的新命名空间,避免旧部署值覆盖新配置。""" """无兼容层:历史旧名(FREIGHT_RPA_MOCK)不作为 FREIGHT_RPA_WORKER_MOCK 的回退,也不发弃用警告。"""
worker = _load_freight_rpa_worker() 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") monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "false" with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
# 断言 1:仅设置历史旧名时,规范名直读为空、带默认值读回默认值(旧名不被咨询)。
def test_worker_reads_legacy_rpa_env_during_migration(monkeypatch): assert worker._env("FREIGHT_RPA_WORKER_MOCK") == ""
"""规范变量缺失时允许读取旧名称,保障 Windows Worker 分阶段迁移不中断。""" assert worker._env("FREIGHT_RPA_WORKER_MOCK", "false") == "false"
worker = _load_freight_rpa_worker() # 断言 2:读取过程不产生任何 DeprecationWarning(兼容层已删除)。
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", raising=False) assert not any(issubclass(item.category, DeprecationWarning) for item in caught)
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"
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys): 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 模块,本用例改测公共接口。
worker_logging = _load_worker_logging() worker_logging = _load_worker_logging()
log_path = tmp_path / "logs" / "worker.log" log_path = tmp_path / "logs" / "worker.log"
timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ") 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_stdout = sys.stdout
original_stderr = sys.stderr 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): 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 模块,本用例改测公共接口。
worker_logging = _load_worker_logging() worker_logging = _load_worker_logging()
log_path = tmp_path / "worker.log" log_path = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8") log_path.write_text("current-log", encoding="utf-8")
Path(f"{log_path}.1").write_text("old-1", 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("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2") monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2")
worker_logging.rotate_log_file_if_needed(log_path) 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 = tmp_path / "worker.log"
log_path.write_text("current-log", encoding="utf-8") log_path.write_text("current-log", encoding="utf-8")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1") monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0") monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "0")
worker_logging.rotate_log_file_if_needed(log_path) 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(): def _load_worker_logging():
"""加载 scripts/rpa/common/worker_logging.py 供单测直接断言。 """加载 scripts/freight_rpa/common/worker_logging.py 供单测直接断言。
历史背景:文件日志实现(tee/轮转/时间戳)原内置于 inventory_rpa_worker.py, 历史背景:文件日志实现(tee/轮转/时间戳)原内置于 inventory_rpa_worker.py,
已提取为公共模块;Worker 内部私有名(_configure_file_logging 等)已删除, 已提取为公共模块;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: if str(common_dir) not in sys.path:
sys.path.insert(0, str(common_dir)) sys.path.insert(0, str(common_dir))
module_path = common_dir / "worker_logging.py" module_path = common_dir / "worker_logging.py"
@@ -700,8 +697,8 @@ def _load_worker_logging():
def _load_worker_disk_cleanup(): def _load_worker_disk_cleanup():
"""加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。""" """加载 scripts/freight_rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
module_path = _repo_root() / "scripts" / "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) spec = importlib.util.spec_from_file_location("worker_disk_cleanup_under_test", module_path)
assert spec is not None assert spec is not None
assert spec.loader 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") (orphan_run / "Cookies").write_text("drop", encoding="utf-8")
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600))) os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "7") monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "7")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
stats = cleanup.run_worker_disk_cleanup( stats = cleanup.run_worker_disk_cleanup(
inventory_trigger_dir=inv_trigger, inventory_trigger_dir=inv_trigger,
@@ -835,8 +832,8 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
orphan_run.mkdir() orphan_run.mkdir()
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600))) os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "0") monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "0")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
cleanup.run_worker_disk_cleanup( cleanup.run_worker_disk_cleanup(
inventory_trigger_dir=inv_trigger, 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 assert stats.deleted_dirs == 1
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch): def test_open_browser_uses_freight_rpa_common_profile_fallback(monkeypatch):
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。""" """未配置 profile 根目录时,应回退到 freight_rpa/common 布局的 browser_profile。"""
worker = _load_freight_rpa_worker() worker = _load_freight_rpa_worker()
observed: dict[str, object] = {} observed: dict[str, object] = {}
@@ -906,12 +903,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
def start(self): def start(self):
return _FakePlaywright() return _FakePlaywright()
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False) monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false") monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true") monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False) monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
temp_roots: list[Path] = [] temp_roots: list[Path] = []
@@ -930,7 +926,8 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
assert context is not None assert context is not None
assert page 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 temp_roots == [expected_root]
assert runtime_profile_dir == expected_root / "run_unit" assert runtime_profile_dir == expected_root / "run_unit"
assert runtime_profile_dir.parent == expected_root 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 根目录解析。""" """profile 根目录配置为 data/shipping_notice 时,应按 backend 根目录解析。"""
worker = _load_freight_rpa_worker() worker = _load_freight_rpa_worker()
monkeypatch.setenv( monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
"data/shipping_notice/freight_rpa/browser_profile", "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() assert worker._browser_profile_root() == expected.resolve()
def test_browser_profile_root_remaps_legacy_freight_rpa_path(monkeypatch): def test_browser_profile_root_keeps_freight_rpa_layout_without_remap(monkeypatch, capsys):
"""本机残留旧 profile 路径时,应强制迁到 shipping_notice 命名空间。""" """profile 配置为 freight_rpa 布局路径时,应按字面解析:不改写、不告警(无兼容层红线)。"""
worker = _load_freight_rpa_worker() worker = _load_freight_rpa_worker()
monkeypatch.setenv( monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
"backend/data/freight_rpa/browser_profile", "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() 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): def test_browser_profile_root_keeps_absolute_freight_rpa_layout_without_remap(monkeypatch, capsys):
"""本机环境变量保存绝对旧路径时,也应迁到 shipping_notice 命名空间。""" """绝对 freight_rpa 路径同样按字面解析,证明 remap 分支已完全移除。"""
worker = _load_freight_rpa_worker() worker = _load_freight_rpa_worker()
monkeypatch.setenv( profile_dir = _repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(profile_dir))
str(_repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"),
)
expected = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile" # 断言意图:绝对路径不再被强制迁往 shipping_notice 命名空间
assert worker._browser_profile_root() == profile_dir.resolve()
assert worker._browser_profile_root() == expected.resolve() # 断言意图:不得再输出 legacy 改写告警
assert "legacy" not in capsys.readouterr().out
def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path): 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") out_file.write_bytes(b"fake inventory content")
return out_file 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, "_download_inventory_with_browser", fake_download_inventory_with_browser)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) 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" processed_dir = trigger_dir / "processed"
callbacks: list[tuple[str, dict]] = [] callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true") monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY", raising=False) monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir) 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): def raise_no_inventory(_trigger: dict, _drop: Path):
raise worker.NoInventoryDataError("DSV report has no inventory data") 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, "_download_inventory_with_browser", raise_no_inventory)
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload))) 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() worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx" workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test") 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"): 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}}) 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() worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx" workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test") workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true") monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true") monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
events: list[tuple[str, object]] = [] events: list[tuple[str, object]] = []
class _Locator: class _Locator:
@@ -1245,7 +1244,7 @@ def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
runtime_profile = tmp_path / "profile" runtime_profile = tmp_path / "profile"
runtime_profile.mkdir() runtime_profile.mkdir()
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url))) 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): 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": "<div/>", "dom_sha256": "abc"}} 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": "<div/>", "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() worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx" workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test") workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true") monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true") monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
events: list[tuple[str, object]] = [] events: list[tuple[str, object]] = []
class _Locator: 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 = tmp_path / "profile"
runtime_profile.mkdir() runtime_profile.mkdir()
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url))) 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": {}}) monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda _page, _filename: {"reference": "", "success_evidence": {}})
assert worker._upload_shipment_with_browser( assert worker._upload_shipment_with_browser(
@@ -1406,7 +1405,7 @@ def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch):
return clock["value"] return clock["value"]
monkeypatch.setattr(worker.time, "monotonic", monotonic) 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"): with pytest.raises(RuntimeError, match="did not confirm a green success status"):
worker._wait_for_dsv_upload_history_receipt(_Page(), "shipment.xlsx") 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", "task_no": "SN-UPLOAD-FAIL", "file_path": str(queue_file), "attempt_id": 8, "callback_id": "rpa:8",
}), encoding="utf-8") }), encoding="utf-8")
callbacks: list[tuple[str, dict]] = [] 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, "_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))) 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", "task_no": "SN-UPLOAD-EMPTY", "attempt_id": 9, "callback_id": "rpa:9",
}), encoding="utf-8") }), encoding="utf-8")
callbacks: list[tuple[str, dict]] = [] 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))) monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed") 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): def start(self):
return _FakePlaywright() return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false") monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge") monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", "msedge")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False) monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads") _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): def start(self):
return _FakePlaywright() return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true") monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true")
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, profile_dir = worker._open_browser( _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): def start(self):
return _FakePlaywright() return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile")) monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true") monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true")
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object)) monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, profile_dir = worker._open_browser( _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): def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch):
"""登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。""" """登录后 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) 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 assert spec is not None and spec.loader is not None
dsv_report_export = importlib.util.module_from_spec(spec) 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( worker._fill_dsv_filter_if_needed(
_FakePage(), _FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
"Owner", "Owner",
"CADU-0000000100", "CADU-0000000100",
) )
@@ -2466,7 +2463,7 @@ def test_fill_dsv_filter_if_needed_accepts_report_name_kwarg():
worker._fill_dsv_filter_if_needed( worker._fill_dsv_filter_if_needed(
_FakePage(), _FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
"Owner", "Owner",
"CADU-0000000100", "CADU-0000000100",
report_name="On Hand Inventory by Location", report_name="On Hand Inventory by Location",
@@ -2622,26 +2619,26 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
""" """
手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。 手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。
默认跳过;仅当 SHIPPING_NOTICE_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码: 默认跳过;仅当 FREIGHT_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码:
- SHIPPING_NOTICE_RPA_WORKER_MOCK=false - FREIGHT_RPA_WORKER_MOCK=false
- SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false(建议首次调试) - FREIGHT_RPA_WORKER_HEADLESS=false(建议首次调试)
- SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录> - FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
- SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD - FREIGHT_RPA_WORKER_DSV_USERNAME / FREIGHT_RPA_WORKER_DSV_PASSWORD
""" """
if str(os.getenv("SHIPPING_NOTICE_RPA_WORKER_E2E") or "").strip().lower() != "true": if str(os.getenv("FREIGHT_RPA_WORKER_E2E") or "").strip().lower() != "true":
pytest.skip("set SHIPPING_NOTICE_RPA_WORKER_E2E=true to run real freight RPA export") pytest.skip("set FREIGHT_RPA_WORKER_E2E=true to run real freight RPA export")
worker = _load_freight_rpa_worker() worker = _load_freight_rpa_worker()
trigger = _build_inventory_export_trigger("SN-20260629-2EDADC77") trigger = _build_inventory_export_trigger("SN-20260629-2EDADC77")
drop_dir = tmp_path / "drop" drop_dir = tmp_path / "drop"
drop_dir.mkdir() drop_dir.mkdir()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS"): if not os.getenv("FREIGHT_RPA_WORKER_HEADLESS"):
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false")
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR"): if not os.getenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR"):
monkeypatch.setenv( monkeypatch.setenv(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
str(tmp_path / "browser_profile"), 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.parent == drop_dir
assert out_file.suffix.lower() in {".xlsx", ".xls", ".csv"} assert out_file.suffix.lower() in {".xlsx", ".xls", ".csv"}
assert out_file.stat().st_size > 0 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"]
@@ -34,7 +34,7 @@ _RPA_MODULE_PATHS = {
def _load_rpa_module(module_name: str): def _load_rpa_module(module_name: str):
rel = _RPA_MODULE_PATHS.get(module_name, f"{module_name}.py") 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) scripts_dir = str(module_path.parent)
if scripts_dir not in sys.path: if scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir) sys.path.insert(0, scripts_dir)
@@ -59,12 +59,12 @@ def test_fill_report_parameter_multi_select(monkeypatch):
page, page,
{ {
"name": "Warehouse", "name": "Warehouse",
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"mode": "multi_select", "mode": "multi_select",
"values": ["WH1", "WH2"], "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): 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 == [ assert calls == [
{ {
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"label": "Warehouse", "label": "Warehouse",
"values": ["RTM"], "values": ["RTM"],
"selectors": None, "selectors": None,
@@ -136,7 +136,7 @@ def test_fill_report_parameter_multi_select_jda_report_passes_template_selectors
) )
assert calls == [ assert calls == [
{ {
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"label": "Warehouse", "label": "Warehouse",
"values": ["RTM"], "values": ["RTM"],
"selectors": None, "selectors": None,
@@ -418,8 +418,8 @@ def test_dsv_existing_portal_session_skips_all_auth_probes(monkeypatch):
"""持久化 Profile 已恢复 Portal 时,不得先等待用户名或认证页面。""" """持久化 Profile 已恢复 Portal 时,不得先等待用户名或认证页面。"""
flow = _load_dsv_auth_login_flow() flow = _load_dsv_auth_login_flow()
page = MagicMock() page = MagicMock()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "user") monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", "user")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "password") monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "password")
selector_wait = MagicMock() selector_wait = MagicMock()
auth_ready = MagicMock() auth_ready = MagicMock()
monkeypatch.setattr(flow, "_has_existing_dsv_portal_session", lambda _page: True) monkeypatch.setattr(flow, "_has_existing_dsv_portal_session", lambda _page: True)
+1 -1
View File
@@ -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。""" """POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。"""
trigger_dir = tmp_path / "triggers" trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir() 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(): with app.app_context():
from app import db from app import db
@@ -126,7 +126,7 @@ def _published_template(*, code: str) -> ShippingExcelTemplate:
def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path): 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_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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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 = tmp_path / 'inventory_drop'
drop_dir.mkdir() drop_dir.mkdir()
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') 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')
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(), patch( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。""" """已绑定发布方案的空库存结果是有效连接证据,不能被误写为 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
) as write_trigger: ) 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): 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path):
"""Worker 领取回调只更新本批次当前运行,终态运行不得被重新打开。""" """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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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_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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
"""RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。""" """RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') 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')
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1 app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
with app.app_context(), patch( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
"""同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。""" """同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10 app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
with app.app_context(), patch( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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_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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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_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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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_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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', '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): 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_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( with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json', 'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
): ):
@@ -114,7 +114,7 @@ def _excel_template_id() -> int:
def test_published_parsing_profile_can_be_shared_by_sources(app): def test_published_parsing_profile_can_be_shared_by_sources(app):
"""同一 published Profile 应可绑定多个库存源,避免重复维护相同模板。""" """同一 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(): with app.app_context():
parsing = _published_profile() parsing = _published_profile()
login = shipping_inventory_service.save_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): def test_source_rejects_draft_parsing_profile(app):
"""库存源只能绑定 published Profile,避免运行期读取可变草稿。""" """库存源只能绑定 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(): with app.app_context():
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None) 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) 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): def test_new_published_version_does_not_retire_bound_version(app):
"""发布新版本不得使现有库存源绑定的旧 published 版本失效。""" """发布新版本不得使现有库存源绑定的旧 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(): with app.app_context():
first = _published_profile() first = _published_profile()
field_id = order_schema_service.get_state()['fields'][0]['id'] 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): def test_referenced_published_profile_cannot_be_retired(app):
"""已绑定库存源的解析 Profile 必须先迁移 Source,不能直接退役。""" """已绑定库存源的解析 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(): with app.app_context():
parsing = _published_profile() parsing = _published_profile()
login = shipping_inventory_service.save_profile({ login = shipping_inventory_service.save_profile({
@@ -12,7 +12,7 @@ from pathlib import Path
def _load_worker(): def _load_worker():
module_path = ( 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) scripts_dir = str(module_path.parent)
if scripts_dir not in sys.path: if scripts_dir not in sys.path:
+34
View File
@@ -0,0 +1,34 @@
"""
tests/test_ot_inline_edit.py
用途:验证通知准备阶段(Notice 未建、仅 OT)的就地编辑全链路。
依赖:pytest、task_workflow.update_notice_line、effective_order_view、有效视图夹具。
逻辑:复现"FORMAL_NOTICE_REQUIRED"报错场景——OT task_no 直接走 update-notice-line 通道,
编辑后有效值立即可见(库存匹配/Excel/通知行的统一读取口径)。
"""
from __future__ import annotations
from app.services.shipping_notice.effective_order_view import effective_order_field_values
from app.services.shipping_notice.task_workflow import update_notice_line
from tests.test_effective_order_view import _seed_frozen_order
def test_update_notice_line_accepts_order_task_before_notice(app):
"""通知准备阶段(无 Notice)编辑 OT 行字段必须成功且进入有效视图。"""
with app.app_context():
fixture = _seed_frozen_order()
response = update_notice_line({
'task_id': fixture.order.task_no,
'line_index': 0,
'patch': {'part_number': 'D4-A08AR12000002'},
'event_source': 'workspace_api',
'reviewed_by_id': fixture.user.id,
'expected_order_data_version': int(fixture.order.order_data_version or 1),
})
# 断言:服务层对 OT 放行(修复前 API 层 _require_formal_notice 报 FORMAL_NOTICE_REQUIRED)。
assert response['status'] == 'ok'
_header, lines = effective_order_field_values(fixture.order)
# 断言:编辑后的料号进入有效视图(重新匹配库存的读取口径),旧值不再出现。
assert lines[0]['f-part'] == 'D4-A08AR12000002'
assert lines[1]['f-part'] == 'D4-B07BR07000001'
+4 -4
View File
@@ -13,7 +13,7 @@ from pathlib import Path
import pytest 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 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): def test_inventory_worker_scans_with_claim(tmp_path):
"""库存 Worker 扫描必须先领取(processing/),不得原地消费根目录文件。""" """库存 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") text = (root / "inventory_rpa_worker.py").read_text(encoding="utf-8")
assert "claim_trigger" in text assert "claim_trigger" in text
# 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent # 三处 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(): def test_receipt_worker_runs_periodic_disk_cleanup():
"""收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。""" """收料 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 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 assert '"receipt_"' in cleanup or "'receipt_'" in cleanup
+59 -39
View File
@@ -67,12 +67,12 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d
trigger_dir.mkdir() trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id=scope_id) _write_shared_sentinel(trigger_dir, scope_id=scope_id)
app.config["ENV_NAME"] = "test" app.config["ENV_NAME"] = "test"
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_RPA_SHARED_SCOPE_ID"] = scope_id app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
return trigger_dir 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 = tmp_path / "triggers"
trigger_dir.mkdir() trigger_dir.mkdir()
app.config["ENV_NAME"] = "test" app.config["ENV_NAME"] = "test"
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_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data" app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
with app.app_context(): with app.app_context():
record_rpa_worker_heartbeat( record_rpa_worker_heartbeat(
@@ -154,9 +154,9 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
"""生产策略要求 Redis 时,写入失败应抛存储不可用。""" """生产策略要求 Redis 时,写入失败应抛存储不可用。"""
trigger_dir = tmp_path / "triggers" trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir() 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)
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
monkeypatch.setattr( monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker", "app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
lambda _worker: False, 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 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 详情供排程日志与运维定位。""" """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 = tmp_path / "triggers"
trigger_dir.mkdir() trigger_dir.mkdir()
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data") _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config["ENV_NAME"] = "test" app.config["ENV_NAME"] = "test"
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_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data" app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
with app.app_context(): with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info: with pytest.raises(ServiceUnavailableError) as exc_info:
assert_inventory_rpa_worker_ready() assert_inventory_rpa_worker_ready()
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE 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") 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 import time as time_module
trigger_dir = _enable_prod_like_checks(app, tmp_path) 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() base_now = time_module.time()
with app.app_context(): 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 = tmp_path / "triggers"
trigger_dir.mkdir() trigger_dir.mkdir()
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key" 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())) payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
res = client.post( res = client.post(
@@ -258,11 +270,19 @@ def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
assert res.status_code == 401 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。""" """排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
from app import db from app import db
from app.models import ScheduleRun, ScheduleTask, User from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule 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) 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): def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_path, monkeypatch):
"""Redis 读取异常应报 heartbeat_storage_unavailable,而非 no_worker_heartbeat。""" """Redis 读取异常应报 heartbeat_storage_unavailable,而非 no_worker_heartbeat。"""
trigger_dir = _enable_prod_like_checks(app, tmp_path) trigger_dir = _enable_prod_like_checks(app, tmp_path)
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
class BrokenRedis: class BrokenRedis:
def smembers(self, _key): 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): def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch):
"""test/prod Redis 策略:写入+读取成功时应 ready。""" """test/prod Redis 策略:写入+读取成功时应 ready。"""
trigger_dir = _enable_prod_like_checks(app, tmp_path) trigger_dir = _enable_prod_like_checks(app, tmp_path)
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
bucket: dict[str, Any] = {"index": set()} bucket: dict[str, Any] = {"index": set()}
class FakeRedis: 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 = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
trigger_dir.mkdir(parents=True) trigger_dir.mkdir(parents=True)
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data") _write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
app.config.pop("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", None) app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None)
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(): with app.app_context():
assert shared_scope_id() == "hxops-rpa-test-data" 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() upload_queue.mkdir()
_write_shared_sentinel(upload_trigger, scope_id=scope_id) _write_shared_sentinel(upload_trigger, scope_id=scope_id)
app.config["ENV_NAME"] = "test" app.config["ENV_NAME"] = "test"
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger) app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue) app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE=" app.config["FREIGHT_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052" app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052"
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
return upload_trigger 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) _enable_freight_upload_checks(app, tmp_path)
# 去掉凭据主密钥:即使 Redis 残留心跳,静态配置缺失也必须阻断。 # 去掉凭据主密钥:即使 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() reset_rpa_worker_heartbeat_state_for_tests()
with app.app_context(): with app.app_context():
with pytest.raises(ServiceUnavailableError) as exc_info: with pytest.raises(ServiceUnavailableError) as exc_info:
@@ -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 = tmp_path / "triggers"
trigger_dir.mkdir() trigger_dir.mkdir()
app.config["ENV_NAME"] = "test" app.config["ENV_NAME"] = "test"
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_RPA_SHARED_SCOPE_ID"] = scope_id app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED"] = True app.config["FREIGHT_RPA_WORKER_ALERT_ENABLED"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600 app.config["FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS"] = 3600
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES"] = "" app.config["FREIGHT_RPA_WORKER_ALERT_USERNAMES"] = ""
app.config["SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false" app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
return trigger_dir return trigger_dir
@@ -188,7 +188,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch
import logging import logging
_enable_alert_checks(app, tmp_path) _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( monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready", "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): def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatch):
"""显式配置的用户名优先于 admin 回退。""" """显式配置的用户名优先于 admin 回退。"""
_enable_alert_checks(app, tmp_path) _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(): with app.app_context():
from app import db 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): def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
"""过期 sending 锁且 sending_target=offline 时,Worker 恢复后应发送恢复通知。""" """过期 sending 锁且 sending_target=offline 时,Worker 恢复后应发送恢复通知。"""
_enable_alert_checks(app, tmp_path) _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 = { stale_sending = {
"status": _STATUS_SENDING, "status": _STATUS_SENDING,
+6 -6
View File
@@ -2,7 +2,7 @@
用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、 用途:锁定 Worker 文件日志行为——tee 落盘带时间戳、stdout 同时可见、
按大小轮转滚动备份、shutdown 恢复标准流。 按大小轮转滚动备份、shutdown 恢复标准流。
依赖:标准库 + scripts/rpa/common/worker_logging。 依赖:标准库 + scripts/freight_rpa/common/worker_logging。
逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。 逻辑:直接驱动公共函数,monkeypatch 环境变量与恢复标准流,不启动真实 Worker。
""" """
@@ -13,7 +13,7 @@ from pathlib import Path
import pytest 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 from worker_logging import ( # noqa: E402
WorkerLogTee, 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): def test_rotate_rolls_backups_and_drops_oldest(tmp_path, monkeypatch):
"""超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。""" """超过 max_bytes 时按 .1/.2 滚动,超过 backup_count 的最旧备份删除。"""
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "10") monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "10")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2") monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2")
path = tmp_path / "worker.log" path = tmp_path / "worker.log"
for round_no in range(3): for round_no in range(3):
path.write_text(f"round-{round_no}-padding", encoding="utf-8") 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): def test_configure_file_logging_enables_tee_and_shutdown_restores(tmp_path, monkeypatch, capsys):
"""configure 启用落盘、print 双写;shutdown 恢复标准流且不再写文件。""" """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() enabled = configure_file_logging()
assert enabled == tmp_path / "logs" / "worker.log" assert enabled == tmp_path / "logs" / "worker.log"
assert enabled.parent.is_dir() # 日志目录自动创建 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): def test_configure_without_env_is_noop(monkeypatch):
"""未配置 LOG_FILE 时 configure 返回 None 且不改标准流。""" """未配置 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 assert configure_file_logging() is None
@@ -135,7 +135,7 @@ def _confirm_direct_rpa_task_customer(task: ShippingOrderTask) -> None:
def test_encrypt_credential_round_trip_requires_runtime_key(app): 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(): with app.app_context():
ciphertext = encrypt_credential('not-a-real-password') ciphertext = encrypt_credential('not-a-real-password')
assert ciphertext != '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): 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): with app.app_context(), pytest.raises(ServiceUnavailableError):
encrypt_credential('not-a-real-password') encrypt_credential('not-a-real-password')
@@ -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): def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path):
"""finalize 预生成应落盘 ZIP 并返回 summary 字段。""" """finalize 预生成应落盘 ZIP 并返回 summary 字段。"""
archive_dir = tmp_path / "inventory_archives" 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 = tmp_path / "inventory.xlsx"
xlsx.write_bytes(b"fake-xlsx-content") 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): def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
"""无可读快照时不生成 ZIP。""" """无可读快照时不生成 ZIP。"""
archive_dir = tmp_path / "inventory_archives" 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(): with app.app_context():
run = _make_inventory_run_with_created( 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): def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp_path):
"""created 有记录但磁盘文件缺失时不应生成 ZIP。""" """created 有记录但磁盘文件缺失时不应生成 ZIP。"""
archive_dir = tmp_path / "inventory_archives" 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(): with app.app_context():
run = _make_inventory_run_with_created( 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): def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path):
"""下载解析应返回归档路径与建议文件名。""" """下载解析应返回归档路径与建议文件名。"""
archive_dir = tmp_path / "inventory_archives" 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 = tmp_path / "inventory.xlsx"
xlsx.write_bytes(b"fake-xlsx-content") 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): def test_resolve_inventory_raw_zip_download_rejects_path_outside_archive_dir(app, tmp_path):
"""summary 指向归档目录外的真实文件时必须 404。""" """summary 指向归档目录外的真实文件时必须 404。"""
archive_dir = tmp_path / "inventory_archives" 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 = tmp_path / "outside.zip"
outside_zip.write_bytes(b"fake-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。""" """summary 指向非 .zip 后缀文件时必须 404。"""
archive_dir = tmp_path / "inventory_archives" archive_dir = tmp_path / "inventory_archives"
archive_dir.mkdir(parents=True) 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 = archive_dir / "RUN-ARCH-RESOLVE-BAD.txt"
fake_file.write_bytes(b"not-a-zip") 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_NOTIFY_ENABLED"] = True
app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com" app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com"
app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/" 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( user = User(
username="wecom_jump_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。""" """admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。"""
archive_dir = tmp_path / "inventory_archives" 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 = tmp_path / "inventory.xlsx"
xlsx.write_bytes(b"fake-xlsx-content") xlsx.write_bytes(b"fake-xlsx-content")
@@ -641,7 +641,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
drop_dir = tmp_path / "drop" drop_dir = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_mixed.xlsx" 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory-mapping-confirmed.xlsx" sample = drop_dir / "inventory-mapping-confirmed.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "batch_task_success.xlsx" 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 = tmp_path / "drop"
drop_dir.mkdir() drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") 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(): with app.app_context():
task = ShippingOrderTask( 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 = tmp_path / "drop"
drop_dir.mkdir() drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") 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 = drop_dir / "crane-multi-warehouse.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("CRANE-WH").getvalue()) 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 = tmp_path / "drop"
drop_dir.mkdir() drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") 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 = drop_dir / "crane-unresolved-link.xlsx"
sample.write_bytes( sample.write_bytes(
inventory_xlsx_with_warehouse( 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "orphan_task.xlsx" sample = drop_dir / "orphan_task.xlsx"
with open(sample, "wb") as handle: 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(): with app.app_context():
trigger_dir = tmp_path / 'inventory_triggers' 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( monkeypatch.setattr(
'app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready', 'app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready',
lambda: (_ for _ in ()).throw(AssertionError('trigger write must not require worker heartbeat')), 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "reuse_ingest_fail.xlsx" sample = drop_dir / "reuse_ingest_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
run_no = "RUN-REUSE-MISMATCH" 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 = tmp_path / "drop"
drop_dir.mkdir(parents=True, exist_ok=True) drop_dir.mkdir(parents=True, exist_ok=True)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") 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_a = drop_dir / "task_a.xlsx"
sample_b = drop_dir / "task_b.xlsx" sample_b = drop_dir / "task_b.xlsx"
sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) 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 = tmp_path / "drop"
drop_dir.mkdir(parents=True, exist_ok=True) drop_dir.mkdir(parents=True, exist_ok=True)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") 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 = drop_dir / "failed_before_confirm.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
callback_calls: list[dict] = [] 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 = tmp_path / "drop"
drop_dir.mkdir() drop_dir.mkdir()
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") 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 = drop_dir / "shared.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
run_no = "RUN-SHARED-LINK" 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "post_commit.xlsx" sample = drop_dir / "post_commit.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "promote_fail.xlsx" sample = drop_dir / "promote_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "move_fail.xlsx" sample = drop_dir / "move_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "quarantine_fail.xlsx" sample = drop_dir / "quarantine_fail.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) 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" processed_dir = tmp_path / "processed"
drop_dir.mkdir() drop_dir.mkdir()
processed_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) app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir)
quarantine = drop_dir / ".hxops_quarantine" quarantine = drop_dir / ".hxops_quarantine"
@@ -103,7 +103,7 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
"""排程 executor 应写入 inventory_export_batch trigger。""" """排程 executor 应写入 inventory_export_batch trigger。"""
trigger_dir = tmp_path / "triggers" trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir() 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(): with app.app_context():
task = _make_inventory_schedule_task( 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。""" """run_task_now 写 trigger 后应保持 running 且 awaiting_rpa=true。"""
trigger_dir = tmp_path / "triggers" trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir() 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(): with app.app_context():
task = _make_inventory_schedule_task( 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,避免立即超时回收。""" """复用无 started_at 的 run 时,defer 应补写 started_at,避免立即超时回收。"""
trigger_dir = tmp_path / "triggers" trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir() 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(): with app.app_context():
task = _make_inventory_schedule_task( 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。""" """全部 source 成功但 Excel 导出失败时应降为 partial_failed 并写入 error_message。"""
drop_dir = tmp_path / "drop" drop_dir = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_excel_fail.xlsx" 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(需人工/接口重试)。""" """finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。"""
drop_dir = tmp_path / "drop" drop_dir = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_fail_finalize.xlsx" 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() drop_dir.mkdir()
processed_dir = drop_dir / "processed" processed_dir = drop_dir / "processed"
processed_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["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_sample.xlsx" sample = drop_dir / "inventory_sample.xlsx"
@@ -516,7 +516,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
"""回调结果少于触发源数时,排程应 partial_failed。""" """回调结果少于触发源数时,排程应 partial_failed。"""
drop_dir = tmp_path / "drop" drop_dir = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory_partial.xlsx" 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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "missing_warehouse.xlsx" sample = drop_dir / "missing_warehouse.xlsx"
_write_sample_inventory(sample, "AWSDU") _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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "retry_snapshot.xlsx" sample = drop_dir / "retry_snapshot.xlsx"
_write_sample_inventory(sample, "AWSDU") _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 = tmp_path / "drop"
drop_dir.mkdir() 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") app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "retry_move.xlsx" sample = drop_dir / "retry_move.xlsx"
_write_sample_inventory(sample, "AWSDU") _write_sample_inventory(sample, "AWSDU")
@@ -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): def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch):
"""batch 开启时单票按需应写 inventory_export_batch trigger。""" """batch 开启时单票按需应写 inventory_export_batch trigger。"""
trigger_dir = tmp_path / "triggers" 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) app.config.pop("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", None)
monkeypatch.setenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true") 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 from app.core.errors import ValidationError
trigger_dir = tmp_path / "triggers" 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 app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}} 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 from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
trigger_dir = tmp_path / "triggers" 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(): with app.app_context():
path = write_inventory_export_batch_trigger("RUN-DBS", [{ path = write_inventory_export_batch_trigger("RUN-DBS", [{
"source_code": "UNKNOWN_FOR_TEST", "connector_type": "dbs", "rpa_profile_code": "DBS_TEST", "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 from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
trigger_dir = tmp_path / "triggers" 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 app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
source = { source = {
"source_code": "DBS", "source_code": "DBS",
+2 -2
View File
@@ -459,8 +459,8 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
headers = _tool_headers(app) headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers" trigger = tmp_path / "inventory_triggers"
trigger.mkdir() trigger.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger) app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1 app.config["FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
monkeypatch.setattr( monkeypatch.setattr(
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready", "app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
lambda: None, lambda: None,
+1 -3
View File
@@ -172,8 +172,6 @@ services:
- SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS=${SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS:-7200} - SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS=${SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS:-7200}
- KB_STORAGE_ROOT=${KB_STORAGE_ROOT:-/app/data/kb} - KB_STORAGE_ROOT=${KB_STORAGE_ROOT:-/app/data/kb}
- SHIPPING_NOTICE_STORAGE_ROOT=${SHIPPING_NOTICE_STORAGE_ROOT:-/app/data/shipping_notice} - 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 内执行 # 立账凭证检核:周批在 schedule-worker 内执行
- VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-} - VOUCHER_CHECK_ERP_DSN=${VOUCHER_CHECK_ERP_DSN:-}
- VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-} - VOUCHER_CHECK_ERP_USERNAME=${VOUCHER_CHECK_ERP_USERNAME:-}
@@ -265,7 +263,7 @@ services:
- FLASK_APP=${FLASK_APP:-run.py} - FLASK_APP=${FLASK_APP:-run.py}
- FLASK_ENV=${FLASK_ENV} - FLASK_ENV=${FLASK_ENV}
- REDIS_URL=${REDIS_URL:-redis://kb-redis:6379/0} - 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_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_QUERY_CONCURRENCY=${IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY:-2}
- IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=${IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY:-1} - IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=${IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY:-1}
+6 -6
View File
@@ -62,10 +62,10 @@
- 新增变量同步更新对应 env 文件和本文档。 - 新增变量同步更新对应 env 文件和本文档。
- 继续清理对 `backend/.env` 的历史依赖。 - 继续清理对 `backend/.env` 的历史依赖。
## 7. Shipping Notice RPA 命名空间 ## 7. 货代 RPA(FREIGHT_RPA)命名空间
- 后端业务参数:`SHIPPING_NOTICE_RPA_<配置项>`。 - 后端业务参数:`FREIGHT_RPA_<配置项>`。
- 后端与 Windows Worker 共享目录、共享 scope、哨兵:`SHIPPING_NOTICE_RPA_SHARED_<配置项>`。 - 后端与 Windows Worker 共享目录、共享 scope、哨兵:`FREIGHT_RPA_SHARED_<配置项>`。
- Windows Worker 自身运行、浏览器、Driver、日志与账号参数:`SHIPPING_NOTICE_RPA_WORKER_<配置项>`。 - Windows Worker 自身运行、浏览器、Driver、日志与账号参数:`FREIGHT_RPA_WORKER_<配置项>`。
- RPA Profile 凭据 Fernet 主密钥:`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。 - RPA Profile 凭据 Fernet 主密钥:`FREIGHT_RPA_CREDENTIAL_KEY`。
- 禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史变量仅作为迁移期 fallback;新名称优先,完成所有环境迁移后删除旧名称。 - 禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,不设兼容层,禁止再新增或引用。
@@ -35,7 +35,7 @@
| `IN_TRANSIT_TRANSFER_ERP_ENDPOINT` / `_USERNAME` / `_PASSWORD` / `_DEFAULT_ORG` | 空 | ERP SOAP 地址与凭据(WSDL 冻结前留空=fail-closed) | | `IN_TRANSIT_TRANSFER_ERP_ENDPOINT` / `_USERNAME` / `_PASSWORD` / `_DEFAULT_ORG` | 空 | ERP SOAP 地址与凭据(WSDL 冻结前留空=fail-closed) |
| `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` | hxops-transfer | 归档 bucket | | `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` | hxops-transfer | 归档 bucket |
| `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | MinIO 连接(复用既有变量) | | `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 响应。 > 凭据纪律:ERP/MinIO 凭据只存在于环境/Secret;不得写入代码、日志、DOM、Excel 或 API 响应。
@@ -12,7 +12,7 @@
## Global Constraints ## 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 的排程时间。 - 首版不实现库存和收料间的登录会话复用、同 Profile 互斥锁或跨排程协调;运维上错开使用同一 Profile 的排程时间。
- 收料 Worker 在单次排程内以 `connector_type + rpa_profile_id + login_url` 分组,每个分组登录一次、串行处理其全部单元。 - 收料 Worker 在单次排程内以 `connector_type + rpa_profile_id + login_url` 分组,每个分组登录一次、串行处理其全部单元。
- DBS 每个收料配置 Warehouse 展开一条单元;报表日期固定不传。Crane 每站点创建 `Inbound Details`,通过本次唯一 Description 轮询并下载。 - DBS 每个收料配置 Warehouse 展开一条单元;报表日期固定不传。Crane 每站点创建 `Inbound Details`,通过本次唯一 Description 轮询并下载。
@@ -88,15 +88,15 @@
### Task 4: 实现独立 DBS/Crane 收料 Windows Worker ### Task 4: 实现独立 DBS/Crane 收料 Windows Worker
**Files:** **Files:**
- Create: `scripts/rpa/receipt/receipt_rpa_worker.py` - Create: `scripts/freight_rpa/receipt/receipt_rpa_worker.py`
- Create: `scripts/rpa/receipt/receipt_dbs_export.py` - Create: `scripts/freight_rpa/receipt/receipt_dbs_export.py`
- Create: `scripts/rpa/receipt/receipt_crane_export.py` - Create: `scripts/freight_rpa/receipt/receipt_crane_export.py`
- Create: `scripts/rpa/receipt/start_receipt_worker.ps1` - Create: `scripts/freight_rpa/receipt/start_receipt_worker.ps1`
- Modify: `scripts/rpa/README.md` - Modify: `scripts/freight_rpa/README.md`
- Test: `backend/tests/test_freight_receipt_worker_contract.py` - Test: `backend/tests/test_freight_receipt_worker_contract.py`
**Interfaces:** **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 复用会话和异步报表能力,但固定收料报表名。 - DBS driver 复用受验证的登录/导航/参数/下载工具;Crane driver 复用会话和异步报表能力,但固定收料报表名。
- [x] 写失败 mock 测试:拒绝非 v1 trigger;DBS 不传日期但填 Warehouse/受控条件;Crane 每单元生成唯一 Description 且只下载匹配项;callback 失败只移动 receipt trigger 至 `failed/`,不触碰 inventory 目录。 - [x] 写失败 mock 测试:拒绝非 v1 trigger;DBS 不传日期但填 Warehouse/受控条件;Crane 每单元生成唯一 Description 且只下载匹配项;callback 失败只移动 receipt trigger 至 `failed/`,不触碰 inventory 目录。
+155 -153
View File
@@ -1729,10 +1729,10 @@ SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000 SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
# RPA 目录 # RPA 目录
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop FREIGHT_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 FREIGHT_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 FREIGHT_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_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
## 字段资产库与 Schema 契约(目标态) ## 字段资产库与 Schema 契约(目标态)
@@ -1831,9 +1831,9 @@ GET /api/admin/shipping-order-schema/published-contract
- **Dify 手动配置说明**:本阶段无需新增、修改或重新导入 Dify Tool/OpenAPI,也无需修改画布或 Prompt。库存站点测试、结构检查、方案确认和启用均由管理端调用 HXOPS Admin API 完成;Dify 不读取或判断 `activation.checks`。 - **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` 才轮询运行详情;关闭抽屉立即停止轮询。重复发起测试仅复用同一版本的运行任务,配置变更后的旧运行不会阻止新测试。 - `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、下载菜单或等待状态污染下一站。 - 批量测试创建时各站点先处于 `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 不读取此管理端状态接口。 - 测试运行超过 `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` 中转页停留 `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 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` 使用 `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 导出下载耗时。 - **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 中复制完整映射。 - 多个 Inventory Source 可绑定同一个 published Profile;同模板只维护一份。存在少量列差异时创建新 Profile 版本或新 Profile,不在 Source 中复制完整映射。
- 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。 - 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。
- 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingInventoryExternalMapping`,绝不自动创建映射。 - 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `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`。 - **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`。 - **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)。 - **不改版本号**:`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、提交 → 以受控页面选择器判定 → 回调。 - **执行链路**:用户触发批量 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 与货代审计事件。 - **结果三态**:`success`(取得可核验成功证据)、`failed`(明确页面失败、浏览器错误、超时或回调失败)、`unknown`(已可能提交但无法确认外部系统结果)。`unknown` 必须转人工处理,禁止自动重试以避免重复上传;成功/失败/未知、页面证据摘要与脱敏错误写入现有 Upload Attempt 与货代审计事件。
@@ -1950,7 +1950,7 @@ GET /api/admin/shipping-order-schema/published-contract
# SHIPPING_NOTICE_TASK_EXECUTION_MODE=worker # SHIPPING_NOTICE_TASK_EXECUTION_MODE=worker
# RPA 库存导出等待超时(秒,默认 900;DSV 实际链路建议至少 900) # RPA 库存导出等待超时(秒,默认 900;DSV 实际链路建议至少 900)
# SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 # FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
# 发货 worker 轮询间隔(秒) # 发货 worker 轮询间隔(秒)
# SHIPPING_NOTICE_WORKER_POLL_SECONDS=2 # SHIPPING_NOTICE_WORKER_POLL_SECONDS=2
@@ -1970,8 +1970,8 @@ GET /api/admin/shipping-order-schema/published-contract
```powershell ```powershell
$env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key" $env:SHIPPING_NOTICE_TOOL_API_KEY = "your-tool-key"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true" $env:FREIGHT_RPA_WORKER_MOCK = "true"
python scripts/rpa/inventory/inventory_rpa_worker.py python scripts/freight_rpa/inventory/inventory_rpa_worker.py
``` ```
### 1.5 库存导出 RPA 共享部署(Windows RPA + Ubuntu 后端) ### 1.5 库存导出 RPA 共享部署(Windows RPA + Ubuntu 后端)
@@ -2024,7 +2024,7 @@ Ubuntu 后端写 Linux 挂载路径,Windows RPA worker 读 Windows 本地路
```powershell ```powershell
foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) {
New-Item -ItemType Directory -Force $root 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\backend\config"
New-Item -ItemType Directory -Force "$root\data\inventory_triggers" New-Item -ItemType Directory -Force "$root\data\inventory_triggers"
@@ -2039,24 +2039,24 @@ foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) {
从项目仓库复制以下文件到 Windows RPA 主机: 从项目仓库复制以下文件到 Windows RPA 主机:
```text ```text
scripts\rpa\inventory\inventory_rpa_worker.py scripts\freight_rpa\inventory\inventory_rpa_worker.py
scripts\rpa\connectors\dsv\dsv_report_parameters.py scripts\freight_rpa\connectors\dsv\dsv_report_parameters.py
scripts\rpa\connectors\dsv\dsv_login_smoke.py scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py
scripts\rpa\inventory\run_inventory_batch_trigger.py scripts\freight_rpa\inventory\run_inventory_batch_trigger.py
``` ```
放置为: 放置为:
```text ```text
C:\HxopsRpaTest\scripts\rpa\inventory\inventory_rpa_worker.py C:\HxopsRpaTest\scripts\freight_rpa\inventory\inventory_rpa_worker.py
C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_report_parameters.py C:\HxopsRpaTest\scripts\freight_rpa\connectors\dsv\dsv_report_parameters.py
C:\HxopsRpaTest\scripts\rpa\connectors\dsv\dsv_login_smoke.py C:\HxopsRpaTest\scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py
C:\HxopsRpaTest\scripts\rpa\inventory\run_inventory_batch_trigger.py C:\HxopsRpaTest\scripts\freight_rpa\inventory\run_inventory_batch_trigger.py
C:\HxopsRpaProd\scripts\rpa\inventory\inventory_rpa_worker.py C:\HxopsRpaProd\scripts\freight_rpa\inventory\inventory_rpa_worker.py
C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_report_parameters.py C:\HxopsRpaProd\scripts\freight_rpa\connectors\dsv\dsv_report_parameters.py
C:\HxopsRpaProd\scripts\rpa\connectors\dsv\dsv_login_smoke.py C:\HxopsRpaProd\scripts\freight_rpa\connectors\dsv\dsv_login_smoke.py
C:\HxopsRpaProd\scripts\rpa\inventory\run_inventory_batch_trigger.py C:\HxopsRpaProd\scripts\freight_rpa\inventory\run_inventory_batch_trigger.py
``` ```
不要复制 `.env*`、密码文件、`backend\data` 旧运行数据、浏览器 profile、旧 trigger / processed / failed 文件。 不要复制 `.env*`、密码文件、`backend\data` 旧运行数据、浏览器 profile、旧 trigger / processed / failed 文件。
@@ -2104,14 +2104,14 @@ python -m playwright install chromium
``` ```
**默认使用 Playwright 捆绑 Chromium**(上一步已 `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`)。 在 Excel 下载时会原生崩溃(`Download.save_as: TargetClosed` / 残留 `.crdownload`)。
#### 1.5.5 Windows RPA 主机:临时环境变量与登录测试 #### 1.5.5 Windows RPA 主机:临时环境变量与登录测试
先在 PowerShell 当前窗口配置临时环境变量,确认链路可用后再改成永久环境变量: 先在 PowerShell 当前窗口配置临时环境变量,确认链路可用后再改成永久环境变量:
> `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 是 RPA Profile 凭据的 Fernet 主密钥。 > `FREIGHT_RPA_CREDENTIAL_KEY` 是 RPA Profile 凭据的 Fernet 主密钥。
> Windows Worker 与对应 test/prod 后端必须使用同一个值,否则 Worker 无法解密 > Windows Worker 与对应 test/prod 后端必须使用同一个值,否则 Worker 无法解密
> 后端下发的 Profile 密文。该值必须从 Jenkins/Secret 管理器或受控运维渠道注入, > 后端下发的 Profile 密文。该值必须从 Jenkins/Secret 管理器或受控运维渠道注入,
> 禁止写入仓库、命令历史、截图或日志。 > 禁止写入仓库、命令历史、截图或日志。
@@ -2121,61 +2121,61 @@ cd C:\HxopsRpaTest
$env:HXOPS_API_BASE = "http://测试后端地址:端口" $env:HXOPS_API_BASE = "http://测试后端地址:端口"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "请替换为测试环境SHIPPING_NOTICE_TOOL_API_KEY" $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 安全交互创建。 # Secret 由 new_rpa_worker_secret.ps1 安全交互创建。
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" $env:FREIGHT_RPA_WORKER_MOCK = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" $env:FREIGHT_RPA_WORKER_HEADLESS = "false"
# 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。 # 不设 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:FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = "C:\HxopsRpaTest\data\inventory_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = "C:\HxopsRpaTest\data\inventory_drop" $env:FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = "C:\HxopsRpaTest\data\inventory_drop"
$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = "C:\HxopsRpaTest\data\upload_triggers" $env:FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = "C:\HxopsRpaTest\data\upload_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = "C:\HxopsRpaTest\data\upload_queue" $env:FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = "C:\HxopsRpaTest\data\upload_queue"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\browser_profile" $env:FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\browser_profile"
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log" $env:FREIGHT_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log"
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760" $env:FREIGHT_RPA_WORKER_LOG_MAX_BYTES = "10485760"
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5" $env:FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = "5"
$env:SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7" $env:FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = "7"
$env:SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600" $env:FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600"
$env:SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24" $env:FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24"
$env:SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号" $env:FREIGHT_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号"
$env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码" $env:FREIGHT_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码"
$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME = "请替换为Crane账号" $env:FREIGHT_RPA_WORKER_CRANE_USERNAME = "请替换为Crane账号"
$env:SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD = "请替换为Crane密码" $env:FREIGHT_RPA_WORKER_CRANE_PASSWORD = "请替换为Crane密码"
# 心跳与共享 scope(test/prod 必填;与 Ubuntu SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID 一致) # 心跳与共享 scope(test/prod 必填;与 Ubuntu FREIGHT_RPA_SHARED_SCOPE_ID 一致)
$env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "test" $env:FREIGHT_RPA_WORKER_ENVIRONMENT = "test"
$env:SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = "hxops-rpa-test-data" $env:FREIGHT_RPA_SHARED_SCOPE_ID = "hxops-rpa-test-data"
$env:SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20" $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 与哨兵 #### 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` | | Ubuntu 后端 | `FREIGHT_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 | `FREIGHT_RPA_SHARED_SCOPE_ID` | `hxops-rpa-test-data` | `hxops-rpa-prod-data` |
| Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` | `prod` | | Windows RPA | `FREIGHT_RPA_WORKER_ENVIRONMENT` | `test` | `prod` |
| Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 | | Windows RPA | `FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS` | `90`(默认) | `90` | | Ubuntu 后端 | `FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS` | `90`(默认) | `90` |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED` | `false`(默认关闭企微心跳告警) | 同左;需要时改为 `true` | | Ubuntu 后端 | `FREIGHT_RPA_WORKER_ALERT_ENABLED` | `false`(默认关闭企微心跳告警) | 同左;需要时改为 `true` |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` | 逗号分隔 HXOPS 用户名(**部署前建议显式填写**) | 同左 | | Ubuntu 后端 | `FREIGHT_RPA_WORKER_ALERT_USERNAMES` | 逗号分隔 HXOPS 用户名(**部署前建议显式填写**) | 同左 |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` | | Ubuntu 后端 | `FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS` | `120`(企微发送中短锁,失败后可重试) | `120` | | 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。 **多进程去重**:告警冷却状态以 `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 启动后验证哨兵(测试环境示例): 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 前台轮询**(仅库存排程工作台模式,后台标签页暂停、请求未返回时跳过);执行记录列表按**历史查询**处理,仅切任务/点查询/重置时加载,不做定时自动刷新。 管理端 `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 登录: 先验证 DSV 登录:
```powershell ```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,执行: 库存 RPA 必须由 HXOPS 管理端的 Inventory Source + RPA Profile 生成 trigger;如需人工联调,选取已生成的 trigger,执行:
```powershell ```powershell
python scripts\rpa\inventory\run_inventory_batch_trigger.py <trigger.json> python scripts\freight_rpa\inventory\run_inventory_batch_trigger.py <trigger.json>
``` ```
该入口不会读取 YAML 或本地账号密码,Profile 的密文凭据和页面操作均由平台生成的 trigger 提供。 该入口不会读取 YAML 或本地账号密码,Profile 的密文凭据和页面操作均由平台生成的 trigger 提供。
@@ -2350,24 +2350,24 @@ SHIPPING_NOTICE_TOOL_API_KEY=请替换为强随机ASCII密钥
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_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_INVENTORY_SNAPSHOT_TTL_HOURS=24
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers FREIGHT_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 FREIGHT_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 FREIGHT_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_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
# Worker 心跳与共享 scope(与 Windows SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID 一致) # Worker 心跳与共享 scope(与 Windows FREIGHT_RPA_SHARED_SCOPE_ID 一致)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true
# 企微心跳告警默认关闭;需要时改为 true # 企微心跳告警默认关闭;需要时改为 true
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 逗号分隔已绑企微的 HXOPS 用户名;留空且 FALLBACK_ADMIN=true 时通知 admin # 逗号分隔已绑企微的 HXOPS 用户名;留空且 FALLBACK_ADMIN=true 时通知 admin
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= FREIGHT_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120 FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
``` ```
正式环境只把路径改为 `/mnt/hxops-rpa-prod-data/...`,并使用正式环境的 `SHIPPING_NOTICE_TOOL_API_KEY`。 正式环境只把路径改为 `/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 文件保存,不写入用户级或机器级环境变量。 同一 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: Windows 如禁止运行 `.ps1`,仅对单次 Secret 创建使用临时 Bypass:
```powershell ```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:\HxopsRpaTest\scripts\freight_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:\HxopsRpaProd\scripts\freight_rpa\common\new_rpa_worker_secret.ps1" -Environment prod
``` ```
若文件来自网络或压缩包并被标记为阻止,先执行 `Unblock-File`。也可用 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` 仅放行当前窗口。禁止永久设置 `Unrestricted` 或修改 `LocalMachine` 策略。 若文件来自网络或压缩包并被标记为阻止,先执行 `Unblock-File`。也可用 `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass` 仅放行当前窗口。禁止永久设置 `Unrestricted` 或修改 `LocalMachine` 策略。
@@ -2412,13 +2412,13 @@ Windows PowerShell 5.1 读取无 BOM UTF-8 脚本时可能出现中文变乱和
```powershell ```powershell
cd C:\HxopsRpaTest cd C:\HxopsRpaTest
.\scripts\rpa\common\new_rpa_worker_secret.ps1 -Environment test .\scripts\freight_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 prod
``` ```
默认 Secret 路径为 `C:\HxopsRpaSecrets\test.xml` 与 `prod.xml`。文件不得进入仓库、SMB 共享、日志或其他 Windows 用户目录。 默认 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: 手工启动 test:
@@ -2426,7 +2426,7 @@ DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Prof
```powershell ```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` 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 ` -Environment test `
-ApiBase "http://<test后端地址>:<端口>" ` -ApiBase "http://<test后端地址>:<端口>" `
-WorkerRoot "C:\HxopsRpaTest" ` -WorkerRoot "C:\HxopsRpaTest" `
@@ -2436,8 +2436,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
若脚本来自网络或压缩包,先确认路径并按需解除文件阻止: 若脚本来自网络或压缩包,先确认路径并按需解除文件阻止:
```powershell ```powershell
Test-Path "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\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 访问: `-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 ```powershell
.\scripts\rpa\inventory\start_inventory_worker.ps1 ` .\scripts\freight_rpa\inventory\start_inventory_worker.ps1 `
-Environment test ` -Environment test `
-ApiBase "http://测试后端:端口" ` -ApiBase "http://测试后端:端口" `
-WorkerRoot "C:\HxopsRpaTest" ` -WorkerRoot "C:\HxopsRpaTest" `
@@ -2462,18 +2462,18 @@ Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing
手工启动 prod: 手工启动 prod:
```powershell ```powershell
C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1 ` C:\HxopsRpaProd\scripts\freight_rpa\inventory\start_inventory_worker.ps1 `
-Environment prod ` -Environment prod `
-ApiBase "http://正式后端:端口" ` -ApiBase "http://正式后端:端口" `
-WorkerRoot "C:\HxopsRpaProd" ` -WorkerRoot "C:\HxopsRpaProd" `
-SecretFile "C:\HxopsRpaSecrets\prod.xml" -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.5.11 端到端验证
1. Windows 手工打开 Edge,确认能访问 DSV/Crane。 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 和密文凭据。 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` 能看到。 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`。 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 常见问题 #### 1.5.12 常见问题
- Ubuntu `smbclient` 能访问,但后端写失败:用 `sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/test.txt` 测试后端服务用户权限,检查挂载参数中的 `uid/gid` 与 Windows 共享/NTFS 权限。 - 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 端口。 - worker 回调失败:确认 Windows 能访问 `HXOPS_API_BASE`,`SHIPPING_NOTICE_TOOL_API_KEY` 与后端一致,Ubuntu 防火墙允许 Windows 访问 HXOPS 端口。
- DSV/Crane 登录失败:先用 Windows Edge 手工登录,再跑 `dsv_login_smoke.py`;重点检查 MFA/验证码/SSO、企业代理、证书、账号密码。 - DSV/Crane 登录失败:先用 Windows Edge 手工登录,再跑 `dsv_login_smoke.py`;重点检查 MFA/验证码/SSO、企业代理、证书、账号密码。
- Ubuntu 重启后目录空了:执行 `sudo mount -a`,检查 `/etc/fstab`、网络是否已就绪、Windows 共享是否可访问。 - Ubuntu 重启后目录空了:执行 `sudo mount -a`,检查 `/etc/fstab`、网络是否已就绪、Windows 共享是否可访问。
@@ -2500,7 +2500,7 @@ C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1 `
| 运行位置 | 适用目的 | 后端目录/环境 | Worker 目录与环境 | 禁止混用 | | 运行位置 | 适用目的 | 后端目录/环境 | 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-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 | | 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 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 ```powershell
$repoRoot = (Get-Location).Path $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" $env:HXOPS_API_BASE = "http://127.0.0.1:5052"
# 由受控 Secret 渠道注入;禁止在此处粘贴真实值。 # 由受控 Secret 渠道注入;禁止在此处粘贴真实值。
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<本地 Tool API Key>" $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:FREIGHT_RPA_WORKER_ENVIRONMENT = "dev"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false" $env:FREIGHT_RPA_WORKER_MOCK = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" $env:FREIGHT_RPA_WORKER_HEADLESS = "false"
# 不设 BROWSER_CHANNEL → Playwright Chromium;勿设 msedge。 # 不设 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 = Join-Path $rpaDataRoot "inventory_triggers" $env:FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory_drop" $env:FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory_drop"
$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaDataRoot "upload_triggers" $env:FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaDataRoot "upload_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "upload_queue" $env:FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "upload_queue"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile" $env:FREIGHT_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_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log"
\.\scripts\rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase "<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml" \.\scripts\freight_rpa\inventory\start_inventory_worker.ps1 -Environment test -ApiBase "<test后端地址>:<端口>" -WorkerRoot "C:\HxopsRpaTest" -SecretFile "C:\HxopsRpaSecrets\test.xml"
``` ```
启动成功后,控制台会输出 `[freight_rpa_worker] started`,并持续轮询 trigger。另开一个 PowerShell 可检查日志和哨兵;本地未配置 shared scope 时不要求哨兵包含 test/prod scope: 启动成功后,控制台会输出 `[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' 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`(或停止其既有计划任务),最后执行: 需要停止测试环境的 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' 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,最后按需停止容器: 计划维护或紧急停止时,先暂停正式库存 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**。 > 本节是收料报表 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 与独立回调。 > 前置条件:已按 `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 的边界和目录规划 #### 1.9.1 与库存 RPA 的边界和目录规划
@@ -2968,25 +2968,25 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui
| 项 | 库存 RPA | 收料 RPA | | 项 | 库存 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` | | 启动脚本 | `inventory\start_inventory_worker.ps1` | `receipt\start_receipt_worker.ps1` |
| trigger 目录 | `data\inventory_triggers` | `data\freight_receipt_rpa\receipt_triggers` | | trigger 目录 | `freight_rpa\inventory\triggers` | `freight_rpa\receipt\triggers` |
| drop 目录 | `data\inventory_drop` | `data\freight_receipt_rpa\receipt_drop` | | drop 目录 | `freight_rpa\inventory\drop` | `freight_rpa\receipt\drop` |
| 回调端点 | `/api/shipping-notice/rpa/inventory-batch-ready` | `/api/shipping-notice/rpa/receipt-batch-ready` | | 回调端点 | `/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 原样归档 + 企微投递,绝不进入库存链路 | | 结果归属 | 库存快照/库存匹配 | MinIO 原样归档 + 企微投递,绝不进入库存链路 |
路径对应关系(测试环境;正式环境把 `Test` / `test-data` 换成 `Prod` / `prod-data`): 路径对应关系(测试环境;正式环境把 `Test` / `test-data` 换成 `Prod` / `prod-data`):
```text ```text
Windows RPA:C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_triggers Windows RPA:C:\HxopsRpaTest\freight_rpa\receipt\triggers
Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
Windows RPA:C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_drop Windows RPA:C:\HxopsRpaTest\freight_rpa\receipt\drop
Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
``` ```
浏览器 Profile:收料 Worker 在 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`(收料启动脚本默认指向 `<WorkerRoot>\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`(收料启动脚本默认指向 `<WorkerRoot>\freight_rpa\common\browser_profile`)下,为每个 `connector + profile + login_url` 分组创建 `receipt_*` 临时目录,组处理完立即删除;不保留跨排程登录会话。与库存 Worker 的 `run_*` 一次性 Profile、`{connector}__{profile}_session` 长期会话目录互不影响。
#### 1.9.2 Windows RPA 主机:部署收料 Worker #### 1.9.2 Windows RPA 主机:部署收料 Worker
@@ -2994,13 +2994,13 @@ Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop
```powershell ```powershell
foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) { 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\freight_rpa\receipt\triggers"
New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\receipt_drop" New-Item -ItemType Directory -Force "$root\freight_rpa\receipt\drop"
New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\logs" 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 一起补齐): 依赖与 `1.5.4` 相同,另需 `cryptography`(解密 RPA Profile 加密凭据;库存 Worker 同样依赖,新增部署时两个 Worker 一起补齐):
@@ -3014,7 +3014,7 @@ Secret 复用 `1.5.10` 创建的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`。
```powershell ```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File ` 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 ` -Environment test `
-ApiBase "http://<test后端地址>:<端口>" ` -ApiBase "http://<test后端地址>:<端口>" `
-WorkerRoot "C:\HxopsRpaTest" ` -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,从仓库原样复制)。 启动成功会输出 `[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 的 `<主机名>-<pid>` 混淆)。收料 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 ```powershell
$TestApiBase = "http://<test后端地址>:<端口>" $TestApiBase = "http://<test后端地址>:<端口>"
$ReceiptAction = New-ScheduledTaskAction ` $ReceiptAction = New-ScheduledTaskAction `
-Execute "cmd.exe" ` -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" -WorkingDirectory "C:\HxopsRpaTest"
# $Trigger / $Principal / $Settings 与 1.5.10 的库存任务完全一致: # $Trigger / $Principal / $Settings 与 1.5.10 的库存任务完全一致:
# AtLogOn + Interactive;RestartCount 10、RestartInterval 1 分钟、ExecutionTimeLimit 0、MultipleInstances IgnoreNew。 # 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.test` 在 `1.5.9` 基础上追加(正式环境把路径换成 `/mnt/hxops-rpa-prod-data/...`):
```env ```env
# 收料 RPA 共享目录(与 Windows Worker 的 data\freight_receipt_rpa 属同一 SMB 共享的子路径) # 收料 RPA 共享目录(与 Windows Worker 的 freight_rpa\receipt 属同一 SMB 共享的子路径)
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
# 收料排程等待回调超时(秒);超时回收为 RPA.RECEIPT_CALLBACK_TIMEOUT,不自动重试 # 收料排程等待回调超时(秒);超时回收为 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` 后按惯例重建相关容器。 容器 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`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。 - 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。
- 企微逐文件推送与汇总发给排程任务配置的接收人(`notify_user_ids` + `notify_enabled`),接收人必须已完成企微绑定,否则投递记 `WECOM_USER_UNBOUND` 失败。 - 企微逐文件推送与汇总发给排程任务配置的接收人(`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.9.4 端到端验证
1. 管理端「货代管理 → 库存站点」抽屉为目标站点配置收料卡(与库存同构):DBS 必须在查询条件中维护 Warehouse 条件(支持多值,每个 Warehouse 展开一个单元);报表日期不得出现在查询条件中。Crane 固定 `Inbound Details`,拒绝查询条件。收料无独立开关,站点启用即参与收料排程。 1. 管理端「货代管理 → 库存站点」抽屉为目标站点配置收料卡(与库存同构):DBS 必须在查询条件中维护 Warehouse 条件(支持多值,每个 Warehouse 展开一个单元);报表日期不得出现在查询条件中。Crane 固定 `Inbound Details`,拒绝查询条件。收料无独立开关,站点启用即参与收料排程。
2. 链路演练(不依赖真实货代网站):以 `-Mock` 启动收料 Worker → 排程管理手工执行一次「货代收料 RPA」→ 确认回调、MinIO 归档、企微投递全链路成功后停止 Mock Worker。 2. 链路演练(不依赖真实货代网站):以 `-Mock` 启动收料 Worker → 排程管理手工执行一次「货代收料 RPA」→ 确认回调、MinIO 归档、企微投递全链路成功后停止 Mock Worker。
3. 真实链路:启动真实收料 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/`); - Worker 领取后文件进入同目录 `processing/`,全部单元处理完进入 `processed/`(契约级失败进 `failed/`);
- `receipt_drop` 出现 `receipt_{callback_id}_{时间戳}.xlsx`; - `receipt_drop` 出现 `receipt_{callback_id}_{时间戳}.xlsx`;
- 回调 `/api/shipping-notice/rpa/receipt-batch-ready` 成功,单元 `success`,MinIO 出现归档对象; - 回调 `/api/shipping-notice/rpa/receipt-batch-ready` 成功,单元 `success`,MinIO 出现归档对象;
@@ -3079,25 +3081,25 @@ SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900
#### 1.9.5 常见问题 #### 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` 的网关口径填写。 - 回调 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`;多为收料/库存目录串用所致。 - 回调报 `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。 - 单元长期 `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 已启用且 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 两端一致(否则无法解密凭据)。 - 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_*`);如需更早释放仍可人工清理,建议保留最近几天便于排障。 - `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 三环境速查 #### 1.9.6 收料 RPA 三环境速查
| 运行位置 | 后端目录/环境 | Worker 目录与环境 | 说明 | | 运行位置 | 后端目录/环境 | Worker 目录与环境 | 说明 |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Windows 本地联调 | 本地后端;默认 `backend/data/shipping_notice/freight_receipt_rpa/*` | 当前项目 `scripts/rpa/receipt/`;`dev` | 不连 test/prod、不用 test/prod Key;`-Mock` 可全链路演练 | | Windows 本地联调 | 本地后端;默认 `backend/data/freight_rpa/receipt/*` | 当前项目 `scripts/freight_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-test-data/freight_rpa/receipt/*`;`.env.test` | `C:\HxopsRpaTest\freight_rpa\receipt`;`test` | 与库存测试共用同一 SMB 共享与挂载 |
| Linux 正式服务器 | `/mnt/hxops-rpa-prod-data/freight_receipt_rpa/*`;`.env.prod` | `C:\HxopsRpaProd\data\freight_receipt_rpa`;`prod` | 测试真实链路验收通过后再开启正式排程 | | Linux 正式服务器 | `/mnt/hxops-rpa-prod-data/freight_rpa/receipt/*`;`.env.prod` | `C:\HxopsRpaProd\freight_rpa\receipt`;`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`) | 本地联调两端默认一致,无需配置 | | `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`) | 本地联调两端默认一致,无需配置 |
| `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`) | 本地联调两端默认一致,无需配置 | | `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 指向一致,无需配置目录变量): Windows 本地联调(项目根目录 PowerShell;本地后端默认目录与 Worker 指向一致,无需配置目录变量):
@@ -3107,14 +3109,14 @@ Windows 本地联调(项目根目录 PowerShell;本地后端默认目录与
# 走完整 trigger 消费 → 回调 → 归档 → 企微链路)。 # 走完整 trigger 消费 → 回调 → 归档 → 企微链路)。
$env:HXOPS_API_BASE = "http://127.0.0.1:5052" $env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<与本地后端一致>" $env:SHIPPING_NOTICE_TOOL_API_KEY = "<与本地后端一致>"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true" $env:FREIGHT_RPA_WORKER_MOCK = "true"
$receiptRoot = Join-Path (Get-Location).Path "backend\data\shipping_notice\freight_receipt_rpa" $receiptRoot = Join-Path (Get-Location).Path "backend\data\freight_rpa"
$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $receiptRoot "receipt_triggers" $env:FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $receiptRoot "receipt\triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $receiptRoot "receipt_drop" $env:FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $receiptRoot "receipt\drop"
python scripts/rpa/receipt/receipt_rpa_worker.py 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_inventory_routing_engine.py` | 通用路由规则引擎单测 |
| `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 | | `backend/tests/test_shipping_notice_inventory_schedule.py` | 定时批量库存 RPA 排程 executor 单测 |
| `backend/tests/test_shipping_notice_match_summary.py` | 匹配摘要相关测试 | | `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` 填充 - **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充
- **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值) - **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/类型漂移。 - **报表控件模板**(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。 - **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` - 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready`
- **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts/<callback_id>/`、创建 `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`)。 - **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts/<callback_id>/`、创建 `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。 - 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 启动及常规扫描均回收超时运行,避免服务或 Worker 重启后运行永久占用排程状态。
- 空结果、Worker 失败、归档成功、对象删除失败、企微文件/汇总投递成功或失败、管理员查看失败单元、人工重试和重发均写追加式 `ShippingAuditEvent`。审计包含操作人/时间/对象、结果、脱敏原因或错误码、变更前后状态;不得写入密码、Cookie、令牌、对象存储定位或浏览器会话。 - 空结果、Worker 失败、归档成功、对象删除失败、企微文件/汇总投递成功或失败、管理员查看失败单元、人工重试和重发均写追加式 `ShippingAuditEvent`。审计包含操作人/时间/对象、结果、脱敏原因或错误码、变更前后状态;不得写入密码、Cookie、令牌、对象存储定位或浏览器会话。
- 管理员失败单元查询仅返回运行诊断所需的站点、Warehouse、状态、错误码/脱敏错误和时间;接收人不拥有该查询、配置、重试或重发权限。 - 管理员失败单元查询仅返回运行诊断所需的站点、Warehouse、状态、错误码/脱敏错误和时间;接收人不拥有该查询、配置、重试或重发权限。
@@ -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 唯一依据,`<ROOT>` 见下):
- `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` = `<ROOT>/inventory/triggers`
- `FREIGHT_RPA_INVENTORY_DROP_DIR` = `<ROOT>/inventory/drop`
- `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` = `<ROOT>/inventory/upload_triggers`
- `FREIGHT_RPA_UPLOAD_QUEUE_DIR` = `<ROOT>/inventory/upload_queue`
- `FREIGHT_RPA_INVENTORY_ARCHIVE_DIR` = `<ROOT>/inventory/archives`
- `FREIGHT_RPA_RECEIPT_TRIGGER_DIR` = `<ROOT>/receipt/triggers`
- `FREIGHT_RPA_RECEIPT_DROP_DIR` = `<ROOT>/receipt/drop`
- `FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR` = `<ROOT>/common/browser_profile`(键名保留 `WORKER_` 二级前缀——它由各 Worker 的 ps1 注入;**值**为共享根,即"同名变量、共享取值")
- Worker 日志(ps1 注入)= `<ROOT>/inventory/logs/worker.log` / `<ROOT>/receipt/logs/worker.log`
- `<ROOT>`:dev 后端默认 = `backend/data/rpa`;test = `/mnt/hxops-rpa-test-data/rpa`;prod = `/mnt/hxops-rpa-prod-data/rpa`;Worker ps1 = `<WorkerRoot>\rpa`
- 完成判据(硬校验):替换范围内 `grep -r "SHIPPING_NOTICE_RPA_"` 命中为 0(白名单见 Task 6);全量相关 pytest 仅已知既有基线失败。
- Conventional Commits:`<type>(<scope>): <中文祈使句>`;本次多为 `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。
+1 -1
View File
@@ -1514,7 +1514,7 @@ RecoveryPlan → Gate Attempt → Job → Worker/RPA → 幂等回调 → `run_t
# 货代收料 RPA 独立架构(2026-08) # 货代收料 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`;三年期满仅删除对象、保留文件事实与审计。 下载接口为 `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`;三年期满仅删除对象、保留文件事实与审计。
@@ -2760,6 +2760,16 @@ function releaseBarLineRequiredFields(line: { snapshot_line_id?: number | null }
return fulfillment?.release_required_fields || []; return fulfillment?.release_required_fields || [];
} }
/**
* 缺失徽标文案:前缀 + 数量 + 后缀(纯文本键拼接)。
* 【注】不用 vue-i18n 命名插值 `{n}`——11.4.7 对该实例深层键+插值组合存在解析异常
* (te=false、t 回原始 key,已用 vitest 分层断言复现,见 src/i18n.spec.ts)。
*/
function releaseMissingBadgeLabel(line: { snapshot_line_id?: number | null }): string {
const n = releaseBarLineRequiredFields(line).length;
return `${t('chat.shippingOrderReview.releaseBar.missingPrefix')}${n}${t('chat.shippingOrderReview.releaseBar.missingSuffix')}`;
}
/** 缺字段型短缺行:放行走行内补录(而非仅原因的旧弹窗路径)。 */ /** 缺字段型短缺行:放行走行内补录(而非仅原因的旧弹窗路径)。 */
function releaseBarHasFields(line: { function releaseBarHasFields(line: {
snapshot_line_id?: number | null; snapshot_line_id?: number | null;
@@ -5309,7 +5319,7 @@ watch(
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll"> <div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs"> <table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead> <thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated <tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
</table> </table>
</div> </div>
</div> </div>
+58
View File
@@ -0,0 +1,58 @@
/**
* src/i18n.spec.ts
*
* 用途:锁定应用真实 i18n 实例的键解析行为,防止"原始 key 直接渲染"回归。
* 依赖:vitest、vue-i18n、src/i18n(mergeExternalLocales 合并后的全局实例)、zh-CN/chat.json。
* 逻辑:分层断言——模块原始对象 → 实例消息表 → t() 解析;并留存 vue-i18n 11.4.7 插值异常的复现记录。
*
* 【已知库级异常(2026-09-18 复现,vue-i18n 11.4.7)】
* 深层嵌套键(如 chat.shippingOrderReview.releaseBar.badge)的**命名插值**消息
* `{n}` 会 te()=false 且 t() 返回原始 key——尽管 getLocaleMessage 与源 JSON 均含该键;
* 最小纯净实例上同名插值正常;同父对象的纯文本键正常。
* 因此本项目交互内联文案(如缺失徽标)采用「纯文本键 + 脚本拼接数量」规避;
* 升级 vue-i18n 后可用 git 历史中的插值断言复检是否已修复。
*/
import { describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import i18n from './i18n';
import zhCNChat from './locales/zh-CN/chat.json';
describe('vue-i18n 最小实例:{n} 插值(库能力基线)', () => {
it('纯净顶层实例可解析 {n} 命名插值', () => {
const minimal = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { badge: '缺 {n} 项放行信息' } },
});
// 断言:{n} 插值在顶层键上可用(深层嵌套键存在 11.4.7 异常,见文件头说明)。
expect(minimal.global.t('badge', { n: 2 })).toBe('缺 2 项放行信息');
});
});
describe('应用 i18n 实例:releaseBar 补录条键解析', () => {
it('模块原始对象包含补录条纯文本键', () => {
const subtree = (zhCNChat as Record<string, any>).shippingOrderReview as Record<string, any>;
// 断言:Vite JSON 管线加载后前缀/后缀键完整(徽标文案由脚本拼接,不依赖命名插值)。
expect(subtree?.releaseBar?.missingPrefix).toBe('缺 ');
expect(subtree?.releaseBar?.missingSuffix).toBe(' 项放行信息');
});
it('实例消息表包含补录条纯文本键', () => {
const instanceMessages = i18n.global.getLocaleMessage('zh-CN') as Record<string, any>;
const releaseBar = instanceMessages?.chat?.shippingOrderReview?.releaseBar;
// 断言:createI18n 合并后的实例消息表携带前缀/后缀。
expect(releaseBar?.missingPrefix).toBe('缺 ');
expect(releaseBar?.missingSuffix).toBe(' 项放行信息');
});
it('纯文本键端到端可解析(label 与 missingPrefix/missingSuffix)', () => {
// 断言:纯文本键在应用实例上全部正常解析(插值键的库级异常与此互不影响)。
expect(i18n.global.t('chat.shippingOrderReview.releaseBar.label')).toBe('放行补录');
expect(i18n.global.t('chat.shippingOrderReview.releaseBar.missingPrefix')).toBe('缺 ');
expect(i18n.global.t('chat.shippingOrderReview.releaseBar.missingSuffix')).toBe(' 项放行信息');
});
it('te() 对缺失键返回 false(回退语义不变)', () => {
expect(i18n.global.te('chat.shippingOrderReview.releaseBar.notExists')).toBe(false);
});
});
+2 -1
View File
@@ -2758,7 +2758,8 @@
}, },
"releaseBar": { "releaseBar": {
"label": "Release info", "label": "Release info",
"badge": "{n} missing release field(s)" "missingPrefix": "Missing ",
"missingSuffix": " release field(s)"
} }
}, },
"shippingOrderExtractionElapsed": "Elapsed {elapsed}", "shippingOrderExtractionElapsed": "Elapsed {elapsed}",
+2 -1
View File
@@ -2758,7 +2758,8 @@
}, },
"releaseBar": { "releaseBar": {
"label": "ข้อมูลเพิ่มเติมเพื่อปล่อยของ", "label": "ข้อมูลเพิ่มเติมเพื่อปล่อยของ",
"badge": "ขาด {n} รายการก่อนปล่อย" "missingPrefix": "ขาด ",
"missingSuffix": " รายการก่อนปล่อย"
} }
}, },
"shippingOrderExtractionElapsed": "ใช้เวลา {elapsed}", "shippingOrderExtractionElapsed": "ใช้เวลา {elapsed}",
+2 -1
View File
@@ -2866,7 +2866,8 @@
}, },
"releaseBar": { "releaseBar": {
"label": "放行补录", "label": "放行补录",
"badge": "缺 {n} 项放行信息" "missingPrefix": "缺 ",
"missingSuffix": " 项放行信息"
} }
}, },
"shippingProcessing": { "shippingProcessing": {
+2 -1
View File
@@ -2758,7 +2758,8 @@
}, },
"releaseBar": { "releaseBar": {
"label": "放行補錄", "label": "放行補錄",
"badge": "缺 {n} 項放行資訊" "missingPrefix": "缺 ",
"missingSuffix": " 項放行資訊"
} }
}, },
"shippingOrderExtractionElapsed": "已用時 {elapsed}", "shippingOrderExtractionElapsed": "已用時 {elapsed}",
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,5 @@
""" """
scripts/rpa/download_artifact_fallback.py scripts/freight_rpa/download_artifact_fallback.py
用途:在浏览器实际已落盘但 Playwright Download 句柄不可用时,按下载目录中的新文件构造兼容适配器。 用途:在浏览器实际已落盘但 Playwright Download 句柄不可用时,按下载目录中的新文件构造兼容适配器。
依赖:pathlib、shutil、time。 依赖:pathlib、shutil、time。
@@ -32,7 +32,7 @@ function Read-RequiredSecret {
$record = [pscustomobject]@{ $record = [pscustomobject]@{
ToolApiKey = Read-RequiredSecret "请输入 $Environment 环境 SHIPPING_NOTICE_TOOL_API_KEY" ToolApiKey = Read-RequiredSecret "请输入 $Environment 环境 SHIPPING_NOTICE_TOOL_API_KEY"
CredentialKey = Read-RequiredSecret "请输入 $Environment 环境 SHIPPING_NOTICE_RPA_CREDENTIAL_KEY" CredentialKey = Read-RequiredSecret "请输入 $Environment 环境 FREIGHT_RPA_CREDENTIAL_KEY"
} }
$record | Export-Clixml -LiteralPath $secretPath $record | Export-Clixml -LiteralPath $secretPath
@@ -1,5 +1,5 @@
""" """
scripts/rpa/rpa_common.py scripts/freight_rpa/rpa_common.py
用途:RPA worker 与 DSV/Crane driver 共用的浏览器与环境变量工具。 用途:RPA worker 与 DSV/Crane driver 共用的浏览器与环境变量工具。
依赖:标准库、Playwright(运行时)。 依赖:标准库、Playwright(运行时)。
@@ -28,64 +28,10 @@ import os
import sys import sys
import time import time
import urllib.request import urllib.request
import warnings
from pathlib import Path from pathlib import Path
from typing import Any, TextIO from typing import Any, TextIO
_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_SHARED_SCOPE_ID": "SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID",
"FREIGHT_RPA_SHARED_SENTINEL_NAME": "SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME",
"FREIGHT_RPA_INVENTORY_ARCHIVE_DIR": "SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR",
"FREIGHT_RPA_WORKER_ID": "SHIPPING_NOTICE_RPA_WORKER_ID",
"FREIGHT_RPA_WORKER_VERSION": "SHIPPING_NOTICE_RPA_WORKER_VERSION",
}
_WARNED_LEGACY_RPA_ENV: set[str] = set()
def _canonical_rpa_env_name(name: str) -> str:
"""
将历史 RPA 环境变量名转换为 Shipping Notice 统一命名空间。
核心逻辑:共享目录和凭据密钥使用显式映射;其余 `FREIGHT_RPA_*`
均属于 Windows Worker 运行参数,统一映射到 `SHIPPING_NOTICE_RPA_WORKER_*`。
Args:
name: 调用方传入的新或旧环境变量名。
Returns:
str: 规范环境变量名;非 RPA 变量原样返回。
"""
if name in _RPA_LEGACY_TO_CANONICAL:
return _RPA_LEGACY_TO_CANONICAL[name]
if name.startswith("FREIGHT_RPA_"):
return f"SHIPPING_NOTICE_RPA_WORKER_{name.removeprefix('FREIGHT_RPA_')}"
return name
def _legacy_rpa_env_name(name: str) -> str | None:
"""
返回规范 RPA 环境变量对应的历史名称,供过渡期只读兼容。
Args:
name: 规范环境变量名。
Returns:
str | None: 历史名称;不存在历史名称时返回 None。
"""
for legacy, canonical in _RPA_LEGACY_TO_CANONICAL.items():
if canonical == name:
return legacy
if name.startswith("SHIPPING_NOTICE_RPA_WORKER_"):
return f"FREIGHT_RPA_{name.removeprefix('SHIPPING_NOTICE_RPA_WORKER_')}"
return None
def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None: def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str, data: dict[str, Any] | None = None) -> None:
"""惰性委托 dsv_debug.emit_debug_event,避免 rpa_common ↔ dsv_debug 循环导入。""" """惰性委托 dsv_debug.emit_debug_event,避免 rpa_common ↔ dsv_debug 循环导入。"""
try: try:
@@ -98,31 +44,19 @@ def _emit_debug_event(run_id: str, hypothesis_id: str, location: str, msg: str,
def _env(name: str, default: str = "") -> str: def _env(name: str, default: str = "") -> str:
""" """
读取 RPA 环境变量,并兼容历史变量名与外层单双引号写法。 读取 RPA 环境变量,并去除首尾空白与最外层成对引号。
核心逻辑:规范名称优先;仅当新名称未设置时读取旧名称并发出弃用警告。 核心逻辑:直接读取规范名称;历史 SHIPPING_NOTICE_RPA_* 前缀已于
随后去除首尾空白与最外层成对引号,避免账号密码把引号输入登录页。 2026-09-18 一刀切废弃,不再提供任何别名兼容。
Args: Args:
name: 新或旧环境变量名;RPA 旧名称会自动转换到统一命名空间。 name: 规范环境变量名(FREIGHT_RPA_*)。
default: 未设置时的默认值。 default: 未设置时的默认值。
Returns: Returns:
str: 去除空白与外层成对引号后的环境变量值。 str: 去除空白与外层成对引号后的环境变量值。
""" """
canonical_name = _canonical_rpa_env_name(name) value = str(os.getenv(name, default) or default).strip()
legacy_name = _legacy_rpa_env_name(canonical_name)
raw_value = os.getenv(canonical_name)
if raw_value is None and legacy_name:
raw_value = os.getenv(legacy_name)
if raw_value is not None and 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)
value = str(raw_value if raw_value is not None else default).strip()
if len(value) >= 2 and ( if len(value) >= 2 and (
(value.startswith('"') and value.endswith('"')) (value.startswith('"') and value.endswith('"'))
or (value.startswith("'") and value.endswith("'")) or (value.startswith("'") and value.endswith("'"))
@@ -132,7 +66,7 @@ def _env(name: str, default: str = "") -> str:
def _browser_timeout_ms() -> int: def _browser_timeout_ms() -> int:
return max(5_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_TIMEOUT_MS", "60000") or "60000")) return max(5_000, int(_env("FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS", "60000") or "60000"))
def _click_text(page: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> None: def _click_text(page: Any, text: str, *, exact: bool = True, timeout_ms: int | None = None) -> None:
timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms() timeout = timeout_ms if timeout_ms is not None else _browser_timeout_ms()
@@ -177,7 +111,7 @@ def _click_selector_or_text(page: Any, selector_env: str, fallback_text: str | N
if selector: if selector:
page.locator(selector).first.click(timeout=_browser_timeout_ms()) page.locator(selector).first.click(timeout=_browser_timeout_ms())
return return
if selector_env == "SHIPPING_NOTICE_RPA_WORKER_DSV_VIEW_REPORT_SELECTOR": if selector_env == "FREIGHT_RPA_WORKER_DSV_VIEW_REPORT_SELECTOR":
for view_selector in ( for view_selector in (
'input[type="submit"][value="View Report"]', 'input[type="submit"][value="View Report"]',
'button:has-text("View Report")', 'button:has-text("View Report")',
@@ -486,14 +420,14 @@ def _maybe_auto_login(page: Any, prefix: str) -> None:
""" """
如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。 如页面出现登录框,则用 RPA 机器环境变量自动登录;未出现登录框则复用现有浏览器登录态。
""" """
username_env = f"SHIPPING_NOTICE_RPA_WORKER_{prefix}_USERNAME" username_env = f"FREIGHT_RPA_WORKER_{prefix}_USERNAME"
password_env = f"SHIPPING_NOTICE_RPA_WORKER_{prefix}_PASSWORD" password_env = f"FREIGHT_RPA_WORKER_{prefix}_PASSWORD"
if not _env(username_env) or not _env(password_env): if not _env(username_env) or not _env(password_env):
return return
user_filled = _fill_login_field( user_filled = _fill_login_field(
page, page,
f"SHIPPING_NOTICE_RPA_WORKER_{prefix}_USERNAME_SELECTOR", f"FREIGHT_RPA_WORKER_{prefix}_USERNAME_SELECTOR",
username_env, username_env,
( (
'input[name="username"]', 'input[name="username"]',
@@ -505,7 +439,7 @@ def _maybe_auto_login(page: Any, prefix: str) -> None:
) )
password_filled = _fill_login_field( password_filled = _fill_login_field(
page, page,
f"SHIPPING_NOTICE_RPA_WORKER_{prefix}_PASSWORD_SELECTOR", f"FREIGHT_RPA_WORKER_{prefix}_PASSWORD_SELECTOR",
password_env, password_env,
('input[name="password"]', 'input[type="password"]'), ('input[name="password"]', 'input[type="password"]'),
) )
@@ -516,7 +450,7 @@ def _maybe_auto_login(page: Any, prefix: str) -> None:
if not _click_login_submit( if not _click_login_submit(
page, page,
f"SHIPPING_NOTICE_RPA_WORKER_{prefix}_LOGIN_BUTTON_SELECTOR", f"FREIGHT_RPA_WORKER_{prefix}_LOGIN_BUTTON_SELECTOR",
("Sign in", "Login", "Log in", "登录"), ("Sign in", "Login", "Log in", "登录"),
): ):
raise RuntimeError(f"{prefix} login fields detected but submit button was not found") raise RuntimeError(f"{prefix} login fields detected but submit button was not found")
@@ -1,9 +1,9 @@
""" """
scripts/rpa/common/rpa_heartbeat.py scripts/freight_rpa/common/rpa_heartbeat.py
用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。 用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
依赖:rpa_common.env、urllib、socket。 依赖:rpa_common.env、urllib、socket。
逻辑:由 freight_rpa_worker 主循环按 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;同步写入共享目录哨兵文件。 逻辑:由 freight_rpa_worker 主循环按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 周期调用;同步写入共享目录哨兵文件。
""" """
from __future__ import annotations from __future__ import annotations
@@ -57,7 +57,7 @@ def get_worker_runtime_status() -> str:
def _resolve_worker_environment() -> str: def _resolve_worker_environment() -> str:
raw = ( raw = (
_env("SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT") _env("FREIGHT_RPA_WORKER_ENVIRONMENT")
or _env("ENV_NAME") or _env("ENV_NAME")
or _env("HXOPS_ENV") or _env("HXOPS_ENV")
or "dev" or "dev"
@@ -74,14 +74,14 @@ def _resolve_worker_environment() -> str:
def _resolve_shared_scope_id() -> str: def _resolve_shared_scope_id() -> str:
raw = ( raw = (
_env("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID") _env("FREIGHT_RPA_SHARED_SCOPE_ID")
or _env("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID") or _env("FREIGHT_RPA_SHARED_SCOPE_ID")
or "" or ""
) )
value = str(raw or "").strip() value = str(raw or "").strip()
if value: if value:
return value return value
trigger = str(_env("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR") or "").replace("\\", "/").lower() trigger = str(_env("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR") or "").replace("\\", "/").lower()
for token in ("hxops-rpa-test-data", "hxops-rpa-prod-data"): for token in ("hxops-rpa-test-data", "hxops-rpa-prod-data"):
if token in trigger: if token in trigger:
return token return token
@@ -90,14 +90,14 @@ def _resolve_shared_scope_id() -> str:
def _resolve_sentinel_name() -> str: def _resolve_sentinel_name() -> str:
return str( return str(
_env("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME") _env("FREIGHT_RPA_SHARED_SENTINEL_NAME")
or _env("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME") or _env("FREIGHT_RPA_SHARED_SENTINEL_NAME")
or _DEFAULT_SENTINEL_NAME or _DEFAULT_SENTINEL_NAME
).strip() or _DEFAULT_SENTINEL_NAME ).strip() or _DEFAULT_SENTINEL_NAME
def _resolve_worker_id(hostname: str) -> str: def _resolve_worker_id(hostname: str) -> str:
explicit = str(_env("SHIPPING_NOTICE_RPA_WORKER_ID") or "").strip() explicit = str(_env("FREIGHT_RPA_WORKER_ID") or "").strip()
if explicit: if explicit:
return explicit return explicit
pid = os.getpid() pid = os.getpid()
@@ -139,7 +139,7 @@ def build_heartbeat_payload(
""" """
hostname = socket.gethostname() hostname = socket.gethostname()
capabilities = ["inventory_export"] capabilities = ["inventory_export"]
upload_enabled = str(_env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in { upload_enabled = str(_env("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "false") or "false").strip().lower() in {
"1", "true", "yes", "on", "1", "true", "yes", "on",
} }
if upload_enabled: if upload_enabled:
@@ -153,7 +153,7 @@ def build_heartbeat_payload(
"trigger_dir": str(trigger_dir), "trigger_dir": str(trigger_dir),
"drop_dir": str(drop_dir), "drop_dir": str(drop_dir),
"shared_scope_id": _resolve_shared_scope_id(), "shared_scope_id": _resolve_shared_scope_id(),
"version": str(_env("SHIPPING_NOTICE_RPA_WORKER_VERSION", "rpa-poc") or "rpa-poc"), "version": str(_env("FREIGHT_RPA_WORKER_VERSION", "rpa-poc") or "rpa-poc"),
"timestamp": datetime.now(UTC).replace(tzinfo=None).isoformat(), "timestamp": datetime.now(UTC).replace(tzinfo=None).isoformat(),
} }
@@ -236,12 +236,12 @@ def maybe_send_heartbeat(
force: bool = False, force: bool = False,
) -> float: ) -> float:
""" """
按 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS 节流发送心跳。 按 FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS 节流发送心跳。
Returns: Returns:
float: 最近一次尝试后的 monotonic 时间戳(成功或失败均更新节流时钟)。 float: 最近一次尝试后的 monotonic 时间戳(成功或失败均更新节流时钟)。
""" """
global _LAST_HEARTBEAT_MONO global _LAST_HEARTBEAT_MONO
interval = max(15, int(_env("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20")) interval = max(15, int(_env("FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"))
now = time.monotonic() now = time.monotonic()
if not force and last_sent_mono and (now - last_sent_mono) < interval: if not force and last_sent_mono and (now - last_sent_mono) < interval:
return last_sent_mono return last_sent_mono
@@ -1,5 +1,5 @@
""" """
scripts/rpa/common/worker_disk_cleanup.py scripts/freight_rpa/common/worker_disk_cleanup.py
用途:RPA Worker 本机磁盘保留清理,防止 logs / 归档 trigger / drop 归档 / 孤儿临时 Profile 长期堆积撑爆盘符。 用途:RPA Worker 本机磁盘保留清理,防止 logs / 归档 trigger / drop 归档 / 孤儿临时 Profile 长期堆积撑爆盘符。
依赖:rpa_common.env、pathlib、shutil、time。 依赖:rpa_common.env、pathlib、shutil、time。
@@ -83,27 +83,27 @@ def retention_days() -> int:
""" """
读取归档保留天数。 读取归档保留天数。
核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7; 核心逻辑:`FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7;
`<=0` 表示禁用按天清理(仍可单独清理孤儿临时 Profile,见 orphan 配置)。 `<=0` 表示禁用按天清理(仍可单独清理孤儿临时 Profile,见 orphan 配置)。
Returns: Returns:
int: 保留天数;禁用时为 0。 int: 保留天数;禁用时为 0。
""" """
return _int_env("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", _DEFAULT_RETENTION_DAYS, min_value=0) return _int_env("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", _DEFAULT_RETENTION_DAYS, min_value=0)
def cleanup_interval_seconds() -> int: def cleanup_interval_seconds() -> int:
""" """
读取清理周期秒数。 读取清理周期秒数。
核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS`,默认 3600; 核心逻辑:`FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS`,默认 3600;
最小值 60,避免主循环过于频繁扫盘。 最小值 60,避免主循环过于频繁扫盘。
Returns: Returns:
int: 清理间隔秒数。 int: 清理间隔秒数。
""" """
return _int_env( return _int_env(
"SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS", "FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS",
_DEFAULT_INTERVAL_SECONDS, _DEFAULT_INTERVAL_SECONDS,
min_value=60, min_value=60,
) )
@@ -113,14 +113,14 @@ def orphan_profile_max_age_seconds() -> int:
""" """
读取孤儿临时 Profile(run_* / receipt_*)最大存活秒数。 读取孤儿临时 Profile(run_* / receipt_*)最大存活秒数。
核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24; 核心逻辑:`FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24;
`<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。 `<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。
Returns: Returns:
int: 最大存活秒数;禁用时为 0。 int: 最大存活秒数;禁用时为 0。
""" """
hours = _int_env( hours = _int_env(
"SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS",
_DEFAULT_ORPHAN_PROFILE_HOURS, _DEFAULT_ORPHAN_PROFILE_HOURS,
min_value=0, min_value=0,
) )
@@ -1,9 +1,9 @@
"""scripts/rpa/common/worker_logging.py """scripts/freight_rpa/common/worker_logging.py
用途:RPA Worker 通用文件日志——stdout/stderr tee 落盘、行级本地时间戳、 用途:RPA Worker 通用文件日志——stdout/stderr tee 落盘、行级本地时间戳、
按大小轮转(启动前 + 运行中),供库存/收料等所有 Worker 复用。 按大小轮转(启动前 + 运行中),供库存/收料等所有 Worker 复用。
依赖:rpa_common._env(环境变量读取与历史名兼容)、标准库。 依赖:rpa_common._env(环境变量读取与历史名兼容)、标准库。
逻辑:configure_file_logging 读 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用; 逻辑:configure_file_logging 读 FREIGHT_RPA_WORKER_LOG_FILE 启用;
maybe_rotate_open_log 在主循环周期调用做运行中轮转;shutdown_logging 恢复标准流。 maybe_rotate_open_log 在主循环周期调用做运行中轮转;shutdown_logging 恢复标准流。
""" """
@@ -19,7 +19,7 @@ from rpa_common import _env
def _backend_dir() -> Path: def _backend_dir() -> Path:
"""返回仓库内 backend 根目录(本模块位于 <repo>/scripts/rpa/common/)。""" """返回仓库内 backend 根目录(本模块位于 <repo>/scripts/freight_rpa/common/)。"""
return Path(__file__).resolve().parents[3] / "backend" return Path(__file__).resolve().parents[3] / "backend"
@@ -114,7 +114,7 @@ _ACTIVE_LOG_HANDLE: TextIO | None = None
def configure_file_logging() -> Path | None: def configure_file_logging() -> Path | None:
""" """
按 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用 worker 文件日志。 按 FREIGHT_RPA_WORKER_LOG_FILE 启用 worker 文件日志。
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量, 【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查 让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
@@ -126,7 +126,7 @@ def configure_file_logging() -> Path | None:
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
if _ACTIVE_LOG_PATH is not None: if _ACTIVE_LOG_PATH is not None:
return _ACTIVE_LOG_PATH return _ACTIVE_LOG_PATH
raw = _env("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE") raw = _env("FREIGHT_RPA_WORKER_LOG_FILE")
if not raw: if not raw:
return None return None
path = Path(raw).expanduser() path = Path(raw).expanduser()
@@ -196,7 +196,7 @@ def maybe_rotate_open_log() -> None:
handle = _ACTIVE_LOG_HANDLE handle = _ACTIVE_LOG_HANDLE
if path is None or stdout_tee is None or stderr_tee is None or handle is None: if path is None or stdout_tee is None or stderr_tee is None or handle is None:
return return
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0) max_bytes = _log_int_env("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
if max_bytes <= 0: if max_bytes <= 0:
return return
try: try:
@@ -222,12 +222,12 @@ def rotate_log_file_if_needed(path: Path) -> None:
""" """
在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。 在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。
核心逻辑:当 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 已存在且大小达到 `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES` 核心逻辑:当 `FREIGHT_RPA_WORKER_LOG_FILE` 已存在且大小达到 `FREIGHT_RPA_WORKER_LOG_MAX_BYTES`
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT` 时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT`
的旧文件会被删除。`SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES<=0` 时禁用轮转。 的旧文件会被删除。`FREIGHT_RPA_WORKER_LOG_MAX_BYTES<=0` 时禁用轮转。
""" """
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0) max_bytes = _log_int_env("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
backup_count = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", 5, min_value=0) backup_count = _log_int_env("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", 5, min_value=0)
if max_bytes <= 0 or not path.is_file(): if max_bytes <= 0 or not path.is_file():
return return
try: try:
@@ -1,13 +1,13 @@
""" """
scripts/rpa/crane_login_smoke.py scripts/freight_rpa/crane_login_smoke.py
用途:本地手动验证 Crane FootPrint Portal 自动登录。 用途:本地手动验证 Crane FootPrint Portal 自动登录。
依赖:Playwright、SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD。 依赖:Playwright、FREIGHT_RPA_WORKER_CRANE_USERNAME / FREIGHT_RPA_WORKER_CRANE_PASSWORD。
逻辑:打开 On Hand Details Query 入口 → maybe_auto_login_crane → 保持窗口供人工确认。 逻辑:打开 On Hand Details Query 入口 → maybe_auto_login_crane → 保持窗口供人工确认。
用法(仓库根目录): 用法(仓库根目录):
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" $env:FREIGHT_RPA_WORKER_HEADLESS = "false"
backend\\venv\\Scripts\\python.exe scripts\\rpa\\crane_login_smoke.py backend\\venv\\Scripts\\python.exe scripts\\freight_rpa\\crane_login_smoke.py
""" """
from __future__ import annotations from __future__ import annotations
@@ -22,7 +22,7 @@ from pathlib import Path
def _load_worker(): def _load_worker():
repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2]) repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2])
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_crane_smoke", module_path) spec = importlib.util.spec_from_file_location("inventory_rpa_worker_crane_smoke", module_path)
assert spec and spec.loader assert spec and spec.loader
module = importlib.util.module_from_spec(spec) module = importlib.util.module_from_spec(spec)
@@ -31,26 +31,26 @@ def _load_worker():
def main() -> int: def main() -> int:
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") os.environ.setdefault("FREIGHT_RPA_WORKER_HEADLESS", "false")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") os.environ.setdefault("FREIGHT_RPA_WORKER_MOCK", "false")
os.environ.setdefault( os.environ.setdefault(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile", "backend/data/shipping_notice/freight_rpa/browser_profile",
) )
# 不默认 msedge:未设置 CHANNEL 时走 Playwright 捆绑 Chromium(需先 playwright install chromium)。 # 不默认 msedge:未设置 CHANNEL 时走 Playwright 捆绑 Chromium(需先 playwright install chromium)。
worker = _load_worker() worker = _load_worker()
username = worker._env("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME") username = worker._env("FREIGHT_RPA_WORKER_CRANE_USERNAME")
password = worker._env("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD") password = worker._env("FREIGHT_RPA_WORKER_CRANE_PASSWORD")
if not username or not password: if not username or not password:
print("[crane-smoke] 缺少 SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD,请先配置环境变量。") print("[crane-smoke] 缺少 FREIGHT_RPA_WORKER_CRANE_USERNAME / FREIGHT_RPA_WORKER_CRANE_PASSWORD,请先配置环境变量。")
return 1 return 1
entry_url = "https://wms-portal.craneww.com/#/on-hand-details-query" entry_url = "https://wms-portal.craneww.com/#/on-hand-details-query"
drop_dir = Path(tempfile.mkdtemp(prefix="crane_smoke_drop_")) drop_dir = Path(tempfile.mkdtemp(prefix="crane_smoke_drop_"))
playwright = context = runtime_profile_dir = None playwright = context = runtime_profile_dir = None
print(f"[crane-smoke] headless={worker._env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false')}") print(f"[crane-smoke] headless={worker._env('FREIGHT_RPA_WORKER_HEADLESS', 'false')}")
print(f"[crane-smoke] user={username[:3]}*** entry={entry_url}") print(f"[crane-smoke] user={username[:3]}*** entry={entry_url}")
print("[crane-smoke] 正在打开浏览器并执行 Crane 自动登录…") print("[crane-smoke] 正在打开浏览器并执行 Crane 自动登录…")
@@ -1,5 +1,5 @@
""" """
scripts/rpa/crane_navigation.py scripts/freight_rpa/crane_navigation.py
用途:Crane FootPrint Portal 报表页导航(On Hand Details Query)。 用途:Crane FootPrint Portal 报表页导航(On Hand Details Query)。
依赖:Playwright Page;由 crane_session.wait_for_crane_app_ready 在登录后调用。 依赖:Playwright Page;由 crane_session.wait_for_crane_app_ready 在登录后调用。
@@ -230,7 +230,7 @@ def _click_dashboard_on_hand_details(
selectors = tuple( selectors = tuple(
item item
for item in (env("SHIPPING_NOTICE_RPA_WORKER_CRANE_DASHBOARD_REPORT_SELECTOR"), *_CRANE_DASHBOARD_REPORT_TILE_SELECTORS) for item in (env("FREIGHT_RPA_WORKER_CRANE_DASHBOARD_REPORT_SELECTOR"), *_CRANE_DASHBOARD_REPORT_TILE_SELECTORS)
if item if item
) )
for selector in selectors: for selector in selectors:
@@ -248,7 +248,7 @@ def _click_dashboard_on_hand_details(
def _open_queries_nav_menu(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool: def _open_queries_nav_menu(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool:
"""展开顶部 Queries 下拉菜单。""" """展开顶部 Queries 下拉菜单。"""
selectors = tuple( selectors = tuple(
item for item in (env("SHIPPING_NOTICE_RPA_WORKER_CRANE_NAV_QUERIES_SELECTOR"), *_CRANE_NAV_QUERIES_MENU_SELECTORS) if item item for item in (env("FREIGHT_RPA_WORKER_CRANE_NAV_QUERIES_SELECTOR"), *_CRANE_NAV_QUERIES_MENU_SELECTORS) if item
) )
for selector in selectors: for selector in selectors:
locator = _visible_locator(page, selector) locator = _visible_locator(page, selector)
@@ -295,7 +295,7 @@ def _click_navbar_on_hand_details(
time.sleep(0.35) time.sleep(0.35)
selectors = tuple( selectors = tuple(
item for item in (env("SHIPPING_NOTICE_RPA_WORKER_CRANE_NAV_REPORT_SELECTOR"), *_CRANE_NAV_ON_HAND_DETAILS_SELECTORS) if item item for item in (env("FREIGHT_RPA_WORKER_CRANE_NAV_REPORT_SELECTOR"), *_CRANE_NAV_ON_HAND_DETAILS_SELECTORS) if item
) )
for selector in selectors: for selector in selectors:
locator = _visible_locator(page, selector) locator = _visible_locator(page, selector)
@@ -1,5 +1,5 @@
""" """
scripts/rpa/crane_report_export.py scripts/freight_rpa/crane_report_export.py
用途:Crane On Hand Details Query 异步报表导出(Run Report → Schedule Report → Scheduled Reports 下载)。 用途:Crane On Hand Details Query 异步报表导出(Run Report → Schedule Report → Scheduled Reports 下载)。
依赖:Playwright Page、download_artifact_fallback;由 inventory_rpa_worker._export_crane_inventory_source 委托调用。 依赖:Playwright Page、download_artifact_fallback;由 inventory_rpa_worker._export_crane_inventory_source 委托调用。
@@ -340,9 +340,9 @@ def _fill_crane_report_parameters(
query = source.get("query") if isinstance(source.get("query"), dict) else {} query = source.get("query") if isinstance(source.get("query"), dict) else {}
if query.get("owner_code"): if query.get("owner_code"):
select_or_fill(page, "SHIPPING_NOTICE_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code")) select_or_fill(page, "FREIGHT_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", query.get("owner_code"))
if query.get("project_code"): if query.get("project_code"):
select_or_fill(page, "SHIPPING_NOTICE_RPA_WORKER_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code")) select_or_fill(page, "FREIGHT_RPA_WORKER_CRANE_PROJECT_SELECTOR", "Select Project...", query.get("project_code"))
def _crane_parameter_selector_env(parameter_name: str) -> str: def _crane_parameter_selector_env(parameter_name: str) -> str:
@@ -351,8 +351,8 @@ def _crane_parameter_selector_env(parameter_name: str) -> str:
库存源只传递参数名与值;无已知映射时仍依靠标签作通用匹配。 库存源只传递参数名与值;无已知映射时仍依靠标签作通用匹配。
""" """
return { return {
"owner": "SHIPPING_NOTICE_RPA_WORKER_CRANE_OWNER_SELECTOR", "owner": "FREIGHT_RPA_WORKER_CRANE_OWNER_SELECTOR",
"project": "SHIPPING_NOTICE_RPA_WORKER_CRANE_PROJECT_SELECTOR", "project": "FREIGHT_RPA_WORKER_CRANE_PROJECT_SELECTOR",
}.get(str(parameter_name or "").strip().lower(), "") }.get(str(parameter_name or "").strip().lower(), "")
@@ -360,7 +360,7 @@ def _click_run_report(page: Any, *, env: Callable[[str, str], str], browser_time
"""点击表单底部 Run Report。""" """点击表单底部 Run Report。"""
if _click_first_visible( if _click_first_visible(
page, page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_RUN_SELECTOR", selector_env="FREIGHT_RPA_WORKER_CRANE_RUN_SELECTOR",
env=env, env=env,
fallback_selectors=_CRANE_RUN_REPORT_SELECTORS, fallback_selectors=_CRANE_RUN_REPORT_SELECTORS,
role_name="Run Report", role_name="Run Report",
@@ -374,7 +374,7 @@ def _click_schedule_report(page: Any, *, env: Callable[[str, str], str], browser
"""点击右上角 Schedule Report(含 file_download 图标)。""" """点击右上角 Schedule Report(含 file_download 图标)。"""
if _click_first_visible( if _click_first_visible(
page, page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_REPORT_SELECTOR", selector_env="FREIGHT_RPA_WORKER_CRANE_SCHEDULE_REPORT_SELECTOR",
env=env, env=env,
fallback_selectors=_CRANE_SCHEDULE_REPORT_SELECTORS, fallback_selectors=_CRANE_SCHEDULE_REPORT_SELECTORS,
role_name="Schedule Report", role_name="Schedule Report",
@@ -386,7 +386,7 @@ def _click_schedule_report(page: Any, *, env: Callable[[str, str], str], browser
def _schedule_description_hex_len(env: Callable[[str, str], str]) -> int: def _schedule_description_hex_len(env: Callable[[str, str], str]) -> int:
"""读取 Description 十六进制长度;默认 12,上限 32(完整 uuid4.hex)。""" """读取 Description 十六进制长度;默认 12,上限 32(完整 uuid4.hex)。"""
raw = str(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN", "") or "").strip() raw = str(env("FREIGHT_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN", "") or "").strip()
if not raw: if not raw:
return _CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT return _CRANE_SCHEDULE_DESCRIPTION_HEX_LEN_DEFAULT
try: try:
@@ -404,9 +404,9 @@ def _build_schedule_description(
) -> str: ) -> str:
""" """
生成 Schedule Report 弹窗 Description,用于 Scheduled Reports 列表唯一识别。 生成 Schedule Report 弹窗 Description,用于 Scheduled Reports 列表唯一识别。
核心逻辑:默认取 UUID4 前 12 位 hex(无连字符);可用 SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION 覆盖。 核心逻辑:默认取 UUID4 前 12 位 hex(无连字符);可用 FREIGHT_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION 覆盖。
""" """
override = str(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION", "") or "").strip() override = str(env("FREIGHT_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION", "") or "").strip()
if override: if override:
return override[:120] return override[:120]
@@ -417,7 +417,7 @@ def _build_schedule_description(
def _wait_for_schedule_modal(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> Any | None: def _wait_for_schedule_modal(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> Any | None:
"""等待 Schedule Report 弹窗出现。""" """等待 Schedule Report 弹窗出现。"""
selectors = tuple( selectors = tuple(
item for item in (env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_MODAL_SELECTOR"), *_CRANE_SCHEDULE_MODAL_SELECTORS) if item item for item in (env("FREIGHT_RPA_WORKER_CRANE_SCHEDULE_MODAL_SELECTOR"), *_CRANE_SCHEDULE_MODAL_SELECTORS) if item
) )
deadline = time.monotonic() + (min(browser_timeout_ms, 15_000) / 1000) deadline = time.monotonic() + (min(browser_timeout_ms, 15_000) / 1000)
while time.monotonic() < deadline: while time.monotonic() < deadline:
@@ -442,7 +442,7 @@ def _fill_schedule_description(
return False return False
selectors = tuple( selectors = tuple(
item for item in (env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_SELECTOR"), *_CRANE_SCHEDULE_DESCRIPTION_SELECTORS) item for item in (env("FREIGHT_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_SELECTOR"), *_CRANE_SCHEDULE_DESCRIPTION_SELECTORS)
if item if item
) )
for selector in selectors: for selector in selectors:
@@ -469,7 +469,7 @@ def _fill_schedule_description(
def _click_schedule_modal_ok(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool: def _click_schedule_modal_ok(page: Any, *, env: Callable[[str, str], str], browser_timeout_ms: int) -> bool:
"""点击 Schedule Report 弹窗 Ok 按钮。""" """点击 Schedule Report 弹窗 Ok 按钮。"""
selectors = tuple(item for item in (env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_OK_SELECTOR"), *_CRANE_SCHEDULE_OK_SELECTORS) if item) selectors = tuple(item for item in (env("FREIGHT_RPA_WORKER_CRANE_SCHEDULE_OK_SELECTOR"), *_CRANE_SCHEDULE_OK_SELECTORS) if item)
for selector in selectors: for selector in selectors:
locator = _visible_locator(page, selector) locator = _visible_locator(page, selector)
if locator is not None and _click_locator(locator, browser_timeout_ms=browser_timeout_ms): if locator is not None and _click_locator(locator, browser_timeout_ms=browser_timeout_ms):
@@ -544,7 +544,7 @@ def _wait_for_report_submission_complete(
等待 Ok 后的 Report Submitted 等待态结束,再进入 Scheduled Reports。 等待 Ok 后的 Report Submitted 等待态结束,再进入 Scheduled Reports。
核心逻辑:先等提示出现,再等提示消失(或超时后继续并打日志)。 核心逻辑:先等提示出现,再等提示消失(或超时后继续并打日志)。
""" """
total_ms = int(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SUBMISSION_COMPLETE_WAIT_MS", "45000") or "45000") total_ms = int(env("FREIGHT_RPA_WORKER_CRANE_SUBMISSION_COMPLETE_WAIT_MS", "45000") or "45000")
appear_ms = min(30_000, total_ms) appear_ms = min(30_000, total_ms)
deadline = time.monotonic() + (total_ms / 1000) deadline = time.monotonic() + (total_ms / 1000)
appear_deadline = time.monotonic() + (appear_ms / 1000) appear_deadline = time.monotonic() + (appear_ms / 1000)
@@ -682,8 +682,8 @@ def _probe_scheduled_download_status(
if not text or not report_name: if not text or not report_name:
return None, None return None, None
table_selector = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_TABLE_SELECTOR") or _CRANE_SCHEDULED_TABLE_SELECTOR table_selector = env("FREIGHT_RPA_WORKER_CRANE_SCHEDULED_TABLE_SELECTOR") or _CRANE_SCHEDULED_TABLE_SELECTOR
max_rows = int(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_SCAN_MAX_ROWS", str(_CRANE_SCHEDULED_SCAN_MAX_ROWS_DEFAULT)) or "20") max_rows = int(env("FREIGHT_RPA_WORKER_CRANE_SCHEDULED_SCAN_MAX_ROWS", str(_CRANE_SCHEDULED_SCAN_MAX_ROWS_DEFAULT)) or "20")
for root in (page, *list(getattr(page, "frames", []))): for root in (page, *list(getattr(page, "frames", []))):
try: try:
@@ -787,7 +787,7 @@ def _goto_scheduled_reports_hash(page: Any, *, env: Callable[[str, str], str], b
def _scheduled_reports_url(page: Any, *, env: Callable[[str, str], str]) -> str: def _scheduled_reports_url(page: Any, *, env: Callable[[str, str], str]) -> str:
"""构造 Scheduled Reports 页面 URL(用于链接点击失败时 goto)。""" """构造 Scheduled Reports 页面 URL(用于链接点击失败时 goto)。"""
override = str(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORTS_URL", "") or "").strip() override = str(env("FREIGHT_RPA_WORKER_CRANE_SCHEDULED_REPORTS_URL", "") or "").strip()
if override: if override:
return override return override
try: try:
@@ -824,7 +824,7 @@ def _open_scheduled_reports(
if _click_first_visible( if _click_first_visible(
page, page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORTS_SELECTOR", selector_env="FREIGHT_RPA_WORKER_CRANE_SCHEDULED_REPORTS_SELECTOR",
env=env, env=env,
fallback_selectors=_CRANE_SCHEDULED_REPORTS_LINK_SELECTORS, fallback_selectors=_CRANE_SCHEDULED_REPORTS_LINK_SELECTORS,
role_name="Scheduled Reports", role_name="Scheduled Reports",
@@ -883,10 +883,26 @@ def _resolve_scheduled_report_file_name(
source_value = str((source or {}).get('scheduled_report_name') or '').strip() source_value = str((source or {}).get('scheduled_report_name') or '').strip()
if source_value: if source_value:
return source_value return source_value
env_value = str(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_NAME", _CRANE_SCHEDULED_REPORT_NAME_DEFAULT) or "").strip() env_value = str(env("FREIGHT_RPA_WORKER_CRANE_SCHEDULED_REPORT_NAME", _CRANE_SCHEDULED_REPORT_NAME_DEFAULT) or "").strip()
return env_value or _CRANE_SCHEDULED_REPORT_NAME_DEFAULT return env_value or _CRANE_SCHEDULED_REPORT_NAME_DEFAULT
def _normalize_scheduled_report_name(value: Any) -> str:
"""
规范化 Scheduled Reports 行名/期望名,用于相等比较。
核心逻辑:门户行名形如 InboundDetails.xlsx,而适配器/配置侧为 Inbound Details 形态;
直接精确比较永远不等(收料轮询曾因此 25 轮全部 not found)。统一去空白、忽略大小写、
去掉 .xlsx/.xls 扩展名后再比较。
"""
text = str(value or "").strip().lower()
if text.endswith(".xlsx"):
text = text[: -len(".xlsx")]
elif text.endswith(".xls"):
text = text[: -len(".xls")]
return "".join(text.split())
def _row_matches_scheduled_report( def _row_matches_scheduled_report(
row: Any, row: Any,
*, *,
@@ -894,15 +910,15 @@ def _row_matches_scheduled_report(
expected_report_name: str, expected_report_name: str,
) -> bool: ) -> bool:
""" """
判断行是否为目标导出:Name 精确匹配且 Description 为本次 UUID。 判断行是否为目标导出:Name 规范化后相等且 Description 为本次 UUID。
核心逻辑:表按 Submitted 降序,自上而下取首条匹配即最近一笔。 核心逻辑:表按 Submitted 降序,自上而下取首条匹配即最近一笔。
""" """
wanted_name = str(expected_report_name or "").strip() wanted_name = _normalize_scheduled_report_name(expected_report_name)
wanted_description = str(description or "").strip() wanted_description = str(description or "").strip()
if not wanted_name or not wanted_description: if not wanted_name or not wanted_description:
return False return False
name = _read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_NAME) name = _normalize_scheduled_report_name(_read_scheduled_row_cell(row, _CRANE_SCHEDULED_COL_NAME))
if name != wanted_name: if name != wanted_name:
return False return False
@@ -962,7 +978,7 @@ def _wait_and_click_scheduled_download(
轮询 Scheduled Reports 直至目标行 Download 列由 Submitted 变为 Download 并点击。 轮询 Scheduled Reports 直至目标行 Download 列由 Submitted 变为 Download 并点击。
核心逻辑:每 2s 探测一次状态;每 10s goto 刷新列表;表格可见时不重登,避免闪回登录页; 核心逻辑:每 2s 探测一次状态;每 10s goto 刷新列表;表格可见时不重登,避免闪回登录页;
expect_download 超时且已配置 download_dir 时,短窗口扫描目录新文件兜底。 expect_download 超时且已配置 download_dir 时,短窗口扫描目录新文件兜底。
等待上限由 SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_WAIT_MS 控制(默认 600000=10 分钟)。 等待上限由 FREIGHT_RPA_WORKER_CRANE_SCHEDULED_REPORT_WAIT_MS 控制(默认 600000=10 分钟)。
Args: Args:
page: Playwright 页面。 page: Playwright 页面。
@@ -978,13 +994,13 @@ def _wait_and_click_scheduled_download(
""" """
entry = entry_url or _default_crane_entry_url(None) entry = entry_url or _default_crane_entry_url(None)
# 默认 10 分钟:Crane 偶发 Submitted 排队 >5 分钟(见 2026-09-03 ~262s / 2026-09-07 满 300s 失败) # 默认 10 分钟:Crane 偶发 Submitted 排队 >5 分钟(见 2026-09-03 ~262s / 2026-09-07 满 300s 失败)
wait_ms = int(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_WAIT_MS", "600000") or "600000") wait_ms = int(env("FREIGHT_RPA_WORKER_CRANE_SCHEDULED_REPORT_WAIT_MS", "600000") or "600000")
deadline = time.monotonic() + (wait_ms / 1000) deadline = time.monotonic() + (wait_ms / 1000)
poll_seconds = float(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_POLL_SECONDS", "2") or "2") poll_seconds = float(env("FREIGHT_RPA_WORKER_CRANE_SCHEDULED_REPORT_POLL_SECONDS", "2") or "2")
list_refresh_seconds = float( list_refresh_seconds = float(
env( env(
"SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_LIST_REFRESH_SECONDS", "FREIGHT_RPA_WORKER_CRANE_SCHEDULED_REPORT_LIST_REFRESH_SECONDS",
env("SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULED_REPORT_SOFT_REFRESH_SECONDS", "10") or "10", env("FREIGHT_RPA_WORKER_CRANE_SCHEDULED_REPORT_SOFT_REFRESH_SECONDS", "10") or "10",
) )
or "10" or "10"
) )
@@ -1113,7 +1129,7 @@ def _wait_for_run_report_results(
等待 Run Report 内联查询完成后再 Schedule。 等待 Run Report 内联查询完成后再 Schedule。
核心逻辑:页面出现「items found」或结果表首行数据即视为 Run 完成;超时后打日志并继续尝试 Schedule。 核心逻辑:页面出现「items found」或结果表首行数据即视为 Run 完成;超时后打日志并继续尝试 Schedule。
""" """
wait_ms = int(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_RUN_REPORT_WAIT_MS", "180000") or "180000") wait_ms = int(env("FREIGHT_RPA_WORKER_CRANE_RUN_REPORT_WAIT_MS", "180000") or "180000")
deadline = time.monotonic() + (wait_ms / 1000) deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline: while time.monotonic() < deadline:
@@ -1148,7 +1164,7 @@ def _should_run_report_before_schedule(
scheduled_report 模式是否先点 Run Report。 scheduled_report 模式是否先点 Run Report。
核心逻辑:默认 True(Crane 须先 Run 才有可 Schedule 的查询结果);仅 Driver 环境变量可关闭。 核心逻辑:默认 True(Crane 须先 Run 才有可 Schedule 的查询结果);仅 Driver 环境变量可关闭。
""" """
return str(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE", "true") or "true").lower() != "false" return str(env("FREIGHT_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE", "true") or "true").lower() != "false"
def export_crane_inventory_report( def export_crane_inventory_report(
@@ -1191,12 +1207,12 @@ def export_crane_inventory_report(
) )
if download_mode == "file_download": if download_mode == "file_download":
_click_run_report(page, env=env, browser_timeout_ms=browser_timeout_ms) _click_run_report(page, env=env, browser_timeout_ms=browser_timeout_ms)
export_selector = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_EXPORT_SELECTOR") export_selector = env("FREIGHT_RPA_WORKER_CRANE_EXPORT_SELECTOR")
with page.expect_download(timeout=browser_timeout_ms) as download_info: with page.expect_download(timeout=browser_timeout_ms) as download_info:
if export_selector: if export_selector:
page.locator(export_selector).first.click(timeout=browser_timeout_ms) page.locator(export_selector).first.click(timeout=browser_timeout_ms)
else: else:
click_text(page, env("SHIPPING_NOTICE_RPA_WORKER_CRANE_EXPORT_TEXT", "file_download"), exact=True) click_text(page, env("FREIGHT_RPA_WORKER_CRANE_EXPORT_TEXT", "file_download"), exact=True)
return download_info.value return download_info.value
# [STEP 1] Run Report:须先产出查询结果,再 Schedule 异步导出 # [STEP 1] Run Report:须先产出查询结果,再 Schedule 异步导出
@@ -1236,5 +1252,5 @@ def export_crane_inventory_report(
def _resolve_download_mode(source: dict[str, Any], *, env: Callable[[str, str], str]) -> str: def _resolve_download_mode(source: dict[str, Any], *, env: Callable[[str, str], str]) -> str:
"""读取 Crane Driver 导出模式,不允许业务配置或连接配置覆盖。""" """读取 Crane Driver 导出模式,不允许业务配置或连接配置覆盖。"""
mode = str(env("SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE", "scheduled_report") or "scheduled_report").strip().lower() mode = str(env("FREIGHT_RPA_WORKER_CRANE_DOWNLOAD_MODE", "scheduled_report") or "scheduled_report").strip().lower()
return mode if mode in {"scheduled_report", "file_download"} else "scheduled_report" return mode if mode in {"scheduled_report", "file_download"} else "scheduled_report"
@@ -1,5 +1,5 @@
""" """
scripts/rpa/crane_session.py scripts/freight_rpa/crane_session.py
用途:Crane AWS FootPrint Portal 登录、报表导航与 session 检测。 用途:Crane AWS FootPrint Portal 登录、报表导航与 session 检测。
依赖:Playwright Page、crane_navigation;由 freight_rpa_worker._ensure_crane_session 委托调用。 依赖:Playwright Page、crane_navigation;由 freight_rpa_worker._ensure_crane_session 委托调用。
@@ -328,8 +328,8 @@ def maybe_auto_login_crane(
Crane FootPrint 自动登录:User Name → Password → Sign in。 Crane FootPrint 自动登录:User Name → Password → Sign in。
核心逻辑:页面无登录框则跳过;填写后等待离开登录页并进入报表路由。 核心逻辑:页面无登录框则跳过;填写后等待离开登录页并进入报表路由。
""" """
username = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME") username = env("FREIGHT_RPA_WORKER_CRANE_USERNAME")
password = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD") password = env("FREIGHT_RPA_WORKER_CRANE_PASSWORD")
if not username or not password: if not username or not password:
return return
@@ -339,7 +339,7 @@ def maybe_auto_login_crane(
user_filled = _fill_crane_field( user_filled = _fill_crane_field(
page, page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR", selector_env="FREIGHT_RPA_WORKER_CRANE_USERNAME_SELECTOR",
value=username, value=username,
env=env, env=env,
browser_timeout_ms=browser_timeout_ms, browser_timeout_ms=browser_timeout_ms,
@@ -349,7 +349,7 @@ def maybe_auto_login_crane(
) )
password_filled = _fill_crane_field( password_filled = _fill_crane_field(
page, page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR", selector_env="FREIGHT_RPA_WORKER_CRANE_PASSWORD_SELECTOR",
value=password, value=password,
env=env, env=env,
browser_timeout_ms=browser_timeout_ms, browser_timeout_ms=browser_timeout_ms,
@@ -365,7 +365,7 @@ def maybe_auto_login_crane(
if not _click_crane_login_submit( if not _click_crane_login_submit(
page, page,
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR", selector_env="FREIGHT_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
env=env, env=env,
browser_timeout_ms=browser_timeout_ms, browser_timeout_ms=browser_timeout_ms,
): ):
@@ -1,5 +1,5 @@
""" """
scripts/rpa/connectors/dsv/dsv_auth.py scripts/freight_rpa/connectors/dsv/dsv_auth.py
用途:DSV 360 PingID 分步登录(邮箱 → 可选切简体 → 密码方式 → 密码 → portal)。 用途:DSV 360 PingID 分步登录(邮箱 → 可选切简体 → 密码方式 → 密码 → portal)。
依赖:rpa_common、dsv_debug;登录主编排见 dsv_auth_login_flow。 依赖:rpa_common、dsv_debug;登录主编排见 dsv_auth_login_flow。
@@ -89,7 +89,7 @@ def _is_dsv_password_method_label(text: str) -> bool:
def _dsv_switch_zh_cn_enabled() -> bool: def _dsv_switch_zh_cn_enabled() -> bool:
"""是否启用「英文登录页尝试切中文简体」加固;默认开启,可用环境变量关闭。""" """是否启用「英文登录页尝试切中文简体」加固;默认开启,可用环境变量关闭。"""
raw = str(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_SWITCH_ZH_CN", "true") or "true").strip().lower() raw = str(_env("FREIGHT_RPA_WORKER_DSV_SWITCH_ZH_CN", "true") or "true").strip().lower()
return raw not in {"0", "false", "no", "off"} return raw not in {"0", "false", "no", "off"}
@@ -216,7 +216,7 @@ def _click_dsv_password_method(page: Any) -> bool:
return True return True
return _wait_for_visible_selector( return _wait_for_visible_selector(
page, page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_SELECTOR", "FREIGHT_RPA_WORKER_DSV_PASSWORD_SELECTOR",
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'), ("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
timeout_ms=250, timeout_ms=250,
) is not None ) is not None
@@ -540,8 +540,8 @@ _DSV_PASSWORD_UPGRADE_PROMPT_MARKERS: tuple[str, ...] = (
def _dsv_maybe_later_selector_candidates() -> tuple[str, ...]: def _dsv_maybe_later_selector_candidates() -> tuple[str, ...]:
"""返回“也许以后 / Maybe later”按钮候选选择器;支持 SHIPPING_NOTICE_RPA_WORKER_DSV_MAYBE_LATER_SELECTOR 覆盖。""" """返回“也许以后 / Maybe later”按钮候选选择器;支持 FREIGHT_RPA_WORKER_DSV_MAYBE_LATER_SELECTOR 覆盖。"""
selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_MAYBE_LATER_SELECTOR") selector = _env("FREIGHT_RPA_WORKER_DSV_MAYBE_LATER_SELECTOR")
return (selector,) if selector else _DSV_MAYBE_LATER_SELECTORS return (selector,) if selector else _DSV_MAYBE_LATER_SELECTORS
@@ -828,7 +828,7 @@ def _has_dsv_human_check_prompt(page: Any) -> bool:
def _wait_for_dsv_login_method_page(page: Any, timeout_ms: int | None = None) -> bool: def _wait_for_dsv_login_method_page(page: Any, timeout_ms: int | None = None) -> bool:
wait_ms = timeout_ms if timeout_ms is not None else max(5_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_METHOD_PAGE_TIMEOUT_MS", "20000") or "20000")) wait_ms = timeout_ms if timeout_ms is not None else max(5_000, int(_env("FREIGHT_RPA_WORKER_DSV_METHOD_PAGE_TIMEOUT_MS", "20000") or "20000"))
deadline = time.monotonic() + (wait_ms / 1000) deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline: while time.monotonic() < deadline:
if "s360.dbschenker.com" in page.url and "auth.dbschenker.com" not in page.url: if "s360.dbschenker.com" in page.url and "auth.dbschenker.com" not in page.url:
@@ -897,7 +897,7 @@ def _find_dsv_password_locator(page: Any, timeout_ms: int = 250):
selectors = tuple( selectors = tuple(
item item
for item in ( for item in (
_env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_SELECTOR"), _env("FREIGHT_RPA_WORKER_DSV_PASSWORD_SELECTOR"),
"input#userpassword", "input#userpassword",
'input[name="userpassword"]', 'input[name="userpassword"]',
'input[name="password"]', 'input[name="password"]',
@@ -945,7 +945,7 @@ def _is_dsv_blank_auth_transition(page: Any) -> bool:
def _dsv_login_ready_timeout_ms() -> int: def _dsv_login_ready_timeout_ms() -> int:
"""DSV 登录表单/跳转就绪的最大等待秒数。""" """DSV 登录表单/跳转就绪的最大等待秒数。"""
return max(60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_LOGIN_READY_TIMEOUT_MS", "120000") or "120000")) return max(60_000, int(_env("FREIGHT_RPA_WORKER_LOGIN_READY_TIMEOUT_MS", "120000") or "120000"))
def _wait_for_dsv_auth_page_ready(page: Any, *, timeout_ms: int | None = None) -> bool: def _wait_for_dsv_auth_page_ready(page: Any, *, timeout_ms: int | None = None) -> bool:
@@ -969,7 +969,7 @@ def _wait_for_dsv_auth_page_ready(page: Any, *, timeout_ms: int | None = None) -
return True return True
if _wait_for_visible_selector( if _wait_for_visible_selector(
page, page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME_SELECTOR", "FREIGHT_RPA_WORKER_DSV_USERNAME_SELECTOR",
_DSV_USERNAME_SELECTORS, _DSV_USERNAME_SELECTORS,
timeout_ms=500, timeout_ms=500,
) is not None: ) is not None:
@@ -1058,7 +1058,7 @@ def _fill_dsv_username(page: Any, username: str, preferred_locator: Any | None =
if preferred_locator is not None and _try_fill_dsv_username_locator(preferred_locator, username): if preferred_locator is not None and _try_fill_dsv_username_locator(preferred_locator, username):
return preferred_locator return preferred_locator
timeout_ms = max(5_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_LOGIN_READY_TIMEOUT_MS", "300000") or "300000")) timeout_ms = max(5_000, int(_env("FREIGHT_RPA_WORKER_LOGIN_READY_TIMEOUT_MS", "300000") or "300000"))
deadline = time.monotonic() + (timeout_ms / 1000) deadline = time.monotonic() + (timeout_ms / 1000)
while time.monotonic() < deadline: while time.monotonic() < deadline:
for frame in page.frames: for frame in page.frames:
@@ -1,5 +1,5 @@
""" """
scripts/rpa/dsv_auth_login_flow.py scripts/freight_rpa/dsv_auth_login_flow.py
用途:DSV 360 PingID 自动登录主编排(maybe_auto_login_dsv)。 用途:DSV 360 PingID 自动登录主编排(maybe_auto_login_dsv)。
依赖:rpa_common、dsv_debug、dsv_auth(表单/探测辅助)、dsv_session(登录后首页 ready)。 依赖:rpa_common、dsv_debug、dsv_auth(表单/探测辅助)、dsv_session(登录后首页 ready)。
@@ -122,8 +122,8 @@ def _maybe_auto_login_dsv(page: Any) -> None:
""" """
DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。 DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。
""" """
username = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") username = _env("FREIGHT_RPA_WORKER_DSV_USERNAME")
password = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") password = _env("FREIGHT_RPA_WORKER_DSV_PASSWORD")
auto_login_started_at = time.monotonic() auto_login_started_at = time.monotonic()
username_step_started_at = auto_login_started_at username_step_started_at = auto_login_started_at
continue_to_method_started_at: float | None = None continue_to_method_started_at: float | None = None
@@ -182,7 +182,7 @@ def _maybe_auto_login_dsv(page: Any) -> None:
print("[dsv-login] waiting username field") print("[dsv-login] waiting username field")
username_locator = _wait_for_visible_selector( username_locator = _wait_for_visible_selector(
page, page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME_SELECTOR", "FREIGHT_RPA_WORKER_DSV_USERNAME_SELECTOR",
_DSV_USERNAME_SELECTORS, _DSV_USERNAME_SELECTORS,
timeout_ms=login_ready_ms, timeout_ms=login_ready_ms,
) )
@@ -213,7 +213,7 @@ def _maybe_auto_login_dsv(page: Any) -> None:
if _wait_for_dsv_auth_page_ready(page, timeout_ms=30_000): if _wait_for_dsv_auth_page_ready(page, timeout_ms=30_000):
username_locator = _wait_for_visible_selector( username_locator = _wait_for_visible_selector(
page, page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME_SELECTOR", "FREIGHT_RPA_WORKER_DSV_USERNAME_SELECTOR",
_DSV_USERNAME_SELECTORS, _DSV_USERNAME_SELECTORS,
timeout_ms=15_000, timeout_ms=15_000,
) )
@@ -234,7 +234,7 @@ def _maybe_auto_login_dsv(page: Any) -> None:
print("[dsv-login] username filled") print("[dsv-login] username filled")
_report_auto_login_substage("username_step", username_step_started_at) _report_auto_login_substage("username_step", username_step_started_at)
continue_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_CONTINUE_BUTTON_SELECTOR") continue_selector = _env("FREIGHT_RPA_WORKER_DSV_CONTINUE_BUTTON_SELECTOR")
if continue_selector: if continue_selector:
page.locator(continue_selector).first.click(timeout=_browser_timeout_ms(), force=True) page.locator(continue_selector).first.click(timeout=_browser_timeout_ms(), force=True)
clicked_continue = True clicked_continue = True
@@ -258,7 +258,7 @@ def _maybe_auto_login_dsv(page: Any) -> None:
print("[dsv-login] waiting password field") print("[dsv-login] waiting password field")
password_locator = None password_locator = None
login_deadline = time.monotonic() + ( login_deadline = time.monotonic() + (
max(60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_STAGE_TIMEOUT_MS", "120000") or "120000")) / 1000 max(60_000, int(_env("FREIGHT_RPA_WORKER_DSV_PASSWORD_STAGE_TIMEOUT_MS", "120000") or "120000")) / 1000
) )
password_method_clicked_at = 0.0 password_method_clicked_at = 0.0
username_retry_allowed_at = time.monotonic() + 6 username_retry_allowed_at = time.monotonic() + 6
@@ -321,7 +321,7 @@ def _maybe_auto_login_dsv(page: Any) -> None:
if password_method_clicked_at and time.monotonic() - password_method_clicked_at < 2: if password_method_clicked_at and time.monotonic() - password_method_clicked_at < 2:
time.sleep(1) time.sleep(1)
continue continue
password_method_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_METHOD_SELECTOR") password_method_selector = _env("FREIGHT_RPA_WORKER_DSV_PASSWORD_METHOD_SELECTOR")
if password_method_selector: if password_method_selector:
page.locator(password_method_selector).first.click(timeout=_browser_timeout_ms(), force=True) page.locator(password_method_selector).first.click(timeout=_browser_timeout_ms(), force=True)
clicked_password_method = True clicked_password_method = True
@@ -391,7 +391,7 @@ def _maybe_auto_login_dsv(page: Any) -> None:
_wait_for_dsv_auth_page_ready(page, timeout_ms=_dsv_login_ready_timeout_ms()) _wait_for_dsv_auth_page_ready(page, timeout_ms=_dsv_login_ready_timeout_ms())
password_locator = _wait_for_visible_selector( password_locator = _wait_for_visible_selector(
page, page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_SELECTOR", "FREIGHT_RPA_WORKER_DSV_PASSWORD_SELECTOR",
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'), ("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
timeout_ms=_dsv_login_ready_timeout_ms(), timeout_ms=_dsv_login_ready_timeout_ms(),
) )
@@ -1,5 +1,5 @@
""" """
scripts/rpa/dsv_debug.py scripts/freight_rpa/dsv_debug.py
用途:DSV 360 RPA 调试探针与链路阶段日志。 用途:DSV 360 RPA 调试探针与链路阶段日志。
依赖:rpa_common。 依赖:rpa_common。
@@ -1,5 +1,5 @@
""" """
scripts/rpa/dsv_driver.py scripts/freight_rpa/dsv_driver.py
用途:DSV 360 库存 RPA 对外编排入口(session → 导航 → 导出)。 用途:DSV 360 库存 RPA 对外编排入口(session → 导航 → 导出)。
依赖:dsv_report_export。 依赖:dsv_report_export。
@@ -1,5 +1,5 @@
""" """
scripts/rpa/dsv_export_timeout_diagnostics.py scripts/freight_rpa/dsv_export_timeout_diagnostics.py
用途:汇总 DSV Excel 导出等待超时现场,输出适合直接写入 worker.log 的诊断字符串。 用途:汇总 DSV Excel 导出等待超时现场,输出适合直接写入 worker.log 的诊断字符串。
依赖:json、标准库。 依赖:json、标准库。
@@ -1,13 +1,13 @@
""" """
scripts/rpa/dsv_login_smoke.py scripts/freight_rpa/dsv_login_smoke.py
用途:本地手动验证 DSV 360 自动登录(含密码方式第二步、首页 ready)。 用途:本地手动验证 DSV 360 自动登录(含密码方式第二步、首页 ready)。
依赖:Playwright、SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD。 依赖:Playwright、FREIGHT_RPA_WORKER_DSV_USERNAME / FREIGHT_RPA_WORKER_DSV_PASSWORD。
逻辑:打开可见浏览器 → _ensure_dsv_session → 保持窗口供人工观察,按 Enter 关闭。 逻辑:打开可见浏览器 → _ensure_dsv_session → 保持窗口供人工观察,按 Enter 关闭。
用法(仓库根目录): 用法(仓库根目录):
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false" $env:FREIGHT_RPA_WORKER_HEADLESS = "false"
backend\\venv\\Scripts\\python.exe scripts\\rpa\\dsv_login_smoke.py backend\\venv\\Scripts\\python.exe scripts\\freight_rpa\\dsv_login_smoke.py
""" """
from __future__ import annotations from __future__ import annotations
@@ -22,7 +22,7 @@ from pathlib import Path
def _load_worker(): def _load_worker():
repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2]) repo_root = next((_p for _p in Path(__file__).resolve().parents if (_p / "backend").is_dir() and (_p / "frontend").is_dir()), Path(__file__).resolve().parents[2])
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_smoke", module_path) spec = importlib.util.spec_from_file_location("inventory_rpa_worker_smoke", module_path)
assert spec and spec.loader assert spec and spec.loader
module = importlib.util.module_from_spec(spec) module = importlib.util.module_from_spec(spec)
@@ -31,26 +31,26 @@ def _load_worker():
def main() -> int: def main() -> int:
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") os.environ.setdefault("FREIGHT_RPA_WORKER_HEADLESS", "false")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") os.environ.setdefault("FREIGHT_RPA_WORKER_MOCK", "false")
os.environ.setdefault( os.environ.setdefault(
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
"backend/data/shipping_notice/freight_rpa/browser_profile", "backend/data/shipping_notice/freight_rpa/browser_profile",
) )
# 不默认 msedge:未设置 CHANNEL 时走 Playwright 捆绑 Chromium(需先 playwright install chromium)。 # 不默认 msedge:未设置 CHANNEL 时走 Playwright 捆绑 Chromium(需先 playwright install chromium)。
worker = _load_worker() worker = _load_worker()
username = worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") username = worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME")
password = worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") password = worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD")
if not username or not password: if not username or not password:
print("[smoke] 缺少 SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD,请先配置环境变量。") print("[smoke] 缺少 FREIGHT_RPA_WORKER_DSV_USERNAME / FREIGHT_RPA_WORKER_DSV_PASSWORD,请先配置环境变量。")
return 1 return 1
drop_dir = Path(tempfile.mkdtemp(prefix="dsv_smoke_drop_")) drop_dir = Path(tempfile.mkdtemp(prefix="dsv_smoke_drop_"))
playwright = context = runtime_profile_dir = None playwright = context = runtime_profile_dir = None
entry_url = "https://s360.dbschenker.com/" entry_url = "https://s360.dbschenker.com/"
print(f"[smoke] headless={worker._env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false')}") print(f"[smoke] headless={worker._env('FREIGHT_RPA_WORKER_HEADLESS', 'false')}")
print(f"[smoke] user={username[:3]}*** entry={entry_url}") print(f"[smoke] user={username[:3]}*** entry={entry_url}")
print("[smoke] 正在打开浏览器并执行 DSV 自动登录…") print("[smoke] 正在打开浏览器并执行 DSV 自动登录…")
@@ -1,5 +1,5 @@
""" """
scripts/rpa/dsv_navigation.py scripts/freight_rpa/dsv_navigation.py
用途:DSV 360 Reports 菜单导航至 SSRS 参数页。 用途:DSV 360 Reports 菜单导航至 SSRS 参数页。
依赖:rpa_common、dsv_debug、dsv_session。 依赖:rpa_common、dsv_debug、dsv_session。
@@ -534,7 +534,7 @@ def _click_dsv_view_report(page: Any) -> None:
'button:has-text("View Report")', 'button:has-text("View Report")',
) )
_debug_dsv_stage(page, "view-report-before-click", target_text="View Report") _debug_dsv_stage(page, "view-report-before-click", target_text="View Report")
wait_ms = max(15_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_VIEW_REPORT_WAIT_MS", "30000") or "30000")) wait_ms = max(15_000, int(_env("FREIGHT_RPA_WORKER_DSV_VIEW_REPORT_WAIT_MS", "30000") or "30000"))
deadline = time.monotonic() + (wait_ms / 1000) deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline: while time.monotonic() < deadline:
for frame in page.frames: for frame in page.frames:
@@ -835,7 +835,7 @@ def _wait_for_dsv_report_form_ready(page: Any, report_name: str, *, timeout_ms:
这样既能避免顺序错乱,也不会因为标题文本稍晚刷新而额外空等数秒。 这样既能避免顺序错乱,也不会因为标题文本稍晚刷新而额外空等数秒。
""" """
wait_ms = timeout_ms if timeout_ms is not None else max( wait_ms = timeout_ms if timeout_ms is not None else max(
60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_FORM_TIMEOUT_MS", "60000") or "60000") 60_000, int(_env("FREIGHT_RPA_WORKER_DSV_REPORT_FORM_TIMEOUT_MS", "60000") or "60000")
) )
deadline = time.monotonic() + (wait_ms / 1000) deadline = time.monotonic() + (wait_ms / 1000)
started_at = time.monotonic() started_at = time.monotonic()
@@ -1,5 +1,5 @@
""" """
scripts/rpa/dsv_report_export.py scripts/freight_rpa/dsv_report_export.py
用途:DSV 360 填参、View Report、Excel 导出与 batch 编排。 用途:DSV 360 填参、View Report、Excel 导出与 batch 编排。
依赖:rpa_common、dsv_debug、dsv_navigation、dsv_session、dsv_report_parameters。 依赖:rpa_common、dsv_debug、dsv_navigation、dsv_session、dsv_report_parameters。
@@ -224,7 +224,7 @@ def _click_dsv_export_excel(page: Any) -> None:
) )
# #endregion # #endregion
frame_root = selected_frame[1] if selected_frame else page frame_root = selected_frame[1] if selected_frame else page
export_menu_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_EXPORT_MENU_SELECTOR") or ",".join( export_menu_selector = _env("FREIGHT_RPA_WORKER_DSV_EXPORT_MENU_SELECTOR") or ",".join(
( (
'a[title="Export drop down menu"]', 'a[title="Export drop down menu"]',
'button[title="Export drop down menu"]', 'button[title="Export drop down menu"]',
@@ -232,7 +232,7 @@ def _click_dsv_export_excel(page: Any) -> None:
'[aria-label="Export drop down menu"]', '[aria-label="Export drop down menu"]',
) )
) )
excel_export_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_EXCEL_EXPORT_SELECTOR") or ",".join( excel_export_selector = _env("FREIGHT_RPA_WORKER_DSV_EXCEL_EXPORT_SELECTOR") or ",".join(
( (
'a[title="Excel"]', 'a[title="Excel"]',
'button[title="Excel"]', 'button[title="Excel"]',
@@ -241,7 +241,7 @@ def _click_dsv_export_excel(page: Any) -> None:
'a[href*="EXCELOPENXML"]', 'a[href*="EXCELOPENXML"]',
) )
) )
legacy_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_EXPORT_SELECTOR") legacy_selector = _env("FREIGHT_RPA_WORKER_DSV_EXPORT_SELECTOR")
if legacy_selector: if legacy_selector:
locator = _visible_locator_in_root(frame_root, legacy_selector) locator = _visible_locator_in_root(frame_root, legacy_selector)
if locator is not None: if locator is not None:
@@ -257,7 +257,7 @@ def _click_dsv_export_excel(page: Any) -> None:
selected_frame is None selected_frame is None
and _click_visible_selector_or_text( and _click_visible_selector_or_text(
page, page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_EXPORT_MENU_SELECTOR", "FREIGHT_RPA_WORKER_DSV_EXPORT_MENU_SELECTOR",
("file_download", "Save", "Export"), ("file_download", "Save", "Export"),
) )
) )
@@ -296,7 +296,7 @@ def _click_dsv_export_excel(page: Any) -> None:
selected_frame is None selected_frame is None
and _click_visible_selector_or_text( and _click_visible_selector_or_text(
page, page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_EXCEL_EXPORT_SELECTOR", "FREIGHT_RPA_WORKER_DSV_EXCEL_EXPORT_SELECTOR",
("Excel", "EXCELOPENXML"), ("Excel", "EXCELOPENXML"),
) )
) )
@@ -1039,9 +1039,9 @@ def _dsv_parameter_selector_env(parameter_name: str) -> str:
""" """
normalized = "".join(ch for ch in str(parameter_name or "").lower() if ch.isalnum()) normalized = "".join(ch for ch in str(parameter_name or "").lower() if ch.isalnum())
return { return {
"warehouse": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "warehouse": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"owner": "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "owner": "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
"putawayzone": "SHIPPING_NOTICE_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR", "putawayzone": "FREIGHT_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR",
}.get(normalized, "") }.get(normalized, "")
@@ -1054,9 +1054,9 @@ def _fill_report_parameters(page: Any, source: dict[str, Any]) -> None:
_fill_report_parameter(page, item, report_name=report_name) _fill_report_parameter(page, item, report_name=report_name)
return return
query = source.get("query") if isinstance(source.get("query"), dict) else {} query = source.get("query") if isinstance(source.get("query"), dict) else {}
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"), report_name=report_name) _fill_dsv_filter_if_needed(page, "FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"), report_name=report_name)
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"), report_name=report_name) _fill_dsv_filter_if_needed(page, "FREIGHT_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"), report_name=report_name)
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code"), report_name=report_name) _fill_dsv_filter_if_needed(page, "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code"), report_name=report_name)
def _dsv_entry_url_host(entry_url: str) -> str: def _dsv_entry_url_host(entry_url: str) -> str:
@@ -1126,7 +1126,12 @@ def _ensure_dsv_session(page: Any, entry_url: str) -> None:
_report_dsv_chain_stage("session_prepare", "end", started_at=started_at) _report_dsv_chain_stage("session_prepare", "end", started_at=started_at)
return return
_goto_dsv_entry_url(page, entry_url) try:
_goto_dsv_entry_url(page, entry_url)
except Exception as exc:
# 未登录时门户会把 goto 重定向到 SSO,Playwright 以 net::ERR_ABORTED 中止导航——
# 这正是需要登录的信号:继续走自动登录(登录自身会重新导航),而不是判死整个源。
print(f"[dsv] entry goto aborted (likely SSO redirect), continue with auto login: {exc}", file=sys.stderr)
home_not_ready_after_login = False home_not_ready_after_login = False
try: try:
_maybe_auto_login_dsv(page) _maybe_auto_login_dsv(page)
@@ -1250,7 +1255,7 @@ def _navigate_dsv_to_report_form_once(page: Any, source: dict[str, Any], report_
"""单次报表导航:开 Reports 菜单 → program_group → program_label → 分组 → 报表 → 等表单就绪。""" """单次报表导航:开 Reports 菜单 → program_group → program_label → 分组 → 报表 → 等表单就绪。"""
query = source.get("query") if isinstance(source.get("query"), dict) else {} query = source.get("query") if isinstance(source.get("query"), dict) else {}
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {} navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
reports_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORTS_SELECTOR") reports_selector = _env("FREIGHT_RPA_WORKER_DSV_REPORTS_SELECTOR")
if reports_selector: if reports_selector:
page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True) page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True)
else: else:
@@ -1261,7 +1266,7 @@ def _navigate_dsv_to_report_form_once(page: Any, source: dict[str, Any], report_
program_label = str(query.get("program_label") or navigation.get("program_label") or "").strip() program_label = str(query.get("program_label") or navigation.get("program_label") or "").strip()
report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory") report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
program_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PROGRAM_SELECTOR") program_selector = _env("FREIGHT_RPA_WORKER_DSV_PROGRAM_SELECTOR")
if program_selector: if program_selector:
page.locator(program_selector).first.click(timeout=_browser_timeout_ms()) page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
else: else:
@@ -1269,13 +1274,13 @@ def _navigate_dsv_to_report_form_once(page: Any, source: dict[str, Any], report_
_click_dsv_menu_item(page, program_group, next_text=program_label) _click_dsv_menu_item(page, program_group, next_text=program_label)
_click_dsv_menu_item(page, program_label, next_text=report_group) _click_dsv_menu_item(page, program_label, next_text=report_group)
report_group_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_GROUP_SELECTOR") report_group_selector = _env("FREIGHT_RPA_WORKER_DSV_REPORT_GROUP_SELECTOR")
if report_group_selector: if report_group_selector:
page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms()) page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms())
else: else:
_click_dsv_report_group(page, report_group, next_text=report_name) _click_dsv_report_group(page, report_group, next_text=report_name)
report_name_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_NAME_SELECTOR") report_name_selector = _env("FREIGHT_RPA_WORKER_DSV_REPORT_NAME_SELECTOR")
if report_name_selector: if report_name_selector:
page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms()) page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms())
else: else:
@@ -1321,9 +1326,9 @@ def _dsv_download_wait_ms() -> int:
核心逻辑:按实测 P99 设定——报表结果就绪后,SSRS 端生成+响应在 34s~90s+ 波动 核心逻辑:按实测 P99 设定——报表结果就绪后,SSRS 端生成+响应在 34s~90s+ 波动
(2026-08-26 实测 54s 命中、87s 兜底救回、90s+ 超时)。默认 240s 覆盖长尾, (2026-08-26 实测 54s 命中、87s 兜底救回、90s+ 超时)。默认 240s 覆盖长尾,
用 `SHIPPING_NOTICE_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS` 可按站点调整。 用 `FREIGHT_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS` 可按站点调整。
""" """
return max(60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS", "240000") or "240000")) return max(60_000, int(_env("FREIGHT_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS", "240000") or "240000"))
def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> Any: def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> Any:
@@ -1,5 +1,5 @@
""" """
scripts/rpa/dsv_report_parameters.py scripts/freight_rpa/dsv_report_parameters.py
用途:填充 DSV 360 SSRS ReportViewer 报表参数(Owner / PutawayZone / Warehouse)。 用途:填充 DSV 360 SSRS ReportViewer 报表参数(Owner / PutawayZone / Warehouse)。
依赖:Playwright Page/Frame;由 freight_rpa_worker._fill_dsv_filter_if_needed 委托调用。 依赖:Playwright Page/Frame;由 freight_rpa_worker._fill_dsv_filter_if_needed 委托调用。
@@ -1,5 +1,5 @@
""" """
scripts/rpa/dsv_session.py scripts/freight_rpa/dsv_session.py
用途:DSV 360 portal 壳层检测、首页 Reports 导航就绪与 entry_url 打开。 用途:DSV 360 portal 壳层检测、首页 Reports 导航就绪与 entry_url 打开。
依赖:rpa_common、dsv_debug、dsv_auth(升级提示与登录后回调)。 依赖:rpa_common、dsv_debug、dsv_auth(升级提示与登录后回调)。
@@ -131,14 +131,14 @@ def _is_dsv_on_portal_home(page: Any) -> bool:
def _dsv_sso_return_timeout_ms() -> int: def _dsv_sso_return_timeout_ms() -> int:
"""读取登录提交后 SSO 回跳的独立上限,避免混入首页菜单等待。""" """读取登录提交后 SSO 回跳的独立上限,避免混入首页菜单等待。"""
return max(30_000, int( return max(30_000, int(
_env("SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS", "90000") or "90000" _env("FREIGHT_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS", "90000") or "90000"
)) ))
def _dsv_sso_reload_after_ms() -> int: def _dsv_sso_reload_after_ms() -> int:
"""读取空白授权中转页的一次性刷新阈值,默认等待 12 秒。""" """读取空白授权中转页的一次性刷新阈值,默认等待 12 秒。"""
return max(5_000, int( return max(5_000, int(
_env("SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS", "12000") or "12000" _env("FREIGHT_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS", "12000") or "12000"
)) ))
@@ -5,36 +5,35 @@ Freight RPA worker (PoC).
DSV 逻辑见 dsv_driver / dsv_session / dsv_navigation / dsv_report_export;Crane 见 crane_*。 DSV 逻辑见 dsv_driver / dsv_session / dsv_navigation / dsv_report_export;Crane 见 crane_*。
Usage: Usage:
python scripts/rpa/inventory/inventory_rpa_worker.py python scripts/freight_rpa/inventory/inventory_rpa_worker.py
Required env (same as backend): Required env (same as backend):
HXOPS_API_BASE e.g. http://127.0.0.1:5052 HXOPS_API_BASE e.g. http://127.0.0.1:5052
SHIPPING_NOTICE_TOOL_API_KEY SHIPPING_NOTICE_TOOL_API_KEY
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR
Optional: Optional:
SHIPPING_NOTICE_RPA_WORKER_MOCK=false FREIGHT_RPA_WORKER_MOCK=false
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 FREIGHT_RPA_WORKER_POLL_SECONDS=3
SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=path/to/sample.xlsx FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=path/to/sample.xlsx
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE=true FREIGHT_RPA_WORKER_SESSION_REUSE=true
# legacy alias: SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE FREIGHT_RPA_WORKER_HEADLESS=false
SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false
# 默认不设 CHANNEL → Playwright 捆绑 Chromium;禁止默认 msedge(Edge 152 持久 Profile 下载崩溃)。 # 默认不设 CHANNEL → Playwright 捆绑 Chromium;禁止默认 msedge(Edge 152 持久 Profile 下载崩溃)。
# SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge # 不推荐 # FREIGHT_RPA_WORKER_BROWSER_CHANNEL=msedge # 不推荐
SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH=C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log FREIGHT_RPA_WORKER_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log
SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES=10485760 FREIGHT_RPA_WORKER_LOG_MAX_BYTES=10485760
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT=5 FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT=5
SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS=7 FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS=7
SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS=3600 FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS=3600
SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS=24 FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS=24
SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD FREIGHT_RPA_WORKER_DSV_USERNAME / FREIGHT_RPA_WORKER_DSV_PASSWORD
SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD FREIGHT_RPA_WORKER_CRANE_USERNAME / FREIGHT_RPA_WORKER_CRANE_PASSWORD
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false FREIGHT_RPA_WORKER_UPLOAD_ENABLED=false
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false
# 上传采用“用连接 login_url 登录 → 直接访问 upload_entry_url 上传页”;文件选择、提交动作与 # 上传采用“用连接 login_url 登录 → 直接访问 upload_entry_url 上传页”;文件选择、提交动作与
# 结果判定由受控 DsvUploadAdapter / CraneUploadAdapter 固化,禁止后端注入任意脚本或 selector。 # 结果判定由受控 DsvUploadAdapter / CraneUploadAdapter 固化,禁止后端注入任意脚本或 selector。
""" """
@@ -90,7 +89,7 @@ from download_artifact_fallback import ( # noqa: E402
wait_for_new_download_file as _wait_for_new_download_file, wait_for_new_download_file as _wait_for_new_download_file,
) )
from trigger_consumer import claim_trigger # noqa: E402 from trigger_consumer import claim_trigger # noqa: E402
# 日志实现已提取至公共模块(scripts/rpa/common/worker_logging.py),本 Worker 仅委托调用。 # 日志实现已提取至公共模块(scripts/freight_rpa/common/worker_logging.py),本 Worker 仅委托调用。
from worker_logging import active_log_path, configure_file_logging, maybe_rotate_open_log # noqa: E402 from worker_logging import active_log_path, configure_file_logging, maybe_rotate_open_log # noqa: E402
# 测试与 smoke 向后兼容 re-export # 测试与 smoke 向后兼容 re-export
@@ -210,26 +209,15 @@ def _browser_profile_root() -> Path:
""" """
解析 Playwright 运行时 profile 根目录。 解析 Playwright 运行时 profile 根目录。
核心逻辑:默认落到 `backend/data/shipping_notice/freight_rpa/browser_profile`; 核心逻辑:bare-run(未配置环境变量)默认 `<backend>/data/freight_rpa/common/browser_profile`,
若本机残留旧的 `data/freight_rpa/browser_profile` 配置,强制迁到 shipping_notice 与 freight_rpa 三层布局(inventory / receipt / common)保持一致;已配置环境变量时按
命名空间,避免库存导出继续污染旧目录。 backend 相对路径字面解析,无任何兼容改写(本分支红线:不做旧布局迁移层)。
Returns: Returns:
Path: 已解析但未创建的 profile 根目录。 Path: 已解析但未创建的 profile 根目录。
""" """
default = _backend_dir() / "data" / "shipping_notice" / "freight_rpa" / "browser_profile" default = _backend_dir() / "data" / "freight_rpa" / "common" / "browser_profile"
legacy_default = _backend_dir() / "data" / "freight_rpa" / "browser_profile" profile = _env("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR")
profile = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR")
normalized = profile.replace("\\", "/").strip("/")
if normalized in {
"data/freight_rpa/browser_profile",
"backend/data/freight_rpa/browser_profile",
} or (Path(profile).is_absolute() and Path(profile).resolve() == legacy_default.resolve()):
print(
"[warn] SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR points to legacy data/freight_rpa; "
f"using {default} instead"
)
return default.resolve()
return _resolve_backend_relative_path(profile, default=default) return _resolve_backend_relative_path(profile, default=default)
@@ -385,7 +373,7 @@ def _inventory_v2_identity_errors(body: dict[str, Any]) -> list[str]:
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path: def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
sample = _env("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY") sample = _env("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY")
if sample and Path(sample).is_file(): if sample and Path(sample).is_file():
dest = drop_dir / Path(sample).name dest = drop_dir / Path(sample).name
shutil.copy2(sample, dest) shutil.copy2(sample, dest)
@@ -739,9 +727,9 @@ def _profile_credentials(source: dict[str, Any]):
return return
if not username_ciphertext or not password_ciphertext: if not username_ciphertext or not password_ciphertext:
raise RuntimeError("RPA Profile credentials are incomplete") raise RuntimeError("RPA Profile credentials are incomplete")
key = _env("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY") key = _env("FREIGHT_RPA_CREDENTIAL_KEY")
if not key: if not key:
raise RuntimeError("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is required for RPA Profile credentials") raise RuntimeError("FREIGHT_RPA_CREDENTIAL_KEY is required for RPA Profile credentials")
try: try:
fernet = Fernet(key.encode("ascii")) fernet = Fernet(key.encode("ascii"))
username = fernet.decrypt(username_ciphertext.encode("ascii")).decode("utf-8") username = fernet.decrypt(username_ciphertext.encode("ascii")).decode("utf-8")
@@ -750,9 +738,9 @@ def _profile_credentials(source: dict[str, Any]):
raise RuntimeError("RPA Profile credentials cannot be decrypted") from exc raise RuntimeError("RPA Profile credentials cannot be decrypted") from exc
connector = _worker_connector_type(source) connector = _worker_connector_type(source)
if connector == "dsv360": if connector == "dsv360":
username_key, password_key = "SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD" username_key, password_key = "FREIGHT_RPA_WORKER_DSV_USERNAME", "FREIGHT_RPA_WORKER_DSV_PASSWORD"
elif connector == "crane_footprint": elif connector == "crane_footprint":
username_key, password_key = "SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME", "SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD" username_key, password_key = "FREIGHT_RPA_WORKER_CRANE_USERNAME", "FREIGHT_RPA_WORKER_CRANE_PASSWORD"
else: else:
raise RuntimeError(f"unsupported worker connector_type: {connector}") raise RuntimeError(f"unsupported worker connector_type: {connector}")
old = {username_key: os.environ.get(username_key), password_key: os.environ.get(password_key)} old = {username_key: os.environ.get(username_key), password_key: os.environ.get(password_key)}
@@ -885,24 +873,16 @@ def _session_reuse_enabled() -> bool:
""" """
返回库存导出是否复用持久浏览器 Profile。 返回库存导出是否复用持久浏览器 Profile。
核心逻辑:优先读 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`;未设置时回落旧名 核心逻辑:读 `FREIGHT_RPA_WORKER_SESSION_REUSE`;未设置时默认开启,避免同账号
`SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE`;两者皆未设置时默认开启,避免同账号
重复 RPA 每次重新登录。上传任务仍由调用方传 `reuse_session=False` 强制一次性目录。 重复 RPA 每次重新登录。上传任务仍由调用方传 `reuse_session=False` 强制一次性目录。
(历史别名 `FREIGHT_RPA_WORKER_DSV_SESSION_REUSE` 已于 2026-09-18 移除,无兼容层。)
""" """
raw = os.getenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE") raw = os.getenv("FREIGHT_RPA_WORKER_SESSION_REUSE")
if raw is None: if raw is None:
legacy = os.getenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE")
if legacy is not None:
return str(legacy).strip().strip("\"'").lower() == "true"
return True return True
return str(raw).strip().strip("\"'").lower() == "true" return str(raw).strip().strip("\"'").lower() == "true"
def _dsv_session_reuse_enabled() -> bool:
"""兼容旧测试/调用名;语义同 `_session_reuse_enabled`。"""
return _session_reuse_enabled()
def _sanitize_profile_dir_segment(value: str) -> str: def _sanitize_profile_dir_segment(value: str) -> str:
""" """
将 connector / RPA Profile 编码成可作目录名的安全片段。 将 connector / RPA Profile 编码成可作目录名的安全片段。
@@ -1105,9 +1085,9 @@ def _open_browser(
f"{profile_mode} connector={connector_type or '-'} profile={profile_code or '-'} " f"{profile_mode} connector={connector_type or '-'} profile={profile_code or '-'} "
f"dir={runtime_profile_dir.name!r}" f"dir={runtime_profile_dir.name!r}"
) )
headless = _env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false").lower() == "true" headless = _env("FREIGHT_RPA_WORKER_HEADLESS", "false").lower() == "true"
channel = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") channel = _env("FREIGHT_RPA_WORKER_BROWSER_CHANNEL")
executable_path = _env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH") executable_path = _env("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH")
launch_options: dict[str, Any] = { launch_options: dict[str, Any] = {
"headless": headless, "headless": headless,
"accept_downloads": True, "accept_downloads": True,
@@ -1152,7 +1132,7 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
_validate_inventory_source_for_rpa(source) _validate_inventory_source_for_rpa(source)
playwright = context = runtime_profile_dir = None playwright = context = runtime_profile_dir = None
keep_open_on_error = _env("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true" keep_open_on_error = _env("FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true"
failed = False failed = False
try: try:
playwright, context, page, runtime_profile_dir = _open_browser( playwright, context, page, runtime_profile_dir = _open_browser(
@@ -1176,7 +1156,7 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
raise raise
finally: finally:
if failed and keep_open_on_error: if failed and keep_open_on_error:
print("[browser] keeping browser open after error because SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR=true") print("[browser] keeping browser open after error because FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR=true")
while True: while True:
time.sleep(3600) time.sleep(3600)
if context is not None: if context is not None:
@@ -1427,7 +1407,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
_move_trigger(trigger_path, failed_dir, "invalid v2 identity") _move_trigger(trigger_path, failed_dir, "invalid v2 identity")
return return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true" mock = _env("FREIGHT_RPA_WORKER_MOCK", "false").lower() == "true"
mode = "mock" if mock else "browser" mode = "mock" if mock else "browser"
results: list[dict[str, Any]] = [] results: list[dict[str, Any]] = []
@@ -1445,7 +1425,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
try: try:
_post_callback("/api/shipping-notice/rpa/inventory-batch-claimed", { _post_callback("/api/shipping-notice/rpa/inventory-batch-claimed", {
"schema_version": "shipping_inventory_rpa.v2", "batch_run_no": run_no, "schema_version": "shipping_inventory_rpa.v2", "batch_run_no": run_no,
"claimed_at": datetime.utcnow().isoformat(), "worker_id": _env("SHIPPING_NOTICE_RPA_WORKER_ID", "worker"), "claimed_at": datetime.utcnow().isoformat(), "worker_id": _env("FREIGHT_RPA_WORKER_ID", "worker"),
"items": claimed_items, "items": claimed_items,
}) })
except Exception as exc: except Exception as exc:
@@ -1677,7 +1657,7 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
_move_trigger(trigger_path, failed_dir, "invalid v2 identity") _move_trigger(trigger_path, failed_dir, "invalid v2 identity")
return return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true" mock = _env("FREIGHT_RPA_WORKER_MOCK", "false").lower() == "true"
mode = "mock" if mock else "browser" mode = "mock" if mock else "browser"
# 单源 Trigger 与 batch 使用同一 v2 身份契约;Worker 只能回传后端冻结的字段。 # 单源 Trigger 与 batch 使用同一 v2 身份契约;Worker 只能回传后端冻结的字段。
@@ -1741,12 +1721,12 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
def _upload_worker_enabled() -> bool: def _upload_worker_enabled() -> bool:
"""返回上传浏览器自动化开关;默认关闭,避免仅部署 Worker 就提交货代文件。""" """返回上传浏览器自动化开关;默认关闭,避免仅部署 Worker 就提交货代文件。"""
return _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false").lower() == "true" return _env("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "false").lower() == "true"
def _upload_submit_confirmed() -> bool: def _upload_submit_confirmed() -> bool:
"""返回真实提交二次确认开关;页面填文件与最终提交必须显式分开授权。""" """返回真实提交二次确认开关;页面填文件与最终提交必须显式分开授权。"""
return _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "false").lower() == "true" return _env("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "false").lower() == "true"
def _click_dsv_upload_tool_entry(page: Any, *, section: str | None = None) -> bool: def _click_dsv_upload_tool_entry(page: Any, *, section: str | None = None) -> bool:
@@ -2344,9 +2324,9 @@ def _upload_shipment_with_browser(
"upload RPA is not enabled for this connection; enable it in '系统连接' after validation" "upload RPA is not enabled for this connection; enable it in '系统连接' after validation"
) )
if not _upload_worker_enabled(): if not _upload_worker_enabled():
raise RuntimeError("upload RPA worker is disabled; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=true after validation") raise RuntimeError("upload RPA worker is disabled; set FREIGHT_RPA_WORKER_UPLOAD_ENABLED=true after validation")
if not _upload_submit_confirmed(): if not _upload_submit_confirmed():
raise RuntimeError("upload RPA submit is not confirmed; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=true after dry run") raise RuntimeError("upload RPA submit is not confirmed; set FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=true after dry run")
business = str(connector_type or '').strip().lower() business = str(connector_type or '').strip().lower()
if business not in {'dbs', 'crane'} and connector_type: if business not in {'dbs', 'crane'} and connector_type:
business = {'dsv360': 'dbs', 'crane_footprint': 'crane'}.get( business = {'dsv360': 'dbs', 'crane_footprint': 'crane'}.get(
@@ -2374,8 +2354,8 @@ def _upload_shipment_with_browser(
failed = True failed = True
raise raise
finally: finally:
if failed and _env("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true": if failed and _env("FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "false").lower() == "true":
print("[browser] keeping browser open after upload error because SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR=true") print("[browser] keeping browser open after upload error because FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR=true")
while True: while True:
time.sleep(3600) time.sleep(3600)
if context is not None: if context is not None:
@@ -2397,7 +2377,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
trigger_path.unlink(missing_ok=True) trigger_path.unlink(missing_ok=True)
return return
mock = _env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false").lower() == "true" mock = _env("FREIGHT_RPA_WORKER_MOCK", "false").lower() == "true"
if not file_path or not Path(file_path).is_file(): if not file_path or not Path(file_path).is_file():
try: try:
_post_callback("/api/shipping-notice/rpa/upload-complete", { _post_callback("/api/shipping-notice/rpa/upload-complete", {
@@ -2548,23 +2528,23 @@ def main() -> None:
防止长期运行撑爆 RPA 主机盘符。 防止长期运行撑爆 RPA 主机盘符。
""" """
log_path = configure_file_logging() log_path = configure_file_logging()
drop_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR") drop_dir = _require_path("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR")
inv_trigger_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR") inv_trigger_dir = _require_path("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR")
upload_queue_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR") upload_queue_dir = _require_path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR")
upload_trigger_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR") upload_trigger_dir = _require_path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR")
poll = max(1, int(_env("SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS", "3") or "3")) poll = max(1, int(_env("FREIGHT_RPA_WORKER_POLL_SECONDS", "3") or "3"))
inv_processed = inv_trigger_dir / "processed" inv_processed = inv_trigger_dir / "processed"
upload_processed = upload_trigger_dir / "processed" upload_processed = upload_trigger_dir / "processed"
api_base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/") api_base = _env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")
heartbeat_seconds = max( heartbeat_seconds = max(
15, 15,
int(_env("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"), int(_env("FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS", "20") or "20"),
) )
auth_source, masked_auth = _resolve_tool_api_auth_debug() auth_source, masked_auth = _resolve_tool_api_auth_debug()
print("[freight_rpa_worker] started") print("[freight_rpa_worker] started")
print(f" mock={_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')}") print(f" mock={_env('FREIGHT_RPA_WORKER_MOCK', 'false')}")
print(f" api_base={api_base}") print(f" api_base={api_base}")
print(f" heartbeat_seconds={heartbeat_seconds}") print(f" heartbeat_seconds={heartbeat_seconds}")
print(f" auth_source={auth_source}") print(f" auth_source={auth_source}")
@@ -19,20 +19,20 @@
- The RPA account should be configured for auto-logon and must not be locked - The RPA account should be configured for auto-logon and must not be locked
/ logged-off, otherwise the AtLogOn task does not stay resident. / logged-off, otherwise the AtLogOn task does not stay resident.
- Before trusting headless, run the headless smoke preflight (README 2.3.1): - Before trusting headless, run the headless smoke preflight (README 2.3.1):
set $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS="true" then run set $env:FREIGHT_RPA_WORKER_HEADLESS="true" then run
dsv_login_smoke.py / crane_login_smoke.py. dsv_login_smoke.py / crane_login_smoke.py.
Scope: Scope:
All actions can target one environment or both via -Scope test|prod|all (default all). All actions can target one environment or both via -Scope test|prod|all (default all).
Usage (run in the RPA account's PowerShell): Usage (run in the RPA account's PowerShell):
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 # register test+prod .\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 # register test+prod
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test # register only test .\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test # register only test
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start # start both now .\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Start # start both now
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Start -Scope prod # start only prod .\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Start -Scope prod # start only prod
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Status -Scope test # only test .\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Status -Scope test # only test
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Stop -Scope prod # stop only prod .\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Stop -Scope prod # stop only prod
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Unregister # unregister both .\scripts\freight_rpa\inventory\register_inventory_worker_tasks.ps1 -Unregister # unregister both
#> #>
[CmdletBinding()] [CmdletBinding()]
param( param(
@@ -69,7 +69,7 @@ function Get-TasksForScope {
function Assert-Launcher { function Assert-Launcher {
# Validate the launcher and DPAPI Secret file required for one environment. # Validate the launcher and DPAPI Secret file required for one environment.
param([string]$Root, [string]$Environment) param([string]$Root, [string]$Environment)
$launcher = Join-Path $Root "scripts\rpa\inventory\start_inventory_worker.ps1" $launcher = Join-Path $Root "scripts\freight_rpa\inventory\start_inventory_worker.ps1"
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) { if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
throw "Launcher not found: $launcher" throw "Launcher not found: $launcher"
} }
@@ -86,7 +86,7 @@ function New-TaskDefinition {
[string]$ApiBase, [string]$ApiBase,
[string]$EnvName [string]$EnvName
) )
$launcher = Join-Path $Root "scripts\rpa\inventory\start_inventory_worker.ps1" $launcher = Join-Path $Root "scripts\freight_rpa\inventory\start_inventory_worker.ps1"
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName) $secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
# Key differences vs the visible scheduled task: # Key differences vs the visible scheduled task:
@@ -31,7 +31,7 @@ def _load_dotenv_dev() -> None:
def _load_worker(): def _load_worker():
"""Load the polling worker module so manual runs share the production trigger contract.""" """Load the polling worker module so manual runs share the production trigger contract."""
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_batch_runner", module_path) spec = importlib.util.spec_from_file_location("inventory_rpa_worker_batch_runner", module_path)
assert spec and spec.loader assert spec and spec.loader
module = importlib.util.module_from_spec(spec) module = importlib.util.module_from_spec(spec)
@@ -42,7 +42,7 @@ def _load_worker():
def main() -> int: def main() -> int:
"""Execute a complete, database-generated batch trigger and post its normal callback.""" """Execute a complete, database-generated batch trigger and post its normal callback."""
if len(sys.argv) < 2: if len(sys.argv) < 2:
print("usage: python scripts/rpa/run_inventory_batch_trigger.py <trigger.json>") print("usage: python scripts/freight_rpa/run_inventory_batch_trigger.py <trigger.json>")
return 1 return 1
trigger_path = Path(sys.argv[1]).expanduser() trigger_path = Path(sys.argv[1]).expanduser()
if not trigger_path.is_file(): if not trigger_path.is_file():
@@ -51,16 +51,16 @@ def main() -> int:
print(f"[batch-run] trigger not found: {sys.argv[1]}") print(f"[batch-run] trigger not found: {sys.argv[1]}")
return 1 return 1
_load_dotenv_dev() _load_dotenv_dev()
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") os.environ.setdefault("FREIGHT_RPA_WORKER_MOCK", "false")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false") os.environ.setdefault("FREIGHT_RPA_WORKER_HEADLESS", "false")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "true") os.environ.setdefault("FREIGHT_RPA_WORKER_KEEP_BROWSER_OPEN_ON_ERROR", "true")
os.environ.setdefault("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", "backend/data/shipping_notice/freight_rpa/browser_profile") os.environ.setdefault("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", "backend/data/freight_rpa/common/browser_profile")
# 不默认 msedge:Edge 152 + 持久 Profile 下载会原生崩溃;未设置 CHANNEL 时走 Playwright Chromium。 # 不默认 msedge:Edge 152 + 持久 Profile 下载会原生崩溃;未设置 CHANNEL 时走 Playwright Chromium。
os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052") os.environ.setdefault("HXOPS_API_BASE", "http://127.0.0.1:5052")
if not os.environ.get("SHIPPING_NOTICE_TOOL_API_KEY"): if not os.environ.get("SHIPPING_NOTICE_TOOL_API_KEY"):
print("[batch-run] SHIPPING_NOTICE_TOOL_API_KEY is required") print("[batch-run] SHIPPING_NOTICE_TOOL_API_KEY is required")
return 1 return 1
drop_dir = Path(os.environ.get("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR") or "backend/data/shipping_notice/freight_rpa/inventory_drop") drop_dir = Path(os.environ.get("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR") or "backend/data/freight_rpa/inventory/drop")
if not drop_dir.is_absolute(): if not drop_dir.is_absolute():
drop_dir = _repo_root() / drop_dir drop_dir = _repo_root() / drop_dir
processed_dir = trigger_path.parent / "processed" processed_dir = trigger_path.parent / "processed"
@@ -32,8 +32,7 @@ param(
# 默认开启库存会话复用;仅在需要强制每次全新登录时传 -NoSessionReuse。 # 默认开启库存会话复用;仅在需要强制每次全新登录时传 -NoSessionReuse。
[switch]$NoSessionReuse, [switch]$NoSessionReuse,
# 兼容旧文档:等价于开启复用(现在默认已开启)。 # 兼容旧文档:等价于开启复用(现在默认已开启)。
[switch]$ReuseSession, [switch]$ReuseSession
[switch]$ReuseDsvSession
) )
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
@@ -41,7 +40,7 @@ $ErrorActionPreference = "Stop"
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) {
throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。" throw "Secret 文件不存在:$SecretFile。请先运行 new_rpa_worker_secret.ps1。"
} }
$workerScript = Join-Path $WorkerRoot "scripts\rpa\inventory\inventory_rpa_worker.py" $workerScript = Join-Path $WorkerRoot "scripts\freight_rpa\inventory\inventory_rpa_worker.py"
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) {
throw "Worker 不存在:$workerScript" throw "Worker 不存在:$workerScript"
} }
@@ -51,7 +50,8 @@ if ($Environment -eq "test") {
} else { } else {
$scopeId = "hxops-rpa-prod-data" $scopeId = "hxops-rpa-prod-data"
} }
$dataRoot = Join-Path $WorkerRoot "data" # freight_rpa 三层布局根:$WorkerRoot\freight_rpa\{inventory,receipt,common}(与后端 settings/.env 默认值一致)。
$rpaRoot = Join-Path $WorkerRoot "freight_rpa"
function ConvertTo-PlainText { function ConvertTo-PlainText {
param([Parameter(Mandatory = $true)][System.Security.SecureString]$Value) param([Parameter(Mandatory = $true)][System.Security.SecureString]$Value)
@@ -69,7 +69,7 @@ foreach ($required in @("ToolApiKey", "CredentialKey")) {
# 库存 Profile 默认按 connector+rpa_profile 长期复用;-NoSessionReuse 可关闭。 # 库存 Profile 默认按 connector+rpa_profile 长期复用;-NoSessionReuse 可关闭。
$sessionReuse = if ($NoSessionReuse) { "false" } else { "true" } $sessionReuse = if ($NoSessionReuse) { "false" } else { "true" }
if ($ReuseSession -or $ReuseDsvSession) { if ($ReuseSession) {
$sessionReuse = "true" $sessionReuse = "true"
} }
@@ -77,30 +77,32 @@ if ($ReuseSession -or $ReuseDsvSession) {
$processVars = [ordered]@{ $processVars = [ordered]@{
HXOPS_API_BASE = $ApiBase HXOPS_API_BASE = $ApiBase
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey FREIGHT_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = $Environment FREIGHT_RPA_WORKER_ENVIRONMENT = $Environment
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = $scopeId # 稳定 Worker 身份:监控端心跳卡片不再随进程重启漂移(缺省回退 <hostname>-<pid>)。
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = "20" FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-inventory"
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" }) FREIGHT_RPA_SHARED_SCOPE_ID = $scopeId
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" }) FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = "20"
SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE = $sessionReuse FREIGHT_RPA_WORKER_MOCK = $(if ($Mock) { "true" } else { "false" })
FREIGHT_RPA_WORKER_HEADLESS = $(if ($Headless) { "true" } else { "false" })
FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium。 # 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium。
# Edge 152 + 持久 Profile 下载会原生崩溃(TargetClosed / .crdownload),禁止默认 msedge。 # Edge 152 + 持久 Profile 下载会原生崩溃(TargetClosed / .crdownload),禁止默认 msedge。
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3" FREIGHT_RPA_WORKER_POLL_SECONDS = "3"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $dataRoot "inventory_triggers" FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaRoot "inventory\triggers"
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $dataRoot "inventory_drop" FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaRoot "inventory\drop"
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $dataRoot "upload_triggers" FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaRoot "inventory\upload_triggers"
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $dataRoot "upload_queue" FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaRoot "inventory\upload_queue"
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $dataRoot "browser_profile" FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot "common\browser_profile"
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot "logs\worker.log" FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot "inventory\logs\worker.log"
SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760" FREIGHT_RPA_WORKER_LOG_MAX_BYTES = "10485760"
SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5" FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = "5"
# 本机磁盘保留:归档 trigger/drop、日志备份、upload_queue、孤儿 run_* Profile;会话 Profile 不删。 # 本机磁盘保留:归档 trigger/drop、日志备份、upload_queue、孤儿 run_* Profile;会话 Profile 不删。
SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7" FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = "7"
SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600" FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600"
SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24" FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24"
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED = "false" FREIGHT_RPA_WORKER_UPLOAD_ENABLED = "false"
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT = "false" FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT = "false"
} }
foreach ($entry in $processVars.GetEnumerator()) { foreach ($entry in $processVars.GetEnumerator()) {
@@ -93,9 +93,9 @@ def _profile_credentials(unit: dict[str, Any]):
return return
if not username_ciphertext or not password_ciphertext: if not username_ciphertext or not password_ciphertext:
raise RuntimeError('RPA Profile credentials are incomplete') raise RuntimeError('RPA Profile credentials are incomplete')
key = env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') key = env('FREIGHT_RPA_CREDENTIAL_KEY')
if not key: if not key:
raise RuntimeError('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is required') raise RuntimeError('FREIGHT_RPA_CREDENTIAL_KEY is required')
try: try:
fernet = Fernet(key.encode('ascii')) fernet = Fernet(key.encode('ascii'))
username = fernet.decrypt(username_ciphertext.encode('ascii')).decode('utf-8') username = fernet.decrypt(username_ciphertext.encode('ascii')).decode('utf-8')
@@ -103,7 +103,7 @@ def _profile_credentials(unit: dict[str, Any]):
except (ValueError, InvalidToken, UnicodeDecodeError) as exc: except (ValueError, InvalidToken, UnicodeDecodeError) as exc:
raise RuntimeError('RPA Profile credentials cannot be decrypted') from exc raise RuntimeError('RPA Profile credentials cannot be decrypted') from exc
connector = str(unit.get('connector_type') or '').lower() connector = str(unit.get('connector_type') or '').lower()
names = ('SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME', 'SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD') if connector == 'dbs' else ('SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME', 'SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD') names = ('FREIGHT_RPA_WORKER_DSV_USERNAME', 'FREIGHT_RPA_WORKER_DSV_PASSWORD') if connector == 'dbs' else ('FREIGHT_RPA_WORKER_CRANE_USERNAME', 'FREIGHT_RPA_WORKER_CRANE_PASSWORD')
before = {name: os.environ.get(name) for name in names} before = {name: os.environ.get(name) for name in names}
os.environ[names[0]], os.environ[names[1]] = username, password os.environ[names[0]], os.environ[names[1]] = username, password
try: try:
@@ -116,17 +116,26 @@ def _profile_credentials(unit: dict[str, Any]):
os.environ[name] = old_value os.environ[name] = old_value
def _open_browser(download_dir: Path): def _open_browser(download_dir: Path, reuse_session: bool = False):
"""为一个 receipt Profile 分组创建临时浏览器上下文,组内登录一次、串行导出。""" """为一个 receipt Profile 分组创建浏览器上下文,组内登录一次、串行导出。
reuse_session=False(默认):一次性临时 Profile(receipt_* 前缀),批次结束即删,隔离最干净。
reuse_session=True:持久会话 Profile(receipt_session),跨批次复用登录态,适用于同日重跑/重试;
持久目录命中磁盘清理的 *_session 豁免规则,不会被孤儿清理删除。
"""
try: try:
from playwright.sync_api import sync_playwright from playwright.sync_api import sync_playwright
except ImportError as exc: except ImportError as exc:
raise RuntimeError('Playwright is required for real receipt RPA') from exc raise RuntimeError('Playwright is required for real receipt RPA') from exc
profile_root = _require_dir('SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR') profile_root = _require_dir('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR')
runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root))) if reuse_session:
runtime_profile = profile_root / 'receipt_session'
runtime_profile.mkdir(parents=True, exist_ok=True)
else:
runtime_profile = Path(tempfile.mkdtemp(prefix='receipt_', dir=str(profile_root)))
playwright = sync_playwright().start() playwright = sync_playwright().start()
options: dict[str, Any] = {'headless': env('SHIPPING_NOTICE_RPA_WORKER_HEADLESS', 'false').lower() == 'true', 'accept_downloads': True, 'downloads_path': str(download_dir)} options: dict[str, Any] = {'headless': env('FREIGHT_RPA_WORKER_HEADLESS', 'false').lower() == 'true', 'accept_downloads': True, 'downloads_path': str(download_dir)}
channel = env('SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL') channel = env('FREIGHT_RPA_WORKER_BROWSER_CHANNEL')
if channel: if channel:
options['channel'] = channel options['channel'] = channel
context = playwright.chromium.launch_persistent_context(str(runtime_profile), **options) context = playwright.chromium.launch_persistent_context(str(runtime_profile), **options)
@@ -179,11 +188,12 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item)) grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
for (connector, _profile, login_url), group in grouped.items(): for (connector, _profile, login_url), group in grouped.items():
print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}') print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}')
mock = env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false').lower() == 'true' mock = env('FREIGHT_RPA_WORKER_MOCK', 'false').lower() == 'true'
reuse_session = env('FREIGHT_RPA_WORKER_SESSION_REUSE', 'false').lower() == 'true'
resources = (None, None, None, None) resources = (None, None, None, None)
try: try:
if not mock: if not mock:
resources = _open_browser(drop_dir) resources = _open_browser(drop_dir, reuse_session=reuse_session)
playwright, context, page, profile_dir = resources playwright, context, page, profile_dir = resources
with _profile_credentials(group[0]): with _profile_credentials(group[0]):
for index, unit in enumerate(group): for index, unit in enumerate(group):
@@ -215,7 +225,8 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
context.close() context.close()
if playwright is not None: if playwright is not None:
playwright.stop() playwright.stop()
if profile_dir is not None: # 会话复用模式保留 receipt_session 持久目录(命中清理豁免),仅一次性模式即删。
if profile_dir is not None and not reuse_session:
shutil.rmtree(profile_dir, ignore_errors=True) shutil.rmtree(profile_dir, ignore_errors=True)
@@ -249,29 +260,29 @@ def _claim_and_process(path: Path, drop_dir: Path) -> None:
def main() -> None: def main() -> None:
"""轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。""" """轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout
drop_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR') drop_dir = _require_dir('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR')
trigger_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR') trigger_dir = _require_dir('FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR')
poll = max(1, int(env('SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS', '3') or '3')) poll = max(1, int(env('FREIGHT_RPA_WORKER_POLL_SECONDS', '3') or '3'))
heartbeat_seconds = max( heartbeat_seconds = max(
15, 15,
int(env('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'), int(env('FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'),
) )
last_cleanup_mono = 0.0 last_cleanup_mono = 0.0
cleanup_interval = cleanup_interval_seconds() cleanup_interval = cleanup_interval_seconds()
# [STEP 1] 启动 banner:字段对齐库存 Worker,排查时一处看全运行配置。 # [STEP 1] 启动 banner:字段对齐库存 Worker,排查时一处看全运行配置。
print( print(
'[freight_receipt_rpa_worker] started\n' '[freight_receipt_rpa_worker] started\n'
f' mock={env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")}\n' f' mock={env("FREIGHT_RPA_WORKER_MOCK", "false")}\n'
f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n' f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
f' poll_seconds={poll}\n' f' poll_seconds={poll}\n'
f' heartbeat_seconds={heartbeat_seconds}\n' f' heartbeat_seconds={heartbeat_seconds}\n'
f' headless={env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")} ' f' headless={env("FREIGHT_RPA_WORKER_HEADLESS", "false")} '
f'channel={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n' f'channel={env("FREIGHT_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n'
f' auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n' f' auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n'
f' credential_key={_mask_secret(env("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"))}\n' f' credential_key={_mask_secret(env("FREIGHT_RPA_CREDENTIAL_KEY"))}\n'
f' trigger_dir={trigger_dir}\n' f' trigger_dir={trigger_dir}\n'
f' drop_dir={drop_dir}\n' f' drop_dir={drop_dir}\n'
f' browser_profile_dir={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n' f' browser_profile_dir={env("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n'
f' log={worker_logging.active_log_path() or "stdout-only"}\n' f' log={worker_logging.active_log_path() or "stdout-only"}\n'
f' disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}' f' disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}'
) )
@@ -285,7 +296,7 @@ def main() -> None:
nonlocal last_cleanup_mono nonlocal last_cleanup_mono
if not force and (now_mono - last_cleanup_mono) < cleanup_interval: if not force and (now_mono - last_cleanup_mono) < cleanup_interval:
return last_cleanup_mono return last_cleanup_mono
profile_root_raw = str(env('SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip() profile_root_raw = str(env('FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
try: try:
stats = run_worker_disk_cleanup( stats = run_worker_disk_cleanup(
inventory_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json inventory_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
@@ -0,0 +1,182 @@
<#
.SYNOPSIS
Register the test/prod Receipt RPA Worker scheduled tasks in FULL-BACKGROUND mode.
.DESCRIPTION
Runs the Receipt Worker as a background scheduled task with NO visible console and
NO visible browser (the Worker launches Playwright headless via -Headless).
Deliberately ASCII-only so it parses identically under any Windows console code page.
Mirrors register_inventory_worker_tasks.ps1 one-to-one, with distinct task names so
both Workers can be registered side by side on the same host:
- Inventory: "HXOPS Inventory RPA Worker TEST/PROD"
- Receipt: "HXOPS Receipt RPA Worker TEST/PROD"
Shape constraints (same as the inventory registration):
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
- Do NOT switch to SYSTEM / AtStartup / Session 0 service: the Secret file is
per-user DPAPI (Export-Clixml in new_rpa_worker_secret.ps1) and cannot be
decrypted in a non-interactive context.
- The RPA account should be configured for auto-logon and must not be locked
/ logged-off, otherwise the AtLogOn task does not stay resident.
- Before trusting headless, run the headless smoke preflight:
set FREIGHT_RPA_WORKER_HEADLESS=true then run crane_login_smoke.py
(the DBS portal has no smoke script - verify the first headless run visually).
Scope:
All actions can target one environment or both via -Scope test|prod|all (default all).
Usage (run in the RPA account's PowerShell):
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 # register test+prod
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Scope test # register only test
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Start # start both now
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Start -Scope prod # start only prod
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Status -Scope test # only test
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Stop -Scope prod # stop only prod
.\scripts\freight_rpa\receipt\register_receipt_worker_tasks.ps1 -Unregister # unregister both
#>
[CmdletBinding()]
param(
[switch]$Register,
[switch]$Start,
[switch]$Stop,
[switch]$Status,
[switch]$Unregister,
[ValidateSet("test", "prod", "all")]
[string]$Scope = "all",
[string]$TestApiBase = "http://192.168.100.192:8890",
[string]$ProdApiBase = "http://192.168.100.230:8890",
[string]$TestRoot = "C:\HxopsRpaTest",
[string]$ProdRoot = "C:\HxopsRpaProd",
[string]$SecretFile = "C:\HxopsRpaSecrets"
)
$ErrorActionPreference = "Stop"
$TestTask = "HXOPS Receipt RPA Worker TEST"
$ProdTask = "HXOPS Receipt RPA Worker PROD"
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
function Get-TasksForScope {
# Return the task name(s) selected by -Scope.
param([string]$Scope)
switch ($Scope) {
"test" { return @($TestTask) }
"prod" { return @($ProdTask) }
default { return @($TestTask, $ProdTask) }
}
}
function Assert-Launcher {
# Validate the launcher and DPAPI Secret file required for one environment.
param([string]$Root, [string]$Environment)
$launcher = Join-Path $Root "scripts\freight_rpa\receipt\start_receipt_worker.ps1"
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
throw "Launcher not found: $launcher"
}
$secret = Join-Path $SecretFile ("{0}.xml" -f $Environment)
if (-not (Test-Path -LiteralPath $secret -PathType Leaf)) {
throw "Secret file not found: $secret. Run new_rpa_worker_secret.ps1 first."
}
}
function New-TaskDefinition {
param(
[string]$TaskName,
[string]$Root,
[string]$ApiBase,
[string]$EnvName
)
$launcher = Join-Path $Root "scripts\freight_rpa\receipt\start_receipt_worker.ps1"
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
# Key differences vs the visible scheduled task:
# -WindowStyle Hidden (no console) + -Headless (no visible browser).
$actionArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$launcher`" -Environment $EnvName -Headless -ApiBase `"$ApiBase`" -WorkerRoot `"$Root`" -SecretFile `"$secret`""
$action = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument $actionArgs `
-WorkingDirectory $Root
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $RunAsUser
$principal = New-ScheduledTaskPrincipal `
-UserId $RunAsUser `
-LogonType Interactive `
-RunLevel Limited
$settings = New-ScheduledTaskSettingsSet `
-StartWhenAvailable `
-RestartCount 10 `
-RestartInterval (New-TimeSpan -Minutes 1) `
-ExecutionTimeLimit ([TimeSpan]::Zero) `
-MultipleInstances IgnoreNew
Register-ScheduledTask `
-TaskName $TaskName `
-Action $action `
-Trigger $trigger `
-Principal $principal `
-Settings $settings `
-Description "HXOPS Receipt RPA Worker ($EnvName) background (headless + hidden console)"
}
# Default action is Register when no switch is given.
if ($Start -or $Stop -or $Status -or $Unregister -or $Register) {
# handled below
} else {
$Register = $true
}
if ($Unregister) {
foreach ($t in (Get-TasksForScope $Scope)) {
Stop-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName $t -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "Unregistered task: $t"
}
exit 0
}
if ($Start) {
foreach ($t in (Get-TasksForScope $Scope)) {
Start-ScheduledTask -TaskName $t
Write-Host "Started task: $t"
}
exit 0
}
if ($Stop) {
foreach ($t in (Get-TasksForScope $Scope)) {
Stop-ScheduledTask -TaskName $t
Write-Host "Stopped task: $t"
}
exit 0
}
if ($Status) {
foreach ($t in (Get-TasksForScope $Scope)) {
$tobj = Get-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
if ($tobj) {
$info = Get-ScheduledTaskInfo -TaskName $t
Write-Host ("{0} State={1} LastRun={2} LastResult={3}" -f $t, $info.State, $info.LastRunTime, $info.LastTaskResult)
Write-Host " (267009 / 0x41301 = running, not an error)"
} else {
Write-Host "Task not registered yet: $t"
}
}
exit 0
}
if ($Register) {
if ($Scope -eq "test" -or $Scope -eq "all") {
Assert-Launcher $TestRoot "test"
New-TaskDefinition -TaskName $TestTask -Root $TestRoot -ApiBase $TestApiBase -EnvName "test"
}
if ($Scope -eq "prod" -or $Scope -eq "all") {
Assert-Launcher $ProdRoot "prod"
New-TaskDefinition -TaskName $ProdTask -Root $ProdRoot -ApiBase $ProdApiBase -EnvName "prod"
}
Write-Host "Registered background task(s) for scope=${Scope}:"
foreach ($t in (Get-TasksForScope $Scope)) { Write-Host " $t" }
Write-Host "Tasks are AtLogOn + Interactive + headless + hidden console."
Write-Host "Use -Start to launch now. Configure auto-logon for the RPA account."
exit 0
}
@@ -4,7 +4,8 @@
.DESCRIPTION .DESCRIPTION
只设置 Process 级环境变量和 receipt 专用目录;可与库存 Worker 并行运行, 只设置 Process 级环境变量和 receipt 专用目录;可与库存 Worker 并行运行,
但二者不共享 trigger、drop、browser profile 或日志目录。 二者不共享 trigger、drop 或日志目录;浏览器 Profile 共用 common/browser_profile
根(各自在其中创建隔离的一次性子目录)。
#> #>
param( param(
[Parameter(Mandatory = $true)][ValidateSet('test', 'prod')][string]$Environment, [Parameter(Mandatory = $true)][ValidateSet('test', 'prod')][string]$Environment,
@@ -13,12 +14,14 @@ param(
[Parameter(Mandatory = $true)][string]$SecretFile, [Parameter(Mandatory = $true)][string]$SecretFile,
[string]$PythonExe = 'python.exe', [string]$PythonExe = 'python.exe',
[switch]$Mock, [switch]$Mock,
[switch]$Headless [switch]$Headless,
# 可选跨批次会话复用:持久 receipt_session Profile(同日重跑/重试免登录);默认一次性临时 Profile。
[switch]$SessionReuse
) )
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile" } if (-not (Test-Path -LiteralPath $SecretFile -PathType Leaf)) { throw "Secret 文件不存在:$SecretFile" }
$workerScript = Join-Path $WorkerRoot 'scripts\rpa\receipt\receipt_rpa_worker.py' $workerScript = Join-Path $WorkerRoot 'scripts\freight_rpa\receipt\receipt_rpa_worker.py'
if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" } if (-not (Test-Path -LiteralPath $workerScript -PathType Leaf)) { throw "Worker 不存在:$workerScript" }
function ConvertTo-PlainText { function ConvertTo-PlainText {
@@ -32,24 +35,32 @@ $secret = Import-Clixml -LiteralPath $SecretFile
foreach ($required in @('ToolApiKey', 'CredentialKey')) { foreach ($required in @('ToolApiKey', 'CredentialKey')) {
if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" } if (-not ($secret.PSObject.Properties.Name -contains $required)) { throw "Secret 文件缺少字段:$required" }
} }
$dataRoot = Join-Path $WorkerRoot 'data\freight_receipt_rpa' # freight_rpa 三层布局根:$WorkerRoot\freight_rpa\{inventory,receipt,common}(与后端 settings/.env 默认值一致)。
$rpaRoot = Join-Path $WorkerRoot 'freight_rpa'
$processVars = [ordered]@{ $processVars = [ordered]@{
HXOPS_API_BASE = $ApiBase HXOPS_API_BASE = $ApiBase
SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey SHIPPING_NOTICE_TOOL_API_KEY = ConvertTo-PlainText $secret.ToolApiKey
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey FREIGHT_RPA_CREDENTIAL_KEY = ConvertTo-PlainText $secret.CredentialKey
SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = $Environment FREIGHT_RPA_WORKER_ENVIRONMENT = $Environment
SHIPPING_NOTICE_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' }) FREIGHT_RPA_WORKER_MOCK = $(if ($Mock) { 'true' } else { 'false' })
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' }) FREIGHT_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
FREIGHT_RPA_WORKER_SESSION_REUSE = $(if ($SessionReuse) { 'true' } else { 'false' })
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。 # 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3' FREIGHT_RPA_WORKER_POLL_SECONDS = '3'
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot 'logs\worker.log' FREIGHT_RPA_WORKER_LOG_FILE = Join-Path $rpaRoot 'receipt\logs\worker.log'
FREIGHT_RPA_WORKER_LOG_MAX_BYTES = '10485760'
FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT = '5'
# 独立 Worker 身份:监控端按 worker_id 出独立收料卡片,固定后缀避免与库存 Worker/按 pid 的身份抖动。 # 独立 Worker 身份:监控端按 worker_id 出独立收料卡片,固定后缀避免与库存 Worker/按 pid 的身份抖动。
SHIPPING_NOTICE_RPA_WORKER_ID = "${env:COMPUTERNAME}-receipt" FREIGHT_RPA_WORKER_ID = "${env:COMPUTERNAME}-receipt"
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = '20' FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS = '20'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers' FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $rpaRoot 'receipt\triggers'
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop' FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $rpaRoot 'receipt\drop'
# 浏览器 Profile 目录复用既有标准变量(与库存 RPA Worker 一致),不另设 RECEIPT_* 冗余变量。 # 浏览器 Profile 根:与库存 Worker 共用 common/browser_profile(各自在其中创建隔离的一次性子目录)。
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $WorkerRoot 'data\shipping_notice\freight_rpa\browser_profile' FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaRoot 'common\browser_profile'
# 本机磁盘保留:与库存 Worker 同参(归档 trigger/drop、日志备份、孤儿 run_*/receipt_* Profile)。
FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS = '7'
FREIGHT_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = '3600'
FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = '24'
} }
foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') } foreach ($entry in $processVars.GetEnumerator()) { [Environment]::SetEnvironmentVariable($entry.Key, [string]$entry.Value, 'Process') }
try { try {
+3 -3
View File
@@ -72,7 +72,7 @@ function Stop-StaleHxopsPythonProcesses {
[regex]::Escape((Join-Path $BackendPath "workers\worker_kb.py")), [regex]::Escape((Join-Path $BackendPath "workers\worker_kb.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")), [regex]::Escape((Join-Path $BackendPath "workers\worker_shipping_notice.py")),
[regex]::Escape((Join-Path $BackendPath "workers\worker_scheduler.py")), [regex]::Escape((Join-Path $BackendPath "workers\worker_scheduler.py")),
[regex]::Escape((Join-Path $RepoRoot "scripts\rpa\inventory\inventory_rpa_worker.py")) [regex]::Escape((Join-Path $RepoRoot "scripts\freight_rpa\inventory\inventory_rpa_worker.py"))
) )
# 说明:上面同时包含 backend/ 根目录的旧部署入口与 workers/ 目录的新单实例入口。 # 说明:上面同时包含 backend/ 根目录的旧部署入口与 workers/ 目录的新单实例入口。
# 两套在仓库中并存(旧路径用于生产多进程部署,新路径推荐用于本地 IDE 单实例调试)。 # 两套在仓库中并存(旧路径用于生产多进程部署,新路径推荐用于本地 IDE 单实例调试)。
@@ -439,13 +439,13 @@ function Start-FreightRpaWorkerWindow {
) )
$envPrefix = Get-DotEnvExportPrefix -Paths $EnvFiles $envPrefix = Get-DotEnvExportPrefix -Paths $EnvFiles
$envPrefix += " `$env:HXOPS_API_BASE='http://127.0.0.1:5052'; `$env:SHIPPING_NOTICE_RPA_WORKER_MOCK='true';" $envPrefix += " `$env:HXOPS_API_BASE='http://127.0.0.1:5052'; `$env:FREIGHT_RPA_WORKER_MOCK='true';"
Start-WorkerWindow ` Start-WorkerWindow `
-Title "freight-rpa-worker" ` -Title "freight-rpa-worker" `
-WorkingDirectory $RepoRoot ` -WorkingDirectory $RepoRoot `
-EnvPrefix $envPrefix ` -EnvPrefix $envPrefix `
-Command "& '$BackendPath\.venv\Scripts\python.exe' .\scripts\rpa\inventory\inventory_rpa_worker.py" -Command "& '$BackendPath\.venv\Scripts\python.exe' .\scripts\freight_rpa\inventory\inventory_rpa_worker.py"
} }
function Start-FrontendWindow { function Start-FrontendWindow {