diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 41803a92..49f17814 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -1629,10 +1629,14 @@ def _handle_rpa_inventory_failed( *, commit: bool = True, ) -> dict[str, Any]: - """处理 failed 回调:累计尝试并在耗尽后转人工上传兜底。""" + """处理 failed 回调:记录稳定失败码、累计尝试并在耗尽后转人工上传兜底。""" apply_task_transition(task, TaskTransition.INV_UNAVAIL) task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500] - log_task_event(task, "inventory_rpa_failed", {"error": task.error_message, "rpa_runtime": runtime}) + log_task_event(task, "inventory_rpa_failed", { + "error": task.error_message, + "error_code": str(payload.get("error_code") or "rpa_export_failed"), + "rpa_runtime": runtime, + }) db.session.flush() attempts = inventory_rpa_attempts(task) if attempts >= max_rpa_inventory_attempts(): @@ -2532,9 +2536,58 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any # 定时批量成功项必须显式携带 Warehouse 身份;先做身份校验, # 避免缺 Warehouse 被后续文件路径错误遮蔽。 if not warehouse_id: + # [STEP] RPA 声称导出成功但缺少仓库身份时,文件绝不能成为可匹配 + # 快照;同时必须终态化本次逐源 Attempt/准备轮次,避免前端永久显示 + # “处理中”或允许重复触发同一运行中的 Attempt。 + if task and source_run_no_item and structured_attempt: + from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler + + per_source_callback_handler( + task, + source_code=source_code, + run_no=source_run_no_item, + callback_payload={ + **dict(merged_item), + 'error_code': 'warehouse_id_missing', + 'error_message': 'RPA 回调缺少 warehouse_id,无法确认库存归属。', + }, + ) + if task: + runtime = _save_last_inventory_rpa_runtime(task, merged_item) + _handle_rpa_inventory_failed( + task, + { + **dict(merged_item), + 'error_code': 'warehouse_id_missing', + 'error_message': 'RPA 回调缺少 warehouse_id,无法确认库存归属。', + }, + runtime, + commit=False, + ) + # 与显式 failed 回调保持相同的 Gate 收口语义:Task 已从 + # rpa_pending 转为可重试失败,正式 Execution 不能继续停在 + # waiting_external,否则右侧页面会显示过期的“处理中”。 + if task.active_process_execution_id: + from app.models import ShippingProcessExecution + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + + execution = db.session.get( + ShippingProcessExecution, + int(task.active_process_execution_id), + ) + if ( + execution is not None + and int(getattr(execution, 'task_id', 0) or 0) == int(task.id) + and str(getattr(execution, 'status', '') or '').strip().lower() != 'superseded' + ): + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + ) failed.append({ "source_code": source_code, "warehouse_id": warehouse_id, + "task_no": task_no or None, "error": "warehouse_id_missing", }) continue diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 19c2159f..8b5a5e0f 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -729,6 +729,69 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): assert len(failed_events) == 1 +def test_batch_success_missing_warehouse_closes_structured_rpa_attempt(app, tmp_path): + """成功回调缺仓库时必须终态化本次 Attempt,不能遗留为运行中。""" + from app import db + from app.models import ShippingInventoryPreparationAttempt, ShippingTaskInventoryRpaAttempt + from app.services.shipping_notice.inventory_recovery_service import create_inventory_preparation_round + + app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + with app.app_context(): + task = ShippingNotice( + task_no="SN-BATCH-MISSING-WAREHOUSE", + source_type="manual", + pending_human_reason="rpa_pending", + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], + ) + _confirm_direct_rpa_task_customer(task) + seed_task_inventory_source(task, source_code="CRANE") + db.session.add(task) + db.session.flush() + preparation = create_inventory_preparation_round( + task=task, + execution_id=None, + recovery_plan_id=None, + action_code="retry_inventory_preparation", + source_codes=["CRANE"], + gate_attempt_id=None, + ) + attempt = ShippingTaskInventoryRpaAttempt( + task_no=task.task_no, + source_code="CRANE", + attempt_no=1, + source_run_no="PSR-SN-BATCH-MISSING-WAREHOUSE-CRANE-A1-TEST", + status="running", + lease_token="lease-missing-warehouse", + callback_payload_json={}, + extra_json={}, + ) + db.session.add(attempt) + db.session.flush() + preparation.source_attempts[0].rpa_attempt_id = attempt.id + db.session.commit() + + result = _process_batch_callback({ + "run_no": "BATCH-MISSING-WAREHOUSE", + "trigger_type": "on_demand", + "results": [{ + "task_no": task.task_no, + "source_code": "CRANE", + "source_run_no": attempt.source_run_no, + "status": "success", + "success": True, + "warehouse_id": "", + }], + }) + + db.session.refresh(attempt) + db.session.refresh(preparation) + assert result["data"]["failed"][0]["error"] == "warehouse_id_missing" + assert attempt.status == "failed" + assert attempt.error_code == "warehouse_id_missing" + assert preparation.status == "failed" + assert preparation.source_attempts[0].status == "failed" + + def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path): """单任务 failed 回调缺少 site/warehouse 时仍应进入失败处理,但须匹配当前 run_no。""" from app import db diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts index 6487c4ab..f5c9e30a 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts @@ -1978,6 +1978,40 @@ describe('ShippingOrderReviewView audit and progress recovery', () => { expect(retryWorkspaceShippingTask).toHaveBeenCalledWith('SN-OT-FAIL-1'); }, 15000); + it('disables the formal Gate retry while inventory preparation is waiting for RPA callback', async () => { + // 关键断言:Gate 仍为 blocked_retryable 时,PreparationAttempt 的等待事实优先禁用重试。 + activeCase.value = { + ...activeCase.value, + status: 'confirmed', + has_formal_ot: true, + confirmed_task_id: 43, + confirmed_task_no: 'SN-OT-WAITING-INVENTORY', + automation: { status: 'failed', retryable: true, can_auto_create: false, can_build: true }, + }; + shippingProcessingProjection.value = { + shippingNoticeNo: 'SN-OT-WAITING-INVENTORY', + retryable: true, + userStatus: 'retryable', + primaryAction: { code: 'retry_inventory_preparation' }, + currentGate: { status: 'blocked_retryable' }, + inventoryPreparation: { + activeAttemptCount: 1, + gateAttemptActive: true, + pendingSources: ['CRANE'], + }, + uiState: { + status: 'retryable', + primary_action: { code: 'retry_inventory_preparation' }, + secondary_actions: [], + }, + }; + + const wrapper = await mountView(); + await flushPromises(); + + expect(wrapper.get('[data-testid="review-current-task-primary-action"]').attributes('disabled')).toBeDefined(); + }, 15000); + it('keeps top / wide / narrow stage labels identical via Progress projection (waiting_system_start)', async () => { // 关键断言:Case.current_stage 故意降级为误导码;三处必须消费 Progress label_key 文案。 shippingProcessingProjection.value = { diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.vue b/frontend/src/features/chat/views/ShippingOrderReviewView.vue index f99ae454..bdeb9128 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.vue +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.vue @@ -3747,9 +3747,7 @@ watch( :gate-status="currentTaskGateStatus" :primary-action="currentTaskPrimaryAction" :recovery-actions="currentTaskRecoveryActions" - :retrying="displayCase?.process_gate?.current_blocking_gate - ? (progressRetrying || caseSwitchLoading) - : (taskRetryButtonDisabled || progressRetrying || caseSwitchLoading)" + :retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading" :retry-exhausted-sources="taskInventoryExhaustedSources" :loading="caseContentSkeleton" @retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())" @@ -4343,9 +4341,7 @@ watch( :gate-status="currentTaskGateStatus" :primary-action="currentTaskPrimaryAction" :recovery-actions="currentTaskRecoveryActions" - :retrying="displayCase?.process_gate?.current_blocking_gate - ? (progressRetrying || caseSwitchLoading) - : (taskRetryButtonDisabled || progressRetrying || caseSwitchLoading)" + :retrying="taskRetryButtonDisabled || progressRetrying || caseSwitchLoading" :retry-exhausted-sources="taskInventoryExhaustedSources" :loading="caseContentSkeleton" @retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"