refactor(rpa): 重构货代RPA上传成功判定与按需库存trigger构造

This commit is contained in:
hugo committed 2026-09-04 02:47:58 +08:00
1 parent 420f1a4abb
commit fee28bd1e9
8 files changed
+1019 -348

No files matched your search

@@ -40,7 +40,7 @@ def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int
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='failed',
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}],
)
@@ -20,7 +20,7 @@ from typing import Any
from app import db
from app.core.errors import AppError, ServiceUnavailableError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_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 (
@@ -78,6 +78,30 @@ from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.task_disposition_service import task_execution_block_reason
def _workflow_owner(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | ShippingOrderTask:
"""将正式 Notice 输入解析为 OT owner;库存运行事实统一写入 OT。"""
if isinstance(task, ShippingOrderTask):
return task
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id:
owner = db.session.get(ShippingOrderTask, int(order_task_id))
if owner is not None:
return owner
return task
def _set_workflow_error(task: ShippingNotice | ShippingOrderTask, message: str | None) -> None:
"""写入库存流程错误;正式 Notice 通过关联 OT 承接。"""
owner = _workflow_owner(task)
if hasattr(owner, 'error_message'):
owner.error_message = message
def _workflow_error(task: ShippingNotice | ShippingOrderTask) -> str | None:
"""读取库存流程错误;正式 Notice 通过关联 OT 承接。"""
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:
@@ -160,34 +184,20 @@ def _try_reuse_inventory_snapshot(
)
db.session.flush()
cached_lines = [
row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)
]
if cached_lines:
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
try:
lines, column_meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError, AppError):
lines, column_meta = [], {}
if lines:
return inventory_loaded_response(
task,
cached_lines,
column_meta={"source": "snapshot_reuse"},
lines,
column_meta=column_meta,
source="snapshot_reuse",
event_type="inventory_snapshot_reused",
)
path = Path(snapshot.storage_path)
if path.is_file():
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
lines, column_meta = parse_inventory_snapshot_file(snapshot)
if lines:
snapshot.inventory_lines_json = lines
snapshot.line_count = len(lines)
return inventory_loaded_response(
task,
lines,
column_meta=column_meta,
source="snapshot_reuse",
event_type="inventory_snapshot_reused",
)
db.session.commit()
return tool_response(
status="running",
@@ -209,9 +219,11 @@ def _save_last_inventory_rpa_runtime(task: ShippingNotice, payload: dict[str, An
source_code = str(payload.get("source_code") or "").strip()
if source_code:
runtime["source_code"] = source_code
step_payload = dict(task.step_payload_json or {})
step_payload["last_inventory_rpa_runtime"] = runtime
task.step_payload_json = step_payload
owner = _workflow_owner(task)
if hasattr(owner, 'step_payload_json'):
step_payload = dict(owner.step_payload_json or {})
step_payload["last_inventory_rpa_runtime"] = runtime
owner.step_payload_json = step_payload
return runtime
@@ -252,10 +264,10 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int |
Returns:
tuple[int | None, int | None, int | None]: (elapsed_seconds, timeout_seconds, remaining_seconds)。
"""
if (
task.pending_human_reason != PH_RPA_PENDING
or task.inventory_lines_json
):
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
if task_blocking_reason(task) != PH_RPA_PENDING or has_ready_inventory_file_for_task(task):
return None, None, None
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
if not last_trigger or not isinstance(last_trigger.created_at, datetime):
@@ -303,12 +315,12 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
)
db.session.flush()
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel"
_set_workflow_error(task, "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel")
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
message=_workflow_error(task),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
)
@@ -316,9 +328,12 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]:
"""从任务正式库存身份推导快照预期二元组。"""
from app.services.shipping_notice.inventory_source_gate import task_inventory_identity
identity = task_inventory_identity(task)
return (
str(task.inventory_source_code or "").strip().upper(),
str(task.inventory_warehouse_id or "").strip().upper(),
str(identity['inventory_source_code'] or "").strip().upper(),
str(identity['inventory_warehouse_id'] or "").strip().upper(),
)
@@ -627,23 +642,29 @@ def _resolve_effective_callback_run_no(task: ShippingNotice, payload: dict[str,
return _expected_rpa_callback_run_no(task)
def _lock_task_for_rpa_callback(task: ShippingNotice) -> ShippingNotice:
"""对任务行加悲观锁,防止并发回调重复消费同一轮次。"""
def _lock_task_for_rpa_callback(task: ShippingOrderTask) -> ShippingOrderTask:
"""对订单任务行加悲观锁,防止并发回调重复消费同一轮次。"""
if task.id is None:
return task
# ShippingNotice 默认关系加载会带 shipping_case 外连接;PostgreSQL 不允许
# 对外连接空值端执行 FOR UPDATE。回调只需锁任务主表,避免成功文件回调在入库前失败。
return (
db.session.query(ShippingNotice)
db.session.query(ShippingOrderTask)
.filter_by(id=task.id)
.with_for_update(of=ShippingNotice)
.with_for_update(of=ShippingOrderTask)
.one()
)
def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str:
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
return str(task.inventory_rpa_consumed_run_no or "").strip()
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:
@@ -651,7 +672,16 @@ def _mark_inventory_rpa_run_no_consumed(task: ShippingNotice, run_no: str) -> No
effective = str(run_no or "").strip()
if not effective:
return
task.inventory_rpa_consumed_run_no = effective
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:
@@ -811,7 +841,9 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。
"""
callback_source = str(payload.get("source_code") or "").strip().upper()
task_source = str(task.inventory_source_code or "").strip().upper()
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
task_sources = set(task_frozen_inventory_source_codes(task))
if not callback_source:
return tool_response(
status="failed",
@@ -819,7 +851,7 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
message="RPA 成功回调缺少 source_code,已拒绝入库",
data=serialize_task_for_tool(task),
)
if not task_source or callback_source != task_source:
if callback_source not in task_sources:
return tool_response(
status="failed",
task=task,
@@ -829,10 +861,12 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task_source)
source = get_database_inventory_source(callback_source)
is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
callback_wh = str(payload.get("warehouse_id") or "").strip().upper()
task_wh = str(task.inventory_warehouse_id or "").strip().upper()
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
task_wh = resolve_inventory_source_warehouse_id(task, source=source) or ''
if is_fixed and (not callback_wh or callback_wh != task_wh):
return tool_response(
status="failed",
@@ -1026,7 +1060,9 @@ def _batch_snapshot_verify_warehouse_id(
if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match':
return None
if task:
warehouse_id = str(task.inventory_warehouse_id or "").strip().upper()
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
warehouse_id = resolve_inventory_source_warehouse_id(task, source=source) or ''
return warehouse_id or None
if item is not None:
warehouse_id = str(item.get("warehouse_id") or "").strip().upper()
@@ -1062,8 +1098,13 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[
return None
def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, Any]:
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str, allow_auto_retry: bool = True) -> dict[str, Any]:
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。
Args:
allow_auto_retry: 只读轮询开关,透传 ensure_all_required_sources_prepared。
poll_inventory_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。
"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
manual_retry_round = mode == "retry_rpa"
@@ -1110,8 +1151,9 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
assert_inventory_source_gate(task, operation="ensure_inventory_via_rpa")
except AppError:
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
task.current_step = "step2_parse_confirm"
task.error_message = "库存源尚未确定,无法启动 RPA"
# OT 在正式 Notice 创建前只保存阶段;不得写 Notice 专属 current_step。
task.stage = "inventory_source_resolving"
_set_workflow_error(task, "库存源尚未确定,无法启动 RPA")
db.session.commit()
return tool_response(
status="needs_human",
@@ -1124,17 +1166,18 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
rpa_source = task_rpa_inventory_source(task) or {}
# 首次自动与人工重试都必须创建逐源 Attempt。只有该路径会冻结
# 首次自动与人工显式重试才可能创建逐源 Attempt;自动路径读到失败事实时
# 必须收口,不能重试。只有该路径会冻结
# source_run_no/lease_token/candidate_set/execution/gate 身份,Worker 回调才可精确收口。
# 下方保留的旧单票逻辑仅用于历史代码阅读,所有受支持 mode 均在这里返回。
if mode in {'auto', 'retry_rpa'}:
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
prepared = ensure_all_required_sources_prepared(task, mode=mode)
prepared = ensure_all_required_sources_prepared(task, mode=mode, allow_auto_retry=allow_auto_retry)
db.session.flush()
if prepared.pending_source_codes:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
_set_workflow_error(task, None)
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
@@ -1158,6 +1201,11 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
if prepared.all_prepared:
return tool_response(status='completed', task=task, message='库存快照已准备完成。')
# [只读轮询失败语义] poll(allow_auto_retry=False)查询到源失败事实时返回
# status='failed'(executor 的 _tool_outcome 映射为 blocked_retryable):
# 失败是可重试的技术结果,不是需要用户决策的人工阻断;重试由用户显式动作发起。
# 显式重试/首次投递路径(allow_auto_retry=True)维持 needs_human 人工兑底。
poll_read_only = not allow_auto_retry
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
@@ -1172,11 +1220,12 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
db.session.commit()
return tool_response(
status='needs_human', task=task,
status='failed' if poll_read_only else 'needs_human', task=task,
message='库存 RPA 未能为全部库存源生成结果。',
data={**serialize_task_for_tool(task), 'rpa': {
'failed_source_codes': prepared.failed_source_codes,
'source_attempts': prepared.source_attempts,
'poll_read_only': poll_read_only,
}},
)
@@ -1188,10 +1237,10 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
timeout_seconds = rpa_inventory_timeout_seconds()
if (
task.pending_human_reason == PH_RPA_PENDING
and not task.inventory_lines_json
):
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
if task_blocking_reason(task) == PH_RPA_PENDING and not has_ready_inventory_file_for_task(task):
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
if last_trigger and isinstance(last_trigger.created_at, datetime):
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
@@ -1215,7 +1264,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
last_failed = latest_task_event(task, "inventory_rpa_failed")
if not last_failed or (last_failed.created_at < last_trigger.created_at):
task.error_message = "RPA 库存导出等待超时"
_set_workflow_error(task, "RPA 库存导出等待超时")
log_task_event(
task,
"inventory_rpa_failed",
@@ -1227,12 +1276,12 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
db.session.flush( )
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel"
_set_workflow_error(task, "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel")
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
message=_workflow_error(task),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
)
@@ -1256,10 +1305,10 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
except ServiceUnavailableError as exc:
trigger = None
detail_message = str((exc.details or {}).get("detail_message") or exc.message or RPA_WORKER_OFFLINE_MESSAGE)
task.error_message = detail_message[:500]
_set_workflow_error(task, detail_message[:500])
if trigger:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
_set_workflow_error(task, None)
progress_message = (
"已重新触发库存获取,等待结果"
if manual_retry_round
@@ -1312,14 +1361,14 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
offline_message = (task.error_message or "").strip()
offline_message = (_workflow_error(task) or "").strip()
if offline_message == RPA_WORKER_OFFLINE_MESSAGE:
human_message = RPA_WORKER_OFFLINE_MESSAGE
detail = "请启动 Windows RPA 服务后重试,或手动上传货代库存 Excel。"
else:
human_message = "RPA 库存目录未配置或触发失败"
detail = "请重新获取库存,或手动上传货代库存 Excel。"
task.error_message = human_message[:500]
_set_workflow_error(task, human_message[:500])
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
@@ -1469,15 +1518,7 @@ def _handle_rpa_inventory_skipped(
detail = str(payload.get("message") or payload.get("error_message") or "").strip()
message = _inventory_rpa_skipped_message(skip_reason=skip_reason, detail=detail)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = None
step_payload = dict(task.step_payload_json or {})
step_payload["inventory_rpa_skipped"] = {
"skip_reason": skip_reason,
"message": detail or message,
"reported_at": datetime.utcnow().isoformat(),
"rpa_runtime": runtime,
}
task.step_payload_json = step_payload
_set_workflow_error(task, None)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
@@ -1519,9 +1560,9 @@ def _handle_rpa_inventory_failed(
) -> dict[str, Any]:
"""处理 failed 回调:记录失败事实并保留用户可重试/上传的恢复入口。"""
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500]
_set_workflow_error(task, str(payload.get("error_message") or "RPA inventory export failed")[:500])
log_task_event(task, "inventory_rpa_failed", {
"error": task.error_message,
"error": _workflow_error(task),
"error_code": str(payload.get("error_code") or "rpa_export_failed"),
"rpa_runtime": runtime,
})
@@ -1530,7 +1571,7 @@ def _handle_rpa_inventory_failed(
step_key='step3_inventory_prepare',
step_title='获取库存',
status='needs_human',
message=task.error_message,
message=_workflow_error(task),
progress_percent=100,
detail='请重新获取库存或上传库存 Excel。',
extra={'error_code': str(payload.get('error_code') or 'rpa_export_failed')},
@@ -1544,11 +1585,51 @@ def _handle_rpa_inventory_failed(
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
message=_workflow_error(task),
data=serialize_task_for_tool(task),
)
def settle_failed_inventory_callback(payload: dict[str, Any], *, error: str) -> None:
"""收口回调处理失败,避免 RPA Attempt 与 Gate 留在外部等待。"""
from app.models import ShippingProcessExecution
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
for item in payload.get('results') or []:
if not isinstance(item, dict):
continue
task_no = str(item.get('task_no') or '').strip()
source_code = str(item.get('source_code') or '').strip().upper()
source_run_no = str(item.get('source_run_no') or '').strip()
task = resolve_task_from_payload({'task_no': task_no}, allow_conversation_fallback=False)
if not isinstance(task, ShippingOrderTask) or not source_code or not source_run_no:
continue
task = _lock_task_for_rpa_callback(task)
per_source_callback_handler(
task,
source_code=source_code,
run_no=source_run_no,
callback_payload={
**dict(item),
'schema_version': str(payload.get('schema_version') or item.get('schema_version') or ''),
'error_code': 'callback_processing_failed',
'error_message': error,
},
)
_handle_rpa_inventory_failed(
task,
{'error_code': 'callback_processing_failed', 'error_message': error},
_save_last_inventory_rpa_runtime(task, payload),
commit=False,
)
if task.active_process_execution_id:
execution = db.session.get(ShippingProcessExecution, int(task.active_process_execution_id))
if execution is not None and str(execution.status or '').lower() != 'superseded':
sync_fulfillment_gates_from_task(execution=execution, actor_type='system')
db.session.commit()
def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
@@ -1756,7 +1837,9 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
trigger_type="on_demand",
success=True,
user_id=task.user_id,
verify_warehouse_id=task_wh if (task_wh := str(task.inventory_warehouse_id or "").strip().upper()) else None,
verify_warehouse_id=(
_expected_snapshot_identity_from_task(task)[1] or None
),
)
if not created_new:
reuse_error = _validate_reused_snapshot_callback_file(inv_file, path)
@@ -2044,6 +2127,43 @@ 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],
*,
@@ -2084,12 +2204,8 @@ def _persist_batch_callback_receipt(
continue
raw_path = str(item.get('file_path') or '').strip()
source_path = Path(raw_path).resolve() if raw_path else None
if source_path is None or not source_path.is_file():
return None
try:
source_path.relative_to(allowed_root)
except ValueError:
source_path = _resolve_shared_inventory_drop_file(raw_path, allowed_root=allowed_root)
if source_path is None:
return None
suffix = source_path.suffix.lower()
@@ -2120,27 +2236,34 @@ def _received_batch_callback_file_path(
callback_id: str,
) -> Path | None:
"""验证 batch 处理可读取的文件仅来自 RPA drop 或本回调受控收件区。"""
candidate = Path(file_path).resolve() if file_path else None
if candidate is None or not candidate.is_file():
return None
allowed_roots: list[Path] = []
drop_dir = inventory_drop_dir()
if drop_dir is not None:
allowed_roots.append(drop_dir.resolve())
from app.services.shipping_notice.export import _storage_root
safe_callback_id = ''.join(
char if char.isalnum() or char in {'-', '_'} else '_'
for char in callback_id
).strip('_') or 'unknown'
allowed_roots.append((_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve())
for allowed_root in allowed_roots:
try:
candidate.relative_to(allowed_root)
return candidate
except ValueError:
continue
return None
receipt_root = (_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve()
drop_dir = inventory_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:
return mapped
text = str(file_path or '').strip()
if not text:
return None
try:
candidate = Path(text).resolve()
except (OSError, RuntimeError):
return None
if not candidate.is_file():
return None
try:
candidate.relative_to(receipt_root)
return candidate
except ValueError:
return None
def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
@@ -2577,7 +2700,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
**(inv_file.schema_preview_json or {}),
'structure_validation': column_meta['structure_validation'],
}
if lines and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} and str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() == 'active':
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if lines and not has_verified_upload_success(task) and str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() == 'active':
inventory_loaded_response(
task,
lines,
@@ -2805,7 +2929,7 @@ def _validate_repair_inventory_snapshot(
return "inventory_source_unstable"
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task.inventory_source_code)
source = get_database_inventory_source(inv_file.source_code)
if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
if not inventory_identities_match(
task,
@@ -3,7 +3,8 @@ services/shipping_notice/per_source_rpa_service.py
用途:逐 (task_no, source_code) 维度的库存 RPA Attempt 结构化管理(决策 D1/D2/D3)。
依赖:models.ShippingTaskInventoryRpaAttempt、inventory_candidate_freeze_service(取候选源)、
rpa.write_inventory_export_trigger_for_task(trigger 文件写入)、
rpa.write_inventory_export_batch_trigger(批次 trigger 文件写入,单文件多源)与
rpa.build_on_demand_inventory_trigger_source(逐源条目构造)、
inventory_snapshot_store(快照复用判断)。
逻辑:T4 新增的结构化表是正式 Attempt 计数真相;旧的 ShippingTaskEvent 统计作为兼容层,
新的调用方(auto_progress Orchestrator、Gate handler、回调入口)逐步迁移到本模块。
@@ -37,7 +38,10 @@ from app.services.shipping_notice.inventory_snapshot_store import (
find_latest_ready_snapshot,
is_snapshot_fresh,
)
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
from app.services.shipping_notice.rpa import (
build_on_demand_inventory_trigger_source,
write_inventory_export_batch_trigger,
)
def _archive_unclaimed_trigger(attempt: ShippingTaskInventoryRpaAttempt) -> str | None:
@@ -233,14 +237,6 @@ def _next_attempt_no(
return base_no + int(subsequent_count) + 1
def _trigger_filename(task_no: str, source_code: str, attempt_no: int) -> str:
"""
新的 per-source trigger 文件名:SN-<task_no>__<SOURCE_CODE>__A<attempt_no>.trigger.json
与 legacy 文件名(无 __SOURCE 后缀)并行不冲突,RPA Worker 按 __ 分割识别 source_code。
"""
return f'SN-{task_no}__{source_code.upper()}__A{attempt_no}.trigger.json'
def _snapshot_ready_for_source(
source_code: str,
*,
@@ -304,6 +300,7 @@ def ensure_all_required_sources_prepared(
*,
mode: str = 'auto',
session: Session | None = None,
allow_auto_retry: bool = True,
) -> PerSourcePrepareResult:
"""
遍历 frozen 候选库存源,逐源 check 快照;未命中则触发 RPA(每源独立 attempt_no/run_no)。
@@ -316,12 +313,15 @@ def ensure_all_required_sources_prepared(
b. 否则检查 (task, source) 当前最新 Attempt 状态:
- queued/running → pending(仍在等待)
- succeeded/consumed → 已 prepared
- failed 且 attempt_no < max_attempts → 触发下一 attempt(queued 新 run)
- failed 且 attempt_no ≥ max_attempts → failed(不自动再触发)
- 从未 attempt → 触发 attempt_no=1
- 从未 attempt → 首次触发新 attempt(queued 新 run)
- failed/exhausted → 仅用户显式 retry_rpa 才触发下一 Attempt
c. 写 ShippingTaskInventoryRpaAttempt 记录 + trigger 文件
Args:
allow_auto_retry: 只读轮询开关。poll_inventory_preparation 等查询路径必须传 False:
轮询只消费 Attempt 事实(快照复用/pending/failed 上报),禁止自动新建 Attempt。
无论此开关取值,失败后的重试都只能由用户显式动作(mode='retry_rpa')发起,
避免 RPA Worker 离线时形成“失败→重试→再失败”的无人值守空转环。
task: 已冻结候选的任务(inventory_source_status ∈ STABLE)。
mode: 'auto' = Orchestrator 自动推进;'retry_rpa' = 用户显式强制重试(跳过复用快照)。
session: 可选 Session。
@@ -331,6 +331,13 @@ def ensure_all_required_sources_prepared(
"""
task_no = str(task.task_no or '').strip()
sess = session or db.session
# OT 级互斥:同一库存准备请求只能产生一个批次 trigger,避免并发点击为同一 OT 写出多个批次。
if getattr(task, 'id', None) is not None:
try:
sess.query(type(task)).filter(type(task).id == int(task.id)).with_for_update().one()
except Exception:
# SQLite/无事务测试环境不支持行锁时继续走现有幂等约束。
pass
source_codes = task_frozen_inventory_source_codes(task)
if not source_codes:
return PerSourcePrepareResult(
@@ -344,6 +351,9 @@ def ensure_all_required_sources_prepared(
prepared: list[str] = []
pending: list[str] = []
failed: list[str] = []
# 本轮待触发源的单源条目与对应 Attempt;循环后合并写入单个批次 trigger。
pending_payloads: list[dict[str, Any]] = []
pending_attempts: list[ShippingTaskInventoryRpaAttempt] = []
for source_code in source_codes:
rpa_source = get_database_inventory_source(source_code) or {'source_code': source_code}
@@ -362,7 +372,7 @@ def ensure_all_required_sources_prepared(
# 题2B 服务层并发双保险:_latest_attempt 可能读到缓存/旧事务;此处在创建前重新 SELECT ... FOR UPDATE
# 再次确认 (task_no, source_code) 的最新状态不为 queued/running,避免“双请求同时通过 _latest_attempt,
# 都判成 failed → 都创建新 Attempt”的竞态。仍以 DB 部分唯一索引作为最后兜底。
if mode == 'retry_rpa' or (current_status == 'failed'):
if mode == 'retry_rpa' or current_status in {'failed', 'exhausted'}:
from app.models.shipping_task_inventory_rpa_attempts import (
ShippingTaskInventoryRpaAttempt as _Attempt2,
)
@@ -388,6 +398,17 @@ def ensure_all_required_sources_prepared(
prepared.append(source_code)
continue
if current_status in {'failed', 'exhausted'} and mode != 'retry_rpa':
# 失败事实只能收口为可重试 Gate;自动推进与轮询不得把它转换为新 RPA Attempt。
failed.append(source_code)
continue
if not allow_auto_retry:
# [只读轮询] failed/从未触发的源只上报 failed 事实,由 Gate 收口为人工阻断;
# 新 Attempt 只能由用户显式重试路径(mode='retry_rpa')创建。
failed.append(source_code)
continue
next_att_no = _next_attempt_no(task_no, source_code, session=sess)
# [STEP 2c] 新建 Attempt + 写 trigger 文件
@@ -407,14 +428,7 @@ def ensure_all_required_sources_prepared(
new_att.source_run_no = _per_source_run_no(new_att)
sess.flush([new_att])
trigger_fname = _trigger_filename(task_no, source_code, next_att_no)
try:
# 复用旧 write_inventory_export_trigger_for_task 内部逻辑,但覆写其生成的文件名
# (旧函数会按 task 级写 trigger;此处先调旧函数保证 payload 完整,再尝试重命名。)
#
# [T4 兼容策略] 先不修改 rpa.py 避免影响单源任务旧链路;RPA Worker 增加按 source_code 识别
# trigger 文件的逻辑,文件名同时带 __SOURCE_CODE__A<N> 后缀即可。
# 这里的 trigger_file_path 仅作为审计字段记录,实际触发由 Worker 按目录扫描识别。
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.models import ShippingProcessExecution, ShippingProcessGate
@@ -441,16 +455,15 @@ def ensure_all_required_sources_prepared(
gate_id=gate_id,
expected_warehouse_id=rpa_source.get('warehouse_id'),
)
# 强制注入 source_code 覆盖旧 task 级单源字段,使 RPA Worker 可按 per-source 执行
# [STEP 2c] 仅构造单源条目不落盘;身份键(source_run_no/lease_token/candidate_set/
# execution/gate)必须冻结在条目内,Worker 回调才能精确收口到本次 Attempt。
per_source_payload = {
'schema_version': 'shipping_inventory_rpa.v2',
'mode': mode,
'attempt': next_att_no,
'attempt_no': next_att_no,
'source_code': source_code,
'source_run_no': new_att.source_run_no,
'callback_id': f'{new_att.source_run_no}:C1',
'batch_run_no': f'BATCH-{task_no}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}',
'lease_token': new_att.lease_token,
# 回调身份必须与本次冻结版本/正式 Execution 绑定;Worker 只原样回传。
'candidate_set_id': getattr(task, 'active_inventory_candidate_set_id', None),
@@ -459,22 +472,15 @@ def ensure_all_required_sources_prepared(
'expected_warehouse_id': rpa_source.get('warehouse_id'),
'per_source_attempt': True,
}
trigger_result = write_inventory_export_trigger_for_task(
task_no,
dict(legacy_rpa_source, **{'source_code': source_code}),
payload=per_source_payload,
pending_payloads.append(
build_on_demand_inventory_trigger_source(
task_no,
dict(legacy_rpa_source, **{'source_code': source_code}),
body=per_source_payload,
)
)
if not trigger_result:
# 没有真实文件就不能宣称 queued;否则 Gate 会显示等待 RPA,Worker 永远不会领取。
new_att.status = 'failed'
new_att.error_code = 'trigger_not_written'
new_att.error_message = '库存 RPA trigger 文件未生成'
new_att.execution_phase = 'trigger_write_failed'
new_att.updated_at = datetime.utcnow()
failed.append(source_code)
else:
new_att.trigger_file_path = str(trigger_result)
pending.append(source_code)
pending.append(source_code)
pending_attempts.append(new_att)
except Exception as exc: # pragma: no cover - RPA 环境异常
new_att.status = 'failed'
new_att.error_code = 'trigger_write_error'
@@ -484,6 +490,41 @@ def ensure_all_required_sources_prepared(
finally:
sess.flush([new_att])
# [STEP 2d] 合并批次触发:本轮 ensure 的全部缺失源写入同一个 trigger 文件,
# Worker 单次登录逐源导出;批次写入失败时本轮全部 Attempt 置 failed——
# 没有真实文件就不能宣称 queued,否则 Gate 会显示等待 RPA,Worker 永远不会领取。
if pending_payloads:
batch_run_no = f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}"
batch_write_error = None
try:
trigger_path = write_inventory_export_batch_trigger(
batch_run_no,
pending_payloads,
payload={
'schema_version': 'shipping_inventory_rpa.v2',
'trigger_type': 'on_demand',
'task_no': task_no,
'mode': mode,
'per_source_attempt': True,
},
)
except Exception as exc: # pragma: no cover - RPA 环境异常
trigger_path = None
batch_write_error = f'{type(exc).__name__}: {str(exc)[:500]}'
if trigger_path:
for att in pending_attempts:
att.trigger_file_path = str(trigger_path)
else:
for att in pending_attempts:
att.status = 'failed'
att.error_code = 'trigger_not_written'
att.error_message = batch_write_error or '库存 RPA trigger 文件未生成'
att.execution_phase = 'trigger_write_failed'
att.updated_at = datetime.utcnow()
failed.extend(pending)
pending.clear()
sess.flush()
summary = _attempts_summary(task_no, source_codes=source_codes, session=sess)
all_ok = len(prepared) == len(source_codes) and not pending and not failed
return PerSourcePrepareResult(
@@ -624,7 +665,8 @@ def per_source_callback_handler(
# [STEP 5] Task 已终态(兼容旧枚举 active/blocked 等非终态)
terminal_statuses = {'completed', 'cancelled', 'failed_terminal'}
if str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in {'voided', 'archived', 'deleted'} or str(getattr(task, 'upload_status', '') or '').strip().lower() in {'uploaded', 'succeeded', 'success'}:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in {'voided', 'archived', 'deleted'} or has_verified_upload_success(task):
attempt.status = 'superseded'
attempt.extra_json = dict(attempt.extra_json or {}, late_callback_ignored=True, reason='task_terminal')
attempt.callback_payload_json = dict(callback_payload or {})
+51 -27
View File
@@ -201,6 +201,56 @@ def inventory_rpa_batch_enabled() -> bool:
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],
@@ -214,36 +264,10 @@ def write_inventory_export_trigger_for_task(
核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed,
不再生成 legacy inventory_export 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', {})
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 = dict(rpa_source)
source_item.update({
"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"),
})
source_item = build_on_demand_inventory_trigger_source(task_no, rpa_source, body=body)
return write_inventory_export_batch_trigger(
run_no,
[source_item],