From 938f3dd0e8d338907232b5ffeadb4b97d78159c7 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Fri, 4 Sep 2026 20:38:48 +0800 Subject: [PATCH] =?UTF-8?q?fix(shipping-recovery):=20=E6=81=A2=E5=A4=8D?= =?UTF-8?q?=E5=BA=93=E5=AD=98RPA=E5=85=A5=E5=8F=A3=E4=B8=8E=E9=97=A8?= =?UTF-8?q?=E7=A6=81=E6=81=A2=E5=A4=8D=E6=B5=81=E7=A8=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../shipping_recovery_sweeper_service.py | 9 +- .../useShippingOrderReview.spec.ts | 158 +++- .../shipping-review/useShippingOrderReview.ts | 203 ++++- .../views/ShippingOrderReviewView.spec.ts | 836 ++++++++++++++++-- .../chat/views/ShippingOrderReviewView.vue | 145 ++- .../api/process-gates.api.ts | 2 +- .../useShippingProcessGateRecovery.spec.ts | 76 ++ .../useShippingProcessGateRecovery.ts | 94 +- 8 files changed, 1329 insertions(+), 194 deletions(-) diff --git a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py index 6e146227..1578e8e0 100644 --- a/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py +++ b/backend/app/services/shipping_notice/shipping_recovery_sweeper_service.py @@ -14,10 +14,7 @@ import logging from flask import current_app from app import db -from app.models import ( - ShippingNotice, - ShippingTaskInventoryRpaAttempt, -) +from app.models import ShippingOrderTask, ShippingTaskInventoryRpaAttempt _LOGGER = logging.getLogger(__name__) @@ -82,8 +79,8 @@ def _scan_stale_inventory_attempts(*, timeout_seconds: int) -> int: total = 0 for task in ( - ShippingNotice.query - .filter(ShippingNotice.task_no.in_(task_nos)) + ShippingOrderTask.query + .filter(ShippingOrderTask.task_no.in_(task_nos)) .all() ): try: diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts index 642932ac..30937ff8 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts @@ -59,6 +59,7 @@ const api = vi.hoisted(() => ({ confirmCase: vi.fn(), validateDraft: vi.fn(), + patchHeader: vi.fn(), })); @@ -89,7 +90,7 @@ vi.mock('../api/shipping.api', () => ({ confirmWorkspaceShippingOrderReviewCase: api.confirmCase, - patchWorkspaceShippingOrderReviewHeaderField: vi.fn(), + patchWorkspaceShippingOrderReviewHeaderField: api.patchHeader, patchWorkspaceShippingOrderReviewLineField: vi.fn(), @@ -135,7 +136,7 @@ const buildCase = (patch: Partial = {}): ShippingOrderR header_values: {}, - lines: [{ line_key: 'line-1' }], + lines: [{ draft_line_id: 'line-1' }], issues: [], @@ -149,7 +150,7 @@ const buildCase = (patch: Partial = {}): ShippingOrderR line_projections: [{ - line_key: 'line-1', + draft_line_id: 'line-1', line_index: 0, @@ -403,7 +404,7 @@ describe('useShippingOrderReview build eligibility writes', () => { expect(review.canConfirmBuild.value).toBe(false); expect(review.routingRecoveryLines.value).toHaveLength(1); - expect(review.routingRecoveryLines.value[0]?.line_key).toBe('line-1'); + expect(review.routingRecoveryLines.value[0]?.draft_line_id).toBe('line-1'); }); @@ -441,6 +442,68 @@ describe('useShippingOrderReview build eligibility writes', () => { expect(resume).toEqual({ outcome: 'auto_create_enqueued' }); }); + it('tracks an enqueued validation until the worker creates the formal order task', async () => { + vi.useFakeTimers(); + const queuedCase = buildCase({ + status: 'ready', + automation: { status: 'queued' }, + }); + const confirmedCase = buildCase({ + status: 'confirmed', + order_task_no: 'OT-1', + confirmed_task_no: 'OT-1', + automation: { status: 'running' }, + }); + api.validateDraft.mockResolvedValue({ + case: queuedCase, + resume_outcome: { outcome: 'auto_create_enqueued' }, + }); + api.getCase.mockResolvedValueOnce(buildCase()).mockResolvedValue(confirmedCase); + api.getQueue.mockResolvedValue({ + summary: { total: 1, needs_action: 0, processing: 1, completed: 0 }, + items: [{ + case_no: 'CASE-1', document_id: 1, status: 'confirmed', + lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [], + }], + }); + api.getExtractionRun.mockResolvedValue({ run_no: 'RUN-1', status: 'completed' }); + api.getProcessingWorkItem.mockResolvedValue({ + work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation', + }); + + const review = useShippingOrderReview(); + await review.load('RUN-1', 'CASE-1'); + await review.validate(); + + await vi.advanceTimersByTimeAsync(0); + expect(review.workflowProgressPolling.value).toBe(true); + await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100); + expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-1'); + expect(api.getProcessingWorkItem).toHaveBeenCalledWith('order_task', 'OT-1'); + + review.stopWorkflowProgressPolling(); + vi.useRealTimers(); + }); + + it('does not treat a field edit revalidation as a formal-order creation request', async () => { + vi.useFakeTimers(); + const revalidatingCase = buildCase({ + status: 'draft', + automation: { status: 'queued' }, + }); + api.patchHeader.mockResolvedValue(revalidatingCase); + + const review = useShippingOrderReview(); + await review.load('RUN-1', 'CASE-1'); + await review.patchHeader('ship_to_name', '新收货方'); + await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100); + + // 字段编辑后的 queued 是异步重校验,不是用户已确认的建单请求。 + expect(api.getCase).toHaveBeenCalledTimes(1); + expect(review.workflowProgressPolling.value).toBe(false); + vi.useRealTimers(); + }); + it('refreshes the current Case silently without entering the PDF-switch loading state', async () => { const review = useShippingOrderReview(); await review.load('RUN-1', 'CASE-1'); @@ -934,6 +997,44 @@ describe('useShippingOrderReview build eligibility writes', () => { vi.useRealTimers(); }); + it('stops workflow progress polling once the unified work item is interrupted (waiting_human)', async () => { + vi.useFakeTimers(); + const readyCase = buildCase({ + status: 'ready', + draft: { + ...buildCase().draft!, + build_eligibility: { can_build: true, status: 'ready', line_projections: [] }, + }, + }); + api.getCase.mockResolvedValue(readyCase); + api.getRun.mockResolvedValue({ + run_no: 'RUN-1', summary: {}, + items: [{ case_no: 'CASE-1', document_id: 1, status: 'ready', available_actions: ['confirm'] }], + }); + api.getEvidence.mockResolvedValue({ items: [] }); + api.getPreview.mockResolvedValue({ preview_url: '' }); + api.getProcessingWorkItem.mockResolvedValue({ + work_item_no: 'OT-1', status: 'blocked', user_status: 'waiting_human', + currentGate: { gateCode: 'inventory_matching', status: 'blocked_manual' }, + }); + api.confirmCase.mockResolvedValue({ + task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false, + case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' }, auto_progress_started: true, + }); + + const review = useShippingOrderReview(); + await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' }); + await review.confirm(); + + await vi.advanceTimersByTimeAsync(0); + await Promise.resolve(); + // 中断(waiting_human,即“等待人工处理”)视为线性终态:结果不会自行变化,必须停止轮询。 + expect(review.workflowProgressPolling.value).toBe(false); + + review.stopWorkflowProgressPolling(); + vi.useRealTimers(); + }); + it('refreshes the active Case and queue while post-confirm automation is still active', async () => { vi.useFakeTimers(); const readyCase = buildCase({ @@ -1116,7 +1217,8 @@ describe('useShippingOrderReview build eligibility writes', () => { run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1', })); - const review = useShippingOrderReview(); + const onReparseCaseReady = vi.fn(); + const review = useShippingOrderReview({ onReparseCaseReady }); await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' }); await review.reparseDocument('document_quality'); @@ -1125,6 +1227,8 @@ describe('useShippingOrderReview build eligibility writes', () => { expect(review.reviewRun.value?.run_no).toBe('RUN-2'); expect(review.activeCase.value?.case_no).toBe('CASE-2'); + // 关键断言:只有新版 Case 真正落到 activeCase 后,页面才接收可同步深链的目标。 + expect(onReparseCaseReady).toHaveBeenCalledWith({ runNo: 'RUN-2', caseNo: 'CASE-2', documentId: 1 }); review.stopReparseCaseRefreshPolling(); vi.useRealTimers(); }); @@ -1250,6 +1354,44 @@ describe('useShippingOrderReview build eligibility writes', () => { vi.useRealTimers(); }); + it('[选法 2] defers review Case + Evidence load on a formal downstream work item', async () => { + api.getRun.mockResolvedValue({ run_no: 'RUN-1', summary: {}, items: [] }); + api.getQueue.mockResolvedValue({ + summary: { total: 1, needs_action: 0, processing: 0, completed: 1 }, + items: [{ + case_no: 'CASE-1', document_id: 1, status: 'confirmed', + lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [], + has_formal_ot: true, confirmed_task_no: 'SN-1', + }], + }); + api.getCase.mockClear(); + api.getEvidence.mockClear(); + + const review = useShippingOrderReview(); + await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' }); + + // 正式任务下游阶段:首屏不拉复核 Case 快照 + Evidence。 + expect(api.getCase).not.toHaveBeenCalled(); + expect(api.getEvidence).not.toHaveBeenCalled(); + }); + + it('[选法 2] loadReviewCase lazily fetches review Case + Evidence on demand', async () => { + api.getCase.mockClear(); + api.getEvidence.mockClear(); + api.getCase.mockResolvedValue({ + case: buildCase({ case_no: 'CASE-1' }), + projection_version: 1, + loading_context: null, + }); + api.getEvidence.mockResolvedValue({ case_no: 'CASE-1', items: [] }); + + const review = useShippingOrderReview(); + await review.loadReviewCase('CASE-1'); + + expect(api.getCase).toHaveBeenCalledWith('CASE-1'); + expect(api.getEvidence).toHaveBeenCalledWith('CASE-1'); + }); + }); @@ -1295,7 +1437,7 @@ describe('inventory routing recovery', () => { can_build: true, status: 'ready', line_projections: [{ - line_key: 'line-pending', + draft_line_id: 'line-pending', line_index: 0, can_build: false, block_reason: 'inventory_source_unavailable', @@ -1309,7 +1451,7 @@ describe('inventory routing recovery', () => { const review = useShippingOrderReview(); await review.load('RUN-1', 'CASE-1'); expect(review.routingRecoveryLines.value).toHaveLength(1); - expect(review.routingRecoveryLines.value[0]?.line_key).toBe('line-pending'); + expect(review.routingRecoveryLines.value[0]?.draft_line_id).toBe('line-pending'); }); it('reroutes inventory routing with idempotency_key and expected_draft_version', async () => { @@ -1324,7 +1466,7 @@ describe('inventory routing recovery', () => { expect(api.rerouteInventoryRouting).toHaveBeenCalledWith('CASE-1', { expected_draft_version: 2, idempotency_key: 'idem-reroute-1', - line_key: 'line-1', + draft_line_id: 'line-1', }); expect(review.activeCase.value?.draft?.draft_version).toBe(3); uuidSpy.mockRestore(); diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts index ffb9e32b..b929f2c0 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts @@ -5,9 +5,17 @@ * 逻辑:按 runNo 加载 Review Run/Case;合成 ShippingReviewProgressContext; * OT 绑定 Case.order_task_no / Candidate;切换时保留稳定显示壳,目标快照到齐后原子替换; * 409 REVIEW_DRAFT_VERSION_MISMATCH 冲突处理;build_eligibility 驱动 confirm/reroute; - * 重识别后刷新正式 Run/Case/Gate 投影;PDF Blob 由 ensurePreviewLoaded 按需加载。 + * 重识别后刷新正式 Run/Case/Gate 投影,并在新版 Case 确认落位后通知页面同步深链; + * PDF Blob 由 ensurePreviewLoaded 按需加载。 */ -import { computed, getCurrentInstance, onBeforeUnmount, ref } from 'vue'; +import { + computed, + getCurrentInstance, + onBeforeUnmount, + ref, + toValue, + type MaybeRefOrGetter, +} from 'vue'; import { BusinessError } from '@/shared/api/client'; import { addWorkspaceShippingOrderReviewLine, @@ -303,7 +311,13 @@ function synthesizeWorkItemFromReviewContext(params: { }; } -export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void } = {}) { +export function useShippingOrderReview(options: { + onWorkflowRefresh?: () => void; + /** 新版重解析 Case 已完成 load 后通知页面;路由和工作面仍由页面统一裁决。 */ + onReparseCaseReady?: (target: { runNo: string; caseNo: string; documentId: number }) => void | Promise; + /** 正式任务 OT 号(选法 2):正式任务下游阶段不再反推复核 Case,改由任务详情提供。 */ + externalOrderTaskNo?: MaybeRefOrGetter; +} = {}) { const reviewRun = ref(null); const reviewQueue = ref(null); const activeCase = ref(null); @@ -316,8 +330,10 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void const authoritativeOrderTaskNo = computed(() => { const item = reviewProgressContext.value; const no = String(item?.user_task_no || '').trim(); - if (!no || item?.user_task_authoritative === false) return null; - return no; + if (no && item?.user_task_authoritative !== false) return no; + // [选法 2] 正式任务下游阶段 activeCase 可能为空;OT 号改由任务详情提供。 + const external = String(toValue(options.externalOrderTaskNo) ?? '').trim(); + return external || null; }); const { projection: shippingProcessingProjection, @@ -399,6 +415,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void let contextConversationId = ''; let contextItemNo = ''; let progressPollTimer: ReturnType | null = null; + let stpCreatePollTimer: ReturnType | null = null; let reparseCaseRefreshTimer: ReturnType | null = null; /** @@ -423,12 +440,67 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void workflowProgressPolling.value = false; }; + /** + * 跟踪复核条件满足后的异步 STP 建单,直到后端产生正式 OT。 + * + * 核心逻辑:复核写操作只保证校验/入队成功;Worker 后续才会把 + * Case 绑定到 order_task_no。发现 OT 后复用既有任务级投影轮询,避免 + * 在各个复核按钮中重复实现阶段刷新逻辑。 + */ + const stopStpAutoCreateTracking = () => { + if (stpCreatePollTimer != null) { + window.clearInterval(stpCreatePollTimer); + stpCreatePollTimer = null; + } + }; + + const startStpAutoCreateTracking = () => { + stopStpAutoCreateTracking(); + const caseNo = String(activeCase.value?.case_no || '').trim(); + const initialStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase(); + if (!caseNo || !['queued', 'running'].includes(initialStatus)) return; + + const tick = async () => { + if (typeof document !== 'undefined' && document.hidden) return; + try { + const [caseSnapshot, queue] = await Promise.all([ + getWorkspaceShippingOrderReviewCase(caseNo), + reviewRun.value?.run_no + ? getWorkspaceShippingOrderReviewQueue(reviewRun.value.run_no) + : Promise.resolve(null), + ]); + if (String(activeCase.value?.case_no || '').trim() !== caseNo) return; + applyCaseSnapshot(caseSnapshot); + if (queue) reviewQueue.value = queue; + await refreshWorkItemContext(); + const taskNo = String( + caseSnapshot.case?.order_task_no + || caseSnapshot.case?.confirmed_task_no + || reviewProgressContext.value?.user_task_no + || '', + ).trim(); + const status = String(caseSnapshot.case?.automation?.status || '').trim().toLowerCase(); + if (taskNo) { + stopStpAutoCreateTracking(); + startWorkflowProgressPolling(taskNo); + } else if (['failed', 'manual_fallback'].includes(status)) { + stopStpAutoCreateTracking(); + } + } catch { + // 临时网络失败由下一拍继续读取,不改变后端 Job 状态。 + } + }; + void tick(); + stpCreatePollTimer = window.setInterval(() => { void tick(); }, PROGRESS_POLL_MS); + }; + /** * 等待后端明确产出新复核 Case 后切换工作台,不将 Run 技术状态推断成另一条用户进度。 * * AI 触发时机:用户发起“重新识别此 PDF”后调用。 * 核心逻辑:以会话级 Review Stream 队列中同一 document_id 的 source_run_no + case_no - * 触发 Case 加载;completed 也可能已生成可复核 Case,不能仅按 Run 技术终态停止。 + * 触发 Case 加载;新版 Case 真正落位后通知页面同步后端授权的生命周期深链; + * completed 也可能已生成可复核 Case,不能仅按 Run 技术终态停止。 * failed/cancelled 仅刷新正式投影并停止,失败原因由正式状态卡与 Gate 表达。 * * Args: @@ -457,13 +529,22 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void if (['review_required', 'partially_completed', 'completed'].includes(normalizedStatus)) { const target = await resolveCurrentStreamTarget(targetDocumentId, targetRunNo); if (target) { - window.clearInterval(reparseCaseRefreshTimer!); - reparseCaseRefreshTimer = null; await load(target.runNo, target.caseNo, { conversationId: contextConversationId, itemNo: contextItemNo || undefined, restoreProgress: false, }); + // [STEP] 只有新 Case 真正落到工作台才停止轮询;Stream 尚未激活或 load + // 静默失败(内部回滚旧快照)时保留下一拍重试,避免一次性失败把用户 + // 永远留在已被替代的历史版本上。 + if (String(activeCase.value?.case_no || '').trim() === target.caseNo) { + await options.onReparseCaseReady?.({ + runNo: target.runNo, + caseNo: target.caseNo, + documentId: targetDocumentId || 0, + }); + stopReparseCaseRefreshPolling(); + } } return; } @@ -522,8 +603,11 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void showWorkflowProgress.value = true; workflowProgressPolling.value = true; // RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。 - // needs_human(等待人工)视为线性终态:结果不会自行变化,继续轮询浪费资源。 - const UNIFIED_TERMINAL = new Set(['completed', 'cancelled', 'needs_human']); + // 等待人工(waiting_human,即“中断”)视为线性终态:结果不会自行变化,继续轮询浪费资源。 + // 注意:统一投影的用户态值是 waiting_human(旧字段是 needs_human),若沿用旧的 + // needs_human 会让已中断任务永远匹配不到终态、一直空转轮询;failed 同理是停止状态。 + // 可重试失败(retryable)不在此列,需保留轮询以便后续成功回调自动刷新工作流。 + const UNIFIED_TERMINAL = new Set(['completed', 'cancelled', 'waiting_human', 'failed']); let lastUnifiedStatus = ''; let lastLifecycleFingerprint = ''; const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']); @@ -589,6 +673,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void onBeforeUnmount(() => { caseSwitchAbortController?.abort(); stopWorkflowProgressPolling(); + stopStpAutoCreateTracking(); stopReparseCaseRefreshPolling(); stopShippingProcessing(); clearPreview(); @@ -960,16 +1045,13 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void const queueRequest = getWorkspaceShippingOrderReviewQueue(runNo); // 路由已明确目标 Case 时,详情读取不应等待较慢的 Run/Queue 摘要; // 四份数据仍在全部成功后原子提交,避免混合工作面。 - const preferredCaseRequest = preferredCaseNo - ? Promise.all([ - getWorkspaceShippingOrderReviewCase(preferredCaseNo), - getWorkspaceShippingOrderReviewEvidence(preferredCaseNo), - ]) - : null; // 已有稳定工作台且路由明确目标 PDF 时,目标详情是用户切换的关键路径; // Run/Queue 只负责后续更新导航和阶段摘要,不能用其慢投影阻塞当前文件显示。 - if (hasStableWorkbench && preferredCaseRequest) { - const [caseSnapshot, caseEvidence] = await preferredCaseRequest; + if (hasStableWorkbench && preferredCaseNo) { + const [caseSnapshot, caseEvidence] = await Promise.all([ + getWorkspaceShippingOrderReviewCase(preferredCaseNo), + getWorkspaceShippingOrderReviewEvidence(preferredCaseNo), + ]); if (generation !== caseLoadGeneration) return; applyCaseSnapshot(caseSnapshot); evidence.value = caseEvidence?.items || []; @@ -987,22 +1069,28 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void return; } - const [run, queue, preferredSnapshot] = await Promise.all([ - runRequest, - queueRequest, - preferredCaseRequest, - ]); + const [run, queue] = await Promise.all([runRequest, queueRequest]); if (generation !== caseLoadGeneration) return; // [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。 const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no; - const [caseSnapshot, caseEvidence] = preferredSnapshot - ? preferredSnapshot - : caseNo - ? await Promise.all([ - getWorkspaceShippingOrderReviewCase(caseNo), - getWorkspaceShippingOrderReviewEvidence(caseNo), - ]) - : [null, null]; + // [选法 2] 正式任务下游阶段(通知准备/货代上传/通知完成)本阶段不拉复核编辑器 + // (Case 快照 + Evidence),改由任务详情 + 统一投影驱动;进入「订单复核」才补拉。 + const navItem = (queue.items || run.items).find( + (item) => String(item.case_no || '').trim() === String(caseNo || '').trim(), + ) || null; + const navStage = String(navItem?.lifecycle_stage || '').trim().toLowerCase(); + const isFormalDownstream = Boolean( + navItem?.has_formal_ot + && !['intake_parse', 'order_review'].includes(navStage), + ); + let caseSnapshot: ShippingOrderReviewCaseSnapshot | null = null; + let caseEvidence: { case_no: string; items: ShippingOrderReviewEvidence[] } | null = null; + if (!isFormalDownstream && caseNo) { + [caseSnapshot, caseEvidence] = await Promise.all([ + getWorkspaceShippingOrderReviewCase(caseNo), + getWorkspaceShippingOrderReviewEvidence(caseNo), + ]); + } if (generation !== caseLoadGeneration) return; reviewRun.value = run; reviewQueue.value = queue; @@ -1134,6 +1222,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void const save = async (action: () => Promise) => { saving.value = true; saveFailed.value = false; + // 任意草稿变更都会使上一轮“已提交建单”跟踪失效;新的草稿版本必须重新显式提交。 + stopStpAutoCreateTracking(); const localVersion = version(); try { const nextCase = await action(); @@ -1182,9 +1272,9 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void return String(field?.field_code || fieldId).trim(); }; - const draftLineIndex = (lineKey: string) => { + const draftLineIndex = (draftLineId: string) => { const lines = activeCase.value?.draft?.lines || []; - return lines.findIndex((row) => String(row.line_key || '') === String(lineKey || '')); + return lines.findIndex((row) => String(row.draft_line_id || '') === String(draftLineId || '')); }; const formalEditOptions = () => ({ @@ -1315,7 +1405,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void fieldId: string, value: unknown, restoreMachine = false, - override?: { override_reason_code?: string; override_reason_text?: string }, ) => { if (!activeCase.value) return Promise.resolve(); if (isFormalTaskFieldEdit()) { @@ -1338,8 +1427,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void expected_draft_version: version(), value, restore_machine: restoreMachine, - override_reason_code: override?.override_reason_code, - override_reason_text: override?.override_reason_text, })); }; const addLine = () => activeCase.value && save(() => addWorkspaceShippingOrderReviewLine(activeCase.value!.case_no, version())); @@ -1351,6 +1438,12 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void try { const response = await validateWorkspaceShippingOrderReviewDraft(activeCase.value.case_no, version()); await save(async () => response.case); + // 只有显式“保存并校验”且后端确认已入队时,才跟踪 Worker 创建正式订单。 + // 普通字段编辑/增删行虽然会触发异步重校验,但仍停留在订单复核阶段。 + const outcome = String(response.resume_outcome?.outcome || '').trim(); + if (['auto_create_enqueued', 'already_queued', 'already_running'].includes(outcome)) { + startStpAutoCreateTracking(); + } return response.resume_outcome; } finally { validationInProgress.value = false; @@ -1359,15 +1452,15 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void /** * ?????????????????409 ????? markWriteFailure? - * @param lineKey - ???????? reroute + * @param draftLineId - 草稿行稳定身份;为空表示整单重算 */ - const rerouteInventoryRouting = (lineKey?: string) => { + const rerouteInventoryRouting = (draftLineId?: string) => { if (!activeCase.value) return Promise.resolve(); - const trimmed = String(lineKey || '').trim(); + const trimmed = String(draftLineId || '').trim(); return save(() => postWorkspaceShippingOrderReviewInventoryRoutingReroute(activeCase.value!.case_no, { expected_draft_version: version(), idempotency_key: crypto.randomUUID(), - ...(trimmed ? { line_key: trimmed } : {}), + ...(trimmed ? { draft_line_id: trimmed } : {}), })); }; @@ -1517,7 +1610,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void try { const response = await requestWorkspaceShippingOrderReviewLlmSuggestion(activeCase.value.case_no, { field_id: focusedFieldId.value, - line_key: focusedLineKey.value, + draft_line_id: focusedLineKey.value, issue_code: issueCode ?? undefined, expected_draft_version: activeCase.value.draft?.draft_version, }); @@ -1580,6 +1673,31 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void return target; }; + /** + * 【选法 2】正式任务下游阶段懒加载复核编辑器:不重拉 Run/Queue,仅按需读取 + * 当前文件的 Case 快照 + Evidence,供用户从「通知准备」切回「订单复核」阶段使用。 + */ + const loadReviewCase = async (caseNo: string | null | undefined) => { + const normalized = String(caseNo || '').trim(); + if (!normalized) return; + const generation = ++caseLoadGeneration; + try { + const [caseSnapshot, caseEvidence] = await Promise.all([ + getWorkspaceShippingOrderReviewCase(normalized), + getWorkspaceShippingOrderReviewEvidence(normalized), + ]); + if (generation !== caseLoadGeneration) return; + applyCaseSnapshot(caseSnapshot); + evidence.value = caseEvidence?.items || []; + clearPreview(); + await refreshWorkItemContext(contextConversationId, contextItemNo, { + expectedLoadGeneration: generation, + }); + } catch { + // 懒加载失败保留当前工作面,不抛到页面主流程。 + } + }; + return { reviewRun, reviewQueue, @@ -1638,6 +1756,7 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void saveFailed, versionsLoading, load, + loadReviewCase, selectCase, resetCaseTransientState, requestedCaseNo, @@ -1654,6 +1773,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void validate, rerouteInventoryRouting, confirm, + startStpAutoCreateTracking, + stopStpAutoCreateTracking, startWorkflowProgressPolling, stopWorkflowProgressPolling, startReparseCaseRefreshPolling, diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts index 01389cc9..a7d2a183 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts @@ -11,12 +11,14 @@ import { flushPromises, mount } from '@vue/test-utils'; import { createI18n } from 'vue-i18n'; import { createRouter, createMemoryHistory } from 'vue-router'; import ShippingOrderReviewView from './ShippingOrderReviewView.vue'; +import ReviewCurrentProcessingCard from '../components/shipping-review/ReviewCurrentProcessingCard.vue'; import ReviewFieldConflictPanel from '../components/shipping-review/ReviewFieldConflictPanel.vue'; import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context'; import { auditWorkspaceShippingOrderReviewEligibilityDetails, auditWorkspaceShippingOrderReviewVersionHistory, getWorkspaceShippingFreightNoticeGroups, + getWorkspaceShippingOrderReviewCase, getWorkspaceShippingTask, decideWorkspaceShippingOrderReviewLineFulfillment, waveWorkspaceShippingOrderReviewLineFulfillment, @@ -58,7 +60,11 @@ const confirmMock = vi.fn(); const reloadLatestDraftMock = vi.fn().mockResolvedValue(undefined); const refreshShippingProcessingMock = vi.fn().mockResolvedValue(undefined); const startWorkflowProgressPollingMock = vi.fn(); +const stopWorkflowProgressPollingMock = vi.fn(); +const stopReparseCaseRefreshPollingMock = vi.fn(); const patchLineMock = vi.fn().mockResolvedValue(undefined); +const reparseDocumentMock = vi.fn().mockResolvedValue({ run: { run_no: 'RUN-2' } }); +let reparseCaseReadyHandler: ((target: { runNo: string; caseNo: string; documentId: number }) => void) | undefined; const { submitProcessGatePrimaryActionMock } = vi.hoisted(() => ({ submitProcessGatePrimaryActionMock: vi.fn().mockResolvedValue({ outcome: 'submitted' }), })); @@ -176,7 +182,7 @@ function createActiveCaseFixture() { machine_fields: [{ field_id: 'fld-po', observations: [{ value: 'PO-1' }] }], }, lines: [{ - line_key: 'LINE-1', + draft_line_id: 'LINE-1', values: {}, machine_fields: [], }], @@ -204,6 +210,7 @@ vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => { case: null, }), retryShippingNoticeIntake: vi.fn().mockResolvedValue({ intake_no: 'SNI-RETRY-1', parse_status: 'queued' }), + getWorkspaceShippingOrderReviewCase: vi.fn().mockResolvedValue({ case: null }), getWorkspaceShippingTask: vi.fn().mockResolvedValue({ task_no: 'SN-MOCK', status: 'created', @@ -221,10 +228,13 @@ const reviewComposableMockApi = vi.hoisted(() => ({ vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({ REVIEW_BUILD_ELIGIBILITY_BLOCKED: 'SHIPPING.REVIEW_BUILD_ELIGIBILITY_BLOCKED', - useShippingOrderReview: () => { + useShippingOrderReview: (options?: { + onReparseCaseReady?: (target: { runNo: string; caseNo: string; documentId: number }) => void; + }) => { if (!reviewComposableMockApi.create) { throw new Error('createReviewComposableMock not initialized'); } + reparseCaseReadyHandler = options?.onReparseCaseReady; return reviewComposableMockApi.create(); }, })); @@ -290,6 +300,7 @@ function createReviewComposableMock() { intakeParseLoading: ref(false), intakeParseLoadFailed: ref(false), load, + loadReviewCase: vi.fn().mockResolvedValue(undefined), selectCase, refreshWorkItemContext: vi.fn(), openCurrentVersion: vi.fn(), @@ -309,7 +320,7 @@ function createReviewComposableMock() { createManualDraft: vi.fn(), markNonOrder: vi.fn(), markQualityIssue: vi.fn(), - reparseDocument: vi.fn(), + reparseDocument: reparseDocumentMock, focusSuggestionField, setEvidenceDrawerFocus: vi.fn(), clearEvidenceDrawerFocus: vi.fn(), @@ -322,7 +333,10 @@ function createReviewComposableMock() { isWorkItemClosed: computed(() => false), showWorkflowProgress: computed(() => false), workflowProgressPolling: computed(() => false), + startStpAutoCreateTracking: vi.fn(), startWorkflowProgressPolling: startWorkflowProgressPollingMock, + stopWorkflowProgressPolling: stopWorkflowProgressPollingMock, + stopReparseCaseRefreshPolling: stopReparseCaseRefreshPollingMock, shippingProcessingProjection, shippingProcessingLoading, shippingProcessingError: ref(null), @@ -446,6 +460,10 @@ async function mountView(query: Record = {}) { caseSwitchRetry: '重试', documentNavigation: 'PDF 导航', documents: 'PDF', + lifecycle: { + autoAdvanced: '已自动推进到{stage}', + stages: { fulfillment_prep: '通知准备' }, + }, unnamedDocument: '未命名', caseStatus: '{status} · {count}', caseStatuses: { draft: '草稿', unknown: '未知' }, @@ -589,6 +607,7 @@ async function mountView(query: Record = {}) { statusCompleted: '已完成', statusIdle: '待机', statusTaskMissing: '关联异常', + stageLoading: '正在获取最新状态…', stages: { waiting_system_start: '等待系统启动', waiting_to_start: '等待系统启动', @@ -638,6 +657,7 @@ async function mountView(query: Record = {}) { jumpToCurrentVersion: '跳转', currentVersionUnavailable: '不可用', lifecycle: { + autoAdvanced: '已自动推进到{stage}', navigation: '订单生命周期阶段', current: '当前可处理', processing: '处理中', @@ -663,8 +683,14 @@ async function mountView(query: Record = {}) { uploadComplete: { title: '通知完成', subtitle: '上传成功证据已核验。', + batchCount: '本批已上传 {count} 张发货通知', uploadModeManual: '人工确认', uploadModeRpa: 'RPA 上传', + empty: '本批暂无已上传的发货通知。', + }, + freightUpload: { + loading: '正在加载发货通知…', + loadFailed: '发货通知加载失败,请刷新后重试。', }, upload: { receipt: '货代回执:{value}', @@ -682,7 +708,7 @@ async function mountView(query: Record = {}) { waiting_system_start: '等待系统启动', }, progress: { - step: { profile_matching: '正在匹配订单模板' }, + step: { profile_matching: '正在匹配订单模板', document_queued: '正在等待解析任务启动' }, lifecycleReason: { processing_slow: '当前步骤耗时较长,系统仍在继续。', review_required: '当前结果需要人工复核。', @@ -697,6 +723,19 @@ async function mountView(query: Record = {}) { versionLabel: 'V{version}', }, }, + workspace: { + shippingNotice: { + processGate: { + inventoryActions: { + retryInventoryPreparation: '重新获取库存(RPA)', + }, + actionCodes: { + confirm_customer: '确认客户', + resolve_field_conflicts: '处理字段冲突', + }, + }, + }, + }, errors: { generic: '错误' }, }, }, @@ -739,7 +778,6 @@ async function mountView(query: Record = {}) { + '' + '', }, - ReviewLineNoOverrideDialog: true, ReviewDocumentEvidenceDrawer: evidenceDrawerStub, }, }, @@ -752,6 +790,14 @@ async function mountView(query: Record = {}) { /** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */ function resetActiveCaseFixture() { activeCase.value = createActiveCaseFixture(); + reviewQueue.value = { + conversation_id: 'conv-1', + summary: { total: 1, needs_action: 1, processing: 0, completed: 0 }, + items: [{ + case_no: 'CASE-1', source_run_no: 'RUN-1', document_id: 1, file_name: 'po.pdf', status: 'draft', + issue_count: 0, available_actions: ['validate', 'confirm'], + }], + }; reviewRun.value = { run_no: 'RUN-1', items: [{ @@ -772,6 +818,9 @@ function resetActiveCaseFixture() { describe('ShippingOrderReviewView layout phase 1', () => { beforeEach(() => { vi.clearAllMocks(); + reparseCaseReadyHandler = undefined; + reparseDocumentMock.mockResolvedValue({ run: { run_no: 'RUN-2' } }); + stopReparseCaseRefreshPollingMock.mockReset(); vi.useRealTimers(); ensureIntakeParseContextLoaded.mockResolvedValue(true); resetActiveCaseFixture(); @@ -788,7 +837,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { vi.useRealTimers(); }); - it('puts customer PO line first and excludes internal line number and inventory source from the main table', async () => { + it('puts customer PO line first, keeps the read-only internal line number, and keeps inventory source in the main table', async () => { activeCase.value = { ...activeCase.value, schema: { @@ -803,7 +852,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { draft: { ...activeCase.value.draft, lines: [{ - line_key: 'LINE-1', + draft_line_id: 'LINE-1', values: { 'fld-line-no': { value: '10' }, 'fld-customer-po-line': { value: '00010' }, @@ -818,11 +867,13 @@ describe('ShippingOrderReviewView layout phase 1', () => { const wrapper = await mountView(); const headers = wrapper.find('[data-testid="review-lines-scroll"]').findAll('th').map((item) => item.text()); - // 关键断言:业务主键首列,内部项次和库存源线索不挤占默认主表宽度。 - expect(headers.slice(0, 3)).toEqual(['#', '客户 PO 项次 *', '料号 *']); - expect(headers).not.toContain('内部项次 *'); - expect(headers).not.toContain('库存源'); - expect(wrapper.find('[data-testid="review-line-inventory-source"]').exists()).toBe(false); + // 关键断言:业务核对项次优先,订单项次 line_no 固定只读展示;库存源线索作为路由核对列保留且值可见。 + expect(headers.slice(0, 3)).toEqual(['#', '客户 PO 项次 *', '内部项次 *']); + expect(headers).toContain('料号 *'); + expect(headers).toContain('库存源线索'); + const inventorySourceCell = wrapper.find('[data-testid="review-line-inventory-source"]'); + expect(inventorySourceCell.exists()).toBe(true); + expect(inventorySourceCell.find('input').element.value).toBe('DBS'); }); it('keeps the requested replacement Case when the loaded Run updates the URL', async () => { @@ -839,6 +890,132 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect((wrapper.vm as any).$route.query.case_no).toBe('CASE-NEW'); }); + it('opens the replacement Case at its backend current stage after reparse completes', async () => { + const originalQueue = reviewQueue.value; + try { + reviewQueue.value = { + ...reviewQueue.value, + items: [{ + ...reviewQueue.value.items[0], + lifecycle_stage: 'intake_parse', + lifecycle_entries: [{ code: 'intake_parse', state: 'current' }], + intake_parse_authorized: true, + }], + }; + const wrapper = await mountView({ lifecycle_stage: 'intake_parse' }); + + (wrapper.vm as any).pendingAction = 'reparse'; + await (wrapper.vm as any).submitPendingAction({ reasonCode: 'ok' }); + expect(reparseCaseReadyHandler).toBeTypeOf('function'); + + reviewQueue.value = { + ...reviewQueue.value, + items: [{ + ...reviewQueue.value.items[0], + case_no: 'CASE-2', + source_run_no: 'RUN-2', + document_id: 1, + lifecycle_stage: 'order_review', + lifecycle_entries: [ + { code: 'intake_parse', state: 'available' }, + { code: 'order_review', state: 'current' }, + ], + }], + }; + activeCase.value = { + ...createActiveCaseFixture(), + case_no: 'CASE-2', + document: { id: 1, file_name: 'po.pdf' }, + }; + reviewRun.value = { run_no: 'RUN-2', items: [{ case_no: 'CASE-2', document_id: 1 }] }; + await nextTick(); + reparseCaseReadyHandler?.({ runNo: 'RUN-2', caseNo: 'CASE-2', documentId: 1 }); + await flushPromises(); + + expect((wrapper.vm as { $route: { query: Record } }).$route.query.lifecycle_stage) + .toBe('order_review'); + expect(wrapper.find('[data-testid="review-editor-body"]').exists()).toBe(true); + } finally { + reviewQueue.value = originalQueue; + } + }); + + it('keeps the manually selected stage when reparse completes', async () => { + const originalQueue = reviewQueue.value; + try { + reviewQueue.value = { + ...reviewQueue.value, + items: [{ + ...reviewQueue.value.items[0], + lifecycle_stage: 'intake_parse', + lifecycle_entries: [{ code: 'intake_parse', state: 'current' }], + intake_parse_authorized: true, + }], + }; + const wrapper = await mountView({ lifecycle_stage: 'intake_parse' }); + + (wrapper.vm as any).pendingAction = 'reparse'; + await (wrapper.vm as any).submitPendingAction({ reasonCode: 'ok' }); + await (wrapper.vm as any).selectLifecycleStage('intake_parse'); + + reviewQueue.value = { + ...reviewQueue.value, + items: [{ + ...reviewQueue.value.items[0], + case_no: 'CASE-2', + source_run_no: 'RUN-2', + document_id: 1, + lifecycle_stage: 'order_review', + lifecycle_entries: [ + { code: 'intake_parse', state: 'available' }, + { code: 'order_review', state: 'current' }, + ], + }], + }; + activeCase.value = { + ...createActiveCaseFixture(), + case_no: 'CASE-2', + document: { id: 1, file_name: 'po.pdf' }, + }; + reviewRun.value = { run_no: 'RUN-2', items: [{ case_no: 'CASE-2', document_id: 1 }] }; + reparseCaseReadyHandler?.({ runNo: 'RUN-2', caseNo: 'CASE-2', documentId: 1 }); + await flushPromises(); + + expect((wrapper.vm as { $route: { query: Record } }).$route.query.lifecycle_stage) + .toBe('intake_parse'); + } finally { + reviewQueue.value = originalQueue; + } + }); + + it('stops the pending reparse navigation when the user selects another PDF', async () => { + const originalQueue = reviewQueue.value; + try { + reviewQueue.value = { + ...reviewQueue.value, + items: [ + ...reviewQueue.value.items, + { + ...reviewQueue.value.items[0], + case_no: 'CASE-OTHER', + document_id: 2, + source_run_no: 'RUN-1', + }, + ], + }; + const wrapper = await mountView(); + + (wrapper.vm as any).pendingAction = 'reparse'; + await (wrapper.vm as any).submitPendingAction({ reasonCode: 'ok' }); + await (wrapper.vm as any).select('CASE-OTHER'); + + // 关键断言:用户主动切换文件后,旧 PDF 的自动恢复轮询必须停止,不能反向抢占工作台。 + expect(stopReparseCaseRefreshPollingMock).toHaveBeenCalledTimes(1); + } finally { + reviewQueue.value = originalQueue; + } + }); + it('shows the five-stage Run progress and current parsing step before a Case is available', async () => { activeCase.value = null as any; reviewRun.value = { run_no: 'RUN-PARSING', items: [] }; @@ -877,10 +1054,57 @@ describe('ShippingOrderReviewView layout phase 1', () => { const wrapper = await mountView(); - // 关键断言:重解析不再拥有第二条黄色横幅;唯一进度紧跟五阶段导航。 + // 关键断言:重解析不再拥有第二条黄色横幅; + // v2:有 Case 时横幅收窄为无 Case 轻提示——此处不得再出现 Run 级提示行。 expect(wrapper.find('[data-testid="review-status-banner"]').exists()).toBe(false); expect(wrapper.findAll('[data-testid="review-run-lifecycle-progress"]')).toHaveLength(1); - expect(wrapper.get('[data-testid="review-run-lifecycle-progress"]').text()).toContain('正在匹配订单模板'); + expect(wrapper.find('[data-testid="review-run-lifecycle-current-step"]').exists()).toBe(false); + }); + + it('hides the run progress hint for completed or unknown lifecycle statuses', async () => { + activeCase.value = null as any; + reviewRun.value = { run_no: 'RUN-DONE', items: [] }; + extractionLifecycleProgress.value = { + lifecycle_stage: 'order_review', lifecycle_status: 'completed', + completed_step_codes: [], health_status: 'normal', + }; + let wrapper = await mountView(); + // 关键断言:completed 不渲染轻提示 + expect(wrapper.find('[data-testid="review-run-lifecycle-current-step"]').exists()).toBe(false); + + extractionLifecycleProgress.value = { + lifecycle_stage: 'intake_parse', lifecycle_status: 'weird_state', + completed_step_codes: [], health_status: 'normal', + }; + wrapper = await mountView(); + // 关键断言:未知状态不渲染,更不得回退成“等待启动” + expect(wrapper.find('[data-testid="review-run-lifecycle-current-step"]').exists()).toBe(false); + }); + + it('derives the card status from the run lifecycle and embeds its detail', async () => { + activeCase.value = createActiveCaseFixture(); + activeCase.value.automation = undefined as any; + shippingProcessingProjection.value = null; + reviewRun.value = { run_no: 'RUN-REVIEW', items: [] }; + extractionLifecycleProgress.value = { + lifecycle_stage: 'order_review', lifecycle_status: 'waiting', + blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.review_required', + completed_step_codes: [], health_status: 'normal', + }; + let wrapper = await mountView(); + // 关键断言:review_required → 状态行“待人工处理”;纯重复说明被隐藏 + expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('待人工处理'); + expect(wrapper.find('[data-testid="review-current-task-status-detail"]').exists()).toBe(false); + + // 关键断言:running + document_queued → 状态“系统处理中” + 内嵌说明“正在等待解析任务启动” + extractionLifecycleProgress.value = { + lifecycle_stage: 'intake_parse', lifecycle_status: 'running', + current_step_i18n_key: 'chat.shippingProcessing.progress.step.document_queued', + completed_step_codes: [], health_status: 'normal', + }; + wrapper = await mountView(); + expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('系统处理中'); + expect(wrapper.get('[data-testid="review-current-task-status-detail"]').text()).toContain('正在等待解析任务启动'); }); it('does not claim automatic processing when the run is waiting at a human gate', async () => { @@ -1025,6 +1249,20 @@ describe('ShippingOrderReviewView layout phase 1', () => { }, automation: { status: 'manual_fallback', can_auto_create: false, can_build: true }, }; + // [§2.4 右卡单源] 主動作必须从 A(shippingProcessingProjection.ui_state.primary_action)读。 + shippingProcessingProjection.value = { + workItemType: 'order_task', workItemNo: 'SN-GATE-1', sourceType: 'direct_pdf', + rootOrderTaskNo: 'SN-GATE-1', shippingNoticeNo: 'SN-GATE-1', conversationId: 'conv-1', + submissionNo: 'SUB-GATE-1', intakeNo: 'SNI-GATE-1', status: 'blocked', stage: 'order_review', + progressVersion: 1, lastActivityAt: '2026-08-18T12:13:30Z', + currentGate: { gateCode: 'customer_confirmation', status: 'blocked', nextActionCode: 'confirm_customer' }, + availableActions: ['confirm_customer'], + uiState: { + status: 'waiting_human', stage: 'order_review', blocking_reason: null, + primary_action: { code: 'confirm_customer', i18nKey: 'chat.shippingProcessing.action.confirm_customer' }, + secondary_actions: [], + }, + }; const taskApi = await import('@/features/chat/api/shipping.api'); vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({ task_no: 'SN-GATE-1', status: 'processing', lines: [], events: [], @@ -1045,6 +1283,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { await flushPromises(); // 任意正式 OT Gate 的可执行入口只保留在“当前任务”;重复 Gate 卡不再挂载。 + // [§2.4 右卡单源] 主動作从 A(shippingProcessingProjection.ui_state)读;此用例补 A 的 primary_action。 expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(true); expect(wrapper.find('[data-testid="mock-process-gate"]').exists()).toBe(false); }); @@ -1183,6 +1422,48 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(scrollIntoView).toHaveBeenCalled(); }); + it('shows the existing running status while an accepted RPA recovery waits for fresh projection', async () => { + activeCase.value = { + ...activeCase.value, + status: 'confirmed', has_formal_ot: true, task_missing: false, + confirmed_task_id: 904, confirmed_task_no: 'SN-RPA-RECOVERY-PENDING', + }; + shippingProcessingProjection.value = { + workItemType: 'order_task', workItemNo: 'SN-RPA-RECOVERY-PENDING', + status: 'failed', userStatus: 'failed', stage: 'inventory_fetching', + progressVersion: 7, currentGate: { status: 'blocked_retryable' }, + uiState: { + status: 'failed', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep', + primary_action: { code: 'retry_inventory_preparation', i18n_key: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation' }, + secondary_actions: [], + }, + } as any; + const taskApi = await import('@/features/chat/api/shipping.api'); + vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({ + task_no: 'SN-RPA-RECOVERY-PENDING', status: 'processing', lines: [], events: [], + ui_state: { + actions: { + primary: { + code: 'retry_inventory_preparation', kind: 'current_gate', enabled: true, + dispatch: 'mutation', requires_confirmation: false, + }, + secondary: [], + process_gate: { execution_no: 'EXEC-RPA-RECOVERY-PENDING' }, + }, + process_gate: { execution_no: 'EXEC-RPA-RECOVERY-PENDING' }, summary: {}, steps: [], + }, + } as any); + + const wrapper = await mountView({ lifecycle_stage: 'freight_upload' }); + await flushPromises(); + await wrapper.get('[data-testid="review-current-processing-retry"]').trigger('click'); + await flushPromises(); + + // 复用既有 running/系统处理中文案;轮询新投影到达前不得继续显示旧失败态。 + expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('系统处理中'); + expect(wrapper.get('[data-testid="review-current-task-status"]').text()).not.toContain('自动处理失败'); + }); + it('refreshes the processing projection after field-conflict adjudication refreshes the Case', async () => { activeCase.value = { ...activeCase.value, @@ -1269,9 +1550,10 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false); }); - it('keeps the known Case stage while the authoritative projection is still loading', async () => { - // Case 先到、Projection 后到的过渡窗口:阶段与投影同源(project_stage_for_task), - // 必须直接展示「Excel 生成」,禁止退回自动建单阶段或“正在更新状态”占位。 + it('shows the stage loading placeholder instead of the Case stage while the authoritative projection is still loading', async () => { + // [Task3 单源] Case 先到、Projection 后到的过渡窗口:右卡阶段只由投影供给, + // Case.current_stage 只是降级快照,投影在途时不得先展示(旧「先 Case 后投影」 + // 两跳正是闪烁根因);空阶段由 stageLoading 骨架占位承接。 activeCase.value = { ...activeCase.value, status: 'confirmed', @@ -1288,11 +1570,100 @@ describe('ShippingOrderReviewView layout phase 1', () => { const wrapper = await mountView(); await flushPromises(); - expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('Excel 生成'); + // 关键断言:阶段行显示读取占位,而不是 Case 下发的「Excel 生成」。 + expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('正在获取最新状态'); + expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).not.toContain('Excel 生成'); // 状态列:loading 只抑制动作,不掩盖后端 automation 运行态真值(系统处理中)。 expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('系统处理中'); }); + it('shows the stage placeholder in the first frame before the formal task detail and projection arrive', async () => { + // [Task3 单源] formalTaskDetail 请求在途(formalTaskDetailLoading)且投影未启动的 + // 首帧:右卡 loading=true,阶段行显示 stageLoading 占位,而不是空值「—」或误导文案。 + activeCase.value = { + ...activeCase.value, + status: 'confirmed', + has_formal_ot: true, + task_missing: false, + confirmed_task_id: 92, + confirmed_task_no: 'SN-FIRST-FRAME-1', + }; + shippingProcessingProjection.value = null; + // 挂起任务详情请求,模拟「详情未到 + 投影未到」首帧;测试末尾手动放行并恢复默认 mock。 + vi.mocked(getWorkspaceShippingTask).mockImplementation( + () => new Promise(() => {}) as any, + ); + + const wrapper = await mountView(); + await flushPromises(); + + const card = wrapper.findComponent(ReviewCurrentProcessingCard); + expect(card.props('loading')).toBe(true); + expect(card.props('stageCode')).toBe(''); + expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('正在获取最新状态'); + + // 放行挂起请求并恢复 mock 工厂默认实现,避免跨用例泄漏挂起实现。 + vi.mocked(getWorkspaceShippingTask).mockResolvedValue({ + task_no: 'SN-MOCK', status: 'created', + } as any); + }); + + it('sources the right-card stage only from the processing projection (single source)', async () => { + // [Task3 单源] 下游阶段不再读 activeCase.current_stage / formalTaskDetail.ui_state: + // 投影未就绪 → code='' + loading 占位;投影到达 → code=投影 stage(简报伪代码 + // shippingProcessingProjection={stage:'fulfillment_prep'} 的组件级适配断言)。 + activeCase.value = { + ...activeCase.value, + status: 'confirmed', + has_formal_ot: true, + task_missing: false, + confirmed_task_id: 91, + confirmed_task_no: 'SN-SINGLE-SOURCE-1', + // 故意下发与投影分叉的 Case 阶段:单源后必须被无视。 + current_stage: { code: 'inventory_matching', label_key: 'inventory_matching', inconsistent: false }, + automation: { status: 'running', retryable: false, can_auto_create: false, can_build: true }, + }; + shippingProcessingProjection.value = null; + shippingProcessingLoading.value = true; + + const wrapper = await mountView(); + await flushPromises(); + + // 投影未就绪:空阶段 + loading 占位,而不是 Case 阶段或「步骤未指定」。 + const card = wrapper.findComponent(ReviewCurrentProcessingCard); + expect(card.props('stageCode')).toBe(''); + expect(card.props('loading')).toBe(true); + expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('正在获取最新状态'); + expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).not.toContain('库存匹配'); + + // 投影到达:阶段只由投影提供,Case.current_stage 仍被无视。 + shippingProcessingProjection.value = { + workItemType: 'order_task', workItemNo: 'SN-SINGLE-SOURCE-1', sourceType: 'eml', + status: 'processing', stage: 'fulfillment_prep', stageLabelKey: 'fulfillment_prep', + progressVersion: 1, lastActivityAt: '2026-09-01T00:00:00Z', + currentGate: null, availableActions: [], + sourceSummary: { emailSubject: null, filename: 'po.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: 'PO-1' }, + childOrderTasks: [], + }; + await flushPromises(); + expect(card.props('stageCode')).toBe('fulfillment_prep'); + expect(card.props('stageLabelKey')).toBe('fulfillment_prep'); + expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).not.toContain('库存匹配'); + expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).not.toContain('正在获取最新状态'); + + // 投影 label_key 驱动渲染文案(复用现有 stages 词汇,验证投影→文案管线)。 + shippingProcessingProjection.value = { + workItemType: 'order_task', workItemNo: 'SN-SINGLE-SOURCE-1', sourceType: 'eml', + status: 'processing', stage: 'excel_generating', stageLabelKey: 'excel_generating', + progressVersion: 2, lastActivityAt: '2026-09-01T00:01:00Z', + currentGate: null, availableActions: [], + sourceSummary: { emailSubject: null, filename: 'po.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: 'PO-1' }, + childOrderTasks: [], + }; + await flushPromises(); + expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('Excel 生成'); + }); + it('does not render legacy reparse failure stage as a separate progress source', async () => { reviewProgressContext.value = { item_no: 'WFI-1', @@ -1326,7 +1697,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { }); it('renders main editor + summary rail without chat context toggle', async () => { - const wrapper = await mountView(); + const wrapper = await mountView({ case_no: 'CASE-1' }); const selectedOrder = wrapper.find('[data-testid="review-selected-order-summary"]'); expect(selectedOrder.exists()).toBe(true); expect(selectedOrder.text()).toContain('po.pdf'); @@ -1373,7 +1744,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(navigation.attributes('data-nav-mode')).toBe('tabs'); expect(shell.classes()).toContain('contents'); expect(wrapper.html().indexOf('review-document-navigation')) - .toBeLessThan(wrapper.html().indexOf('review-lifecycle-workbench-header')); + .toBeLessThan(wrapper.html().indexOf('review-workbench-status-region')); }); it('uses a left file list before lifecycle stages for 5+ files', async () => { @@ -1395,7 +1766,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(navigation.attributes('data-nav-mode')).toBe('sidebar'); expect(shell.classes()).toContain('lg:grid-cols-[16rem_minmax(0,1fr)]'); expect(wrapper.html().indexOf('review-document-navigation')) - .toBeLessThan(wrapper.html().indexOf('review-lifecycle-workbench-header')); + .toBeLessThan(wrapper.html().indexOf('review-workbench-status-region')); }); it('replaces a stale lifecycle deep link with the selected file backend current stage', async () => { @@ -1448,6 +1819,53 @@ describe('ShippingOrderReviewView layout phase 1', () => { } }); + it('does not show auto-advance toast when switching to a file already in fulfillment prep', async () => { + const originalQueue = reviewQueue.value; + const originalSelectCase = selectCase.getMockImplementation(); + try { + reviewQueue.value = { + ...reviewQueue.value, + summary: { total: 2, needs_action: 2, processing: 0, completed: 0 }, + items: [ + { + ...reviewQueue.value.items[0], + lifecycle_stage: 'order_review', + lifecycle_entries: [ + { code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }, + ], + }, + { + case_no: 'CASE-2', source_run_no: 'RUN-1', document_id: 2, file_name: 'po-2.pdf', + status: 'draft', issue_count: 0, available_actions: ['validate', 'confirm'], + lifecycle_stage: 'fulfillment_prep', + lifecycle_entries: [ + { code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' }, + { code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }, + ], + }, + ], + }; + selectCase.mockImplementation(async (caseNo: string) => { + activeCase.value = { + ...activeCase.value, + case_no: caseNo, + document_id: caseNo === 'CASE-2' ? 2 : 1, + }; + }); + + const wrapper = await mountView({ lifecycle_stage: 'order_review' }); + messageMocks.success.mockClear(); + await wrapper.get('[data-testid="review-doc-nav-CASE-2"]').trigger('click'); + await flushPromises(); + + expect((wrapper.vm as any).$route.query.lifecycle_stage).toBe('fulfillment_prep'); + expect(messageMocks.success).not.toHaveBeenCalledWith('已自动推进到通知准备'); + } finally { + reviewQueue.value = originalQueue; + selectCase.mockImplementation(originalSelectCase || (() => Promise.resolve(undefined))); + } + }); + it('does not open a lifecycle stage before the backend authorizes lifecycle entries', async () => { // 未收到正式 ui_state.lifecycle_entries 时,前端只能等待实时裁决, // 不能因页面默认值自行开放订单复核或其他生命周期阶段。 @@ -1502,6 +1920,8 @@ describe('ShippingOrderReviewView layout phase 1', () => { // 用户仍停在刚完成的订单复核时,后端推进后自动替换为通知准备。 expect((wrapper.vm as { $route: { query: Record } }).$route.query.lifecycle_stage) .toBe('fulfillment_prep'); + // 自动推进落点一次性提示(T7)。 + expect(messageMocks.success).toHaveBeenCalledWith('已自动推进到通知准备'); } finally { reviewQueue.value = originalQueue; } @@ -1981,9 +2401,9 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成'); }); - it('normalizes Decimal quantity display in the case fallback while formal preparation rows are temporarily empty', async () => { + it('never falls back to case lines for the prep matrix while the task detail is unavailable', async () => { const taskApi = await import('@/features/chat/api/shipping.api'); - // 正式任务详情延迟/失败不能阻塞已由 Case 投影下发的只读库存匹配事实。 + // Case 行回退兜底已删除:正式任务详情失败时不得用 Case line_fulfillment 伪造只读矩阵。 vi.mocked(taskApi.getWorkspaceShippingTask).mockRejectedValue(new Error('detail unavailable')); activeCase.value = { ...activeCase.value, @@ -1993,7 +2413,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { current_stage: { code: 'completed', label_key: 'completed' }, line_fulfillment: { lines: [{ - line_key: 'line-1', reservation_id: 'RSV-FALLBACK', part_number: 'PN-FALLBACK', + draft_line_id: 'line-1', reservation_id: 'RSV-FALLBACK', part_number: 'PN-FALLBACK', required_qty: '8.0', available_qty: '5.0', shortage_qty: '3.0', inventory_source_code: 'DBS_DUB', }], }, @@ -2010,16 +2430,13 @@ describe('ShippingOrderReviewView layout phase 1', () => { const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' }); await flushPromises(); - expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('RSV-FALLBACK'); - expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('PN-FALLBACK'); - const preparationText = wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text(); - expect(preparationText).toContain('3'); - expect(preparationText).not.toContain('3.0'); - expect(wrapper.find('[data-testid="review-fulfillment-prep-workspace"]').exists()).toBe(true); + // 关键断言:Case 行投影不再回填准备工作区,不出现误导性的只读矩阵与波次入口。 + expect(wrapper.find('[data-testid="review-fulfillment-prep-workspace"]').exists()).toBe(false); + expect(wrapper.find('[data-testid="review-fulfillment-prep-confirm-wave"]').exists()).toBe(false); + // 工作面停留在通知准备并给出可重试诊断,不能静默空白或误报结果未生成。 + expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()) + .toContain('chat.shippingOrderReview.lifecycle.prepare.loadFailed'); expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成'); - // 通知准备工作区必须属于五阶段导航的下方主区,不能仍停留在导航之前的状态摘要区。 - expect(wrapper.html().indexOf('review-lifecycle-workbench-header')) - .toBeLessThan(wrapper.html().indexOf('review-fulfillment-prep-workspace')); }); it('renders one row-level inventory workspace with each line source and authorized retry', async () => { @@ -2029,7 +2446,8 @@ describe('ShippingOrderReviewView layout phase 1', () => { status: 'confirmed', confirmed_task_id: 903, confirmed_task_no: 'SN-FROZEN', has_formal_ot: true, line_fulfillment: { lines: [{ - line_key: 'line-frozen', + draft_line_id: 'line-frozen', + snapshot_line_id: 1001, inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'], line_allowed_actions: ['release_inventory_shortage'], @@ -2065,12 +2483,22 @@ describe('ShippingOrderReviewView layout phase 1', () => { preparation: { status: 'blocked', has_match_result: true, frozen_order_lines: [{ - line_key: 'line-frozen', reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6', + snapshot_line_id: 1001, line_no: 1, + reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6', }], lines: [{ - line_key: 'line-frozen', reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', + snapshot_line_id: 1001, line_no: 1, + reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6', available_qty: null, shortage_qty: null, source_code: 'DBS', inventory_file_no: 'SIF-LINE-DBS', status: 'shortage', + draft_line_id: 'line-frozen', + inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'], + line_allowed_actions: ['release_inventory_shortage'], + release_template_fields: [ + { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false }, + { field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true }, + ], + release_required_fields: [{ field_id: '102', display_name: '库位' }], }], artifact: { file_name: null, status: 'not_generated' }, }, @@ -2093,26 +2521,26 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(workspace.text()).toContain('PN-FROZEN'); expect(workspace.text()).toContain('DBS'); expect(wrapper.find('[data-testid="review-fulfillment-frozen-order"]').exists()).toBe(false); - expect(wrapper.get('[data-testid="review-fulfillment-line-download-line-frozen"]').attributes('title')) + expect(wrapper.get('[data-testid="review-fulfillment-line-download-1001"]').attributes('title')) .toBeTruthy(); - expect(wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-line-frozen"]').attributes('title')) + expect(wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-1001"]').attributes('title')) .toBeTruthy(); - expect(wrapper.get('[data-testid="review-fulfillment-line-retry-matching-line-frozen"]').exists()).toBe(true); - expect(wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').exists()).toBe(true); + expect(wrapper.get('[data-testid="review-fulfillment-line-retry-matching-1001"]').exists()).toBe(true); + expect(wrapper.get('[data-testid="review-fulfillment-line-release-1001"]').exists()).toBe(true); expect(workspace.text()).toContain('库存不足'); - await wrapper.get('[data-testid="review-fulfillment-line-download-line-frozen"]').trigger('click'); + await wrapper.get('[data-testid="review-fulfillment-line-download-1001"]').trigger('click'); expect(downloadWorkspaceShippingLineInventoryFileMock).toHaveBeenCalledWith('SN-FROZEN', 'SIF-LINE-DBS'); - await wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-line-frozen"]').trigger('click'); + await wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-1001"]').trigger('click'); expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith( expect.any(Object), expect.objectContaining({ actionCode: 'retry_inventory_preparation', - payload: { line_key: 'line-frozen' }, + payload: { snapshot_line_id: 1001 }, }), ); // Gate 恢复受理后立即启动五阶段轮询,不依赖浏览器手动刷新。 expect(startWorkflowProgressPollingMock).toHaveBeenCalledTimes(1); - await wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').trigger('click'); + await wrapper.get('[data-testid="review-fulfillment-line-release-1001"]').trigger('click'); expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM ID'); expect(wrapper.get('[data-testid="review-release-inventory-dialog"]').text()).toContain('ODM-001'); const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]'); @@ -2120,7 +2548,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { await dialog.find('input').setValue('A-01'); await dialog.get('button.bg-amber-600').trigger('click'); expect(vi.mocked(decideWorkspaceShippingOrderReviewLineFulfillment)).toHaveBeenCalledWith('CASE-1', expect.objectContaining({ - line_key: 'line-frozen', + draft_line_id: 'line-frozen', reason: '客户确认分批发货', release_field_values: { '102': 'A-01' }, })); @@ -2137,7 +2565,8 @@ describe('ShippingOrderReviewView layout phase 1', () => { status: 'confirmed', confirmed_task_id: 903, confirmed_task_no: 'SN-FROZEN', has_formal_ot: true, line_fulfillment: { lines: [{ - line_key: 'line-frozen', + draft_line_id: 'line-frozen', + snapshot_line_id: 1001, inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, line_allowed_actions: ['release_inventory_shortage'], release_template_fields: [ @@ -2167,13 +2596,18 @@ describe('ShippingOrderReviewView layout phase 1', () => { { code: 'freight_upload', state: 'current' }, ] : [{ code: 'fulfillment_prep', state: 'current' }], - stage_context: { upload: {} }, + stage_context: releaseAccepted ? { upload: {} } : { + preparation: { + frozen_order_lines: [{ snapshot_line_id: 1001, line_no: 1, reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6' }], + lines: [{ snapshot_line_id: 1001, line_no: 1, reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-frozen', line_allowed_actions: ['release_inventory_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }], + }, + }, }, } as any)); const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' }); await flushPromises(); - await wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').trigger('click'); + await wrapper.get('[data-testid="review-fulfillment-line-release-1001"]').trigger('click'); const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]'); await dialog.find('textarea').setValue('客户确认分批发货'); await dialog.find('input').setValue('A-01'); @@ -2186,6 +2620,81 @@ describe('ShippingOrderReviewView layout phase 1', () => { .toBe('freight_upload'); }); + it('advances to freight upload when the release job completes asynchronously after polling', async () => { + const taskApi = await import('@/features/chat/api/shipping.api'); + let releaseAccepted = false; + let advanceDone = false; + activeCase.value = { + ...activeCase.value, + status: 'confirmed', confirmed_task_id: 905, confirmed_task_no: 'SN-ASYNC', has_formal_ot: true, + line_fulfillment: { + lines: [{ + draft_line_id: 'line-async', + snapshot_line_id: 1002, + inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, + line_allowed_actions: ['release_inventory_shortage'], + release_template_fields: [ + { field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false }, + { field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true }, + ], + release_required_fields: [{ field_id: '102', display_name: '库位' }], + }], + }, + }; + vi.mocked(taskApi.decideWorkspaceShippingOrderReviewLineFulfillment).mockImplementation(async () => { + releaseAccepted = true; + return { status: 'ok' } as any; + }); + // 异步推进:放行后首个刷新仍停在通知准备(Job 未完成),随后一次(投影 progressVersion 变化触发 + // loadFormalTaskDetail)才抵达货代上传——这正是生产上与"同步放行即推进"用例的差异。 + vi.mocked(taskApi.getWorkspaceShippingTask).mockImplementation(async () => ({ + task_no: 'SN-ASYNC', status: advanceDone ? 'waiting_human' : 'processing', lines: [], events: [], + ui_state: { + process_gate: { execution_no: 'EXEC-ASYNC-LINE', current_blocking_gate: { gate_code: 'manual_upload_handoff', status: 'blocked_manual' } }, + actions: { primary: null, secondary: [] }, + lifecycle_stage: advanceDone ? 'freight_upload' : 'fulfillment_prep', + lifecycle_entries: advanceDone + ? [{ code: 'fulfillment_prep', state: 'available' }, { code: 'freight_upload', state: 'current' }] + : [{ code: 'fulfillment_prep', state: 'current' }], + stage_context: advanceDone ? { upload: {} } : { + preparation: { + frozen_order_lines: [{ snapshot_line_id: 1002, line_no: 1, reservation_id: 'RSV-ASYNC', part_number: 'PN-ASYNC', required_qty: '6' }], + lines: [{ snapshot_line_id: 1002, line_no: 1, reservation_id: 'RSV-ASYNC', part_number: 'PN-ASYNC', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-async', line_allowed_actions: ['release_inventory_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }], + }, + }, + }, + } as any)); + + const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' }); + await flushPromises(); + await wrapper.get('[data-testid="review-fulfillment-line-release-1002"]').trigger('click'); + const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]'); + await dialog.find('textarea').setValue('客户确认单行放行'); + await dialog.find('input').setValue('A-01'); + await dialog.get('button.bg-amber-600').trigger('click'); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + + // 异步 Job 尚未落地:仍停留在通知准备。 + expect((wrapper.vm as { $route: { query: Record } }).$route.query.lifecycle_stage) + .toBe('fulfillment_prep'); + + // 模拟后端异步推进落地:处理投影 progressVersion 变化 → 触发 loadFormalTaskDetail → 抵达货代上传。 + advanceDone = true; + shippingProcessingProjection.value = { + progressVersion: 42, + userStatus: 'waiting_human', + status: 'waiting_human', + uiState: { lifecycleStage: 'freight_upload', lifecycleEntries: [{ code: 'freight_upload', state: 'current' }] }, + }; + await flushPromises(); + await new Promise((resolve) => setTimeout(resolve, 0)); + await nextTick(); + + expect((wrapper.vm as { $route: { query: Record } }).$route.query.lifecycle_stage) + .toBe('freight_upload'); + }); + it('keeps notification preparation when the user navigates there while a shortage release is advancing', async () => { const taskApi = await import('@/features/chat/api/shipping.api'); let releaseAccepted = false; @@ -2195,7 +2704,8 @@ describe('ShippingOrderReviewView layout phase 1', () => { status: 'confirmed', confirmed_task_id: 904, confirmed_task_no: 'SN-MANUAL', has_formal_ot: true, line_fulfillment: { lines: [{ - line_key: 'line-manual', + draft_line_id: 'line-manual', + snapshot_line_id: 1003, inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, line_allowed_actions: ['release_inventory_shortage'], release_template_fields: [ @@ -2215,7 +2725,12 @@ describe('ShippingOrderReviewView layout phase 1', () => { lifecycle_entries: releaseAccepted ? [{ code: 'fulfillment_prep', state: 'available' }, { code: 'freight_upload', state: 'current' }] : [{ code: 'fulfillment_prep', state: 'current' }], - stage_context: { upload: {} }, + stage_context: releaseAccepted ? { upload: {} } : { + preparation: { + frozen_order_lines: [{ snapshot_line_id: 1003, line_no: 1, reservation_id: 'RSV-MANUAL', part_number: 'PN-MANUAL', required_qty: '6' }], + lines: [{ snapshot_line_id: 1003, line_no: 1, reservation_id: 'RSV-MANUAL', part_number: 'PN-MANUAL', required_qty: '6', shortage_qty: '3', source_code: 'DBS', status: 'shortage', draft_line_id: 'line-manual', line_allowed_actions: ['release_inventory_shortage'], release_required_fields: [{ field_id: '102', display_name: '库位' }] }], + }, + }, }, }); vi.mocked(taskApi.decideWorkspaceShippingOrderReviewLineFulfillment).mockImplementation(async () => { @@ -2228,7 +2743,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { }); const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' }); - await wrapper.get('[data-testid="review-fulfillment-line-release-line-manual"]').trigger('click'); + await wrapper.get('[data-testid="review-fulfillment-line-release-1003"]').trigger('click'); const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]'); await dialog.find('textarea').setValue('客户确认分批发货'); await dialog.find('input').setValue('A-01'); @@ -2252,7 +2767,8 @@ describe('ShippingOrderReviewView layout phase 1', () => { status: 'confirmed', confirmed_task_id: 904, confirmed_task_no: 'SN-READY', has_formal_ot: true, line_fulfillment: { lines: [{ - line_key: 'line-ready', line_status: 'pending_decision', can_fulfill_complete_line: true, + draft_line_id: 'line-ready', snapshot_line_id: 1004, + line_status: 'pending_decision', can_fulfill_complete_line: true, inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, }], }, @@ -2271,10 +2787,12 @@ describe('ShippingOrderReviewView layout phase 1', () => { lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }], stage_context: { preparation: { - status: 'ready', has_match_result: true, + status: 'ready', has_match_result: true, editable: true, + frozen_order_lines: [{ snapshot_line_id: 1004, line_no: 1, reservation_id: 'RSV-READY', part_number: 'PN-READY', required_qty: '20' }], lines: [{ - line_key: 'line-ready', reservation_id: 'RSV-READY', part_number: 'PN-READY', + snapshot_line_id: 1004, line_no: 1, reservation_id: 'RSV-READY', part_number: 'PN-READY', required_qty: '20', available_qty: '65', shortage_qty: '0', source_code: 'DBS', status: 'matched', + draft_line_id: 'line-ready', line_status: 'pending_decision', can_fulfill_complete_line: true, }], }, }, @@ -2288,12 +2806,141 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(workspace.get('[data-testid="review-fulfillment-prep-confirm-wave"]').exists()).toBe(true); expect(wrapper.findComponent({ name: 'ReviewFulfillmentDecisionPanel' }).exists()).toBe(false); - await workspace.get('[data-testid="review-fulfillment-line-select-line-ready"]').setValue(true); + await workspace.get('[data-testid="review-fulfillment-line-select-1004"]').setValue(true); + // [REGRESSION] wave 确认后后端入队异步推进(生成 Excel → OT 进入货代上传); + // 前端必须因此启动投影轮询,否则自动推进落地后五阶段导航/右栏不会自动刷新(反复出现的 bug)。 + vi.mocked(waveWorkspaceShippingOrderReviewLineFulfillment).mockResolvedValue({ + status: 'ok', + auto_progress_started: true, + wave_no: 1, + task_no: 'OT-WAVE-1', + } as any); await workspace.get('[data-testid="review-fulfillment-prep-confirm-wave"]').trigger('click'); + // 点击处理器是 async 且未被 trigger 等待;需 flush 微任务让 confirmPreparationWave 走到 + // auto_progress_started 分支(backend 已入队异步推进 → 必须启动投影轮询)之后再断言。 + await flushPromises(); expect(vi.mocked(waveWorkspaceShippingOrderReviewLineFulfillment)).toHaveBeenCalledWith('CASE-1', expect.objectContaining({ - line_keys: ['line-ready'], + snapshot_line_ids: [1004], expected_draft_version: 1, })); + expect(startWorkflowProgressPollingMock).toHaveBeenCalled(); + }); + + it('renders the editable prep matrix from ui_state alone while activeCase stays absent', async () => { + const taskApi = await import('@/features/chat/api/shipping.api'); + const originalQueue = reviewQueue.value; + try { + // 关键前置:case 级 formalEditable 关闭,可编辑性只能来自 ui_state.preparation.editable。 + reviewEditable.value = false; + reviewFormalEditable.value = false; + // activeCase 缺省(下游懒加载):复核 Case 不拉取,任务身份由 work-item 投影(导航项)提供。 + activeCase.value = null as any; + requestedCaseNo.value = 'CASE-1'; + reviewQueue.value = { + ...originalQueue, + items: [{ + ...originalQueue.items[0], + confirmed_task_no: 'SN-READY', + has_formal_ot: true, + } as any], + }; + shippingProcessingProjection.value = { + uiState: { + lifecycleStage: 'fulfillment_prep', + lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }], + primary_action: null, + secondary_actions: [], + }, + }; + vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({ + task_no: 'SN-READY', status: 'processing', lines: [], events: [], + ui_state: { + lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }], + stage_context: { + preparation: { + status: 'ready', has_match_result: true, editable: true, + frozen_order_lines: [{ snapshot_line_id: 1004, line_no: 1, reservation_id: 'RSV-READY', part_number: 'PN-READY', required_qty: '20' }], + lines: [{ + snapshot_line_id: 1004, line_no: 1, reservation_id: 'RSV-READY', part_number: 'PN-READY', + required_qty: '20', available_qty: '65', shortage_qty: '0', source_code: 'DBS', status: 'matched', + draft_line_id: 'line-ready', line_status: 'pending_decision', can_fulfill_complete_line: true, + }], + }, + }, + }, + } as any); + + const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' }); + await flushPromises(); + + // 进入 Prep:ui_state 单源就绪即渲染完整可编辑矩阵;无需二次 activeCase。 + expect(wrapper.find('[data-testid="review-fulfillment-prep-confirm-wave"]').exists()).toBe(true); + // activeCase 缺省(下游懒加载)不影响可编辑性与行矩阵。 + expect(getWorkspaceShippingOrderReviewCase).not.toHaveBeenCalled(); + } finally { + reviewQueue.value = originalQueue; + // 恢复任务详情 mock 默认值,避免 SN-READY 详情泄漏到后续用例。 + vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({ + task_no: 'SN-MOCK', + status: 'created', + } as any); + } + }); + + it('does not start workflow polling when the wave schedules no async auto-progress', async () => { + const taskApi = await import('@/features/chat/api/shipping.api'); + reviewEditable.value = false; + reviewFormalEditable.value = true; + activeCase.value = { + ...activeCase.value, + status: 'confirmed', confirmed_task_id: 904, confirmed_task_no: 'SN-READY', has_formal_ot: true, + line_fulfillment: { + lines: [{ + draft_line_id: 'line-ready', snapshot_line_id: 1004, + line_status: 'pending_decision', can_fulfill_complete_line: true, + inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' }, + }], + }, + }; + shippingProcessingProjection.value = { + uiState: { + lifecycleStage: 'fulfillment_prep', + lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }], + primary_action: null, + secondary_actions: [], + }, + }; + vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({ + task_no: 'SN-READY', status: 'processing', lines: [], events: [], + ui_state: { + lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }], + stage_context: { + preparation: { + status: 'ready', has_match_result: true, editable: true, + frozen_order_lines: [{ snapshot_line_id: 1004, line_no: 1, reservation_id: 'RSV-READY', part_number: 'PN-READY', required_qty: '20' }], + lines: [{ + snapshot_line_id: 1004, line_no: 1, reservation_id: 'RSV-READY', part_number: 'PN-READY', + required_qty: '20', available_qty: '65', shortage_qty: '0', source_code: 'DBS', status: 'matched', + draft_line_id: 'line-ready', line_status: 'pending_decision', can_fulfill_complete_line: true, + }], + }, + }, + }, + } as any); + + const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' }); + await flushPromises(); + const workspace = wrapper.get('[data-testid="review-fulfillment-prep-workspace"]'); + await workspace.get('[data-testid="review-fulfillment-line-select-1004"]').setValue(true); + startWorkflowProgressPollingMock.mockClear(); + vi.mocked(waveWorkspaceShippingOrderReviewLineFulfillment).mockResolvedValue({ + status: 'ok', + auto_progress_started: false, + wave_no: 1, + } as any); + await workspace.get('[data-testid="review-fulfillment-prep-confirm-wave"]').trigger('click'); + await flushPromises(); + expect(startWorkflowProgressPollingMock).not.toHaveBeenCalled(); }); it('keeps intake parse on the standard workbench and removes the inventory return row', async () => { @@ -2398,7 +3045,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { await flushPromises(); // 关键断言:A 的迟到详情不能覆盖 B 的 lifecycle_entries。 - expect(wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]').findAll('button')[1].attributes('disabled')).toBe(''); + expect(wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]').findAll('button')[1].attributes('disabled')).toBeUndefined(); expect(wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]').findAll('button')[1].attributes('disabled')).toBeDefined(); }); @@ -2534,14 +3181,14 @@ describe('ShippingOrderReviewView layout phase 1', () => { draft: { ...activeCase.value.draft, lines: [ - { line_key: 'LINE-1', values: { 'fld-line-no': { value: '10' }, 'fld-part-number': { value: 'PN-ONE' }, 'fld-quantity': { value: '4' } }, machine_fields: [] }, - { line_key: 'LINE-2', values: { 'fld-line-no': { value: '20' }, 'fld-part-number': { value: 'PN-TWO' }, 'fld-quantity': { value: '7' } }, machine_fields: [] }, + { draft_line_id: 'LINE-1', values: { 'fld-line-no': { value: '10' }, 'fld-part-number': { value: 'PN-ONE' }, 'fld-quantity': { value: '4' } }, machine_fields: [] }, + { draft_line_id: 'LINE-2', values: { 'fld-line-no': { value: '20' }, 'fld-part-number': { value: 'PN-TWO' }, 'fld-quantity': { value: '7' } }, machine_fields: [] }, ], }, line_fulfillment: { lines: [ - { line_key: 'LINE-1', reservation_id: 'RSV-1', line_status: 'fulfilled' }, - { line_key: 'LINE-2', reservation_id: 'RSV-2', line_status: 'fulfilled' }, + { draft_line_id: 'LINE-1', reservation_id: 'RSV-1', line_status: 'fulfilled' }, + { draft_line_id: 'LINE-2', reservation_id: 'RSV-2', line_status: 'fulfilled' }, ], }, }; @@ -2860,6 +3507,57 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(wrapper.find('[data-testid="review-current-task-next-step-section"]').exists()).toBe(false); }); + it('keeps upload-complete evidence on the loading placeholder until freight groups arrive', async () => { + activeCase.value = { + ...activeCase.value, + status: 'confirmed', confirmed_task_no: 'SN-UPCOMPLETE-LOADING', confirmed_task_id: 25, has_formal_ot: true, + }; + const taskApi = await import('@/features/chat/api/shipping.api'); + vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({ + task_no: 'SN-UPCOMPLETE-LOADING', status: 'completed', upload_status: 'uploaded', lines: [], events: [], + ui_state: { + lifecycle_stage: 'upload_complete', + lifecycle_entries: [ + { code: 'intake_parse', state: 'available' }, + { code: 'order_review', state: 'available' }, + { code: 'fulfillment_prep', state: 'available' }, + { code: 'freight_upload', state: 'available' }, + { code: 'upload_complete', state: 'current' }, + ], + actions: { primary: null, secondary: [] }, summary: {}, steps: [], + }, + } as any); + // 分组请求保持挂起:模拟直入通知完成时 freightNoticeGroups 尚未就绪的首屏窗口。 + let resolveGroups: (value: unknown) => void = () => {}; + vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockImplementation( + () => new Promise((resolve) => { resolveGroups = resolve; }) as any, + ); + + const wrapper = await mountView({ lifecycle_stage: 'upload_complete' }); + await flushPromises(); + + const evidence = wrapper.get('[data-testid="review-lifecycle-upload-complete"]'); + // 直入上传完成(freightNoticeGroups 未就绪):段内显示 loading,不闪「0 已上传/空」。 + expect(evidence.text()).toContain('正在加载发货通知…'); + expect(evidence.text()).not.toContain('本批已上传'); + expect(evidence.text()).not.toContain('本批暂无已上传的发货通知。'); + expect(wrapper.find('[data-testid="review-upload-complete-groups"]').exists()).toBe(false); + expect(wrapper.find('[data-testid="review-upload-complete-toolbar"]').exists()).toBe(false); + + // 分组到达后:loading 让位,batchCount 工具栏与已上传列表恢复渲染。 + resolveGroups({ + po_number: 'PO-UPCOMPLETE', + items: [{ + business_no: 'WYC-UPCOMPLETE-1', po_number: 'PO-UPCOMPLETE', upload_status: 'uploaded', + upload_mode: 'manual', export_file_name: 'WYC-UPCOMPLETE-1.xlsx', lines: [], + }], + }); + await flushPromises(); + expect(wrapper.get('[data-testid="review-upload-complete-toolbar"]').text()).toContain('本批已上传 1 张发货通知'); + expect(wrapper.find('[data-testid="review-upload-complete-groups"]').exists()).toBe(true); + expect(wrapper.text()).toContain('WYC-UPCOMPLETE-1'); + }); + it('allows inspecting a completed order-review stage without allowing edits', async () => { activeCase.value = { ...activeCase.value, @@ -2985,12 +3683,12 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect(wrapper.findAll('[data-testid="review-freight-upload-more"]')).toHaveLength(0); }); - it('does not place internal inventory hint fields in the primary line table', async () => { + it('keeps the inventory source hint as a routing check column in the primary line table', async () => { const wrapper = await mountView(); - const inputs = wrapper.findAll('[data-testid="review-line-field-input"]'); - // 关键断言:主表只保留业务核对字段,库存源线索由行级履约详情承载。 - expect(wrapper.text()).not.toContain('库存源线索'); - expect(inputs).toHaveLength(0); + const headers = wrapper.find('[data-testid="review-lines-scroll"]').findAll('th').map((item) => item.text()); + // 关键断言:库存源线索作为路由核对列始终保留在主表,便于用户核对各库存源;无值时仍保留列头。 + expect(headers).toContain('库存源线索'); + expect(wrapper.find('[data-testid="review-line-inventory-source"]').exists()).toBe(true); }); it('ignores a stale line change after the current draft has accepted the value', async () => { @@ -3006,7 +3704,7 @@ describe('ShippingOrderReviewView layout phase 1', () => { draft: { ...activeCase.value.draft, lines: [{ - line_key: 'LINE-1', + draft_line_id: 'LINE-1', values: { 'fld-part': { value: 'D4-AR1200072A1', source: 'manual' } }, machine_fields: [], }], @@ -3326,7 +4024,9 @@ describe('ShippingOrderReviewView audit and progress recovery', () => { const wrapper = await mountView(); await flushPromises(); // 关键断言:failed 态主卡/底栏露出 STP 重试(非确认后 auto_progress)。 - expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('创建正式订单'); + // [契约 §1.1「当前门禁 —」] 建单前无 processing projection:阶段为空渲染中性 + // 占位文案(stageLoading),不再由 Case automation 兜底推导「创建正式订单」阶段,也禁止落「—」。 + expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('正在获取最新状态'); expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('自动处理失败'); const railBtn = wrapper.find('[data-testid="review-current-processing-retry"]'); const footerBtn = wrapper.find('[data-testid="review-retry-stp-auto-create"]'); diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.vue b/frontend/src/features/chat/views/ShippingOrderReviewView.vue index 3152e89e..81d1f0a4 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.vue +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.vue @@ -200,6 +200,7 @@ const { isFieldEditable, loadReviewCase, showWorkflowProgress, + workflowProgressPolling, startWorkflowProgressPolling, stopWorkflowProgressPolling, stopReparseCaseRefreshPolling, @@ -675,6 +676,32 @@ const showObjectRetryOnFooter = computed(() => ( * 补任一字段。否则“检查已通过”与旧 Gate 的“待裁决”会被拼到同一张卡上。 */ const currentTaskUiState = computed(() => shippingProcessingProjection.value?.uiState ?? null); +/** + * Gate/RPA 动作已受理但新投影尚未落位时的本地过渡态。 + * 仅用于避免上一帧 failed 在轮询窗口继续冒充当前状态;真实终态仍以后端 + * shippingProcessingProjection 为准,不新增业务状态或动作权限。 + */ +const recoveryProjectionPending = ref(false); +const recoveryProjectionBaselineVersion = ref(null); + +watch( + shippingProcessingProjection, + (projection) => { + if (!recoveryProjectionPending.value || !projection) return; + const version = Number(projection.progressVersion || 0); + const baseline = recoveryProjectionBaselineVersion.value; + const status = String(projection.userStatus || projection.status || '').trim().toLowerCase(); + const gateStatus = String(projection.currentGate?.status || '').trim().toLowerCase(); + const hasFreshVersion = baseline == null || version > baseline; + const isActive = ['running', 'processing', 'automating', 'queued'].includes(status) + || ['pending', 'queued', 'running', 'waiting_external'].includes(gateStatus); + const isSettled = ['completed', 'cancelled', 'waiting_human', 'retryable'].includes(status); + if (hasFreshVersion || isActive || isSettled) { + recoveryProjectionPending.value = false; + recoveryProjectionBaselineVersion.value = null; + } + }, +); /** * 正式 OT 已存在且文件切换或统一处理投影读取中时,Case Gate 只是降级快照,不能先暴露可执行动作。 * Projection 返回后才拥有动作裁决权;非切换错误路径仍保留原有的 Case Gate 恢复能力。 @@ -698,22 +725,14 @@ const NOTICE_SCOPED_ACTION_CODES = new Set([ 'regenerate_excel_artifact', ]); -function isNoticeScopedAction(action: ShippingUnifiedAction | null | undefined): boolean { - return NOTICE_SCOPED_ACTION_CODES.has(String(action?.code || '').trim()); -} - /** - * 将正式任务详情的已启用 Gate 动作适配为右侧当前任务卡的展示契约。 - * - * 正式 OT 的写授权只能来自 ``ui_state.actions``;统一处理 Projection 仅承载 - * 进度、阶段和阻断事实,不能以历史动作码替代正式 Gate 动作。 + * 判断动作是否属于 Notice 作用域(应在通知组而非任务卡展示)。 + * 核心逻辑:只读 code,兼容 ShippingUnifiedAction 与 Projection 的 primary/secondary 动作形状。 + * @param action - 任意带 code 的动作对象 + * @returns 是否为 Notice 作用域动作 */ -function toCurrentTaskAction(action: ShippingUnifiedAction | null | undefined) { - if (!action?.enabled || !String(action.code || '').trim() || isNoticeScopedAction(action)) return null; - return { - code: String(action.code).trim(), - i18nKey: `workspace.shippingNotice.processGate.actionCodes.${action.code}`, - }; +function isNoticeScopedAction(action: { code?: string | null } | null | undefined): boolean { + return NOTICE_SCOPED_ACTION_CODES.has(String(action?.code || '').trim()); } const formalTaskActions = computed(() => { @@ -725,15 +744,23 @@ const formalTaskActions = computed(() => { /** 行级库存选源动作:只在表格逐行处理,禁止作为任务级按钮出现在右侧"当前任务"卡(避免与表格打勾重复)。 */ const LINE_SCOPE_INVENTORY_ACTIONS = new Set([ 'override_line_inventory_source', - 'select_line_inventory_source', ]); const currentTaskPrimaryAction = computed(() => { if (formalTaskProjectionPending.value) return null; if (hasFormalOt.value) { - const first = toCurrentTaskAction(formalTaskActions.value[0]); - if (!first || LINE_SCOPE_INVENTORY_ACTIONS.has(first.code)) return null; - return first; + // [§2.4 单源] 正式 OT 的主动作只从 A(shippingProcessingProjection.ui_state.primary_action)读, + // 不再读 B(formalTaskDetail.ui_state.actions —— 之后仅作工作面事实)。后端 flatten 已保证 + // A==C==B(动作码同源),故该改动纯收敛、不改变已授权按钮。 + // 注意:A 的 i18nKey 可能是 chat 域(如 chat.shippingProcessing.action.*),而右卡 + // ReviewCurrentProcessingCard 只解析 workspace.shippingNotice.processGate.actionCodes.*, + // 故必须统一映射到卡片域,否则按钮会因 businessActionLabel 为空而 fail-closed 消失。 + const action = currentTaskUiState.value?.primary_action ?? null; + if (!action?.code || LINE_SCOPE_INVENTORY_ACTIONS.has(action.code)) return null; + return { + code: String(action.code).trim(), + i18nKey: `workspace.shippingNotice.processGate.actionCodes.${action.code}`, + }; } const projection = shippingProcessingProjection.value; if (projection) { @@ -759,6 +786,7 @@ const currentTaskPrimaryAction = computed(() => { }); const currentTaskUserStatus = computed(() => { if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') return 'completed'; + if (recoveryProjectionPending.value) return 'running'; // 已确认 OT 且权威投影在途时,先消费后端 automation 运行态(queued/running → running, // failed/manual_fallback → failed),状态行即显真实值,不应退回「正在获取最新状态」骨架; // authority 仍以右侧投影为准,投影到达后覆盖。 @@ -778,6 +806,7 @@ const currentTaskUserStatus = computed(() => { * 仅当原因码在隐藏白名单且映射结果==当前状态(纯重复)才隐藏,其余诊断信息一律保留。 */ const currentTaskStatusDetail = computed<{ text: string } | null>(() => { + if (recoveryProjectionPending.value) return null; if (['completed', 'cancelled'].includes(String(currentTaskUserStatus.value || ''))) return null; const message = resolveExtractionActivityMessage(lifecycleProgressForView.value, { t, te }); if (!message) return null; @@ -788,12 +817,14 @@ const currentTaskStatusDetail = computed<{ text: string } | null>(() => { }); const currentTaskBlockingReason = computed(() => { if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') return null; + if (recoveryProjectionPending.value) return null; if (formalTaskProjectionPending.value) return null; return currentTaskUiState.value?.blocking_reason ?? null; }); /** 当前 Gate 状态必须与右栏动作同源,均来自统一处理 Projection。 */ const currentTaskGateStatus = computed(() => { if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') return null; + if (recoveryProjectionPending.value) return 'running'; if (formalTaskProjectionPending.value) return null; const projection = shippingProcessingProjection.value; if (projection?.currentGate?.status) return projection.currentGate.status; @@ -809,15 +840,20 @@ const currentTaskRetryable = computed(() => ( const currentTaskRecoveryActions = computed(() => { if (formalTaskProjectionPending.value) return []; if (hasFormalOt.value) { - // [STAGE_CAPABILITY] 门禁恢复动作 + 阶段能力(任务级、已启用)按 code 去重。 - // 能力统一在右侧"当前任务"卡展示,主工作台不再重复放按钮。这样在整库存阶段 - // (含非原生 gate,如 inventory_field_mapping 死局)右侧卡始终有"重抓/重读/改源"。 - // 行级库存选源动作(override/select_line_inventory_source)只在表格逐行处理, - // 禁止作为任务级按钮出现在右侧卡,避免与表格"打勾"重复。 - const gateRecovery = formalTaskActions.value.slice(1) - .filter((action) => String(action.code || '').trim() !== 'download_excel' && !isNoticeScopedAction(action)) - .map(toCurrentTaskAction) - .filter((action): action is NonNullable => Boolean(action)); + // [§2.4 单源] 恢复动作从 A(shippingProcessingProjection.ui_state.secondary_actions)读, + // 不再从 B(formalTaskDetail.ui_state.actions)slice。能力仍取任务级 + // stage_context.preparation.capabilities(B 工作面事实,§2 保留)。动作码同源(A==C==B), + // 该改动纯收敛。行级库存选源动作只在表格逐行处理,禁止作为任务级按钮出现在右侧卡。 + const gateRecovery = (currentTaskUiState.value?.secondary_actions || []) + .filter((action) => action.enabled + && String(action.code || '').trim() !== 'download_excel' + && !isNoticeScopedAction(action)) + .map((action) => ({ + code: String(action.code || '').trim(), + // 统一右卡 domain:actionCodes.(见 currentTaskPrimaryAction 注;A 的 i18nKey 可能是 chat 域)。 + i18nKey: `workspace.shippingNotice.processGate.actionCodes.${String(action.code || '').trim()}`, + })) + .filter((action): action is { code: string; i18nKey: string } => Boolean(action.code)); const capabilityActions = (formalPreparationContext.value?.capabilities || []) .filter((cap) => cap.scope === 'task' && cap.enabled && String(cap.action_code || '').trim()) .map((cap) => ({ @@ -1640,6 +1676,10 @@ async function retryFormalUploadRpa(taskNo: string) { * 一次性自动推进许可,待后端生命周期投影确认后才更新深链。 */ function handleGateRecoveryAccepted(options: { releaseAutoAdvance?: boolean } = {}) { + if (hasFormalOt.value) { + recoveryProjectionBaselineVersion.value = shippingProcessingProjection.value?.progressVersion ?? null; + recoveryProjectionPending.value = true; + } const caseNo = String(activeCase.value?.case_no || '').trim(); if (options.releaseAutoAdvance && caseNo) { // 放行前可能是用户手动进入通知准备;该历史意图不能阻止本次放行后的自动推进。 @@ -2634,14 +2674,17 @@ async function retryFormalPreparationLine( /** * 人工上传登记是后端 Gate 的受控写动作;仅进入「货代上传」工作面不构成授权。 - * 任务详情与批次中心共用 ui_state.actions,避免页面按上传状态或生命周期自行放行。 + * [§2 单源] 授权从 A(shippingProcessingProjection.ui_state)读 —— §2.5 差异① 已归一,A 的 + * secondary_actions/primary_action 透传原始 mark_manual_uploaded 码(与 B/C 一致的写契约码)。 + * 避免页面按上传状态或生命周期自行放行。 */ const manualUploadRegistrationAuthorized = computed(() => { - const actions = formalTaskDetail.value?.ui_state?.actions; - const candidates = [actions?.primary, ...(actions?.secondary || [])]; - return candidates.some((action) => ( - action?.code === 'mark_manual_uploaded' && action.enabled === true - )); + const uiState = currentTaskUiState.value; + // primary_action 无 enabled 字段,出现即视为已授权;secondary_actions 必须 enabled === true。 + if (uiState?.primary_action?.code === 'mark_manual_uploaded') return true; + return (uiState?.secondary_actions || []).some( + (action) => action.code === 'mark_manual_uploaded' && action.enabled === true, + ); }); /** 直接在订单复核页打开人工上传登记,避免依赖仅在 formal_task 模式挂载的 TaskTodoPanel ref。 */ @@ -2838,6 +2881,42 @@ watch( { immediate: true }, ); +// ============================================================================ +// 正式 OT 自动推进的「阶段无关」投影轮询(问题1修复的正解) +// ============================================================================ +// 背景:shippingProcessingProjection 是整工作台唯一的轻量实时投影(progressVersion 变化会 +// 触发 [REFRESH_ON_CHANGE] 重新加载正式任务详情 → 表格数字/门禁/阶段自动更新)。但它的刷新 +// 完全依赖 startWorkflowProgressPolling(useShippingProcessingWorkItem 已关 continuousPolling), +// 而历史上只有「货代上传」watching 会持续推进该轮询;通知准备阶段的 RPA 取数→匹配→满足性 +// 异步推进期间轮询被停,导致「可用数量/缺口/匹配状态」停在初值,需手动刷新。 +// 方案:新增一条与业务阶段解耦的推进监控——只要存在正式 OT、且其投影仍处于「自动推进中」 +// (非终态/非等待人工/非中断),就保持轮询;落到终态/等待人工即停止。与货代上传 watcher 互不耦合, +// prep 阶段不再寄生在 freight 逻辑上。 +const OT_PROGRESS_ACTIVE_STATUSES = new Set(['running', 'processing', 'automating', 'queued']); +const OT_PROGRESS_IDLE_STATUSES = new Set(['waiting_human', 'interrupted', 'failed', 'completed', 'cancelled']); +function isOtProgressing(projection: typeof shippingProcessingProjection.value): boolean { + const status = String( + projection?.uiState?.status + || projection?.userStatus + || projection?.status + || '', + ).trim().toLowerCase(); + return OT_PROGRESS_ACTIVE_STATUSES.has(status) && !OT_PROGRESS_IDLE_STATUSES.has(status); +} +watch( + [() => hasFormalOt.value, authoritativeOrderTaskNo, shippingProcessingProjection], + ([hasOt, otNo, projection]) => { + // 仅当正式 OT 存在且其投影处于自动推进态时保持轮询;否则停止,避免空转。 + if (!hasOt || !otNo || !projection || !isOtProgressing(projection)) { + if (workflowProgressPolling.value) stopWorkflowProgressPolling(); + return; + } + // 已在轮询则不动,避免每次投影刷新都重建 interval(否则 2.5s 定时器被反复重置)。 + if (!workflowProgressPolling.value) startWorkflowProgressPolling(); + }, + { immediate: true }, +); + function toggleFreightNoticeSelection(businessNo: string, checked: boolean) { selectedFreightBusinessNos.value = checked ? Array.from(new Set([...selectedFreightBusinessNos.value, businessNo])) diff --git a/frontend/src/features/shipping-process-gates/api/process-gates.api.ts b/frontend/src/features/shipping-process-gates/api/process-gates.api.ts index 7fd4a3f9..9a3c1083 100644 --- a/frontend/src/features/shipping-process-gates/api/process-gates.api.ts +++ b/frontend/src/features/shipping-process-gates/api/process-gates.api.ts @@ -49,7 +49,7 @@ export interface AdminProcessExecutionListPage { page_size: number; } -export interface AdminProcessExecutionDetail extends ShippingProcessGateUserSummary { +export interface AdminProcessExecutionDetail extends Omit { current_gate?: Record | null; current_blocking_gate?: ShippingProcessGateUserSummary['current_blocking_gate']; gates?: Array>; diff --git a/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts index 6ec04ab4..34baf759 100644 --- a/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts +++ b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.spec.ts @@ -54,6 +54,24 @@ function summary() { } as never; } +/** 非原生 Gate 摘要:阶段能力不在 recovery_targets / allowed_actions 内(Task 5 根因)。 */ +function capabilitySummary() { + return { + execution_no: 'EXEC-1', + status: 'blocked', + current_blocking_gate: { + gate_code: 'inventory_field_mapping', + evaluation_version: 5, + status: 'blocked', + }, + primary_action: null, + allowed_actions: [], + recovery_targets: [], + action_presentation: [], + next_action_code: null, + } as never; +} + function mountComposable() { let exposed!: ReturnType; const app = createApp(defineComponent({ @@ -92,4 +110,62 @@ describe('useShippingProcessGateRecovery', () => { app.unmount(); }); + + it('dispatches an enabled stage capability past the server guard when stageCapabilityBypass is true', async () => { + // 断言:能力动作不在 recovery_targets / allowed_actions 内(非原生 Gate 的根因场景), + // 开启 stageCapabilityBypass 后仍应 POST 到 request_gate_action,而非返回 noop。 + const { exposed, app } = mountComposable(); + + const result = await exposed.submitPrimaryAction(capabilitySummary(), { + actionCode: 'override_line_inventory_source', + stageCapabilityBypass: true, + }); + + expect(result.outcome).toBe('submitted'); + expect(postActionMock).toHaveBeenCalledTimes(1); + expect(getExecutionMock).not.toHaveBeenCalled(); + expect(postActionMock).toHaveBeenCalledWith( + 'EXEC-1', + 'inventory_field_mapping', + expect.objectContaining({ action_code: 'override_line_inventory_source' }), + ); + + app.unmount(); + }); + + it('uses current_gate when the user projection omits current_blocking_gate', async () => { + const { exposed, app } = mountComposable(); + const result = await exposed.submitPrimaryAction({ + execution_no: 'EXEC-1', + status: 'processing', + current_gate: { gate_code: 'inventory_preparation', evaluation_version: 7, status: 'running' }, + allowed_actions: [], + recovery_targets: [], + } as never, { + actionCode: 'retry_inventory_preparation', + stageCapabilityBypass: true, + }); + expect(result.outcome).toBe('submitted'); + expect(postActionMock).toHaveBeenCalledWith( + 'EXEC-1', + 'inventory_preparation', + expect.objectContaining({ action_code: 'retry_inventory_preparation' }), + ); + app.unmount(); + }); + + it('keeps a non-capability action not in recovery_targets / allowed_actions guarded as noop', async () => { + // 断言:普通门禁动作不在服务端恢复集合内时,仍被 serverRecoveryAction 守卫拦截 + // 返回 noop,符合「普通动作必须保持服务端校验」的不变式。 + const { exposed, app } = mountComposable(); + + const result = await exposed.submitPrimaryAction(capabilitySummary(), { + actionCode: 'retry_freight_upload_rpa', + }); + + expect(result.outcome).toBe('noop'); + expect(postActionMock).not.toHaveBeenCalled(); + + app.unmount(); + }); }); diff --git a/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts index a2246bcb..a19527c5 100644 --- a/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts +++ b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts @@ -85,62 +85,82 @@ export function useShippingProcessGateRecovery() { navigationContext?: ProcessGateNavigationContext; /** 仅允许使用服务端 recovery_targets 下发的动作码覆盖主动作。 */ actionCode?: ShippingProcessGateActionCode | string; + /** + * 阶段能力强制绕过:跳过服务端 recovery_targets/allowed_actions 校验与展示精确匹配, + * 直接把请求动作码作为 mutation POST 到 request_gate_action;后端按阶段能力豁免 + * (Task 4)做授权并执行 execute_stage_capability。仅由已按 enabled 裁决的调用方 + * (如 prep 工作台)用于正式阶段能力;普通门禁动作必须保持服务端校验。 + */ + stageCapabilityBypass?: boolean; }, ): Promise { - const gate = summary.current_blocking_gate; + // 正式 OT 的系统等待态不会投影 current_blocking_gate,但仍保留 + // current_gate 供通知准备阶段能力(改源/重抓)提交到当前 Execution。 + // 普通人工恢复优先使用 current_blocking_gate,避免把非当前 Gate 当成待办。 + const gate = summary.current_blocking_gate || summary.current_gate; const requestedAction = String(options?.actionCode || '').trim(); + const stageCapabilityBypass = Boolean(options?.stageCapabilityBypass); const serverRecoveryAction = (summary.recovery_targets || []) .find((target) => String(target.action_code || '').trim() === requestedAction) ?.action_code || (summary.allowed_actions || []).find((code) => String(code).trim() === requestedAction); - if (requestedAction && !serverRecoveryAction) { + if (requestedAction && !stageCapabilityBypass && !serverRecoveryAction) { msg.warning(t('workspace.shippingNotice.processGate.noAction')); return { outcome: 'noop' }; } - const actionCode = (serverRecoveryAction || summary.next_action_code || gate?.next_action_code || '') as ShippingProcessGateActionCode | ''; + // 阶段能力不在 recovery_targets/allowed_actions 内;绕过时以调用方请求动作码为准。 + const actionCode = ( + stageCapabilityBypass && requestedAction + ? requestedAction + : (serverRecoveryAction || summary.next_action_code || gate?.next_action_code || '') + ) as ShippingProcessGateActionCode | ''; if (!summary.execution_no || !gate?.gate_code || !actionCode) { msg.warning(t('workspace.shippingNotice.processGate.noAction')); return { outcome: 'noop' }; } - const action = resolveActionPresentation(summary, String(actionCode)); - if (!action) { - msg.warning(t('workspace.shippingNotice.processGate.noAction')); - return { outcome: 'noop' }; - } - - if (String(action.dispatch || '').trim() === 'dialog') { - const uiHandler = String(action.ui_handler || '').trim(); - if (!uiHandler) { + // 阶段能力是纯 mutation POST:调用方已按 enabled 裁决,且其动作码不在门禁 + // action_presentation 内,故跳过展示精确匹配与 dialog/导航分支,由后端授权。 + if (!stageCapabilityBypass) { + const action = resolveActionPresentation(summary, String(actionCode)); + if (!action) { msg.warning(t('workspace.shippingNotice.processGate.noAction')); - return { outcome: 'failed' }; + return { outcome: 'noop' }; } - return { - outcome: 'dialog', - uiHandler, - taskNo: String(summary.navigation?.task_no || summary.task_no || '').trim().toUpperCase(), - }; - } - if (isProcessGateNavigationAction(action)) { - const route = buildProcessGateNavigationRoute( - summary, - action, - options?.navigationContext || {}, - ); - if (!route) { - msg.warning(t('workspace.shippingNotice.processGate.navigationMissing')); - return { outcome: 'failed' }; + if (String(action.dispatch || '').trim() === 'dialog') { + const uiHandler = String(action.ui_handler || '').trim(); + if (!uiHandler) { + msg.warning(t('workspace.shippingNotice.processGate.noAction')); + return { outcome: 'failed' }; + } + return { + outcome: 'dialog', + uiHandler, + taskNo: String(summary.navigation?.task_no || summary.task_no || '').trim().toUpperCase(), + }; } - busy.value = true; - try { - await router.push(route); - return { outcome: 'navigated' }; - } catch { - msg.warning(t('workspace.shippingNotice.actions.failed')); - return { outcome: 'failed' }; - } finally { - busy.value = false; + + if (isProcessGateNavigationAction(action)) { + const route = buildProcessGateNavigationRoute( + summary, + action, + options?.navigationContext || {}, + ); + if (!route) { + msg.warning(t('workspace.shippingNotice.processGate.navigationMissing')); + return { outcome: 'failed' }; + } + busy.value = true; + try { + await router.push(route); + return { outcome: 'navigated' }; + } catch { + msg.warning(t('workspace.shippingNotice.actions.failed')); + return { outcome: 'failed' }; + } finally { + busy.value = false; + } } }