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],
+93 -10
View File
@@ -932,8 +932,8 @@ def test_real_upload_requires_connection_config_enabled(monkeypatch, tmp_path):
worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={"upload_config_json": {"enabled": False}})
def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
"""DSV 上传须复用登录态打开入口、设置文件,并以 History 绿色回执作为证据返回。"""
def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
"""DSV 上传须点击 Process File,并以结果页三项判定的证据回传。"""
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
@@ -986,10 +986,10 @@ def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
def fake_history(_page, filename):
return {"reference": "FREIGHT-REF-001", "success_evidence": {"kind": "dsv_history_green_dom", "selector": "em.fa.fa-circle.success-color.status-icon", "filename": filename, "reference": "FREIGHT-REF-001", "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<em/>", "dom_sha256": "abc"}}
def fake_result(_page, filename):
return {"reference": "", "success_evidence": {"kind": "dsv_upload_success_dom", "selector": ".alert.alert-success", "filename": filename, "reference": None, "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<div/>", "dom_sha256": "abc"}}
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", fake_history)
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", fake_result)
result = worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={
"connector_type": "dbs",
@@ -1001,11 +1001,12 @@ def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
"result_mode": "page_notice", "result_selector": None, "success_texts": [], "timeout_seconds": 120,
},
})
assert result['reference'] == 'FREIGHT-REF-001'
assert result['success_evidence']['kind'] == 'dsv_history_green_dom'
assert result['reference'] == ''
assert result['success_evidence']['kind'] == 'dsv_upload_success_dom'
assert events[0] == ("session", "https://s360.dbschenker.com/")
assert ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2") in events
assert ("file", str(workbook)) in events
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
@@ -1053,7 +1054,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
runtime_profile.mkdir()
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", lambda _page, filename: f"REF-{filename}")
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda _page, _filename: {"reference": "", "success_evidence": {}})
assert worker._upload_shipment_with_browser(
workbook, connector_type="dbs", upload_source={
@@ -1068,12 +1069,52 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
"success_texts": [], "timeout_seconds": 120,
},
}
) == "REF-shipment.xlsx"
) == {"reference": "", "success_evidence": {}}
assert events[0] == ("session", "https://s360.dbschenker.com/")
assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2")
assert ("file", "#file2") in events
assert ("click", 'button.upload-button:has-text("Process File")') in events
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
def test_dsv_upload_always_confirms_process_file_after_selecting_file(monkeypatch, tmp_path):
"""DSV 选中文件后必须点击 Process File,不能仅凭 set_input_files 视为已上传。"""
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
events: list[tuple[str, object]] = []
class _Locator:
def __init__(self, selector: str):
self.selector = selector
self.first = self
def set_input_files(self, value: str, **_kwargs) -> None:
events.append(("file", value))
def click(self, **_kwargs) -> None:
events.append(("click", self.selector))
class _Page:
def goto(self, _url: str, **_kwargs) -> None:
return None
def locator(self, selector: str) -> _Locator:
return _Locator(selector)
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda *_args: None)
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda *_args: {"reference": "", "success_evidence": {}})
worker.DsvUploadAdapter(
file_path=workbook,
upload_config={
"entry_url": "https://s360.dbschenker.com/upload",
"file_input_selector": "#file2",
"submit_mode": "auto_after_file",
"timeout_seconds": 1,
},
).run(_Page(), login_url="https://s360.dbschenker.com/")
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch):
@@ -1154,6 +1195,48 @@ def test_dsv_upload_history_returns_reference_only_for_confirmed_success(monkeyp
assert evidence["page_url"]
def test_crane_upload_result_requires_processing_and_shipping_order_allocated():
"""Crane 上传成功必须同时满足单号行状态与状态描述。"""
worker = _load_freight_rpa_worker()
assert worker._crane_upload_result_is_success({
"found": True,
"order_status": "Processing",
"order_status_description": "Shipping Order Allocated",
}) is True
assert worker._crane_upload_result_is_success({
"found": True,
"order_status": "Completed",
"order_status_description": "Shipping Order Allocated",
}) is False
assert worker._crane_upload_result_is_success({
"found": True,
"order_status": "Processing",
"order_status_description": "Allocating the Shipping Order",
}) is False
def test_dsv_upload_result_requires_success_button_and_empty_errors():
"""DSV 只有成功按钮且两类错误均为空时才算上传成功。"""
worker = _load_freight_rpa_worker()
assert worker._dsv_upload_result_is_success({
"button": "Upload Successful",
"upload_file_errors": "",
"wms_errors": "",
}) is True
assert worker._dsv_upload_result_is_success({
"button": "Upload Unsuccessful",
"upload_file_errors": "",
"wms_errors": "",
}) is False
assert worker._dsv_upload_result_is_success({
"button": "Upload Successful",
"upload_file_errors": "Missing column",
"wms_errors": "",
}) is False
def test_dsv_upload_falls_back_to_apps_menu(monkeypatch):
"""首页入口缺失时,DSV 仅可退回已确认的 Apps > Upload Tool 路径。"""
worker = _load_freight_rpa_worker()
@@ -16,7 +16,7 @@ from app.models import (
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource,
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink,
ShippingOrderCustomerMatch,
ShippingOrderTask,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import (
@@ -45,7 +45,7 @@ def _tool_headers():
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None:
def _attach_dynamic_order(task: ShippingOrderTask | ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None:
"""为库存/RPA 测试构造已接受 FieldValue,禁止通过固定任务行投影绕过履约门禁。"""
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
if version is None:
@@ -74,12 +74,18 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
str(item['field_code']): str(item['field_id'])
for item in (version.definition_json or {}).get('fields') or []
}
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id)
if owner is None:
owner = ShippingOrderTask(task_no=f'OT-{task.task_no}', user_id=1, status='ready', current_step='customer_review')
db.session.add(owner)
db.session.flush()
task.order_task_id = owner.id
extraction = ShippingOrderExtraction(
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted',
task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='r' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
db.session.add(line)
db.session.flush()
for code, value in {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}.items():
@@ -94,11 +100,11 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
value_json=value,
))
task.current_order_extraction_id = extraction.id
owner.current_order_extraction_id = extraction.id
db.session.flush()
def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
def _confirm_direct_rpa_task_customer(task: ShippingOrderTask | ShippingNotice) -> None:
"""为直接构造的 RPA 回调任务补齐已确认客户。
核心逻辑:测试不经建单工作流时,显式绑定激活客户,
@@ -111,15 +117,31 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None:
)
db.session.add(customer)
db.session.flush()
task.customer = customer
task.customer_name_snapshot = customer.standard_name
task.customer_short_code_snapshot = customer.short_code
task.customer_resolution_status = 'confirmed'
task.customer_resolution_method = 'test_fixture'
db.session.add(task)
db.session.flush()
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id)
if owner is None:
owner = ShippingOrderTask(task_no=f'OT-{task.task_no}', user_id=1, status='ready', current_step='customer_review')
db.session.add(owner)
db.session.flush()
task.order_task_id = owner.id
from tests.conftest import confirm_test_customer_resolution
extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id)
if extraction is None:
rows = getattr(task, 'lines_json', None)
if not isinstance(rows, list) or len(rows) != 1 or not isinstance(rows[0], dict):
raise ValueError('RPA test task must have an accepted extraction before customer confirmation')
row = rows[0]
_attach_dynamic_order(
task,
part_number=str(row.get('part_number') or ''),
reservation_id=str(row.get('reservation_id') or ''),
quantity=int(row.get('qty') or 0),
)
extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id)
confirm_test_customer_resolution(owner, customer=customer, extraction=extraction)
# 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。
task._test_customer_confirmed = True
owner._test_customer_confirmed = True
if not isinstance(task, ShippingOrderTask):
task._test_customer_confirmed = True
@pytest.fixture(autouse=True)
@@ -169,7 +191,7 @@ def test_auto_inventory_missing_snapshot_triggers_rpa(monkeypatch):
trigger = {'status': 'running', 'task_id': task.task_no, 'rpa': {'attempts': 1}}
monkeypatch.setattr(
'app.services.shipping_notice.inventory_rpa_workflow.ensure_inventory_via_rpa',
lambda _task, *, mode: trigger,
lambda _task, *, mode, allow_auto_retry=True: trigger,
)
result = inventory_workflow.ensure_inventory({
@@ -203,7 +225,7 @@ def test_auto_inventory_uses_per_source_attempt_identity_contract(app, monkeypat
monkeypatch.setattr(workflow, 'task_rpa_inventory_source', lambda _task: {'source_code': 'DSV360_AWSDU'})
monkeypatch.setattr(
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
lambda actual_task, *, mode: calls.append((actual_task, mode)) or prepared,
lambda actual_task, *, mode, allow_auto_retry=True: calls.append((actual_task, mode)) or prepared,
)
monkeypatch.setattr(workflow, 'apply_task_transition', lambda *_args, **_kwargs: None)
monkeypatch.setattr(workflow, 'set_task_step_progress', lambda *_args, **_kwargs: None)
@@ -288,14 +310,8 @@ def test_inventory_loaded_response_clears_stale_match_state(monkeypatch):
"""库存重新载入/复用后必须清空任务级旧匹配结果,避免旧缺货/旧 match_status 残留。"""
from app.services.shipping_notice import inventory_mapping_workflow as workflow
task = SimpleNamespace(
id=1, task_no="SN-INV-CLEAR", inventory_lines_json=None,
match_status="unfulfillable", line_results_json=[{"a": 1}], shortage_json={"lines": []},
)
linked_task = SimpleNamespace(
id=2, task_no="SN-INV-CLEAR-LINKED", inventory_lines_json=None,
match_status="unfulfillable", line_results_json=None, shortage_json=None,
)
task = SimpleNamespace(id=1, task_no="SN-INV-CLEAR")
linked_task = SimpleNamespace(id=2, task_no="SN-INV-CLEAR-LINKED")
inventory_file = SimpleNamespace(inventory_file_no="INV-CLEAR")
monkeypatch.setattr(workflow, "active_inventory_file_for_task", lambda _task: inventory_file)
@@ -317,7 +333,7 @@ def test_inventory_loaded_response_clears_stale_match_state(monkeypatch):
lambda notice: None,
)
workflow.inventory_loaded_response(
response = workflow.inventory_loaded_response(
task,
[{"part_number": "A001", "qty": 1}],
source="rpa",
@@ -325,13 +341,11 @@ def test_inventory_loaded_response_clears_stale_match_state(monkeypatch):
commit=False,
)
# 库存内容变更后,task 与其同库存文件的关联任务都不能再读旧匹配结果。
assert task.match_status is None
assert task.line_results_json is None
assert task.shortage_json is None
assert linked_task.match_status is None
assert linked_task.line_results_json is None
assert linked_task.shortage_json is None
# 新模型不再向 OT 写入库存匹配旧投影;库存事实由 File/Link/Match/Gate 承载。
assert response['status'] == 'ok'
assert not hasattr(task, 'match_status')
assert not hasattr(task, 'shortage_json')
assert not hasattr(linked_task, 'line_results_json')
def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantity_selection(app, tmp_path):
@@ -363,9 +377,8 @@ def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantit
'report_group': 'Inventory', 'report_name': 'On Hand',
},
)
task = ShippingNotice(
task_no='SN-SNAPSHOT-SOURCE-UNIQUE', source_type='manual',
lines_json=[{'part_number': 'A001', 'reservation_id': '1000123456', 'qty': 1}],
task = ShippingOrderTask(
task_no='OT-SNAPSHOT-SOURCE-UNIQUE', user_id=1, source_type='direct_pdf', status='ready',
)
source_snapshot = ShippingInventoryFile(
inventory_file_no='SIF-SOURCE-UNIQUE', storage_path=str(source_file), snapshot_status='ready',
@@ -422,28 +435,32 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'storage')
with app.app_context():
task = ShippingNotice(
task_no='SN-MANUAL-PROFILE-001', source_type='manual',
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
task = ShippingOrderTask(
task_no='OT-MANUAL-PROFILE-001', user_id=1, source_type='direct_pdf', status='ready',
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
db.session.add(task)
db.session.commit()
assert task.order_snapshot_id is not None
upload = FileStorage(
stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', reservation_id='00001', qty=8).getvalue()),
filename='manual-stock.xlsx',
)
result = upload_inventory_file(task.task_no, upload)
result = upload_inventory_file(
task.task_no,
upload,
)
db.session.refresh(task)
assert result['status'] == 'ok'
assert result['checkpoint'] == 'ready_to_match'
assert task.inventory_snapshot_id is not None
assert task.review_status is None
assert task.pending_human_reason is None
snapshot = db.session.get(ShippingInventoryFile, task.inventory_snapshot_id)
assert result['status'] == 'ok', result
assert result['data']['stage'] == 'step5_match_inventory'
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one()
snapshot = db.session.get(ShippingInventoryFile, link.inventory_file_id)
assert snapshot is not None
assert snapshot.mapping_source == 'parsing_profile'
assert snapshot.mapping_confirmed is True
@@ -473,10 +490,12 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
stream.seek(0)
with app.app_context():
task = ShippingNotice(
task_no='SN-MANUAL-DRIFT-001', source_type='manual',
lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}],
task = ShippingOrderTask(
task_no='OT-MANUAL-DRIFT-001', user_id=1, source_type='direct_pdf', status='ready',
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code='DSV360_AWSDU')
db.session.add(task)
@@ -490,8 +509,6 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path):
assert result['status'] == 'failed'
assert '结构' in result['message'] or '解析' in result['message']
assert task.inventory_snapshot_id is None
assert task.inventory_lines_json in (None, [])
assert ShippingInventoryFile.query.count() == 0
assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 0
assert not list((tmp_path / 'storage' / 'inventory_uploads').glob('**/inventory.*'))
@@ -680,12 +697,12 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
task = ShippingNotice(
task_no="SN-BATCH-RUNNO",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-BATCH-RUNNO", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
@@ -702,15 +719,15 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
"status": "success",
"success": True,
"file_path": str(sample),
"source_code": task.inventory_source_code,
"warehouse_id": task.inventory_warehouse_id,
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
}],
}))
db.session.refresh(task)
assert receipt["status"] == "ok"
assert receipt["result_status"] == "accepted"
assert task.inventory_snapshot_id is None
assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 0
job = db.session.get(Job, int(receipt["data"]["job_id"]))
assert job is not None
assert job.status == "queued"
@@ -729,8 +746,8 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
"status": "success",
"success": True,
"file_path": str(sample),
"source_code": task.inventory_source_code,
"warehouse_id": task.inventory_warehouse_id,
"source_code": "DSV360_AWSDU",
"warehouse_id": "AWSDU",
}],
}))
assert replay["result_status"] == "accepted"
@@ -739,7 +756,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
result = _process_batch_callback(job.payload_json)
db.session.refresh(task)
assert result["result_status"] == "success"
assert task.inventory_snapshot_id is not None
assert ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).count() == 1
def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
@@ -760,12 +777,12 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
with app.app_context():
task = ShippingNotice(
task_no="SN-BATCH-FAIL-TASK",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-BATCH-FAIL-TASK", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
@@ -801,7 +818,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
status="running",
lease_token="batch-fail-lease",
extra_json={
"candidate_set_id": 0,
"candidate_set_id": task.active_inventory_candidate_set_id,
"execution_id": execution.id,
"gate_id": gate.id,
},
@@ -826,7 +843,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
"callback_id": "callback-batch-fail-dsv-a1",
"attempt_no": 1,
"lease_token": "batch-fail-lease",
"candidate_set_id": 0,
"candidate_set_id": task.active_inventory_candidate_set_id,
"execution_id": execution.id,
"gate_id": gate.id,
"status": "failed",
@@ -838,13 +855,11 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
assert result["status"] == "ok"
assert result["failed_count"] == 1
assert task.pending_human_reason == "inv_unavail"
assert task.error_message
db.session.refresh(rpa_attempt)
db.session.refresh(preparation)
db.session.refresh(execution)
db.session.refresh(gate)
assert rpa_attempt.status == "failed"
assert rpa_attempt.status == "consumed"
assert preparation.status == "failed"
assert gate.status == "blocked_retryable"
assert gate.blocking_reason_code == "inventory_rpa_timeout"
@@ -904,15 +919,14 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot
warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None,
report_path_json={}, query_parameters_json=[], enabled=True,
)
task = ShippingNotice(
task_no="SN-CRANE-EMPTY-WAREHOUSE",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-CRANE-EMPTY-WAREHOUSE", user_id=1, source_type="direct_pdf", status="ready",
)
task._test_order_rows = [{"part_number": "A001", "reservation_id": "00001", "qty": 1}]
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
db.session.add_all([crane_profile, crane_source, task])
db.session.add_all([crane_profile, crane_source])
db.session.flush()
seed_task_inventory_source(task, source_code="CRANE")
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
@@ -946,8 +960,8 @@ def test_batch_callback_crane_empty_warehouse_ingests_and_links_dynamic_snapshot
assert result["success_count"] == 1, result
assert result["failed_count"] == 0
assert task.inventory_snapshot_id is not None
assert task.inventory_warehouse_id == "CRANE-WH"
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one()
assert link.matched_warehouse_id == "CRANE-WH"
def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolvable(app, tmp_path):
@@ -982,15 +996,14 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
warehouse_resolution_mode="inventory_match", fixed_warehouse_id=None,
report_path_json={}, query_parameters_json=[], enabled=True,
)
task = ShippingNotice(
task_no="SN-CRANE-UNRESOLVED-LINK",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-CRANE-UNRESOLVED-LINK", user_id=1, source_type="direct_pdf", status="ready",
)
task._test_order_rows = [{"part_number": "A001", "reservation_id": "00001", "qty": 1}]
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
db.session.add_all([crane_profile, crane_source, task])
db.session.add_all([crane_profile, crane_source])
db.session.flush()
seed_task_inventory_source(task, source_code="CRANE")
order_snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id)
@@ -1031,7 +1044,6 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
assert result["success_count"] == 1, result
assert result["failed_count"] == 0
assert task.inventory_snapshot_id is not None
snapshot = ShippingInventoryFile.query.filter_by(
rpa_run_no="RUN-CRANE-UNRESOLVED-LINK", source_code="CRANE",
).one()
@@ -1043,7 +1055,6 @@ def test_batch_callback_keeps_dynamic_snapshot_when_task_link_is_not_yet_resolva
task_id=task.id, inventory_file_id=snapshot.id, is_active=True,
).one()
assert link.identity_check_status == "pending_matching"
assert task.pending_human_reason is None
sync_fulfillment_gates_from_task(execution=execution)
db.session.refresh(execution)
@@ -1095,20 +1106,88 @@ def test_inventory_callback_job_marks_business_failure_as_failed(app, monkeypatc
assert job.result_json["callback_result"]["data"]["result_status"] == "failed"
def test_inventory_callback_job_marks_top_level_failure_as_failed(app, monkeypatch):
"""事务级失败没有 result_status 时,回调 Job 也必须失败。"""
from app import db
from app.jobs.context import JobContext
from app.jobs.handlers import shipping_inventory_callback_process as handler
from app.models import Job
with app.app_context():
job = Job(
domain="shipping_notice",
job_type="shipping_inventory_callback_process",
status="running",
attempts=1,
max_attempts=3,
payload_json={"callback_id": "callback-transaction-failed"},
)
db.session.add(job)
db.session.commit()
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow.process_rpa_report_inventory_batch",
lambda _payload: {
"status": "failed",
"message": "batch callback transaction failed",
"data": {"run_no": "RUN-TRANSACTION-FAILED"},
},
)
settled = []
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow.settle_failed_inventory_callback",
lambda payload, *, error: settled.append((payload, error)),
)
handler.run_shipping_inventory_callback_process(
JobContext(config={}, logger=None, extras={}), {"job_id": job.id},
)
db.session.refresh(job)
assert job.status == "failed"
assert job.error_message == "batch callback transaction failed"
assert settled == [(job.payload_json, "batch callback transaction failed")]
def test_rpa_callback_locks_order_task_model(app):
"""订单生命周期的库存回调必须锁定 ShippingOrderTask,不得查询旧 Notice。"""
from app import db
from app.models import ShippingOrderTask, User
from app.services.shipping_notice.inventory_rpa_workflow import _lock_task_for_rpa_callback
with app.app_context():
user = User(username="callback-lock-user", email="callback-lock@example.com")
db.session.add(user)
db.session.flush()
task = ShippingOrderTask(
task_no="OT-CALLBACK-LOCK",
user_id=int(user.id),
status="processing",
)
db.session.add(task)
db.session.commit()
locked = _lock_task_for_rpa_callback(task)
assert isinstance(locked, ShippingOrderTask)
assert locked.id == task.id
def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
"""单任务 failed 回调缺少 site/warehouse 时仍应进入失败处理,但须匹配当前 run_no。"""
from app import db
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory
with app.app_context():
task = ShippingNotice(
task_no="SN-FAIL-NO-IDENT",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-FAIL-NO-IDENT", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
freeze_test_task_order_snapshot(task)
assert task.order_snapshot_id is not None
seed_rpa_inventory_trigger(task, run_no="RUN-FAIL-NO-IDENT")
db.session.add(task)
db.session.commit()
@@ -1123,8 +1202,6 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "upload_req"
assert task.pending_human_reason == "inv_unavail"
failed_events = ShippingTaskEvent.query.filter_by(
task_id=task.id,
event_type="inventory_rpa_failed",
@@ -1319,12 +1396,13 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
task = ShippingNotice(
task_no="SN-BATCH-NO-IDENT",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-BATCH-NO-IDENT", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT")
db.session.add(task)
@@ -1344,7 +1422,6 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
assert result["status"] == "ok"
assert result["failed_count"] == 1
assert task.pending_human_reason == "rpa_pending"
def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkeypatch):
@@ -1386,12 +1463,13 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
assert storage_path.is_file()
snap_id = snap.id
task = ShippingNotice(
task_no="SN-REUSE-INGEST-FAIL",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-REUSE-INGEST-FAIL", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no=run_no)
db.session.add(task)
@@ -1415,7 +1493,6 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
assert snap_after.snapshot_status == "ready"
assert Path(snap_after.storage_path).is_file()
assert ShippingInventoryFile.query.filter_by(rpa_run_no=run_no, snapshot_status="ready").count() == 1
assert task.pending_human_reason == "rpa_pending"
def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
@@ -1501,27 +1578,23 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
)
with app.app_context():
task_a = ShippingNotice(
task_no="SN-BATCH-OK",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task_a = ShippingOrderTask(
task_no="OT-BATCH-OK", user_id=1, source_type="direct_pdf", status="ready",
)
task_b = ShippingNotice(
task_no="SN-BATCH-FAIL",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
task_b = ShippingOrderTask(
task_no="OT-BATCH-FAIL", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add_all([task_a, task_b])
db.session.flush()
_attach_dynamic_order(task_a, part_number='A001', reservation_id='00001', quantity=1)
_attach_dynamic_order(task_b, part_number='B001', reservation_id='00002', quantity=1)
_confirm_direct_rpa_task_customer(task_a)
_confirm_direct_rpa_task_customer(task_b)
seed_task_inventory_source(task_a, source_code="DSV360_AWSDU")
seed_task_inventory_source(task_b, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task_a, run_no=run_no)
seed_rpa_inventory_trigger(task_b, run_no=run_no)
db.session.add_all([task_a, task_b])
db.session.commit()
before_b_status = task_b.pending_human_reason
result = _process_batch_callback({
"run_no": run_no,
@@ -1546,9 +1619,8 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
assert result["success_count"] == 1
assert result["failed_count"] == 1
assert task_a.inventory_rpa_consumed_run_no == run_no
assert task_b.inventory_rpa_consumed_run_no is None
assert task_b.pending_human_reason == before_b_status
assert ShippingTaskInventoryLink.query.filter_by(task_id=task_a.id, is_active=True).count() == 1
assert ShippingTaskInventoryLink.query.filter_by(task_id=task_b.id, is_active=True).count() == 0
def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path, monkeypatch):
@@ -1582,12 +1654,13 @@ def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path,
)
with app.app_context():
task = ShippingNotice(
task_no="SN-BATCH-DEFER-CONFIRM",
source_type="manual",
task = ShippingOrderTask(
task_no="OT-BATCH-DEFER-CONFIRM", user_id=1, source_type="direct_pdf", status="ready",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-DEFER-CONFIRM")
@@ -1624,25 +1697,22 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
run_no = "RUN-SHARED-LINK"
with app.app_context():
task_ok = ShippingNotice(
task_no="SN-SHARED-OK",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task_ok = ShippingOrderTask(
task_no="OT-SHARED-OK", user_id=1, source_type="direct_pdf", status="ready",
)
task_fail = ShippingNotice(
task_no="SN-SHARED-FAIL",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}],
task_fail = ShippingOrderTask(
task_no="OT-SHARED-FAIL", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add_all([task_ok, task_fail])
db.session.flush()
_attach_dynamic_order(task_ok, part_number='A001', reservation_id='00001', quantity=1)
_attach_dynamic_order(task_fail, part_number='B001', reservation_id='00002', quantity=1)
_confirm_direct_rpa_task_customer(task_ok)
_confirm_direct_rpa_task_customer(task_fail)
seed_task_inventory_source(task_ok, source_code="DSV360_AWSDU")
seed_task_inventory_source(task_fail, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task_ok, run_no=run_no)
seed_rpa_inventory_trigger(task_fail, run_no=run_no)
db.session.add_all([task_ok, task_fail])
db.session.commit()
ok_result = _process_batch_callback({
@@ -1711,12 +1781,12 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
)
with app.app_context():
task = ShippingNotice(
task_no="SN-POST-COMMIT-FAIL",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-POST-COMMIT-FAIL", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-POST-COMMIT")
@@ -1729,7 +1799,6 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
assert snap is not None
assert Path(snap.storage_path).is_file()
assert result.get("data", {}).get("post_commit_warnings")
assert task.inventory_rpa_consumed_run_no == "RUN-POST-COMMIT"
def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkeypatch):
@@ -1755,12 +1824,12 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
)
with app.app_context():
task = ShippingNotice(
task_no="SN-PROMOTE-FAIL-REBUILD",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-PROMOTE-FAIL-REBUILD", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-PROMOTE-FAIL")
@@ -1774,7 +1843,6 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
warnings = result.get("data", {}).get("post_commit_warnings") or []
assert any("promote_recovered_via_snapshot_rebuild" in item for item in warnings)
assert attachment is not None and attachment.is_file()
assert task.inventory_rpa_consumed_run_no == "RUN-PROMOTE-FAIL"
def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
@@ -1792,11 +1860,13 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
snap_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
task = ShippingNotice(
task_no="SN-REPAIR-ATTACH",
source_type="manual",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-REPAIR-ATTACH", user_id=1, source_type="direct_pdf", status="ready",
)
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
db.session.flush()
@@ -1949,14 +2019,14 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
other_file.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
task = ShippingNotice(
task_no="SN-REPAIR-REJECT",
source_type="manual",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
task = ShippingOrderTask(
task_no="OT-REPAIR-REJECT", user_id=1, source_type="direct_pdf", status="ready",
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
db.session.flush()
_attach_dynamic_order(task, part_number='A001', reservation_id='00001', quantity=1)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
active_snap = ShippingInventoryFile(
inventory_file_no="SIF-ACTIVE-SNAP",
storage_path=str(active_file),
@@ -2028,3 +2098,176 @@ def test_recover_pending_callback_cleanup_jobs_without_new_callback(app, tmp_pat
assert list(processed_dir.glob("stuck.xlsx"))
assert not stuck.is_file()
assert warnings == []
def test_ensure_all_required_sources_writes_single_batch_trigger(monkeypatch, app):
"""[断言] 多候选源缺失快照时:一轮 ensure 只写 1 个批次 trigger(单文件多源),
逐源身份键(task_no/source_run_no/lease_token/callback_id)进入条目,
且全部 Attempt 共享该 trigger_file_path;批次载荷为 on_demand。"""
from app import db
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
from app.services.shipping_notice import per_source_rpa_service
task = ShippingNotice(task_no='SN-PREP-BATCH-SINGLE')
db.session.add(task)
db.session.flush()
captured = {}
def _fake_batch_writer(run_no, sources, payload=None):
captured['run_no'] = run_no
captured['sources'] = [dict(item) for item in sources]
captured['payload'] = dict(payload or {})
return 'trigger/batch.json'
monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A', 'SRC_B'])
monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False)
monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
lambda task: {'source_code': 'SRC_A'},
)
monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_batch_trigger', _fake_batch_writer)
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='auto')
assert result.pending_source_codes == ['SRC_A', 'SRC_B']
assert result.failed_source_codes == []
assert captured['run_no'].startswith('BATCH-SN-PREP-BATCH-SINGLE-')
assert [item['source_code'] for item in captured['sources']] == ['SRC_A', 'SRC_B']
for item in captured['sources']:
assert item['task_no'] == task.task_no
assert item['source_run_no']
assert item['lease_token']
assert item['callback_id'].endswith(':C1')
assert captured['payload']['trigger_type'] == 'on_demand'
attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=task.task_no).all()
assert len(attempts) == 2
assert all(att.trigger_file_path == 'trigger/batch.json' for att in attempts)
assert all(att.status == 'queued' for att in attempts)
def test_stp_multi_candidate_missing_files_auto_triggers_probe(monkeypatch, app):
"""[断言] 多候选缺文件:auto 模式自动触发批次探测并返回 running(D3),
而非旧的 needs_human + inv_unavail;无候选集的 blocked 场景维持 needs_human。"""
from types import SimpleNamespace
from app.services.shipping_notice import inventory_workflow
from app.services.shipping_notice.state_machine import TaskTransition
task = SimpleNamespace(
task_no='SN-STP-AUTO-PROBE',
inventory_lines_json=None,
inventory_source_status='candidates_frozen',
active_inventory_candidate_set_id=5,
error_message='stale',
)
transitions = []
probe_calls = []
def _fake_transition(actual_task, transition):
transitions.append(transition)
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'apply_task_transition', _fake_transition)
monkeypatch.setattr(inventory_workflow, 'set_task_step_progress', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'log_task_event', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {})
monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs)
monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['SRC_A', 'SRC_B'],
)
monkeypatch.setattr(
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
lambda _task: {
'status': 'missing_files',
'lines': [],
'missing_source_codes': ['SRC_A', 'SRC_B'],
'loaded_source_codes': [],
'evidence': [],
'required_source_codes': ['SRC_A', 'SRC_B'],
},
)
def _fake_probe(actual_task, *, mode, allow_auto_retry=True):
probe_calls.append((actual_task, mode))
return SimpleNamespace(
pending_source_codes=['SRC_A', 'SRC_B'],
prepared_source_codes=[],
failed_source_codes=[],
source_attempts={},
all_prepared=False,
)
monkeypatch.setattr(
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
_fake_probe,
)
result = inventory_workflow.ensure_inventory({
'task_id': task.task_no,
'mode': 'auto',
'_orchestrator_internal_dispatch': True,
})
assert probe_calls == [(task, 'auto')]
assert result['status'] == 'running'
assert result['data']['rpa']['pending_source_codes'] == ['SRC_A', 'SRC_B']
assert transitions == [TaskTransition.RPA_PENDING]
assert task.error_message is None
def test_stp_multi_candidate_probe_exhausted_falls_back_to_needs_human(monkeypatch, app):
"""[断言] 探测无 pending(全部触发失败)→ needs_human,不得伪装 running。"""
from types import SimpleNamespace
from app.services.shipping_notice import inventory_workflow
task = SimpleNamespace(
task_no='SN-STP-PROBE-FAILED',
inventory_lines_json=None,
inventory_source_status='candidates_frozen',
active_inventory_candidate_set_id=5,
)
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'set_task_step_progress', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'log_task_event', lambda *_a, **_k: None)
monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {})
monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs)
monkeypatch.setattr(inventory_workflow.db.session, 'commit', lambda: None)
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['SRC_A'],
)
monkeypatch.setattr(
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
lambda _task: {
'status': 'missing_files',
'lines': [],
'missing_source_codes': ['SRC_A'],
'loaded_source_codes': [],
'evidence': [],
'required_source_codes': ['SRC_A'],
},
)
monkeypatch.setattr(
'app.services.shipping_notice.per_source_rpa_service.ensure_all_required_sources_prepared',
lambda actual_task, *, mode, allow_auto_retry=True: SimpleNamespace(
pending_source_codes=[],
prepared_source_codes=[],
failed_source_codes=['SRC_A'],
source_attempts={},
all_prepared=False,
),
)
result = inventory_workflow.ensure_inventory({
'task_id': task.task_no,
'mode': 'auto',
'_orchestrator_internal_dispatch': True,
})
assert result['status'] == 'needs_human'
assert result['data']['blocking_reason']['code'] == 'inventory_preparation_failed'
+40
View File
@@ -1393,6 +1393,46 @@ cd C:\HxopsRpaTest
.\scripts\rpa\inventory\register_inventory_worker_tasks.ps1 -Scope test -Unregister # 只注销 test
```
#### PowerShell 执行策略阻止脚本时
如果直接执行 `.ps1` 时出现“在此系统上禁止运行脚本”(`PSSecurityException` / `UnauthorizedAccess`),优先使用一次性的 `ExecutionPolicy Bypass`,不要修改计算机或用户的全局执行策略:
```powershell
cd C:\HxopsRpaTest
# 注册 TEST 计划任务
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
"C:\HxopsRpaTest\scripts\rpa\inventory\register_inventory_worker_tasks.ps1" `
-Scope test `
-TestApiBase "http://192.168.100.192:8890" `
-TestRoot "C:\HxopsRpaTest" `
-SecretFile "C:\HxopsRpaSecrets"
# 启动或查看 TEST 任务
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
"C:\HxopsRpaTest\scripts\rpa\inventory\register_inventory_worker_tasks.ps1" `
-Scope test -Start
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
"C:\HxopsRpaTest\scripts\rpa\inventory\register_inventory_worker_tasks.ps1" `
-Scope test -Status
```
如果脚本是从浏览器、邮件或压缩包复制而来,可能带有 Internet 下载标记;确认路径无误后可解除该文件的阻止状态,再按普通方式执行:
```powershell
Unblock-File -LiteralPath `
"C:\HxopsRpaTest\scripts\rpa\inventory\register_inventory_worker_tasks.ps1"
```
可用以下命令查看当前执行策略:
```powershell
Get-ExecutionPolicy -List
```
不建议直接设置 `Unrestricted`。如果 `MachinePolicy` 或 `UserPolicy` 已由公司组策略设置,`Bypass` 仍可能被拦截,此时需要管理员调整组策略或按公司运维流程批准执行该脚本。
- **`-Scope test|prod|all`**:`Start/Stop/Status/Unregister`(以及默认注册)都可只作用于单个环境;不带 `-Scope` 时默认操作 test 和 prod 两个任务。两个任务是独立命名的(`HXOPS Inventory RPA Worker TEST` / `...PROD`),也可用原生 `Get-ScheduledTask -TaskName <任务名>` 单独查询。
- 与 2.3 可见模式仅两处差异:计划任务给 `powershell.exe` 加 `-WindowStyle Hidden`(无控制台),并给 `start_rpa_worker.ps1` 加 `-Headless`(Playwright headless,无可见 Edge)。其余 `AtLogOn`、`Interactive`、`RestartCount/RestartInterval`、`ExecutionTimeLimit=0`、`MultipleInstances=IgnoreNew` 均与 2.3 一致。
+123 -8
View File
@@ -1634,7 +1634,7 @@ def _capture_success_page_evidence(
def _wait_for_dsv_upload_history_receipt(page: Any, filename: str) -> dict[str, Any]:
"""
仅以 DSV History 同名行的绿色 success DOM 确认上传受理;Reference 可选。
兼容旧调用方的 History 证据读取。上传主流程不再调用此函数判定成功。
核心逻辑:succeeded=true 即成功;reference 可为空字符串。
@@ -1699,6 +1699,72 @@ def _wait_for_dsv_upload_history_receipt(page: Any, filename: str) -> dict[str,
)
def _dsv_upload_result_is_success(state: dict[str, Any]) -> bool:
"""判断 DSV 上传页结果:成功按钮且 Upload File/WMS 错误均为空。"""
return (
str(state.get('button') or '').strip().lower() == 'upload successful'
and not str(state.get('upload_file_errors') or '').strip()
and not str(state.get('wms_errors') or '').strip()
)
def _crane_upload_result_is_success(state: dict[str, Any]) -> bool:
"""判断 Crane 发货通知行是否进入 Processing/Shipping Order Allocated。"""
return (
bool(state.get('found'))
and str(state.get('order_status') or '').strip().lower() == 'processing'
and str(state.get('order_status_description') or '').strip().lower() == 'shipping order allocated'
)
def _wait_for_dsv_upload_result(page: Any, filename: str) -> dict[str, Any]:
"""轮询 DSV 上传结果页,不再使用 History 绿图标作为成功依据。
成功条件:`.alert.alert-success`(文本为 Upload Successful!)可见,且
Upload File Errors 与 WMS Errors 各自结果单元格为空或显示 No Errors;
`.alert.alert-danger`(文本为 Upload Unsuccessful)始终判定失败。
"""
script = """
() => {
const clean = (v) => String(v || '').replace(/\\s+/g, ' ').trim();
const success = document.querySelector('.alert.alert-success, [role="alert"].alert-success');
const unsuccessful = document.querySelector('.alert.alert-danger, [role="alert"].alert-danger');
const button = clean((success || unsuccessful)?.textContent).match(/Upload (?:Un)?Successful!?/i)?.[0] || '';
const valueByHeader = (label) => {
const heading = Array.from(document.querySelectorAll('th')).find((n) => clean(n.textContent).toLowerCase() === label.toLowerCase());
if (!heading) return '';
const value = heading.closest('table')?.querySelector('tbody tr td') || heading.parentElement?.nextElementSibling?.querySelector('td');
return clean(value?.textContent);
};
const normalizeError = (value) => /^(no errors?|none|n\\/a)$/i.test(clean(value)) ? '' : clean(value);
return { button, upload_file_errors: normalizeError(valueByHeader('Upload File Errors')), wms_errors: normalizeError(valueByHeader('WMS Errors')) };
}
"""
deadline = time.monotonic() + (_browser_timeout_ms() / 1000)
last_state: dict[str, Any] = {}
while time.monotonic() < deadline:
try:
state = page.evaluate(script) or {}
if isinstance(state, dict):
last_state = state
if str(state.get('button') or '').strip().lower() == 'upload unsuccessful':
raise RuntimeError(f"DSV upload unsuccessful for {filename!r}: {state}")
if _dsv_upload_result_is_success(state):
return {
'reference': '',
'success_evidence': _capture_success_page_evidence(
page, kind='dsv_upload_success_dom', selector='div[role="alert"]',
filename=filename, reference=None,
),
}
except RuntimeError:
raise
except Exception:
pass
time.sleep(1)
raise RuntimeError(f"DSV upload result was not confirmed for {filename!r}; last_state={last_state}")
class _UploadResultUnknownError(RuntimeError):
"""上传动作已发生但结果无法确认(未能取得可核验成功证据);必须转人工,禁止自动重试。"""
@@ -1732,21 +1798,20 @@ class _BaseUploadAdapter:
class DsvUploadAdapter(_BaseUploadAdapter):
"""DSV 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → History 绿色判定。"""
"""DSV 受控上传流程:登录、提交后按上传结果页提示与错误区域判定。"""
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
"""选择 DSV 文件后强制点击 Process File,再读取结果页三项成功条件。"""
self._require('entry_url', 'file_input_selector')
_ensure_dsv_session(page, login_url)
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
file_selector = str(self.config.get('file_input_selector') or '#file2').strip()
page.locator(file_selector).first.set_input_files(str(self.file_path), timeout=self._timeout_ms())
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
submit_selector = str(self.config.get('submit_selector') or '').strip()
if not submit_selector:
raise RuntimeError('DSV click_submit upload requires submit_selector')
page.locator(submit_selector).first.click(timeout=self._timeout_ms())
# DSV 页面选择文件后只完成预览;必须点击真实二次确认按钮才会提交上传。
submit_selector = 'button.btn.btn-primary.upload-button:has-text("Process File")'
page.locator(submit_selector).first.click(timeout=self._timeout_ms())
try:
return _wait_for_dsv_upload_history_receipt(page, self.file_path.name)
return _wait_for_dsv_upload_result(page, self.file_path.name)
except RuntimeError as exc:
# 文件已选择/可能已提交但未取得可核验成功证据 → unknown,转人工。
raise _UploadResultUnknownError(str(exc)) from exc
@@ -1892,6 +1957,11 @@ class CraneUploadAdapter(_BaseUploadAdapter):
def _resolve_result(self, page: Any) -> dict[str, Any]:
result_mode = str(self.config.get('result_mode') or '').strip()
filename = self.file_path.name
# [STEP 1] Crane 页面成功反馈后仍需核对发货通知列表中的业务状态,
# 只有 Processing + Shipping Order Allocated 才视为真正上传成功。
status_result = self._wait_for_order_status(page, filename)
if status_result:
return status_result
# 提交后先探测一次失败/成功弹窗;判定期内仍会持续探测(结果选择器可能晚于弹窗出现)。
self._raise_if_crane_error(page)
success = self._success_from_popup(page, filename)
@@ -1959,6 +2029,51 @@ class CraneUploadAdapter(_BaseUploadAdapter):
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
)
def _wait_for_order_status(self, page: Any, filename: str) -> dict[str, Any] | None:
"""轮询 Crane 发货通知表,按上传单号核对 Processing/Shipping Order Allocated。"""
result_selector = str(self.config.get('result_selector') or '').strip()
script = """
({ filename, resultSelector }) => {
const clean = (v) => String(v || '').replace(/\\s+/g, ' ').trim();
const wanted = clean(filename).replace(/\\.[^.]+$/, '');
const roots = resultSelector ? document.querySelectorAll(resultSelector) : document.querySelectorAll('tr[id^="shipping-order-"]');
for (const root of roots) {
const row = root.closest('tr') || root;
const text = clean(row.textContent);
if (!text || (!text.includes(filename) && !text.includes(wanted))) continue;
const cells = Array.from(row.querySelectorAll(':scope > td')).map((cell) => clean(cell.textContent));
const headers = Array.from(row.closest('table')?.querySelectorAll('thead th') || []).map((n) => clean(n.textContent).toLowerCase());
const at = (label) => { const i = headers.findIndex((h) => h === label); return i >= 0 ? cells[i] || '' : ''; };
const status = at('order status');
const description = at('order status description');
return { found: true, order_status: status, order_status_description: description };
}
return { found: false, order_status: '', order_status_description: '' };
}
"""
deadline = time.monotonic() + (self._timeout_ms() / 1000)
last_state: dict[str, Any] = {}
while time.monotonic() < deadline:
try:
state = page.evaluate(script, {'filename': filename, 'resultSelector': result_selector}) or {}
if isinstance(state, dict):
last_state = state
if _crane_upload_result_is_success(state):
return {
'reference': '',
'success_evidence': _capture_success_page_evidence(
page, kind='crane_order_status_dom', selector='tr[id^="shipping-order-"]',
filename=filename, reference=None,
),
}
except RuntimeError:
raise
except Exception:
# 旧版/非列表页面没有可执行的状态查询时,交回既有弹窗/配置判定。
return None
time.sleep(1)
return None
def _upload_shipment_with_browser(
file_path: Path, *, connector_type: str = "", upload_source: dict[str, Any] | None = None,