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
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user