Files
syops/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts
T
hugo 1b6483a4ea feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
2026-08-20 20:23:10 +08:00

2581 lines
111 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* features/chat/views/ShippingOrderReviewView.spec.ts
* 用途:锁定复核工作台布局与统一重试契约。
* 依赖:vitest、@vue/test-utils、vue-i18n、vue-router mocks。
* 逻辑:标准模式无对话上下文、无常驻 PDF 列;底栏无「确认并创建任务」;
* 正式 OT / STP 对象级重试走 /retry 或 STP retry;敏感面板审计失败不打开。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { computed, nextTick, ref } from 'vue';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { createRouter, createMemoryHistory } from 'vue-router';
import ShippingOrderReviewView from './ShippingOrderReviewView.vue';
import ReviewFieldConflictPanel from '../components/shipping-review/ReviewFieldConflictPanel.vue';
import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import {
auditWorkspaceShippingOrderReviewEligibilityDetails,
auditWorkspaceShippingOrderReviewVersionHistory,
getWorkspaceShippingTask,
decideWorkspaceShippingOrderReviewLineFulfillment,
retryWorkspaceShippingOrderStpAutoCreate,
retryWorkspaceShippingTask,
retryWorkspaceShippingTaskLine,
} from '@/features/chat/api/shipping.api';
const { downloadWorkspaceShippingLineInventoryFileMock } = vi.hoisted(() => ({
downloadWorkspaceShippingLineInventoryFileMock: vi.fn().mockResolvedValue(undefined),
}));
const { downloadWorkspaceShippingExcelFileMock } = vi.hoisted(() => ({
downloadWorkspaceShippingExcelFileMock: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('@/features/chat/shipping/shippingDownload', () => ({
downloadWorkspaceShippingLineInventoryFile: downloadWorkspaceShippingLineInventoryFileMock,
}));
vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({
downloadWorkspaceShippingExcelFile: downloadWorkspaceShippingExcelFileMock,
}));
const focusSuggestionField = vi.fn();
const load = vi.fn().mockResolvedValue(undefined);
const selectCase = vi.fn().mockResolvedValue(undefined);
const ensureIntakeParseContextLoaded = vi.fn().mockResolvedValue(true);
/** 确认建单 mock:用例可改写返回值以断言 confirm_outcome / auto_progress 解析。 */
const confirmMock = vi.fn();
const reloadLatestDraftMock = vi.fn().mockResolvedValue(undefined);
const refreshShippingProcessingMock = vi.fn().mockResolvedValue(undefined);
const patchLineMock = vi.fn().mockResolvedValue(undefined);
const { submitProcessGatePrimaryActionMock } = vi.hoisted(() => ({
submitProcessGatePrimaryActionMock: vi.fn().mockResolvedValue({ outcome: 'submitted' }),
}));
const { postFormalGateActionMock } = vi.hoisted(() => ({
postFormalGateActionMock: vi.fn().mockResolvedValue({}),
}));
const messageMocks = vi.hoisted(() => ({
info: vi.fn(),
warning: vi.fn(),
error: vi.fn(),
success: vi.fn(),
}));
/** 同步 stub 异步证据抽屉(覆盖相对路径与 @ 别名,供 defineAsyncComponent 解析)。 */
const evidenceDrawerStub = vi.hoisted(() => ({
name: 'ReviewDocumentEvidenceDrawer',
props: ['open', 'pinned', 'expanded', 'docked', 'floatSide'],
emits: ['close', 'toggle-pin', 'toggle-expand', 'toggle-dock', 'toggle-side'],
template: `
<aside
v-if="open"
data-testid="review-document-evidence-drawer"
:data-docked="docked ? 'true' : 'false'"
:data-presentation="docked ? 'docked' : 'floating'"
>
<button data-testid="review-evidence-toggle-dock" @click="$emit('toggle-dock')">dock</button>
<button data-testid="review-evidence-toggle-expand" @click="$emit('toggle-expand')">expand</button>
</aside>
`,
}));
const reviewRun = ref({
run_no: 'RUN-1',
items: [
{
case_no: 'CASE-1',
document_id: 1,
file_name: 'po.pdf',
status: 'draft',
issue_count: 0,
available_actions: ['validate', 'confirm'],
},
],
});
const reviewQueue = ref({
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'],
}],
});
const workItem = ref<Record<string, any> | null>(null);
const reviewProgressContext = ref<Record<string, any> | null>(null);
/** 与 activeCase 同源共享,供断言 Progress 优先阶段源。 */
const shippingProcessingProjection = ref<Record<string, any> | null>(null);
/** 正式任务投影的请求中状态;用于覆盖 Case 先到、Projection 后到的过渡窗口。 */
const shippingProcessingLoading = ref(false);
const intakeParseContext = ref<Record<string, any> | null>(null);
/** 每个用例必须从独立的 Case 图快照开始,避免嵌套 schema/draft 被浅拷贝污染。 */
function createActiveCaseFixture() {
return {
case_no: 'CASE-1',
document_id: 1,
status: 'draft',
available_actions: ['validate', 'confirm', 'mark_non_order', 'reparse'],
schema: {
schema_version_id: 14,
fields: [
{
field_id: 'fld-po',
field_code: 'customer_po_number',
display_name: '客户 PO',
scope: 'header',
value_type: 'string',
required: true,
options: [],
},
{
field_id: 'fld-inventory-source-hint',
field_code: 'inventory_source_hint',
display_name: '库存源线索',
scope: 'line',
value_type: 'string',
required: false,
options: [],
},
],
},
draft: {
draft_version: 1,
header_values: {
values: { 'fld-po': { value: 'PO-1', source: 'machine' } },
machine_fields: [{ field_id: 'fld-po', observations: [{ value: 'PO-1' }] }],
},
lines: [{
line_key: 'LINE-1',
values: {},
machine_fields: [],
}],
issues: [],
},
process_gate: null,
profile_match: { available: false, visibility: 'admin_only', candidates: [] },
automation: { status: 'idle', can_auto_create: false, can_build: true },
};
}
const activeCase = ref<Record<string, any>>(createActiveCaseFixture());
vi.mock('@/features/chat/api/shipping.api', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/features/chat/api/shipping.api')>();
return {
...actual,
auditWorkspaceShippingOrderReviewVersionHistory: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
auditWorkspaceShippingOrderReviewEligibilityDetails: vi.fn().mockResolvedValue({ audited: true, case_no: 'CASE-1' }),
retryWorkspaceShippingTask: vi.fn().mockResolvedValue({ status: 'ok' }),
retryWorkspaceShippingTaskLine: vi.fn().mockResolvedValue({ status: 'ok' }),
decideWorkspaceShippingOrderReviewLineFulfillment: vi.fn().mockResolvedValue({ status: 'ok' }),
retryWorkspaceShippingOrderStpAutoCreate: vi.fn().mockResolvedValue({
status: 'queued',
job_id: 901,
case: null,
}),
getWorkspaceShippingTask: vi.fn().mockResolvedValue({
task_no: 'SN-MOCK',
status: 'created',
}),
};
});
/** mock 工厂句柄:vi.mock 提升后由下方 createReviewComposableMock 赋值。 */
const reviewComposableMockApi = vi.hoisted(() => ({
create: null as null | (() => Record<string, unknown>),
}));
vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
REVIEW_BUILD_ELIGIBILITY_BLOCKED: 'SHIPPING.REVIEW_BUILD_ELIGIBILITY_BLOCKED',
useShippingOrderReview: () => {
if (!reviewComposableMockApi.create) {
throw new Error('createReviewComposableMock not initialized');
}
return reviewComposableMockApi.create();
},
}));
/**
* 统一维护 useShippingOrderReview mock 契约,避免新增返回字段时漏改。
*/
function createReviewComposableMock() {
return {
reviewRun,
reviewQueue,
activeCase,
caseProjectionVersion: ref(1),
caseLoadingContext: ref(null),
reviewProgressContext,
workItem,
authoritativeOrderTaskNo: computed(() => {
const no = String(reviewProgressContext.value?.user_task_no || '').trim();
if (!no || reviewProgressContext.value?.user_task_authoritative === false) return null;
return no;
}),
versions: ref([]),
statusMessage: ref(null),
draftConflict: ref(null),
draftConflictDiffLines: ref([]),
buildEligibility: ref({ can_build: true, issues: [], lines: [] }),
canConfirmBuild: computed(() => true),
routingRecoveryLines: ref([]),
isViewingHistoricalVersion: computed(() => false),
isReadOnly: computed(() => false),
loading: ref(false),
loadFailed: ref(false),
caseSwitchLoading: ref(false),
caseSwitchFailed: ref(false),
requestedCaseNo: ref(null),
saving: ref(false),
validationInProgress: ref(false),
saveFailed: ref(false),
versionsLoading: ref(false),
evidence: ref([
{
field_id: 'fld-po',
page_no: 1,
quote: 'PO-1',
bbox: { x0: 0.1, y0: 0.1, x1: 0.2, y1: 0.2 },
},
]),
llmSuggestions: ref([]),
suggestionLoading: ref(false),
focusedFieldId: ref(null),
focusedLineKey: ref(null),
previewUrl: ref('blob:mock-pdf'),
previewLoading: ref(false),
previewLoadFailed: ref(false),
ensurePreviewLoaded: vi.fn().mockResolvedValue(true),
ensureEmailEvidenceLoaded: vi.fn().mockResolvedValue(true),
ensureIntakeParseContextLoaded,
emailPreview: ref(null),
intakeParseContext,
intakeParseLoading: ref(false),
intakeParseLoadFailed: ref(false),
load,
selectCase,
refreshWorkItemContext: vi.fn(),
openCurrentVersion: vi.fn(),
reloadLatestDraft: reloadLatestDraftMock,
toggleConflictDiff: vi.fn(),
patchHeader: vi.fn(),
patchLine: patchLineMock,
addLine: vi.fn(),
copyLine: vi.fn(),
deleteLine: vi.fn(),
validate: vi.fn(),
setLineInventoryCandidates: vi.fn(),
rerouteInventoryRouting: vi.fn(),
adoptInventoryRoutingSuggestion: vi.fn(),
keepManualInventoryRouting: vi.fn(),
confirm: confirmMock,
createManualDraft: vi.fn(),
markNonOrder: vi.fn(),
markQualityIssue: vi.fn(),
reparseDocument: vi.fn(),
focusSuggestionField,
setEvidenceDrawerFocus: vi.fn(),
clearEvidenceDrawerFocus: vi.fn(),
requestSuggestion: vi.fn(),
decideSuggestion: vi.fn(),
editable: computed(() => true),
formalEditable: computed(() => false),
canEditFormalFields: computed(() => false),
isFieldEditable: () => true,
isWorkItemClosed: computed(() => false),
showWorkflowProgress: computed(() => false),
workflowProgressPolling: computed(() => false),
shippingProcessingProjection,
shippingProcessingLoading,
shippingProcessingError: ref(null),
refreshShippingProcessing: refreshShippingProcessingMock,
};
}
reviewComposableMockApi.create = createReviewComposableMock;
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => messageMocks,
}));
vi.mock('@/features/shipping-process-gates/composables/useShippingProcessGateRecovery', () => ({
useShippingProcessGateRecovery: () => ({
busy: ref(false),
submitPrimaryAction: submitProcessGatePrimaryActionMock,
}),
}));
vi.mock('@/features/shipping-process-gates/api/process-gates.api', () => ({
postWorkspaceProcessGateAction: (...args: unknown[]) => postFormalGateActionMock(...args),
}));
vi.mock('../components/shipping-review/ReviewDocumentPreview.vue', () => ({
default: {
name: 'ReviewDocumentPreview',
template: '<div data-testid="mock-pdf-preview" />',
},
}));
vi.mock('../components/shipping-review/ReviewDocumentEvidenceDrawer.vue', () => ({
default: evidenceDrawerStub,
}));
vi.mock('@/features/chat/components/shipping-review/ReviewDocumentEvidenceDrawer.vue', () => ({
default: evidenceDrawerStub,
}));
vi.mock('../components/shipping-review/ReviewBuildEligibilitySummary.vue', () => ({
default: {
name: 'ReviewBuildEligibilitySummary',
props: ['eligibility', 'exceptionCount', 'exceptionOrdinal'],
emits: ['open-details', 'navigate-exception'],
template:
'<div data-testid="mock-eligibility-summary">'
+ '<button data-testid="review-open-eligibility-details" @click="$emit(\'open-details\')">详情</button>'
+ '<div v-if="exceptionCount" data-testid="review-exception-nav">'
+ '<button data-testid="review-exception-prev" @click="$emit(\'navigate-exception\', -1)">上一</button>'
+ '<button data-testid="review-exception-next" @click="$emit(\'navigate-exception\', 1)">下一</button>'
+ '</div>'
+ '</div>',
},
}));
vi.mock('../components/shipping-review/ReviewBuildEligibilityDetailsDrawer.vue', () => ({
default: {
name: 'ReviewBuildEligibilityDetailsDrawer',
props: ['open'],
template: '<div v-if="open" data-testid="mock-eligibility-details" />',
},
}));
vi.mock('../components/shipping-review/ReviewInventoryIssueList.vue', () => ({
default: {
name: 'ReviewInventoryIssueList',
template: '<div data-testid="mock-inventory-issues" />',
},
}));
vi.mock('../components/shipping-review/ReviewInventoryCandidatesPanel.vue', () => ({
default: {
name: 'ReviewInventoryCandidatesPanel',
template: '<div data-testid="mock-inventory" />',
},
}));
vi.mock('@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue', () => ({
default: {
name: 'ProcessGateRecoveryCard',
props: ['showActions'],
template: '<div data-testid="mock-process-gate" :data-actions="showActions === false ? \'hidden\' : \'shown\'" />',
},
}));
vi.mock('../components/shipping-review/ReviewLlmSuggestionDrawer.vue', () => ({
default: {
name: 'ReviewLlmSuggestionDrawer',
template: '<div data-testid="mock-llm-drawer" />',
},
}));
vi.mock('../components/shipping-review/ReviewVersionHistoryDrawer.vue', () => ({
default: {
name: 'ReviewVersionHistoryDrawer',
props: ['open'],
template: '<div v-if="open" data-testid="mock-versions-drawer" />',
},
}));
/**
* 挂载复核工作台视图并注入最小 Chat 上下文。
*/
async function mountView(query: Record<string, string> = {}) {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
title: '订单人工复核',
run: '识别批次 {runNo}',
workItemHeader: '{itemNo} {version}',
backToSession: '返回',
readOnly: '只读',
loading: '加载中',
unavailable: '不可用',
retryLoad: '重试',
caseSwitchLoading: '正在加载当前 PDF…',
caseSwitchFailed: '当前 PDF 加载失败,可重试',
caseSwitchRetry: '重试',
documentNavigation: 'PDF 导航',
documents: 'PDF',
unnamedDocument: '未命名',
caseStatus: '{status} · {count}',
caseStatuses: { draft: '草稿', unknown: '未知' },
previewTitle: 'PDF 预览',
previewLoading: '加载 PDF',
previewUnavailable: '无预览',
locateSource: '定位 {field}',
locateUnavailableHint: '无可靠坐标,点击查看诊断',
locateCandidateHint: '候选位置',
dblclickLocateHint: '双击定位',
exceptionNav: {
prev: '上一异常',
next: '下一异常',
prevHint: '上一异常',
nextHint: '下一异常',
},
issues: '问题',
highlightQuality: {
verified: '已验证',
candidate: '候选',
unavailable: '无坐标',
invalid: '无效',
},
orderFields: '订单字段',
schemaVersion: 'V{version}',
lines: '明细',
line: '行 {index}',
noLines: '无明细',
noMachineOrder: '无订单',
createManualDraft: '手工建草稿',
markNonOrder: '非订单',
markQualityIssue: '质量异常',
reparse: '重新识别',
saveNow: '保存并校验',
saveOrderAndValidate: '保存订单并校验',
confirmCreate: '确认并建单',
restoreMachine: '恢复',
moreFields: '更多 {count}',
moreLineFields: '更多列 {count}',
collapseFields: '收起',
addLine: '新增行',
copyLine: '复制行',
deleteLine: '删除行',
emptyValue: '空',
valueSources: { machine: '系统' },
primaryBlockTitle: '阻断',
primaryBlockParty: '{party}',
versionHistory: { title: '版本历史' },
auditTrail: { open: '查看审计' },
customerResolution: {
title: '客户确认',
unresolved: '未确认',
confirmed: '已确认',
select: '选择客户',
search: '搜索',
empty: '无候选',
confirm: '确认',
cancel: '取消',
},
workbench: {
mode: {
standard: '标准复核',
evidence: '证据核对',
inventory: '库存处理',
reparse: '重新识别',
confirm_progress: '建单进度',
},
moreStatus: '更多状态',
enterInventory: '查看库存问题',
returnStandard: '返回标准复核',
openPdf: '打开 PDF',
closePdf: '关闭 PDF',
pinPdf: '退出后保留',
unpinPdf: '退出后关闭',
pinPdfHint: '退出证据模式后仍保留 PDF 打开(不会固定在视口)',
unpinPdfHint: '退出证据模式时关闭 PDF',
openVersionHistory: '版本历史',
auditFailed: '审计记录失败,敏感面板未打开,请重试',
summaryRail: '摘要',
actionSuccess: '已完成',
resultNotReady: '结果未就绪',
},
evidenceAt: 'PDF 第 {page} 页',
evidenceNoHighlight: '无坐标',
evidenceDrawer: {
title: '证据核对',
pageUnknown: '页码未知',
prevEvidence: '上一证据',
nextEvidence: '下一证据',
field: '字段:{field}',
currentValue: '当前值',
machineValue: '机器值',
source: '来源',
},
llmSuggestion: { request: '请求 AI' },
restoreMachine: '恢复机器值',
saving: '保存中',
saved: '已保存',
saveFailed: '失败',
versionConflict: { badge: '冲突' },
statusBanner: { unknown: '未知' },
autoProgress: {
status: { unknown: '', needs_retry: '待重试', needs_human: '需要人工处理' },
result: '{status}',
checkpoint: '{checkpoint}',
viewTask: '返回对话查看进度',
returnToChat: '返回对话查看进度',
retry: '重试自动推进',
retryObject: '重试',
retrySuccess: '已重新触发',
retryStp: '重试自动推进',
retryStpSuccess: '已重新入队自动建单',
},
conversationRetry: {
title: '对话重试结果',
retried: '已重试',
skipped: '已跳过',
failed: '失败',
closeAndRefresh: '关闭并刷新',
},
currentProcessing: {
title: '当前处理状态',
status: '状态',
formalOt: '正式 OT',
waitingStart: '等待系统启动',
taskMissing: '正式任务关联异常',
taskMissingHint: '正式任务关联异常,请联系管理员',
stateInconsistent: '状态同步中',
statusRunning: '系统处理中',
statusFailedRetryable: '失败可重试',
statusCompleted: '已完成',
statusIdle: '待机',
statusTaskMissing: '关联异常',
stages: {
waiting_system_start: '等待系统启动',
waiting_to_start: '等待系统启动',
order_creating: '等待系统启动',
inventory_matching: '库存匹配',
},
},
automation: {
waitingPreOt: '等待自动建单',
waitingPostOt: '等待系统启动自动推进',
},
buildEligibility: {
confirmBlocked: '不可建单',
autoGateWaitingHint: '资格已达标,等待系统自动建单',
autoGateRunningHint: '系统正在自动推进',
},
fulfillmentDecision: {
actions: '操作',
availableQty: '可用',
shortage: '缺口',
},
lineOps: {
retry: '重试',
moreActions: '更多操作',
inventorySource: '库存源',
},
workflowProgress: {
automatingFooterHint: '系统自动推进中',
},
confirmSuccess: '{taskNo}',
confirmAutoProgress: '{taskNo}',
confirmProgressFailed: '已创建任务 {taskNo},但自动推进失败,请重试推进',
jumpToCurrentVersion: '跳转',
currentVersionUnavailable: '不可用',
lifecycle: {
navigation: '订单生命周期阶段',
current: '当前可处理',
prerequisite: '请先完成当前阶段',
stages: {
intake_parse: '接收解析',
order_review: '订单复核',
fulfillment_prep: '通知准备',
upload_complete: '通知完成',
},
prepare: {
title: '通知准备',
subtitle: '库存候选、匹配异常和通知文件生成均在此阶段处理。',
frozenOrder: '冻结订单',
inventorySource: '库存源',
downloadInventory: '下载库存文件',
retryInventory: '重新获取库存',
releaseShortage: '库存缺口放行',
shortage: '库存不足',
pending: '库存匹配或通知文件尚未生成。',
},
},
},
shippingProcessing: {
stage: {
order_creating: '创建正式订单',
inventory_matching: '库存匹配',
},
stageLabel: {
waiting_system_start: '等待系统启动',
},
},
},
errors: { generic: '错误' },
},
},
});
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/chat/:agentId', name: 'Chat', component: { template: '<div />' } },
{
path: '/workspace/shipping-tasks/:taskNo',
name: 'workspace-shipping-tasks',
component: { template: '<div />' },
},
],
});
await router.push({
path: '/chat/agent-1',
query: { mode: 'order-review', run_no: 'RUN-1', ...query },
});
await router.isReady();
const wrapper = mount(ShippingOrderReviewView, {
global: {
plugins: [i18n, router],
provide: {
[CHAT_PAGE_KEY as symbol]: {
conversationId: 'conv-1',
messages: [],
},
},
stubs: {
ReviewActionConfirmDialog: {
name: 'ReviewActionConfirmDialog',
props: ['action', 'modelValue', 'confirmLoading'],
emits: ['confirm', 'cancel', 'update:modelValue'],
template:
'<div data-testid="review-action-confirm-dialog">'
+ '<button data-testid="review-action-confirm-submit" @click="$emit(\'confirm\', { reasonCode: \'ok\' })">确认</button>'
+ '</div>',
},
ReviewLineNoOverrideDialog: true,
ReviewDocumentEvidenceDrawer: evidenceDrawerStub,
},
},
});
await flushPromises();
return wrapper;
}
/** 将共享 Case fixture 恢复为可编辑草稿,避免跨用例污染确认恢复态。 */
function resetActiveCaseFixture() {
activeCase.value = createActiveCaseFixture();
shippingProcessingProjection.value = null;
shippingProcessingLoading.value = false;
intakeParseContext.value = null;
}
describe('ShippingOrderReviewView layout phase 1', () => {
beforeEach(() => {
vi.clearAllMocks();
ensureIntakeParseContextLoaded.mockResolvedValue(true);
resetActiveCaseFixture();
workItem.value = null;
reviewProgressContext.value = null;
});
it('uses the current-task card as the only Gate action entry for every formal-OT Gate', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 88,
confirmed_task_no: 'SN-GATE-1',
process_gate: {
execution_no: 'EXEC-GATE-1',
status: 'blocked',
owner_type: 'human',
technical_auto_only: false,
current_blocking_gate: { gate_code: 'customer_confirmation', status: 'blocked' },
primary_action: {
code: 'confirm_customer',
label_key: 'chat.shippingNotice.processGate.actionCodes.confirm_customer',
kind: 'current_gate',
dispatch: 'mutation',
},
},
automation: { status: 'manual_fallback', can_auto_create: false, can_build: true },
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-GATE-1', status: 'processing', lines: [], events: [],
ui_state: {
actions: {
primary: {
code: 'confirm_customer', kind: 'current_gate', enabled: true,
dispatch: 'navigation', ui_handler: 'customer_resolution',
requires_confirmation: false,
},
secondary: [],
},
process_gate: { execution_no: 'EXEC-GATE-1' }, summary: {}, steps: [],
},
} as any);
const wrapper = await mountView();
await flushPromises();
// 任意正式 OT Gate 的可执行入口只保留在“当前任务”;重复 Gate 卡不再挂载。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="mock-process-gate"]').exists()).toBe(false);
});
it('submits a server-authorized Gate action from the current-task card without an action-code alias', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', has_formal_ot: true, task_missing: false,
confirmed_task_id: 98, confirmed_task_no: 'SN-EXCEL-1',
};
shippingProcessingProjection.value = {
workItemType: 'order_task', workItemNo: 'SN-EXCEL-1', sourceType: 'direct_pdf',
rootOrderTaskNo: 'SN-EXCEL-1', shippingNoticeNo: 'SN-EXCEL-1', conversationId: 'conv-1',
submissionNo: 'SUB-EXCEL-1', intakeNo: 'SNI-EXCEL-1', status: 'blocked', stage: 'excel_generating',
progressVersion: 1, lastActivityAt: '2026-08-18T12:13:30Z', currentGate: {
gateCode: 'artifact_generation', status: 'blocked_retryable', nextActionCode: 'regenerate_excel_artifact',
},
processGate: {
execution_no: 'EXEC-EXCEL-1', status: 'blocked_retryable', current_gate_code: 'artifact_generation',
next_action_code: 'regenerate_excel_artifact', allowed_actions: ['regenerate_excel_artifact'],
current_blocking_gate: { gate_code: 'artifact_generation', status: 'blocked_retryable', evaluation_version: 8 },
},
availableActions: ['regenerate_excel_artifact'],
sourceSummary: { emailSubject: null, filename: 'po.xlsx', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
childOrderTasks: [],
uiState: {
status: 'retryable', stage: 'excel_generating', blocking_reason: null,
primary_action: { code: 'regenerate_excel_artifact', i18nKey: 'chat.shippingProcessing.action.regenerate_excel' },
secondary_actions: [],
},
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-EXCEL-1', status: 'processing', lines: [], events: [],
ui_state: {
actions: {
primary: {
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
dispatch: 'mutation',
target_surface: 'fulfillment_prep', target_anchor: 'excel_artifact',
requires_confirmation: false,
},
secondary: [],
},
process_gate: {
execution_no: 'EXEC-EXCEL-1',
current_blocking_gate: {
gate_code: 'artifact_generation', evaluation_version: 8,
},
},
summary: {}, steps: [],
},
} as any);
const wrapper = await mountView();
await flushPromises();
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
await flushPromises();
// 关键断言:旧 Projection 的 regenerate_excel 不可执行;正式任务的原始动作码
// 只委托统一 Gate 执行器,由其按后端版本与授权再次校验。
expect(submitProcessGatePrimaryActionMock).toHaveBeenCalledWith(
expect.objectContaining({
execution_no: 'EXEC-EXCEL-1',
current_blocking_gate: expect.objectContaining({ gate_code: 'artifact_generation' }),
}),
{ actionCode: 'regenerate_excel_artifact' },
);
expect(postFormalGateActionMock).not.toHaveBeenCalled();
});
it('does not submit an action merely because its code has a Gate-like prefix', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', has_formal_ot: true, task_missing: false,
confirmed_task_id: 99, confirmed_task_no: 'SN-UNAUTHORIZED-1',
// 旧 Case 投影仍可能带上 Gate;不能让它以动作码前缀绕过实时 Projection。
process_gate: {
execution_no: 'EXEC-STALE-CASE-1', status: 'blocked_retryable', owner_type: 'human', technical_auto_only: false,
current_blocking_gate: { gate_code: 'artifact_generation', status: 'blocked_retryable' },
},
};
shippingProcessingProjection.value = {
workItemType: 'order_task', workItemNo: 'SN-UNAUTHORIZED-1', sourceType: 'direct_pdf',
rootOrderTaskNo: 'SN-UNAUTHORIZED-1', shippingNoticeNo: 'SN-UNAUTHORIZED-1', conversationId: 'conv-1',
submissionNo: 'SUB-UNAUTHORIZED-1', intakeNo: 'SNI-UNAUTHORIZED-1', status: 'blocked', stage: 'excel_generating',
progressVersion: 1, lastActivityAt: '2026-08-18T12:13:30Z', currentGate: {
gateCode: 'artifact_generation', status: 'blocked_retryable', nextActionCode: 'confirm_customer',
},
processGate: {
execution_no: 'EXEC-UNAUTHORIZED-1', status: 'blocked_retryable', current_gate_code: 'artifact_generation',
next_action_code: 'confirm_customer', allowed_actions: ['confirm_customer'],
current_blocking_gate: { gate_code: 'artifact_generation', status: 'blocked_retryable', evaluation_version: 9 },
},
availableActions: ['confirm_customer'],
sourceSummary: { emailSubject: null, filename: 'po.xlsx', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
childOrderTasks: [],
uiState: {
status: 'retryable', stage: 'excel_generating', blocking_reason: null,
primary_action: { code: 'regenerate_excel_artifact', i18nKey: 'chat.shippingProcessing.action.regenerate_excel' },
secondary_actions: [],
},
};
const wrapper = await mountView();
await flushPromises();
// 旧 Projection 的 action 不可替代正式任务动作;详情无同码授权时右侧不展示写按钮。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
});
it('routes the right-rail field-conflict action through the registered focus executor', async () => {
activeCase.value = {
...activeCase.value,
process_gate: {
execution_no: 'EXEC-CONFLICT-1',
status: 'blocked',
owner_type: 'human',
technical_auto_only: false,
current_blocking_gate: { gate_code: 'field_conflict_resolution', status: 'blocked' },
primary_action: {
code: 'resolve_field_conflicts',
label_key: 'workspace.shippingNotice.processGate.actionCodes.resolve_field_conflicts',
},
},
field_conflicts: [{
conflict_key: '0:part_number', field_code: 'part_number', line_index: 0,
reason: 'field_conflict', options: [],
}],
automation: { status: 'manual_fallback', can_auto_create: false, can_build: false },
};
const scrollIntoView = vi.fn();
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
configurable: true,
value: scrollIntoView,
});
const wrapper = await mountView();
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
await flushPromises();
// 关键断言:右栏上下文入口必须复用字段冲突聚焦执行器,不能落入未知动作提示。
expect(messageMocks.info).not.toHaveBeenCalled();
expect(scrollIntoView).toHaveBeenCalled();
});
it('refreshes the processing projection after field-conflict adjudication refreshes the Case', async () => {
activeCase.value = {
...activeCase.value,
field_conflicts: [{
conflict_key: '0:part_number', field_code: 'part_number', line_index: 0,
reason: 'field_conflict', options: [],
}],
process_gate: {
execution_no: 'EXEC-CONFLICT-REFRESH', status: 'blocked', owner_type: 'human', technical_auto_only: false,
current_blocking_gate: { gate_code: 'field_conflict_resolution', status: 'blocked' },
primary_action: { code: 'resolve_field_conflicts', label_key: 'workspace.shippingNotice.processGate.actionCodes.resolve_field_conflicts' },
},
};
shippingProcessingProjection.value = {
uiState: {
primary_action: { code: 'resolve_field_conflicts' },
secondary_actions: [],
},
};
const wrapper = await mountView();
reloadLatestDraftMock.mockClear();
refreshShippingProcessingMock.mockClear();
wrapper.findComponent(ReviewFieldConflictPanel).vm.$emit('refreshed');
await flushPromises();
// 字段裁决会同时改变 Case 与正式 Gate;两份读取模型必须一起刷新,避免右栏继续展示旧动作。
expect(reloadLatestDraftMock).toHaveBeenCalledTimes(1);
expect(refreshShippingProcessingMock).toHaveBeenCalledTimes(1);
});
it('does not revive a Case Gate action when the formal OT ui_state explicitly has no action', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', has_formal_ot: true, task_missing: false,
confirmed_task_id: 89, confirmed_task_no: 'SN-NO-ACTION-1',
process_gate: {
execution_no: 'EXEC-NO-ACTION-1', status: 'blocked', owner_type: 'human', technical_auto_only: false,
current_blocking_gate: { gate_code: 'customer_confirmation', status: 'blocked' },
primary_action: { code: 'confirm_customer', label_key: 'chat.shippingNotice.processGate.actionCodes.confirm_customer' },
},
automation: { status: 'running', can_auto_create: false, can_build: true },
};
shippingProcessingProjection.value = {
workItemType: 'order_task', workItemNo: 'SN-NO-ACTION-1', sourceType: 'direct_pdf',
rootOrderTaskNo: 'SN-NO-ACTION-1', shippingNoticeNo: 'SN-NO-ACTION-1', conversationId: 'conv-1',
submissionNo: 'SUB-NO-ACTION', intakeNo: 'SNI-NO-ACTION', status: 'processing', stage: 'order_creating',
progressVersion: 1, lastActivityAt: '2026-08-14T00:00:00Z', currentGate: null, availableActions: ['confirm_customer'],
sourceSummary: { emailSubject: null, filename: 'no-action.pdf', documentCount: 1, parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: null },
childOrderTasks: [], uiState: { status: 'processing', stage: 'order_creating', blocking_reason: null, primary_action: null, secondary_actions: [] },
};
const wrapper = await mountView();
await flushPromises();
// 正式 OT 已有后端 ui_state,Case Gate 只是诊断/建单前兼容来源,不能复活按钮。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
});
it('keeps a formal task action loading until its authoritative processing projection arrives', async () => {
// Case 快照先返回时可能携带历史/降级 Gate;正式 OT 的动作必须等待统一 Projection 裁决。
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
confirmed_task_id: 90,
confirmed_task_no: 'SN-PROJECTION-PENDING',
process_gate: {
execution_no: 'EXEC-PROJECTION-PENDING', status: 'blocked_retryable', owner_type: 'human', technical_auto_only: false,
current_blocking_gate: { gate_code: 'inventory_preparation', status: 'blocked_retryable' },
primary_action: { code: 'retry', label_key: 'chat.shippingOrderReview.currentTask.actionRetry' },
},
automation: { status: 'failed', retryable: true, can_auto_create: false, can_build: true },
};
shippingProcessingProjection.value = null;
shippingProcessingLoading.value = true;
const wrapper = await mountView();
await flushPromises();
// 关键断言:不得先显示 Case 的通用“重试”,避免 Projection 到达后按钮语义跳变。
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
});
it('does not render legacy reparse failure stage as a separate progress source', async () => {
reviewProgressContext.value = {
item_no: 'WFI-1',
current_version_no: 4,
lifecycle_status: 'reparse_failed',
displayed_version: { version_no: 3, run_no: 'RUN-3', case_no: 'CASE-1', status: 'restored' },
latest_attempt: {
version_no: 4,
run_no: 'RUN-4',
status: 'failed',
failure_stage: 'layout_parsing',
error_code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED',
},
};
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-reparse-failed-version-notice"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-reparse-progress"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-reparse-progress-rail"]').exists()).toBe(false);
// 关键断言:页面只消费统一生命周期/处理投影,禁止用旧失败阶段重建另一条进度轨道。
expect(wrapper.find('[data-testid="review-workbench-execution-summary"]').exists()).toBe(false);
expect(wrapper.text()).toContain('V3');
});
it('does not render a legacy reparse progress rail for normal review', async () => {
reviewProgressContext.value = {
item_no: 'WFI-1', current_version_no: 3, lifecycle_status: 'pending_review',
};
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-reparse-progress"]').exists()).toBe(false);
});
it('renders main editor + summary rail without chat context toggle', async () => {
const wrapper = await mountView();
const selectedOrder = wrapper.find('[data-testid="review-selected-order-summary"]');
expect(selectedOrder.exists()).toBe(true);
expect(selectedOrder.text()).toContain('po.pdf');
expect(selectedOrder.text()).toContain('CASE-1');
expect(wrapper.find('[data-testid="review-doc-nav-collapse"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('standard');
expect(wrapper.find('[data-testid="review-main-editor"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-build-gate-rail"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-document-navigation"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-workbench-ot-shell"]').classes()).toContain('contents');
expect(wrapper.find('[data-testid="review-lifecycle-stage-context"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-lifecycle-workbench-identity"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('对话上下文');
expect(wrapper.html()).not.toContain('showContext');
expect(wrapper.html()).not.toContain('hideContext');
});
it('keeps the original adaptive navigation behavior when the run has one order candidate', async () => {
const wrapper = await mountView();
// 关键断言:工作台不得强制 sidebar;单项沿用导航组件原有 hidden 模式。
const queue = wrapper.find('[data-testid="review-document-navigation"]');
expect(queue.exists()).toBe(false);
});
it('renders compact file tabs before lifecycle stages for 2–4 files', async () => {
reviewQueue.value = {
...reviewQueue.value,
summary: { total: 2, needs_action: 2, processing: 0, completed: 0 },
items: [
...reviewQueue.value.items,
{
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'],
},
],
};
const wrapper = await mountView();
const shell = wrapper.get('[data-testid="review-workbench-ot-shell"]');
const navigation = wrapper.get('[data-testid="review-document-navigation"]');
// 2–4 文件不浪费一列宽度,但必须在四阶段前完成文件选择。
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'));
});
it('uses a left file list before lifecycle stages for 5+ files', async () => {
reviewQueue.value = {
...reviewQueue.value,
summary: { total: 5, needs_action: 5, processing: 0, completed: 0 },
items: Array.from({ length: 5 }, (_, index) => ({
...reviewQueue.value.items[0],
case_no: `CASE-${index + 1}`,
document_id: index + 1,
file_name: `po-${index + 1}.pdf`,
})),
};
const wrapper = await mountView();
const shell = wrapper.get('[data-testid="review-workbench-ot-shell"]');
const navigation = wrapper.get('[data-testid="review-document-navigation"]');
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'));
});
it('replaces a stale lifecycle deep link with the selected file backend current stage', 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',
lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', 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' });
await wrapper.get('[data-testid="review-doc-nav-CASE-2"]').trigger('click');
await flushPromises();
// 深链属于当前文件展示位置;不能把 A 的订单复核参数带到 B 的通知准备。
expect((wrapper.vm as any).$router.currentRoute.value.query.lifecycle_stage).toBe('fulfillment_prep');
expect((wrapper.vm as any).$router.currentRoute.value.query.case_no).toBe('CASE-2');
expect((wrapper.vm as any).$router.currentRoute.value.query.case).toBeUndefined();
} 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 时,前端只能等待实时裁决,
// 不能因页面默认值自行开放订单复核或其他生命周期阶段。
const wrapper = await mountView({ lifecycle_stage: 'order_review' });
await flushPromises();
for (const code of ['order_review', 'fulfillment_prep', 'upload_complete']) {
const stage = wrapper.get(`[data-testid="review-lifecycle-stage-${code}"]`);
expect(stage.findAll('button')[1].attributes('disabled')).toBeDefined();
}
// 无后端当前阶段时,任何卡片都不能被前端默认高亮为“当前订单复核”。
expect(wrapper.find('[data-testid="review-lifecycle-stage-order_review"]').classes())
.not.toContain('border-brand-500');
});
it('follows the backend to the next lifecycle stage when the user remains on the former current stage', async () => {
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'order_review',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
const wrapper = await mountView({ lifecycle_stage: 'order_review' });
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
await nextTick();
await flushPromises();
// 用户仍停在刚完成的订单复核时,后端推进后自动替换为通知准备。
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
.toBe('fulfillment_prep');
} finally {
reviewQueue.value = originalQueue;
}
});
it('keeps a manually revisited earlier lifecycle stage when the backend advances', async () => {
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'order_review',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
const wrapper = await mountView({ lifecycle_stage: 'intake_parse' });
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
await nextTick();
await flushPromises();
// 接收解析是可回看的前序阶段;推进不能把用户强制带离当前查看面。
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
.toBe('intake_parse');
} finally {
reviewQueue.value = originalQueue;
}
});
it('does not honor a lifecycle deep link with an unknown backend entry state', async () => {
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'order_review',
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'paused', targetSurface: 'order_lifecycle_workbench' }],
primary_action: null,
secondary_actions: [],
},
};
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
expect(wrapper.find('[data-testid="review-lifecycle-fulfillment-prep"]').exists()).toBe(false);
});
it('prefers the active Case lifecycle entries from the review queue', async () => {
// Run/Queue 已返回当前 Case 的授权入口时,工作台不得再从旧实时投影或路由默认值裁决阶段。
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'order_review',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'fulfillment_prep',
primary_action: null,
secondary_actions: [],
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
},
};
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
// 关键断言:当前 Case 的 Queue 是更贴近该文件的后端真相,库存准备必须保持禁用。
expect(wrapper.find('[data-testid="review-lifecycle-stage-fulfillment_prep"]').findAll('button')[1].attributes('disabled')).toBeDefined();
expect(wrapper.find('[data-testid="review-editor-body"]').exists()).toBe(true);
} finally {
reviewQueue.value = originalQueue;
}
});
it('does not borrow another file lifecycle when the active Case has no candidate entries', async () => {
// 空 Candidate Case 的空 entries 是后端的 fail-closed 裁决,不能退回会话级其他 PDF。
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'intake_parse',
lifecycle_entries: [],
}],
};
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'fulfillment_prep',
primary_action: null,
secondary_actions: [],
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
},
};
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
expect(wrapper.find('[data-testid="review-lifecycle-fulfillment-prep"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]').findAll('button')[1].attributes('disabled')).toBeDefined();
} finally {
reviewQueue.value = originalQueue;
}
});
it('opens the separately authorized intake parse surface without restoring order lifecycle entries', async () => {
// 无 Candidate Case 可读取解析上下文,但该 capability 不能开放订单复核或后续阶段。
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'intake_parse',
lifecycle_entries: [],
intake_parse_authorized: true,
}],
};
const wrapper = await mountView({ lifecycle_stage: 'intake_parse' });
await flushPromises();
expect(ensureIntakeParseContextLoaded).toHaveBeenCalledWith('CASE-1');
expect(wrapper.find('[data-testid="intake-parse-panel"]').exists()).toBe(true);
expect(wrapper.get('[data-testid="review-lifecycle-stage-intake_parse"]').findAll('button')[1].attributes('disabled')).toBeUndefined();
expect(wrapper.get('[data-testid="review-lifecycle-stage-order_review"]').findAll('button')[1].attributes('disabled')).toBeDefined();
} finally {
reviewQueue.value = originalQueue;
}
});
it('requests intake parse context only when the backend-authorized intake stage opens', async () => {
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'intake_parse',
primary_action: null,
secondary_actions: [],
lifecycleEntries: [
{ code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
};
await mountView({ lifecycle_stage: 'intake_parse' });
// 关键断言:接收解析工作面只以当前 Case 编号按需读取,不在普通复核首屏预取。
expect(ensureIntakeParseContextLoaded).toHaveBeenCalledWith('CASE-1');
});
it('renders the current Case intake context and keeps parse dispositions out of order review', async () => {
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'intake_parse',
primary_action: null,
secondary_actions: [],
lifecycleEntries: [
{ code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
],
},
};
intakeParseContext.value = {
case_no: 'CASE-1',
attachment: { document_id: 1, filename: 'current.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' },
email: { document_id: 2, filename: 'source.eml', render_kind: 'text', text: 'current CASE-1 EML body' },
};
const intakeWrapper = await mountView({ lifecycle_stage: 'intake_parse' });
await flushPromises();
// 关键断言:接收解析面板只显示当前 Case context 的邮件正文和附件。
expect(intakeWrapper.get('[data-testid="intake-parse-email-body"]').text()).toContain('current CASE-1 EML body');
expect(intakeWrapper.get('[data-testid="intake-parse-attachment-preview"] iframe').attributes('src')).toBe('blob:mock-pdf');
const intakeFooter = intakeWrapper.get('[data-testid="review-footer-actions"]');
// 关键断言:接收解析处置复用订单复核的固定底栏,滚动邮件/附件时仍可操作。
expect(intakeFooter.classes()).toEqual(expect.arrayContaining(['sticky', 'bottom-0']));
expect(intakeFooter.text()).toContain('非订单');
expect(intakeWrapper.find('[data-testid="intake-parse-disposition-actions"]').exists()).toBe(false);
const orderWrapper = await mountView({ lifecycle_stage: 'order_review' });
// 关键断言:订单复核底栏保留 validate,但不再承载四个接收解析处置入口。
expect(orderWrapper.find('[data-testid="intake-parse-panel"]').exists()).toBe(false);
expect(orderWrapper.text()).not.toContain('非订单');
expect(orderWrapper.text()).not.toContain('质量异常');
expect(orderWrapper.text()).not.toContain('重新识别');
expect(orderWrapper.text()).not.toContain('替换 PDF');
expect(orderWrapper.text()).toContain('保存订单并校验');
});
it('does not request intake context when its lifecycle entry is missing or unavailable', async () => {
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'intake_parse',
primary_action: null,
secondary_actions: [],
lifecycleEntries: [
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
],
},
};
await mountView({ lifecycle_stage: 'intake_parse' });
expect(ensureIntakeParseContextLoaded).not.toHaveBeenCalled();
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'intake_parse',
primary_action: null,
secondary_actions: [],
lifecycleEntries: [
{ code: 'intake_parse', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
},
};
await flushPromises();
expect(ensureIntakeParseContextLoaded).not.toHaveBeenCalled();
});
it('mounts all order-review adjudication surfaces only in the order review workbench', async () => {
activeCase.value = {
...activeCase.value,
customer_resolution: { resolved: false, status: 'ambiguous', candidates: [] },
field_conflicts: [{
conflict_key: 'conflict-1', field_code: 'customer_po_number', reason: 'ambiguous',
options: [{ value_key: 'PO-1', display_value: 'PO-1' }],
}],
duplicate: {
status: 'possible_duplicate', blocking: true, fingerprint_strength: 'strong',
matches: [{ task_no: 'SN-1', document_version: 1, match_type: 'same_active_task', matched_fields: ['po_number'] }],
allowed_actions: ['open_existing'], resolved: false, needs_adjudication: true,
},
reservation: {
needs_attention: true, status: 'needs_attention', lines: [],
issues: [{ code: 'reservation_missing', severity: 'blocking', line_index: 0 }],
},
};
const orderReview = await mountView();
expect(orderReview.find('[data-testid="review-customer-resolution-panel"]').exists()).toBe(true);
expect(orderReview.find('[data-testid="review-field-conflict-panel"]').exists()).toBe(true);
expect(orderReview.find('[data-testid="review-duplicate-panel"]').exists()).toBe(true);
expect(orderReview.find('[data-testid="review-reservation-panel"]').exists()).toBe(true);
expect(orderReview.get('[data-testid="review-build-gate-rail"]')
.find('[data-testid="review-reservation-panel"]').exists()).toBe(true);
expect(orderReview.get('[data-testid="review-build-gate-rail"]')
.find('[data-testid="review-customer-resolution-panel"]').exists()).toBe(true);
expect(orderReview.get('[data-testid="review-build-gate-rail"]')
.find('[data-testid="review-field-conflict-panel"]').exists()).toBe(true);
expect(orderReview.get('[data-testid="review-build-gate-rail"]')
.find('[data-testid="review-duplicate-panel"]').exists()).toBe(true);
// 关键断言:宽屏右栏的当前任务卡不能替代建单门禁摘要;用户必须能看到具体字段级原因。
expect(orderReview.get('[data-testid="review-build-gate-rail"]')
.find('[data-testid="mock-eligibility-summary"]').exists()).toBe(true);
expect(orderReview.get('[data-testid="review-main-editor"]')
.find('[data-testid="review-reservation-panel"]').exists()).toBe(false);
expect(orderReview.get('[data-testid="review-main-editor"]')
.find('[data-testid="review-customer-resolution-panel"]').exists()).toBe(false);
expect(orderReview.get('[data-testid="review-main-editor"]')
.find('[data-testid="review-field-conflict-panel"]').exists()).toBe(false);
expect(orderReview.get('[data-testid="review-main-editor"]')
.find('[data-testid="review-duplicate-panel"]').exists()).toBe(false);
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'fulfillment_prep', lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
], primary_action: null, secondary_actions: [],
},
};
const fulfillment = await mountView({ lifecycle_stage: 'fulfillment_prep' });
expect(fulfillment.find('[data-testid="review-field-conflict-panel"]').exists()).toBe(false);
expect(fulfillment.find('[data-testid="review-duplicate-panel"]').exists()).toBe(false);
expect(fulfillment.find('[data-testid="review-reservation-panel"]').exists()).toBe(false);
});
it('stops requesting intake context when the backend revokes its lifecycle entry', async () => {
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'intake_parse',
primary_action: null,
secondary_actions: [],
lifecycleEntries: [
{ code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench' },
],
},
};
await mountView({ lifecycle_stage: 'intake_parse' });
const callsBeforeRevocation = ensureIntakeParseContextLoaded.mock.calls.length;
expect(callsBeforeRevocation).toBeGreaterThan(0);
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'intake_parse',
primary_action: null,
secondary_actions: [],
lifecycleEntries: [],
},
};
await flushPromises();
// 关键断言:entry 被后端撤销后,watch 重跑也不能继续读取受控邮件上下文。
expect(ensureIntakeParseContextLoaded).toHaveBeenCalledTimes(callsBeforeRevocation);
});
it('keeps the fulfillment-prep deep link when only the realtime processing projection is available', async () => {
activeCase.value = {
...activeCase.value,
confirmed_task_id: 901,
confirmed_task_no: 'SN-MOCK',
has_formal_ot: true,
};
// 正式任务详情尚未含 ui_state 时,工作台仍须使用批次中心同源实时投影,
// 而不是默认回退到订单复核。
shippingProcessingProjection.value = {
status: 'processing',
stage: 'inventory_matching',
uiState: {
status: 'processing',
stage: 'inventory_matching',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
};
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
// 关键断言:批次中心跳转到通知准备时,在正式详情延迟期间也停留在通知准备工作面。
expect(wrapper.find('[data-testid="review-lifecycle-fulfillment-prep"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-lifecycle-stage-fulfillment_prep"]').attributes('disabled')).toBeUndefined();
expect(wrapper.find('[data-testid="review-lifecycle-stage-upload_complete"]').findAll('button')[1].attributes('disabled')).toBeDefined();
});
it('shows an actionable diagnostic instead of a blank preparation page when task detail loading fails', async () => {
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockRejectedValue(new Error('detail unavailable'));
activeCase.value = {
...activeCase.value,
confirmed_task_id: 901,
confirmed_task_no: 'SN-MOCK',
has_formal_ot: true,
current_stage: { code: 'completed', label_key: 'completed' },
};
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
primary_action: null,
secondary_actions: [],
},
};
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text())
.toContain('chat.shippingOrderReview.lifecycle.prepare.loadFailed');
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text())
.toContain('chat.shippingOrderReview.lifecycle.prepare.retry');
// 批次中心的阶段深链是纯导航;详情请求失败应留在工作面内诊断,不能误报结果未生成。
expect(messageMocks.warning).not.toHaveBeenCalledWith('处理结果尚未生成');
});
it('uses case line fulfillment as a read-only fallback when formal preparation rows are temporarily empty', async () => {
const taskApi = await import('@/features/chat/api/shipping.api');
// 正式任务详情延迟/失败不能阻塞已由 Case 投影下发的只读库存匹配事实。
vi.mocked(taskApi.getWorkspaceShippingTask).mockRejectedValue(new Error('detail unavailable'));
activeCase.value = {
...activeCase.value,
confirmed_task_id: 902,
confirmed_task_no: 'SN-MOCK',
has_formal_ot: true,
current_stage: { code: 'completed', label_key: 'completed' },
line_fulfillment: {
lines: [{
line_key: 'line-1', reservation_id: 'RSV-FALLBACK', part_number: 'PN-FALLBACK',
required_qty: '8', available_qty: '5', shortage_qty: '3', inventory_source_code: 'DBS_DUB',
}],
},
};
shippingProcessingProjection.value = {
uiState: {
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
primary_action: null,
secondary_actions: [],
},
};
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');
expect(wrapper.get('[data-testid="review-lifecycle-fulfillment-prep"]').text()).toContain('3');
expect(wrapper.find('[data-testid="review-fulfillment-prep-workspace"]').exists()).toBe(true);
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 () => {
const taskApi = await import('@/features/chat/api/shipping.api');
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_id: 903, confirmed_task_no: 'SN-FROZEN', has_formal_ot: true,
line_fulfillment: {
lines: [{
line_key: 'line-frozen',
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
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: '库位' }],
}],
},
};
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-FROZEN', status: 'processing', lines: [], events: [],
ui_state: {
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
stage_context: {
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',
}],
lines: [{
line_key: 'line-frozen', 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',
}],
artifact: { file_name: null, status: 'not_generated' },
},
},
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
// 关键断言:订单基线列和库存事实合为唯一行级工作表,库存源不得退化为任务级 CRANE。
const workspace = wrapper.get('[data-testid="review-fulfillment-prep-workspace"]');
expect(workspace.text()).toContain('RSV-FROZEN');
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'))
.toBeTruthy();
expect(wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-line-frozen"]').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(workspace.text()).toContain('库存不足');
await wrapper.get('[data-testid="review-fulfillment-line-download-line-frozen"]').trigger('click');
expect(downloadWorkspaceShippingLineInventoryFileMock).toHaveBeenCalledWith('SN-FROZEN', 'SIF-LINE-DBS');
await wrapper.get('[data-testid="review-fulfillment-line-retry-preparation-line-frozen"]').trigger('click');
expect(retryWorkspaceShippingTaskLine).toHaveBeenCalledWith('SN-FROZEN', 'line-frozen');
await wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').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"]');
await dialog.find('textarea').setValue('客户确认分批发货');
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',
reason: '客户确认分批发货',
release_field_values: { '102': 'A-01' },
}));
});
it('keeps intake parse on the standard workbench and removes the inventory return row', async () => {
const originalQueue = reviewQueue.value;
try {
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0],
lifecycle_stage: 'intake_parse',
lifecycle_entries: [],
intake_parse_authorized: true,
}],
};
const intakeWrapper = await mountView({ lifecycle_stage: 'intake_parse' });
await flushPromises();
// 关键断言:接收解析不是库存工作面,避免用户看不到重解析入口。
expect(intakeWrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode'))
.toBe('standard');
expect(intakeWrapper.find('[data-testid="review-enter-inventory-mode"]').exists()).toBe(false);
expect(intakeWrapper.find('[data-testid="review-return-standard-mode"]').exists()).toBe(false);
} finally {
reviewQueue.value = originalQueue;
}
});
it('uses the current processing projection instead of a stale formal-task Gate in the current-task card', async () => {
const taskApi = await import('@/features/chat/api/shipping.api');
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_id: 904, confirmed_task_no: 'SN-GATE-TRUTH', has_formal_ot: true,
};
shippingProcessingProjection.value = {
userStatus: 'running',
uiState: {
status: 'running', 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-GATE-TRUTH', status: 'processing', lines: [], events: [],
ui_state: {
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
process_gate: {
gate_status: 'blocked_retryable', blocking_reason_code: 'inventory_file_missing',
primary_action: { code: 'retry_inventory_preparation', label_key: 'retry_inventory_preparation' },
},
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
// 关键断言:正式任务详情是附件/明细快照;当前 Gate 必须由实时 Projection 裁决。
expect(wrapper.get('[data-testid="review-build-gate-rail"] [data-testid="review-current-processing-card"]')
.attributes('data-user-status')).toBe('running');
});
it('ignores a late formal-task response after switching to another PDF', async () => {
const resolvers = new Map<string, (value: any) => void>();
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockImplementation((taskNo) => (
new Promise((resolve) => { resolvers.set(String(taskNo), resolve); }) as any
));
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_id: 1, confirmed_task_no: 'SN-FIRST', has_formal_ot: true,
current_stage: { code: 'completed', label_key: 'completed' },
};
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
expect(resolvers.has('SN-FIRST')).toBe(true);
activeCase.value = {
...activeCase.value,
case_no: 'CASE-2', confirmed_task_id: 2, confirmed_task_no: 'SN-SECOND', has_formal_ot: true,
current_stage: { code: 'completed', label_key: 'completed' },
};
await nextTick();
expect(resolvers.has('SN-SECOND')).toBe(true);
resolvers.get('SN-SECOND')?.({
task_no: 'SN-SECOND', status: 'processing', lines: [], events: [],
ui_state: {
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'order_review', state: 'available', target_surface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', target_surface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', target_surface: 'order_lifecycle_workbench' },
],
},
});
await flushPromises();
resolvers.get('SN-FIRST')?.({
task_no: 'SN-FIRST', status: 'processing', lines: [], events: [],
ui_state: {
lifecycle_stage: 'order_review',
lifecycle_entries: [{ code: 'order_review', state: 'current', target_surface: 'order_lifecycle_workbench' }],
},
});
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-upload_complete"]').findAll('button')[1].attributes('disabled')).toBeDefined();
});
it('hides PDF evidence drawer in standard mode by default', async () => {
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
});
it('keeps footer actions without confirm-create when draft exists', async () => {
const wrapper = await mountView();
// 关键断言:底栏仍在,但正常路径不再暴露「确认并创建任务」。
expect(wrapper.find('[data-testid="review-footer-actions"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
});
it('keeps legacy order review editing and validate when lifecycle entries are absent', async () => {
shippingProcessingProjection.value = null;
const wrapper = await mountView();
// 关键断言:接收解析才需新 entry 授权;旧投影不能因此丢失订单复核编辑和校验入口。
expect(wrapper.find('[data-testid="intake-parse-panel"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-editor-body"]').exists()).toBe(true);
expect(wrapper.get('[data-testid="review-footer-actions"]').text()).toContain('保存订单并校验');
});
it('keeps backend-authorized manual upload registration out of the upload main area', async () => {
const originalQueue = reviewQueue.value;
try {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-UPLOAD-1', confirmed_task_id: 11, has_formal_ot: true,
};
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0], lifecycle_stage: 'upload_complete',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'current', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-UPLOAD-1', status: 'processing', lines: [], events: [],
ui_state: { actions: { primary: null, secondary: [] }, summary: {}, steps: [] },
} as any);
const withoutAuthorization = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises();
expect(withoutAuthorization.find('[data-testid="review-lifecycle-upload-manual"]').exists()).toBe(false);
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-UPLOAD-1', status: 'processing', lines: [], events: [],
ui_state: {
actions: {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
target_surface: 'upload_complete',
target_anchor: 'manual_upload',
requires_confirmation: false,
},
secondary: [],
},
summary: {}, steps: [],
},
} as any);
const withAuthorization = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises();
// Gate 写操作只在右侧“当前任务”显示;主区只保留上传事实与审计摘要。
expect(withAuthorization.find('[data-testid="review-lifecycle-upload-manual"]').exists()).toBe(false);
// 正式动作直接提交当前 Gate,不允许无界面 TaskTodoPanel 作为隐藏执行器。
expect((withAuthorization.vm as { formalTodoPanelRef?: unknown }).formalTodoPanelRef).toBeUndefined();
} finally {
reviewQueue.value = originalQueue;
}
});
it('opens the page-level evidence dialog when the authorized current-task action is manual upload', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-UPLOAD-DIALOG', confirmed_task_id: 19, has_formal_ot: true,
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-UPLOAD-DIALOG', status: 'processing', lines: [], events: [],
ui_state: {
actions: {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
target_surface: 'upload_complete', target_anchor: 'manual_upload',
requires_confirmation: false,
},
secondary: [],
},
summary: {}, steps: [],
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises();
await wrapper.get('[data-testid="review-current-task-primary-action"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="manual-upload-evidence-dialog"]').exists()).toBe(true);
});
it('renders the authorized Excel download in every upload-complete order line instead of the task rail', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-DOWNLOAD-DISPATCH', confirmed_task_id: 20, has_formal_ot: true,
schema: {
...activeCase.value.schema,
fields: [
...activeCase.value.schema.fields,
{ field_id: 'fld-line-no', field_code: 'line_no', display_name: '项次', scope: 'line', value_type: 'string', required: true, options: [] },
{ field_id: 'fld-part-number', field_code: 'part_number', display_name: '料号', scope: 'line', value_type: 'string', required: true, options: [] },
{ field_id: 'fld-quantity', field_code: 'quantity', display_name: '数量', scope: 'line', value_type: 'number', required: true, options: [] },
],
},
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: [] },
],
},
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' },
],
},
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-DOWNLOAD-DISPATCH', status: 'completed', lines: [], events: [],
ui_state: {
actions: {
primary: {
code: 'mark_manual_uploaded', kind: 'forward', enabled: true,
dispatch: 'dialog', ui_handler: 'manual_upload_evidence',
requires_confirmation: false,
},
secondary: [{
code: 'download_excel', label: '下载 Excel', kind: 'view', enabled: true,
dispatch: 'view', ui_handler: 'excel_download',
target_surface: 'upload_complete', target_anchor: 'excel_artifact',
requires_confirmation: false,
}],
},
lifecycle_stage: 'upload_complete',
lifecycle_entries: [{ code: 'upload_complete', state: 'current' }],
process_gate: { execution_no: 'EXEC-DOWNLOAD-DISPATCH' }, summary: {}, steps: [],
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises();
const rows = wrapper.findAll('[data-testid="review-upload-complete-line"]');
expect(rows).toHaveLength(2);
expect(rows[0].text()).toContain('PN-ONE');
expect(rows[1].text()).toContain('PN-TWO');
expect(wrapper.find('[data-testid="review-current-task-recovery-download_excel"]').exists()).toBe(false);
await wrapper.get('[data-testid="review-upload-complete-download-LINE-1"]').trigger('click');
await flushPromises();
// 下载是 Artifact 只读操作;订单行不按 PO 聚合,且不得伪装成 Gate mutation。
expect(downloadWorkspaceShippingExcelFileMock).toHaveBeenCalledWith('SN-DOWNLOAD-DISPATCH');
expect(messageMocks.success).not.toHaveBeenCalled();
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
});
it('keeps backend-authorized Excel regeneration out of fulfillment preparation main area', async () => {
const originalQueue = reviewQueue.value;
try {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-EXCEL-RETRY', confirmed_task_id: 12, has_formal_ot: true,
};
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0], lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-EXCEL-RETRY', status: 'processing', lines: [], events: [],
ui_state: {
actions: {
primary: {
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
dispatch: 'mutation',
target_surface: 'fulfillment_prep',
target_anchor: 'excel_artifact',
requires_confirmation: false,
},
secondary: [],
},
stage_context: { preparation: { status: 'blocked', has_match_result: false, lines: [] } },
summary: {}, steps: [],
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
// Gate 18 的写入口只属于右侧“当前任务”;准备区仅展示库存与产物事实。
expect(wrapper.find('[data-testid="review-lifecycle-preparation-regenerate_excel_artifact"]').exists()).toBe(false);
} finally {
reviewQueue.value = originalQueue;
}
});
it('does not place a backend action in a lifecycle area when its anchor differs', async () => {
const originalQueue = reviewQueue.value;
try {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-ANCHOR-1', confirmed_task_id: 13, has_formal_ot: true,
};
reviewQueue.value = {
...reviewQueue.value,
items: [{
...reviewQueue.value.items[0], lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
],
}],
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-ANCHOR-1', status: 'processing', lines: [], events: [],
ui_state: {
actions: {
primary: {
code: 'regenerate_excel_artifact', kind: 'recovery', enabled: true,
dispatch: 'mutation',
target_surface: 'fulfillment_prep', target_anchor: 'inventory_matching',
requires_confirmation: false,
},
secondary: [],
},
stage_context: { preparation: { status: 'blocked', has_match_result: false, lines: [] } },
summary: {}, steps: [],
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
// 位置必须同时由后端 surface 与 anchor 授权;前端不能仅凭动作码或阶段补放。
expect(wrapper.find('[data-testid="review-lifecycle-preparation-regenerate_excel_artifact"]').exists()).toBe(false);
} finally {
reviewQueue.value = originalQueue;
}
}, 15000);
it('renders a persistent result panel for a completed formal task', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed',
confirmed_task_no: 'SN-MOCK',
confirmed_task_id: 1,
has_formal_ot: true,
current_stage: { code: 'completed', label_key: 'completed' },
automation: { status: 'completed', can_auto_create: false, can_build: false },
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValueOnce({
task_no: 'SN-MOCK',
status: 'completed',
upload_status: 'uploaded',
upload_status: 'uploaded',
lines: [],
line_results: [{
part_number: 'PN-1', reservation_id: 'RES-1', required_qty: 2,
available_qty: 2, shortage_qty: 0, line_status: 'ok',
}],
export_artifacts: [{ id: 1, artifact_no: 'EXP-1', status: 'ready', file_name: 'result.xlsx' }],
events: [],
ui_state: {
actions: {
primary: { code: 'download_excel', kind: 'view', enabled: true, requires_confirmation: false },
secondary: [],
},
summary: {}, process_gate: null,
},
} as any);
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-lifecycle-stage-context"]').exists()).toBe(false);
});
it('does not show Excel download merely because a historical artifact is present', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed',
confirmed_task_no: 'SN-MOCK',
confirmed_task_id: 1,
has_formal_ot: true,
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValueOnce({
task_no: 'SN-MOCK', status: 'processing', upload_status: 'pending', lines: [], events: [],
export_file_name: 'stale.xlsx',
export_artifacts: [{ id: 1, artifact_no: 'EXP-STALE', status: 'ready', file_name: 'stale.xlsx' }],
ui_state: { actions: { primary: null, secondary: [] }, summary: {}, process_gate: null },
} as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises();
expect(wrapper.find('[data-testid="review-lifecycle-upload-download"]').exists()).toBe(false);
});
it('renders empty optional schema fields as editable line columns', async () => {
const wrapper = await mountView();
const inputs = wrapper.findAll('[data-testid="review-line-field-input"]');
// 关键断言:库存源线索即使非必填且尚无机器值,也必须作为 Schema 列显示并可编辑。
expect(wrapper.text()).toContain('库存源线索');
expect(inputs).toHaveLength(1);
expect(inputs[0].attributes('disabled')).toBeUndefined();
});
it('ignores a stale line change after the current draft has accepted the value', async () => {
activeCase.value = {
...activeCase.value,
schema: {
...activeCase.value.schema,
fields: [{
field_id: 'fld-part', field_code: 'part_number', display_name: '内部料号', scope: 'line',
value_type: 'string', required: true, options: [],
}],
},
draft: {
...activeCase.value.draft,
lines: [{
line_key: 'LINE-1',
values: { 'fld-part': { value: 'D4-AR1200072A1', source: 'manual' } },
machine_fields: [],
}],
},
};
const wrapper = await mountView();
const input = wrapper.find('[data-testid="review-line-field-input"]');
(input.element as HTMLInputElement).value = '';
await input.trigger('change');
await flushPromises();
// 关键断言:旧节点的空 change 不能覆盖当前草稿中已确认的人工内部料号。
expect(patchLineMock).not.toHaveBeenCalled();
// 此 describe 共享响应式 fixture;恢复默认值,避免影响后续证据交互回归。
resetActiveCaseFixture();
});
it('does not render resident AI card without focused field', async () => {
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-llm-field-entry"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="mock-llm-drawer"]').exists()).toBe(true);
expect(wrapper.html()).not.toContain('panelTitle');
});
it('opens evidence PDF drawer only via locate action, not via input focus', async () => {
const wrapper = await mountView();
const input = wrapper.find('[data-testid="review-header-field-input"]');
expect(input.exists()).toBe(true);
await input.trigger('focus');
await flushPromises();
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('standard');
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(false);
const locate = wrapper.find('[data-testid="review-field-locate"]');
expect(locate.exists()).toBe(true);
await locate.trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('evidence');
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(true);
// 关键断言:定位后字段与 PDF 证据联动高亮。
expect(wrapper.find('[data-testid="review-header-field-input"]').attributes('data-evidence-active')).toBe('true');
});
it('opens evidence PDF drawer via field double-click', async () => {
const wrapper = await mountView();
const input = wrapper.find('[data-testid="review-header-field-input"]');
await input.trigger('dblclick');
await flushPromises();
// 关键断言:双击字段等价于定位原文,进入证据模式。
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('evidence');
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(true);
});
it('navigates exception fields from the summary rail', async () => {
activeCase.value = {
...activeCase.value,
draft: {
...activeCase.value.draft,
issues: [
{
code: 'required_field_missing',
severity: 'blocking',
field_id: 'fld-po',
message: '缺少 PO',
},
],
},
};
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-exception-nav"]').exists()).toBe(true);
await wrapper.find('[data-testid="review-exception-next"]').trigger('click');
await flushPromises();
// 关键断言:异常导航会打开证据并定位到问题字段。
expect(wrapper.find('[data-testid="shipping-order-review-view"]').attributes('data-workbench-mode')).toBe('evidence');
expect(wrapper.find('[data-testid="review-header-field-input"]').attributes('data-evidence-active')).toBe('true');
});
it('opens evidence as floating panel without docking editor body layout', async () => {
const wrapper = await mountView();
await wrapper.find('[data-testid="review-field-locate"]').trigger('click');
await flushPromises();
const body = wrapper.find('[data-testid="review-editor-body"]');
const drawer = wrapper.find('[data-testid="review-document-evidence-drawer"]');
// 关键断言:定位证据默认浮窗;主编辑区不切换为 PDF 网格列。
expect(drawer.attributes('data-presentation')).toBe('floating');
expect(body.attributes('data-evidence-docked')).toBe('false');
expect(body.classes()).toContain('space-y-4');
expect(body.classes().some((cls) => cls.includes('minmax(280px'))).toBe(false);
});
});
describe('ShippingOrderReviewView audit and progress recovery', () => {
beforeEach(async () => {
vi.clearAllMocks();
resetActiveCaseFixture();
reviewProgressContext.value = null;
vi.mocked(auditWorkspaceShippingOrderReviewVersionHistory).mockResolvedValue({
audited: true,
case_no: 'CASE-1',
});
vi.mocked(auditWorkspaceShippingOrderReviewEligibilityDetails).mockResolvedValue({
audited: true,
case_no: 'CASE-1',
});
}, 20000);
it('refuses to open version history when access audit fails', async () => {
vi.mocked(auditWorkspaceShippingOrderReviewVersionHistory).mockRejectedValueOnce(new Error('audit down'));
const wrapper = await mountView();
await wrapper.find('[data-testid="review-open-version-history"]').trigger('click');
await flushPromises();
// 关键断言:审计失败有告警且不打开版本历史面板。
expect(wrapper.find('[data-testid="mock-versions-drawer"]').exists()).toBe(false);
expect(messageMocks.warning).toHaveBeenCalledWith('审计记录失败,敏感面板未打开,请重试');
});
it('refuses to open eligibility details when access audit fails', async () => {
vi.mocked(auditWorkspaceShippingOrderReviewEligibilityDetails).mockRejectedValueOnce(new Error('audit down'));
const wrapper = await mountView();
await wrapper.find('[data-testid="review-open-eligibility-details"]').trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="mock-eligibility-details"]').exists()).toBe(false);
expect(messageMocks.warning).toHaveBeenCalledWith('审计记录失败,敏感面板未打开,请重试');
});
it('waits for the authoritative Gate projection instead of restoring Case retry after reload', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 7,
confirmed_task_no: 'SN-RECOVER-1',
automation: {
status: 'failed',
retryable: true,
phase: 'post_ot_progress',
can_auto_create: false,
can_build: true,
},
post_confirm_auto_progress: {
task_no: 'SN-RECOVER-1',
needs_retry: true,
status: 'needs_retry',
message: '已建单但任务仍停在待推进,可重试自动推进',
},
};
const wrapper = await mountView();
await flushPromises();
// 关键断言:正式 OT 的旧 Case 快照不是写授权;实时 Gate 未返回时只能等待。
expect(wrapper.find('[data-testid="review-confirm-outcome"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="retry-auto-progress-after-confirm"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-RECOVER-1');
}, 15000);
it('does not call legacy retry before the formal OT Gate projection arrives (UI-01)', async () => {
// 关键断言:刷新后无实时 Gate 时,不能用 confirmed_task_no 调旧 /retry。
vi.mocked(retryWorkspaceShippingTask).mockClear();
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 42,
confirmed_task_no: 'SN-OT-FAIL-1',
current_stage: { code: 'order_creating', inconsistent: false },
automation: {
status: 'failed',
retryable: true,
phase: 'post_ot_progress',
can_auto_create: false,
can_build: true,
},
post_confirm_auto_progress: {
task_no: 'SN-OT-FAIL-1',
needs_retry: true,
status: 'needs_retry',
},
};
const wrapper = await mountView();
await flushPromises();
const retryBtn = wrapper.find('[data-testid="review-current-processing-retry"]');
expect(retryBtn.exists()).toBe(false);
expect(retryWorkspaceShippingTask).not.toHaveBeenCalled();
}, 15000);
it('disables the formal Gate retry while inventory preparation is waiting for RPA callback', async () => {
// 关键断言:Gate 仍为 blocked_retryable 时,PreparationAttempt 的等待事实优先禁用重试。
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
confirmed_task_id: 43,
confirmed_task_no: 'SN-OT-WAITING-INVENTORY',
automation: { status: 'failed', retryable: true, can_auto_create: false, can_build: true },
};
shippingProcessingProjection.value = {
shippingNoticeNo: 'SN-OT-WAITING-INVENTORY',
retryable: true,
userStatus: 'retryable',
primaryAction: { code: 'retry_inventory_preparation' },
currentGate: { status: 'blocked_retryable' },
inventoryPreparation: {
activeAttemptCount: 1,
gateAttemptActive: true,
pendingSources: ['CRANE'],
},
uiState: {
status: 'retryable',
primary_action: { code: 'retry_inventory_preparation' },
secondary_actions: [],
},
};
vi.mocked(getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-OT-WAITING-INVENTORY', status: 'processing', lines: [], events: [],
ui_state: {
actions: {
primary: {
code: 'retry_inventory_preparation', kind: 'recovery', enabled: true,
dispatch: 'mutation', requires_confirmation: false,
},
secondary: [],
},
process_gate: {
execution_no: 'EXEC-INVENTORY-WAITING',
current_blocking_gate: {
gate_code: 'inventory_preparation', evaluation_version: 1,
},
},
summary: {}, steps: [],
},
} as any);
const wrapper = await mountView();
await flushPromises();
expect(wrapper.get('[data-testid="review-current-task-primary-action"]').attributes('disabled')).toBeDefined();
}, 15000);
it('keeps top / wide / narrow stage labels identical via Progress projection (waiting_system_start)', async () => {
// 关键断言:Case.current_stage 故意降级为误导码;三处必须消费 Progress label_key 文案。
shippingProcessingProjection.value = {
workItemType: 'order_task',
workItemNo: 'OT-WAIT-1',
sourceType: 'eml',
rootOrderTaskNo: 'OT-WAIT-1',
shippingNoticeNo: 'SN-WAIT-1',
conversationId: 'conv-1',
submissionNo: 'SUB-1',
intakeNo: 'INT-1',
status: 'automating',
stage: 'order_creating',
stageLabelKey: 'waiting_system_start',
progressVersion: 1,
lastActivityAt: '2026-08-07T00:00:00Z',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-1',
},
childOrderTasks: [],
};
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 88,
confirmed_task_no: 'SN-WAIT-1',
// 故意与 Progress 文案分叉:若宽屏仍直读 Case code,会显示「库存匹配」。
current_stage: {
code: 'inventory_matching',
label_key: 'inventory_matching',
inconsistent: false,
},
automation: {
status: 'waiting_to_start',
retryable: false,
phase: 'post_ot_progress',
can_auto_create: false,
can_build: true,
},
};
const wrapper = await mountView();
await flushPromises();
const expected = '等待系统启动';
const cards = wrapper.findAll('[data-testid="review-current-processing-card"]');
expect(cards.length).toBeGreaterThan(0);
expect(wrapper.find('[data-testid="review-lifecycle-stage-detail-order_review"]').exists()).toBe(true);
});
it('shows STP retry button for failed automation and calls retry API (UI-02)', async () => {
activeCase.value = {
...activeCase.value,
status: 'ready',
confirmed_task_no: null,
available_actions: ['validate', 'retry_stp_auto_create'],
automation: {
status: 'failed',
retryable: true,
can_auto_create: true,
can_build: true,
reason_code: 'stp_job_failed',
},
};
const wrapper = await mountView();
await flushPromises();
// 关键断言:failed 态主卡/底栏露出 STP 重试(非确认后 auto_progress)。
const railBtn = wrapper.find('[data-testid="review-current-processing-retry"]');
const footerBtn = wrapper.find('[data-testid="review-retry-stp-auto-create"]');
expect(railBtn.exists() || footerBtn.exists()).toBe(true);
await (railBtn.exists() ? railBtn : footerBtn).trigger('click');
await flushPromises();
expect(retryWorkspaceShippingOrderStpAutoCreate).toHaveBeenCalledWith('CASE-1');
}, 15000);
it('shows STP retry for manual_fallback without confirm-create (UI-02)', async () => {
activeCase.value = {
...activeCase.value,
status: 'ready',
confirmed_task_no: null,
available_actions: ['validate', 'retry_stp_auto_create'],
automation: {
status: 'manual_fallback',
retryable: true,
can_auto_create: true,
can_build: true,
reason_code: 'stp_waiting_timeout',
},
};
const wrapper = await mountView();
await flushPromises();
expect(
wrapper.find('[data-testid="review-current-processing-retry"]').exists()
|| wrapper.find('[data-testid="review-retry-stp-auto-create"]').exists(),
).toBe(true);
// 关键断言:正常路径不再保留「确认并创建任务」兜底。
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
}, 15000);
it('hides profile match panel when profile_match.available is false', async () => {
activeCase.value = {
...activeCase.value,
profile_match: { available: false, visibility: 'admin_only', candidates: [] },
};
const wrapper = await mountView();
await flushPromises();
// 关键断言:普通用户裁剪后 DOM 不得出现模板匹配面板。
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(false);
});
it('shows profile match panel for admin when profile_match.available is true', async () => {
activeCase.value = {
...activeCase.value,
profile_match: {
available: true,
visibility: 'admin',
status: 'matched',
candidates: [{ profile_id: 1, score: 0.9 }],
selected_profile: { profile_id: 1, profile_code: 'P1' },
},
};
const wrapper = await mountView();
await flushPromises();
expect(wrapper.find('[data-testid="review-profile-match-panel"]').exists()).toBe(true);
}, 15000);
it('does not hydrate a write retry from Case projection without formal Gate data', async () => {
// 关键断言:无确认建单按钮时,Case 的失败状态只能作为历史摘要,不能恢复写入口。
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 55,
confirmed_task_no: 'SN-CONFIRM-PROGRESS-FAIL',
automation: {
status: 'failed',
retryable: true,
phase: 'post_ot_progress',
can_auto_create: false,
can_build: true,
},
post_confirm_auto_progress: {
task_no: 'SN-CONFIRM-PROGRESS-FAIL',
needs_retry: true,
status: 'needs_retry',
message: '入队失败',
},
};
const wrapper = await mountView();
await flushPromises();
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-CONFIRM-PROGRESS-FAIL');
}, 15000);
});
describe('ShippingOrderReviewView viewport layout remediation', () => {
beforeEach(() => {
vi.clearAllMocks();
resetActiveCaseFixture();
});
it('uses a single primary vertical scroll container (not nested editor/rail scroll)', async () => {
const wrapper = await mountView();
const scroll = wrapper.find('[data-testid="review-workbench-scroll"]');
const editor = wrapper.find('[data-testid="review-main-editor"]');
const rail = wrapper.find('[data-testid="review-build-gate-rail"]');
// 关键断言:仅外层主滚动带 overflow-y-auto;编辑区与摘要栏不得再套纵向滚动。
expect(scroll.classes()).toContain('overflow-y-auto');
expect(editor.classes()).not.toContain('overflow-y-auto');
expect(rail.classes()).not.toContain('overflow-y-auto');
expect(editor.classes()).not.toContain('xl:max-h-[calc(100vh-12rem)]');
});
it('keeps footer sticky for always-visible actions', async () => {
const wrapper = await mountView();
const footer = wrapper.find('[data-testid="review-footer-actions"]');
expect(footer.classes()).toContain('sticky');
expect(footer.classes()).toContain('bottom-0');
});
it('keeps summary rail visible in floating evidence mode and docks only on demand', async () => {
const wrapper = await mountView();
await wrapper.find('[data-testid="review-field-locate"]').trigger('click');
await flushPromises();
const rail = wrapper.find('[data-testid="review-build-gate-rail"]');
// 关键断言:浮窗证据不再为挤 PDF 而隐藏摘要栏。
expect(rail.classes()).not.toContain('hidden');
expect(rail.classes()).toContain('xl:sticky');
await wrapper.find('[data-testid="review-evidence-toggle-dock"]').trigger('click');
await flushPromises();
const body = wrapper.find('[data-testid="review-editor-body"]');
const drawer = wrapper.find('[data-testid="review-document-evidence-drawer"]');
// 关键断言:用户主动固定后才进入双栏网格。
expect(body.attributes('data-evidence-docked')).toBe('true');
expect(drawer.attributes('data-docked')).toBe('true');
expect(wrapper.html()).toContain('minmax(420px,1fr)');
});
});