feat(freight-rpa): 批次R解耦编排层并切换 onhand/inbound 契约
将 RPA 编排收编至 freight_rpa,回调迁 /api/freight-rpa/*。 共享目录与 Worker 契约一次切换至 onhand/inbound/upload, 并补 outbound 骨架与 tt16 排程 job key 迁移。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
bf3154033b
commit
ffc0d4a430
147 files changed
+4221
-2678
No files matched your search
@@ -134,28 +134,31 @@ SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
# RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=data/freight_rpa/receipt/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers
|
||||
# RPA 目录(相对 backend/ 根;freight_rpa/{onhand,inbound,outbound,upload,common},2026-10-16 批次 R)
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=data/freight_rpa/onhand/drop
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=data/freight_rpa/onhand/triggers
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=data/freight_rpa/inbound/drop
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=data/freight_rpa/inbound/triggers
|
||||
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=data/freight_rpa/inbound/archives
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=data/freight_rpa/outbound/drop
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=data/freight_rpa/outbound/triggers
|
||||
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=data/freight_rpa/outbound/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/upload/queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload/triggers
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
# 本地 RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py)
|
||||
# 本地 RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py)
|
||||
FREIGHT_RPA_WORKER_MOCK=false
|
||||
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
|
||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
|
||||
@@ -142,21 +142,24 @@ SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
|
||||
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=900
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
|
||||
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||
# RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/archives
|
||||
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
|
||||
# RPA 目录(正式:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/drop
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/onhand/triggers
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/drop
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/triggers
|
||||
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inbound/archives
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/drop
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/triggers
|
||||
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/outbound/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/upload/queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/upload/triggers
|
||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||
# 订单交期回复 Agent(2026-10-10 上线边界):只同步订单日期 ≥ 起始日的订单行,早于边界的历史行随 erp_missing 语义自动移出工作台;留空/删除 = 全量同步(dev/test 不配置)
|
||||
|
||||
@@ -151,8 +151,8 @@ SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||
# 两域超时须覆盖最坏批次总时长(10 站串行 + 单站失败重试可达 30 分钟+),
|
||||
# 否则每轮对账会把仍在飞的健康批次误回收(2026-10-08 RUN20261008003113B726 实测教训)
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=3600
|
||||
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=3600
|
||||
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS=3600
|
||||
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS=3600
|
||||
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
@@ -165,20 +165,23 @@ FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
|
||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers
|
||||
# RPA 目录(测试:Ubuntu 挂载 Windows 共享;freight_rpa/{onhand,inbound,outbound,upload,common})
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/drop
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/onhand/triggers
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/drop
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/triggers
|
||||
FREIGHT_RPA_INBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inbound/archives
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/drop
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/triggers
|
||||
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/outbound/archives
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/queue
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/upload/triggers
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
# 本地 Mock RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py,可选)
|
||||
# 本地 Mock RPA(scripts/freight_rpa/onhand/onhand_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_WORKER_MOCK=true
|
||||
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# FREIGHT_RPA_WORKER_SAMPLE_ONHAND=
|
||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
|
||||
@@ -163,7 +163,7 @@ docker compose logs -f hxops-backend
|
||||
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
|
||||
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。
|
||||
- **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。
|
||||
- **RPA 命名空间(强制,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)。
|
||||
- **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/` 根下,按 `onhand/`、`inbound/`、`outbound/`(抓取域,叶目录同构 triggers/drop/logs/archives)、`upload/`(上传域,triggers/queue)、`common/`(跨 Worker 共享物,如 browser_profile)分域(2026-10-16 批次 R:原 inventory/receipt 已随迁)。
|
||||
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
|
||||
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
|
||||
|
||||
|
||||
@@ -79,6 +79,14 @@ def create_app(config_name='default'):
|
||||
|
||||
_transfer_capabilities.register_transfer_capabilities()
|
||||
|
||||
# onhand/inbound RPA 回调 sink 注册(幂等):/api/freight-rpa/onhand-*、/api/freight-rpa/
|
||||
# inbound-* 端点经 callback_sinks.dispatch_sink 分发到业务处理器;未注册的 kind 仍显式
|
||||
# 404(FREIGHT_RPA.SINK_NOT_REGISTERED),不静默吞回调。
|
||||
from app.services.shipping_notice.rpa_sinks import register_inbound_sinks, register_onhand_sinks
|
||||
|
||||
register_onhand_sinks()
|
||||
register_inbound_sinks()
|
||||
|
||||
# 启动时强制加载一次,避免 worker 冷启动到首个请求之间仍用镜像默认值。
|
||||
with app.app_context():
|
||||
_apply_persisted_settings(app, force=True)
|
||||
@@ -149,7 +157,7 @@ def create_app(config_name='default'):
|
||||
# 负责(dev Wave 4),Web 进程不再兜底扫描。
|
||||
# AUTO_UPLOAD 显式开启时启动级校验货代上传 RPA(仅告警,不阻断启动)。
|
||||
try:
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
log_auto_upload_readiness_at_startup,
|
||||
)
|
||||
log_auto_upload_readiness_at_startup(app)
|
||||
|
||||
@@ -47,6 +47,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
procurement_contract_bp,
|
||||
shipping_notice_bp,
|
||||
)
|
||||
from app.api.freight_rpa import freight_rpa_bp
|
||||
from app.api.files import files_bp
|
||||
from app.api.contract_payment import contract_payment_bp
|
||||
from app.api.equipment_acceptance import equipment_acceptance_bp
|
||||
@@ -71,6 +72,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(freight_rpa_bp, url_prefix='/api/freight-rpa')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
||||
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||
|
||||
@@ -24,6 +24,7 @@ import app.api.admin.announcements # noqa: F401
|
||||
import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||
import app.api.admin.shipping_inventory # noqa: F401
|
||||
import app.api.admin_freight_rpa # noqa: F401
|
||||
import app.api.admin.shipping_order_schema # noqa: F401
|
||||
import app.api.admin.shipping_field_assets # noqa: F401
|
||||
import app.api.admin.shipping_order_document_profiles # noqa: F401
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
api/admin/shipping_inventory.py
|
||||
|
||||
用途:提供库存源、RPA Profile、路由规则及外部系统映射的管理 API。
|
||||
用途:提供库存源、路由规则及外部系统映射的管理 API。
|
||||
依赖:admin blueprint、require_admin、shipping_inventory_service。
|
||||
逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成。
|
||||
逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成;
|
||||
RPA Profile CRUD 已迁至 api/admin_freight_rpa.py(/api/admin/freight-rpa/rpa-profiles)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -110,35 +111,6 @@ def delete_shipping_excel_template(template_id: int):
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_rpa_profiles():
|
||||
"""列出脱敏后的 RPA Profile 配置。"""
|
||||
return _ok(shipping_inventory_service.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_rpa_profile():
|
||||
"""创建 RPA Profile;明文凭据仅在本次请求内用于加密。"""
|
||||
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_rpa_profile(profile_id: int):
|
||||
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
|
||||
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_rpa_profile(profile_id: int):
|
||||
"""删除没有库存源引用的错误连接配置。"""
|
||||
shipping_inventory_service.delete_profile(profile_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_sources():
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
api/admin_freight_rpa.py
|
||||
|
||||
用途:货代 RPA 凭据(RPA Profile)管理 API——批次 R 自 /api/admin/shipping-notice/rpa-profiles
|
||||
迁移至 /api/admin/freight-rpa/rpa-profiles(批次 S 再统一 onhand/inbound 子域命名空间)。
|
||||
依赖:admin blueprint、require_admin、shipping_inventory_service(服务层留原地,仅路由搬家)。
|
||||
逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成;
|
||||
与 admin/shipping_inventory.py 的 sources/receipt-report-config 路由解耦(批次 S 再迁)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.admin import shipping_inventory_service
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按平台统一 envelope 返回管理 API 成功结果。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_rpa_profiles():
|
||||
"""列出脱敏后的 RPA Profile 配置。"""
|
||||
return _ok(shipping_inventory_service.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_rpa_profile():
|
||||
"""创建 RPA Profile;明文凭据仅在本次请求内用于加密。"""
|
||||
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_rpa_profile(profile_id: int):
|
||||
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
|
||||
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_rpa_profile(profile_id: int):
|
||||
"""删除没有库存源引用的错误连接配置。"""
|
||||
shipping_inventory_service.delete_profile(profile_id)
|
||||
return '', 204
|
||||
@@ -0,0 +1,219 @@
|
||||
"""
|
||||
backend/app/api/freight_rpa.py
|
||||
|
||||
用途:货代 RPA 回调蓝图(/api/freight-rpa/*)——Windows Worker 向后端上报心跳、
|
||||
库存(onhand)/收料(inbound)导出结果与货代上传结果的唯一回调入口。
|
||||
批次 R 解耦后取代旧 shipping-notice rpa 回调前缀(无双路由、无兼容层)。
|
||||
依赖:app.core.tool_auth(集成密钥鉴权)、freight_rpa.common.callback_sinks(sink 分发)、
|
||||
freight_rpa.common.worker_heartbeat(心跳)、shipping_tools、
|
||||
shipping_notice.rpa_sinks(api 层为组合根,允许同时 import 双侧)。
|
||||
逻辑:before_request 统一 Bearer / X-Integration-Key 鉴权(与 Tool 蓝图同一把 key)。
|
||||
分发策略按「处理函数当前住在哪个包」决定:
|
||||
- /heartbeat 直连 freight_rpa.common.worker_heartbeat;
|
||||
- /upload-complete 直连现有业务处理器(shipping_notice.tools);
|
||||
- onhand-* 与 inbound-* 全部经 callback_sinks.dispatch_sink 分发,真实业务 sink 由
|
||||
组合根(create_app → shipping_notice.rpa_sinks.register_onhand_sinks /
|
||||
register_inbound_sinks)注册;未注册的 kind 显式 404(FREIGHT_RPA.SINK_NOT_REGISTERED)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.tool_auth import require_tool_auth
|
||||
from app.services.freight_rpa.common.callback_sinks import dispatch_sink
|
||||
from app.services.freight_rpa.common.worker_heartbeat import record_rpa_worker_heartbeat
|
||||
|
||||
freight_rpa_bp = Blueprint('freight_rpa', __name__)
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
"""
|
||||
读取回调 JSON 请求体,并剥离不可信的操作人身份字段。
|
||||
|
||||
核心逻辑:与 shipping_notice Tool 蓝图同口径——集成密钥调用方不得通过 body
|
||||
伪造 `_trusted_user_id` / `operator_id` / `actor_id`。
|
||||
"""
|
||||
raw = request.get_json(silent=True) or {}
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
payload = dict(raw)
|
||||
for key in ('_trusted_user_id', 'operator_id', 'actor_id'):
|
||||
payload.pop(key, None)
|
||||
return payload
|
||||
|
||||
|
||||
@freight_rpa_bp.before_request
|
||||
def _verify_worker_access():
|
||||
"""RPA Worker 回调统一 Header 鉴权;与 Tool API 共用同一集成密钥配置。"""
|
||||
require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/heartbeat', methods=['POST'])
|
||||
def heartbeat():
|
||||
"""
|
||||
RPA Worker 心跳上报。
|
||||
【AI 触发时机】:非 Agent 入口;Windows Worker(库存/收料)由独立守护线程周期调用。
|
||||
|
||||
核心逻辑:校验 payload 后写入 Redis/内存;后端在写各类 trigger 前以此做在线就绪检查。
|
||||
"""
|
||||
payload = _payload()
|
||||
try:
|
||||
worker = record_rpa_worker_heartbeat(payload)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
# 心跳存储不可用(ServiceUnavailableError)原样上抛,由全局 AppError handler 出标准错误 envelope。
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-ready', methods=['POST'])
|
||||
def onhand_ready():
|
||||
"""
|
||||
onhand 单任务导出回调(旧 inventory-ready 端点随批次 R 迁入本蓝图)。
|
||||
【AI 触发时机】:非 Agent 入口;库存 Worker 完成单任务导出后调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-ready') 分发到组合根注册的业务 sink
|
||||
(inventory_rpa_workflow.rpa_report_inventory:快照落盘 + 任务状态回写),
|
||||
envelope = 裸业务 tool_response dict(与旧 /rpa/inventory-ready 逐字一致)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-ready', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-batch-ready', methods=['POST'])
|
||||
def onhand_batch_ready():
|
||||
"""
|
||||
onhand 批量导出终态回调(旧 /rpa/inventory-batch-ready)。
|
||||
【AI 触发时机】:非 Agent 入口;库存 Worker 按排程批次完成全部站点导出后调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-batch-ready') 分发;按 Warehouse 写入库存快照并
|
||||
finalize 排程 run(rpa_report_inventory_batch),envelope = 裸业务 dict。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-batch-ready', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-batch-claimed', methods=['POST'])
|
||||
def onhand_batch_claimed():
|
||||
"""
|
||||
onhand 批量领取回调(旧 /rpa/inventory-batch-claimed)。
|
||||
【AI 触发时机】:非 Agent 入口;v2 Worker 领取批次 trigger 后立即调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-batch-claimed') 分发;仅记录 Attempt 执行阶段
|
||||
(per_source_rpa_service.claim_inventory_batch),envelope = {'success':True,'data':...}。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-batch-claimed', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-batch-progress', methods=['POST'])
|
||||
def onhand_batch_progress():
|
||||
"""
|
||||
onhand 批量导出进度回调(旧 /rpa/inventory-batch-progress)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 每完成一个站点导出后调用(非终态,以 batch-ready 为准)。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-batch-progress') 分发;实时回写排程 run 计数
|
||||
(inventory_rpa_workflow.report_inventory_batch_progress),envelope = 裸业务 dict。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-batch-progress', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-configuration-test-start', methods=['POST'])
|
||||
def onhand_configuration_test_start():
|
||||
"""
|
||||
onhand 配置测试开始回调(旧 /rpa/inventory-configuration-test-batch-progress)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 领取批量验证中的单个站点后立即调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-configuration-test-start') 分发;把该站点测试运行写为
|
||||
processing / rpa_exporting,envelope = {'status':'ok','data':...}(旧 batch-progress 同款)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-configuration-test-start', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-configuration-test-analyze', methods=['POST'])
|
||||
def onhand_configuration_test_analyze():
|
||||
"""
|
||||
onhand 配置测试结构分析回调(旧 /rpa/inventory-configuration-test-ready)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 完成单站点配置测试导出后调用。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-configuration-test-analyze') 分发;仅分析文件结构,
|
||||
不创建生产库存快照或任务关联,envelope = {'status':'ok','data':...}(旧 ready 同款)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-configuration-test-analyze', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-configuration-test-complete', methods=['POST'])
|
||||
def onhand_configuration_test_complete():
|
||||
"""
|
||||
onhand 配置测试批次终态回调(旧 /rpa/inventory-configuration-test-batch-ready)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 完成批量配置测试后按 validation_run_no 回传 results。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-configuration-test-complete') 分发;独立回写每个库存站点
|
||||
的测试结果,envelope = {'status':'ok','data':...}(旧 batch-ready 同款)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-configuration-test-complete', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/onhand-repair', methods=['POST'])
|
||||
def onhand_repair():
|
||||
"""
|
||||
onhand 受控库存回调修复(旧 /rpa/inventory-repair)。
|
||||
【AI 触发时机】:非 Agent 入口;人工/运维补偿链路调用,复用正式 v2 ingest 流程。
|
||||
|
||||
核心逻辑:dispatch_sink('onhand-repair') 分发;repair 语义由 kind 承载——sink 等价于
|
||||
旧实现 `payload['repair'] = True` 后走 batch-ready ingest,envelope = 裸业务 dict。
|
||||
"""
|
||||
return jsonify(dispatch_sink('onhand-repair', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/inbound-batch-ready', methods=['POST'])
|
||||
def inbound_batch_ready():
|
||||
"""
|
||||
inbound(收料)批量导出终态回调(旧 /rpa/receipt-batch-ready)。
|
||||
【AI 触发时机】:非 Agent 入口;收料 Worker 完成报表导出并落 drop 目录后调用。
|
||||
|
||||
核心逻辑:dispatch_sink('inbound-batch-ready') 分发到组合根注册的业务 sink
|
||||
(receipt_report_storage.ingest_receipt_callback:委托 freight_rpa.inbound.report_archive
|
||||
原样归档,终态 commit 后由域内业务桥推进在途调拨并归集排程终态)——独立归档文件,
|
||||
绝不进入库存回调或库存匹配链路;envelope = {'success': True, 'data': ...}(旧端点逐字一致)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('inbound-batch-ready', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/inbound-unit-progress', methods=['POST'])
|
||||
def inbound_unit_progress():
|
||||
"""
|
||||
inbound 单元领取/导出中回调(旧 /rpa/receipt-unit-progress)。
|
||||
【AI 触发时机】:非 Agent 入口;收料 Worker 领取单元后调用(awaiting_rpa → processing)。
|
||||
|
||||
核心逻辑:dispatch_sink('inbound-unit-progress') 分发到 mark_receipt_unit_processing
|
||||
(Task 11 已随排程壳平移改名,现住 schedule.freight_inbound_rpa_finalize);本路由同时是收料
|
||||
超时对账的活动锚数据源(mark 落单元 started_at)。曾因重构分叉合并丢失(2026-10-08),
|
||||
Worker 上报全程 404,勿再从任何路由文件删除。
|
||||
"""
|
||||
return jsonify(dispatch_sink('inbound-unit-progress', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/inbound-batch-progress', methods=['POST'])
|
||||
def inbound_batch_progress():
|
||||
"""
|
||||
inbound 批量导出累计进度回调(旧 /rpa/receipt-batch-progress)。
|
||||
【AI 触发时机】:非 Agent 入口;收料 Worker 每完成一笔导出后调用(非终态)。
|
||||
|
||||
核心逻辑:dispatch_sink('inbound-batch-progress') 分发到 report_receipt_batch_progress
|
||||
(Task 11 已随排程壳平移改名,现住 schedule.freight_inbound_rpa_finalize),回写排程 run 计数
|
||||
(对齐 onhand-batch-progress 语义)。
|
||||
"""
|
||||
return jsonify(dispatch_sink('inbound-batch-progress', **_payload()))
|
||||
|
||||
|
||||
@freight_rpa_bp.route('/upload-complete', methods=['POST'])
|
||||
def upload_complete():
|
||||
"""
|
||||
货代上传结果回调(旧 /rpa/upload-complete,URL 词根不变)。
|
||||
【AI 触发时机】:非 Agent 入口;Worker 完成出货 Excel 上传(成功或失败)后调用。
|
||||
|
||||
核心逻辑:直连 shipping_notice.tools.rpa_report_upload 回写任务状态。
|
||||
"""
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
@@ -19,12 +19,12 @@ from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.job_registry import get_platform_job, run_platform_job
|
||||
from app.services.schedule.schedule_contract import normalize_job_key
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import (
|
||||
apply_deferred_receipt_schedule_run_state,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
should_defer_receipt_schedule_run,
|
||||
|
||||
@@ -67,7 +67,7 @@ def update_schedule_task_config(task_id: int):
|
||||
|
||||
config_data = data.get('config', data)
|
||||
if isinstance(config_data, dict) and config_data:
|
||||
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
|
||||
# platform_job 仅白名单且 enabled 的任务(如 freight-rpa-onhand)允许写 ScheduleTaskConfig
|
||||
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
||||
raise ValidationError(
|
||||
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/api/schedule/rpa_workers.py
|
||||
|
||||
用途:管理端查询货代库存/收料 RPA Worker 在线状态与就绪摘要。
|
||||
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
||||
依赖:schedule.blueprint、freight_rpa.common.worker_heartbeat.serialize_rpa_worker_status。
|
||||
逻辑:ScheduleWorkbenchPanel 在库存或收料 RPA 排程工作台展示对应 worker 心跳状态。
|
||||
"""
|
||||
|
||||
@@ -13,7 +13,7 @@ from flask import request
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status
|
||||
from app.services.freight_rpa.common.worker_heartbeat import serialize_rpa_worker_status
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
|
||||
@@ -23,7 +23,7 @@ def get_rpa_workers_status():
|
||||
返回 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||
|
||||
Query:
|
||||
scope: inventory(默认)或 receipt。
|
||||
scope: onhand(默认)或 inbound。
|
||||
"""
|
||||
scope = str(request.args.get('scope') or 'inventory').strip().lower() or 'inventory'
|
||||
scope = str(request.args.get('scope') or 'onhand').strip().lower() or 'onhand'
|
||||
return ok(serialize_rpa_worker_status(scope=scope))
|
||||
@@ -21,11 +21,11 @@ from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||
from app.services.schedule.queue_service import enqueue_manual_schedule_run
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
from app.services.schedule.freight_onhand_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.freight_inbound_rpa_archive import resolve_receipt_raw_zip_download
|
||||
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@@ -152,7 +152,7 @@ def resend_receipt_report_file(file_id: int):
|
||||
if report_file is None or report_file.archive_deleted_at is not None:
|
||||
raise NotFoundError('Receipt report file not found')
|
||||
user = get_current_user()
|
||||
outcome = deliver_receipt_file(report_file.id, force=True)
|
||||
outcome = deliver_inbound_file(report_file.id, force=True)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_notification_resent', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='admin', actor_id=getattr(user, 'id', None),
|
||||
@@ -247,9 +247,9 @@ def retry_receipt_rpa_unit(unit_id: int):
|
||||
}
|
||||
retry.trigger_snapshot_json = trigger_unit
|
||||
run = retry.schedule_run
|
||||
trigger_path = write_receipt_export_batch_trigger(
|
||||
trigger_path = write_inbound_export_batch_trigger(
|
||||
f'{run.run_no}-retry-{retry.id}', [trigger_unit],
|
||||
{'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': 'shipping_receipt_rpa.v1', 'retry_of_unit_id': failed.id},
|
||||
{'schedule_run_id': run.id, 'schedule_task_id': run.schedule_task_id, 'schema_version': SCHEMA, 'retry_of_unit_id': failed.id},
|
||||
)
|
||||
if not trigger_path:
|
||||
db.session.rollback()
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
backend/app/api/tools/shipping_notice.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent 与导出下载入口调用。
|
||||
依赖:app.core.errors、app.core.tool_auth、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||
逻辑:register_blueprints 从 api.tools 挂载;Tool 成功响应仍用 status: ok/failed 业务 envelope;
|
||||
HTTP 级参数/资源错误统一 raise AppError;`_payload()` 剥离 body 中的操作人伪造字段;
|
||||
RPA 回调已整体迁出至 api/freight_rpa.py(/api/freight-rpa/*,无双路由);
|
||||
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -15,10 +16,8 @@ from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from app.core.tool_auth import require_tool_auth
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.query_service import (
|
||||
@@ -28,40 +27,10 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验货代 Tool API 鉴权 Header。
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
or current_app.config.get('INTEGRATION_API_KEY')
|
||||
or ''
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||
code='missing_auth',
|
||||
)
|
||||
bearer = str(request.headers.get('Authorization') or '').strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
|
||||
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and (not integration_key):
|
||||
raise UnauthorizedError('missing_auth')
|
||||
raise UnauthorizedError('invalid_auth')
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
|
||||
message = str(exc.message or '').strip()
|
||||
@@ -84,12 +53,13 @@ def _handle_tool_app_error(exc: AppError):
|
||||
@shipping_notice_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
|
||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
|
||||
对货代 Tool / 导出接口做统一 Header 鉴权。
|
||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key
|
||||
(鉴权实现见 app.core.tool_auth.require_tool_auth,与 freight-rpa 回调蓝图共用)。
|
||||
"""
|
||||
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
require_tool_auth()
|
||||
return None
|
||||
|
||||
def _tool_api_base_url() -> str:
|
||||
@@ -299,98 +269,6 @@ def tool_get_task_status():
|
||||
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
|
||||
return jsonify(shipping_tools.get_task_status(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||
def rpa_worker_heartbeat():
|
||||
"""
|
||||
RPA Worker 心跳上报。
|
||||
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
|
||||
"""
|
||||
payload = _payload()
|
||||
try:
|
||||
worker = record_rpa_worker_heartbeat(payload)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
|
||||
def rpa_inventory_ready():
|
||||
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_batch_ready():
|
||||
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/receipt-batch-ready', methods=['POST'])
|
||||
def rpa_receipt_batch_ready():
|
||||
"""收料 RPA 回调:独立归档文件,绝不进入库存回调或库存匹配链路。"""
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
|
||||
return jsonify({'success': True, 'data': ingest_receipt_callback(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/receipt-unit-progress', methods=['POST'])
|
||||
def rpa_receipt_unit_progress():
|
||||
"""收料单元领取/导出中:awaiting_rpa → processing,供管理端实时看到进行中。
|
||||
|
||||
本路由同时是收料超时对账的活动锚数据源(mark 落单元 started_at);
|
||||
曾因重构分叉合并丢失(2026-10-08),Worker 上报全程 404,勿再从旧路径文件删除。
|
||||
"""
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import mark_receipt_unit_processing
|
||||
|
||||
return jsonify({'success': True, 'data': mark_receipt_unit_processing(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/receipt-batch-progress', methods=['POST'])
|
||||
def rpa_receipt_batch_progress():
|
||||
"""收料 RPA 每完成一笔导出的累计进度回写(非终态,对齐库存 inventory-batch-progress)。"""
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import report_receipt_batch_progress
|
||||
|
||||
return jsonify({'success': True, 'data': report_receipt_batch_progress(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-claimed', methods=['POST'])
|
||||
def rpa_inventory_batch_claimed():
|
||||
"""v2 Worker 领取回调:仅记录 Attempt 执行阶段。"""
|
||||
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
|
||||
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST'])
|
||||
def rpa_inventory_batch_progress():
|
||||
"""RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
|
||||
return jsonify(report_inventory_batch_progress(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_ready():
|
||||
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_ready():
|
||||
"""RPA 批量配置测试回调:按 validation_run_no 独立回写每个库存站点。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_exports(_payload())})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-batch-progress', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_batch_progress():
|
||||
"""RPA 批量配置测试进度:Worker 领取单个站点后立即回写执行阶段。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_batch_test_progress(_payload())})
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
def repair_task_inventory_attachment(task_no: str):
|
||||
"""
|
||||
@@ -402,19 +280,6 @@ def repair_task_inventory_attachment(task_no: str):
|
||||
payload.setdefault("task_id", task_no)
|
||||
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-repair', methods=['POST'])
|
||||
def rpa_inventory_repair():
|
||||
"""受控库存回调修复:复用正式 v2 ingest 链路。"""
|
||||
payload = _payload()
|
||||
payload['repair'] = True
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
|
||||
def download_task_export(task_no: str):
|
||||
"""下载任务已生成的出货 Excel。"""
|
||||
|
||||
@@ -373,11 +373,15 @@ class Config:
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
|
||||
FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
|
||||
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
# 出站抓取本期无 Worker;超时键与 inbound 同形预留,避免后续批次再改 env 骨架。
|
||||
FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_OUTBOUND_TIMEOUT_SECONDS') or '900'
|
||||
)
|
||||
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
||||
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
||||
@@ -444,33 +448,46 @@ class Config:
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
# RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。
|
||||
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop'
|
||||
# RPA 运行期数据目录分域(2026-10-16 批次 R):
|
||||
# onhand/ inbound/ outbound/ — 抓取域,叶目录同构 triggers|drop|logs|archives
|
||||
# upload/ — 上传域,叶目录 triggers|queue(与抓取域并列,勿挂 outbound 下)
|
||||
# common/ — 跨 Worker 共享(browser_profile)
|
||||
# outbound 本期无 Worker,仍落盘同构目录 + env,避免切换日再改骨架。
|
||||
FREIGHT_RPA_SHARED_ONHAND_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_ONHAND_DROP_DIR', 'freight_rpa', 'onhand', 'drop'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers'
|
||||
FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR', 'freight_rpa', 'onhand', 'triggers'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop'
|
||||
FREIGHT_RPA_SHARED_INBOUND_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_INBOUND_DROP_DIR', 'freight_rpa', 'inbound', 'drop'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers'
|
||||
FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', 'freight_rpa', 'inbound', 'triggers'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR', 'freight_rpa', 'outbound', 'drop'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR', 'freight_rpa', 'outbound', 'triggers'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'inventory', 'upload_queue'
|
||||
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'upload', 'queue'
|
||||
)
|
||||
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'inventory', 'upload_triggers'
|
||||
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'upload', 'triggers'
|
||||
)
|
||||
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
|
||||
FREIGHT_RPA_ONHAND_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_ONHAND_ARCHIVE_DIR', 'freight_rpa', 'onhand', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_RECEIPT_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_RECEIPT_ARCHIVE_DIR', 'freight_rpa', 'receipt', 'archives'
|
||||
FREIGHT_RPA_INBOUND_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_INBOUND_ARCHIVE_DIR', 'freight_rpa', 'inbound', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR = _rpa_data_path(
|
||||
'FREIGHT_RPA_OUTBOUND_ARCHIVE_DIR', 'freight_rpa', 'outbound', 'archives'
|
||||
)
|
||||
FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false')
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
backend/app/core/tool_auth.py
|
||||
|
||||
用途:集成密钥鉴权的公共实现,供所有以 Bearer / X-Integration-Key 方式接入的
|
||||
Tool / 回调蓝图共用(当前:shipping_notice Tool 蓝图、freight-rpa 回调蓝图)。
|
||||
依赖:flask.current_app/request、app.core.errors(ServiceUnavailableError / UnauthorizedError)。
|
||||
逻辑:由各蓝图 before_request 调用 require_tool_auth();本模块只做 Header 校验,
|
||||
不感知任何具体蓝图的错误 envelope(由蓝图自身 errorhandler 决定响应格式)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, request
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, UnauthorizedError
|
||||
|
||||
|
||||
def require_tool_auth() -> None:
|
||||
"""
|
||||
校验集成方 Tool / RPA 回调 API 鉴权 Header。
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA Worker 或
|
||||
外部系统请求挂接本鉴权的蓝图时,由该蓝图的 before_request 自动触发。
|
||||
|
||||
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
configured = str(
|
||||
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
or current_app.config.get('INTEGRATION_API_KEY')
|
||||
or ''
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||
code='missing_auth',
|
||||
)
|
||||
bearer = str(request.headers.get('Authorization') or '').strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
|
||||
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and (not integration_key):
|
||||
raise UnauthorizedError('missing_auth')
|
||||
raise UnauthorizedError('invalid_auth')
|
||||
@@ -2,7 +2,7 @@
|
||||
models/shipping_inventory_config.py
|
||||
|
||||
用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。
|
||||
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。
|
||||
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 freight_rpa.common.credential_crypto 读写。
|
||||
逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置,
|
||||
外部系统映射仅供后端内部复用,不承载调拨决策。
|
||||
"""
|
||||
|
||||
@@ -24,7 +24,7 @@ from app.models import (
|
||||
ShippingReceiptReportConfig,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.credential_crypto import encrypt_credential
|
||||
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
||||
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
|
||||
@@ -588,7 +588,7 @@ def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
|
||||
# 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。
|
||||
schedule_runs = ScheduleRun.query.join(ScheduleTask).filter(
|
||||
ScheduleTask.platform_api_path == 'shipping-inventory-rpa',
|
||||
ScheduleTask.platform_api_path == 'freight-rpa-onhand',
|
||||
).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all()
|
||||
for run in schedule_runs:
|
||||
response = run.api_response_json if isinstance(run.api_response_json, dict) else {}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""货代 RPA 模块根:承载 freight_rpa 域代码(common/onhand/inbound/upload)。"""
|
||||
@@ -0,0 +1 @@
|
||||
"""common:域中立件(跨 RPA Worker 共用、不依赖具体业务域)。"""
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
services/freight_rpa/common/callback_sinks.py
|
||||
|
||||
用途:RPA 回调业务 sink 注册表——freight_rpa 侧的回调分发缝。
|
||||
依赖:app.core.errors.AppError。
|
||||
逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,onhand 等待拆端点按 kind 分发到
|
||||
组合根(create_app / api 层)注册的业务处理器;未注册的 kind 显式 404,
|
||||
绝不静默吞回调。Task 9/10 落地 workflow_protocol / report_archive 时由
|
||||
组合根调用 register_sink 注入真实业务持久化处理器。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
_SINKS: dict[str, Callable[..., Any]] = {}
|
||||
|
||||
|
||||
def register_sink(kind: str, handler: Callable[..., Any]) -> None:
|
||||
"""
|
||||
注册一个回调 sink 处理器(由组合根在应用启动时调用)。
|
||||
|
||||
Args:
|
||||
kind: 回调种类,命名 = 回调路由名去前缀(如 "onhand-ready"、
|
||||
"onhand-configuration-test-complete");同一 kind 重复注册为覆盖。
|
||||
handler: 业务处理器;契约:接收回调载荷的关键字参数并返回可 jsonify 的业务结果。
|
||||
"""
|
||||
_SINKS[kind] = handler
|
||||
|
||||
|
||||
def dispatch_sink(kind: str, **payload: Any) -> Any:
|
||||
"""
|
||||
按 kind 分发回调载荷到已注册 sink。
|
||||
|
||||
Args:
|
||||
kind: register_sink 注册过的回调种类。
|
||||
payload: 回调载荷键值对;键必须为合法 Python 标识符(回调 schema 均为 snake_case)。
|
||||
Returns:
|
||||
handler 的返回值(业务结果 dict,由蓝图 jsonify)。
|
||||
Raises:
|
||||
AppError: code=FREIGHT_RPA.SINK_NOT_REGISTERED、http_status=404——kind 未注册时
|
||||
显式失败(Task 9/10 注册真实 sink 前的既定语义)。
|
||||
"""
|
||||
handler = _SINKS.get(kind)
|
||||
if handler is None:
|
||||
raise AppError(
|
||||
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
|
||||
message=f'No callback sink registered for kind: {kind}',
|
||||
http_status=404,
|
||||
)
|
||||
return handler(**payload)
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
services/shipping_notice/credential_crypto.py
|
||||
services/freight_rpa/common/credential_crypto.py
|
||||
|
||||
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
||||
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
services/freight_rpa/common/rpa_runtime.py
|
||||
|
||||
用途:RPA 运行模式(browser/mock)的展示助手——把任务回调记录或后端配置规范化为前端安全摘要。
|
||||
依赖:Flask current_app 配置(FREIGHT_RPA_WORKER_MOCK);不依赖目录 IO 与 Worker 文件契约。
|
||||
逻辑:由 shipping_notice.query_service(任务序列化注入 rpa_runtime 摘要)、
|
||||
同包 worker_heartbeat(mock 模式下跳过真实 Worker 在线探测)消费;
|
||||
仅做展示归一,不承载触发/回调逻辑。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def _runtime_summary(mode: str) -> dict[str, str | bool]:
|
||||
"""将 browser/mock 规范化为前端安全展示摘要。"""
|
||||
normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser"
|
||||
mock_enabled = normalized == "mock"
|
||||
return {
|
||||
"mode": normalized,
|
||||
"label": "Mock RPA" if mock_enabled else "真实 RPA",
|
||||
"mock": mock_enabled,
|
||||
}
|
||||
|
||||
|
||||
def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]:
|
||||
"""返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。"""
|
||||
if isinstance(runtime, dict):
|
||||
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
|
||||
if mode in {"browser", "mock"}:
|
||||
return _runtime_summary(mode)
|
||||
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower()
|
||||
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
|
||||
+57
-47
@@ -1,11 +1,13 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_worker_heartbeat.py
|
||||
services/freight_rpa/common/worker_heartbeat.py
|
||||
|
||||
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
|
||||
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)、
|
||||
shipping_notice.receipt_rpa(收料 trigger 目录)。
|
||||
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload/receipt trigger 前强制就绪检查;
|
||||
管理端 /rpa-workers/status?scope=inventory|receipt 展示对应 Worker 心跳徽标。
|
||||
依赖:Flask current_app、redis_client、同包 rpa_runtime(mock 模式)、
|
||||
freight_rpa.onhand.trigger_io(onhand trigger 目录)、
|
||||
freight_rpa.upload.trigger_io(上传目录)、
|
||||
freight_rpa.inbound.trigger_io(inbound trigger 目录)。
|
||||
逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound trigger 前强制就绪检查;
|
||||
管理端 /rpa-workers/status?scope=onhand|inbound 展示对应 Worker 心跳徽标。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,18 +26,22 @@ from flask import current_app
|
||||
|
||||
from app.core.config.settings import _normalize_env_name
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.rpa import inventory_trigger_dir, rpa_runtime_mode
|
||||
from app.services.freight_rpa.onhand.trigger_io import onhand_trigger_dir
|
||||
from .rpa_runtime import rpa_runtime_mode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
|
||||
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
|
||||
INVENTORY_EXPORT_CAPABILITY = "inventory_export"
|
||||
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换——
|
||||
# inventory_export→onhand_export、receipt_export→inbound_export(freight_upload 不变);
|
||||
# worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。
|
||||
ONHAND_EXPORT_CAPABILITY = "onhand_export"
|
||||
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
|
||||
RECEIPT_EXPORT_CAPABILITY = "receipt_export"
|
||||
# 收料 Worker 由 start_receipt_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-receipt。
|
||||
RECEIPT_WORKER_ID_SUFFIX = "-receipt"
|
||||
INBOUND_EXPORT_CAPABILITY = "inbound_export"
|
||||
# inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。
|
||||
INBOUND_WORKER_ID_SUFFIX = "-inbound"
|
||||
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
|
||||
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
|
||||
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
|
||||
@@ -51,7 +57,8 @@ _REASON_USER_HINTS: dict[str, str] = {
|
||||
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
|
||||
"trigger_dir_not_writable": "trigger 目录不可写",
|
||||
"environment_mismatch": "Worker 环境与后端环境不一致",
|
||||
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
|
||||
"missing_onhand_export_capability": "Worker 未声明 onhand_export 能力",
|
||||
"missing_inbound_export_capability": "Worker 未声明 inbound_export 能力",
|
||||
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力",
|
||||
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
|
||||
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
|
||||
@@ -139,7 +146,7 @@ def shared_scope_id() -> str:
|
||||
explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "")
|
||||
if explicit:
|
||||
return explicit
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
trigger_dir = onhand_trigger_dir()
|
||||
if not trigger_dir:
|
||||
return ""
|
||||
for part in Path(trigger_dir).parts:
|
||||
@@ -402,16 +409,16 @@ def _verify_shared_trigger_mount(
|
||||
|
||||
def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool:
|
||||
"""
|
||||
判断心跳是否来自收料 Worker。
|
||||
判断心跳是否来自 inbound(原收料)Worker。
|
||||
|
||||
优先认 <主机名>-receipt(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
|
||||
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与收料目录对齐判定。
|
||||
优先认 <主机名>-inbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
|
||||
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与 inbound 目录对齐判定。
|
||||
"""
|
||||
if str(worker.get("worker_id") or "").strip().lower().endswith(RECEIPT_WORKER_ID_SUFFIX):
|
||||
if str(worker.get("worker_id") or "").strip().lower().endswith(INBOUND_WORKER_ID_SUFFIX):
|
||||
return True
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
|
||||
|
||||
expected = receipt_trigger_dir()
|
||||
expected = inbound_trigger_dir()
|
||||
actual = str(worker.get("trigger_dir") or "").strip()
|
||||
if expected is None or not actual:
|
||||
return False
|
||||
@@ -437,7 +444,7 @@ def _worker_is_eligible(
|
||||
backend_env: str,
|
||||
ttl_seconds: int,
|
||||
now: float,
|
||||
required_capability: str = INVENTORY_EXPORT_CAPABILITY,
|
||||
required_capability: str = ONHAND_EXPORT_CAPABILITY,
|
||||
) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。
|
||||
@@ -447,7 +454,7 @@ def _worker_is_eligible(
|
||||
backend_env: 后端归一环境(dev/test/prod)。
|
||||
ttl_seconds: 心跳 TTL。
|
||||
now: 当前 epoch 秒。
|
||||
required_capability: 必选能力(inventory_export / freight_upload)。
|
||||
required_capability: 必选能力(onhand_export / inbound_export / freight_upload)。
|
||||
|
||||
Returns:
|
||||
(是否合格, 不合格原因列表)。
|
||||
@@ -461,10 +468,7 @@ def _worker_is_eligible(
|
||||
|
||||
capabilities = _parse_capabilities(worker.get("capabilities"))
|
||||
if required_capability and required_capability not in capabilities:
|
||||
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
|
||||
reasons.append("missing_freight_upload_capability")
|
||||
else:
|
||||
reasons.append("missing_inventory_export_capability")
|
||||
reasons.append(_missing_capability_reason(required_capability))
|
||||
|
||||
worker_env = str(worker.get("environment") or "").strip().lower()
|
||||
if worker_env and worker_env != backend_env:
|
||||
@@ -477,6 +481,11 @@ def _worker_is_eligible(
|
||||
return not reasons, reasons
|
||||
|
||||
|
||||
def _missing_capability_reason(required_capability: str) -> str:
|
||||
"""按必选能力生成缺失原因码(onhand_export / inbound_export / freight_upload)。"""
|
||||
return f"missing_{required_capability}_capability"
|
||||
|
||||
|
||||
def _summarize_reasons(reasons: list[str]) -> str:
|
||||
hints: list[str] = []
|
||||
for reason in reasons:
|
||||
@@ -623,8 +632,8 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
|
||||
"""
|
||||
return _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir=inventory_trigger_dir(),
|
||||
required_capability=INVENTORY_EXPORT_CAPABILITY,
|
||||
trigger_dir=onhand_trigger_dir(),
|
||||
required_capability=ONHAND_EXPORT_CAPABILITY,
|
||||
)
|
||||
|
||||
|
||||
@@ -632,14 +641,14 @@ def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
"""
|
||||
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
|
||||
|
||||
核心逻辑:仅看收料 Worker 心跳(*-receipt 或 trigger_dir 对齐);要求
|
||||
receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。
|
||||
核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求
|
||||
inbound_export 能力;校验 inbound trigger 目录可写;与 onhand 同口径要求共享哨兵。
|
||||
"""
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
|
||||
|
||||
return _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir=receipt_trigger_dir(),
|
||||
required_capability=RECEIPT_EXPORT_CAPABILITY,
|
||||
trigger_dir=inbound_trigger_dir(),
|
||||
required_capability=INBOUND_EXPORT_CAPABILITY,
|
||||
worker_predicate=is_receipt_rpa_worker,
|
||||
require_sentinel=True,
|
||||
)
|
||||
@@ -655,7 +664,7 @@ def assert_receipt_rpa_worker_ready() -> None:
|
||||
Raises:
|
||||
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
|
||||
"""
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
|
||||
|
||||
result = check_receipt_rpa_worker_ready()
|
||||
if result.ready:
|
||||
@@ -677,7 +686,7 @@ def assert_receipt_rpa_worker_ready() -> None:
|
||||
'detail_message': result.detail_message,
|
||||
'checked_at': result.checked_at,
|
||||
'shared_scope_id': shared_scope_id(),
|
||||
'trigger_dir': str(receipt_trigger_dir() or ''),
|
||||
'trigger_dir': str(inbound_trigger_dir() or ''),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -689,7 +698,7 @@ def _freight_upload_config_reasons() -> list[str]:
|
||||
Returns:
|
||||
不合规原因码列表(空表示静态配置通过)。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa import upload_queue_dir, upload_trigger_dir
|
||||
from app.services.freight_rpa.upload.trigger_io import upload_queue_dir, upload_trigger_dir
|
||||
|
||||
reasons: list[str] = []
|
||||
credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "")
|
||||
@@ -727,7 +736,7 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
|
||||
Returns:
|
||||
RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa import upload_trigger_dir
|
||||
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
|
||||
|
||||
return _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir=upload_trigger_dir(),
|
||||
@@ -757,7 +766,7 @@ def assert_freight_upload_rpa_ready() -> None:
|
||||
result.reasons,
|
||||
result.detail_message,
|
||||
)
|
||||
from app.services.shipping_notice.rpa import upload_trigger_dir
|
||||
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
|
||||
|
||||
raise ServiceUnavailableError(
|
||||
result.message,
|
||||
@@ -836,29 +845,30 @@ def assert_inventory_rpa_worker_ready() -> None:
|
||||
"detail_message": result.detail_message,
|
||||
"checked_at": result.checked_at,
|
||||
"shared_scope_id": shared_scope_id(),
|
||||
"trigger_dir": str(inventory_trigger_dir() or ""),
|
||||
"trigger_dir": str(onhand_trigger_dir() or ""),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]:
|
||||
def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]:
|
||||
"""
|
||||
管理端展示:按 scope 返回库存或收料 Worker 心跳摘要。
|
||||
管理端展示:按 scope 返回在手(onhand)或入站(inbound)Worker 心跳摘要。
|
||||
|
||||
Args:
|
||||
scope: inventory(默认)或 receipt。
|
||||
scope: onhand(默认,库存 RPA 工作台)或 inbound(入站 RPA 工作台);
|
||||
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识(Task 12)无关。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa import upload_trigger_dir
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
|
||||
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
|
||||
|
||||
normalized = str(scope or "inventory").strip().lower()
|
||||
if normalized == "receipt":
|
||||
normalized = str(scope or "onhand").strip().lower()
|
||||
if normalized == "inbound":
|
||||
readiness = check_receipt_rpa_worker_ready()
|
||||
trigger_path = str(receipt_trigger_dir() or "")
|
||||
trigger_path = str(inbound_trigger_dir() or "")
|
||||
else:
|
||||
readiness = check_inventory_rpa_worker_ready()
|
||||
trigger_path = str(inventory_trigger_dir() or "")
|
||||
normalized = "inventory"
|
||||
trigger_path = str(onhand_trigger_dir() or "")
|
||||
normalized = "onhand"
|
||||
|
||||
freight_readiness = check_freight_upload_rpa_ready()
|
||||
ttl_seconds = _heartbeat_ttl_seconds()
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_worker_heartbeat_alert.py
|
||||
services/freight_rpa/common/worker_heartbeat_alert.py
|
||||
|
||||
用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
|
||||
依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
|
||||
依赖:同包 worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
|
||||
逻辑:由 schedule worker 每轮循环调用;默认 ALERT_ENABLED=false 不发送;DB 为告警状态权威源,Redis 仅作缓存同步。
|
||||
"""
|
||||
|
||||
@@ -21,7 +21,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
from app import db
|
||||
from app.models import AppSetting, User
|
||||
from app.services.permission_roles.service import list_platform_admin_users
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from .worker_heartbeat import (
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
_heartbeat_check_required,
|
||||
@@ -0,0 +1 @@
|
||||
"""inbound:入站 RPA。"""
|
||||
@@ -0,0 +1,275 @@
|
||||
"""
|
||||
services/freight_rpa/inbound/report_archive.py
|
||||
|
||||
用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
|
||||
三年保留期、不写库存快照表)、到期对象清理(retention)、单文件企微投递与管理员
|
||||
强制重发(resend)。批次 R Task 10 自 shipping_notice.receipt_report_storage /
|
||||
schedule.freight_inbound_rpa_retention / shipping_notice.receipt_report_notification
|
||||
平移而来(函数名 receipt 词根→inbound;模型 ShippingReceiptReport* 引用不变——批次 S 才改表)。
|
||||
依赖:models(ShippingReceiptReportFile / ShippingReceiptRpaUnitRun / ShippingReceiptNotificationDelivery /
|
||||
User / ScheduleRun 相关模型经行对象访问)、file_assets.storage、integrations.wecom.notify、
|
||||
freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
|
||||
shipping_notice.audit_service(适应度测试白名单内,本模块唯一 shipping_notice 业务依赖,
|
||||
见 tests/services/freight_rpa/test_import_boundary.py)。
|
||||
逻辑:Worker 回调进入 /api/freight-rpa/inbound-batch-ready 后由组合根注册的业务 sink
|
||||
(shipping_notice.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
|
||||
empty/success/failed 三个终态分支各自 commit;终态落库后的业务桥(推进在途调拨来源任务、
|
||||
调拨证据同步)与排程终态归集(finalize)经 on_terminal 钩子回调 shipping_notice 侧实现,
|
||||
本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa,
|
||||
与拆分前「归档 commit 后立刻推桥」的调用顺序逐点一致。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingReceiptNotificationDelivery,
|
||||
ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
User,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir
|
||||
from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
# 终态落库后的业务收尾钩子:由 shipping_notice 域注入(推进在途调拨来源任务 + 调拨证据同步
|
||||
# + 排程终态归集),契约 = 原 storage.ingest_receipt_callback 中「commit 之后的桥/finalize 尾巴」。
|
||||
InboundTerminalHook = Callable[..., None]
|
||||
|
||||
|
||||
def _read_inbound_callback_file(file_path: str) -> bytes:
|
||||
"""只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
|
||||
|
||||
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
|
||||
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...),
|
||||
Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史
|
||||
载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。
|
||||
"""
|
||||
configured_root = str(inbound_drop_dir() or '').strip()
|
||||
if not configured_root:
|
||||
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||
root = Path(configured_root).resolve()
|
||||
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
|
||||
name = Path(str(file_path).replace('\\', '/')).name
|
||||
path = (root / name).resolve()
|
||||
try:
|
||||
path.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise ValidationError('receipt callback file is outside receipt drop root', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') from exc
|
||||
if path.suffix.lower() != '.xlsx' or not path.is_file():
|
||||
raise ValidationError('receipt callback file must be an existing xlsx', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||
max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024
|
||||
if path.stat().st_size > max_size:
|
||||
raise ValidationError('receipt callback file exceeds configured size limit', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||
return path.read_bytes()
|
||||
|
||||
|
||||
def ingest_inbound_callback(payload: dict[str, Any], *, on_terminal: InboundTerminalHook) -> dict[str, Any]:
|
||||
"""幂等接收单个 inbound 单元回调,原样归档三年且不写库存快照表。
|
||||
|
||||
Args:
|
||||
payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。
|
||||
on_terminal: 必填业务收尾钩子(shipping_notice 域注入,见模块 docstring);在每个终态
|
||||
分支 commit 之后、以与拆分前完全一致的实参被调用——
|
||||
empty/failed: on_terminal(unit, ok=False, error_code=..., error_message=...);
|
||||
success: on_terminal(unit, ok=True, file_no=..., file_sha256=...)。
|
||||
业务约束:钩子内部异常只记日志,绝不回滚归档终态(契约由实现方保持)。
|
||||
"""
|
||||
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
|
||||
raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID')
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
|
||||
if unit is None:
|
||||
raise NotFoundError('Receipt RPA unit not found', code='SHIPPING.RECEIPT_UNIT_NOT_FOUND')
|
||||
status = str(payload.get('status') or '').strip().lower()
|
||||
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
|
||||
if status in {'empty', 'no_data'}:
|
||||
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。
|
||||
unit.status = 'empty'
|
||||
unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64]
|
||||
unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000]
|
||||
unit.finished_at = datetime.utcnow()
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
|
||||
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success',
|
||||
before=before,
|
||||
after={
|
||||
'status': 'empty',
|
||||
'callback_id': unit.callback_id,
|
||||
'error_code': unit.error_code,
|
||||
'error_message': unit.error_message,
|
||||
},
|
||||
metadata={'callback_status': status, 'skip_reason': unit.error_code},
|
||||
)
|
||||
db.session.commit()
|
||||
on_terminal(
|
||||
unit, ok=False, error_code=unit.error_code or 'no_receipt_data',
|
||||
error_message=unit.error_message or 'no_receipt_data',
|
||||
)
|
||||
return {'unit_run_id': unit.id, 'status': 'empty'}
|
||||
if status != 'success':
|
||||
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow()
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
|
||||
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='failure',
|
||||
before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message},
|
||||
metadata={'callback_status': status},
|
||||
)
|
||||
db.session.commit()
|
||||
on_terminal(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
|
||||
return {'unit_run_id': unit.id, 'status': 'failed'}
|
||||
data = _read_inbound_callback_file(str(payload.get('file_path') or ''))
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
claimed = str(payload.get('sha256') or '').lower()
|
||||
if claimed and claimed != sha256:
|
||||
raise ValidationError('receipt callback sha256 mismatch', code='SHIPPING.RECEIPT_CALLBACK_SHA_MISMATCH')
|
||||
existing = ShippingReceiptReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
|
||||
if existing:
|
||||
return {'unit_run_id': unit.id, 'status': unit.status, 'file_id': existing.id, 'idempotent': True}
|
||||
filename = Path(str(payload.get('original_filename') or payload.get('file_path') or 'receipt.xlsx')).name
|
||||
storage_key = f'shipping/receipt-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx'
|
||||
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
record = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3))
|
||||
db.session.add(record)
|
||||
unit.status = 'success'; unit.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
|
||||
db.session.commit()
|
||||
on_terminal(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
|
||||
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
|
||||
|
||||
|
||||
def run_freight_inbound_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
|
||||
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。
|
||||
|
||||
Args:
|
||||
task: 排程任务行(job_params.limit 提供单批上限,1..1000)。
|
||||
run: 排程执行记录(本函数不改写 run,仅按排程协议返回计数/明细/日志)。
|
||||
Returns:
|
||||
排程平台 Job 协议七元组(总查得数、成功、失败、跳过 0、明细、错误、step_logs)。
|
||||
"""
|
||||
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
|
||||
now = datetime.utcnow()
|
||||
rows = ShippingReceiptReportFile.query.filter(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_not(None),
|
||||
ShippingReceiptReportFile.archive_expires_at <= now,
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
|
||||
success = failed = 0
|
||||
errors: list[str] = []
|
||||
for report_file in rows:
|
||||
try:
|
||||
file_asset_storage.delete_object(report_file.storage_key)
|
||||
report_file.archive_deleted_at = now
|
||||
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='success',
|
||||
before={'status': 'archived'}, after={'status': 'archive_deleted'},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
success += 1
|
||||
except Exception as exc:
|
||||
errors.append(f'{report_file.id}: {exc}')
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='failure',
|
||||
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
|
||||
|
||||
|
||||
def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]:
|
||||
"""从所属排程冻结的接收人列表取目标用户;停用通知时返回空。"""
|
||||
run = report_file.unit_run.schedule_run
|
||||
task = run.task if run else None
|
||||
if task is None or not task.notify_enabled:
|
||||
return []
|
||||
return sorted({int(user_id) for user_id in (task.notify_user_ids_json or []) if str(user_id).isdigit()})
|
||||
|
||||
|
||||
def deliver_inbound_file(file_id: int, *, force: bool = False) -> dict:
|
||||
"""向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。
|
||||
|
||||
Args:
|
||||
file_id: 已归档收料文件主键(ShippingReceiptReportFile.id)。
|
||||
force: 管理员补偿重发(resend 端点传 True),绕过成功幂等但仍受通知开关约束。
|
||||
Returns:
|
||||
dict: success_count / failed_count(file_not_found 时附 reason)。
|
||||
"""
|
||||
report_file = db.session.get(ShippingReceiptReportFile, file_id)
|
||||
if report_file is None:
|
||||
return {'success_count': 0, 'failed_count': 0, 'reason': 'file_not_found'}
|
||||
success_count = failed_count = 0
|
||||
for user_id in _recipient_ids(report_file):
|
||||
key = f'receipt:file:{report_file.id}:user:{user_id}'
|
||||
delivery = ShippingReceiptNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
|
||||
if delivery and delivery.status == 'success' and not force:
|
||||
success_count += 1
|
||||
continue
|
||||
if delivery is None:
|
||||
delivery = ShippingReceiptNotificationDelivery(
|
||||
unit_run_id=report_file.unit_run_id, report_file_id=report_file.id, recipient_user_id=user_id,
|
||||
message_type='file', idempotency_key=key, status='pending',
|
||||
)
|
||||
db.session.add(delivery)
|
||||
db.session.flush()
|
||||
user = db.session.get(User, user_id)
|
||||
if user is None or not user.wecom_userid:
|
||||
delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding'
|
||||
failed_count += 1
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
|
||||
unit_id=report_file.unit_run_id, result='failure',
|
||||
before={'delivery_status': 'pending'},
|
||||
after={'delivery_status': delivery.status, 'error_code': delivery.error_code},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
|
||||
)
|
||||
continue
|
||||
try:
|
||||
media_id = upload_wecom_temp_media(file_asset_storage.get_bytes(report_file.storage_key), report_file.original_filename)
|
||||
result = send_wecom_file_message(user.wecom_userid, media_id)
|
||||
if int(result.get('errcode', -1)) != 0:
|
||||
raise RuntimeError(str(result.get('errmsg') or result.get('errcode')))
|
||||
delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.error_code = None; delivery.error_message = None
|
||||
delivery.response_summary_json = {'media_uploaded': True, 'errcode': 0}
|
||||
success_count += 1
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', aggregate_id=str(report_file.id),
|
||||
actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='success',
|
||||
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
|
||||
)
|
||||
except Exception as exc:
|
||||
delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]
|
||||
failed_count += 1
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
|
||||
unit_id=report_file.unit_run_id, result='failure',
|
||||
before={'delivery_status': 'pending'},
|
||||
after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
|
||||
)
|
||||
db.session.commit()
|
||||
return {'success_count': success_count, 'failed_count': failed_count}
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
services/freight_rpa/inbound/trigger_io.py
|
||||
|
||||
用途:inbound(入站,原收料)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON
|
||||
原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
|
||||
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
|
||||
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
|
||||
逻辑:由 schedule.freight_inbound_rpa_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
|
||||
in_transit_transfer.inbound_trigger_service(调拨按需/批量触发)、
|
||||
freight_rpa.common.worker_heartbeat(inbound trigger 目录探测/就绪检查)、
|
||||
freight_rpa.inbound.report_archive(drop 目录定位与回调 SCHEMA 校验,Task 10 下沉)等调用,
|
||||
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
|
||||
(Worker 侧 Task 12 对表:freight_rpa.inbound.v1 / inbound_export_batch)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
|
||||
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
|
||||
# (旧 receipt 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
|
||||
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
|
||||
SCHEMA = "freight_rpa.inbound.v1"
|
||||
ACTION_INBOUND_EXPORT_BATCH = "inbound_export_batch"
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def inbound_trigger_dir() -> Path | None:
|
||||
"""RPA inbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR);
|
||||
绝不回落到 onhand trigger 目录。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR")
|
||||
|
||||
|
||||
def inbound_drop_dir() -> Path | None:
|
||||
"""RPA inbound 导出文件落盘目录(FREIGHT_RPA_SHARED_INBOUND_DROP_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INBOUND_DROP_DIR")
|
||||
|
||||
|
||||
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
|
||||
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
|
||||
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
try:
|
||||
with open(temp_path, 'w', encoding='utf-8') as handle:
|
||||
json.dump(body, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, path)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def write_inbound_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""
|
||||
写入 inbound 批量 trigger 文件 inbound_export_batch_{run_no}.json
|
||||
([PROMPT_UPDATE] 2026-10-16 批次 R:文件名前缀随 Worker 侧 Task 12 一起由
|
||||
receipt_export_batch_* 切换为 inbound_export_batch_*;Worker 轮询 <root>/*.json
|
||||
按内容消费,schema/action 取本文件常量新值)。
|
||||
|
||||
Args:
|
||||
run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。
|
||||
units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。
|
||||
payload: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。
|
||||
"""
|
||||
trigger_dir = inbound_trigger_dir()
|
||||
if not trigger_dir or not units:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'inbound'
|
||||
body = {
|
||||
'schema_version': SCHEMA, 'action': ACTION_INBOUND_EXPORT_BATCH,
|
||||
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
|
||||
**(payload or {}),
|
||||
}
|
||||
path = trigger_dir / f'inbound_export_batch_{safe_run_no}.json'
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
@@ -0,0 +1 @@
|
||||
"""onhand:在手库存 RPA。"""
|
||||
+10
-8
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_attempts.py
|
||||
services/freight_rpa/onhand/attempts.py
|
||||
|
||||
用途:统计任务的 RPA 库存导出与货代上传重试次数,并返回统一上限。
|
||||
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑。
|
||||
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,决定是否还能继续触发 RPA 重试。
|
||||
用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。
|
||||
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。
|
||||
逻辑:由 shipping_notice 的 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,
|
||||
决定是否还能继续触发 RPA 重试;事件类型字符串(inventory_rpa_* 等)是落库数据值,
|
||||
随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +17,7 @@ from app.models import ShippingNotice, ShippingTaskEvent
|
||||
|
||||
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
|
||||
|
||||
_INVENTORY_SUCCESS_EVENTS = {
|
||||
_ONHAND_SUCCESS_EVENTS = {
|
||||
"inventory_uploaded",
|
||||
"inventory_parsed",
|
||||
"inventory_rpa_drop_ingested",
|
||||
@@ -23,7 +25,7 @@ _INVENTORY_SUCCESS_EVENTS = {
|
||||
"inventory_template_mapping_used",
|
||||
}
|
||||
|
||||
_INVENTORY_ATTEMPT_RESET_EVENTS = _INVENTORY_SUCCESS_EVENTS | {
|
||||
_ONHAND_ATTEMPT_RESET_EVENTS = _ONHAND_SUCCESS_EVENTS | {
|
||||
"decision_retry_rpa",
|
||||
}
|
||||
|
||||
@@ -33,14 +35,14 @@ _UPLOAD_SUCCESS_EVENTS = {
|
||||
}
|
||||
|
||||
|
||||
def inventory_rpa_attempts(task: ShippingNotice | None) -> int:
|
||||
def onhand_rpa_attempts(task: ShippingNotice | None) -> int:
|
||||
"""统计自上次库存成功事件以来的 RPA 库存导出触发/失败次数。"""
|
||||
if not task or task.id is None:
|
||||
return 0
|
||||
|
||||
last_reset = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||||
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_ATTEMPT_RESET_EVENTS))
|
||||
.filter(ShippingTaskEvent.event_type.in_(_ONHAND_ATTEMPT_RESET_EVENTS))
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
+11
-9
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_rpa_callback_cleanup.py
|
||||
services/freight_rpa/onhand/callback_cleanup.py
|
||||
|
||||
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。
|
||||
依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。
|
||||
逻辑:commit 后尝试归档;失败则移入 .hxops_quarantine 并入队;scheduler/worker 启动时定期消费队列。
|
||||
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记
|
||||
(Task 9 自 shipping_notice.inventory_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
|
||||
依赖:freight_rpa.onhand.trigger_io(onhand_drop_dir / onhand_processed_dir)、json、uuid、Flask current_app。
|
||||
逻辑:commit 后由 shipping_notice 业务 sink 调用尝试归档;失败则移入 .hxops_quarantine 并入队;
|
||||
scheduler/worker 启动时定期消费队列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,7 +20,7 @@ from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir, inventory_processed_dir
|
||||
from app.services.freight_rpa.onhand.trigger_io import onhand_drop_dir, onhand_processed_dir
|
||||
|
||||
_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed"
|
||||
_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
|
||||
@@ -30,7 +32,7 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
def callback_cleanup_queue_dir() -> Path | None:
|
||||
"""drop 目录下 callback 归档重试队列路径。"""
|
||||
drop = inventory_drop_dir()
|
||||
drop = onhand_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _CLEANUP_QUEUE_DIRNAME
|
||||
@@ -38,7 +40,7 @@ def callback_cleanup_queue_dir() -> Path | None:
|
||||
|
||||
def callback_cleanup_failed_dir() -> Path | None:
|
||||
"""超过最大重试次数的 cleanup job 隔离目录。"""
|
||||
drop = inventory_drop_dir()
|
||||
drop = onhand_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _CLEANUP_FAILED_DIRNAME
|
||||
@@ -49,7 +51,7 @@ def callback_quarantine_dir() -> Path | None:
|
||||
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
|
||||
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
|
||||
"""
|
||||
drop = inventory_drop_dir()
|
||||
drop = onhand_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _QUARANTINE_DIRNAME
|
||||
@@ -243,7 +245,7 @@ def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]:
|
||||
callback_raw = str(payload.get("callback_path") or "").strip()
|
||||
processed_raw = str(payload.get("processed_dir") or "").strip()
|
||||
callback_path = Path(callback_raw) if callback_raw else None
|
||||
processed_dir = Path(processed_raw) if processed_raw else inventory_processed_dir()
|
||||
processed_dir = Path(processed_raw) if processed_raw else onhand_processed_dir()
|
||||
if callback_path is None or processed_dir is None:
|
||||
try:
|
||||
job_path.unlink()
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
services/freight_rpa/onhand/trigger_io.py
|
||||
|
||||
用途:onhand(在手库存)RPA 的纯文件 IO——trigger/落盘目录解析、trigger JSON 原子写、
|
||||
单任务导出 trigger 写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
|
||||
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
|
||||
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
|
||||
逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、inventory_rpa_workflow(回调 schema 校验)、
|
||||
per_source_rpa_service(回调 schema 校验)、freight_rpa.common.worker_heartbeat(目录探测)等调用,
|
||||
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
|
||||
(Worker 侧 Task 12 对表:freight_rpa.onhand.v1 / onhand_export / onhand_export_batch)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
|
||||
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
|
||||
# (旧 inventory 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
|
||||
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
|
||||
SCHEMA = "freight_rpa.onhand.v1"
|
||||
ACTION_ONHAND_EXPORT = "onhand_export"
|
||||
ACTION_ONHAND_EXPORT_BATCH = "onhand_export_batch"
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def onhand_drop_dir() -> Path | None:
|
||||
"""RPA onhand 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_ONHAND_DROP_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_ONHAND_DROP_DIR")
|
||||
|
||||
|
||||
def onhand_processed_dir() -> Path | None:
|
||||
"""已处理 onhand 文件归档子目录(drop_dir/processed)。"""
|
||||
base = onhand_drop_dir()
|
||||
if not base:
|
||||
return None
|
||||
return base / "processed"
|
||||
|
||||
|
||||
def onhand_trigger_dir() -> Path | None:
|
||||
"""RPA onhand 导出触发 JSON 目录(FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR")
|
||||
|
||||
|
||||
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
|
||||
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
|
||||
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
try:
|
||||
with open(temp_path, 'w', encoding='utf-8') as handle:
|
||||
json.dump(body, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, path)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def write_onhand_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""
|
||||
写入 RPA onhand 导出触发文件 inventory_export_{task_no}.json
|
||||
(文件名沿用既有 Worker 契约,仅 action 取新值 ACTION_ONHAND_EXPORT)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径;目录未配置时返回 None。
|
||||
"""
|
||||
trigger_dir = onhand_trigger_dir()
|
||||
if not trigger_dir:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
body = {
|
||||
"action": ACTION_ONHAND_EXPORT,
|
||||
"task_no": task_no,
|
||||
"run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}",
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
path = trigger_dir / f"inventory_export_{task_no}.json"
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
|
||||
|
||||
# TODO(批次S): 全仓零调用,死代码候选,收敛时删除
|
||||
def find_latest_inventory_file() -> Path | None:
|
||||
"""在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。"""
|
||||
drop = onhand_drop_dir()
|
||||
if not drop or not drop.is_dir():
|
||||
return None
|
||||
candidates = [
|
||||
p for p in drop.iterdir()
|
||||
if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"}
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
return max(candidates, key=lambda p: p.stat().st_mtime)
|
||||
@@ -0,0 +1,336 @@
|
||||
"""
|
||||
services/freight_rpa/onhand/workflow_protocol.py
|
||||
|
||||
用途:onhand(在手库存)RPA 回调协议态——attempt 行记账、run_no 幂等键、轮次校验、
|
||||
排程进度记账与超时窗口判定的纯协议层。
|
||||
依赖:app.models(ShippingTaskEvent / ShippingTaskInventoryRpaAttempt / ScheduleRun)、
|
||||
app.extensions.db、freight_rpa.onhand 包内模块;**禁止 import 任何
|
||||
shipping_notice 业务模块**(import 边界由 tests/services/freight_rpa/test_import_boundary.py
|
||||
AST 全包扫描锁死,含函数内延迟 import)。
|
||||
逻辑:Task 9 拆分自 shipping_notice.inventory_rpa_workflow——回调进入
|
||||
/api/freight-rpa/* 蓝图后,业务 sink(shipping_notice.rpa_sinks 注册)在原事务内
|
||||
调用本模块完成协议记账(不改变 commit 时机),再由域内业务函数做快照落盘/
|
||||
门禁推进/审计投影;快照、Gate、状态机等业务终态一律留在 shipping_notice。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ScheduleRun, ShippingTaskEvent, ShippingTaskInventoryRpaAttempt
|
||||
|
||||
|
||||
def latest_task_event(task: Any, event_type: str) -> ShippingTaskEvent | None:
|
||||
"""返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试/轮次校验用)。"""
|
||||
if task.id is None:
|
||||
return None
|
||||
return (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def extract_run_no_from_trigger(trigger_path: str | None) -> str:
|
||||
"""从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 单票均支持)。"""
|
||||
path = Path(str(trigger_path or ""))
|
||||
name = path.name
|
||||
prefix = "inventory_export_batch_"
|
||||
if name.startswith(prefix) and name.endswith(".json"):
|
||||
return name[len(prefix) : -len(".json")]
|
||||
if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file():
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(payload, dict):
|
||||
run_no = str(payload.get("run_no") or "").strip()
|
||||
if run_no:
|
||||
return run_no
|
||||
except (OSError, json.JSONDecodeError, TypeError, ValueError):
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def is_legacy_trigger_run_no(run_no: str) -> bool:
|
||||
"""判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传 run_no)。"""
|
||||
return str(run_no or "").strip().upper().startswith("LEGACY-")
|
||||
|
||||
|
||||
def expected_rpa_callback_run_no(task: Any) -> str:
|
||||
"""读取任务最近一次 RPA 触发记录的 run_no(事件 detail 优先,缺失回退 trigger 文件)。"""
|
||||
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
|
||||
if not last_trigger:
|
||||
return ""
|
||||
detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {}
|
||||
run_no = str(detail.get("run_no") or "").strip()
|
||||
if run_no:
|
||||
return run_no
|
||||
return extract_run_no_from_trigger(str(detail.get("trigger") or ""))
|
||||
|
||||
|
||||
def validate_rpa_callback_run_no(task: Any, callback_run_no: str) -> str | None:
|
||||
"""校验回调 run_no 属于当前任务最近一次有效触发轮次。
|
||||
|
||||
Returns:
|
||||
None 校验通过;否则返回拒绝原因码(no_active_trigger / run_no_missing / run_no_mismatch)。
|
||||
"""
|
||||
provided = str(callback_run_no or "").strip()
|
||||
expected = expected_rpa_callback_run_no(task)
|
||||
if not expected:
|
||||
return "no_active_trigger"
|
||||
if not provided:
|
||||
if is_legacy_trigger_run_no(expected):
|
||||
return None
|
||||
return "run_no_missing"
|
||||
if provided != expected:
|
||||
return "run_no_mismatch"
|
||||
return None
|
||||
|
||||
|
||||
def resolve_effective_callback_run_no(task: Any, payload: dict[str, Any]) -> str:
|
||||
"""解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。"""
|
||||
provided = str(payload.get("run_no") or "").strip()
|
||||
if provided:
|
||||
return provided
|
||||
return expected_rpa_callback_run_no(task)
|
||||
|
||||
|
||||
def get_consumed_inventory_rpa_run_no(task: Any) -> str:
|
||||
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
|
||||
attempt = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter_by(task_no=str(task.task_no or ''), status='consumed')
|
||||
.order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
|
||||
.first()
|
||||
)
|
||||
return str(getattr(attempt, 'source_run_no', '') or '').strip()
|
||||
|
||||
|
||||
def mark_inventory_rpa_run_no_consumed(task: Any, run_no: str) -> None:
|
||||
"""[协议记账] 标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。
|
||||
|
||||
核心逻辑:只改 Attempt 行(status/consumed_at),不 commit——commit 时机由调用方
|
||||
业务事务决定,与拆分前行为一致。
|
||||
"""
|
||||
effective = str(run_no or "").strip()
|
||||
if not effective:
|
||||
return
|
||||
attempt = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter_by(task_no=str(task.task_no or ''), source_run_no=effective)
|
||||
.one_or_none()
|
||||
)
|
||||
if attempt is not None:
|
||||
attempt.status = 'consumed'
|
||||
attempt.consumed_at = datetime.utcnow()
|
||||
|
||||
|
||||
def validate_rpa_callback_not_replayed(task: Any, run_no: str) -> str | None:
|
||||
"""拒绝同一 run_no 的重复成功/失败/跳过回调。
|
||||
|
||||
Returns:
|
||||
None 允许处理;"run_no_already_consumed" 表示重放,应拒绝。
|
||||
"""
|
||||
effective = str(run_no or "").strip()
|
||||
consumed = get_consumed_inventory_rpa_run_no(task)
|
||||
if effective and consumed and effective == consumed:
|
||||
return "run_no_already_consumed"
|
||||
return None
|
||||
|
||||
|
||||
def validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callback_run_no: str) -> str | None:
|
||||
"""校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。
|
||||
|
||||
Returns:
|
||||
None 校验通过;否则返回拒绝原因码(schedule_run_not_found / schedule_run_no_missing /
|
||||
schedule_run_no_mismatch / schedule_run_not_awaiting)。
|
||||
"""
|
||||
if schedule_run_id is None:
|
||||
return None
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
if not run:
|
||||
return "schedule_run_not_found"
|
||||
expected = str(run.run_no or "").strip()
|
||||
provided = str(callback_run_no or "").strip()
|
||||
if not expected:
|
||||
return "schedule_run_no_missing"
|
||||
if provided != expected:
|
||||
return "schedule_run_no_mismatch"
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if run.status != "running" or not summary.get("awaiting_rpa"):
|
||||
return "schedule_run_not_awaiting"
|
||||
return None
|
||||
|
||||
|
||||
def record_onhand_batch_progress(
|
||||
run: ScheduleRun,
|
||||
run_no: str,
|
||||
*,
|
||||
success_count: int,
|
||||
skipped_count: int,
|
||||
failed_count: int,
|
||||
) -> dict[str, Any]:
|
||||
"""[协议记账] 排程批量导出进度回写:max(现有, 上报) 防乱序回退,写后即 commit。
|
||||
|
||||
【AI 触发时机】:onhand-batch-progress 业务 sink 已完成 schema/run 校验后调用;
|
||||
非终态记账(不修改 status/started_at/finished_at,终态仍以 batch-ready 为准)。
|
||||
|
||||
Args:
|
||||
run: 已确认存在且处于 awaiting_rpa 的 ScheduleRun 行。
|
||||
run_no: 批次 run_no,写入 response_summary_json.progress 供审计。
|
||||
success_count / skipped_count / failed_count: 已按 max(0, int(x)) 归一的非负计数。
|
||||
|
||||
Returns:
|
||||
dict: 提交后的最终计数 {'success_count','skipped_count','failed_count','run_no'};
|
||||
供业务层拼装响应,键值与拆分前响应逐字一致。
|
||||
"""
|
||||
run.success_count = max(int(run.success_count or 0), success_count)
|
||||
run.skipped_count = max(int(run.skipped_count or 0), skipped_count)
|
||||
run.failed_count = max(int(run.failed_count or 0), failed_count)
|
||||
summary = dict(run.response_summary_json or {})
|
||||
summary['progress'] = {
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
'batch_run_no': run_no,
|
||||
'updated_at': datetime.utcnow().isoformat(),
|
||||
}
|
||||
run.response_summary_json = summary
|
||||
# commit 时机与拆分前 inventory_rpa_workflow.report_inventory_batch_progress 完全一致:
|
||||
# 校验通过、计数写完后立即提交,再由业务层构造响应。
|
||||
db.session.commit()
|
||||
return {
|
||||
'run_no': run_no,
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
}
|
||||
|
||||
|
||||
def compute_rpa_wait_window(
|
||||
triggered_at: datetime,
|
||||
timeout_seconds: int,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> tuple[int, int, int]:
|
||||
"""计算库存 RPA 等待窗口(elapsed / timeout / remaining 秒)。
|
||||
|
||||
【AI 触发时机】:业务层已确认任务处于 RPA 等待态、需要判断是否超时或调度复查时调用。
|
||||
|
||||
Args:
|
||||
triggered_at: 最近一次 inventory_rpa_triggered 事件的 created_at。
|
||||
timeout_seconds: 超时阈值秒数(由业务层 tool_common 读取配置)。
|
||||
now: 可注入当前时间(测试用);缺省 utcnow。
|
||||
|
||||
Returns:
|
||||
tuple[int, int, int]: (elapsed_seconds, timeout_seconds, remaining_seconds);
|
||||
elapsed 向下取整且不为负,remaining 不为负。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
elapsed = max(int((current - triggered_at).total_seconds()), 0)
|
||||
remaining = max(int(timeout_seconds) - elapsed, 0)
|
||||
return elapsed, int(timeout_seconds), remaining
|
||||
|
||||
|
||||
def resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None:
|
||||
"""将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。
|
||||
|
||||
Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``,
|
||||
Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。
|
||||
安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。
|
||||
|
||||
Returns:
|
||||
Path | None: 解析成功且确为 allowed_root 下存在文件时返回绝对路径;否则 None。
|
||||
"""
|
||||
text = str(raw_path or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
root = allowed_root.resolve()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
candidate = Path(text)
|
||||
try:
|
||||
resolved = candidate.resolve()
|
||||
if resolved.is_file():
|
||||
resolved.relative_to(root)
|
||||
return resolved
|
||||
except (OSError, ValueError, RuntimeError):
|
||||
pass
|
||||
|
||||
name = Path(text.replace('\\', '/')).name.strip()
|
||||
if not name or name in {'.', '..'} or '/' in name or '\\' in name:
|
||||
return None
|
||||
mapped = (root / name).resolve()
|
||||
try:
|
||||
mapped.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
if mapped.is_file():
|
||||
return mapped
|
||||
return None
|
||||
|
||||
|
||||
def normalize_inventory_result_status(payload: dict[str, Any]) -> str:
|
||||
"""归一化单任务 RPA 库存回调结果。
|
||||
|
||||
核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段;
|
||||
缺省 success 视为 true(历史单任务回调兼容)。
|
||||
|
||||
Returns:
|
||||
str: success | skipped | failed
|
||||
"""
|
||||
raw_status = str(payload.get("status") or "").strip().lower()
|
||||
if raw_status in {"success", "skipped", "failed"}:
|
||||
return raw_status
|
||||
if payload.get("skipped"):
|
||||
return "skipped"
|
||||
if bool(payload.get("success", True)):
|
||||
return "success"
|
||||
return "failed"
|
||||
|
||||
|
||||
def normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
|
||||
"""归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。
|
||||
|
||||
核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或
|
||||
缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。
|
||||
|
||||
Returns:
|
||||
str: success | skipped | failed
|
||||
"""
|
||||
raw_status = str(item.get("status") or "").strip().lower()
|
||||
if raw_status in {"success", "skipped", "failed"}:
|
||||
return raw_status
|
||||
if item.get("skipped"):
|
||||
return "skipped"
|
||||
if item.get("success") is True:
|
||||
return "success"
|
||||
return "failed"
|
||||
|
||||
|
||||
def merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""合并 batch 顶层契约字段到 result item。
|
||||
|
||||
核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由
|
||||
Worker item 显式返回,禁止后端从任务或数据库补齐。
|
||||
|
||||
Returns:
|
||||
dict: 合并后的 item 副本(不修改入参)。
|
||||
"""
|
||||
merged = dict(item)
|
||||
top_schema_version = str(payload.get('schema_version') or '').strip()
|
||||
if top_schema_version and not str(merged.get('schema_version') or '').strip():
|
||||
merged['schema_version'] = top_schema_version
|
||||
top_run_no = str(payload.get("run_no") or "").strip()
|
||||
if top_run_no and not str(merged.get("run_no") or "").strip():
|
||||
merged["run_no"] = top_run_no
|
||||
|
||||
task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip()
|
||||
if task_no and not str(merged.get("task_no") or "").strip():
|
||||
merged["task_no"] = task_no
|
||||
return merged
|
||||
@@ -0,0 +1 @@
|
||||
"""upload:货代上传 RPA。"""
|
||||
@@ -0,0 +1,144 @@
|
||||
"""
|
||||
services/freight_rpa/upload/trigger_io.py
|
||||
|
||||
用途:upload(货代上传)RPA 的纯文件 IO——上传队列/trigger 目录解析、Excel 复制入队、
|
||||
上传 trigger JSON 原子写入(含凭据信封固化)。
|
||||
依赖:Flask current_app 配置、Path/shutil/uuid/JSON/文件系统工具;不 import 任何业务编排模块
|
||||
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
|
||||
逻辑:由 shipping_notice.fulfillment_workflow(upload_to_freight 触发上传)、
|
||||
freight_rpa.common.worker_heartbeat(上传目录就绪探测)调用,
|
||||
与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相
|
||||
([PROMPT_UPDATE] 2026-10-16 批次 R 新裁定:upload 契约随发布窗口一次切换——
|
||||
action 由 shipment_upload 改为 outbound_upload、schema 由 shipping_notice_upload_rpa.v1
|
||||
改为 freight_rpa.upload.v1,Worker 侧 Task 12 同窗口对齐,旧串全仓清零)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
# Worker 触发契约常量:后端写入侧单一真相,禁止再写字面量(Worker 侧常量见
|
||||
# scripts/freight_rpa/common/rpa_callbacks.py 邻域的 inbound/onhand 对齐方式)。
|
||||
SCHEMA = "freight_rpa.upload.v1"
|
||||
ACTION_OUTBOUND_UPLOAD = "outbound_upload"
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
|
||||
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
|
||||
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
try:
|
||||
with open(temp_path, 'w', encoding='utf-8') as handle:
|
||||
json.dump(body, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, path)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def upload_queue_dir() -> Path | None:
|
||||
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR")
|
||||
|
||||
|
||||
def upload_trigger_dir() -> Path | None:
|
||||
"""RPA 货代上传触发 JSON 目录。"""
|
||||
return _path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR")
|
||||
|
||||
|
||||
def write_upload_trigger(
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
payload: dict[str, Any] | None = None,
|
||||
*,
|
||||
attempt_id: int | None = None,
|
||||
artifact_id: int | None = None,
|
||||
connector_type: str | None = None,
|
||||
upload_config: dict[str, Any] | None = None,
|
||||
upload_config_hash: str | None = None,
|
||||
login_url: str | None = None,
|
||||
credential_envelope: dict[str, Any] | None = None,
|
||||
callback_id: str | None = None,
|
||||
business_no: str | None = None,
|
||||
) -> tuple[str | None, str | None, str | None]:
|
||||
"""
|
||||
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
|
||||
【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。
|
||||
|
||||
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
|
||||
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
|
||||
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
|
||||
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
|
||||
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
export_file_path: 待上传发货 Excel 的服务端路径。
|
||||
payload: 附加字段(如 mode),与下列具名参数合并。
|
||||
attempt_id: 本次 Upload Attempt 主键。
|
||||
artifact_id: 当前上传目标 Artifact 主键。
|
||||
connector_type: 业务连接类型(dbs / crane)。
|
||||
upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。
|
||||
upload_config_hash: 该快照的 sha256,用于审计关联。
|
||||
login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。
|
||||
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
|
||||
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
|
||||
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
|
||||
|
||||
Returns:
|
||||
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
|
||||
失败时 (None, None, None)。
|
||||
"""
|
||||
queue = upload_queue_dir()
|
||||
trigger_dir = upload_trigger_dir()
|
||||
if not queue or not trigger_dir:
|
||||
return None, None, None
|
||||
queue.mkdir(parents=True, exist_ok=True)
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
src = Path(export_file_path)
|
||||
if not src.is_file():
|
||||
return None, None, None
|
||||
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
|
||||
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
|
||||
emit_no = str(business_no or '').strip() or task_no
|
||||
suffix = str(src.suffix or '.xlsx').lower()
|
||||
dest = queue / f"{emit_no}{suffix}"
|
||||
shutil.copy2(src, dest)
|
||||
|
||||
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
|
||||
body = {
|
||||
"action": ACTION_OUTBOUND_UPLOAD,
|
||||
"schema_version": SCHEMA,
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"artifact_id": artifact_id,
|
||||
"callback_id": resolved_callback_id,
|
||||
"connector_type": str(connector_type or '').strip() or None,
|
||||
"upload_config": upload_config,
|
||||
"upload_config_hash": upload_config_hash,
|
||||
"login_url": login_url,
|
||||
"credential_envelope": credential_envelope,
|
||||
"file_path": str(dest),
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
trigger_path = trigger_dir / f"upload_{task_no}.json"
|
||||
_write_trigger_json_atomic(trigger_path, body)
|
||||
return str(dest), str(trigger_path), resolved_callback_id
|
||||
@@ -69,7 +69,7 @@ def recover_stale_waiting_source_jobs() -> int:
|
||||
from flask import current_app
|
||||
|
||||
try:
|
||||
timeout = max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
|
||||
timeout = max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900)))
|
||||
except (TypeError, ValueError):
|
||||
timeout = 900
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout)
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
复用货代 ShippingReceiptReport trigger 链路,shipping_notice 域术语保留),不创建排程。
|
||||
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
|
||||
先落 RPA 单元运行行(awaiting_rpa,回调按 callback_id 查库可达),
|
||||
再装配入站 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
|
||||
依赖:write_receipt_export_batch_trigger(默认 writer,shipping_notice 域)、models、db。
|
||||
再装配入站 trigger unit 并调用 write_inbound_export_batch_trigger 原子写 trigger。
|
||||
依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、models、db。
|
||||
逻辑:list_inbound_capable_source_codes 供排程 source_codes 留空时的缺省范围;
|
||||
一源一单元,query_parameters 原样下发;来源停用/ShippingReceiptReportConfig 缺失/rpa_profile 缺失时
|
||||
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
|
||||
@@ -19,7 +19,11 @@ import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.freight_rpa.inbound.trigger_io import (
|
||||
ACTION_INBOUND_EXPORT_BATCH,
|
||||
SCHEMA,
|
||||
write_inbound_export_batch_trigger,
|
||||
)
|
||||
|
||||
RouteTriggerWriter = Callable[..., str | None]
|
||||
|
||||
@@ -105,7 +109,7 @@ def trigger_inbound_rpa(
|
||||
source_code: 来源实例编码。
|
||||
business_date: 业务日期。
|
||||
reason: 触发原因(写入 trigger)。
|
||||
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
|
||||
writer: 触发写者;缺省复用 write_inbound_export_batch_trigger。
|
||||
Returns:
|
||||
{"ok": True, "callback_id": ..., "trigger_path": ...} 或
|
||||
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
|
||||
@@ -136,10 +140,10 @@ def trigger_inbound_rpa(
|
||||
|
||||
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
|
||||
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
|
||||
writer_fn = writer or write_receipt_export_batch_trigger
|
||||
writer_fn = writer or write_inbound_export_batch_trigger
|
||||
path = writer_fn(run_no, [unit_payload], payload={
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'action': 'receipt_export_batch',
|
||||
'schema_version': SCHEMA,
|
||||
'action': ACTION_INBOUND_EXPORT_BATCH,
|
||||
'source_code': source_code,
|
||||
'business_date': business_date,
|
||||
'reason': reason,
|
||||
@@ -171,14 +175,14 @@ def trigger_inbound_rpa_batch(
|
||||
|
||||
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批;
|
||||
parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行
|
||||
RPA 单元运行行再一次性 write_receipt_export_batch_trigger 原子落盘。
|
||||
RPA 单元运行行再一次性 write_inbound_export_batch_trigger 原子落盘。
|
||||
Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
|
||||
business_date: 业务日期。
|
||||
reason: 触发原因(写入 trigger payload)。
|
||||
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
|
||||
writer: 触发写者;缺省复用 write_inbound_export_batch_trigger。
|
||||
|
||||
Returns:
|
||||
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
|
||||
@@ -247,10 +251,10 @@ def trigger_inbound_rpa_batch(
|
||||
|
||||
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
|
||||
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
|
||||
writer_fn = writer or write_receipt_export_batch_trigger
|
||||
writer_fn = writer or write_inbound_export_batch_trigger
|
||||
path = writer_fn(run_no, unit_payloads, payload={
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'action': 'receipt_export_batch',
|
||||
'schema_version': SCHEMA,
|
||||
'action': ACTION_INBOUND_EXPORT_BATCH,
|
||||
'business_date': business_date,
|
||||
'reason': reason,
|
||||
'source_codes': [payload['source_code'] for payload in unit_payloads],
|
||||
|
||||
@@ -343,8 +343,8 @@ def _register_headers_from_config() -> None:
|
||||
for name, cfg in get_all_schedule_sql_configs().items():
|
||||
if cfg.alias_order and cfg.header_labels:
|
||||
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import register_receipt_rpa_excel_headers
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import register_inventory_rpa_excel_headers
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import register_receipt_rpa_excel_headers
|
||||
|
||||
register_inventory_rpa_excel_headers()
|
||||
register_receipt_rpa_excel_headers()
|
||||
|
||||
+7
-7
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/schedule/shipping_receipt_rpa_archive.py
|
||||
backend/app/services/schedule/freight_inbound_rpa_archive.py
|
||||
|
||||
用途:货代收料 RPA 排程 run 的原始收料 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
|
||||
依赖:ScheduleRun、ShippingReceiptReportFile / ShippingReceiptRpaUnitRun、
|
||||
file_asset_storage、timezone_util、freight_receipt_rpa_finalize.is_freight_receipt_rpa_task。
|
||||
file_asset_storage、timezone_util、freight_inbound_rpa_finalize.is_freight_receipt_rpa_task。
|
||||
逻辑:finalize 调用 persist_receipt_rpa_raw_zip_archive 写入磁盘与 summary;
|
||||
企微/下载展示名用「收料RPA-日期-时刻-收料」;包内条目 `{序号}_{source_code}.xlsx`;
|
||||
warehouse_id / file_id 只写在 manifest.json;磁盘归档键为 {run_no}.zip。
|
||||
@@ -23,7 +23,7 @@ from flask import current_app
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import ScheduleRun, ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import is_freight_receipt_rpa_task
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import is_freight_receipt_rpa_task
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
|
||||
|
||||
_RAW_ZIP_NOT_FOUND_MESSAGE = '原始收料包不存在,请重新执行或联系管理员'
|
||||
@@ -46,12 +46,12 @@ def get_receipt_archive_dir() -> str:
|
||||
"""
|
||||
configured = ''
|
||||
if current_app:
|
||||
raw = current_app.config.get('FREIGHT_RPA_RECEIPT_ARCHIVE_DIR')
|
||||
raw = current_app.config.get('FREIGHT_RPA_INBOUND_ARCHIVE_DIR')
|
||||
configured = str(raw).strip() if raw is not None else ''
|
||||
if not configured:
|
||||
from app.core.config.settings import Config
|
||||
|
||||
configured = str(Config.FREIGHT_RPA_RECEIPT_ARCHIVE_DIR or '').strip()
|
||||
configured = str(Config.FREIGHT_RPA_INBOUND_ARCHIVE_DIR or '').strip()
|
||||
archive_dir = Path(configured)
|
||||
archive_dir.mkdir(parents=True, exist_ok=True)
|
||||
return str(archive_dir)
|
||||
@@ -229,7 +229,7 @@ def _is_allowed_receipt_archive_path(zip_path: Path) -> bool:
|
||||
"""
|
||||
校验归档 ZIP 路径是否安全可下载。
|
||||
|
||||
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内。
|
||||
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内。
|
||||
"""
|
||||
resolved = zip_path.resolve()
|
||||
if resolved.suffix.lower() != '.zip':
|
||||
@@ -250,7 +250,7 @@ def resolve_receipt_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
|
||||
解析 run 已归档的原始收料 ZIP 路径供下载接口 send_file。
|
||||
|
||||
核心逻辑:读取 summary.raw_receipt_zip_path,校验文件存在、后缀为 .zip、
|
||||
且真实路径位于 FREIGHT_RPA_RECEIPT_ARCHIVE_DIR 内;任一不满足则 404。
|
||||
且真实路径位于 FREIGHT_RPA_INBOUND_ARCHIVE_DIR 内;任一不满足则 404。
|
||||
|
||||
Returns:
|
||||
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
|
||||
+15
-14
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/schedule/freight_receipt_rpa_finalize.py
|
||||
backend/app/services/schedule/freight_inbound_rpa_finalize.py
|
||||
|
||||
用途:独立收料 RPA 排程等待态收口——进度回写、全单元终态后写计数、预生成 ZIP、发企微;
|
||||
另含超时对账:排程 run 级(每轮 tick)与按需触发孤儿单元级(schedule_run_id=NULL)。
|
||||
依赖:ShippingReceiptRpaUnitRun、shipping_receipt_rpa_archive、scheduler_service 企微通知。
|
||||
依赖:ShippingReceiptRpaUnitRun、freight_inbound_rpa_archive、scheduler_service 企微通知。
|
||||
逻辑:每笔回调 → refresh 进度计数 → 全终态时 persist ZIP → _notify_schedule_run_wecom;
|
||||
超时对账只终态化失败,绝不自动重试或重发(恢复走人工显式重试入口)。
|
||||
"""
|
||||
@@ -21,7 +21,8 @@ from app.models import ScheduleRun, ScheduleTask
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY
|
||||
from app.services.schedule.freight_inbound_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, INBOUND_RPA_JOB_KEY
|
||||
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
_RECEIPT_RPA_HEADER_ORDER = [
|
||||
@@ -50,7 +51,7 @@ def register_receipt_rpa_excel_headers() -> None:
|
||||
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
|
||||
"""
|
||||
register_schedule_header(
|
||||
RECEIPT_RPA_JOB_KEY,
|
||||
INBOUND_RPA_JOB_KEY,
|
||||
_RECEIPT_RPA_HEADER_ORDER,
|
||||
_RECEIPT_RPA_HEADER_LABELS,
|
||||
)
|
||||
@@ -94,7 +95,7 @@ def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None
|
||||
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
|
||||
return bool(
|
||||
task.schedule_type == 'platform_job'
|
||||
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
|
||||
and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY
|
||||
and any(isinstance(row, dict) and row.get('status') == AWAITING_RECEIPT_RPA_CALLBACK_STATUS for row in step_logs or [])
|
||||
)
|
||||
|
||||
@@ -185,7 +186,7 @@ def report_receipt_batch_progress(payload: dict) -> dict:
|
||||
Returns:
|
||||
dict: updated / rejected 及当前计数。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
|
||||
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
|
||||
return {'updated': False, 'reason': 'callback_schema_invalid'}
|
||||
try:
|
||||
schedule_run_id = int(payload.get('schedule_run_id')) if payload.get('schedule_run_id') is not None else None
|
||||
@@ -233,7 +234,7 @@ def mark_receipt_unit_processing(payload: dict) -> dict:
|
||||
|
||||
核心逻辑:仅 awaiting_rpa → processing;已终态或已 processing 幂等返回。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
|
||||
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
|
||||
return {'updated': False, 'reason': 'callback_schema_invalid'}
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
if not callback_id:
|
||||
@@ -285,7 +286,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
|
||||
# [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
|
||||
register_receipt_rpa_excel_headers()
|
||||
header_order, header_labels = resolve_schedule_header(RECEIPT_RPA_JOB_KEY)
|
||||
header_order, header_labels = resolve_schedule_header(INBOUND_RPA_JOB_KEY)
|
||||
excel_export_ok = True
|
||||
excel_data, excel_name, excel_size = None, None, 0
|
||||
try:
|
||||
@@ -314,7 +315,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
|
||||
else:
|
||||
# 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import receipt_rpa_result_excel_name
|
||||
from app.services.schedule.freight_inbound_rpa_archive import receipt_rpa_result_excel_name
|
||||
|
||||
excel_name = receipt_rpa_result_excel_name(run)
|
||||
run.excel_file_data = excel_data
|
||||
@@ -330,7 +331,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
'raw_receipt_zip_size': 0,
|
||||
}
|
||||
try:
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import persist_receipt_rpa_raw_zip_archive
|
||||
from app.services.schedule.freight_inbound_rpa_archive import persist_receipt_rpa_raw_zip_archive
|
||||
|
||||
archive_summary = persist_receipt_rpa_raw_zip_archive(run)
|
||||
except Exception as archive_exc:
|
||||
@@ -366,7 +367,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
def _receipt_timeout_seconds() -> int:
|
||||
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
|
||||
try:
|
||||
return max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
|
||||
return max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900)))
|
||||
except (TypeError, ValueError):
|
||||
return 900
|
||||
|
||||
@@ -376,7 +377,7 @@ def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
|
||||
return bool(
|
||||
task
|
||||
and task.schedule_type == 'platform_job'
|
||||
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
|
||||
and normalize_platform_api_path(task.platform_api_path) == INBOUND_RPA_JOB_KEY
|
||||
)
|
||||
|
||||
|
||||
@@ -384,7 +385,7 @@ def _receipt_last_activity(run: ScheduleRun, units: list[ShippingReceiptRpaUnitR
|
||||
"""收料 run 的最后活动锚:run 开始时间与全部单元 started/finished 时间的最大值。
|
||||
|
||||
语义为「笔间静默」:worker 每开始/完成一笔都会推进锚点,锚点静默超过
|
||||
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
|
||||
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 才判定 worker 不再活动。刻意不含单元
|
||||
created_at——批量 trigger 中排队单元的创建时间不代表活动,否则整批永不超时。
|
||||
极端长单笔(单站点导出超过 timeout)会被判超时,需按最慢单笔调大该配置。
|
||||
"""
|
||||
@@ -502,7 +503,7 @@ def recover_all_stale_orphan_receipt_units() -> int:
|
||||
(coalesce(started_at, created_at):与 run 级同为活动锚思想,单元未被领取
|
||||
无 started_at 时以 created_at 兜底;注意 run 级 _receipt_last_activity 是
|
||||
笔间静默口径、刻意不含 created_at,两者语义不同)超过
|
||||
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_receipt_rpa_unit)
|
||||
FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS 的单元;admin 单元重试(retry_receipt_rpa_unit)
|
||||
原样复制 schedule_run_id,其 retry 单元同为孤儿,一并覆盖。
|
||||
[STEP 2] 逐单元经 _fail_receipt_unit_with_timeout 收口(failed +
|
||||
RPA.RECEIPT_CALLBACK_TIMEOUT + 审计,与 run 级扫描同一实现零漂移);
|
||||
+8
-8
@@ -1,11 +1,11 @@
|
||||
"""
|
||||
backend/app/services/schedule/freight_receipt_rpa_job.py
|
||||
backend/app/services/schedule/freight_inbound_rpa_job.py
|
||||
|
||||
用途:独立收料 RPA 排程——按勾选库存源一对一冻结执行单元并写 receipt trigger。
|
||||
依赖:receipt_rpa.write_receipt_export_batch_trigger、assert_receipt_rpa_worker_ready、
|
||||
依赖:freight_rpa.inbound.trigger_io.write_inbound_export_batch_trigger、assert_receipt_rpa_worker_ready、
|
||||
ShippingInventorySource / ShippingReceiptReportConfig / ShippingReceiptRpaUnitRun、
|
||||
ScheduleTask/Run。
|
||||
逻辑:job_registry 的 freight-receipt-rpa 调用本 handler;写 trigger 前 fail-fast;
|
||||
逻辑:job_registry 的 freight-rpa-inbound 调用本 handler;写 trigger 前 fail-fast;
|
||||
口径与库存排程一致(选中 N 源 → N unit),query_parameters 原样下发。
|
||||
"""
|
||||
|
||||
@@ -17,13 +17,13 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.inbound.trigger_io import SCHEMA, write_inbound_export_batch_trigger
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
assert_receipt_rpa_worker_ready,
|
||||
)
|
||||
|
||||
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
|
||||
INBOUND_RPA_JOB_KEY = 'freight-rpa-inbound'
|
||||
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
@@ -139,8 +139,8 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
|
||||
for unit, trigger_unit in zip(units, trigger_units):
|
||||
unit.trigger_snapshot_json = trigger_unit
|
||||
trigger_path = write_receipt_export_batch_trigger(run.run_no, trigger_units, {
|
||||
'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': 'shipping_receipt_rpa.v1',
|
||||
trigger_path = write_inbound_export_batch_trigger(run.run_no, trigger_units, {
|
||||
'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': SCHEMA,
|
||||
})
|
||||
if not trigger_path:
|
||||
for unit in units:
|
||||
@@ -0,0 +1,18 @@
|
||||
"""收料原样归档三年到期对象清理(排程壳)。
|
||||
|
||||
批次 R Task 10 起,清理能力本体已下沉 freight_rpa.inbound.report_archive
|
||||
(run_freight_inbound_rpa_retention_schedule,函数名 receipt 词根→inbound);
|
||||
本文件仅保留排程平台 Job 处理器接缝(job_registry 按 schedule 包路径注册,
|
||||
Task 11 已随排程壳平移改名为 freight_inbound_rpa_retention,git mv 保留历史)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
|
||||
"""排程壳:委托 freight_rpa.inbound.report_archive 执行三年保留清理(行为不变)。"""
|
||||
from app.services.freight_rpa.inbound.report_archive import run_freight_inbound_rpa_retention_schedule
|
||||
|
||||
return run_freight_inbound_rpa_retention_schedule(task, run)
|
||||
+7
-7
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/services/schedule/shipping_inventory_rpa_archive.py
|
||||
backend/app/services/schedule/freight_onhand_rpa_archive.py
|
||||
|
||||
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
|
||||
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
|
||||
依赖:ScheduleRun、ShippingInventoryFile、freight_onhand_rpa_finalize.is_shipping_inventory_rpa_task。
|
||||
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
|
||||
企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」;
|
||||
完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。
|
||||
@@ -22,7 +22,7 @@ from flask import current_app
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import ScheduleRun, ShippingInventoryFile
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import is_shipping_inventory_rpa_task
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
|
||||
|
||||
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
|
||||
@@ -39,14 +39,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
|
||||
def get_inventory_archive_dir() -> str:
|
||||
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
|
||||
archive_dir = Path(
|
||||
current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
|
||||
current_app.config.get("FREIGHT_RPA_ONHAND_ARCHIVE_DIR")
|
||||
if current_app
|
||||
else ""
|
||||
)
|
||||
if not str(archive_dir):
|
||||
from app.core.config.settings import Config
|
||||
|
||||
archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
|
||||
archive_dir = Path(Config.FREIGHT_RPA_ONHAND_ARCHIVE_DIR)
|
||||
archive_dir.mkdir(parents=True, exist_ok=True)
|
||||
return str(archive_dir)
|
||||
|
||||
@@ -251,7 +251,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
|
||||
"""
|
||||
校验归档 ZIP 路径是否安全可下载。
|
||||
|
||||
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
|
||||
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_ONHAND_ARCHIVE_DIR 内。
|
||||
"""
|
||||
resolved = zip_path.resolve()
|
||||
if resolved.suffix.lower() != ".zip":
|
||||
@@ -272,7 +272,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
|
||||
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
|
||||
|
||||
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
|
||||
且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
|
||||
且真实路径位于 FREIGHT_RPA_ONHAND_ARCHIVE_DIR 内;任一不满足则 404。
|
||||
|
||||
Returns:
|
||||
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
|
||||
+8
-8
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/schedule/shipping_inventory_rpa_finalize.py
|
||||
backend/app/services/schedule/freight_onhand_rpa_finalize.py
|
||||
|
||||
用途:货代库存 RPA 排程异步终态(defer / finalize / 超时回收)。
|
||||
依赖:ScheduleRun/ScheduleTask、excel_service、kb_sync、scheduler_service 企微通知、tool_common。
|
||||
逻辑:shipping_inventory_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize;
|
||||
逻辑:freight_onhand_rpa_job 写 trigger 后 defer;inventory_rpa_workflow 回调后 finalize;
|
||||
run_task_now / cron 调度循环启动前回收超时 awaiting run;服务重启跳过 awaiting RPA run。
|
||||
"""
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule import normalize_platform_api_path
|
||||
from app.services.shipping_notice.tool_common import rpa_inventory_timeout_seconds
|
||||
|
||||
SHIPPING_INVENTORY_RPA_JOB_KEY = "shipping-inventory-rpa"
|
||||
ONHAND_RPA_JOB_KEY = "freight-rpa-onhand"
|
||||
AWAITING_RPA_CALLBACK_STATUS = "awaiting_rpa_callback"
|
||||
|
||||
FinalizeScheduleRunResult = dict[str, Any]
|
||||
@@ -52,7 +52,7 @@ def register_inventory_rpa_excel_headers() -> None:
|
||||
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
|
||||
"""
|
||||
register_schedule_header(
|
||||
SHIPPING_INVENTORY_RPA_JOB_KEY,
|
||||
ONHAND_RPA_JOB_KEY,
|
||||
_INVENTORY_RPA_HEADER_ORDER,
|
||||
_INVENTORY_RPA_HEADER_LABELS,
|
||||
)
|
||||
@@ -78,7 +78,7 @@ def is_shipping_inventory_rpa_task(task: ScheduleTask | None) -> bool:
|
||||
"""判断是否为货代库存 RPA 平台排程任务。"""
|
||||
if not task or task.schedule_type != "platform_job":
|
||||
return False
|
||||
return normalize_platform_api_path(task.platform_api_path) == SHIPPING_INVENTORY_RPA_JOB_KEY
|
||||
return normalize_platform_api_path(task.platform_api_path) == ONHAND_RPA_JOB_KEY
|
||||
|
||||
|
||||
def is_awaiting_rpa_callback(step_logs: list | None) -> bool:
|
||||
@@ -468,7 +468,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
|
||||
)
|
||||
|
||||
register_inventory_rpa_excel_headers()
|
||||
header_order, header_labels = resolve_schedule_header(SHIPPING_INVENTORY_RPA_JOB_KEY)
|
||||
header_order, header_labels = resolve_schedule_header(ONHAND_RPA_JOB_KEY)
|
||||
excel_export_ok = True
|
||||
try:
|
||||
file_data, file_name, file_size = export_schedule_result_excel(
|
||||
@@ -495,7 +495,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
|
||||
status = "partial_failed"
|
||||
else:
|
||||
# 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name
|
||||
from app.services.schedule.freight_onhand_rpa_archive import inventory_rpa_result_excel_name
|
||||
|
||||
file_name = inventory_rpa_result_excel_name(run)
|
||||
|
||||
@@ -537,7 +537,7 @@ def _finalize_shipping_inventory_schedule_run_impl(
|
||||
"raw_inventory_zip_size": 0,
|
||||
}
|
||||
try:
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import persist_inventory_rpa_raw_zip_archive
|
||||
from app.services.schedule.freight_onhand_rpa_archive import persist_inventory_rpa_raw_zip_archive
|
||||
|
||||
archive_summary = persist_inventory_rpa_raw_zip_archive(run, created=created)
|
||||
except Exception as archive_exc:
|
||||
+6
-6
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/services/schedule/shipping_inventory_rpa_job.py
|
||||
backend/app/services/schedule/freight_onhand_rpa_job.py
|
||||
|
||||
用途:排程触发货代库存 RPA 批量导出(每个 Inventory Source 一次执行)。
|
||||
依赖:inventory_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
|
||||
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用;
|
||||
写 trigger 后返回 awaiting_rpa_callback;终态由 shipping_inventory_rpa_finalize 在 RPA 回调时写入。
|
||||
逻辑:platform_api_path=freight-rpa-onhand 时由 job_registry 调用;
|
||||
写 trigger 后返回 awaiting_rpa_callback;终态由 freight_onhand_rpa_finalize 在 RPA 回调时写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,10 +16,10 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
|
||||
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
assert_inventory_rpa_worker_ready,
|
||||
)
|
||||
@@ -1,49 +0,0 @@
|
||||
"""收料原样归档三年到期对象清理。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
|
||||
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。"""
|
||||
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
|
||||
now = datetime.utcnow()
|
||||
rows = ShippingReceiptReportFile.query.filter(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_not(None),
|
||||
ShippingReceiptReportFile.archive_expires_at <= now,
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
|
||||
success = failed = 0
|
||||
errors: list[str] = []
|
||||
for report_file in rows:
|
||||
try:
|
||||
file_asset_storage.delete_object(report_file.storage_key)
|
||||
report_file.archive_deleted_at = now
|
||||
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='success',
|
||||
before={'status': 'archived'}, after={'status': 'archive_deleted'},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
success += 1
|
||||
except Exception as exc:
|
||||
errors.append(f'{report_file.id}: {exc}')
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='failure',
|
||||
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
|
||||
@@ -133,7 +133,7 @@ def validate_task_params(
|
||||
[STEP 4] check_options=True 时校验 select/multi_select 值在选项范围内。
|
||||
|
||||
Args:
|
||||
task_type: platform job key(如 shipping-inventory-rpa)。
|
||||
task_type: platform job key(如 freight-rpa-onhand)。
|
||||
job_params: 前端提交或 task.job_params 存储的参数 dict;None 视为空。
|
||||
check_options: 是否联动 options_source 校验取值范围;执行期建议 False(选项可能漂移)。
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/schedule/job_registry.py
|
||||
|
||||
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
|
||||
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
|
||||
依赖:freight_onhand_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
|
||||
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
|
||||
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
|
||||
"""
|
||||
@@ -132,9 +132,9 @@ def _register_builtin_platform_jobs() -> None:
|
||||
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
|
||||
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
|
||||
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.schedule.freight_receipt_rpa_retention_job import run_freight_receipt_rpa_retention_schedule
|
||||
from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.schedule.freight_inbound_rpa_retention import run_freight_receipt_rpa_retention_schedule
|
||||
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
|
||||
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
|
||||
run_shipping_post_ot_auto_fulfill_compensation_schedule,
|
||||
@@ -371,7 +371,7 @@ def _register_builtin_platform_jobs() -> None:
|
||||
defaults={"hash_sample_limit": 500, "dry_run": True, "limit": 1},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-inventory-rpa",
|
||||
key="freight-rpa-onhand",
|
||||
label="货代库存 RPA",
|
||||
label_key="admin.schedule.form.platformJobShippingInventory",
|
||||
handler=run_shipping_inventory_rpa_schedule,
|
||||
@@ -397,10 +397,10 @@ def _register_builtin_platform_jobs() -> None:
|
||||
defaults={"source_codes": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="freight-receipt-rpa",
|
||||
label="货代收料 RPA",
|
||||
key="freight-rpa-inbound",
|
||||
label="货代入站 RPA",
|
||||
handler=run_freight_receipt_rpa_schedule,
|
||||
description="按计划从已配置收料报表的站点导出并归档收料文件。",
|
||||
description="按计划从已配置入站报表的站点导出并归档入站文件。",
|
||||
category="shipping",
|
||||
params_schema=({
|
||||
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
|
||||
@@ -410,9 +410,9 @@ def _register_builtin_platform_jobs() -> None:
|
||||
defaults={"source_codes": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key='freight-receipt-rpa-retention', label='货代收料归档到期清理',
|
||||
key='freight-rpa-inbound-retention', label='货代入站归档到期清理',
|
||||
handler=run_freight_receipt_rpa_retention_schedule,
|
||||
description='仅删除已过三年保留期的收料对象,保留运行、文件事实和审计记录。', category='shipping',
|
||||
description='仅删除已过三年保留期的入站对象,保留运行、文件事实和审计记录。', category='shipping',
|
||||
params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
|
||||
@@ -9,8 +9,8 @@ from sqlalchemy.orm import joinedload
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.core.response import utc_iso
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
|
||||
from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary
|
||||
from app.services.schedule.timezone_util import (
|
||||
DEFAULT_SCHEDULE_TIMEZONE,
|
||||
compute_next_run_at,
|
||||
|
||||
@@ -19,11 +19,11 @@ from app import db
|
||||
from app.jobs.queue import enqueue, fail_job, finish_job, recover_stale_jobs
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import (
|
||||
recover_all_stale_awaiting_rpa_schedule_runs,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import (
|
||||
recover_all_stale_orphan_receipt_units,
|
||||
recover_all_stale_receipt_rpa_schedule_runs,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
@@ -332,7 +332,7 @@ def prepare_schedule_queue() -> int:
|
||||
|
||||
if not _worker_initialized:
|
||||
# [STEP 1] 兼容升级前由 Web 线程留下的 running 记录;无活动 Job 承接时标记中断。
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import is_awaiting_rpa_schedule_run
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import is_awaiting_rpa_schedule_run
|
||||
|
||||
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
|
||||
interrupted = 0
|
||||
@@ -358,7 +358,7 @@ def prepare_schedule_queue() -> int:
|
||||
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
|
||||
if recovered:
|
||||
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import (
|
||||
recover_pending_rpa_callback_cleanup_jobs,
|
||||
)
|
||||
|
||||
@@ -379,7 +379,7 @@ def prepare_schedule_queue() -> int:
|
||||
|
||||
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
|
||||
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
|
||||
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_receipt_rpa_finalize。
|
||||
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_inbound_rpa_finalize。
|
||||
receipt_stale = recover_all_stale_receipt_rpa_schedule_runs()
|
||||
if receipt_stale:
|
||||
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_stale)
|
||||
@@ -392,7 +392,7 @@ def prepare_schedule_queue() -> int:
|
||||
current_app.logger.info("[schedule-worker] recovered %d stale orphan receipt RPA units", orphan_stale)
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import maybe_alert_rpa_worker_status
|
||||
|
||||
maybe_alert_rpa_worker_status(force=False)
|
||||
except Exception as exc:
|
||||
|
||||
@@ -24,12 +24,12 @@ VALID_DATA_PIPELINE_SOURCES = frozenset({DATA_SOURCE_DATABASE, DATA_SOURCE_EXTER
|
||||
LEGACY_SCHEDULE_TYPES = frozenset({"platform_app", "dify_app"})
|
||||
|
||||
LEGACY_DATA_SOURCE_TO_PLATFORM_JOB = {
|
||||
"shipping_inventory_rpa": "shipping-inventory-rpa",
|
||||
"shipping_inventory_rpa": "freight-rpa-onhand",
|
||||
"faq_hot_aggregate": "faq-aggregate-hot",
|
||||
}
|
||||
|
||||
# 允许写 ScheduleTaskConfig 的 platform_job(其余平台任务仅存 cron + job key,禁配置)
|
||||
PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"shipping-inventory-rpa"})
|
||||
PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"freight-rpa-onhand"})
|
||||
|
||||
|
||||
def platform_job_allows_config(key: str | None) -> bool:
|
||||
|
||||
@@ -23,14 +23,14 @@ from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header, normalize_platform_api_path
|
||||
from app.services.schedule.freight_receipt_rpa_job import RECEIPT_RPA_JOB_KEY
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
from app.services.schedule.freight_inbound_rpa_job import INBOUND_RPA_JOB_KEY
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import (
|
||||
apply_deferred_schedule_run_state,
|
||||
is_awaiting_rpa_schedule_run,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import (
|
||||
apply_deferred_receipt_schedule_run_state,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
should_defer_receipt_schedule_run,
|
||||
@@ -106,8 +106,8 @@ def _build_schedule_run_wecom_jump_params(task: ScheduleTask, run: ScheduleRun)
|
||||
核心逻辑:指向管理端 /admin/schedules;有原始库存/收料归档时附加 raw_zip=1
|
||||
与对应 download 意图,由前端登录后自动触发一次下载,失败时保留手动入口。
|
||||
"""
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
|
||||
from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary
|
||||
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
params: dict[str, Any] = {
|
||||
@@ -137,7 +137,7 @@ def _receipt_report_files_for_run(run: ScheduleRun) -> list[ShippingReceiptRepor
|
||||
if (
|
||||
task is None
|
||||
or task.schedule_type != 'platform_job'
|
||||
or normalize_platform_api_path(task.platform_api_path) != RECEIPT_RPA_JOB_KEY
|
||||
or normalize_platform_api_path(task.platform_api_path) != INBOUND_RPA_JOB_KEY
|
||||
):
|
||||
return []
|
||||
return (
|
||||
@@ -171,8 +171,8 @@ def _build_schedule_run_wecom_description(run: ScheduleRun) -> str:
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
|
||||
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import receipt_raw_zip_available_from_summary
|
||||
from app.services.schedule.freight_onhand_rpa_archive import inventory_raw_zip_available_from_summary
|
||||
from app.services.schedule.freight_inbound_rpa_archive import receipt_raw_zip_available_from_summary
|
||||
|
||||
if inventory_raw_zip_available_from_summary(summary):
|
||||
description += '\n原始库存包:点击本通知,登录 HXOPS 后自动下载'
|
||||
@@ -238,7 +238,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
raw_zip_media_id = None
|
||||
raw_zip_file_name = None
|
||||
try:
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||
from app.services.schedule.freight_onhand_rpa_archive import resolve_inventory_raw_zip_download
|
||||
|
||||
raw_zip_path, raw_zip_file_name = resolve_inventory_raw_zip_download(run)
|
||||
raw_zip_media_id = upload_wecom_temp_media(raw_zip_path.read_bytes(), raw_zip_file_name)
|
||||
@@ -251,7 +251,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
receipt_zip_media_id = None
|
||||
receipt_zip_file_name = None
|
||||
try:
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import resolve_receipt_raw_zip_download
|
||||
from app.services.schedule.freight_inbound_rpa_archive import resolve_receipt_raw_zip_download
|
||||
|
||||
receipt_zip_path, receipt_zip_file_name = resolve_receipt_raw_zip_download(run)
|
||||
receipt_zip_media_id = upload_wecom_temp_media(
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/fulfillment_workflow.py
|
||||
|
||||
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传(RPA/人工)与下游衔接入口。
|
||||
依赖:customer_identity_gate、reservation_gate、match、export、query_service、inventory_workflow、
|
||||
inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、rpa.write_upload_trigger、
|
||||
inventory_mapping_workflow、stp_line_inventory_match、upload_attempt_service、freight_rpa.upload.trigger_io、
|
||||
tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、
|
||||
order_task_stage_machine。
|
||||
逻辑:tools.py 门面 re-export;匹配成功后 Gate 路径禁止 try_auto_chain 内嵌 generate/upload,
|
||||
@@ -65,11 +65,11 @@ from app.services.shipping_notice.upload_attempt_service import (
|
||||
record_manual_upload,
|
||||
start_rpa_attempt,
|
||||
)
|
||||
from app.services.shipping_notice.rpa import write_upload_trigger
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
from app.services.freight_rpa.onhand.attempts import (
|
||||
max_rpa_upload_attempts,
|
||||
upload_rpa_attempts,
|
||||
)
|
||||
from app.services.freight_rpa.upload.trigger_io import write_upload_trigger
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.upload_config_validation import compute_upload_config_hash
|
||||
@@ -465,7 +465,7 @@ def _trigger_freight_upload_rpa(
|
||||
|
||||
# [STEP] 自动上传前强制系统级就绪:Worker / 凭据 / 共享目录 / 环境隔离 / 回调基址。
|
||||
try:
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import assert_freight_upload_rpa_ready
|
||||
from app.services.freight_rpa.common.worker_heartbeat import assert_freight_upload_rpa_ready
|
||||
|
||||
assert_freight_upload_rpa_ready()
|
||||
except ServiceUnavailableError as exc:
|
||||
|
||||
@@ -122,7 +122,7 @@ def start_batch_test_export(source_ids: list[int], *, actor_id: int | None, retr
|
||||
"""创建批量验证并按连接配置分组投递 RPA;每站点保留独立运行与回调结果。"""
|
||||
sources = _validate_batch_sources(source_ids)
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
|
||||
stamp = datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
|
||||
batch = ShippingInventoryValidationBatch(
|
||||
@@ -219,7 +219,7 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
|
||||
同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站
|
||||
等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。
|
||||
"""
|
||||
timeout = max(1, int(current_app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS']))
|
||||
timeout = max(1, int(current_app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS']))
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
@@ -274,7 +274,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
if active:
|
||||
return _payload(active)
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||
@@ -354,14 +354,14 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
|
||||
# FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
|
||||
# FREIGHT_RPA_SHARED_ONHAND_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
|
||||
raw_file_path = str(payload.get('file_path') or '').strip()
|
||||
path: Path | None = None
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _resolve_shared_inventory_drop_file
|
||||
drop_root = inventory_drop_dir()
|
||||
from app.services.freight_rpa.onhand.trigger_io import onhand_drop_dir
|
||||
from app.services.freight_rpa.onhand.workflow_protocol import resolve_shared_inventory_drop_file
|
||||
drop_root = onhand_drop_dir()
|
||||
if drop_root is not None:
|
||||
path = _resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root)
|
||||
path = resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root)
|
||||
if path is None:
|
||||
candidate = Path(raw_file_path)
|
||||
if candidate.is_file():
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_rpa_workflow.py
|
||||
|
||||
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
|
||||
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、
|
||||
inventory_mapping_workflow、query_service、动态订单字段、tool_common、state_machine、tool_response。
|
||||
用途:发货通知库存 RPA 业务编排(触发导出、等待/超时、回调落盘、快照与门禁推进)。
|
||||
依赖:customer_identity_gate、reservation_gate、freight_rpa.onhand(trigger_io 目录/attempts 计数/
|
||||
workflow_protocol 协议记账)、inventory_snapshot、inventory_mapping_workflow、query_service、
|
||||
动态订单字段、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
|
||||
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取;
|
||||
复用 ready 快照走 link_snapshot_to_task_for_preparation(动态仓未决可 pending_matching)。
|
||||
Task 9 拆分:attempt 行记账/run_no 幂等键/轮次与排程校验/批量进度记账/超时窗口数学/
|
||||
回调契约归一化等纯协议态下沉 freight_rpa.onhand.workflow_protocol(零 shipping_notice
|
||||
import);快照落盘、ScheduleRun finalize、ProcessGate/Execution 推进、审计投影与状态机
|
||||
留守本文件(事务边界与 commit 时机与拆分前逐点等价)。下方旧私有名以模块别名 re-export,
|
||||
既有同包调用与测试 import(含 monkeypatch 接缝)不换名。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
@@ -36,7 +41,7 @@ from app.services.shipping_notice.inventory_upload import (
|
||||
rebuild_task_inventory_attachment_from_snapshot,
|
||||
stage_task_inventory_callback_file,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import (
|
||||
enqueue_callback_file_move,
|
||||
flush_callback_cleanup_queue,
|
||||
mark_callback_drop_file_consumed,
|
||||
@@ -60,15 +65,34 @@ from app.services.shipping_notice.query_service import (
|
||||
)
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.rpa import (
|
||||
inventory_drop_dir,
|
||||
inventory_processed_dir,
|
||||
from app.services.freight_rpa.onhand.attempts import onhand_rpa_attempts
|
||||
from app.services.freight_rpa.onhand.trigger_io import (
|
||||
SCHEMA,
|
||||
onhand_drop_dir,
|
||||
onhand_processed_dir,
|
||||
)
|
||||
from app.services.freight_rpa.onhand.workflow_protocol import (
|
||||
compute_rpa_wait_window,
|
||||
expected_rpa_callback_run_no,
|
||||
extract_run_no_from_trigger,
|
||||
get_consumed_inventory_rpa_run_no,
|
||||
is_legacy_trigger_run_no,
|
||||
latest_task_event,
|
||||
mark_inventory_rpa_run_no_consumed,
|
||||
merge_batch_callback_item,
|
||||
normalize_inventory_batch_item_status,
|
||||
normalize_inventory_result_status,
|
||||
record_onhand_batch_progress,
|
||||
resolve_effective_callback_run_no,
|
||||
resolve_shared_inventory_drop_file,
|
||||
validate_rpa_callback_not_replayed,
|
||||
validate_rpa_callback_run_no,
|
||||
validate_schedule_batch_callback_run_no,
|
||||
)
|
||||
from app.services.shipping_notice.onhand_trigger_batch import (
|
||||
write_inventory_export_trigger_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
)
|
||||
from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
log_task_event,
|
||||
@@ -78,6 +102,23 @@ from app.services.shipping_notice.tool_common import (
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.task_disposition_service import task_execution_block_reason
|
||||
|
||||
# [协议态 re-export] Task 9 下沉 freight_rpa.onhand.workflow_protocol 的函数在本模块保留旧私有名
|
||||
# 别名:既有同包调用与测试(tests/test_shipping_process_recovery_plan 等直接 import 旧名)
|
||||
# 不换名;monkeypatch 接缝仍以本模块全局名为准。
|
||||
_extract_run_no_from_trigger = extract_run_no_from_trigger
|
||||
_is_legacy_trigger_run_no = is_legacy_trigger_run_no
|
||||
_expected_rpa_callback_run_no = expected_rpa_callback_run_no
|
||||
_validate_rpa_callback_run_no = validate_rpa_callback_run_no
|
||||
_resolve_effective_callback_run_no = resolve_effective_callback_run_no
|
||||
_get_consumed_inventory_rpa_run_no = get_consumed_inventory_rpa_run_no
|
||||
_mark_inventory_rpa_run_no_consumed = mark_inventory_rpa_run_no_consumed
|
||||
_validate_rpa_callback_not_replayed = validate_rpa_callback_not_replayed
|
||||
_validate_schedule_batch_callback_run_no = validate_schedule_batch_callback_run_no
|
||||
_resolve_shared_inventory_drop_file = resolve_shared_inventory_drop_file
|
||||
_normalize_rpa_inventory_result_status = normalize_inventory_result_status
|
||||
_normalize_rpa_inventory_batch_item_status = normalize_inventory_batch_item_status
|
||||
_merge_batch_callback_item = merge_batch_callback_item
|
||||
|
||||
|
||||
def _workflow_owner(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | ShippingOrderTask:
|
||||
"""将正式 Notice 输入解析为 OT owner;库存运行事实统一写入 OT。"""
|
||||
@@ -103,17 +144,6 @@ def _workflow_error(task: ShippingNotice | ShippingOrderTask) -> str | None:
|
||||
return getattr(_workflow_owner(task), 'error_message', None)
|
||||
|
||||
|
||||
def latest_task_event(task: ShippingNotice, event_type: str) -> ShippingTaskEvent | None:
|
||||
"""返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试用)。"""
|
||||
if task.id is None:
|
||||
return None
|
||||
return (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _inventory_rpa_attempt_label(*, attempt_no: int, max_attempts: int, manual_retry_round: bool) -> str:
|
||||
"""
|
||||
生成库存 RPA 尝试状态文案。
|
||||
@@ -276,10 +306,10 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int |
|
||||
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
|
||||
if not last_trigger or not isinstance(last_trigger.created_at, datetime):
|
||||
return None, None, None
|
||||
# 超时窗口数学为协议态(workflow_protocol.compute_rpa_wait_window);
|
||||
# 业务门禁(blocking reason / ready 文件)与超时阈值配置(tool_common)留守本域。
|
||||
timeout_seconds = rpa_inventory_timeout_seconds()
|
||||
elapsed = max(int((datetime.utcnow() - last_trigger.created_at).total_seconds()), 0)
|
||||
remaining = max(timeout_seconds - elapsed, 0)
|
||||
return elapsed, timeout_seconds, remaining
|
||||
return compute_rpa_wait_window(last_trigger.created_at, timeout_seconds)
|
||||
|
||||
|
||||
def next_inventory_rpa_recheck_at(task: ShippingNotice) -> datetime | None:
|
||||
@@ -603,65 +633,6 @@ def _persist_post_commit_task_event(
|
||||
)
|
||||
|
||||
|
||||
def _extract_run_no_from_trigger(trigger_path: str | None) -> str:
|
||||
"""从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 均支持)。"""
|
||||
path = Path(str(trigger_path or ""))
|
||||
name = path.name
|
||||
prefix = "inventory_export_batch_"
|
||||
if name.startswith(prefix) and name.endswith(".json"):
|
||||
return name[len(prefix) : -len(".json")]
|
||||
if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file():
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(payload, dict):
|
||||
run_no = str(payload.get("run_no") or "").strip()
|
||||
if run_no:
|
||||
return run_no
|
||||
except (OSError, json.JSONDecodeError, TypeError, ValueError):
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def _is_legacy_trigger_run_no(run_no: str) -> bool:
|
||||
"""判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传)。"""
|
||||
return str(run_no or "").strip().upper().startswith("LEGACY-")
|
||||
|
||||
|
||||
def _expected_rpa_callback_run_no(task: ShippingNotice) -> str:
|
||||
"""读取任务最近一次 RPA 触发记录的 run_no。"""
|
||||
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
|
||||
if not last_trigger:
|
||||
return ""
|
||||
detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {}
|
||||
run_no = str(detail.get("run_no") or "").strip()
|
||||
if run_no:
|
||||
return run_no
|
||||
return _extract_run_no_from_trigger(str(detail.get("trigger") or ""))
|
||||
|
||||
|
||||
def _validate_rpa_callback_run_no(task: ShippingNotice, callback_run_no: str) -> str | None:
|
||||
"""校验回调 run_no 属于当前任务最近一次有效触发轮次。"""
|
||||
provided = str(callback_run_no or "").strip()
|
||||
expected = _expected_rpa_callback_run_no(task)
|
||||
if not expected:
|
||||
return "no_active_trigger"
|
||||
if not provided:
|
||||
if _is_legacy_trigger_run_no(expected):
|
||||
return None
|
||||
return "run_no_missing"
|
||||
if provided != expected:
|
||||
return "run_no_mismatch"
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_effective_callback_run_no(task: ShippingNotice, payload: dict[str, Any]) -> str:
|
||||
"""解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。"""
|
||||
provided = str(payload.get("run_no") or "").strip()
|
||||
if provided:
|
||||
return provided
|
||||
return _expected_rpa_callback_run_no(task)
|
||||
|
||||
|
||||
def _lock_task_for_rpa_callback(task: ShippingOrderTask) -> ShippingOrderTask:
|
||||
"""对订单任务行加悲观锁,防止并发回调重复消费同一轮次。"""
|
||||
if task.id is None:
|
||||
@@ -674,45 +645,6 @@ def _lock_task_for_rpa_callback(task: ShippingOrderTask) -> ShippingOrderTask:
|
||||
)
|
||||
|
||||
|
||||
def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str:
|
||||
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
attempt = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter_by(task_no=str(task.task_no or ''), status='consumed')
|
||||
.order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
|
||||
.first()
|
||||
)
|
||||
return str(getattr(attempt, 'source_run_no', '') or '').strip()
|
||||
|
||||
|
||||
def _mark_inventory_rpa_run_no_consumed(task: ShippingNotice, run_no: str) -> None:
|
||||
"""标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。"""
|
||||
effective = str(run_no or "").strip()
|
||||
if not effective:
|
||||
return
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
|
||||
attempt = (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter_by(task_no=str(task.task_no or ''), source_run_no=effective)
|
||||
.one_or_none()
|
||||
)
|
||||
if attempt is not None:
|
||||
attempt.status = 'consumed'
|
||||
attempt.consumed_at = datetime.utcnow()
|
||||
|
||||
|
||||
def _validate_rpa_callback_not_replayed(task: ShippingNotice, run_no: str) -> str | None:
|
||||
"""拒绝同一 run_no 的重复成功/失败/跳过回调。"""
|
||||
effective = str(run_no or "").strip()
|
||||
consumed = _get_consumed_inventory_rpa_run_no(task)
|
||||
if effective and consumed and effective == consumed:
|
||||
return "run_no_already_consumed"
|
||||
return None
|
||||
|
||||
|
||||
def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""
|
||||
校验 RPA 回调轮次契约(run_no + 幂等)。
|
||||
@@ -918,7 +850,7 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
|
||||
def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""强制单源库存成功回调携带 v2 身份围栏,禁止旧 payload 写入库存事实。
|
||||
|
||||
单源 Worker 与批量 Worker 共用 ``shipping_inventory_rpa.v2``;缺少任一
|
||||
单源 Worker 与批量 Worker 共用 ``freight_rpa.onhand.v1``;缺少任一
|
||||
Attempt/Execution 身份时直接拒绝,避免回调按 Task 级旧 run_no 错绑轮次。
|
||||
"""
|
||||
if str(payload.get('status') or '').strip().lower() != 'success':
|
||||
@@ -935,7 +867,7 @@ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str,
|
||||
'gate_id': payload.get('gate_id'),
|
||||
}
|
||||
missing = [key for key, value in required.items() if value in (None, '')]
|
||||
if required['schema_version'] != 'shipping_inventory_rpa.v2' or missing:
|
||||
if required['schema_version'] != SCHEMA or missing:
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
@@ -949,47 +881,6 @@ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str,
|
||||
return None
|
||||
|
||||
|
||||
def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
合并 batch 顶层契约字段到 result item。
|
||||
核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由
|
||||
Worker item 显式返回,禁止后端从任务或数据库补齐。
|
||||
"""
|
||||
merged = dict(item)
|
||||
top_schema_version = str(payload.get('schema_version') or '').strip()
|
||||
if top_schema_version and not str(merged.get('schema_version') or '').strip():
|
||||
merged['schema_version'] = top_schema_version
|
||||
top_run_no = str(payload.get("run_no") or "").strip()
|
||||
if top_run_no and not str(merged.get("run_no") or "").strip():
|
||||
merged["run_no"] = top_run_no
|
||||
|
||||
task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip()
|
||||
if task_no and not str(merged.get("task_no") or "").strip():
|
||||
merged["task_no"] = task_no
|
||||
return merged
|
||||
|
||||
|
||||
def _validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callback_run_no: str) -> str | None:
|
||||
"""校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。"""
|
||||
if schedule_run_id is None:
|
||||
return None
|
||||
from app.models import ScheduleRun
|
||||
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
if not run:
|
||||
return "schedule_run_not_found"
|
||||
expected = str(run.run_no or "").strip()
|
||||
provided = str(callback_run_no or "").strip()
|
||||
if not expected:
|
||||
return "schedule_run_no_missing"
|
||||
if provided != expected:
|
||||
return "schedule_run_no_mismatch"
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if run.status != "running" or not summary.get("awaiting_rpa"):
|
||||
return "schedule_run_not_awaiting"
|
||||
return None
|
||||
|
||||
|
||||
def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
RPA 批量导出进度回调:实时回写排程 run 的成功/跳过/失败笔数(非终态)。
|
||||
@@ -998,13 +889,14 @@ def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
展示"执行中"run 的笔数;最终计数仍以 inventory-batch-ready 回调为准(终态化时重算覆盖)。
|
||||
|
||||
核心逻辑:校验 schema_version、schedule_run_id 与 run_no 匹配且 run 仍处于 awaiting_rpa;
|
||||
仅更新计数列与 response_summary_json.progress,不修改 status/started_at/finished_at,
|
||||
不影响超时回收与最终终态化。计数采用 max(现有, 上报) 防乱序回退。
|
||||
计数写入与提交下沉 freight_rpa.onhand.workflow_protocol.record_onhand_batch_progress
|
||||
(max(现有, 上报) 防乱序回退,commit 时机与拆分前一致:校验通过、计数写完后立即提交),
|
||||
本函数只保留业务响应 envelope(tool_response)。
|
||||
|
||||
Returns:
|
||||
tool_response: 进度已回写为 ok;无效/非等待态为 failed(不改变 run 状态)。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
|
||||
if payload.get('schema_version') != SCHEMA:
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'progress_status': 'invalid', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
@@ -1018,7 +910,7 @@ def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status='failed', message='progress_schema_invalid', data={
|
||||
'progress_status': 'invalid', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, run_no)
|
||||
schedule_run_error = validate_schedule_batch_callback_run_no(schedule_run_id, run_no)
|
||||
if schedule_run_error:
|
||||
return tool_response(status='failed', message=f'排程进度回调无效: {schedule_run_error}', data={
|
||||
'progress_status': 'rejected', 'schedule_run_error': schedule_run_error,
|
||||
@@ -1030,30 +922,16 @@ def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status='failed', message='schedule_run_not_found', data={
|
||||
'progress_status': 'rejected', 'schedule_run_error': 'schedule_run_not_found',
|
||||
})
|
||||
incoming = {
|
||||
'success_count': max(0, int(payload.get('success_count') or 0)),
|
||||
'skipped_count': max(0, int(payload.get('skipped_count') or 0)),
|
||||
'failed_count': max(0, int(payload.get('failed_count') or 0)),
|
||||
}
|
||||
run.success_count = max(int(run.success_count or 0), incoming['success_count'])
|
||||
run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count'])
|
||||
run.failed_count = max(int(run.failed_count or 0), incoming['failed_count'])
|
||||
summary = dict(run.response_summary_json or {})
|
||||
summary['progress'] = {
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
'batch_run_no': run_no,
|
||||
'updated_at': datetime.utcnow().isoformat(),
|
||||
}
|
||||
run.response_summary_json = summary
|
||||
db.session.commit()
|
||||
counts = record_onhand_batch_progress(
|
||||
run,
|
||||
run_no,
|
||||
success_count=max(0, int(payload.get('success_count') or 0)),
|
||||
skipped_count=max(0, int(payload.get('skipped_count') or 0)),
|
||||
failed_count=max(0, int(payload.get('failed_count') or 0)),
|
||||
)
|
||||
return tool_response(status='ok', message='库存 RPA 导出进度已回写', data={
|
||||
'progress_status': 'updated',
|
||||
'run_no': run_no,
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
**counts,
|
||||
})
|
||||
|
||||
|
||||
@@ -1295,7 +1173,7 @@ def ensure_inventory_via_rpa(
|
||||
if last_trigger and isinstance(last_trigger.created_at, datetime):
|
||||
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
|
||||
if elapsed < timeout_seconds:
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
attempts = onhand_rpa_attempts(task)
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
@@ -1338,7 +1216,7 @@ def ensure_inventory_via_rpa(
|
||||
|
||||
# [STEP 2] 仅本次用户或系统明确触发可创建一次 RPA 尝试。
|
||||
# 禁止消费全局 drop 目录未校验文件,必须等待 RPA 回调或复用正式快照。
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
attempts = onhand_rpa_attempts(task)
|
||||
|
||||
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
|
||||
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
|
||||
@@ -1441,46 +1319,6 @@ def ensure_inventory_via_rpa(
|
||||
)
|
||||
|
||||
|
||||
def _normalize_rpa_inventory_result_status(payload: dict[str, Any]) -> str:
|
||||
"""
|
||||
归一化单任务 RPA 库存回调结果。
|
||||
|
||||
核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段;
|
||||
缺省 success 视为 true(历史单任务回调兼容)。
|
||||
|
||||
Returns:
|
||||
str: success | skipped | failed
|
||||
"""
|
||||
raw_status = str(payload.get("status") or "").strip().lower()
|
||||
if raw_status in {"success", "skipped", "failed"}:
|
||||
return raw_status
|
||||
if payload.get("skipped"):
|
||||
return "skipped"
|
||||
if bool(payload.get("success", True)):
|
||||
return "success"
|
||||
return "failed"
|
||||
|
||||
|
||||
def _normalize_rpa_inventory_batch_item_status(item: dict[str, Any]) -> str:
|
||||
"""
|
||||
归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。
|
||||
|
||||
核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或
|
||||
缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。
|
||||
|
||||
Returns:
|
||||
str: success | skipped | failed
|
||||
"""
|
||||
raw_status = str(item.get("status") or "").strip().lower()
|
||||
if raw_status in {"success", "skipped", "failed"}:
|
||||
return raw_status
|
||||
if item.get("skipped"):
|
||||
return "skipped"
|
||||
if item.get("success") is True:
|
||||
return "success"
|
||||
return "failed"
|
||||
|
||||
|
||||
def _summarize_rpa_inventory_batch_outcome(
|
||||
*,
|
||||
created: list[Any],
|
||||
@@ -1865,7 +1703,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not path.is_file():
|
||||
return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在")
|
||||
|
||||
processed = inventory_processed_dir()
|
||||
processed = onhand_processed_dir()
|
||||
rpa_source = task_rpa_inventory_source(task)
|
||||
if not rpa_source or not rpa_source.get("source_code"):
|
||||
return tool_response(
|
||||
@@ -2106,7 +1944,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
【AI 触发时机】:freight_rpa_worker 已完成库存文件导出、需要确认 HXOPS 已接收回调时调用。
|
||||
本函数只验证回调信封并持久化 Job;禁止在 HTTP 请求内解析 Excel、关联任务或推进 Gate。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
|
||||
if payload.get('schema_version') != SCHEMA:
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
@@ -2179,43 +2017,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
|
||||
def _resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None:
|
||||
"""将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。
|
||||
|
||||
Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``,
|
||||
Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。
|
||||
安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。
|
||||
"""
|
||||
text = str(raw_path or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
root = allowed_root.resolve()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
candidate = Path(text)
|
||||
try:
|
||||
resolved = candidate.resolve()
|
||||
if resolved.is_file():
|
||||
resolved.relative_to(root)
|
||||
return resolved
|
||||
except (OSError, ValueError, RuntimeError):
|
||||
pass
|
||||
|
||||
name = Path(text.replace('\\', '/')).name.strip()
|
||||
if not name or name in {'.', '..'} or '/' in name or '\\' in name:
|
||||
return None
|
||||
mapped = (root / name).resolve()
|
||||
try:
|
||||
mapped.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
if mapped.is_file():
|
||||
return mapped
|
||||
return None
|
||||
|
||||
|
||||
def _persist_batch_callback_receipt(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
@@ -2230,7 +2031,7 @@ def _persist_batch_callback_receipt(
|
||||
Returns:
|
||||
用受控副本路径替换成功项 ``file_path`` 后的 payload;无法安全收件时返回 None。
|
||||
"""
|
||||
allowed_root = inventory_drop_dir()
|
||||
allowed_root = onhand_drop_dir()
|
||||
if allowed_root is None:
|
||||
return None
|
||||
try:
|
||||
@@ -2296,7 +2097,7 @@ def _received_batch_callback_file_path(
|
||||
).strip('_') or 'unknown'
|
||||
receipt_root = (_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve()
|
||||
|
||||
drop_dir = inventory_drop_dir()
|
||||
drop_dir = onhand_drop_dir()
|
||||
if drop_dir is not None:
|
||||
mapped = _resolve_shared_inventory_drop_file(file_path, allowed_root=drop_dir)
|
||||
if mapped is not None:
|
||||
@@ -2331,7 +2132,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
|
||||
cleanup_retry_warnings = flush_callback_cleanup_queue()
|
||||
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
|
||||
if payload.get('schema_version') != SCHEMA:
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
@@ -2790,7 +2591,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
f'per_source_callback_confirmation_failed:{final_code}'
|
||||
)
|
||||
|
||||
drop_dir = inventory_drop_dir()
|
||||
drop_dir = onhand_drop_dir()
|
||||
is_drop_file = False
|
||||
if drop_dir is not None:
|
||||
try:
|
||||
@@ -2875,7 +2676,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
|
||||
finalize_result: dict[str, Any] = {"ok": False, "schedule_finalize_status": "skipped"}
|
||||
if schedule_run_id is not None:
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import finalize_shipping_inventory_schedule_run
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import finalize_shipping_inventory_schedule_run
|
||||
|
||||
finalize_result = finalize_shipping_inventory_schedule_run(
|
||||
schedule_run_id,
|
||||
@@ -2890,7 +2691,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
callback_move_warnings.extend(
|
||||
_flush_pending_callback_moves(
|
||||
pending_callback_moves,
|
||||
inventory_processed_dir(),
|
||||
onhand_processed_dir(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
"""
|
||||
services/shipping_notice/onhand_trigger_batch.py
|
||||
|
||||
用途:onhand(在手库存)RPA 的批量/按需导出编排——组装逐源凭据与身份键、写批量 trigger、
|
||||
单票按需触发的 fail-closed 入口。
|
||||
依赖:Flask current_app 配置、freight_rpa.onhand.trigger_io(目录解析/原子写/SCHEMA/ACTION 常量)、
|
||||
shipping_notice.inventory_source_repository(按源补 Profile 密文,函数内延迟 import)。
|
||||
逻辑:由 schedule.freight_onhand_rpa_job(定时批量)、inventory_configuration_test(配置测试)、
|
||||
inventory_rpa_workflow / per_source_rpa_service(按需触发)调用,
|
||||
与 freight_rpa.onhand.trigger_io 的纯文件 IO 分层:本文件管业务编排,目录与 JSON 原子写下沉包内。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.freight_rpa.onhand.trigger_io import (
|
||||
ACTION_ONHAND_EXPORT_BATCH,
|
||||
SCHEMA,
|
||||
_write_trigger_json_atomic,
|
||||
onhand_trigger_dir,
|
||||
)
|
||||
|
||||
|
||||
def write_inventory_export_batch_trigger(
|
||||
run_no: str,
|
||||
sources: list[dict[str, Any]],
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
写入批量库存导出 trigger(DSV/Crane 一次登录多 Warehouse)。
|
||||
【AI 触发时机】:定时排程或后台批量预热库存快照时调用。
|
||||
|
||||
Args:
|
||||
run_no: RPA 批次号,写入回调 audit。
|
||||
sources: build_rpa_inventory_source 构造的源列表。
|
||||
payload: 额外字段(trigger_type、schedule_run_id 等)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径。
|
||||
"""
|
||||
trigger_dir = onhand_trigger_dir()
|
||||
if not trigger_dir or not sources:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
inventory_sources = []
|
||||
for source in sources:
|
||||
if not isinstance(source, dict) or not source.get("source_code"):
|
||||
continue
|
||||
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'}
|
||||
trigger_source = get_rpa_trigger_inventory_source(
|
||||
str(source["source_code"]), enabled_only=not configuration_test,
|
||||
) or source
|
||||
source = {**source, **trigger_source}
|
||||
business_connector = str(source.get("connector_type") or "").strip().lower()
|
||||
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
|
||||
item = {
|
||||
"source_code": source.get("source_code"),
|
||||
"connector_type": business_connector,
|
||||
"worker_connector_type": worker_connector,
|
||||
"rpa_profile_code": source.get("rpa_profile_code"),
|
||||
"warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"),
|
||||
"login_url": source.get("login_url"),
|
||||
"entry_url": source.get("login_url"),
|
||||
"navigation": source.get("navigation") or {},
|
||||
"parameters": source.get("parameters") or [],
|
||||
"query": source.get("query") or {},
|
||||
"credential_envelope": source.get("credential_envelope") or {},
|
||||
# 配置测试回调据此将批次结果精确回写到各自站点运行。
|
||||
"validation_run_no": source.get("validation_run_no"),
|
||||
}
|
||||
# v2 逐源身份必须由后端显式写入,Worker 不得重新生成。
|
||||
for identity_key in (
|
||||
"callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version",
|
||||
"execution_id", "gate_id", "expected_warehouse_id", "lease_token",
|
||||
):
|
||||
if source.get(identity_key) is not None:
|
||||
item[identity_key] = source[identity_key]
|
||||
if not item.get('callback_id') and item.get('source_run_no'):
|
||||
item['callback_id'] = f"{item['source_run_no']}:C1"
|
||||
inventory_sources.append(item)
|
||||
if not inventory_sources:
|
||||
return None
|
||||
|
||||
body = {
|
||||
"action": ACTION_ONHAND_EXPORT_BATCH,
|
||||
"schema_version": SCHEMA,
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段
|
||||
"trigger_type": "scheduled",
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
"inventory_sources": inventory_sources,
|
||||
**(payload or {}),
|
||||
}
|
||||
safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch"
|
||||
path = trigger_dir / f"inventory_export_batch_{safe_run}.json"
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
|
||||
|
||||
def inventory_rpa_batch_enabled() -> bool:
|
||||
"""是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。"""
|
||||
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED")
|
||||
if raw is None:
|
||||
raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def build_on_demand_inventory_trigger_source(
|
||||
task_no: str,
|
||||
rpa_source: dict[str, Any],
|
||||
*,
|
||||
body: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造按需库存导出批次触发内的单源条目(含 Profile 凭据与逐源身份键)。
|
||||
【AI 触发时机】:单源 on-demand 触发与多候选合并批次触发(per_source_rpa_service)共用本构造,
|
||||
保证两条路径投递给 Worker 的输入契约完全一致。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
rpa_source: 调用方持有的非敏感源快照(含 source_code);DB 配置/Profile 存在时以其为准。
|
||||
body: 触发载荷,提供 callback_id/source_run_no/attempt_no/lease_token 等逐源身份键。
|
||||
|
||||
Returns:
|
||||
可直接传入 write_inventory_export_batch_trigger 的单源条目。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
source_code = str(rpa_source.get('source_code') or '').strip()
|
||||
rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source
|
||||
# Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。
|
||||
rpa_source = dict(rpa_source)
|
||||
business_connector = str(rpa_source.get('connector_type') or '').strip().lower()
|
||||
rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector))
|
||||
rpa_source.setdefault('entry_url', rpa_source.get('login_url'))
|
||||
rpa_source.setdefault('credential_envelope', {})
|
||||
source_item = dict(rpa_source)
|
||||
source_item.update({
|
||||
"source_code": source_code,
|
||||
"callback_id": body.get("callback_id") or (
|
||||
f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None
|
||||
),
|
||||
"task_no": task_no,
|
||||
# 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致
|
||||
# Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。
|
||||
"attempt_no": body.get("attempt_no") or body.get("attempt"),
|
||||
"source_run_no": body.get("source_run_no"),
|
||||
"candidate_set_id": body.get("candidate_set_id"),
|
||||
"candidate_set_version": body.get("candidate_set_version"),
|
||||
"execution_id": body.get("execution_id"),
|
||||
"gate_id": body.get("gate_id"),
|
||||
"expected_warehouse_id": body.get("expected_warehouse_id"),
|
||||
"lease_token": body.get("lease_token"),
|
||||
})
|
||||
return source_item
|
||||
|
||||
|
||||
def write_inventory_export_trigger_for_task(
|
||||
task_no: str,
|
||||
rpa_source: dict[str, Any],
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。
|
||||
|
||||
核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed,
|
||||
不再生成 legacy inventory_export trigger。
|
||||
"""
|
||||
body = dict(payload or {})
|
||||
if inventory_rpa_batch_enabled():
|
||||
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
|
||||
source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body)
|
||||
return write_inventory_export_batch_trigger(
|
||||
run_no,
|
||||
[source_item],
|
||||
payload={
|
||||
"schema_version": SCHEMA,
|
||||
"trigger_type": "on_demand",
|
||||
"task_no": task_no,
|
||||
**body,
|
||||
},
|
||||
)
|
||||
raise ValidationError(
|
||||
'shipping inventory RPA v2 batch trigger is required',
|
||||
code='SHIPPING.INVENTORY_RPA_V2_REQUIRED',
|
||||
)
|
||||
@@ -38,10 +38,11 @@ from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
find_latest_ready_snapshot,
|
||||
is_snapshot_fresh,
|
||||
)
|
||||
from app.services.shipping_notice.rpa import (
|
||||
from app.services.shipping_notice.onhand_trigger_batch import (
|
||||
build_on_demand_inventory_trigger_source,
|
||||
write_inventory_export_batch_trigger,
|
||||
)
|
||||
from app.services.freight_rpa.onhand.trigger_io import SCHEMA
|
||||
|
||||
|
||||
def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str | None:
|
||||
@@ -99,7 +100,7 @@ def _validate_callback_attempt_identity(
|
||||
"""校验回调身份与已冻结 Attempt/当前 CandidateSet/正式 Execution 一致。"""
|
||||
required = ('schema_version', 'callback_id', 'source_run_no', 'attempt_no', 'lease_token',
|
||||
'candidate_set_id', 'execution_id', 'gate_id')
|
||||
if str(callback_payload.get('schema_version') or '') != 'shipping_inventory_rpa.v2':
|
||||
if str(callback_payload.get('schema_version') or '') != SCHEMA:
|
||||
return False
|
||||
if any(callback_payload.get(key) in (None, '') for key in required):
|
||||
return False
|
||||
@@ -521,7 +522,7 @@ def ensure_all_required_sources_prepared(
|
||||
batch_run_no,
|
||||
pending_payloads,
|
||||
payload={
|
||||
'schema_version': 'shipping_inventory_rpa.v2',
|
||||
'schema_version': SCHEMA,
|
||||
'trigger_type': 'on_demand',
|
||||
'task_no': task_no,
|
||||
'mode': mode,
|
||||
@@ -771,7 +772,7 @@ def per_source_callback_handler(
|
||||
|
||||
def claim_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""记录 Worker 领取的逐源 Attempt,不推进 Snapshot、Link 或 Gate。"""
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2' or not isinstance(payload.get('items'), list):
|
||||
if payload.get('schema_version') != SCHEMA or not isinstance(payload.get('items'), list):
|
||||
return {'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid'}
|
||||
worker_id = str(payload.get('worker_id') or '').strip() or None
|
||||
now = datetime.utcnow()
|
||||
|
||||
@@ -520,7 +520,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
|
||||
'inventory_snapshot': _serialize_inventory_snapshot(task),
|
||||
}
|
||||
from app.services.shipping_notice.notice_upload import max_notice_chars
|
||||
from app.services.shipping_notice.rpa import rpa_runtime_mode
|
||||
from app.services.freight_rpa.common.rpa_runtime import rpa_runtime_mode
|
||||
|
||||
workflow_owner = (
|
||||
db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||||
@@ -787,7 +787,7 @@ def _serialize_source_candidate_projection(task: ShippingNotice) -> dict[str, An
|
||||
|
||||
def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str, Any]:
|
||||
"""按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。"""
|
||||
from app.services.shipping_notice.rpa import rpa_runtime_mode
|
||||
from app.services.freight_rpa.common.rpa_runtime import rpa_runtime_mode
|
||||
|
||||
workflow_owner = (
|
||||
db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||||
|
||||
@@ -147,7 +147,7 @@ def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
sync_intake_after_parse_job_recovery,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import (
|
||||
recover_pending_rpa_callback_cleanup_jobs,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
"""收料报表企微通知的管理员重发通道。
|
||||
|
||||
用途:收料排程的正常通知已统一并入排程通用出口——run 终态后一次性发送
|
||||
textcard 汇总 + 原始收料 ZIP(scheduler_service._notify_schedule_run_wecom,
|
||||
与库存 RPA 同门禁同出口);本模块只保留管理员对单个已归档收料文件的
|
||||
强制重发能力(POST /receipt-report-files/<id>/resend),不触发 RPA。
|
||||
依赖:models、file_asset_storage、audit_service、integrations.wecom.notify。
|
||||
逻辑:deliver_receipt_file 幂等投递单文件并落 ShippingReceiptNotificationDelivery
|
||||
与 shipping 审计;force=True 供管理员补偿重发,绕过成功幂等但仍受通知开关约束。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptNotificationDelivery, ShippingReceiptReportFile, User
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.integrations.wecom.notify import send_wecom_file_message, upload_wecom_temp_media
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _recipient_ids(report_file: ShippingReceiptReportFile) -> list[int]:
|
||||
"""从所属排程冻结的接收人列表取目标用户;停用通知时返回空。"""
|
||||
run = report_file.unit_run.schedule_run
|
||||
task = run.task if run else None
|
||||
if task is None or not task.notify_enabled:
|
||||
return []
|
||||
return sorted({int(user_id) for user_id in (task.notify_user_ids_json or []) if str(user_id).isdigit()})
|
||||
|
||||
|
||||
def deliver_receipt_file(file_id: int, *, force: bool = False) -> dict:
|
||||
"""向排程接收人逐一投递原样收料文件;同文件用户的成功投递可幂等重放。"""
|
||||
report_file = db.session.get(ShippingReceiptReportFile, file_id)
|
||||
if report_file is None:
|
||||
return {'success_count': 0, 'failed_count': 0, 'reason': 'file_not_found'}
|
||||
success_count = failed_count = 0
|
||||
for user_id in _recipient_ids(report_file):
|
||||
key = f'receipt:file:{report_file.id}:user:{user_id}'
|
||||
delivery = ShippingReceiptNotificationDelivery.query.filter_by(idempotency_key=key).one_or_none()
|
||||
if delivery and delivery.status == 'success' and not force:
|
||||
success_count += 1
|
||||
continue
|
||||
if delivery is None:
|
||||
delivery = ShippingReceiptNotificationDelivery(
|
||||
unit_run_id=report_file.unit_run_id, report_file_id=report_file.id, recipient_user_id=user_id,
|
||||
message_type='file', idempotency_key=key, status='pending',
|
||||
)
|
||||
db.session.add(delivery)
|
||||
db.session.flush()
|
||||
user = db.session.get(User, user_id)
|
||||
if user is None or not user.wecom_userid:
|
||||
delivery.status = 'failed'; delivery.error_code = 'WECOM_USER_UNBOUND'; delivery.error_message = 'recipient has no wecom binding'
|
||||
failed_count += 1
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
|
||||
unit_id=report_file.unit_run_id, result='failure',
|
||||
before={'delivery_status': 'pending'},
|
||||
after={'delivery_status': delivery.status, 'error_code': delivery.error_code},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
|
||||
)
|
||||
continue
|
||||
try:
|
||||
media_id = upload_wecom_temp_media(file_asset_storage.get_bytes(report_file.storage_key), report_file.original_filename)
|
||||
result = send_wecom_file_message(user.wecom_userid, media_id)
|
||||
if int(result.get('errcode', -1)) != 0:
|
||||
raise RuntimeError(str(result.get('errmsg') or result.get('errcode')))
|
||||
delivery.status = 'success'; delivery.sent_at = datetime.utcnow(); delivery.error_code = None; delivery.error_message = None
|
||||
delivery.response_summary_json = {'media_uploaded': True, 'errcode': 0}
|
||||
success_count += 1
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file', aggregate_id=str(report_file.id),
|
||||
actor_type='system', owner_user_id=user_id, unit_id=report_file.unit_run_id, result='success',
|
||||
before={'delivery_status': 'pending'}, after={'delivery_status': delivery.status, 'sent_at': delivery.sent_at.isoformat() if delivery.sent_at else None},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
|
||||
)
|
||||
except Exception as exc:
|
||||
delivery.status = 'failed'; delivery.error_code = 'WECOM_SEND_FAILED'; delivery.error_message = str(exc)[:2000]
|
||||
failed_count += 1
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_file_notification_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='system', owner_user_id=user_id,
|
||||
unit_id=report_file.unit_run_id, result='failure',
|
||||
before={'delivery_status': 'pending'},
|
||||
after={'delivery_status': delivery.status, 'error_code': delivery.error_code, 'error_message': delivery.error_message},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
metadata={'delivery_id': delivery.id, 'message_type': 'file'},
|
||||
)
|
||||
db.session.commit()
|
||||
return {'success_count': success_count, 'failed_count': failed_count}
|
||||
@@ -1,58 +1,26 @@
|
||||
"""收料 RPA callback 的原样归档服务。
|
||||
"""收料 RPA callback 的域内业务桥与终态收尾(shipping_notice 留守侧)。
|
||||
|
||||
用途:接收收料 RPA 单元回调,原样归档文件三年且不写库存快照表;终态落库后
|
||||
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线);
|
||||
每笔终态回调回写 ScheduleRun 进度计数(对齐库存 inventory-batch-progress)。
|
||||
依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、
|
||||
audit_service、freight_receipt_rpa_finalize、in_transit_transfer.inbound_callback_bridge(惰性导入)、
|
||||
in_transit_transfer.evidence_sync(惰性导入,仅 success 终态)。
|
||||
逻辑:success/empty/failed 三个终态分支各自 commit 后调用 _advance_transfer_source_job;
|
||||
empty 落库 error_code=no_receipt_data(对齐库存 no_inventory_data);
|
||||
有 schedule_run_id 时 refresh 进度再 finalize;success 分支再触发调拨证据同步;
|
||||
两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
|
||||
用途:批次 R Task 10 拆分后,本模块只留守「业务桥」——收料终态落库后推进在途调拨的
|
||||
waiting_rpa_callback 来源任务(B3 接线)、success 终态的调拨证据同步,以及排程
|
||||
终态归集(finalize)调用;原样归档/三年保留/resend/通知投递等 RPA 产物事实能力
|
||||
已下沉 freight_rpa.inbound.report_archive(函数名 receipt 词根→inbound)。
|
||||
依赖:freight_rpa.inbound.report_archive(归档能力,经 ingest_receipt_callback 委托)、
|
||||
in_transit_transfer.inbound_callback_bridge / evidence_sync(惰性导入,仅桥),
|
||||
schedule.freight_inbound_rpa_finalize(惰性导入,仅 finalize)。
|
||||
逻辑:ingest_receipt_callback 仍是本域回调入口(rpa_sinks 以 {'success':True,'data':...}
|
||||
envelope 注册为 inbound-batch-ready sink):委托 report_archive.ingest_inbound_callback
|
||||
归档(各终态分支各自 commit),并以 _finish_inbound_callback_terminal 作为
|
||||
on_terminal 钩子——commit 之后按拆分前同一顺序执行「推桥 →(success)证据同步 →
|
||||
finalize」;两座桥都是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _read_receipt_callback_file(file_path: str) -> bytes:
|
||||
"""只读取收料专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
|
||||
|
||||
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
|
||||
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...),
|
||||
Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史
|
||||
载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。
|
||||
"""
|
||||
configured_root = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR') or '').strip()
|
||||
if not configured_root:
|
||||
raise ValidationError('receipt callback file root is unavailable', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||
root = Path(configured_root).resolve()
|
||||
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
|
||||
name = Path(str(file_path).replace('\\', '/')).name
|
||||
path = (root / name).resolve()
|
||||
try:
|
||||
path.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise ValidationError('receipt callback file is outside receipt drop root', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID') from exc
|
||||
if path.suffix.lower() != '.xlsx' or not path.is_file():
|
||||
raise ValidationError('receipt callback file must be an existing xlsx', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||
max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024
|
||||
if path.stat().st_size > max_size:
|
||||
raise ValidationError('receipt callback file exceeds configured size limit', code='SHIPPING.RECEIPT_CALLBACK_FILE_INVALID')
|
||||
return path.read_bytes()
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
|
||||
def _advance_transfer_source_job(
|
||||
@@ -84,107 +52,53 @@ def _advance_transfer_source_job(
|
||||
current_app.logger.warning('[receipt-callback] advance transfer source job failed: %s', exc)
|
||||
|
||||
|
||||
def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""幂等接收单个收料单元回调,原样归档三年且不写库存快照表。"""
|
||||
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
|
||||
raise ValidationError('receipt callback schema_version is invalid', code='SHIPPING.RECEIPT_CALLBACK_INVALID')
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
|
||||
if unit is None:
|
||||
raise NotFoundError('Receipt RPA unit not found', code='SHIPPING.RECEIPT_UNIT_NOT_FOUND')
|
||||
status = str(payload.get('status') or '').strip().lower()
|
||||
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
|
||||
if status in {'empty', 'no_data'}:
|
||||
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_receipt_data。
|
||||
unit.status = 'empty'
|
||||
unit.error_code = str(payload.get('error_code') or 'no_receipt_data')[:64]
|
||||
unit.error_message = str(payload.get('error_message') or 'no_receipt_data')[:2000]
|
||||
unit.finished_at = datetime.utcnow()
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
|
||||
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success',
|
||||
before=before,
|
||||
after={
|
||||
'status': 'empty',
|
||||
'callback_id': unit.callback_id,
|
||||
'error_code': unit.error_code,
|
||||
'error_message': unit.error_message,
|
||||
},
|
||||
metadata={'callback_status': status, 'skip_reason': unit.error_code},
|
||||
)
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(
|
||||
unit, ok=False, error_code=unit.error_code or 'no_receipt_data',
|
||||
error_message=unit.error_message or 'no_receipt_data',
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'empty'}
|
||||
if status != 'success':
|
||||
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.RECEIPT_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'receipt export failed')[:2000]; unit.finished_at = datetime.utcnow()
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_callback_received', aggregate_type='shipping_receipt_unit',
|
||||
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='failure',
|
||||
before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message},
|
||||
metadata={'callback_status': status},
|
||||
)
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'failed'}
|
||||
data = _read_receipt_callback_file(str(payload.get('file_path') or ''))
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
claimed = str(payload.get('sha256') or '').lower()
|
||||
if claimed and claimed != sha256:
|
||||
raise ValidationError('receipt callback sha256 mismatch', code='SHIPPING.RECEIPT_CALLBACK_SHA_MISMATCH')
|
||||
existing = ShippingReceiptReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
|
||||
if existing:
|
||||
return {'unit_run_id': unit.id, 'status': unit.status, 'file_id': existing.id, 'idempotent': True}
|
||||
filename = Path(str(payload.get('original_filename') or payload.get('file_path') or 'receipt.xlsx')).name
|
||||
storage_key = f'shipping/receipt-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx'
|
||||
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
record = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3))
|
||||
db.session.add(record)
|
||||
unit.status = 'success'; unit.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
|
||||
# [调拨证据同步·主链路] success 终态文件落地即解析写调拨待办(本分支专属;
|
||||
# empty/failed 分支不触发同步)。桥模式失败仅日志,绝不影响收料归档主链路
|
||||
# (语义见 in_transit_transfer/evidence_sync.sync_and_commit_for_callback)。
|
||||
try:
|
||||
from datetime import datetime as _dt
|
||||
def _finish_inbound_callback_terminal(
|
||||
unit: 'ShippingReceiptRpaUnitRun', *, ok: bool,
|
||||
file_no: str | None = None, file_sha256: str | None = None,
|
||||
error_code: str | None = None, error_message: str | None = None,
|
||||
) -> None:
|
||||
"""终态归档 commit 之后的业务收尾(on_terminal 钩子实现),顺序与拆分前逐点一致。
|
||||
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
核心逻辑:[STEP 1] 推进在途调拨来源任务(_advance_transfer_source_job,原 B3 接线);
|
||||
[STEP 2] 仅 success 终态触发调拨证据同步(桥模式失败仅日志,绝不影响收料归档主链路,
|
||||
语义见 in_transit_transfer/evidence_sync.sync_and_commit_for_callback);[STEP 3] 有排程
|
||||
run 时回写进度并归集终态(按需触发单元 schedule_run_id 为 NULL,跳过排程终态归集;
|
||||
文件通知不在此逐文件发送:统一由排程终态归集后一次性推送,与库存 RPA 同构)。
|
||||
"""
|
||||
_advance_transfer_source_job(
|
||||
unit, ok=ok, file_no=file_no, file_sha256=file_sha256,
|
||||
error_code=error_code, error_message=error_message,
|
||||
)
|
||||
if ok:
|
||||
# [调拨证据同步·主链路] success 终态文件落地即解析写调拨待办(本分支专属;
|
||||
# empty/failed 分支不触发同步)。
|
||||
try:
|
||||
from datetime import datetime as _dt
|
||||
|
||||
sync_and_commit_for_callback(
|
||||
source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
|
||||
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
|
||||
sync_and_commit_for_callback(
|
||||
source_code=unit.source_code, business_date=str(_dt.utcnow().date()), now=_dt.utcnow(),
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 —— 双保险:桥内部已吞异常
|
||||
current_app.logger.warning('[receipt-callback] transfer evidence sync failed: %s', exc)
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import (
|
||||
finalize_receipt_schedule_run_if_complete,
|
||||
refresh_receipt_schedule_run_progress,
|
||||
)
|
||||
# 按需触发单元无排程 run(schedule_run_id 为 NULL),跳过排程终态归集。
|
||||
# 文件通知不在此处逐文件发送:统一由排程终态归集后一次性推送(与库存 RPA 同构)。
|
||||
if unit.schedule_run_id:
|
||||
refresh_receipt_schedule_run_progress(unit.schedule_run_id)
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
|
||||
|
||||
|
||||
def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""幂等接收单个收料单元回调:委托 report_archive 原样归档,终态后执行业务桥收尾。
|
||||
|
||||
Args:
|
||||
payload: Worker 回调载荷;schema_version 必须等于 freight_rpa.inbound.v1。
|
||||
Returns:
|
||||
dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。
|
||||
"""
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
|
||||
return ingest_inbound_callback(payload, on_terminal=_finish_inbound_callback_terminal)
|
||||
@@ -1,56 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/receipt_rpa.py
|
||||
|
||||
用途:独立收料 RPA trigger 的目录解析与批量载荷原子写入。
|
||||
依赖:Flask current_app 配置 FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR。
|
||||
逻辑:freight_receipt_rpa_job / receipt_trigger_service 调用写 trigger;
|
||||
Worker 仅消费 shipping_receipt_rpa.v1,绝不回落到库存 trigger 目录。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def receipt_trigger_dir() -> Path | None:
|
||||
"""返回收料专用 trigger 目录;绝不回落到库存 trigger 目录。"""
|
||||
value = str(current_app.config.get('FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR') or '').strip()
|
||||
return Path(value) if value else None
|
||||
|
||||
|
||||
def write_receipt_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""写入收料批量 trigger;worker 仅允许消费 shipping_receipt_rpa.v1。"""
|
||||
trigger_dir = receipt_trigger_dir()
|
||||
if trigger_dir is None or not units:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'receipt'
|
||||
body = {
|
||||
'schema_version': 'shipping_receipt_rpa.v1', 'action': 'receipt_export_batch',
|
||||
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
|
||||
**(payload or {}),
|
||||
}
|
||||
path = trigger_dir / f'receipt_export_batch_{safe_run_no}.json'
|
||||
# Worker 轮询 *.json;必须先写入同目录临时文件后原子替换,不能让 Worker
|
||||
# 领取到半截 JSON 并误入 failed/,这不会影响库存 trigger 的既有实现。
|
||||
fd, temp_name = tempfile.mkstemp(prefix=f'.{path.stem}.', suffix='.tmp', dir=str(trigger_dir))
|
||||
try:
|
||||
with os.fdopen(fd, 'w', encoding='utf-8') as handle:
|
||||
handle.write(json.dumps(body, ensure_ascii=False, indent=2))
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_name, path)
|
||||
except Exception:
|
||||
try:
|
||||
Path(temp_name).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
return str(path)
|
||||
@@ -1,380 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/rpa.py
|
||||
|
||||
用途:管理库存导出与货代上传相关的 RPA 目录、触发文件和落盘辅助逻辑。
|
||||
依赖:Flask current_app 配置、Path/JSON/文件系统工具。
|
||||
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等上游模块调用本文件,与外部 RPA 文件投递目录进行交互。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
def _runtime_summary(mode: str) -> dict[str, str | bool]:
|
||||
"""将 browser/mock 规范化为前端安全展示摘要。"""
|
||||
normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser"
|
||||
mock_enabled = normalized == "mock"
|
||||
return {
|
||||
"mode": normalized,
|
||||
"label": "Mock RPA" if mock_enabled else "真实 RPA",
|
||||
"mock": mock_enabled,
|
||||
}
|
||||
|
||||
|
||||
def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]:
|
||||
"""返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。"""
|
||||
if isinstance(runtime, dict):
|
||||
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
|
||||
if mode in {"browser", "mock"}:
|
||||
return _runtime_summary(mode)
|
||||
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower()
|
||||
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def inventory_drop_dir() -> Path | None:
|
||||
"""RPA 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR")
|
||||
|
||||
|
||||
def inventory_processed_dir() -> Path | None:
|
||||
"""已处理库存文件归档子目录(drop_dir/processed)。"""
|
||||
base = inventory_drop_dir()
|
||||
if not base:
|
||||
return None
|
||||
return base / "processed"
|
||||
|
||||
|
||||
def inventory_trigger_dir() -> Path | None:
|
||||
"""RPA 库存导出触发 JSON 目录。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR")
|
||||
|
||||
|
||||
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
|
||||
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
|
||||
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
try:
|
||||
with open(temp_path, 'w', encoding='utf-8') as handle:
|
||||
json.dump(body, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, path)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def upload_queue_dir() -> Path | None:
|
||||
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR")
|
||||
|
||||
|
||||
def upload_trigger_dir() -> Path | None:
|
||||
"""RPA 货代上传触发 JSON 目录。"""
|
||||
return _path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR")
|
||||
|
||||
|
||||
def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""
|
||||
写入 RPA 库存导出触发文件 inventory_export_{task_no}.json。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径;目录未配置时返回 None。
|
||||
"""
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
if not trigger_dir:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
body = {
|
||||
"action": "inventory_export",
|
||||
"task_no": task_no,
|
||||
"run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}",
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
path = trigger_dir / f"inventory_export_{task_no}.json"
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
|
||||
|
||||
def write_inventory_export_batch_trigger(
|
||||
run_no: str,
|
||||
sources: list[dict[str, Any]],
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
写入批量库存导出 trigger(DSV/Crane 一次登录多 Warehouse)。
|
||||
【AI 触发时机】:定时排程或后台批量预热库存快照时调用。
|
||||
|
||||
Args:
|
||||
run_no: RPA 批次号,写入回调 audit。
|
||||
sources: build_rpa_inventory_source 构造的源列表。
|
||||
payload: 额外字段(trigger_type、schedule_run_id 等)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径。
|
||||
"""
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
if not trigger_dir or not sources:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
inventory_sources = []
|
||||
for source in sources:
|
||||
if not isinstance(source, dict) or not source.get("source_code"):
|
||||
continue
|
||||
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
configuration_test = str((payload or {}).get('trigger_type') or '') in {'configuration_test', 'configuration_test_batch'}
|
||||
trigger_source = get_rpa_trigger_inventory_source(
|
||||
str(source["source_code"]), enabled_only=not configuration_test,
|
||||
) or source
|
||||
source = {**source, **trigger_source}
|
||||
business_connector = str(source.get("connector_type") or "").strip().lower()
|
||||
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
|
||||
item = {
|
||||
"source_code": source.get("source_code"),
|
||||
"connector_type": business_connector,
|
||||
"worker_connector_type": worker_connector,
|
||||
"rpa_profile_code": source.get("rpa_profile_code"),
|
||||
"warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"),
|
||||
"login_url": source.get("login_url"),
|
||||
"entry_url": source.get("login_url"),
|
||||
"navigation": source.get("navigation") or {},
|
||||
"parameters": source.get("parameters") or [],
|
||||
"query": source.get("query") or {},
|
||||
"credential_envelope": source.get("credential_envelope") or {},
|
||||
# 配置测试回调据此将批次结果精确回写到各自站点运行。
|
||||
"validation_run_no": source.get("validation_run_no"),
|
||||
}
|
||||
# v2 逐源身份必须由后端显式写入,Worker 不得重新生成。
|
||||
for identity_key in (
|
||||
"callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version",
|
||||
"execution_id", "gate_id", "expected_warehouse_id", "lease_token",
|
||||
):
|
||||
if source.get(identity_key) is not None:
|
||||
item[identity_key] = source[identity_key]
|
||||
if not item.get('callback_id') and item.get('source_run_no'):
|
||||
item['callback_id'] = f"{item['source_run_no']}:C1"
|
||||
inventory_sources.append(item)
|
||||
if not inventory_sources:
|
||||
return None
|
||||
|
||||
body = {
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段
|
||||
"trigger_type": "scheduled",
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
"inventory_sources": inventory_sources,
|
||||
**(payload or {}),
|
||||
}
|
||||
safe_run = "".join(ch for ch in run_no if ch.isalnum() or ch in {"-", "_"}) or "batch"
|
||||
path = trigger_dir / f"inventory_export_batch_{safe_run}.json"
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
|
||||
|
||||
def inventory_rpa_batch_enabled() -> bool:
|
||||
"""是否启用按需单票走 batch trigger 统一路径(Flask config 优先于环境变量)。"""
|
||||
raw = current_app.config.get("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED")
|
||||
if raw is None:
|
||||
raw = os.getenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
return str(raw).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def build_on_demand_inventory_trigger_source(
|
||||
task_no: str,
|
||||
rpa_source: dict[str, Any],
|
||||
*,
|
||||
body: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造按需库存导出批次触发内的单源条目(含 Profile 凭据与逐源身份键)。
|
||||
【AI 触发时机】:单源 on-demand 触发与多候选合并批次触发(per_source_rpa_service)共用本构造,
|
||||
保证两条路径投递给 Worker 的输入契约完全一致。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
rpa_source: 调用方持有的非敏感源快照(含 source_code);DB 配置/Profile 存在时以其为准。
|
||||
body: 触发载荷,提供 callback_id/source_run_no/attempt_no/lease_token 等逐源身份键。
|
||||
|
||||
Returns:
|
||||
可直接传入 write_inventory_export_batch_trigger 的单源条目。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
source_code = str(rpa_source.get('source_code') or '').strip()
|
||||
rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source
|
||||
# Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。
|
||||
rpa_source = dict(rpa_source)
|
||||
business_connector = str(rpa_source.get('connector_type') or '').strip().lower()
|
||||
rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector))
|
||||
rpa_source.setdefault('entry_url', rpa_source.get('login_url'))
|
||||
rpa_source.setdefault('credential_envelope', {})
|
||||
source_item = dict(rpa_source)
|
||||
source_item.update({
|
||||
"source_code": source_code,
|
||||
"callback_id": body.get("callback_id") or (
|
||||
f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None
|
||||
),
|
||||
"task_no": task_no,
|
||||
# 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致
|
||||
# Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。
|
||||
"attempt_no": body.get("attempt_no") or body.get("attempt"),
|
||||
"source_run_no": body.get("source_run_no"),
|
||||
"candidate_set_id": body.get("candidate_set_id"),
|
||||
"candidate_set_version": body.get("candidate_set_version"),
|
||||
"execution_id": body.get("execution_id"),
|
||||
"gate_id": body.get("gate_id"),
|
||||
"expected_warehouse_id": body.get("expected_warehouse_id"),
|
||||
"lease_token": body.get("lease_token"),
|
||||
})
|
||||
return source_item
|
||||
|
||||
|
||||
def write_inventory_export_trigger_for_task(
|
||||
task_no: str,
|
||||
rpa_source: dict[str, Any],
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。
|
||||
|
||||
核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed,
|
||||
不再生成 legacy inventory_export trigger。
|
||||
"""
|
||||
body = dict(payload or {})
|
||||
if inventory_rpa_batch_enabled():
|
||||
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
|
||||
source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body)
|
||||
return write_inventory_export_batch_trigger(
|
||||
run_no,
|
||||
[source_item],
|
||||
payload={
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"trigger_type": "on_demand",
|
||||
"task_no": task_no,
|
||||
**body,
|
||||
},
|
||||
)
|
||||
raise ValidationError(
|
||||
'shipping inventory RPA v2 batch trigger is required',
|
||||
code='SHIPPING.INVENTORY_RPA_V2_REQUIRED',
|
||||
)
|
||||
|
||||
|
||||
def write_upload_trigger(
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
payload: dict[str, Any] | None = None,
|
||||
*,
|
||||
attempt_id: int | None = None,
|
||||
artifact_id: int | None = None,
|
||||
connector_type: str | None = None,
|
||||
upload_config: dict[str, Any] | None = None,
|
||||
upload_config_hash: str | None = None,
|
||||
login_url: str | None = None,
|
||||
credential_envelope: dict[str, Any] | None = None,
|
||||
callback_id: str | None = None,
|
||||
business_no: str | None = None,
|
||||
) -> tuple[str | None, str | None, str | None]:
|
||||
"""
|
||||
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
|
||||
【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。
|
||||
|
||||
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
|
||||
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
|
||||
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
|
||||
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
|
||||
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
export_file_path: 待上传发货 Excel 的服务端路径。
|
||||
payload: 附加字段(如 mode),与下列具名参数合并。
|
||||
attempt_id: 本次 Upload Attempt 主键。
|
||||
artifact_id: 当前上传目标 Artifact 主键。
|
||||
connector_type: 业务连接类型(dbs / crane)。
|
||||
upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。
|
||||
upload_config_hash: 该快照的 sha256,用于审计关联。
|
||||
login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。
|
||||
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
|
||||
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
|
||||
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
|
||||
|
||||
Returns:
|
||||
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
|
||||
失败时 (None, None, None)。
|
||||
"""
|
||||
queue = upload_queue_dir()
|
||||
trigger_dir = upload_trigger_dir()
|
||||
if not queue or not trigger_dir:
|
||||
return None, None, None
|
||||
queue.mkdir(parents=True, exist_ok=True)
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
src = Path(export_file_path)
|
||||
if not src.is_file():
|
||||
return None, None, None
|
||||
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
|
||||
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
|
||||
emit_no = str(business_no or '').strip() or task_no
|
||||
suffix = str(src.suffix or '.xlsx').lower()
|
||||
dest = queue / f"{emit_no}{suffix}"
|
||||
shutil.copy2(src, dest)
|
||||
|
||||
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
|
||||
body = {
|
||||
"action": "shipment_upload",
|
||||
"schema_version": "shipping_notice_upload_rpa.v1",
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"artifact_id": artifact_id,
|
||||
"callback_id": resolved_callback_id,
|
||||
"connector_type": str(connector_type or '').strip() or None,
|
||||
"upload_config": upload_config,
|
||||
"upload_config_hash": upload_config_hash,
|
||||
"login_url": login_url,
|
||||
"credential_envelope": credential_envelope,
|
||||
"file_path": str(dest),
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
trigger_path = trigger_dir / f"upload_{task_no}.json"
|
||||
_write_trigger_json_atomic(trigger_path, body)
|
||||
return str(dest), str(trigger_path), resolved_callback_id
|
||||
|
||||
|
||||
def find_latest_inventory_file() -> Path | None:
|
||||
"""在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。"""
|
||||
drop = inventory_drop_dir()
|
||||
if not drop or not drop.is_dir():
|
||||
return None
|
||||
candidates = [
|
||||
p for p in drop.iterdir()
|
||||
if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"}
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
return max(candidates, key=lambda p: p.stat().st_mtime)
|
||||
@@ -0,0 +1,103 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_sinks.py
|
||||
|
||||
用途:onhand(在手库存)与 inbound(入站,原收料)RPA 回调的业务 sink 注册适配层——把
|
||||
/api/freight-rpa/* 蓝图的 dispatch_sink kind 接到真实业务处理器。
|
||||
依赖:freight_rpa.common.callback_sinks(register_sink)、inventory_rpa_workflow(快照落盘/
|
||||
批量 ingest)、per_source_rpa_service(Attempt 认领)、inventory_configuration_test(配置测试)、
|
||||
receipt_report_storage(inbound 归档入口 + 业务桥留守)、schedule.freight_inbound_rpa_finalize
|
||||
(inbound 进度/领取处理器,Task 11 已随排程壳平移改名)。
|
||||
逻辑:由组合根(app.create_app)调用 register_onhand_sinks() / register_inbound_sinks() 完成
|
||||
注册(幂等,重复注册覆盖)。各 sink 仅做两件事:① 复刻旧 shipping-notice rpa 回调端点
|
||||
端点的响应 envelope(逐 kind 对齐,禁止统一 envelope);② 对 onhand-repair 注入旧路由
|
||||
等价的 payload['repair']=True。业务事务边界完全由被包装的域内函数保持,本层不碰 db。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def _bare(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
|
||||
"""旧端点直接 jsonify(业务函数返回值)——裸业务 dict envelope(inventory-ready 同款)。"""
|
||||
|
||||
def _sink(**payload: Any) -> dict[str, Any]:
|
||||
return handler(payload)
|
||||
|
||||
return _sink
|
||||
|
||||
|
||||
def _ok_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
|
||||
"""旧 /rpa/inventory-configuration-test-* 的 envelope:{'status':'ok','data':业务结果}。"""
|
||||
|
||||
def _sink(**payload: Any) -> dict[str, Any]:
|
||||
return {'status': 'ok', 'data': handler(payload)}
|
||||
|
||||
return _sink
|
||||
|
||||
|
||||
def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
|
||||
"""旧 /rpa/inventory-batch-claimed 的 envelope:{'success':True,'data':业务结果}。"""
|
||||
|
||||
def _sink(**payload: Any) -> dict[str, Any]:
|
||||
return {'success': True, 'data': handler(payload)}
|
||||
|
||||
return _sink
|
||||
|
||||
|
||||
def _onhand_repair_sink(**payload: Any) -> dict[str, Any]:
|
||||
"""受控库存回调修复:等价旧 /rpa/inventory-repair——payload['repair']=True 后走 batch-ready ingest。"""
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
|
||||
payload['repair'] = True
|
||||
return rpa_report_inventory_batch(payload)
|
||||
|
||||
|
||||
def register_onhand_sinks() -> None:
|
||||
"""组合根入口:注册全部 onhand 回调 sink(幂等;create_app 每次启动调用)。
|
||||
|
||||
核心逻辑:kind 命名 = /api/freight-rpa/* 回调路由名去前缀;被包装函数全部住在
|
||||
shipping_notice(业务落盘留守域),与 Task 4 裁定一致——认领(claim_inventory_batch)
|
||||
与批量编排留 per_source_rpa_service,本层只做 envelope 复刻与分发接线。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.shipping_notice import inventory_configuration_test, inventory_rpa_workflow
|
||||
from app.services.shipping_notice.per_source_rpa_service import claim_inventory_batch
|
||||
|
||||
register_sink('onhand-ready', _bare(inventory_rpa_workflow.rpa_report_inventory))
|
||||
register_sink('onhand-batch-ready', _bare(inventory_rpa_workflow.rpa_report_inventory_batch))
|
||||
register_sink('onhand-batch-claimed', _success_data_envelope(claim_inventory_batch))
|
||||
register_sink('onhand-batch-progress', _bare(inventory_rpa_workflow.report_inventory_batch_progress))
|
||||
register_sink(
|
||||
'onhand-configuration-test-start',
|
||||
_ok_data_envelope(inventory_configuration_test.report_batch_test_progress),
|
||||
)
|
||||
register_sink(
|
||||
'onhand-configuration-test-analyze',
|
||||
_ok_data_envelope(inventory_configuration_test.report_test_export),
|
||||
)
|
||||
register_sink(
|
||||
'onhand-configuration-test-complete',
|
||||
_ok_data_envelope(inventory_configuration_test.report_batch_test_exports),
|
||||
)
|
||||
register_sink('onhand-repair', _onhand_repair_sink)
|
||||
|
||||
|
||||
def register_inbound_sinks() -> None:
|
||||
"""组合根入口:注册全部 inbound(收料)回调 sink(幂等;create_app 每次启动调用)。
|
||||
|
||||
核心逻辑:kind 命名 = /api/freight-rpa/* 回调路由名去前缀。inbound-batch-ready 的
|
||||
业务处理器 = receipt_report_storage.ingest_receipt_callback(归档能力下沉
|
||||
freight_rpa.inbound.report_archive 后的域内入口,内部把「终态推进在途调拨来源任务
|
||||
+ 调拨证据同步 + 排程终态归集」业务桥作为 on_terminal 钩子注入——业务桥留守
|
||||
shipping_notice,与拆分前调用方向一致);unit/batch-progress 处理器仍住排程壳
|
||||
(Task 11 已平移改名为 schedule.freight_inbound_rpa_finalize),按「处理函数住在哪个包」
|
||||
由本层接注册表。三个 kind 旧端点 envelope 均为 {'success':True,'data':...},逐字复刻。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.schedule import freight_inbound_rpa_finalize
|
||||
from app.services.shipping_notice import receipt_report_storage
|
||||
|
||||
register_sink('inbound-batch-ready', _success_data_envelope(receipt_report_storage.ingest_receipt_callback))
|
||||
register_sink('inbound-unit-progress', _success_data_envelope(freight_inbound_rpa_finalize.mark_receipt_unit_processing))
|
||||
register_sink('inbound-batch-progress', _success_data_envelope(freight_inbound_rpa_finalize.report_receipt_batch_progress))
|
||||
@@ -36,7 +36,7 @@ def shipping_recovery_tick() -> int:
|
||||
# 根据最新 Attempt/Gate 状态刷新按钮与阻断原因。
|
||||
inventory_timeout_seconds = max(int(getattr(
|
||||
current_app.config,
|
||||
'FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS',
|
||||
'FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS',
|
||||
900,
|
||||
) or 900), 1)
|
||||
inventory_scan_count = _scan_stale_inventory_attempts(
|
||||
|
||||
@@ -83,7 +83,7 @@ def auto_rpa_inventory_enabled() -> bool:
|
||||
|
||||
def rpa_inventory_timeout_seconds() -> int:
|
||||
"""RPA 库存导出等待超时秒数。"""
|
||||
return cfg_int("FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS", 900, min_value=5)
|
||||
return cfg_int("FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS", 900, min_value=5)
|
||||
|
||||
|
||||
def auto_mapping_allow_llm() -> bool:
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""tt16:RPA 排程任务 key 更名(批次 R,随代码同窗口发布)
|
||||
|
||||
Revision ID: tt16c7d8e9f0a1b2
|
||||
Revises: tt16a7b8c9d0e1f2
|
||||
Create Date: 2026-10-16
|
||||
|
||||
用途:schedule_tasks.platform_api_path 存量的三个 RPA 平台 job key 入站化改名——
|
||||
shipping-inventory-rpa→freight-rpa-onhand(在手/库存)、
|
||||
freight-receipt-rpa→freight-rpa-inbound(入站/收料)、
|
||||
freight-receipt-rpa-retention→freight-rpa-inbound-retention(入站归档保留期清理),
|
||||
与 job_registry.py / freight_onhand_rpa_*、freight_inbound_rpa_* 排程壳改名同窗口发布。
|
||||
依赖:实施时 flask db heads 的单 head 为 tt16a7b8c9d0e1f2(调拨域迁移,其上游即
|
||||
tt15b6a7b8c9d0);本迁移若直挂 tt15 会产生双 head,故按单 head 纪律链在其上。
|
||||
逻辑:列为 platform_api_path(String(500),承载归一化 job key——自 b9c0d1e2f3a4 起
|
||||
排程表无独立 job_key 列,运行时一律读写 platform_api_path,见
|
||||
schedule_contract.normalize_job_key);三键 UPDATE;
|
||||
options_source 键(shipping_inventory_sources / shipping_receipt_sources)
|
||||
绑定业务表名,本批不动(批次 S)。
|
||||
降级:反向映射对称 UPDATE,逐键还原;无表结构变更,SQLite/PG 语句通用。
|
||||
Fix round 1:SQL 列名由计划骨架误写的 job_key 修正为真实列 platform_api_path
|
||||
(计划骨架错误,控制方已认领;契约测试桩表同步改真实列名)。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "tt16c7d8e9f0a1b2"
|
||||
down_revision = "tt16a7b8c9d0e1f2"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# 升级方向三键对照;downgrade 取反。键值与 job_registry.register_platform_job 一致。
|
||||
_MAPPING = {
|
||||
"shipping-inventory-rpa": "freight-rpa-onhand",
|
||||
"freight-receipt-rpa": "freight-rpa-inbound",
|
||||
"freight-receipt-rpa-retention": "freight-rpa-inbound-retention",
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""job key 三键前向改名:platform_api_path 旧行 UPDATE 为新键(无表结构变更)。"""
|
||||
for old_key, new_key in _MAPPING.items():
|
||||
op.execute(
|
||||
f"UPDATE schedule_tasks SET platform_api_path='{new_key}' "
|
||||
f"WHERE platform_api_path='{old_key}'"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""job key 三键反向还原:platform_api_path 新键 UPDATE 回旧键(与 upgrade 对称)。"""
|
||||
for old_key, new_key in _MAPPING.items():
|
||||
op.execute(
|
||||
f"UPDATE schedule_tasks SET platform_api_path='{old_key}' "
|
||||
f"WHERE platform_api_path='{new_key}'"
|
||||
)
|
||||
@@ -0,0 +1,306 @@
|
||||
"""
|
||||
tests/api/test_freight_rpa_api.py
|
||||
|
||||
用途:/api/freight-rpa/* 回调蓝图的 HTTP 契约测试(批次 R Task 8 建立、Task 9 补 sink 注册后契约)。
|
||||
依赖:tests/conftest.py 的 app/client fixture;freight_rpa.common.callback_sinks。
|
||||
逻辑:锁定四条关键契约——① 心跳新路由鉴权必备;② 旧 shipping-notice rpa 回调前缀无双路由
|
||||
(脏回调显式 404);③ 未注册 sink 的 kind 显式 404 且错误码 FREIGHT_RPA.SINK_NOT_REGISTERED
|
||||
(分发层语义,用自造 kind 单测锁定);④ Task 9 组合根注册真实 sink 后,8 个 onhand 端点
|
||||
的响应 envelope 与旧 shipping-notice rpa 回调端点逐 kind 逐字一致(禁止统一 envelope):
|
||||
inventory-ready / batch-ready / batch-progress 返回裸业务 tool_response dict,
|
||||
batch-claimed 返回 {'success':True,'data':...},configuration-test-* 返回 {'status':'ok','data':...};
|
||||
⑤ Task 10 注册 inbound sink 后,3 个 inbound 端点维持 {'success':True,'data':...} 旧形态,
|
||||
业务校验路径(400/404 错误码)与拆分前直连逐字一致。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
TEST_TOOL_KEY = 'test-tool-key'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tool_auth_headers(app):
|
||||
"""以测试 integration key 生成 Bearer 鉴权头(与生产 Worker 的 Bearer 形态一致)。"""
|
||||
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY
|
||||
return {'Authorization': f'Bearer {TEST_TOOL_KEY}'}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def terminal_configuration_test_run(app):
|
||||
"""预置一个已终态的配置测试运行 + 批次,供 configuration-test 三端点走 OK envelope 路径。"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryValidationBatch,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
batch = ShippingInventoryValidationBatch(batch_no='CONFIG-BATCH-ENV-TEST', status='running', total_count=1)
|
||||
db.session.add(batch)
|
||||
db.session.flush()
|
||||
run = ShippingInventoryConfigurationTestRun(
|
||||
run_no='CONFIG-ENV-TEST-RUN', validation_batch_id=batch.id, inventory_source_id=source.id,
|
||||
source_config_version=source.config_version,
|
||||
rpa_profile_config_version=source.rpa_profile.config_version,
|
||||
status='completed', stage='current_profile_verified', result_json={},
|
||||
completed_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
return {'batch_id': batch.id, 'run_no': run.run_no}
|
||||
|
||||
|
||||
def test_heartbeat_requires_auth(client, app):
|
||||
"""heartbeat 走新路由且鉴权必备:无 Header 必须 401,绝不能匿名写心跳。"""
|
||||
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY
|
||||
assert client.post("/api/freight-rpa/heartbeat", json={}).status_code == 401
|
||||
|
||||
|
||||
def test_legacy_rpa_routes_removed(client):
|
||||
"""旧路由已死(无兼容层,脏回调显式 404):旧 URL 不得再被任何蓝图接住。"""
|
||||
assert client.post("/api/shipping-notice" + "/rpa/heartbeat", json={}).status_code == 404
|
||||
|
||||
|
||||
def test_onhand_ready_registered_sink_returns_tool_envelope(client, tool_auth_headers):
|
||||
"""Task 9 注册 sink 后 onhand-ready 可达:空载荷走业务失败分支,envelope 与旧
|
||||
/rpa/inventory-ready 的裸 tool_response dict 逐字一致(status/message/data 顶层键)。"""
|
||||
resp = client.post("/api/freight-rpa/onhand-ready", json={}, headers=tool_auth_headers)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
# [断言意图] 旧端点 = jsonify(rpa_report_inventory(payload)),tool_response 顶层键固定为
|
||||
# status/message/data;失败文案必须保留旧值「未找到任务编号」。
|
||||
assert set(body) == {"status", "message", "data"}
|
||||
assert body["status"] == "failed"
|
||||
assert body["message"] == "未找到任务编号"
|
||||
assert body["data"] == {}
|
||||
|
||||
|
||||
def test_unauthenticated_sink_endpoint_is_401_not_404(client, app):
|
||||
"""鉴权先于分发:未携带 key 打 sink 端点是 401(未授权),不能泄漏 404 分发语义。"""
|
||||
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = TEST_TOOL_KEY
|
||||
assert client.post("/api/freight-rpa/onhand-ready", json={}).status_code == 401
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 9 envelope 逐 kind 契约:以 git HEAD 旧端点实现为基准写死期望 shape。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_onhand_batch_ready_envelope_matches_legacy(client, tool_auth_headers):
|
||||
"""onhand-batch-ready(旧 /rpa/inventory-batch-ready = jsonify(rpa_report_inventory(...))):
|
||||
裸业务 dict;schema 非法分支 data 内 transport_status/business_status/error_code 三键。"""
|
||||
resp = client.post("/api/freight-rpa/onhand-batch-ready", json={}, headers=tool_auth_headers)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
assert set(body) == {"status", "message", "data"}
|
||||
assert body["status"] == "failed"
|
||||
assert body["message"] == "callback_schema_invalid"
|
||||
assert body["data"] == {
|
||||
"transport_status": "invalid",
|
||||
"business_status": "rejected",
|
||||
"error_code": "callback_schema_invalid",
|
||||
}
|
||||
|
||||
|
||||
def test_onhand_batch_claimed_envelope_matches_legacy(client, tool_auth_headers):
|
||||
"""onhand-batch-claimed(旧 /rpa/inventory-batch-claimed):
|
||||
envelope = {'success': True, 'data': claim_inventory_batch(payload)},禁止裸 dict。"""
|
||||
resp = client.post("/api/freight-rpa/onhand-batch-claimed", json={}, headers=tool_auth_headers)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
# [断言意图] 旧端点包裹 {'success': True, 'data': ...};schema 非法时业务层返回三键拒绝体。
|
||||
assert set(body) == {"success", "data"}
|
||||
assert body["success"] is True
|
||||
assert body["data"] == {
|
||||
"transport_status": "invalid",
|
||||
"business_status": "rejected",
|
||||
"error_code": "callback_schema_invalid",
|
||||
}
|
||||
|
||||
|
||||
def test_onhand_batch_progress_envelope_matches_legacy(client, tool_auth_headers):
|
||||
"""onhand-batch-progress(旧 /rpa/inventory-batch-progress):
|
||||
裸业务 dict;schema 非法分支 data.progress_status='invalid'。"""
|
||||
resp = client.post("/api/freight-rpa/onhand-batch-progress", json={}, headers=tool_auth_headers)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
assert set(body) == {"status", "message", "data"}
|
||||
assert body["status"] == "failed"
|
||||
assert body["message"] == "callback_schema_invalid"
|
||||
assert body["data"] == {
|
||||
"progress_status": "invalid",
|
||||
"error_code": "callback_schema_invalid",
|
||||
}
|
||||
|
||||
|
||||
def test_onhand_configuration_test_start_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run):
|
||||
"""onhand-configuration-test-start(旧 /rpa/inventory-configuration-test-batch-progress =
|
||||
report_batch_test_progress):envelope = {'status':'ok','data':测试运行投影}。"""
|
||||
resp = client.post(
|
||||
"/api/freight-rpa/onhand-configuration-test-start",
|
||||
json={
|
||||
'validation_batch_id': terminal_configuration_test_run['batch_id'],
|
||||
'validation_run_no': terminal_configuration_test_run['run_no'],
|
||||
},
|
||||
headers=tool_auth_headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
# [断言意图] 旧端点 = jsonify({'status':'ok','data': report_batch_test_progress(...)});
|
||||
# 终态 run 早退分支返回 _payload(run)(含 id/run_no/status)。
|
||||
assert set(body) == {"status", "data"}
|
||||
assert body["status"] == "ok"
|
||||
assert body["data"]["run_no"] == terminal_configuration_test_run['run_no']
|
||||
assert body["data"]["status"] == "completed"
|
||||
|
||||
|
||||
def test_onhand_configuration_test_analyze_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run):
|
||||
"""onhand-configuration-test-analyze(旧 /rpa/inventory-configuration-test-ready =
|
||||
report_test_export):envelope = {'status':'ok','data':测试运行投影}。"""
|
||||
resp = client.post(
|
||||
"/api/freight-rpa/onhand-configuration-test-analyze",
|
||||
json={'run_no': terminal_configuration_test_run['run_no']},
|
||||
headers=tool_auth_headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
assert set(body) == {"status", "data"}
|
||||
assert body["status"] == "ok"
|
||||
assert body["data"]["run_no"] == terminal_configuration_test_run['run_no']
|
||||
|
||||
|
||||
def test_onhand_configuration_test_complete_envelope_matches_legacy(client, tool_auth_headers, terminal_configuration_test_run):
|
||||
"""onhand-configuration-test-complete(旧 /rpa/inventory-configuration-test-batch-ready =
|
||||
report_batch_test_exports):envelope = {'status':'ok','data':批次投影+updated/ignored 计数}。"""
|
||||
resp = client.post(
|
||||
"/api/freight-rpa/onhand-configuration-test-complete",
|
||||
json={'validation_batch_id': terminal_configuration_test_run['batch_id'], 'results': []},
|
||||
headers=tool_auth_headers,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
assert set(body) == {"status", "data"}
|
||||
assert body["status"] == "ok"
|
||||
assert body["data"]["updated_count"] == 0
|
||||
assert body["data"]["ignored_count"] == 0
|
||||
assert body["data"]["batch_no"] == "CONFIG-BATCH-ENV-TEST"
|
||||
|
||||
|
||||
def test_onhand_repair_envelope_matches_legacy(client, tool_auth_headers):
|
||||
"""onhand-repair(旧 /rpa/inventory-repair = repair=True 后 jsonify(rpa_report_inventory(...))):
|
||||
裸业务 dict,schema 非法分支与 batch-ready 同形。"""
|
||||
resp = client.post("/api/freight-rpa/onhand-repair", json={}, headers=tool_auth_headers)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
assert set(body) == {"status", "message", "data"}
|
||||
assert body["status"] == "failed"
|
||||
assert body["data"] == {
|
||||
"transport_status": "invalid",
|
||||
"business_status": "rejected",
|
||||
"error_code": "callback_schema_invalid",
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 10 inbound sink 注册后契约:三端点改 dispatch_sink 后 envelope 与拆分前直连
|
||||
# 形态(jsonify({'success': True, 'data': 业务结果}))逐字一致,禁止裸 dict / 统一 envelope。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_inbound_unit_progress_envelope_matches_legacy(client, tool_auth_headers):
|
||||
"""inbound-unit-progress(旧直连 jsonify({'success':True,'data':mark_receipt_unit_processing(p)})):
|
||||
schema 非法分支 data={'updated':False,'reason':'callback_schema_invalid'},证明 sink 已注册
|
||||
(未注册会是 404 FREIGHT_RPA.SINK_NOT_REGISTERED)且 envelope 未漂移。"""
|
||||
resp = client.post("/api/freight-rpa/inbound-unit-progress", json={}, headers=tool_auth_headers)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
assert set(body) == {"success", "data"}
|
||||
assert body["success"] is True
|
||||
assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"}
|
||||
|
||||
|
||||
def test_inbound_batch_progress_envelope_matches_legacy(client, tool_auth_headers):
|
||||
"""inbound-batch-progress(旧直连同款 envelope):schema 非法分支与 unit-progress 同形。"""
|
||||
resp = client.post("/api/freight-rpa/inbound-batch-progress", json={}, headers=tool_auth_headers)
|
||||
assert resp.status_code == 200
|
||||
body = resp.get_json()
|
||||
assert set(body) == {"success", "data"}
|
||||
assert body["success"] is True
|
||||
assert body["data"] == {"updated": False, "reason": "callback_schema_invalid"}
|
||||
|
||||
|
||||
def test_inbound_batch_ready_schema_invalid_reaches_business_validation(client, tool_auth_headers):
|
||||
"""inbound-batch-ready sink 已注册:schema 非法穿透到业务校验(400 +
|
||||
SHIPPING.RECEIPT_CALLBACK_INVALID),而非未注册 404;错误 envelope 与拆分前同形
|
||||
(旧端点在 jsonify 之前由 ingest 抛 ValidationError → 全局 AppError handler)。"""
|
||||
resp = client.post("/api/freight-rpa/inbound-batch-ready", json={}, headers=tool_auth_headers)
|
||||
assert resp.status_code == 400
|
||||
body = resp.get_json()
|
||||
assert body["success"] is False
|
||||
assert body["error"]["code"] == "SHIPPING.RECEIPT_CALLBACK_INVALID"
|
||||
|
||||
|
||||
def test_inbound_batch_ready_unknown_unit_is_404(client, tool_auth_headers):
|
||||
"""inbound-batch-ready 未知 callback_id:404 + SHIPPING.RECEIPT_UNIT_NOT_FOUND,
|
||||
与拆分前 ingest 直连时的 NotFoundError 路径逐字一致。"""
|
||||
resp = client.post(
|
||||
"/api/freight-rpa/inbound-batch-ready",
|
||||
json={"schema_version": "freight_rpa.inbound.v1", "callback_id": "no-such-callback"},
|
||||
headers=tool_auth_headers,
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
body = resp.get_json()
|
||||
assert body["error"]["code"] == "SHIPPING.RECEIPT_UNIT_NOT_FOUND"
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_dispatch_sink_unregistered_raises_app_error():
|
||||
"""注册表单测:未注册 kind 抛 AppError(404, FREIGHT_RPA.SINK_NOT_REGISTERED),不静默吞回调。"""
|
||||
from app.core.errors import AppError
|
||||
from app.services.freight_rpa.common.callback_sinks import dispatch_sink, register_sink
|
||||
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
def _handler(**payload):
|
||||
seen.update(payload)
|
||||
return {'ok': True}
|
||||
|
||||
register_sink('unit-test-kind', _handler)
|
||||
assert dispatch_sink('unit-test-kind', callback_id='cb-1') == {'ok': True}
|
||||
assert seen == {'callback_id': 'cb-1'}
|
||||
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
dispatch_sink('never-registered-kind', callback_id='cb-2')
|
||||
assert excinfo.value.code == 'FREIGHT_RPA.SINK_NOT_REGISTERED'
|
||||
assert excinfo.value.http_status == 404
|
||||
|
||||
|
||||
def test_admin_rpa_profiles_routes_migrated(app, client):
|
||||
"""admin rpa-profiles 已迁 /api/admin/freight-rpa/*:管理员可达、旧 URL 404、普通用户 403。"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
db.session.add_all([
|
||||
User(username='rpa-admin', email='rpa-admin@example.com', role='admin', status='active'),
|
||||
User(username='rpa-user', email='rpa-user@example.com', role='user', status='active'),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
admin_headers = {'X-Username': 'rpa-admin', 'X-Role': 'admin'}
|
||||
user_headers = {'X-Username': 'rpa-user', 'X-Role': 'user'}
|
||||
|
||||
migrated = client.get('/api/admin/freight-rpa/rpa-profiles', headers=admin_headers)
|
||||
assert migrated.status_code == 200
|
||||
assert migrated.get_json()['success'] is True
|
||||
|
||||
# [断言意图] 普通用户必须被 require_admin 拦截(迁移未放松权限)。
|
||||
assert client.get('/api/admin/freight-rpa/rpa-profiles', headers=user_headers).status_code == 403
|
||||
|
||||
# [断言意图] 旧 admin URL 无双路由:脏调用显式 404(前端已同窗口切换)。
|
||||
assert client.get('/api/admin/shipping-notice/rpa-profiles', headers=admin_headers).status_code == 404
|
||||
@@ -94,11 +94,11 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
|
||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||||
lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.assert_freight_upload_rpa_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat.assert_freight_upload_rpa_ready",
|
||||
lambda: None,
|
||||
)
|
||||
return
|
||||
@@ -111,10 +111,10 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
|
||||
from app.services.freight_rpa.common.worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
|
||||
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import reset_rpa_worker_alert_state_for_tests
|
||||
|
||||
reset_rpa_worker_alert_state_for_tests()
|
||||
|
||||
@@ -475,10 +475,10 @@ def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]:
|
||||
|
||||
|
||||
def v2_inventory_batch_payload(payload: dict) -> dict:
|
||||
"""测试构造器:补齐冻结 shipping_inventory_rpa.v2 回调 envelope。"""
|
||||
"""测试构造器:补齐冻结 freight_rpa.onhand.v1 回调 envelope。"""
|
||||
body = dict(payload or {})
|
||||
run_no = str(body.get('batch_run_no') or body.get('run_no') or '').strip()
|
||||
body.setdefault('schema_version', 'shipping_inventory_rpa.v2')
|
||||
body.setdefault('schema_version', 'freight_rpa.onhand.v1')
|
||||
body.setdefault('callback_id', f'test-callback:{run_no or "unknown"}')
|
||||
body.setdefault('batch_run_no', run_no)
|
||||
return body
|
||||
@@ -498,7 +498,7 @@ def rpa_callback_payload(
|
||||
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
|
||||
source = get_database_inventory_source(source_code) or {}
|
||||
return {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": f"test-callback:{run_no}",
|
||||
"task_id": task.task_no,
|
||||
"status": status,
|
||||
|
||||
@@ -30,7 +30,7 @@ def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycl
|
||||
"""
|
||||
from app.services.in_transit_transfer import inbound_callback_bridge
|
||||
from app.services.schedule import queue_service
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat_alert
|
||||
from app.services.freight_rpa.common import worker_heartbeat_alert
|
||||
|
||||
calls: list[int] = []
|
||||
|
||||
@@ -42,7 +42,7 @@ def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycl
|
||||
return {"skipped": True, "reason": "test_stub"}
|
||||
|
||||
monkeypatch.setattr(inbound_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
|
||||
monkeypatch.setattr(rpa_worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
|
||||
monkeypatch.setattr(worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
|
||||
monkeypatch.setattr(queue_service, "_worker_initialized", False)
|
||||
|
||||
assert prepare_schedule_queue() == 0
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""freight_rpa 包 import 边界适应度测试。
|
||||
|
||||
用途:锁死阶段 A 验收标准——freight_rpa 不寄生业务编排。
|
||||
依赖:app/services/freight_rpa 包、ast。
|
||||
逻辑:遍历包内 .py 的 import(ast 解析),命中禁列即失败;
|
||||
白名单是 RPA 归档/凭据所需的两块业务工具(阶段 B 收敛为零)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from pathlib import Path
|
||||
|
||||
PKG = Path(__file__).resolve().parents[3] / "app" / "services" / "freight_rpa"
|
||||
|
||||
ALLOWED_SHIPPING_NOTICE = {
|
||||
"app.services.shipping_notice.audit_service",
|
||||
"app.services.shipping_notice.file_assets",
|
||||
}
|
||||
|
||||
|
||||
def _imported_modules(path: Path) -> set[str]:
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
mods: set[str] = set()
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
mods.update(a.name for a in node.names)
|
||||
elif isinstance(node, ast.ImportFrom) and node.module:
|
||||
mods.add(node.module)
|
||||
return mods
|
||||
|
||||
|
||||
def test_freight_rpa_import_boundary():
|
||||
assert PKG.exists(), "freight_rpa 包不存在"
|
||||
violations: list[str] = []
|
||||
for py in PKG.rglob("*.py"):
|
||||
for mod in _imported_modules(py):
|
||||
if mod.startswith("app.services.shipping_notice") and mod not in ALLOWED_SHIPPING_NOTICE:
|
||||
violations.append(f"{py.name}: {mod}")
|
||||
assert not violations, "freight_rpa 违规 import:\n" + "\n".join(violations)
|
||||
+41
-41
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/tests/test_rpa_worker_heartbeat.py
|
||||
backend/tests/services/freight_rpa/test_worker_heartbeat.py
|
||||
|
||||
用途:货代库存/上传 RPA Worker 心跳存储、共享目录校验、就绪检查与 API 契约单测。
|
||||
依赖:rpa_worker_heartbeat、shipping_notice_tools heartbeat 路由。
|
||||
依赖:freight_rpa.common.worker_heartbeat、shipping_notice_tools heartbeat 路由。
|
||||
逻辑:覆盖跨平台 scope、哨兵、Redis 策略、环境匹配、货代上传就绪与 fail-fast 断言。
|
||||
"""
|
||||
|
||||
@@ -14,10 +14,10 @@ from typing import Any
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
FREIGHT_UPLOAD_CAPABILITY,
|
||||
INVENTORY_EXPORT_CAPABILITY,
|
||||
RECEIPT_EXPORT_CAPABILITY,
|
||||
ONHAND_EXPORT_CAPABILITY,
|
||||
INBOUND_EXPORT_CAPABILITY,
|
||||
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE,
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
@@ -53,7 +53,7 @@ def _heartbeat_payload(
|
||||
"worker_id": worker_id,
|
||||
"hostname": "WIN-RPA-HOST",
|
||||
"environment": environment or resolve_backend_rpa_environment(),
|
||||
"capabilities": capabilities or [INVENTORY_EXPORT_CAPABILITY],
|
||||
"capabilities": capabilities or [ONHAND_EXPORT_CAPABILITY],
|
||||
"status": "idle",
|
||||
"trigger_dir": trigger_dir,
|
||||
"drop_dir": str(trigger_dir).replace("triggers", "drop"),
|
||||
@@ -68,7 +68,7 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id=scope_id)
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
@@ -133,7 +133,7 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
@@ -155,11 +155,11 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
|
||||
"""生产策略要求 Redis 时,写入失败应抛存储不可用。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
|
||||
"app.services.freight_rpa.common.worker_heartbeat._redis_store_worker",
|
||||
lambda _worker: False,
|
||||
)
|
||||
|
||||
@@ -172,20 +172,20 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
|
||||
|
||||
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
|
||||
"""fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.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
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
@@ -205,8 +205,8 @@ def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path
|
||||
def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
|
||||
"""收料 fail-fast 应附带 reasons,且与库存同口径要求共享哨兵。"""
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
assert_receipt_rpa_worker_ready,
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
@@ -217,7 +217,7 @@ def test_assert_receipt_rpa_worker_ready_includes_reason_details(app, tmp_path,
|
||||
trigger_dir = tmp_path / 'receipt_triggers'
|
||||
trigger_dir.mkdir()
|
||||
app.config['ENV_NAME'] = 'test'
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(trigger_dir)
|
||||
app.config['FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR'] = str(trigger_dir)
|
||||
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED'] = True
|
||||
app.config['FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK'] = True
|
||||
app.config['FREIGHT_RPA_WORKER_MOCK'] = 'false'
|
||||
@@ -249,7 +249,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path,
|
||||
)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.time.time",
|
||||
"app.services.freight_rpa.common.worker_heartbeat.time.time",
|
||||
lambda: base_now + 120,
|
||||
)
|
||||
result = check_inventory_rpa_worker_ready()
|
||||
@@ -258,7 +258,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path,
|
||||
|
||||
|
||||
def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
|
||||
"""POST /rpa/heartbeat 应写入心跳并返回 ok。"""
|
||||
"""POST /api/freight-rpa/heartbeat 应写入心跳并返回 ok(旧 shipping-notice 路由已删)。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
@@ -266,7 +266,7 @@ def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/rpa/heartbeat",
|
||||
"/api/freight-rpa/heartbeat",
|
||||
headers={"X-Integration-Key": "test-tool-key"},
|
||||
json=payload,
|
||||
)
|
||||
@@ -283,7 +283,7 @@ def test_rpa_heartbeat_api_rejects_missing_auth(client, app, tmp_path):
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post("/api/shipping-notice/rpa/heartbeat", json=payload)
|
||||
res = client.post("/api/freight-rpa/heartbeat", json=payload)
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
@@ -295,7 +295,7 @@ def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post(
|
||||
"/api/shipping-notice/rpa/heartbeat",
|
||||
"/api/freight-rpa/heartbeat",
|
||||
headers={"X-Integration-Key": "wrong-key"},
|
||||
json=payload,
|
||||
)
|
||||
@@ -306,9 +306,9 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
|
||||
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.schedule.freight_onhand_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.freight_rpa.common import worker_heartbeat as heartbeat_module
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
@@ -326,7 +326,7 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
|
||||
schedule_no="SCH-HB-OFFLINE",
|
||||
name="货代库存每日导出",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
enabled=True,
|
||||
@@ -364,7 +364,7 @@ def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_pat
|
||||
raise ConnectionError("redis read failed")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
|
||||
@@ -400,7 +400,7 @@ def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch)
|
||||
return bucket.get(key)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
@@ -417,13 +417,13 @@ def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch)
|
||||
|
||||
def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path):
|
||||
"""未显式配置 scope 时,可从 /mnt/hxops-rpa-* 挂载路径推导。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import shared_scope_id
|
||||
from app.services.freight_rpa.common.worker_heartbeat import shared_scope_id
|
||||
|
||||
trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
|
||||
trigger_dir.mkdir(parents=True)
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
assert shared_scope_id() == "hxops-rpa-test-data"
|
||||
@@ -457,7 +457,7 @@ def test_check_freight_upload_rpa_ready_requires_freight_upload_capability(app,
|
||||
_heartbeat_payload(
|
||||
trigger_dir=str(upload_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[INVENTORY_EXPORT_CAPABILITY],
|
||||
capabilities=[ONHAND_EXPORT_CAPABILITY],
|
||||
)
|
||||
)
|
||||
result = check_freight_upload_rpa_ready()
|
||||
@@ -474,7 +474,7 @@ def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
|
||||
_heartbeat_payload(
|
||||
trigger_dir=str(upload_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[INVENTORY_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
|
||||
capabilities=[ONHAND_EXPORT_CAPABILITY, FREIGHT_UPLOAD_CAPABILITY],
|
||||
)
|
||||
)
|
||||
result = check_freight_upload_rpa_ready()
|
||||
@@ -483,7 +483,7 @@ def test_check_freight_upload_rpa_ready_when_worker_and_dirs_ok(app, tmp_path):
|
||||
|
||||
def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
|
||||
"""上传 fail-fast 须带 reasons,供建单前/触发时展示阻断原因。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
@@ -501,7 +501,7 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
|
||||
|
||||
def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
"""收料 ready 与库存同口径:要求共享哨兵;仅有库存 Worker 不能冒充收料在线。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
check_receipt_rpa_worker_ready,
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
serialize_rpa_worker_status,
|
||||
@@ -513,8 +513,8 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
inventory_trigger.mkdir(parents=True)
|
||||
_write_shared_sentinel(inventory_trigger, scope_id="hxops-rpa-test-data")
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(inventory_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(inventory_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
@@ -537,7 +537,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
worker_id="HOST-receipt",
|
||||
trigger_dir=str(receipt_trigger),
|
||||
shared_scope_id="hxops-rpa-test-data",
|
||||
capabilities=[RECEIPT_EXPORT_CAPABILITY],
|
||||
capabilities=[INBOUND_EXPORT_CAPABILITY],
|
||||
))
|
||||
without_sentinel = check_receipt_rpa_worker_ready()
|
||||
assert without_sentinel.ready is False
|
||||
@@ -547,8 +547,8 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
assert receipt_ready.ready is True
|
||||
assert [w["worker_id"] for w in receipt_ready.workers] == ["HOST-receipt"]
|
||||
|
||||
payload = serialize_rpa_worker_status(scope="receipt")
|
||||
assert payload["scope"] == "receipt"
|
||||
payload = serialize_rpa_worker_status(scope="inbound")
|
||||
assert payload["scope"] == "inbound"
|
||||
assert payload["ready"] is True
|
||||
assert payload["trigger_dir"] == str(receipt_trigger)
|
||||
assert [w["worker_id"] for w in payload["workers"]] == ["HOST-receipt"]
|
||||
@@ -556,7 +556,7 @@ def test_receipt_worker_status_requires_sentinel_like_inventory(app, tmp_path):
|
||||
|
||||
def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tmp_path):
|
||||
"""未注入 *-receipt 身份时,仍可用收料 trigger_dir 识别在线收料 Worker。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat import (
|
||||
check_receipt_rpa_worker_ready,
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
@@ -564,7 +564,7 @@ def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tm
|
||||
receipt_trigger = tmp_path / "receipt" / "triggers"
|
||||
receipt_trigger.mkdir(parents=True)
|
||||
app.config["ENV_NAME"] = "dev"
|
||||
app.config["FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR"] = str(receipt_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = ""
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
@@ -577,7 +577,7 @@ def test_receipt_worker_recognized_by_trigger_dir_without_receipt_suffix(app, tm
|
||||
worker_id="Hugo-30820",
|
||||
trigger_dir=str(receipt_trigger),
|
||||
shared_scope_id="",
|
||||
capabilities=[RECEIPT_EXPORT_CAPABILITY],
|
||||
capabilities=[INBOUND_EXPORT_CAPABILITY],
|
||||
))
|
||||
result = check_receipt_rpa_worker_ready()
|
||||
assert result.ready is True
|
||||
+23
-23
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/tests/test_rpa_worker_heartbeat_alert.py
|
||||
backend/tests/services/freight_rpa/test_worker_heartbeat_alert.py
|
||||
|
||||
用途:RPA Worker 心跳告警冷却、Redis/DB 不可用兜底与接收人回退单测。
|
||||
依赖:rpa_worker_heartbeat_alert、rpa_worker_heartbeat、models.AppSetting。
|
||||
依赖:freight_rpa.common.worker_heartbeat_alert、freight_rpa.common.worker_heartbeat、models.AppSetting。
|
||||
逻辑:验证 DB 权威读取、Redis 陈旧/空 DB 清理、并发 claim、企微失败可重试、恢复与 admin 回退。
|
||||
"""
|
||||
|
||||
@@ -17,7 +17,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import AppSetting, User
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import (
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import (
|
||||
_DB_ALERT_STATE_KEY,
|
||||
_STATUS_SENDING,
|
||||
_claim_alert_send_lock,
|
||||
@@ -32,7 +32,7 @@ def _enable_alert_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-data"
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
@@ -62,7 +62,7 @@ def test_alert_state_memory_fallback_when_redis_save_fails(app, monkeypatch):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
|
||||
@@ -89,15 +89,15 @@ def test_storage_unavailable_alert_respects_memory_cooldown(app, tmp_path, monke
|
||||
raise ConnectionError("redis write failed")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
lambda **kwargs: send_calls.append(kwargs["title"]) or True,
|
||||
)
|
||||
|
||||
@@ -129,11 +129,11 @@ def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
_capture_send,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
@@ -147,7 +147,7 @@ def test_alert_fallback_admin_recipients(app, tmp_path, monkeypatch):
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients
|
||||
|
||||
recipients = _alert_recipients()
|
||||
assert len(recipients) == 1
|
||||
@@ -170,7 +170,7 @@ def test_alert_state_persists_to_db_when_redis_unavailable(app, monkeypatch):
|
||||
raise ConnectionError("redis down")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: BrokenRedis(),
|
||||
)
|
||||
|
||||
@@ -191,7 +191,7 @@ def test_alert_logs_recipient_gap_when_no_wecom_users(app, tmp_path, monkeypatch
|
||||
app.config["FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN"] = True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
@@ -225,7 +225,7 @@ def test_alert_prefers_configured_usernames_over_admin(app, tmp_path, monkeypatc
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import _alert_recipients
|
||||
from app.services.freight_rpa.common.worker_heartbeat_alert import _alert_recipients
|
||||
|
||||
recipients = _alert_recipients()
|
||||
assert len(recipients) == 1
|
||||
@@ -242,11 +242,11 @@ def test_alert_wecom_send_failure_allows_retry_before_cooldown(app, tmp_path, mo
|
||||
return send_attempts["count"] >= 2
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
_flaky_send,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
@@ -302,7 +302,7 @@ def test_concurrent_first_claim_integrity_error_does_not_claim(app, monkeypatch)
|
||||
raise IntegrityError("INSERT", {}, Exception("duplicate key"))
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._claim_alert_send_lock_db",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._claim_alert_send_lock_db",
|
||||
_raise_integrity,
|
||||
)
|
||||
|
||||
@@ -342,11 +342,11 @@ def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._send_alert_to_recipients",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._send_alert_to_recipients",
|
||||
_capture_send,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert.check_inventory_rpa_worker_ready",
|
||||
lambda: type(
|
||||
"Ready",
|
||||
(),
|
||||
@@ -359,7 +359,7 @@ def test_recovery_after_stale_sending_lock(app, tmp_path, monkeypatch):
|
||||
)(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: type("BrokenRedis", (), {"get": lambda *_a, **_k: None, "set": lambda *_a, **_k: None, "delete": lambda *_a, **_k: None})(),
|
||||
)
|
||||
|
||||
@@ -404,7 +404,7 @@ def test_load_alert_state_prefers_db_over_stale_redis(app, monkeypatch):
|
||||
redis_bucket.pop(key, None)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
@@ -448,7 +448,7 @@ def test_load_alert_state_overwrites_newer_stale_redis_from_db(app, monkeypatch)
|
||||
redis_bucket.pop(key, None)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
@@ -488,7 +488,7 @@ def test_load_alert_state_clears_stale_redis_when_db_has_no_row(app, monkeypatch
|
||||
redis_bucket.pop(key, None)
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat_alert._redis_client",
|
||||
"app.services.freight_rpa.common.worker_heartbeat_alert._redis_client",
|
||||
lambda: FakeRedis(),
|
||||
)
|
||||
|
||||
@@ -62,7 +62,7 @@ def test_trigger_inbound_rpa_writes_batch_trigger(app, receipt_source):
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
|
||||
]
|
||||
assert calls['units'][0]['credential_envelope']
|
||||
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert calls['payload']['schema_version'] == 'freight_rpa.inbound.v1'
|
||||
|
||||
|
||||
def test_trigger_inbound_rpa_disabled_source_fails_closed(app):
|
||||
@@ -139,27 +139,28 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
|
||||
inventory_source_id=receipt_source.id).one()
|
||||
_bind_published_inbound_profile(config)
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
# [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
|
||||
# [断言意图] 真实落盘:Worker 轮询目录必须能看到 inbound_export_batch_*.json
|
||||
# (批次 R 自 receipt_export_batch_* 改名,旧 glob 会把已写入的文件判成没写)。
|
||||
assert list(tmp_path.glob("inbound_export_batch_*.json")), "trigger file not written"
|
||||
|
||||
|
||||
def test_default_trigger_fails_closed_when_inbound_profile_missing(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""收料配置存在但未绑已发布 inbound 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="matching_missing_ready_file",
|
||||
)
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 inbound trigger 文件。
|
||||
assert outcome["ok"] is False
|
||||
assert outcome["error_code"] == "RPA_INBOUND_PROFILE_MISSING"
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")) == []
|
||||
assert list(tmp_path.glob("inbound_export_batch_*.json")) == []
|
||||
|
||||
|
||||
def test_trigger_inbound_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
@@ -233,7 +234,7 @@ def test_trigger_inbound_rpa_batch_writes_one_trigger_for_all_units(app, receipt
|
||||
assert outcome['ok'] is True and outcome['triggered'] is True
|
||||
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
|
||||
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
|
||||
assert calls[0]['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert calls[0]['payload']['schema_version'] == 'freight_rpa.inbound.v1'
|
||||
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
|
||||
callback_ids = {u['callback_id'] for u in calls[0]['units']}
|
||||
assert len(callback_ids) == 2
|
||||
|
||||
@@ -229,10 +229,10 @@ def test_stale_orphan_unit_sweeps_projection_to_failed(app):
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
db.session.add(ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=None, inventory_source_id=source.id, source_code=source.source_code,
|
||||
|
||||
@@ -46,7 +46,7 @@ def test_inventory_snapshot_and_export_records_are_admin_only(app, client, tmp_p
|
||||
)
|
||||
schedule_task = ScheduleTask(
|
||||
schedule_no='SCH-INVENTORY-FAILED', name='Inventory Export', schedule_type='platform_job',
|
||||
owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='shipping-inventory-rpa',
|
||||
owner_user_id=1, cron_expr='0 0 * * *', platform_api_path='freight-rpa-onhand',
|
||||
)
|
||||
db.session.add_all([file_record, schedule_task])
|
||||
db.session.flush()
|
||||
@@ -139,7 +139,7 @@ def test_inventory_catalogs_remain_readable_before_order_schema_is_published(app
|
||||
|
||||
|
||||
def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_missing_steps(app, client):
|
||||
"""管理端普通保存不允许跳过测试直接启用,独立启用接口应返回业务缺失项。"""
|
||||
"""管理端普通保存不允许直接启用;独立启用接口只返回硬门槛缺失项,不含配置测试。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
@@ -166,7 +166,9 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
|
||||
assert created.status_code == 201
|
||||
source = parse_api_data(created.get_json())
|
||||
assert source['enabled'] is False
|
||||
assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
|
||||
# 关键断言:配置测试已退出启用门禁,缺失项只剩解析方案与发货模板。
|
||||
assert source['activation']['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
assert 'configuration_test' not in {item['code'] for item in source['activation']['checks']}
|
||||
|
||||
activation = client.post(
|
||||
f"/api/admin/shipping-notice/sources/{source['id']}/activate",
|
||||
@@ -175,7 +177,7 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
|
||||
assert activation.status_code == 409
|
||||
error = parse_api_error(activation.get_json())
|
||||
assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
|
||||
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
|
||||
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template']
|
||||
|
||||
|
||||
def test_latest_inventory_configuration_test_is_admin_only(app, client):
|
||||
|
||||
@@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
|
||||
|
||||
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
|
||||
"""batch 内 session 有效时不应重复 goto + login。"""
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
|
||||
assert spec and spec.loader
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -18,7 +18,7 @@ def test_receipt_recipient_can_download_but_other_user_is_rejected(app, client,
|
||||
other = User(username='receipt-other-user', email='receipt-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-DL', name='Receipt download', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-DL', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -47,8 +47,8 @@ def test_receipt_recipient_lists_only_own_archived_files(app, client):
|
||||
other = User(username='receipt-list-other', email='receipt-list-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIST-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIST-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
@@ -82,8 +82,8 @@ def test_receipt_file_list_filters_before_applying_limit(app):
|
||||
other = User(username='receipt-limit-other', email='receipt-limit-other@example.com', role='user', status='active')
|
||||
db.session.add_all([recipient, other]); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
own_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OWN', name='Own receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
other_task = ScheduleTask(schedule_no='SCH-RECEIPT-LIMIT-OTHER', name='Other receipt', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=other.id, cron_expr='0 8 * * *', notify_user_ids_json=[other.id])
|
||||
db.session.add_all([own_task, other_task]); db.session.flush()
|
||||
own_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OWN', schedule_task_id=own_task.id, status='success')
|
||||
other_run = ScheduleRun(run_no='RUN-RECEIPT-LIMIT-OTHER', schedule_task_id=other_task.id, status='success')
|
||||
@@ -113,7 +113,7 @@ def test_admin_can_resend_without_reexporting(app, client, monkeypatch):
|
||||
admin = User(username='receipt-resend-admin', email='receipt-resend-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id])
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RESEND', name='Receipt resend', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *', notify_user_ids_json=[admin.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RESEND', schedule_task_id=task.id, status='success')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -123,7 +123,7 @@ def test_admin_can_resend_without_reexporting(app, client, monkeypatch):
|
||||
db.session.add(report_file); db.session.commit()
|
||||
file_id = report_file.id
|
||||
calls = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.deliver_receipt_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0})
|
||||
monkeypatch.setattr('app.api.schedule.runs.deliver_inbound_file', lambda file_id, force=False: calls.append((file_id, force)) or {'success_count': 1, 'failed_count': 0})
|
||||
|
||||
response = client.post(f'/api/admin/receipt-report-files/{file_id}/resend', headers=_headers('receipt-resend-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
@@ -140,7 +140,7 @@ def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, clien
|
||||
admin = User(username='receipt-retry-admin', email='receipt-retry-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-RETRY', name='Receipt retry', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-RETRY', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -148,7 +148,7 @@ def test_admin_retry_creates_a_new_receipt_unit_linked_to_failed_unit(app, clien
|
||||
db.session.add(failed); db.session.commit()
|
||||
failed_id = failed.id
|
||||
captured = []
|
||||
monkeypatch.setattr('app.api.schedule.runs.write_receipt_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json')
|
||||
monkeypatch.setattr('app.api.schedule.runs.write_inbound_export_batch_trigger', lambda run_no, units, payload: captured.append((run_no, units, payload)) or 'retry-trigger.json')
|
||||
|
||||
response = client.post(f'/api/admin/receipt-rpa-units/{failed_id}/retry', json={'reason': 'portal recovered'}, headers=_headers('receipt-retry-admin', 'admin'))
|
||||
assert response.status_code == 200
|
||||
@@ -169,7 +169,7 @@ def test_admin_lists_failed_receipt_units_for_manual_compensation(app, client):
|
||||
admin = User(username='receipt-units-admin', email='receipt-units-admin@example.com', role='admin', status='active')
|
||||
db.session.add(admin); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-UNITS', name='Receipt units', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=admin.id, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-UNITS', schedule_task_id=task.id, status='failed')
|
||||
db.session.add(run); db.session.flush()
|
||||
|
||||
@@ -11,7 +11,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
"""开始导出标记 processing;每笔完成后 batch-progress 抬升排程计数。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import (
|
||||
mark_receipt_unit_processing,
|
||||
report_receipt_batch_progress,
|
||||
)
|
||||
@@ -20,7 +20,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-LIVE', name='Receipt live progress', schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -40,7 +40,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
db.session.commit()
|
||||
|
||||
marked = mark_receipt_unit_processing({
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.callback_id,
|
||||
'status': 'processing',
|
||||
})
|
||||
@@ -49,7 +49,7 @@ def test_receipt_unit_processing_and_batch_progress(app):
|
||||
assert db.session.get(ShippingReceiptRpaUnitRun, unit.id).status == 'processing'
|
||||
|
||||
progressed = report_receipt_batch_progress({
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'schedule_run_id': run.id,
|
||||
'batch_run_no': run.run_no,
|
||||
'success_count': 1,
|
||||
@@ -73,7 +73,7 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-PROG', name='Receipt progress', schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -92,15 +92,15 @@ def test_receipt_callback_success_refreshes_schedule_progress(app, monkeypatch):
|
||||
db.session.add(unit)
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file',
|
||||
'app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file',
|
||||
lambda _path: b'receipt-bytes',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes',
|
||||
'app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
payload = {
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.callback_id,
|
||||
'status': 'success',
|
||||
'file_path': 'Z:/receipt.xlsx',
|
||||
@@ -122,15 +122,15 @@ def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch)
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB', name='Receipt callback', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code, connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-callback-archive', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
first = ingest_receipt_callback(payload)
|
||||
second = ingest_receipt_callback(payload)
|
||||
assert first['file_id'] == second['file_id']
|
||||
@@ -145,7 +145,7 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB2', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -155,9 +155,9 @@ def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
|
||||
db.session.add(transfer_run); db.session.flush()
|
||||
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
|
||||
db.session.add(job); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive._read_inbound_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
|
||||
result = ingest_receipt_callback(payload)
|
||||
# [断言意图] 桥接发生:收料归档后调拨任务状态推进 file_ready,file_no 为归档文件 id
|
||||
@@ -175,7 +175,7 @@ def test_ingest_failed_advance_is_durable(app):
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB3', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -185,7 +185,7 @@ def test_ingest_failed_advance_is_durable(app):
|
||||
db.session.add(transfer_run); db.session.flush()
|
||||
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
|
||||
db.session.add(job); db.session.commit()
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
|
||||
payload = {'schema_version': 'freight_rpa.inbound.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
|
||||
|
||||
result = ingest_receipt_callback(payload)
|
||||
assert result['status'] == 'failed'
|
||||
@@ -201,17 +201,17 @@ def test_ingest_failed_advance_is_durable(app):
|
||||
def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
|
||||
"""Callback cannot read arbitrary local xlsx files outside the receipt-only drop root."""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file
|
||||
from app.services.freight_rpa.inbound.report_archive import _read_inbound_callback_file
|
||||
|
||||
with app.app_context():
|
||||
allowed_root = tmp_path / 'receipt-drop'
|
||||
allowed_root.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
|
||||
app.config['FREIGHT_RPA_SHARED_INBOUND_DROP_DIR'] = str(allowed_root)
|
||||
outside = tmp_path / 'outside.xlsx'
|
||||
outside.write_bytes(b'not-a-real-xlsx')
|
||||
|
||||
with pytest.raises(ValidationError, match='receipt callback file'):
|
||||
_read_receipt_callback_file(str(outside))
|
||||
_read_inbound_callback_file(str(outside))
|
||||
|
||||
|
||||
def test_ingest_empty_persists_no_receipt_data(app):
|
||||
@@ -230,7 +230,7 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
schedule_no='SCH-RECEIPT-EMPTY',
|
||||
name='Receipt empty',
|
||||
schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa',
|
||||
platform_api_path='freight-rpa-inbound',
|
||||
owner_user_id=1,
|
||||
cron_expr='0 8 * * *',
|
||||
)
|
||||
@@ -253,7 +253,7 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
db.session.commit()
|
||||
|
||||
result = ingest_receipt_callback({
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'schema_version': 'freight_rpa.inbound.v1',
|
||||
'callback_id': unit.callback_id,
|
||||
'status': 'empty',
|
||||
'error_code': 'no_receipt_data',
|
||||
@@ -269,19 +269,21 @@ def test_ingest_empty_persists_no_receipt_data(app):
|
||||
|
||||
|
||||
def test_receipt_progress_routes_are_registered(app):
|
||||
"""回归锁:receipt-unit-progress / receipt-batch-progress 必须注册在 Tool 蓝图上。
|
||||
"""回归锁:inbound-unit-progress / inbound-batch-progress 必须注册在 freight-rpa 蓝图上。
|
||||
|
||||
2026-10-08 事故:重构分叉合并丢失两路由,Worker 上报全程 404、活动锚失效、
|
||||
在飞批次被超时对账误杀——本用例保证路由缺失在任何部署前即红。
|
||||
(批次 R:路由自旧 shipping-notice rpa 回调前缀迁至 /api/freight-rpa/inbound-*,
|
||||
处理函数不变,本回归锁同步改指新 URL。)
|
||||
"""
|
||||
app.config['SHIPPING_NOTICE_TOOL_API_KEY'] = 'test-tool-key'
|
||||
client = app.test_client()
|
||||
headers = {'X-Integration-Key': 'test-tool-key'}
|
||||
for path, payload in (
|
||||
('/api/shipping-notice/rpa/receipt-unit-progress',
|
||||
{'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': 'no-such-callback'}),
|
||||
('/api/shipping-notice/rpa/receipt-batch-progress',
|
||||
{'schema_version': 'shipping_receipt_rpa.v1', 'schedule_run_id': 999999999}),
|
||||
('/api/freight-rpa/inbound-unit-progress',
|
||||
{'schema_version': 'freight_rpa.inbound.v1', 'callback_id': 'no-such-callback'}),
|
||||
('/api/freight-rpa/inbound-batch-progress',
|
||||
{'schema_version': 'freight_rpa.inbound.v1', 'schedule_run_id': 999999999}),
|
||||
):
|
||||
# [断言意图] 路由必须存在且鉴权通过(非 401/403/404);无匹配数据时服务层
|
||||
# 返回 200 + updated=False(注册性探针,不依赖任何夹具数据)。
|
||||
@@ -293,22 +295,22 @@ def test_receipt_progress_routes_are_registered(app):
|
||||
def test_read_receipt_callback_file_resolves_drop_root_filename(app, tmp_path):
|
||||
"""跨机路径契约:Worker 只上报文件名(或历史 Windows 绝对路径),后端按自身 drop 根定位。"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.receipt_report_storage import _read_receipt_callback_file
|
||||
from app.services.freight_rpa.inbound.report_archive import _read_inbound_callback_file
|
||||
|
||||
with app.app_context():
|
||||
drop_root = tmp_path / 'receipt-drop'
|
||||
drop_root.mkdir()
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(drop_root)
|
||||
app.config['FREIGHT_RPA_SHARED_INBOUND_DROP_DIR'] = str(drop_root)
|
||||
target = drop_root / 'receipt_RUN_X_SITE_NA_2026.xlsx'
|
||||
target.write_bytes(b'receipt-bytes')
|
||||
|
||||
# [断言意图] 裸文件名(新 Worker 契约)与 Windows 本机绝对路径(历史载荷)都
|
||||
# 必须解析到后端 drop 根内同一文件;根外文件依旧拒绝(任意本机文件读取护栏不变)。
|
||||
assert _read_receipt_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes'
|
||||
assert _read_receipt_callback_file(
|
||||
assert _read_inbound_callback_file('receipt_RUN_X_SITE_NA_2026.xlsx') == b'receipt-bytes'
|
||||
assert _read_inbound_callback_file(
|
||||
r'C:\HxopsRpaTest\data\freight_rpa\receipt\drop\receipt_RUN_X_SITE_NA_2026.xlsx'
|
||||
) == b'receipt-bytes'
|
||||
outside = tmp_path / 'outside.xlsx'
|
||||
outside.write_bytes(b'x')
|
||||
with pytest.raises(ValidationError, match='receipt callback file'):
|
||||
_read_receipt_callback_file(str(outside))
|
||||
_read_inbound_callback_file(str(outside))
|
||||
@@ -10,13 +10,13 @@ def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipient
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-recipient', email='recipient@example.com', role='user', status='active', wecom_userid='receipt-user')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY', name='Receipt notify', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -24,13 +24,13 @@ def test_receipt_file_delivery_is_idempotent_and_only_targets_schedule_recipient
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='a' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.upload_wecom_temp_media', lambda *_args: 'media-1')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.upload_wecom_temp_media', lambda *_args: 'media-1')
|
||||
calls: list[tuple] = []
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_notification.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0})
|
||||
monkeypatch.setattr('app.services.freight_rpa.inbound.report_archive.send_wecom_file_message', lambda *args: calls.append(args) or {'errcode': 0})
|
||||
|
||||
assert deliver_receipt_file(report_file.id)['success_count'] == 1
|
||||
assert deliver_receipt_file(report_file.id)['success_count'] == 1
|
||||
assert deliver_inbound_file(report_file.id)['success_count'] == 1
|
||||
assert deliver_inbound_file(report_file.id)['success_count'] == 1
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@@ -41,13 +41,13 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch):
|
||||
ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun, User,
|
||||
)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
from app.services.freight_rpa.inbound.report_archive import deliver_inbound_file
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-unbound-recipient', email='receipt-unbound@example.com', role='user', status='active')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-NOTIFY-FAIL', name='Receipt notify fail', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=recipient.id, cron_expr='0 8 * * *', notify_user_ids_json=[recipient.id])
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-NOTIFY-FAIL', schedule_task_id=task.id, status='running')
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -56,7 +56,7 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch):
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-fail.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='b' * 64)
|
||||
db.session.add(report_file); db.session.commit()
|
||||
|
||||
outcome = deliver_receipt_file(report_file.id)
|
||||
outcome = deliver_inbound_file(report_file.id)
|
||||
|
||||
assert outcome['failed_count'] == 1
|
||||
audit = ShippingAuditEvent.query.filter_by(event_type='shipping_receipt_file_notification_attempted', aggregate_id=str(report_file.id)).one()
|
||||
@@ -73,7 +73,7 @@ def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True} if awaiting else None)
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -115,10 +115,10 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_
|
||||
"""收料 run 终态后经通用排程出口一次性发 textcard+收料 ZIP;重复归集不重发。"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives')
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives')
|
||||
recipient = User(username='receipt-one-shot', email='one-shot@example.com', role='user', status='active', wecom_userid='one-shot-user')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
task, run, _report_file = _make_receipt_run_fixture(db, 'SCH-RECEIPT-ONESHOT', 'RUN-RECEIPT-ONESHOT', 'receipt-oneshot-callback')
|
||||
@@ -160,12 +160,12 @@ def test_receipt_finalize_generates_summary_excel(app, tmp_path):
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
|
||||
app.config['FREIGHT_RPA_INBOUND_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
|
||||
@@ -9,7 +9,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
"""一源一单元:有/无 Warehouse 条件均产出 unit;多值 Warehouse 不拆分。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingRpaProfile
|
||||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule
|
||||
|
||||
with app.app_context():
|
||||
dbs = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
@@ -53,7 +53,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
])
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
job_params={'source_codes': [dbs.source_code, crane.source_code, empty_dbs.source_code]},
|
||||
)
|
||||
db.session.add(task); db.session.flush()
|
||||
@@ -62,7 +62,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
|
||||
captured = {}
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger',
|
||||
'app.services.schedule.freight_inbound_rpa_job.write_inbound_export_batch_trigger',
|
||||
lambda run_no, units, payload: captured.update(run_no=run_no, units=units, payload=payload) or 'receipt-trigger.json',
|
||||
)
|
||||
total, success, failed, skipped, details, errors, logs = run_freight_receipt_rpa_schedule(task, run)
|
||||
@@ -71,7 +71,7 @@ def test_receipt_schedule_one_unit_per_source_including_empty_query_params(app,
|
||||
assert (total, success, failed, skipped, errors) == (3, 0, 0, 0, [])
|
||||
assert {item['source_code'] for item in details} == {dbs.source_code, crane.source_code, empty_dbs.source_code}
|
||||
assert all(item['warehouse_id'] is None for item in details)
|
||||
assert captured['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
assert captured['payload']['schema_version'] == 'freight_rpa.inbound.v1'
|
||||
assert len(captured['units']) == 3
|
||||
dbs_unit = next(item for item in captured['units'] if item['source_code'] == dbs.source_code)
|
||||
assert dbs_unit['rpa_profile_code'] == 'DBS_DUB_TEST'
|
||||
@@ -95,8 +95,8 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.schedule.freight_inbound_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.freight_rpa.common.worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
@@ -110,7 +110,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
))
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-RECEIPT-OFFLINE', name='Receipt offline', schedule_type='platform_job',
|
||||
platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *',
|
||||
job_params={'source_codes': [source.source_code]},
|
||||
)
|
||||
db.session.add(task)
|
||||
@@ -121,7 +121,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
|
||||
trigger_calls = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_receipt_rpa_job.assert_receipt_rpa_worker_ready',
|
||||
'app.services.schedule.freight_inbound_rpa_job.assert_receipt_rpa_worker_ready',
|
||||
lambda: (_ for _ in ()).throw(ServiceUnavailableError(
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
code='RPA.WORKER_OFFLINE',
|
||||
@@ -129,7 +129,7 @@ def test_receipt_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypa
|
||||
)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.schedule.freight_receipt_rpa_job.write_receipt_export_batch_trigger',
|
||||
'app.services.schedule.freight_inbound_rpa_job.write_inbound_export_batch_trigger',
|
||||
lambda *args, **kwargs: trigger_calls.append(args) or 'should-not-write.json',
|
||||
)
|
||||
|
||||
@@ -173,12 +173,12 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
"""无回调超时只关闭本次 run/单元并写审计,绝不创建重试单元。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-TIMEOUT', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=2), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -197,13 +197,13 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
|
||||
def test_receipt_trigger_is_published_atomically(app, tmp_path):
|
||||
"""Worker 只能观察到完整 JSON;临时写入文件不会匹配其 *.json 扫描。"""
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.freight_rpa.inbound.trigger_io import write_inbound_export_batch_trigger
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
|
||||
path = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'c1'}], {})
|
||||
app.config['FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR'] = str(tmp_path)
|
||||
path = write_inbound_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'c1'}], {})
|
||||
assert path
|
||||
assert (tmp_path / 'receipt_export_batch_RUN-ATOMIC.json').exists()
|
||||
assert (tmp_path / 'inbound_export_batch_RUN-ATOMIC.json').exists()
|
||||
assert not list(tmp_path.glob('.*.tmp'))
|
||||
|
||||
|
||||
@@ -211,12 +211,12 @@ def test_stale_receipt_full_scan_recovers_without_task_trigger_or_restart(app):
|
||||
"""全量扫描(每轮 tick 路径)无需任务再次执行/进程重启即可收口超时收料 run。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-ORPHAN', name='Receipt orphan', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-ORPHAN', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=5), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -235,12 +235,12 @@ def test_receipt_recovery_respects_fresh_activity_of_long_batch(app):
|
||||
"""长批次健康在跑不得被误杀:超时锚取最后单元活动而非 run 开始时间。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-LONG', name='Receipt long batch', schedule_type='platform_job', platform_api_path='freight-rpa-inbound', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-LONG', schedule_task_id=task.id, status='running', started_at=datetime.utcnow() - timedelta(minutes=30), response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
@@ -274,10 +274,10 @@ def test_stale_orphan_inbound_units_are_failed_by_full_scan(app):
|
||||
"""按需触发(无排程)的入站单元超时由全量扫描收口为失败,健康在跑单元不受影响。"""
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
from app.services.schedule.freight_inbound_rpa_finalize import recover_all_stale_orphan_receipt_units
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
# 单元1:排队 5 分钟从未被领取(created_at 为锚,queued 分支);单元2:领取后
|
||||
# 静默 5 分钟(started_at 为锚);单元3:30 秒前刚领取(健康在跑,不得误杀)。
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""独立收料 Worker 静态契约。"""
|
||||
"""独立 inbound(原收料)Worker 静态契约。"""
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
@@ -6,22 +6,23 @@ from pathlib import Path
|
||||
|
||||
|
||||
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
|
||||
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
|
||||
assert 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR' in text
|
||||
assert 'shipping_receipt_rpa.v1' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-batch-ready' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-batch-progress' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-unit-progress' in text
|
||||
"""inbound Worker 只消费 freight_rpa.inbound.v1 trigger、专用目录和独立 callback。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR' in text
|
||||
assert 'FREIGHT_RPA_SHARED_INBOUND_DROP_DIR' in text
|
||||
assert 'freight_rpa.inbound.v1' in text
|
||||
assert "from rpa_callbacks import" in text
|
||||
assert 'INBOUND_BATCH_READY' in text
|
||||
assert 'INBOUND_BATCH_PROGRESS' in text
|
||||
assert 'INBOUND_UNIT_PROGRESS' in text
|
||||
assert 'freight_rpa_worker' not in text
|
||||
assert 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
|
||||
assert 'FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR' not in text
|
||||
|
||||
|
||||
def test_receipt_dbs_export_does_not_require_warehouse_id():
|
||||
"""空条件允许走页面默认:Worker 不得因缺少 warehouse_id 直接失败。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_dbs_export.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_dbs_export.py'
|
||||
).read_text(encoding='utf-8')
|
||||
# 关键断言:历史必填门禁已移除;仅在 warehouse_id 有值时追加(兼容旧 trigger)。
|
||||
assert 'DBS receipt unit requires warehouse_id' not in text
|
||||
@@ -31,7 +32,7 @@ def test_receipt_dbs_export_does_not_require_warehouse_id():
|
||||
def test_receipt_dbs_export_maps_report_path_to_navigation():
|
||||
"""收料路径必须写入 navigation,避免共享导出驱动回退到库存报表名。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_dbs_export.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_dbs_export.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert "'navigation': report_path" in text
|
||||
assert "report_path = dict(unit.get('report_path_json') or {})" in text
|
||||
@@ -39,9 +40,9 @@ def test_receipt_dbs_export_maps_report_path_to_navigation():
|
||||
|
||||
def test_receipt_dbs_batch_reuses_inventory_session_prepare():
|
||||
"""DBS 收料批内必须复用库存 prepare_dsv_batch_export_step,禁止每源 new_page。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt'
|
||||
worker = (root / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
export = (root / 'receipt_dbs_export.py').read_text(encoding='utf-8')
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound'
|
||||
worker = (root / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
export = (root / 'inbound_dbs_export.py').read_text(encoding='utf-8')
|
||||
# 关键断言:与库存同构的批内会话准备;不得再写 first_in_profile / 按 index 新开空白页。
|
||||
assert 'prepare_dsv_batch_export_step' in worker
|
||||
assert 'skip_navigation' in worker and 'skip_navigation' in export
|
||||
@@ -51,12 +52,12 @@ def test_receipt_dbs_batch_reuses_inventory_session_prepare():
|
||||
|
||||
def test_receipt_worker_download_name_uses_source_not_callback():
|
||||
"""落盘名必须含 source_code,禁止用 callback_id 拼文件名(对齐库存 batch 命名)。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt'
|
||||
worker = (root / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound'
|
||||
worker = (root / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
# 关键断言:命名函数与 source/run 字段存在;不再用 safe_callback 拼 receipt_ 文件名。
|
||||
assert 'def _receipt_download_name(' in worker
|
||||
assert 'def _inbound_download_name(' in worker
|
||||
assert 'batch_run_no' in worker
|
||||
assert "f'receipt_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'" in worker
|
||||
assert "f'inbound_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}'" in worker
|
||||
assert 'safe_callback' not in worker
|
||||
assert "receipt_{safe_callback}" not in worker
|
||||
|
||||
@@ -64,7 +65,7 @@ def test_receipt_worker_download_name_uses_source_not_callback():
|
||||
def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。"""
|
||||
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 / 'inbound' / 'inbound_crane_export.py').read_text(encoding='utf-8')
|
||||
crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8')
|
||||
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver
|
||||
assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver
|
||||
@@ -73,7 +74,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
def test_receipt_crane_export_passes_download_dir_for_fallback():
|
||||
"""Crane 收料 source 必须带 __download_dir,否则共享 driver 目录兜底不会启用。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_crane_export.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_crane_export.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert "'__download_dir': str(unit.get('__download_dir') or '')" in text
|
||||
|
||||
@@ -81,7 +82,7 @@ def test_receipt_crane_export_passes_download_dir_for_fallback():
|
||||
def test_receipt_worker_save_download_uses_directory_fallback():
|
||||
"""收料落盘必须在 TargetClosed 时走 download_artifact_fallback(对齐库存)。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert 'download_artifact_fallback' in text
|
||||
assert 'def _persist_download_to_dest(' in text
|
||||
@@ -92,20 +93,20 @@ def test_receipt_worker_save_download_uses_directory_fallback():
|
||||
def test_receipt_worker_validates_excel_and_reports_empty():
|
||||
"""收料落盘后必须结构校验;无明细走 NoReceiptDataError → empty/no_receipt_data。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py'
|
||||
).read_text(encoding='utf-8')
|
||||
empty_mod = (
|
||||
Path(__file__).resolve().parents[2]
|
||||
/ 'scripts'
|
||||
/ 'freight_rpa'
|
||||
/ 'receipt'
|
||||
/ 'receipt_excel_empty.py'
|
||||
/ 'inbound'
|
||||
/ 'inbound_excel_empty.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert 'def _validate_receipt_excel(' in text
|
||||
assert 'from receipt_excel_empty import' in text
|
||||
assert 'class NoReceiptDataError' in empty_mod
|
||||
assert 'def _validate_inbound_excel(' in text
|
||||
assert 'from inbound_excel_empty import' in text
|
||||
assert 'class NoInboundDataError' in empty_mod
|
||||
assert 'no_receipt_data' in empty_mod
|
||||
assert 'is_receipt_excel_header_row' in empty_mod
|
||||
assert 'is_inbound_excel_header_row' in empty_mod
|
||||
assert "'error_code': 'no_receipt_data'" in text
|
||||
assert "_post_callback({" in text and "'status': 'empty'" in text
|
||||
assert '_EXPORT_UNIT_MAX_ATTEMPTS = 2' in text
|
||||
@@ -120,7 +121,7 @@ def test_receipt_ready_callback_outside_export_retry_like_inventory_progress():
|
||||
_post_unit_ready / batch-progress 放在导出循环外,并禁止 ready 失败再导。
|
||||
"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py'
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert 'def _post_unit_ready(' in text
|
||||
assert '重试只覆盖导出/落盘/校验' in text or 'ready 回调禁止进入本循环' in text
|
||||
@@ -133,18 +134,18 @@ def test_receipt_ready_callback_outside_export_retry_like_inventory_progress():
|
||||
|
||||
|
||||
def test_receipt_heartbeat_capability_is_receipt_export():
|
||||
"""收料 Worker 心跳能力必须声明 receipt_export,不得再写 inventory_export。"""
|
||||
"""inbound Worker 心跳能力必须声明 inbound_export,不得再写 onhand_export。"""
|
||||
text = (
|
||||
Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'common' / 'rpa_heartbeat.py'
|
||||
).read_text(encoding='utf-8')
|
||||
assert 'receipt_export' in text
|
||||
assert 'is_receipt' in text
|
||||
assert 'inbound_export' in text
|
||||
assert 'is_inbound' in text
|
||||
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
module_path = root / 'receipt' / 'receipt_crane_export.py'
|
||||
module_path = root / 'inbound' / 'inbound_crane_export.py'
|
||||
sys.path.insert(0, str(root))
|
||||
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path)
|
||||
assert spec and spec.loader
|
||||
@@ -161,7 +162,7 @@ def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
|
||||
def test_receipt_worker_uses_common_trigger_consumer():
|
||||
"""收料 Worker 必须复用公共 claim/归档原语,不再自建目录搬移实现。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'claim_trigger' in text
|
||||
assert 'archive_trigger' in text
|
||||
assert "path.replace(claimed)" not in text # 领取逻辑收敛到公共模块
|
||||
@@ -169,47 +170,47 @@ def test_receipt_worker_uses_common_trigger_consumer():
|
||||
|
||||
def test_receipt_worker_logs_full_lifecycle_and_banner():
|
||||
"""收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'configure_file_logging' in text
|
||||
assert 'maybe_rotate_open_log' in text
|
||||
assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段
|
||||
assert '[receipt-unit] success' in text # 成功单元留痕(此前成功路径零输出)
|
||||
assert '[receipt-unit] failed' in text
|
||||
assert '[receipt-trigger] claimed' in text and '[receipt-trigger] archived' in text
|
||||
assert '[inbound-unit] success' in text # 成功单元留痕(此前成功路径零输出)
|
||||
assert '[inbound-unit] failed' in text
|
||||
assert '[inbound-trigger] claimed' in text and '[inbound-trigger] archived' in text
|
||||
|
||||
|
||||
def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
|
||||
"""收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'start_inbound_worker.ps1').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-inbound' 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 = (root / 'inbound' / 'register_inbound_worker_tasks.ps1').read_text(encoding='utf-8')
|
||||
inventory = (root / 'onhand' / 'register_onhand_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 '$TestTask = "HXOPS Freight Inbound RPA Worker TEST"' in receipt
|
||||
assert '$ProdTask = "HXOPS Freight Inbound RPA Worker PROD"' in receipt
|
||||
assert 'HXOPS Freight Onhand RPA Worker TEST' in inventory and 'HXOPS Freight Inbound RPA Worker' not in inventory
|
||||
# [断言意图] 动作必须指向收料启动脚本,且不得把库存启动脚本带进收料注册
|
||||
assert 'start_receipt_worker.ps1' in receipt and 'start_inventory_worker.ps1' not in receipt
|
||||
assert 'start_inbound_worker.ps1' in receipt and 'start_onhand_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_defaults_session_reuse_with_scoped_profiles():
|
||||
"""收料默认会话复用,且持久目录按 connector+profile 隔离(对齐库存)。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'inbound_rpa_worker.py').read_text(encoding='utf-8')
|
||||
# [断言意图] 默认开启复用;持久目录形如 connector__profile_session,禁止单一 receipt_session
|
||||
assert 'def _session_reuse_enabled()' in text
|
||||
assert "f'{connector}__{code}_session'" in text or 'f"{connector}__{code}_session"' in text
|
||||
assert "profile_root / 'receipt_session'" not in text
|
||||
assert 'receipt-batch-progress' in text
|
||||
assert 'receipt-unit-progress' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
|
||||
assert 'INBOUND_BATCH_PROGRESS' in text
|
||||
assert 'INBOUND_UNIT_PROGRESS' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'inbound' / 'start_inbound_worker.ps1').read_text(encoding='utf-8')
|
||||
assert '[switch]$NoSessionReuse' in ps1
|
||||
assert "FREIGHT_RPA_WORKER_SESSION_REUSE = $sessionReuse" in ps1
|
||||
@@ -27,24 +27,24 @@ def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_ID", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
payload = module.build_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\inventory_drop",
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\onhand_triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\onhand_drop",
|
||||
)
|
||||
assert payload["shared_scope_id"] == "hxops-rpa-test-data"
|
||||
assert payload["trigger_dir"] == r"C:\HxopsRpaTest\data\inventory_triggers"
|
||||
assert payload["capabilities"] == ["inventory_export"]
|
||||
assert payload["trigger_dir"] == r"C:\HxopsRpaTest\data\onhand_triggers"
|
||||
assert payload["capabilities"] == ["onhand_export"]
|
||||
|
||||
|
||||
def test_build_heartbeat_payload_receipt_worker_declares_receipt_export(monkeypatch):
|
||||
"""收料 Worker(*-receipt 或 receipt trigger 路径)须声明 receipt_export。"""
|
||||
def test_build_heartbeat_payload_inbound_worker_declares_inbound_export(monkeypatch):
|
||||
"""inbound Worker(*-inbound 或 inbound trigger 路径)须声明 inbound_export。"""
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ID", "WIN-RPA-01-receipt")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ID", "WIN-RPA-01-inbound")
|
||||
payload = module.build_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\freight_rpa\receipt\triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\freight_rpa\receipt\drop",
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\freight_rpa\inbound\triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\freight_rpa\inbound\drop",
|
||||
)
|
||||
assert payload["capabilities"] == ["receipt_export"]
|
||||
assert payload["worker_id"].endswith("-receipt")
|
||||
assert payload["capabilities"] == ["inbound_export"]
|
||||
assert payload["worker_id"].endswith("-inbound")
|
||||
|
||||
|
||||
def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
|
||||
@@ -52,13 +52,13 @@ def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
|
||||
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.setenv(
|
||||
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
"FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR",
|
||||
r"C:\HxopsRpaTest\data\onhand_triggers",
|
||||
)
|
||||
assert module._resolve_shared_scope_id() == ""
|
||||
monkeypatch.setenv(
|
||||
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
r"C:\mount\hxops-rpa-test-data\inventory_triggers",
|
||||
"FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR",
|
||||
r"C:\mount\hxops-rpa-test-data\onhand_triggers",
|
||||
)
|
||||
assert module._resolve_shared_scope_id() == "hxops-rpa-test-data"
|
||||
|
||||
@@ -66,7 +66,7 @@ def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
|
||||
def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
|
||||
trigger_dir = tmp_path / "inventory_triggers"
|
||||
trigger_dir = tmp_path / "onhand_triggers"
|
||||
trigger_dir.mkdir()
|
||||
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01")
|
||||
|
||||
@@ -28,8 +28,8 @@ def _repo_root() -> Path:
|
||||
|
||||
|
||||
def _load_freight_rpa_worker():
|
||||
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)
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("onhand_rpa_worker_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -40,12 +40,12 @@ def _load_freight_rpa_worker():
|
||||
def _build_inventory_export_trigger(task_no: str) -> dict[str, object]:
|
||||
"""构造库存导出 trigger 样本,避免测试依赖会被 worker 消费掉的仓库文件。"""
|
||||
return {
|
||||
"action": "inventory_export",
|
||||
"action": "onhand_export",
|
||||
"task_no": task_no,
|
||||
"requested_at": "2026-07-01T03:23:25.114522",
|
||||
"mode": "auto",
|
||||
"attempt": 3,
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": f"SRC-{task_no}:C1",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
"source_run_no": f"SRC-{task_no}",
|
||||
@@ -87,15 +87,15 @@ def test_single_inventory_trigger_missing_source_run_is_rejected_before_rpa(monk
|
||||
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
monkeypatch.setattr(worker, "_download_onhand_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks == [
|
||||
(
|
||||
"/api/shipping-notice/rpa/inventory-ready",
|
||||
"/api/freight-rpa/onhand-ready",
|
||||
{
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": None,
|
||||
"task_no": "SN-IDENTITY-INVALID",
|
||||
"business_status": "rejected",
|
||||
@@ -122,9 +122,9 @@ def test_single_inventory_trigger_missing_callback_id_is_rejected(monkeypatch, t
|
||||
trigger_path.write_text(json.dumps(payload), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
monkeypatch.setattr(worker, "_download_onhand_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start"))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks[0][1]["callback_id"] is None
|
||||
assert callbacks[0][1]["error_code"] == "trigger_identity_invalid"
|
||||
@@ -156,7 +156,7 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "BATCH-001:batch:C1",
|
||||
"batch_run_no": "BATCH-001",
|
||||
"task_no": "SN-BATCH-IDENTITY",
|
||||
@@ -166,9 +166,9 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
|
||||
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
|
||||
result = completed["results"][0]
|
||||
assert {key: result[key] for key in (
|
||||
"callback_id", "task_no", "source_code", "source_run_no", "attempt_no",
|
||||
@@ -210,7 +210,7 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "BATCH-CRANE-DYNAMIC:batch:C1",
|
||||
"batch_run_no": "BATCH-CRANE-DYNAMIC",
|
||||
"task_no": "SN-CRANE-DYNAMIC",
|
||||
@@ -220,9 +220,9 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
|
||||
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
|
||||
assert completed["results"][0]["callback_id"] == "PSR-CRANE-DYNAMIC:C1"
|
||||
assert completed["results"][0]["expected_warehouse_id"] is None
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
@@ -239,7 +239,7 @@ def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch
|
||||
trigger_path = trigger_dir / "inventory_export_batch_invalid.json"
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "BATCH-INVALID:batch:C1",
|
||||
"batch_run_no": "BATCH-INVALID",
|
||||
"task_no": "SN-BATCH-INVALID",
|
||||
@@ -259,7 +259,7 @@ def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
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_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert callbacks[0][1]["callback_id"] == "BATCH-INVALID:batch:C1"
|
||||
assert callbacks[0][1]["identity_errors"] == ["inventory_sources[0].expected_warehouse_id"]
|
||||
@@ -279,7 +279,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
# batch 级无 task_no,逐源无 task_no/source_run_no/lease_token/candidate_set_id/execution_id/gate_id。
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "RUN-SCHEDULED:batch:C1",
|
||||
"batch_run_no": "RUN-SCHEDULED",
|
||||
"run_no": "RUN-SCHEDULED",
|
||||
@@ -304,9 +304,9 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
|
||||
completed = next(body for path, body in callbacks if path.endswith("/onhand-batch-ready"))
|
||||
assert completed["schedule_run_id"] == 713
|
||||
assert completed["trigger_type"] == "scheduled"
|
||||
result = completed["results"][0]
|
||||
@@ -314,7 +314,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
assert result["warehouse_id"] == "AWSDU"
|
||||
assert result["status"] == "success"
|
||||
# 每完成一个站点应回传一次累计进度,供后端实时回写排程 run 笔数。
|
||||
progress = next(body for path, body in callbacks if path.endswith("/inventory-batch-progress"))
|
||||
progress = next(body for path, body in callbacks if path.endswith("/onhand-batch-progress"))
|
||||
assert progress["schedule_run_id"] == 713
|
||||
assert progress["batch_run_no"] == "RUN-SCHEDULED"
|
||||
assert progress["success_count"] == 1
|
||||
@@ -339,7 +339,7 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
|
||||
# trigger_type=configuration_test,无 task_no / gate_id / execution_id 等生产身份。
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": f"{run_no}:batch:C1",
|
||||
"batch_run_no": run_no,
|
||||
"run_no": run_no,
|
||||
@@ -363,14 +363,14 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert not any(body.get("error_code") == "trigger_identity_invalid" for _, body in callbacks)
|
||||
ready = next(body for path, body in callbacks if path.endswith("/inventory-configuration-test-ready"))
|
||||
ready = next(body for path, body in callbacks if path.endswith("/onhand-configuration-test-analyze"))
|
||||
assert ready["run_no"] == run_no
|
||||
assert ready["status"] == "success"
|
||||
assert ready.get("file_path")
|
||||
assert not any(path.endswith("/inventory-batch-ready") for path, _ in callbacks)
|
||||
assert not any(path.endswith("/onhand-batch-ready") for path, _ in callbacks)
|
||||
assert (processed_dir / trigger_path.name).is_file()
|
||||
assert not (failed_dir / trigger_path.name).exists()
|
||||
|
||||
@@ -398,7 +398,7 @@ def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup
|
||||
}
|
||||
trigger_path.write_text(json.dumps({
|
||||
"action": "inventory_export_batch",
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "BATCH-INTERRUPT:batch:C1",
|
||||
"batch_run_no": "BATCH-INTERRUPT",
|
||||
"task_no": "SN-CRANE-INTERRUPT",
|
||||
@@ -417,14 +417,14 @@ def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup
|
||||
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda *_args, **_kwargs: (_Playwright(), _Context(), object(), tmp_path / "profile"))
|
||||
monkeypatch.setattr(worker, "_ensure_crane_session", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(worker, "_export_crane_inventory_source", lambda *_args, **_kwargs: (_ for _ in ()).throw(KeyboardInterrupt()))
|
||||
monkeypatch.setattr(worker, "_export_crane_onhand_source", lambda *_args, **_kwargs: (_ for _ in ()).throw(KeyboardInterrupt()))
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
with pytest.raises(KeyboardInterrupt):
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert stopped == [True]
|
||||
assert [path for path, _body in callbacks] == ["/api/shipping-notice/rpa/inventory-batch-claimed"]
|
||||
assert [path for path, _body in callbacks] == ["/api/freight-rpa/onhand-batch-claimed"]
|
||||
assert trigger_path.is_file()
|
||||
assert not (processed_dir / trigger_path.name).exists()
|
||||
|
||||
@@ -443,10 +443,10 @@ def test_env_strips_wrapping_quotes(monkeypatch):
|
||||
def test_worker_accepts_business_connector_without_site_id():
|
||||
"""数据库 Source 的 dbs/crane 业务类型不应要求已删除的 site_id 字段。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
worker._validate_inventory_source_for_rpa({
|
||||
worker._validate_onhand_source_for_rpa({
|
||||
"source_code": "DBS_DUB", "connector_type": "dbs", "warehouse_id": "DUB",
|
||||
})
|
||||
worker._validate_inventory_source_for_rpa({
|
||||
worker._validate_onhand_source_for_rpa({
|
||||
"source_code": "CRANE", "connector_type": "crane",
|
||||
})
|
||||
|
||||
@@ -788,7 +788,7 @@ def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypat
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
stats = cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
onhand_trigger_dir=inv_trigger,
|
||||
upload_trigger_dir=upload_trigger,
|
||||
drop_dir=drop,
|
||||
upload_queue_dir=queue,
|
||||
@@ -836,7 +836,7 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
onhand_trigger_dir=inv_trigger,
|
||||
browser_profile_dir=profiles,
|
||||
now_unix=now,
|
||||
)
|
||||
@@ -845,36 +845,36 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
|
||||
assert not orphan_run.exists()
|
||||
|
||||
|
||||
def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
|
||||
def test_cleanup_orphan_runtime_profiles_removes_inbound_prefix(tmp_path):
|
||||
"""
|
||||
崩溃残留的 receipt_* 临时 Profile 超期必须被清理;_session 目录保留。
|
||||
崩溃残留的 inbound_* 临时 Profile 超期必须被清理;_session 目录保留。
|
||||
|
||||
断言意图:收料 Worker 的一次性 Profile 以 receipt_ 前缀创建,异常中断后
|
||||
断言意图:inbound Worker 的一次性 Profile 以 inbound_ 前缀创建,异常中断后
|
||||
残留目录同样按孤儿 Profile 规则清理;会话复用目录按名豁免(与年龄无关);
|
||||
未超期的 receipt_* Profile 正在使用中,前缀匹配不得误删。
|
||||
未超期的 inbound_* Profile 正在使用中,前缀匹配不得误删。
|
||||
"""
|
||||
cleanup = _load_worker_disk_cleanup()
|
||||
root = tmp_path / "browser_profile"
|
||||
stale_receipt = root / "receipt_abcd1234"
|
||||
stale_receipt.mkdir(parents=True)
|
||||
(stale_receipt / "Cookies").write_text("drop", encoding="utf-8")
|
||||
young_receipt = root / "receipt_fresh5678"
|
||||
young_receipt.mkdir()
|
||||
stale_inbound = root / "inbound_abcd1234"
|
||||
stale_inbound.mkdir(parents=True)
|
||||
(stale_inbound / "Cookies").write_text("drop", encoding="utf-8")
|
||||
young_inbound = root / "inbound_fresh5678"
|
||||
young_inbound.mkdir()
|
||||
session_dir = root / "dsv_session"
|
||||
session_dir.mkdir()
|
||||
now = time.time()
|
||||
old = now - 10 * 24 * 3600
|
||||
os.utime(stale_receipt, (old, old))
|
||||
os.utime(young_receipt, (now - 3600, now - 3600))
|
||||
os.utime(stale_inbound, (old, old))
|
||||
os.utime(young_inbound, (now - 3600, now - 3600))
|
||||
os.utime(session_dir, (old, old))
|
||||
stats = cleanup.DiskCleanupStats()
|
||||
|
||||
# cutoff 对齐真实调用语义:run_worker_disk_cleanup 传入 now - 孤儿最大存活(默认 24h)
|
||||
cleanup.cleanup_orphan_runtime_profiles(root, cutoff_unix=now - 24 * 3600, stats=stats)
|
||||
|
||||
# 过期 receipt_* 目录树删除;未过期 receipt_* 与 _session 结尾目录即使过期也保留
|
||||
assert not stale_receipt.exists() and session_dir.exists()
|
||||
assert young_receipt.exists()
|
||||
# 过期 inbound_* 目录树删除;未过期 inbound_* 与 _session 结尾目录即使过期也保留
|
||||
assert not stale_inbound.exists() and session_dir.exists()
|
||||
assert young_inbound.exists()
|
||||
assert stats.deleted_dirs == 1
|
||||
|
||||
|
||||
@@ -995,17 +995,17 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
download_calls: list[dict] = []
|
||||
|
||||
def fake_download_inventory_with_browser(trigger: dict, target_drop_dir: Path) -> Path:
|
||||
def fake_download_onhand_with_browser(trigger: dict, target_drop_dir: Path) -> Path:
|
||||
download_calls.append(trigger)
|
||||
out_file = target_drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"
|
||||
out_file = target_drop_dir / "onhand_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"
|
||||
out_file.write_bytes(b"fake inventory content")
|
||||
return out_file
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser)
|
||||
monkeypatch.setattr(worker, "_download_onhand_with_browser", fake_download_onhand_with_browser)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert len(download_calls) == 1
|
||||
trigger = download_calls[0]
|
||||
@@ -1018,9 +1018,9 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
|
||||
assert len(callbacks) == 1
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_path == "/api/freight-rpa/onhand-ready"
|
||||
assert callback_payload == {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
@@ -1034,7 +1034,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
"expected_warehouse_id": "AWSDU",
|
||||
"status": "success",
|
||||
"success": True,
|
||||
"file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
|
||||
"file_path": str(drop_dir / "onhand_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"),
|
||||
"file_sha256": hashlib.sha256(b"fake inventory content").hexdigest(),
|
||||
"rpa_mode": "browser",
|
||||
}
|
||||
@@ -1060,12 +1060,12 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_ONHAND", raising=False)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
exported_files = list(drop_dir.glob("inventory_SN-20260629-2EDADC77_*.xlsx"))
|
||||
exported_files = list(drop_dir.glob("onhand_SN-20260629-2EDADC77_*.xlsx"))
|
||||
assert len(exported_files) == 1
|
||||
exported = exported_files[0]
|
||||
wb = load_workbook(exported, data_only=True, read_only=True)
|
||||
@@ -1080,9 +1080,9 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
assert rows[2] == ("A002", 50)
|
||||
assert len(callbacks) == 1
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_path == "/api/freight-rpa/onhand-ready"
|
||||
assert callback_payload == {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "SRC-SN-20260629-2EDADC77:C1",
|
||||
"task_no": "SN-20260629-2EDADC77",
|
||||
"source_code": "DSV360_AWSDU",
|
||||
@@ -1122,14 +1122,14 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
|
||||
raise worker.NoInventoryDataError("DSV report has no inventory data")
|
||||
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory)
|
||||
monkeypatch.setattr(worker, "_download_onhand_with_browser", raise_no_inventory)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
worker._handle_onhand_trigger(trigger_path, drop_dir, processed_dir)
|
||||
|
||||
assert len(callbacks) == 1
|
||||
callback_path, callback_payload = callbacks[0]
|
||||
assert callback_path == "/api/shipping-notice/rpa/inventory-ready"
|
||||
assert callback_path == "/api/freight-rpa/onhand-ready"
|
||||
assert callback_payload["status"] == "skipped"
|
||||
assert callback_payload["success"] is False
|
||||
assert callback_payload["skipped"] is True
|
||||
@@ -1139,10 +1139,10 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
|
||||
assert not trigger_path.exists()
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_all_skipped():
|
||||
def test_summarize_onhand_batch_results_all_skipped():
|
||||
"""全 skipped 时 batch 顶层 legacy success 应为 true,status 为 success。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([
|
||||
summary = worker._summarize_onhand_batch_results([
|
||||
{"source_code": "A", "status": "skipped", "success": False, "skipped": True},
|
||||
{"source_code": "B", "status": "skipped", "success": False, "skipped": True},
|
||||
])
|
||||
@@ -1153,10 +1153,10 @@ def test_summarize_inventory_batch_results_all_skipped():
|
||||
assert summary["failed_count"] == 0
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_partial_failed():
|
||||
def test_summarize_onhand_batch_results_partial_failed():
|
||||
"""存在 failed 但有 success/skipped 时 legacy success 仍为 true,status=partial_failed。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([
|
||||
summary = worker._summarize_onhand_batch_results([
|
||||
{"source_code": "A", "status": "success", "success": True},
|
||||
{"source_code": "B", "status": "failed", "success": False},
|
||||
])
|
||||
@@ -1167,10 +1167,10 @@ def test_summarize_inventory_batch_results_partial_failed():
|
||||
assert summary["failed_count"] == 1
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_empty():
|
||||
def test_summarize_onhand_batch_results_empty():
|
||||
"""空 results 应返回全 0 计数,避免 helper 复用时 KeyError。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([])
|
||||
summary = worker._summarize_onhand_batch_results([])
|
||||
assert summary == {
|
||||
"status": "failed",
|
||||
"success": False,
|
||||
@@ -1547,7 +1547,7 @@ def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path):
|
||||
|
||||
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
|
||||
|
||||
assert callbacks == [("/api/shipping-notice/rpa/upload-complete", {
|
||||
assert callbacks == [("/api/freight-rpa/upload-complete", {
|
||||
"task_no": "SN-UPLOAD-FAIL", "attempt_id": 8, "callback_id": "rpa:8",
|
||||
"result": "failed", "success": False, "error_message": "success marker missing",
|
||||
})]
|
||||
@@ -1573,10 +1573,10 @@ def test_upload_empty_queue_path_reports_failed_callback(monkeypatch, tmp_path):
|
||||
assert callbacks[0][1]["error_message"] == "queue file missing: <empty>"
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_skipped_and_failed():
|
||||
def test_summarize_onhand_batch_results_skipped_and_failed():
|
||||
"""仅有 skipped+failed 时 legacy success 为 true(skipped 算已处理)。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
summary = worker._summarize_inventory_batch_results([
|
||||
summary = worker._summarize_onhand_batch_results([
|
||||
{"source_code": "A", "status": "skipped", "success": False, "skipped": True},
|
||||
{"source_code": "B", "status": "failed", "success": False},
|
||||
])
|
||||
@@ -1590,18 +1590,18 @@ def test_summarize_inventory_batch_results_skipped_and_failed():
|
||||
def test_summarize_inventory_batch_item_empty_dict_counts_as_failed():
|
||||
"""batch 归一化对空 dict 应算 failed,避免缺字段误计 success。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
assert worker._normalize_inventory_batch_item_status({}) == "failed"
|
||||
summary = worker._summarize_inventory_batch_results([{}])
|
||||
assert worker._normalize_onhand_batch_item_status({}) == "failed"
|
||||
summary = worker._summarize_onhand_batch_results([{}])
|
||||
assert summary["failed_count"] == 1
|
||||
assert summary["success_count"] == 0
|
||||
assert summary["success"] is False
|
||||
|
||||
|
||||
def test_summarize_inventory_batch_results_all_skipped_is_success():
|
||||
def test_summarize_onhand_batch_results_all_skipped_is_success():
|
||||
"""全 skipped 代表链路正常但无库存,不得误报为批量导出失败。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
results = [{"source_code": "A", "status": "skipped", "success": False, "skipped": True}]
|
||||
summary = worker._summarize_inventory_batch_results(results)
|
||||
summary = worker._summarize_onhand_batch_results(results)
|
||||
assert summary["status"] == "success"
|
||||
assert summary["has_success"] is False
|
||||
assert summary["status"] not in {"failed", "partial_failed"}
|
||||
@@ -2760,7 +2760,7 @@ def test_fill_dsv_filter_if_needed_accepts_report_name_kwarg():
|
||||
assert filled == {"#ReportViewerMain_ctl08_ctl03_txtValue": "CADU-0000000100"}
|
||||
|
||||
|
||||
def test_validate_inventory_excel_accepts_real_report_shape(tmp_path):
|
||||
def test_validate_onhand_excel_accepts_real_report_shape(tmp_path):
|
||||
"""下载完成后必须能打开 Excel,并包含库存报表标题和关键表头。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
path = tmp_path / "inventory.xlsx"
|
||||
@@ -2775,17 +2775,17 @@ def test_validate_inventory_excel_accepts_real_report_shape(tmp_path):
|
||||
ws.append(["CADU-0000000100", "Well Trust Precision Technology", f"504-006043-{index:03d}", "Frame"])
|
||||
wb.save(path)
|
||||
|
||||
worker._validate_inventory_excel(path)
|
||||
worker._validate_onhand_excel(path)
|
||||
|
||||
|
||||
def test_validate_inventory_excel_rejects_invalid_download(tmp_path):
|
||||
def test_validate_onhand_excel_rejects_invalid_download(tmp_path):
|
||||
"""下载文件太小或不是有效 Excel 时不能回调 success。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
path = tmp_path / "inventory.xlsx"
|
||||
path.write_bytes(b"not a complete excel")
|
||||
|
||||
with pytest.raises(RuntimeError, match="too small|valid Excel"):
|
||||
worker._validate_inventory_excel(path)
|
||||
worker._validate_onhand_excel(path)
|
||||
|
||||
|
||||
def test_find_dsv_report_result_frame_prefers_grid_like_frame():
|
||||
@@ -2952,7 +2952,7 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
|
||||
str(tmp_path / "browser_profile"),
|
||||
)
|
||||
|
||||
out_file = worker._download_inventory_with_browser(trigger, drop_dir)
|
||||
out_file = worker._download_onhand_with_browser(trigger, drop_dir)
|
||||
|
||||
assert out_file.is_file()
|
||||
assert out_file.parent == drop_dir
|
||||
|
||||
@@ -9,7 +9,7 @@ from unittest.mock import MagicMock
|
||||
|
||||
|
||||
def _load_worker():
|
||||
return _load_rpa_module("freight_rpa_worker")
|
||||
return _load_rpa_module("onhand_rpa_worker")
|
||||
|
||||
|
||||
def _load_dsv_report_export():
|
||||
@@ -21,8 +21,8 @@ def _load_dsv_auth_login_flow():
|
||||
|
||||
|
||||
_RPA_MODULE_PATHS = {
|
||||
"freight_rpa_worker": "inventory/inventory_rpa_worker.py",
|
||||
"inventory_rpa_worker": "inventory/inventory_rpa_worker.py",
|
||||
"freight_rpa_worker": "onhand/onhand_rpa_worker.py",
|
||||
"onhand_rpa_worker": "onhand/onhand_rpa_worker.py",
|
||||
"dsv_report_export": "connectors/dsv/dsv_report_export.py",
|
||||
"dsv_auth_login_flow": "connectors/dsv/dsv_auth_login_flow.py",
|
||||
"dsv_navigation": "connectors/dsv/dsv_navigation.py",
|
||||
@@ -205,18 +205,18 @@ def test_ensure_dsv_inventory_rows_skips_retry_when_rows_already_visible(monkeyp
|
||||
assert clicks == []
|
||||
|
||||
|
||||
def test_dsv_export_kind_receipt_from_flag_and_report_name():
|
||||
"""收料 source 须显式或按报表名识别为 receipt,不得默认库存。"""
|
||||
def test_dsv_export_kind_inbound_from_flag_and_report_name():
|
||||
"""inbound source 须显式或按报表名识别为 inbound,不得默认库存。"""
|
||||
worker = _load_dsv_report_export()
|
||||
assert worker._dsv_export_kind({"__export_kind__": "receipt"}) == "receipt"
|
||||
assert worker._dsv_export_kind({"navigation": {"report_name": "Receipt Detail"}}) == "receipt"
|
||||
assert worker._dsv_export_kind({"__export_kind__": "inbound"}) == "inbound"
|
||||
assert worker._dsv_export_kind({"navigation": {"report_name": "Receipt Detail"}}) == "inbound"
|
||||
assert worker._dsv_export_kind({"navigation": {"report_name": "On Hand Inventory by Location"}}) == "inventory"
|
||||
assert "on hand inventory by location" not in worker._dsv_body_markers_for_kind("receipt")
|
||||
assert "qty expected" in worker._dsv_body_markers_for_kind("receipt")
|
||||
assert "qty available" not in " ".join(worker._dsv_body_markers_for_kind("receipt"))
|
||||
assert "on hand inventory by location" not in worker._dsv_body_markers_for_kind("inbound")
|
||||
assert "qty expected" in worker._dsv_body_markers_for_kind("inbound")
|
||||
assert "qty available" not in " ".join(worker._dsv_body_markers_for_kind("inbound"))
|
||||
|
||||
|
||||
def test_wait_receipt_result_ready_accepts_export_toolbar(monkeypatch):
|
||||
def test_wait_inbound_result_ready_accepts_export_toolbar(monkeypatch):
|
||||
"""收料就绪:无库存正文时,Export 工具栏 + 非 loading 即应放行。"""
|
||||
worker = _load_dsv_report_export()
|
||||
state = {
|
||||
@@ -239,10 +239,10 @@ def test_wait_receipt_result_ready_accepts_export_toolbar(monkeypatch):
|
||||
)
|
||||
monkeypatch.setattr(worker, "_debug_dsv_stage", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(worker, "_emit_debug_event", lambda *args, **kwargs: None)
|
||||
worker._wait_for_dsv_report_result_ready(_FakePage(), 2_000, kind="receipt")
|
||||
worker._wait_for_dsv_report_result_ready(_FakePage(), 2_000, kind="inbound")
|
||||
|
||||
|
||||
def test_ensure_dsv_receipt_rows_retries_then_export_fallback(monkeypatch):
|
||||
def test_ensure_dsv_inbound_rows_retries_then_export_fallback(monkeypatch):
|
||||
"""收料 DOM 无行时重试 View Report;仍无行不得抛空,继续导出。"""
|
||||
worker = _load_dsv_report_export()
|
||||
clicks: list[str] = []
|
||||
@@ -252,20 +252,20 @@ def test_ensure_dsv_receipt_rows_retries_then_export_fallback(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_browser_timeout_ms", lambda: 5_000)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_wait_dsv_report_receipt_rows",
|
||||
"_wait_dsv_report_inbound_rows",
|
||||
lambda page_arg, timeout_ms: (waits.append(timeout_ms) or next(row_outcomes, False)),
|
||||
)
|
||||
monkeypatch.setattr(worker, "_click_dsv_view_report", lambda page_arg: clicks.append("view"))
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms, kind="inventory": None)
|
||||
|
||||
worker._ensure_dsv_receipt_rows_or_export_fallback(page=object(), report_name="Receipt Detail")
|
||||
worker._ensure_dsv_inbound_rows_or_export_fallback(page=object(), report_name="Receipt Detail")
|
||||
|
||||
assert clicks == ["view"]
|
||||
assert waits == [5_000, 5_000]
|
||||
|
||||
|
||||
def test_run_dsv_export_uses_receipt_row_probe(monkeypatch):
|
||||
"""__export_kind__=receipt 时须走收料行探针,不得调用库存行 ensure。"""
|
||||
def test_run_dsv_export_uses_inbound_row_probe(monkeypatch):
|
||||
"""__export_kind__=inbound 时须走 inbound 行探针,不得调用库存行 ensure。"""
|
||||
worker = _load_dsv_report_export()
|
||||
calls: list[str] = []
|
||||
monkeypatch.setattr(worker, "_fill_report_parameters", lambda page_arg, source: None)
|
||||
@@ -273,8 +273,8 @@ def test_run_dsv_export_uses_receipt_row_probe(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_wait_dsv_report_ready", lambda page_arg, timeout_ms, kind="inventory": calls.append(f"wait:{kind}"))
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_ensure_dsv_receipt_rows_or_export_fallback",
|
||||
lambda page_arg, report_name: calls.append("receipt-rows"),
|
||||
"_ensure_dsv_inbound_rows_or_export_fallback",
|
||||
lambda page_arg, report_name: calls.append("inbound-rows"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
@@ -303,13 +303,13 @@ def test_run_dsv_export_uses_receipt_row_probe(monkeypatch):
|
||||
|
||||
result = worker._run_dsv_inventory_export_from_form(
|
||||
_Page(),
|
||||
{"__export_kind__": "receipt", "navigation": {"report_name": "Receipt Detail"}},
|
||||
{"__export_kind__": "inbound", "navigation": {"report_name": "Receipt Detail"}},
|
||||
)
|
||||
assert result == "download"
|
||||
assert "wait:receipt" in calls
|
||||
assert "receipt-rows" in calls
|
||||
assert "wait:inbound" in calls
|
||||
assert "inbound-rows" in calls
|
||||
assert "inventory-rows" not in calls
|
||||
assert "export:receipt" in calls
|
||||
assert "export:inbound" in calls
|
||||
|
||||
|
||||
def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
|
||||
@@ -324,7 +324,7 @@ def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
|
||||
export_mock = MagicMock(return_value="download")
|
||||
monkeypatch.setattr(worker.dsv_driver, "download_dsv360_inventory", export_mock)
|
||||
|
||||
result = worker._download_dsv360_inventory(page, {"task_no": "SN-1"}, source)
|
||||
result = worker._download_dsv360_onhand(page, {"task_no": "SN-1"}, source)
|
||||
|
||||
export_mock.assert_called_once_with(page, {"task_no": "SN-1"}, source)
|
||||
assert result == "download"
|
||||
|
||||
@@ -6,10 +6,10 @@ from app.models import ScheduleRun, ScheduleTask, User
|
||||
|
||||
|
||||
def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_path):
|
||||
"""POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。"""
|
||||
"""POST /api/internal/jobs/freight-rpa-onhand 应写入 batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
from app import db
|
||||
@@ -21,7 +21,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
|
||||
schedule_no="SCH-IJ-001",
|
||||
name="货代库存每日导出",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
data_source_type=None,
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
@@ -41,7 +41,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
|
||||
run_id = run.id
|
||||
|
||||
resp = client.post(
|
||||
"/api/internal/jobs/shipping-inventory-rpa",
|
||||
"/api/internal/jobs/freight-rpa-onhand",
|
||||
data=json.dumps({"run_no": run_no, "schedule_task_id": task_id}),
|
||||
content_type="application/json",
|
||||
)
|
||||
@@ -95,7 +95,7 @@ def test_internal_job_rejects_mismatched_schedule_task_id(client, app):
|
||||
task_id = task.id
|
||||
|
||||
resp = client.post(
|
||||
"/api/internal/jobs/shipping-inventory-rpa",
|
||||
"/api/internal/jobs/freight-rpa-onhand",
|
||||
data=json.dumps({"schedule_task_id": task_id}),
|
||||
content_type="application/json",
|
||||
)
|
||||
@@ -114,7 +114,7 @@ def test_internal_job_rejects_foreign_run_no(client, app):
|
||||
schedule_no="SCH-IJ-A",
|
||||
name="shipping task",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
data_source_type=None,
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
@@ -143,7 +143,7 @@ def test_internal_job_rejects_foreign_run_no(client, app):
|
||||
run_no = run.run_no
|
||||
|
||||
resp = client.post(
|
||||
"/api/internal/jobs/shipping-inventory-rpa",
|
||||
"/api/internal/jobs/freight-rpa-onhand",
|
||||
data=json.dumps({"schedule_task_id": task_a_id, "run_no": run_no}),
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
@@ -128,7 +128,7 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -151,9 +151,9 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app,
|
||||
drop_dir.mkdir()
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_DROP_DIR'] = str(drop_dir)
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -172,7 +172,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend
|
||||
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
field_id = _published_order_field()
|
||||
@@ -208,7 +208,7 @@ def test_empty_configuration_export_without_published_profile_is_rejected(app):
|
||||
"""没有受控解析定义时,空结果不能被用作站点可用性的替代证据。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -225,7 +225,7 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app,
|
||||
"""当前绑定方案的核心栏位仍在时,历史无关列缺失也必须直接成为验证证据。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -245,7 +245,7 @@ def test_verified_current_profile_does_not_auto_enable_ready_source(app, tmp_pat
|
||||
"""当前解析验证通过且硬门槛齐全时,测试回调仍不得自动启用;启停只走显式开关。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
@@ -268,7 +268,7 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm
|
||||
"""解析测试通过不绕过发货模板门禁,条件不完整的站点必须保持停用。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
@@ -289,7 +289,7 @@ def test_empty_export_does_not_auto_enable_ready_fixed_source(app, tmp_path):
|
||||
"""固定仓查询成功但无库存时,只写入验证事实,不得自动启用站点。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
seeded = _complete_test_run(source, tmp_path)
|
||||
@@ -313,7 +313,7 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app,
|
||||
"""同连接站点一次投递,混合成功、空库存及失败后仍独立汇总为部分失败。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
) as write_trigger:
|
||||
first = _source('BATCH_SOURCE_A', 'BATCH_LOGIN_A')
|
||||
second = _source('BATCH_SOURCE_B', 'BATCH_LOGIN_B')
|
||||
@@ -355,7 +355,7 @@ def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
||||
"""批次重试只新建失败站点运行,成功和空库存结果不会被重复导出。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('RETRY_SOURCE', 'RETRY_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -377,7 +377,7 @@ def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app,
|
||||
"""配置变更后的旧批次回调必须失效,未知运行号不能污染同批次状态。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('STALE_BATCH_SOURCE', 'STALE_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -405,7 +405,7 @@ def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
|
||||
"""页面刷新只能恢复仍在执行的批次,已结束批次不会反复占用进度面板。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('RESTORE_BATCH_SOURCE', 'RESTORE_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -427,7 +427,7 @@ def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path)
|
||||
"""Worker 领取回调只更新本批次当前运行,终态运行不得被重新打开。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source('PROGRESS_BATCH_SOURCE', 'PROGRESS_BATCH_LOGIN')
|
||||
seed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -460,7 +460,7 @@ def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
first = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -480,9 +480,9 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
"""RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
|
||||
app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS'] = 1
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
@@ -509,9 +509,9 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
|
||||
"""同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
|
||||
app.config['FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS'] = 10
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
first = _source('TIMEOUT_QUEUE_A', 'TIMEOUT_QUEUE_LOGIN')
|
||||
second = _source('TIMEOUT_QUEUE_B', 'TIMEOUT_QUEUE_LOGIN_B')
|
||||
@@ -537,7 +537,7 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
@@ -579,7 +579,7 @@ def test_rpa_profile_change_does_not_block_activation_hard_gates(app, tmp_path):
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
@@ -611,7 +611,7 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
completed = _complete_test_run(source, tmp_path)
|
||||
@@ -645,7 +645,7 @@ 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['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
'app.services.shipping_notice.onhand_trigger_batch.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
source = _source()
|
||||
failed = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
"""
|
||||
inventory RPA:Playwright Download.save_as 因浏览器关闭失败时,应按 downloads_path 目录兜底落盘。
|
||||
tests/test_inventory_rpa_download_save_fallback.py
|
||||
|
||||
用途:Playwright Download.save_as 因浏览器关闭失败时,onhand Worker 按下载目录兜底落盘。
|
||||
依赖:scripts/freight_rpa/onhand/onhand_rpa_worker.py 的 _save_download / _save_batch_download。
|
||||
逻辑:假 Download 抛出 TargetClosed;目录里已有的 xlsx 应被改成规范文件名。
|
||||
报表结构校验 _validate_onhand_excel 换成空操作,避免假字节触发门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +17,7 @@ from pathlib import Path
|
||||
|
||||
def _load_worker():
|
||||
module_path = (
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "onhand" / "onhand_rpa_worker.py"
|
||||
)
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
@@ -21,7 +26,7 @@ def _load_worker():
|
||||
common_dir = str(module_path.parent.parent / "common")
|
||||
if common_dir not in sys.path:
|
||||
sys.path.insert(0, common_dir)
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_save_fallback_test", module_path)
|
||||
spec = importlib.util.spec_from_file_location("onhand_rpa_worker_save_fallback_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
@@ -47,7 +52,8 @@ def test_save_batch_download_falls_back_when_browser_closed(monkeypatch):
|
||||
landed = drop_dir / "chromium_download.xlsx"
|
||||
landed.write_bytes(b"PK" + b"0" * 600)
|
||||
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
# [断言意图] 假 xlsx 只覆盖落盘兜底,跳过 onhand 报表结构校验。
|
||||
monkeypatch.setattr(worker, "_validate_onhand_excel", lambda _path: None)
|
||||
|
||||
out = worker._save_batch_download(
|
||||
_ClosedBrowserDownload(),
|
||||
@@ -72,7 +78,8 @@ def test_save_batch_download_reraises_when_fallback_missing(monkeypatch):
|
||||
drop_dir = Path(tmp) / "drop"
|
||||
drop_dir.mkdir()
|
||||
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
# [断言意图] 假 xlsx 只覆盖落盘兜底,跳过 onhand 报表结构校验。
|
||||
monkeypatch.setattr(worker, "_validate_onhand_excel", lambda _path: None)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_wait_for_new_download_file",
|
||||
@@ -102,7 +109,8 @@ def test_save_download_falls_back_when_browser_closed(monkeypatch):
|
||||
drop_dir.mkdir()
|
||||
landed = drop_dir / "raw.xlsx"
|
||||
landed.write_bytes(b"PK" + b"0" * 600)
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
# [断言意图] 假 xlsx 只覆盖落盘兜底,跳过 onhand 报表结构校验。
|
||||
monkeypatch.setattr(worker, "_validate_onhand_excel", lambda _path: None)
|
||||
|
||||
out = worker._save_download(
|
||||
_ClosedBrowserDownload(),
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""tt16c7d8e9f0a1b2 排程 job key 入站化迁移契约测试。
|
||||
|
||||
用途:锁定 tt16 迁移两侧契约——schedule_tasks.platform_api_path 三键更名
|
||||
(shipping-inventory-rpa→freight-rpa-onhand、freight-receipt-rpa→freight-rpa-inbound、
|
||||
freight-receipt-rpa-retention→freight-rpa-inbound-retention,随代码同窗口发布),
|
||||
并锁定迁移链挂接当前单 head(tt16a7b8c9d0e1f2,其上游为 tt15b6a7b8c9d0)。
|
||||
依赖:migrations/versions(_load 手法沿用 tests/services/in_transit_transfer/
|
||||
test_migration_inbound_rename.py 的 tt14 契约测试)、app_ctx(根 conftest
|
||||
app fixture 上下文别名)。
|
||||
逻辑:revision 链断言 + SQLite 真实 UPDATE upgrade/downgrade 往返
|
||||
(UPDATE 语句 SQLite/PG 通用,迁移语义以 PG 为准)。
|
||||
Fix round 1:桩表列名由计划骨架误写的 job_key 修正为真实列 platform_api_path
|
||||
(models/schedule.py:34,排程表无独立 job_key 列),并追加无关 key 对照行与
|
||||
往返前后命中计数断言,确保 UPDATE 真实生效且 WHERE 谓词不误伤其他 key。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[1] / "migrations" / "versions"
|
||||
|
||||
# 与 tt16._MAPPING 同源的三键对照(升级方向)。
|
||||
_MAPPING = {
|
||||
"shipping-inventory-rpa": "freight-rpa-onhand",
|
||||
"freight-receipt-rpa": "freight-rpa-inbound",
|
||||
"freight-receipt-rpa-retention": "freight-rpa-inbound-retention",
|
||||
}
|
||||
# 无关对照 key:全程不得被 UPDATE 触碰(验证 WHERE 谓词精确性)。
|
||||
_UNRELATED_KEY = "faq-aggregate-hot"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app_ctx(app):
|
||||
"""根 conftest app fixture 的语义别名:app fixture 产出时已处于 app_context 内。"""
|
||||
return app
|
||||
|
||||
|
||||
def _load(revision_prefix: str):
|
||||
for path in sorted(MIGRATIONS_DIR.glob(f"{revision_prefix}*.py")):
|
||||
spec = importlib.util.spec_from_file_location(path.stem, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
raise AssertionError(f"migration {revision_prefix} not found")
|
||||
|
||||
|
||||
def test_revision_chains_from_tt15():
|
||||
"""tt16 必须单头挂接:直接前驱为 tt16a7b8c9d0e1f2,链上溯两跳即 tt15b6a7b8c9d0。
|
||||
|
||||
[断言意图] 实施时 tt15 已被调拨域迁移 tt16a7b8c9d0e1f2 占用为前驱;
|
||||
本迁移若再直挂 tt15 会产生双 head,破坏 flask db upgrade,故锁两级链。
|
||||
"""
|
||||
migration = _load("tt16c7d8e9f0a1b2")
|
||||
assert migration.down_revision == "tt16a7b8c9d0e1f2"
|
||||
parent = _load(migration.down_revision)
|
||||
assert parent.down_revision == "tt15b6a7b8c9d0"
|
||||
|
||||
|
||||
def test_job_key_upgrade_downgrade(app_ctx):
|
||||
"""SQLite 往返:三旧行 upgrade 后全量换新 key,downgrade 精确还原旧行。
|
||||
|
||||
[断言意图] 桩表用真实列名 platform_api_path(迁移 SQL 在其上真实可执行);
|
||||
_MAPPING 三键在 upgrade 后不复存在、downgrade 后新键清零且旧行 id→key 对应
|
||||
关系逐行还原(双向 UPDATE 均为全表谓词替换);无关 key 对照行全程不变。
|
||||
"""
|
||||
engine = sa.create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
|
||||
# tt16 仅 UPDATE schedule_tasks.platform_api_path(真实列名,String(500)),
|
||||
# 无表结构变更:建最小桩表承接。
|
||||
sa.Table(
|
||||
"schedule_tasks", sa.MetaData(),
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("platform_api_path", sa.String(length=500)),
|
||||
).create(connection)
|
||||
|
||||
old_keys = list(_MAPPING)
|
||||
rows = [{"id": index + 1, "key": key} for index, key in enumerate(old_keys)]
|
||||
# id=4 为无关 key 对照行:升级/降级都不得被改写。
|
||||
rows.append({"id": len(rows) + 1, "key": _UNRELATED_KEY})
|
||||
connection.execute(
|
||||
sa.text("INSERT INTO schedule_tasks (id, platform_api_path) VALUES (:id, :key)"),
|
||||
rows,
|
||||
)
|
||||
|
||||
migration = _load("tt16c7d8e9f0a1b2")
|
||||
migration.op = operations
|
||||
|
||||
def _job_keys() -> dict[int, str]:
|
||||
result = connection.execute(
|
||||
sa.text("SELECT id, platform_api_path FROM schedule_tasks ORDER BY id")
|
||||
)
|
||||
return {row_id: key for row_id, key in result.fetchall()}
|
||||
|
||||
def _count_any_of(keys: list[str]) -> int:
|
||||
return connection.execute(sa.text(
|
||||
"SELECT COUNT(*) FROM schedule_tasks WHERE platform_api_path IN "
|
||||
"('" + "','".join(keys) + "')"
|
||||
)).scalar()
|
||||
|
||||
# [前置基线] 旧三键恰 3 行、新键 0 行、无关 key 恰 1 行。
|
||||
assert _count_any_of(old_keys) == 3
|
||||
assert _count_any_of(list(_MAPPING.values())) == 0
|
||||
assert _count_any_of([_UNRELATED_KEY]) == 1
|
||||
|
||||
# [STEP 1] upgrade:旧行逐行映射新键,旧键零残留,无关 key 不受影响。
|
||||
migration.upgrade()
|
||||
assert _job_keys() == {
|
||||
1: _MAPPING[old_keys[0]],
|
||||
2: _MAPPING[old_keys[1]],
|
||||
3: _MAPPING[old_keys[2]],
|
||||
4: _UNRELATED_KEY,
|
||||
}
|
||||
assert _count_any_of(old_keys) == 0
|
||||
assert _count_any_of(list(_MAPPING.values())) == 3
|
||||
assert _count_any_of([_UNRELATED_KEY]) == 1
|
||||
|
||||
# [STEP 2] downgrade:反向映射逐行还原旧键,新键零残留,无关 key 不受影响。
|
||||
migration.downgrade()
|
||||
assert _job_keys() == {row["id"]: row["key"] for row in rows}
|
||||
assert _count_any_of(old_keys) == 3
|
||||
assert _count_any_of(list(_MAPPING.values())) == 0
|
||||
assert _count_any_of([_UNRELATED_KEY]) == 1
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_receipt_excel_empty.py
|
||||
|
||||
用途:收料 Excel「有表头无明细」判空回归;钉死标题行不得当表头。
|
||||
依赖:openpyxl、scripts/freight_rpa/receipt/receipt_excel_empty。
|
||||
依赖:openpyxl、scripts/freight_rpa/inbound/inbound_excel_empty。
|
||||
逻辑:构造 DSV 标题+表头无数据簿;复制生产 drop 样例断言 empty。
|
||||
"""
|
||||
|
||||
@@ -16,14 +16,14 @@ import pytest
|
||||
from openpyxl import Workbook
|
||||
|
||||
_REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
_RECEIPT_DIR = _REPO_ROOT / 'scripts' / 'freight_rpa' / 'receipt'
|
||||
if str(_RECEIPT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_RECEIPT_DIR))
|
||||
_INBOUND_DIR = _REPO_ROOT / 'scripts' / 'freight_rpa' / 'inbound'
|
||||
if str(_INBOUND_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_INBOUND_DIR))
|
||||
|
||||
from receipt_excel_empty import ( # noqa: E402
|
||||
NoReceiptDataError,
|
||||
enforce_receipt_excel_not_empty,
|
||||
receipt_excel_has_detail_rows,
|
||||
from inbound_excel_empty import ( # noqa: E402
|
||||
NoInboundDataError,
|
||||
enforce_inbound_excel_not_empty,
|
||||
inbound_excel_has_detail_rows,
|
||||
)
|
||||
|
||||
_DROP_SAMPLE = (
|
||||
@@ -72,9 +72,9 @@ def test_title_row_must_not_count_as_detail(tmp_path: Path):
|
||||
"""
|
||||
path = tmp_path / 'header_only.xlsx'
|
||||
_write_dsv_title_header_only(path)
|
||||
assert receipt_excel_has_detail_rows(path) is False
|
||||
with pytest.raises(NoReceiptDataError, match='no_receipt_data'):
|
||||
enforce_receipt_excel_not_empty(path)
|
||||
assert inbound_excel_has_detail_rows(path) is False
|
||||
with pytest.raises(NoInboundDataError, match='no_receipt_data'):
|
||||
enforce_inbound_excel_not_empty(path)
|
||||
|
||||
|
||||
def test_header_plus_data_row_is_not_empty(tmp_path: Path):
|
||||
@@ -88,8 +88,8 @@ def test_header_plus_data_row_is_not_empty(tmp_path: Path):
|
||||
assert sheet is not None
|
||||
sheet.append(['Well Trust', 'HOX1', '0001', 'O', 'KN', 'WB1', 'Inbound', 'Closed', '01/01/2026', '', '0010', 'CBIS', '', '', 'SKU-1'])
|
||||
workbook.save(path)
|
||||
assert receipt_excel_has_detail_rows(path) is True
|
||||
enforce_receipt_excel_not_empty(path)
|
||||
assert inbound_excel_has_detail_rows(path) is True
|
||||
enforce_inbound_excel_not_empty(path)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _DROP_SAMPLE.is_file(), reason='production drop sample not present')
|
||||
@@ -101,6 +101,6 @@ def test_production_header_only_sample_is_empty(tmp_path: Path):
|
||||
"""
|
||||
target = tmp_path / _DROP_SAMPLE.name
|
||||
shutil.copy2(_DROP_SAMPLE, target)
|
||||
assert receipt_excel_has_detail_rows(target) is False
|
||||
with pytest.raises(NoReceiptDataError, match='no_receipt_data'):
|
||||
enforce_receipt_excel_not_empty(target)
|
||||
assert inbound_excel_has_detail_rows(target) is False
|
||||
with pytest.raises(NoInboundDataError, match='no_receipt_data'):
|
||||
enforce_inbound_excel_not_empty(target)
|
||||
@@ -63,17 +63,17 @@ def test_archive_rejects_bad_outcome_and_unclaimed_path(tmp_path):
|
||||
|
||||
|
||||
def test_inventory_worker_scans_with_claim(tmp_path):
|
||||
"""库存 Worker 扫描必须先领取(processing/),不得原地消费根目录文件。"""
|
||||
root = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory"
|
||||
text = (root / "inventory_rpa_worker.py").read_text(encoding="utf-8")
|
||||
"""onhand Worker 扫描必须先领取(processing/),不得原地消费根目录文件。"""
|
||||
root = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "onhand"
|
||||
text = (root / "onhand_rpa_worker.py").read_text(encoding="utf-8")
|
||||
assert "claim_trigger" in text
|
||||
# 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent
|
||||
assert text.count('trigger_path.parent / "failed"') == 0
|
||||
|
||||
|
||||
def test_receipt_worker_runs_periodic_disk_cleanup():
|
||||
"""收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。"""
|
||||
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
|
||||
"""inbound Worker 必须周期执行保留清理(对齐 onhand),孤儿 inbound_* Profile 必须纳入清理。"""
|
||||
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inbound" / "inbound_rpa_worker.py").read_text(encoding="utf-8")
|
||||
assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt
|
||||
cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
|
||||
assert '"receipt_"' in cleanup or "'receipt_'" in cleanup
|
||||
assert '"inbound_"' in cleanup or "'inbound_'" in cleanup
|
||||
@@ -35,11 +35,11 @@ def admin_jwt_headers(app):
|
||||
def test_platform_jobs_registered():
|
||||
"""内置 platform job 应已注册。"""
|
||||
keys = {job.key for job in list_platform_jobs()}
|
||||
assert "shipping-inventory-rpa" in keys
|
||||
assert "freight-rpa-onhand" in keys
|
||||
assert "faq-aggregate-hot" in keys
|
||||
assert "fixed-assets-snapshot" in keys
|
||||
assert "accounting-voucher-po-print" in keys
|
||||
assert get_platform_job("shipping-inventory-rpa") is not None
|
||||
assert get_platform_job("freight-rpa-onhand") is not None
|
||||
|
||||
|
||||
def test_unknown_platform_job_raises():
|
||||
@@ -62,7 +62,7 @@ def test_resolve_schedule_executor_dispatch():
|
||||
def test_normalize_job_key_extracts_last_segment_from_full_path():
|
||||
"""历史数据存完整内部路径或 URL 时,应提取最后一段作为 job key。"""
|
||||
assert normalize_job_key('/api/internal/jobs/faq-aggregate-hot') == 'faq-aggregate-hot'
|
||||
assert normalize_job_key('http://hxops.local/api/internal/jobs/shipping-inventory-rpa') == 'shipping-inventory-rpa'
|
||||
assert normalize_job_key('http://hxops.local/api/internal/jobs/freight-rpa-onhand') == 'freight-rpa-onhand'
|
||||
assert normalize_job_key('/api/internal/jobs/fixed_assets_snapshot?token=x') == 'fixed-assets-snapshot'
|
||||
assert normalize_job_key('faq_aggregate_hot') == 'faq-aggregate-hot'
|
||||
assert normalize_job_key(None) == ''
|
||||
@@ -97,7 +97,7 @@ def test_migrate_legacy_shipping_inventory_rpa():
|
||||
"platform_api_path": "/123",
|
||||
})
|
||||
assert migrated["schedule_type"] == "platform_job"
|
||||
assert migrated["platform_api_path"] == "shipping-inventory-rpa"
|
||||
assert migrated["platform_api_path"] == "freight-rpa-onhand"
|
||||
assert migrated["data_source_type"] is None
|
||||
|
||||
|
||||
@@ -135,7 +135,7 @@ def test_run_platform_job_unknown_key(app):
|
||||
schedule_no="SCH-REG-001",
|
||||
name="test",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
)
|
||||
@@ -208,14 +208,14 @@ def test_get_platform_jobs_api(client, admin_jwt_headers):
|
||||
assert res.status_code == 200
|
||||
body = res.get_json()
|
||||
keys = {item["key"] for item in body}
|
||||
assert "shipping-inventory-rpa" in keys
|
||||
assert "freight-rpa-onhand" in keys
|
||||
assert "faq-aggregate-hot" in keys
|
||||
assert "disabled-for-filter-test" not in keys
|
||||
assert all(item.get("enabled") is True for item in body)
|
||||
assert all("label" in item for item in body)
|
||||
# 内置 job 应返回稳定 i18n key,供前端 $t(label_key) 渲染
|
||||
by_key = {item["key"]: item for item in body}
|
||||
assert by_key["shipping-inventory-rpa"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
|
||||
assert by_key["freight-rpa-onhand"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
|
||||
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
|
||||
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
|
||||
assert by_key["accounting-voucher-po-print"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherPoPrint"
|
||||
|
||||
@@ -61,7 +61,7 @@ def test_platform_task_definitions_returns_params_schema(client, admin_jwt_heade
|
||||
assert body['success'] is True
|
||||
by_type = {item['task_type']: item for item in body['data']}
|
||||
# 货代库存 RPA:multi_select 库存源字段
|
||||
rpa = by_type['shipping-inventory-rpa']
|
||||
rpa = by_type['freight-rpa-onhand']
|
||||
assert rpa['category'] == 'shipping'
|
||||
schema_keys = {f['key']: f for f in rpa['params_schema']}
|
||||
assert schema_keys['source_codes']['type'] == 'multi_select'
|
||||
@@ -106,7 +106,7 @@ def test_platform_task_options_unknown_source_rejected(client, admin_jwt_headers
|
||||
def test_validate_task_params_fills_defaults(app):
|
||||
"""未提供字段应回填注册表默认值。"""
|
||||
with app.app_context():
|
||||
result = validate_task_params('shipping-inventory-rpa', {}, check_options=False)
|
||||
result = validate_task_params('freight-rpa-onhand', {}, check_options=False)
|
||||
assert result == {'source_codes': []}
|
||||
result_faq = validate_task_params('faq-aggregate-hot', {}, check_options=False)
|
||||
assert result_faq == {'app_id': None}
|
||||
@@ -125,7 +125,7 @@ def test_validate_task_params_rejects_wrong_type(app):
|
||||
source_code = _enabled_source_code()
|
||||
with pytest.raises(JobParamsValidationError, match='list of option values'):
|
||||
validate_task_params(
|
||||
'shipping-inventory-rpa',
|
||||
'freight-rpa-onhand',
|
||||
{'source_codes': source_code},
|
||||
check_options=False,
|
||||
)
|
||||
@@ -137,13 +137,13 @@ def test_validate_task_params_checks_option_range(app):
|
||||
source_code = _enabled_source_code()
|
||||
with pytest.raises(JobParamsValidationError, match='not in options'):
|
||||
validate_task_params(
|
||||
'shipping-inventory-rpa',
|
||||
'freight-rpa-onhand',
|
||||
{'source_codes': ['NOT_A_REAL_SOURCE']},
|
||||
check_options=True,
|
||||
)
|
||||
# 合法值应通过
|
||||
result = validate_task_params(
|
||||
'shipping-inventory-rpa',
|
||||
'freight-rpa-onhand',
|
||||
{'source_codes': [source_code]},
|
||||
check_options=True,
|
||||
)
|
||||
@@ -154,7 +154,7 @@ def test_validate_task_params_passes_advanced_through(app):
|
||||
"""_advanced 高级 JSON 区域应原样透传(历史/特殊任务兜底)。"""
|
||||
with app.app_context():
|
||||
result = validate_task_params(
|
||||
'shipping-inventory-rpa',
|
||||
'freight-rpa-onhand',
|
||||
{'source_codes': [], ADVANCED_PARAMS_KEY: {'timeout_seconds': 300}},
|
||||
check_options=False,
|
||||
)
|
||||
@@ -175,7 +175,7 @@ def _create_platform_schedule(client, headers, owner_id, *, job_params=None, ext
|
||||
payload = {
|
||||
'name': 'contract test',
|
||||
'schedule_type': 'platform_job',
|
||||
'platform_api_path': 'shipping-inventory-rpa',
|
||||
'platform_api_path': 'freight-rpa-onhand',
|
||||
'owner_user_id': owner_id,
|
||||
'cron_expr': '0 3 * * *',
|
||||
}
|
||||
@@ -365,7 +365,7 @@ def test_faq_job_prefers_job_params_over_dify_agent_id(app):
|
||||
|
||||
def test_shipping_rpa_filter_prefers_job_params(app):
|
||||
"""货代 RPA 应优先按 job_params.source_codes 筛选库存源。"""
|
||||
from app.services.schedule.shipping_inventory_rpa_job import _filter_sources
|
||||
from app.services.schedule.freight_onhand_rpa_job import _filter_sources
|
||||
|
||||
with app.app_context():
|
||||
source_code = _enabled_source_code()
|
||||
@@ -536,7 +536,7 @@ def test_enable_rejects_disabled_platform_job(client, admin_jwt_headers, owner_i
|
||||
register_platform_job,
|
||||
)
|
||||
|
||||
job_key = 'shipping-inventory-rpa'
|
||||
job_key = 'freight-rpa-onhand'
|
||||
original = get_platform_job(job_key)
|
||||
assert original is not None
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
tests/test_shipping_inventory_configuration.py
|
||||
|
||||
用途:验证库存源主数据、外部系统映射约束和 RPA 凭据加密的阶段一契约。
|
||||
依赖:Flask app/db、库存配置模型、credential_crypto、inventory_source_repository。
|
||||
依赖:Flask app/db、库存配置模型、freight_rpa.common.credential_crypto、inventory_source_repository。
|
||||
逻辑:阶段二前锁定最小数据安全与关系约束,避免错误配置进入路由或 RPA 执行链路。
|
||||
"""
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.models import (
|
||||
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine, ShippingOrderTask, ShippingRpaProfile,
|
||||
)
|
||||
from app.services.shipping_notice.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source, get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.inventory_external_mapping import resolve_external_warehouse
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_shipping_notice_inventory_rpa_archive.py
|
||||
|
||||
用途:库存 RPA 原始库存 ZIP 归档、summary 可见性与 admin API 路由单测。
|
||||
依赖:shipping_inventory_rpa_archive、api/schedule/runs、query_service、shipping_inventory_rpa_finalize。
|
||||
依赖:freight_onhand_rpa_archive、api/schedule/runs、query_service、freight_onhand_rpa_finalize。
|
||||
逻辑:finalize 预生成 ZIP;列表只读 summary;下载 send_file 归档路径。
|
||||
"""
|
||||
|
||||
@@ -26,7 +26,7 @@ from app.services.schedule.scheduler_service import (
|
||||
_build_schedule_run_wecom_description,
|
||||
_build_schedule_run_wecom_jump_params,
|
||||
)
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import (
|
||||
from app.services.schedule.freight_onhand_rpa_archive import (
|
||||
inventory_raw_zip_available_from_summary,
|
||||
inventory_raw_zip_download_name,
|
||||
inventory_rpa_attachment_stem,
|
||||
@@ -130,7 +130,7 @@ def test_serialize_run_reads_inventory_raw_zip_available_from_summary(app):
|
||||
def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_path):
|
||||
"""finalize 预生成应落盘 ZIP 并返回 summary 字段。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
xlsx.write_bytes(b"fake-xlsx-content")
|
||||
|
||||
@@ -176,7 +176,7 @@ def test_persist_inventory_rpa_raw_zip_archive_writes_zip_and_summary(app, tmp_p
|
||||
def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_files(app, tmp_path):
|
||||
"""无可读快照时不生成 ZIP。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
with app.app_context():
|
||||
run = _make_inventory_run_with_created(
|
||||
@@ -193,7 +193,7 @@ def test_persist_inventory_rpa_raw_zip_archive_returns_false_when_no_packable_fi
|
||||
def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp_path):
|
||||
"""created 有记录但磁盘文件缺失时不应生成 ZIP。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
with app.app_context():
|
||||
run = _make_inventory_run_with_created(
|
||||
@@ -219,7 +219,7 @@ def test_persist_inventory_rpa_raw_zip_archive_skips_missing_disk_files(app, tmp
|
||||
def test_resolve_inventory_raw_zip_download_returns_path_and_name(app, tmp_path):
|
||||
"""下载解析应返回归档路径与建议文件名。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
xlsx.write_bytes(b"fake-xlsx-content")
|
||||
|
||||
@@ -262,7 +262,7 @@ def test_resolve_inventory_raw_zip_download_raises_when_archive_missing(app):
|
||||
def test_resolve_inventory_raw_zip_download_rejects_path_outside_archive_dir(app, tmp_path):
|
||||
"""summary 指向归档目录外的真实文件时必须 404。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
outside_zip = tmp_path / "outside.zip"
|
||||
outside_zip.write_bytes(b"fake-zip")
|
||||
@@ -286,7 +286,7 @@ def test_resolve_inventory_raw_zip_download_rejects_non_zip_suffix(app, tmp_path
|
||||
"""summary 指向非 .zip 后缀文件时必须 404。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
archive_dir.mkdir(parents=True)
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
|
||||
fake_file = archive_dir / "RUN-ARCH-RESOLVE-BAD.txt"
|
||||
fake_file.write_bytes(b"not-a-zip")
|
||||
@@ -414,7 +414,7 @@ def test_notify_schedule_run_wecom_jump_url_points_to_admin_schedules(app, monke
|
||||
app.config["WECOM_NOTIFY_ENABLED"] = True
|
||||
app.config["WECOM_PUBLIC_BASE_URL"] = "https://hxops.example.com"
|
||||
app.config["WECOM_NOTIFY_BASE_URL"] = "http://legacy.internal:8890/"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(tmp_path / "archives")
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(tmp_path / "archives")
|
||||
|
||||
user = User(
|
||||
username="wecom_jump_user",
|
||||
@@ -482,7 +482,7 @@ def test_get_inventory_raw_zip_returns_zip_with_correct_filename(
|
||||
):
|
||||
"""admin 鉴权通过时应返回 application/zip 且展示名为库存RPA-*-库存.zip。"""
|
||||
archive_dir = tmp_path / "inventory_archives"
|
||||
app.config["FREIGHT_RPA_INVENTORY_ARCHIVE_DIR"] = str(archive_dir)
|
||||
app.config["FREIGHT_RPA_ONHAND_ARCHIVE_DIR"] = str(archive_dir)
|
||||
xlsx = tmp_path / "inventory.xlsx"
|
||||
xlsx.write_bytes(b"fake-xlsx-content")
|
||||
|
||||
|
||||
@@ -191,7 +191,9 @@ def test_auto_inventory_missing_snapshot_triggers_rpa(monkeypatch):
|
||||
trigger = {'status': 'running', 'task_id': task.task_no, 'rpa': {'attempts': 1}}
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa',
|
||||
lambda _task, *, mode, allow_auto_retry=True: trigger,
|
||||
# source_codes:inventory_workflow.ensure_inventory 自 70dd0051b 起透传 scoped 源列表,
|
||||
# 测试桩需同步接受(修复既有签名漂移,与本任务平移无关)。
|
||||
lambda _task, *, mode, allow_auto_retry=True, source_codes=None: trigger,
|
||||
)
|
||||
|
||||
result = inventory_workflow.ensure_inventory({
|
||||
@@ -225,7 +227,9 @@ def test_auto_inventory_uses_per_source_attempt_identity_contract(app, monkeypat
|
||||
monkeypatch.setattr(workflow, 'task_rpa_inventory_source', lambda _task: {'source_code': 'DSV360_AWSDU'})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
|
||||
lambda actual_task, *, mode, allow_auto_retry=True: calls.append((actual_task, mode)) or prepared,
|
||||
# source_codes:ensure_inventory_via_rpa 会透传 scoped 源列表,
|
||||
# 测试桩需同步接受(修复既有签名漂移,与本任务平移无关)。
|
||||
lambda actual_task, *, mode, allow_auto_retry=True, source_codes=None: calls.append((actual_task, mode)) or prepared,
|
||||
)
|
||||
monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_args, **_kwargs: None)
|
||||
@@ -641,7 +645,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_mixed.xlsx"
|
||||
@@ -683,7 +687,7 @@ def test_rpa_snapshot_persists_confirmed_profile_mapping(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "inventory-mapping-confirmed.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -769,7 +773,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "batch_task_success.xlsx"
|
||||
@@ -854,7 +858,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = ShippingOrderTask(
|
||||
@@ -981,7 +985,7 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "crane-multi-warehouse.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("CRANE-WH").getvalue())
|
||||
|
||||
@@ -1054,7 +1058,7 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "crane-unresolved-link.xlsx"
|
||||
sample.write_bytes(
|
||||
inventory_xlsx_with_warehouse(
|
||||
@@ -1301,7 +1305,7 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "orphan_task.xlsx"
|
||||
with open(sample, "wb") as handle:
|
||||
@@ -1394,13 +1398,13 @@ def test_per_source_timeout_archives_unclaimed_trigger_into_failed(app, tmp_path
|
||||
|
||||
def test_inventory_trigger_writes_without_online_worker(app, tmp_path, monkeypatch):
|
||||
"""投递库存 trigger 只依赖共享目录可写,Worker 可在稍后启动并领取。"""
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
|
||||
with app.app_context():
|
||||
trigger_dir = tmp_path / 'inventory_triggers'
|
||||
app.config['FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR'] = str(trigger_dir)
|
||||
app.config['FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR'] = str(trigger_dir)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready',
|
||||
'app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready',
|
||||
lambda: (_ for _ in ()).throw(AssertionError('trigger write must not require worker heartbeat')),
|
||||
)
|
||||
|
||||
@@ -1515,7 +1519,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "reuse_ingest_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1587,7 +1591,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
run_no = "RUN-REUSE-MISMATCH"
|
||||
|
||||
@@ -1642,7 +1646,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample_a = drop_dir / "task_a.xlsx"
|
||||
sample_b = drop_dir / "task_b.xlsx"
|
||||
sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1714,7 +1718,7 @@ def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path,
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir(parents=True, exist_ok=True)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "failed_before_confirm.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
callback_calls: list[dict] = []
|
||||
@@ -1775,7 +1779,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
sample = drop_dir / "shared.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
run_no = "RUN-SHARED-LINK"
|
||||
@@ -1851,7 +1855,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "post_commit.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1894,7 +1898,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "promote_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -1982,13 +1986,13 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
|
||||
def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch):
|
||||
"""callback 归档失败时应写入持久化 cleanup job。"""
|
||||
from app import db
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import callback_cleanup_queue_dir
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import callback_cleanup_queue_dir
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "move_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -2021,13 +2025,13 @@ def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, m
|
||||
"""move 与 quarantine 均失败时,仍应以原路径入队且 API 返回 ok。"""
|
||||
import json
|
||||
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import callback_cleanup_queue_dir
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import callback_cleanup_queue_dir
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
|
||||
from tests.conftest import scheduled_rpa_batch_item
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "quarantine_fail.xlsx"
|
||||
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
|
||||
@@ -2146,7 +2150,7 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
|
||||
|
||||
def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_path):
|
||||
"""cleanup 队列应由启动恢复独立消费,不依赖下一次 callback。"""
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
from app.services.freight_rpa.onhand.callback_cleanup import (
|
||||
callback_cleanup_queue_dir,
|
||||
enqueue_callback_file_move,
|
||||
recover_pending_rpa_callback_cleanup_jobs,
|
||||
@@ -2156,7 +2160,7 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat
|
||||
processed_dir = tmp_path / "processed"
|
||||
drop_dir.mkdir()
|
||||
processed_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_INVENTORY_PROCESSED_DIR"] = str(processed_dir)
|
||||
|
||||
quarantine = drop_dir / ".hxops_quarantine"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_shipping_notice_inventory_schedule.py
|
||||
|
||||
用途:货代库存 RPA 排程 executor、defer/finalize 契约与 source 过滤单测。
|
||||
依赖:ScheduleTask/ScheduleRun、shipping_inventory_rpa_job、shipping_inventory_rpa_finalize。
|
||||
依赖:ScheduleTask/ScheduleRun、freight_onhand_rpa_job、freight_onhand_rpa_finalize。
|
||||
逻辑:覆盖 trigger 写入、awaiting 终态、回调 finalize、超时回收。
|
||||
"""
|
||||
|
||||
@@ -14,7 +14,7 @@ import pytest
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig, User
|
||||
from app.services.schedule.scheduler_service import run_task_now
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
from app.services.schedule.freight_onhand_rpa_finalize import (
|
||||
_build_finalize_details,
|
||||
_compute_run_status,
|
||||
is_awaiting_rpa_schedule_run,
|
||||
@@ -22,7 +22,7 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
)
|
||||
from app.services.schedule import reload_config, resolve_schedule_header
|
||||
from app.services.schedule.shipping_inventory_rpa_job import (
|
||||
from app.services.schedule.freight_onhand_rpa_job import (
|
||||
_filter_sources,
|
||||
run_shipping_inventory_rpa_schedule,
|
||||
)
|
||||
@@ -79,7 +79,7 @@ def _make_inventory_schedule_task(
|
||||
schedule_no=schedule_no,
|
||||
name="货代库存每日导出",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="shipping-inventory-rpa",
|
||||
platform_api_path="freight-rpa-onhand",
|
||||
data_source_type=None,
|
||||
owner_user_id=user.id,
|
||||
cron_expr="0 3 * * *",
|
||||
@@ -103,7 +103,7 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
|
||||
"""排程 executor 应写入 inventory_export_batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -135,7 +135,7 @@ def test_run_task_now_defers_inventory_rpa_until_callback(app, tmp_path):
|
||||
"""run_task_now 写 trigger 后应保持 running 且 awaiting_rpa=true。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -157,7 +157,7 @@ def test_deferred_run_sets_started_at_when_missing(app, tmp_path):
|
||||
"""复用无 started_at 的 run 时,defer 应补写 started_at,避免立即超时回收。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
task = _make_inventory_schedule_task(
|
||||
@@ -244,7 +244,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
|
||||
"""全部 source 成功但 Excel 导出失败时应降为 partial_failed 并写入 error_message。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_excel_fail.xlsx"
|
||||
@@ -254,7 +254,7 @@ def test_finalize_excel_failure_marks_partial_failed(app, tmp_path, monkeypatch)
|
||||
raise RuntimeError("excel exploded")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.shipping_inventory_rpa_finalize.export_schedule_result_excel",
|
||||
"app.services.schedule.freight_onhand_rpa_finalize.export_schedule_result_excel",
|
||||
_excel_boom,
|
||||
)
|
||||
|
||||
@@ -309,7 +309,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
|
||||
"""finalize 失败时应写入 run 错误摘要并在回调 data 暴露 manual_retryable(需人工/接口重试)。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_fail_finalize.xlsx"
|
||||
@@ -319,7 +319,7 @@ def test_finalize_failure_exposes_manual_retryable_status(app, tmp_path, monkeyp
|
||||
raise RuntimeError("finalize exploded")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.shipping_inventory_rpa_finalize._build_finalize_details",
|
||||
"app.services.schedule.freight_onhand_rpa_finalize._build_finalize_details",
|
||||
_boom,
|
||||
)
|
||||
|
||||
@@ -373,7 +373,7 @@ def test_finalize_inventory_rpa_schedule_run_after_callback(app, tmp_path):
|
||||
drop_dir.mkdir()
|
||||
processed_dir = drop_dir / "processed"
|
||||
processed_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_sample.xlsx"
|
||||
@@ -516,7 +516,7 @@ def test_finalize_partial_callback_marks_partial_failed(app, tmp_path):
|
||||
"""回调结果少于触发源数时,排程应 partial_failed。"""
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
|
||||
sample = drop_dir / "inventory_partial.xlsx"
|
||||
@@ -653,10 +653,10 @@ def test_is_awaiting_rpa_schedule_run_helper(app):
|
||||
|
||||
|
||||
def test_inventory_rpa_excel_headers_survive_reload_config(app):
|
||||
"""reload_config 后 shipping-inventory-rpa 表头仍应可用。"""
|
||||
"""reload_config 后 freight-rpa-onhand 表头仍应可用。"""
|
||||
with app.app_context():
|
||||
reload_config()
|
||||
header_order, header_labels = resolve_schedule_header("shipping-inventory-rpa")
|
||||
header_order, header_labels = resolve_schedule_header("freight-rpa-onhand")
|
||||
assert header_order
|
||||
assert header_labels.get("inventory_file_no") == "库存快照号"
|
||||
|
||||
@@ -753,7 +753,7 @@ def test_scheduled_batch_progress_updates_run_counts(app):
|
||||
db.session.commit()
|
||||
|
||||
result = report_inventory_batch_progress({
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "RUN-PROGRESS:batch:C1",
|
||||
"batch_run_no": "RUN-PROGRESS",
|
||||
"run_no": "RUN-PROGRESS",
|
||||
@@ -795,7 +795,7 @@ def test_scheduled_batch_progress_rejects_mismatched_run_no(app):
|
||||
db.session.commit()
|
||||
|
||||
result = report_inventory_batch_progress({
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "RUN-PROGRESS-WRONG:batch:C1",
|
||||
"batch_run_no": "RUN-PROGRESS-WRONG",
|
||||
"schedule_run_id": run.id,
|
||||
@@ -834,7 +834,7 @@ def test_scheduled_batch_progress_noop_after_finalized(app):
|
||||
db.session.commit()
|
||||
|
||||
result = report_inventory_batch_progress({
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"schema_version": "freight_rpa.onhand.v1",
|
||||
"callback_id": "RUN-PROGRESS-FINAL:batch:C1",
|
||||
"batch_run_no": "RUN-PROGRESS-FINAL",
|
||||
"schedule_run_id": run.id,
|
||||
@@ -853,7 +853,7 @@ def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "missing_warehouse.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
@@ -883,7 +883,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "retry_snapshot.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
@@ -892,7 +892,7 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
raise RuntimeError("finalize exploded")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.schedule.shipping_inventory_rpa_finalize._build_finalize_details",
|
||||
"app.services.schedule.freight_onhand_rpa_finalize._build_finalize_details",
|
||||
_boom,
|
||||
)
|
||||
|
||||
@@ -942,11 +942,11 @@ def test_scheduled_finalize_retry_reuses_existing_snapshot(app, tmp_path, monkey
|
||||
def test_scheduled_finalize_retry_success_moves_callback_file(app, tmp_path, monkeypatch):
|
||||
"""finalize 首次失败、重试成功后应归档 callback 原文件。"""
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.services.schedule import shipping_inventory_rpa_finalize as finalize_mod
|
||||
from app.services.schedule import freight_onhand_rpa_finalize as finalize_mod
|
||||
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_DROP_DIR"] = str(drop_dir)
|
||||
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
|
||||
sample = drop_dir / "retry_move.xlsx"
|
||||
_write_sample_inventory(sample, "AWSDU")
|
||||
|
||||
@@ -2,19 +2,19 @@
|
||||
backend/tests/test_shipping_notice_rpa_trigger_for_task.py
|
||||
|
||||
用途:验证按需库存导出仅生成 v2 batch trigger,并携带完整冻结身份。
|
||||
依赖:shipping_notice.rpa、pytest app/tmp_path 夹具。
|
||||
依赖:shipping_notice.onhand_trigger_batch、pytest app/tmp_path 夹具。
|
||||
逻辑:构造 connector_type 库存连接器载荷,检查 trigger 文件分支与关键字段。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_trigger_for_task
|
||||
|
||||
|
||||
def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch):
|
||||
"""batch 开启时单票按需应写 inventory_export_batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config.pop("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", None)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
|
||||
|
||||
@@ -41,7 +41,8 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch):
|
||||
trigger_files = list(trigger_dir.glob("inventory_export_batch_*.json"))
|
||||
assert trigger_files
|
||||
payload = __import__("json").loads(trigger_files[0].read_text(encoding="utf-8"))
|
||||
assert payload["action"] == "inventory_export_batch"
|
||||
assert payload["action"] == "onhand_export_batch"
|
||||
assert payload["schema_version"] == "freight_rpa.onhand.v1"
|
||||
item = payload["inventory_sources"][0]
|
||||
assert item["task_no"] == "SN-ON-DEMAND-1"
|
||||
assert item["source_code"] == "DSV360_AWSDU"
|
||||
@@ -55,7 +56,7 @@ def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path):
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False
|
||||
|
||||
source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}}
|
||||
@@ -68,10 +69,10 @@ def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path):
|
||||
def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_path):
|
||||
"""平台 trigger 仅保留业务 connector,且明确给 worker 兼容的 driver 与登录入口。"""
|
||||
import json
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
with app.app_context():
|
||||
path = write_inventory_export_batch_trigger("RUN-DBS", [{
|
||||
"source_code": "UNKNOWN_FOR_TEST", "connector_type": "dbs", "rpa_profile_code": "DBS_TEST",
|
||||
@@ -89,10 +90,10 @@ def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_p
|
||||
def test_batch_trigger_writes_explicit_v2_callback_identity(app, tmp_path):
|
||||
"""新 batch Trigger 必须显式写入顶层和逐源 callback_id,Worker 不得推导。"""
|
||||
import json
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.onhand_trigger_batch import write_inventory_export_batch_trigger
|
||||
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True
|
||||
source = {
|
||||
"source_code": "DBS",
|
||||
|
||||
@@ -459,10 +459,10 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
|
||||
headers = _tool_headers(app)
|
||||
trigger = tmp_path / "inventory_triggers"
|
||||
trigger.mkdir()
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS"] = 1
|
||||
app.config["FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR"] = str(trigger)
|
||||
app.config["FREIGHT_RPA_ONHAND_TIMEOUT_SECONDS"] = 1
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||||
"app.services.freight_rpa.common.worker_heartbeat.assert_inventory_rpa_worker_ready",
|
||||
lambda: None,
|
||||
)
|
||||
|
||||
|
||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user