Files
syops/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts
T
hugo 18af972d20 refactor(shipping-notice): 进度信号统一为 15 阶 stage 契约码并透传阻断原因
- 后端进度写入 step_key 全量切换为 15 阶契约 stage 码
- 投影层清除 CheckPoint stepN_* 遗留别名与子串/前缀启发式,阶段信号按契约码精确匹配
- 建单前 Case 摘要透传草稿首要阻断原因
- 前端标签/归一化/处理卡片同步契约码,阻断原因按 i18n 优先展示
- 修复正式下游回看时 activeCase 刻意为空导致队列定位与接收解析上下文静默跳过
- 同步更新投影/门禁/工作台/RPA 流程测试
2026-09-17 15:54:53 +08:00

1775 lines
68 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/shipping-review/useShippingOrderReview.spec.ts
* 用途:阶段 3 复核页历史版本只读、草稿版本冲突、建单资格门禁、库存候选与路由恢复写入冒烟。
* 依赖:isReviewCaseHistorical / isDraftVersionMismatchError / summarizeDraftConflictDiff /
* isBuildConfirmBlocked / lineNeedsInventoryRoutingRecovery、useShippingOrderReview。
* 逻辑:断言 superseded 只读、版本冲突码识别、差异摘要、confirm 门禁、inventory PUT、
* reroute/adopt/keep 与 suggestion_pending 行筛选。
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BusinessError } from '@/shared/api/client';
import {
isBuildConfirmBlocked,
isDraftVersionMismatchError,
isReviewCaseHistorical,
isReviewReadOnly,
isReviewWorkItemClosed,
lineNeedsInventoryRoutingRecovery,
mapReviewContextLifecycleStatus,
REVIEW_BUILD_ELIGIBILITY_BLOCKED,
REVIEW_DRAFT_VERSION_MISMATCH,
PROGRESS_POLL_MS,
summarizeDraftConflictDiff,
useShippingOrderReview,
} from './useShippingOrderReview';
import type { ShippingOrderReviewCase } from '../types/shipping.api.types';
const api = vi.hoisted(() => ({
getCase: vi.fn(),
getRun: vi.fn(),
getQueue: vi.fn(),
getEvidence: vi.fn(),
getPreview: vi.fn(),
getIntakeParseContext: vi.fn(),
getExtractionRun: vi.fn(),
getProcessingWorkItem: vi.fn(),
reparseDocument: vi.fn(),
rerouteInventoryRouting: vi.fn(),
confirmCase: vi.fn(),
validateDraft: vi.fn(),
patchHeader: vi.fn(),
}));
vi.mock('../api/shipping.api', () => ({
getWorkspaceShippingOrderReviewCase: (...args: unknown[]) => Promise.resolve(api.getCase(...args)).then((value: any) => (
value && typeof value === 'object' && 'case' in value
? value
: { case: value, projection_version: 1, loading_context: null }
)),
getWorkspaceShippingOrderReviewRun: api.getRun,
getWorkspaceShippingOrderReviewQueue: api.getQueue,
getWorkspaceShippingOrderReviewEvidence: api.getEvidence,
getWorkspaceShippingOrderReviewPreview: api.getPreview,
getWorkspaceShippingOrderReviewIntakeParseContext: api.getIntakeParseContext,
getWorkspaceShippingOrderExtractionRun: api.getExtractionRun,
getWorkspaceShippingProcessingWorkItem: api.getProcessingWorkItem,
postWorkspaceShippingOrderReviewInventoryRoutingReroute: api.rerouteInventoryRouting,
confirmWorkspaceShippingOrderReviewCase: api.confirmCase,
patchWorkspaceShippingOrderReviewHeaderField: api.patchHeader,
patchWorkspaceShippingOrderReviewLineField: vi.fn(),
addWorkspaceShippingOrderReviewLine: vi.fn(),
copyWorkspaceShippingOrderReviewLine: vi.fn(),
deleteWorkspaceShippingOrderReviewLine: vi.fn(),
validateWorkspaceShippingOrderReviewDraft: api.validateDraft,
createWorkspaceShippingOrderReviewManualDraft: vi.fn(),
markWorkspaceShippingOrderReviewNonOrder: vi.fn(),
markWorkspaceShippingOrderReviewQualityIssue: vi.fn(),
reparseWorkspaceShippingOrderReviewDocument: api.reparseDocument,
createWorkspaceShippingOrderReviewReplacementIntake: vi.fn(),
createWorkspaceShippingOrderReviewReplacementRun: vi.fn(),
}));
const buildCase = (patch: Partial<ShippingOrderReviewCase> = {}): ShippingOrderReviewCase => ({
case_no: 'CASE-1',
run_no: 'RUN-1',
document: { id: 1, file_name: 'order.pdf' },
status: 'draft',
schema: { schema_version_id: 1, fields: [] },
draft: {
draft_version: 2,
header_values: {},
lines: [{ draft_line_id: 'line-1' }],
issues: [],
validation: {},
build_eligibility: {
can_build: false,
status: 'needs_review',
line_projections: [{
draft_line_id: 'line-1',
line_index: 0,
effective_reservation_id: '3000000001',
candidate_inventory_source_codes: ['DSV360_AWSDU', 'DSV360_AWSHK'],
routing_status: 'conflicted',
can_build: false,
block_reason: 'require_manual_review',
}],
},
},
available_actions: ['edit_draft', 'validate', 'confirm'],
...patch,
});
describe('useShippingOrderReview historical readonly', () => {
it('forces readonly when case status is superseded', () => {
expect(isReviewCaseHistorical(
{ case_no: 'CASE-OLD', status: 'superseded' },
{ current_case_no: 'CASE-NEW' },
)).toBe(true);
});
it('forces readonly when viewing non-current work item case', () => {
expect(isReviewCaseHistorical(
{ case_no: 'CASE-OLD', status: 'draft' },
{ current_case_no: 'CASE-NEW', version_replaced: true },
)).toBe(true);
});
it('does not treat peer PDF cases in the same run as historical', () => {
// 关键断言:同 Run 多 PDF 并列 Case,不得因 current_case_no 指向另一份而只读。
expect(isReviewCaseHistorical(
{ case_no: 'CASE-B', status: 'draft' },
{ current_case_no: 'CASE-A', version_replaced: false },
)).toBe(false);
expect(isReviewCaseHistorical(
{ case_no: 'CASE-B', status: 'ready' },
{ current_case_no: 'CASE-A' },
)).toBe(false);
});
it('allows edit when viewing current case', () => {
expect(isReviewCaseHistorical(
{ case_no: 'CASE-1', status: 'draft' },
{ current_case_no: 'CASE-1', version_replaced: false },
)).toBe(false);
});
it('forces readonly when session work item is closed', () => {
expect(isReviewWorkItemClosed({ lifecycle_status: 'closed', current_case_no: 'CASE-1' })).toBe(true);
expect(isReviewWorkItemClosed({ lifecycle_status: 'manual_upload_pending', current_case_no: 'CASE-1' })).toBe(false);
expect(isReviewReadOnly(
{ case_no: 'CASE-1', status: 'draft' },
{ current_case_no: 'CASE-1', lifecycle_status: 'closed' },
)).toBe(true);
});
it('maps confirmed case to non-closed lifecycle for post-confirm automation', () => {
// 关键断言:confirmed 不得映射 closed,否则统一进度轨道会被误判为终态。
expect(mapReviewContextLifecycleStatus('confirmed', null)).toBe('building_order');
expect(mapReviewContextLifecycleStatus('confirmed', 'inventory_matching')).toBe('inventory_matching');
expect(mapReviewContextLifecycleStatus('closed', null)).toBe('closed');
expect(mapReviewContextLifecycleStatus('quality_issue', null)).toBe('closed');
});
});
describe('draft version conflict helpers', () => {
it('recognizes REVIEW_DRAFT_VERSION_MISMATCH BusinessError', () => {
expect(isDraftVersionMismatchError(
new BusinessError({ message: 'stale', code: REVIEW_DRAFT_VERSION_MISMATCH }),
)).toBe(true);
expect(isDraftVersionMismatchError(
new BusinessError({ message: 'other', code: 'SHIPPING.REVIEW_FIELD_INVALID' }),
)).toBe(false);
expect(isDraftVersionMismatchError(new Error('nope'))).toBe(false);
});
it('summarizes local vs server draft version and header values', () => {
const local = {
status: 'draft',
draft: {
draft_version: 3,
issues: [],
header_values: { values: { 'po-id': { value: 'PO-LOCAL' } } },
},
} as unknown as ShippingOrderReviewCase;
const server = {
status: 'ready',
draft: {
draft_version: 5,
issues: [{ code: 'x' }],
header_values: { values: { 'po-id': { value: 'PO-SERVER' } } },
},
} as unknown as ShippingOrderReviewCase;
const lines = summarizeDraftConflictDiff(local, server);
expect(lines.some((line) => line.includes('draft_version'))).toBe(true);
expect(lines.some((line) => line.includes('header.po-id'))).toBe(true);
expect(lines.some((line) => line.includes('status'))).toBe(true);
});
});
describe('build eligibility helpers', () => {
it('blocks confirm only when can_build is explicitly false', () => {
expect(isBuildConfirmBlocked(null)).toBe(false);
expect(isBuildConfirmBlocked(undefined)).toBe(false);
expect(isBuildConfirmBlocked({ can_build: true, status: 'ready', line_projections: [] })).toBe(false);
expect(isBuildConfirmBlocked({ can_build: false, status: 'needs_review', line_projections: [] })).toBe(true);
});
});
describe('useShippingOrderReview build eligibility writes', () => {
beforeEach(() => {
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
items: [{ case_no: 'CASE-1', status: 'draft', issue_count: 0 }],
});
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{ case_no: 'CASE-1', document_id: 1, status: 'draft', issue_count: 0, available_actions: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockRejectedValue(new Error('preview unavailable'));
api.getIntakeParseContext.mockImplementation(async (caseNo: string) => ({
case_no: caseNo,
attachment: {
document_id: caseNo === 'CASE-2' ? 2 : 1,
filename: caseNo === 'CASE-2' ? 'second.pdf' : 'order.pdf',
mime_type: 'application/pdf',
preview_kind: 'pdf',
},
email: null,
}));
api.getProcessingWorkItem.mockRejectedValue(
Object.assign(new Error('not found'), { name: 'BusinessError', status: 404, code: 'NOT_FOUND' }),
);
api.getCase.mockResolvedValue(buildCase());
});
afterEach(() => {
vi.clearAllMocks();
});
it('exposes buildEligibility and automatic routing recovery lines from active case draft', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(review.buildEligibility.value?.can_build).toBe(false);
expect(review.canConfirmBuild.value).toBe(false);
expect(review.routingRecoveryLines.value).toHaveLength(1);
expect(review.routingRecoveryLines.value[0]?.draft_line_id).toBe('line-1');
});
it('does not prefetch PDF preview on load or selectCase; ensurePreviewLoaded fetches on demand', async () => {
// 关键断言:进入工作台/切换文档不触发 preview 审计与下载。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(api.getPreview).not.toHaveBeenCalled();
await review.selectCase('CASE-1');
expect(api.getPreview).not.toHaveBeenCalled();
const blob = new Blob(['%PDF'], { type: 'application/pdf' });
api.getPreview.mockResolvedValue(blob);
const ok = await review.ensurePreviewLoaded('CASE-1');
expect(ok).toBe(true);
expect(api.getPreview).toHaveBeenCalledTimes(1);
expect(review.previewUrl.value).toMatch(/^blob:/);
});
it('applies the latest Case returned by save and validate', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
api.validateDraft.mockResolvedValue({
case: buildCase({
draft: { ...buildCase().draft!, draft_version: 3 },
}),
resume_outcome: { outcome: 'auto_create_enqueued' },
});
const resume = await review.validate();
expect(api.validateDraft).toHaveBeenCalledWith('CASE-1', 2);
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
expect(resume).toEqual({ outcome: 'auto_create_enqueued' });
});
it('tracks an enqueued validation until the worker creates the formal order task', async () => {
vi.useFakeTimers();
const queuedCase = buildCase({
status: 'ready',
automation: { status: 'queued' },
});
const confirmedCase = buildCase({
status: 'confirmed',
order_task_no: 'OT-1',
confirmed_task_no: 'OT-1',
automation: { status: 'running' },
});
api.validateDraft.mockResolvedValue({
case: queuedCase,
resume_outcome: { outcome: 'auto_create_enqueued' },
});
api.getCase.mockResolvedValueOnce(buildCase()).mockResolvedValue(confirmedCase);
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 1, completed: 0 },
items: [{
case_no: 'CASE-1', document_id: 1, status: 'confirmed',
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [],
}],
});
api.getExtractionRun.mockResolvedValue({ run_no: 'RUN-1', status: 'completed' });
api.getProcessingWorkItem.mockResolvedValue({
work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation',
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.validate();
await vi.advanceTimersByTimeAsync(0);
expect(review.workflowProgressPolling.value).toBe(true);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-1');
expect(api.getProcessingWorkItem).toHaveBeenCalledWith('order_task', 'OT-1');
review.stopWorkflowProgressPolling();
vi.useRealTimers();
});
it('does not treat a field edit revalidation as a formal-order creation request', async () => {
vi.useFakeTimers();
const revalidatingCase = buildCase({
status: 'draft',
automation: { status: 'queued' },
});
api.patchHeader.mockResolvedValue(revalidatingCase);
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.patchHeader('ship_to_name', '新收货方');
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
// 字段编辑后的 queued 是异步重校验,不是用户已确认的建单请求。
expect(api.getCase).toHaveBeenCalledTimes(1);
expect(review.workflowProgressPolling.value).toBe(false);
vi.useRealTimers();
});
it('refreshes the current Case silently without entering the PDF-switch loading state', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
const blob = new Blob(['%PDF'], { type: 'application/pdf' });
api.getPreview.mockResolvedValue(blob);
await review.ensurePreviewLoaded('CASE-1');
api.getCase.mockResolvedValue(buildCase({
draft: { ...buildCase().draft!, draft_version: 3 },
}));
await review.reloadLatestDraft();
// Gate 操作后的同步不能冒充 PDF 切换:保留工作面和已加载预览,不展示大骨架。
expect(review.caseSwitchLoading.value).toBe(false);
expect(review.caseSwitchFailed.value).toBe(false);
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
expect(review.previewCaseNo.value).toBe('CASE-1');
expect(review.previewUrl.value).toMatch(/^blob:/);
});
it('refreshReviewQueue reloads lifecycle stages without touching Case or PDF preview', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
const blob = new Blob(['%PDF'], { type: 'application/pdf' });
api.getPreview.mockResolvedValue(blob);
await review.ensurePreviewLoaded('CASE-1');
const previewBefore = review.previewUrl.value;
const caseCallsBefore = api.getCase.mock.calls.length;
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 0, completed: 1 },
items: [{
case_no: 'CASE-1',
document_id: 1,
status: 'confirmed',
issue_count: 0,
available_actions: [],
lifecycle_stage: 'upload_complete',
}],
});
const ok = await review.refreshReviewQueue();
// 左侧队列阶段必须可单独刷新;不得顺带切换 Case 或清掉已加载预览。
expect(ok).toBe(true);
expect(review.reviewQueue.value?.items[0]?.lifecycle_stage).toBe('upload_complete');
expect(api.getCase.mock.calls.length).toBe(caseCallsBefore);
expect(review.previewUrl.value).toBe(previewBefore);
expect(review.caseSwitchLoading.value).toBe(false);
});
it('discards a stale preview success after Case A switches to Case B', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let resolveA: ((value: Blob) => void) | null = null;
let resolveB: ((value: Blob) => void) | null = null;
api.getPreview.mockImplementation((caseNo: string) => new Promise<Blob>((resolve) => {
if (caseNo === 'CASE-1') resolveA = resolve;
if (caseNo === 'CASE-2') resolveB = resolve;
}));
const previewA = review.ensurePreviewLoaded('CASE-1');
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await review.selectCase('CASE-2');
// 关键断言:切换立即清除旧 URL;B 必须启动独立预览请求,不能复用 A in-flight。
expect(review.previewUrl.value).toBe('');
const previewB = review.ensurePreviewLoaded('CASE-2');
expect(api.getPreview).toHaveBeenNthCalledWith(1, 'CASE-1');
expect(api.getPreview).toHaveBeenNthCalledWith(2, 'CASE-2');
resolveA?.(new Blob(['A'], { type: 'application/pdf' }));
await expect(previewA).resolves.toBe(false);
expect(review.previewUrl.value).toBe('');
resolveB?.(new Blob(['B'], { type: 'application/pdf' }));
await expect(previewB).resolves.toBe(true);
expect(review.previewCaseNo.value).toBe('CASE-2');
expect(review.previewUrl.value).toMatch(/^blob:/);
});
it('discards a stale preview failure after Case A switches to Case B', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let rejectA: ((reason?: unknown) => void) | null = null;
let resolveB: ((value: Blob) => void) | null = null;
api.getPreview.mockImplementation((caseNo: string) => new Promise<Blob>((resolve, reject) => {
if (caseNo === 'CASE-1') rejectA = reject;
if (caseNo === 'CASE-2') resolveB = resolve;
}));
const previewA = review.ensurePreviewLoaded('CASE-1');
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await review.selectCase('CASE-2');
const previewB = review.ensurePreviewLoaded('CASE-2');
rejectA?.(new Error('stale preview failure'));
await expect(previewA).resolves.toBe(false);
// 关键断言:A 的失败不能把 B 标为预览失败或清空 B 的进行态。
expect(review.previewLoadFailed.value).toBe(false);
expect(review.previewLoading.value).toBe(true);
resolveB?.(new Blob(['B'], { type: 'application/pdf' }));
await expect(previewB).resolves.toBe(true);
expect(review.previewCaseNo.value).toBe('CASE-2');
expect(review.previewLoadFailed.value).toBe(false);
});
it('loads intake parse context on demand for the active Case and clears it before a new Case resolves', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(api.getIntakeParseContext).not.toHaveBeenCalled();
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(api.getIntakeParseContext).toHaveBeenCalledWith('CASE-1');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
api.getCase.mockImplementation((caseNo: string) => caseNo === 'CASE-2'
? new Promise<ShippingOrderReviewCase>((resolve) => { resolveCase = resolve; })
: Promise.resolve(buildCase({ case_no: caseNo })));
const pending = review.selectCase('CASE-2');
// 关键断言:切换附件期间不得展示 CASE-1 的 EML/附件上下文。
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoading.value).toBe(false);
resolveCase?.(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await pending;
await review.ensureIntakeParseContextLoaded('CASE-2');
expect(api.getIntakeParseContext).toHaveBeenLastCalledWith('CASE-2');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-2');
});
it('does not retain an older intake context when the next Case context request fails', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await review.selectCase('CASE-2');
api.getIntakeParseContext.mockRejectedValueOnce(new Error('context unavailable'));
await expect(review.ensureIntakeParseContextLoaded('CASE-2')).resolves.toBe(false);
// 关键断言:失败只显示本次错误,不得回退为上一附件的邮件正文。
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoadFailed.value).toBe(true);
});
it('loads intake parse context for a formal-downstream Case while activeCase stays unloaded', async () => {
// 选法 2:正式下游(货代上传等)切 PDF 不拉 Case/Evidence,activeCase 保持 null。
// 关键断言:接收解析工作面回看已完成阶段时,上下文仍必须按 requestedCaseNo 拉取,
// 不得因 activeCase 为 null 静默跳过(否则面板渲染成空白)。
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 0, completed: 1 },
items: [{
case_no: 'CASE-2', document_id: 2, status: 'confirmed',
has_formal_ot: true,
lifecycle_stage: 'freight_upload',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available' },
{ code: 'order_review', state: 'available' },
{ code: 'fulfillment_prep', state: 'available' },
{ code: 'freight_upload', state: 'current' },
],
}],
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-2');
api.getCase.mockClear();
api.getEvidence.mockClear();
await review.selectCase('CASE-2');
// 选法 2 关键断言:正式下游切换不拉复核 Case/Evidence,activeCase 为空。
expect(api.getCase).not.toHaveBeenCalled();
expect(review.activeCase.value).toBeNull();
expect(review.requestedCaseNo.value).toBe('CASE-2');
await expect(review.ensureIntakeParseContextLoaded('CASE-2')).resolves.toBe(true);
expect(api.getIntakeParseContext).toHaveBeenLastCalledWith('CASE-2');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-2');
expect(review.intakeParseLoading.value).toBe(false);
expect(review.intakeParseLoadFailed.value).toBe(false);
});
it('keeps the latest same-Case intake context when an older success resolves last', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let resolveFirst: ((value: Record<string, unknown>) => void) | null = null;
let resolveSecond: ((value: Record<string, unknown>) => void) | null = null;
api.getIntakeParseContext
.mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))
.mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));
const first = review.ensureIntakeParseContextLoaded('CASE-1');
const second = review.ensureIntakeParseContextLoaded('CASE-1');
resolveSecond?.({ case_no: 'CASE-1', attachment: { document_id: 2, filename: 'latest.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' }, email: null });
await second;
resolveFirst?.({ case_no: 'CASE-1', attachment: { document_id: 1, filename: 'stale.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' }, email: null });
await first;
// 关键断言:同一 Case 的旧成功响应不可覆盖后发请求的附件/EML。
expect(review.intakeParseContext.value?.attachment.filename).toBe('latest.pdf');
expect(review.intakeParseLoadFailed.value).toBe(false);
});
it('keeps the latest same-Case success when an older request fails last', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let rejectFirst: ((reason?: unknown) => void) | null = null;
let resolveSecond: ((value: Record<string, unknown>) => void) | null = null;
api.getIntakeParseContext
.mockImplementationOnce(() => new Promise((_, reject) => { rejectFirst = reject; }))
.mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));
const first = review.ensureIntakeParseContextLoaded('CASE-1');
const second = review.ensureIntakeParseContextLoaded('CASE-1');
resolveSecond?.({ case_no: 'CASE-1', attachment: { document_id: 2, filename: 'latest.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' }, email: null });
await second;
rejectFirst?.(new Error('stale failure'));
await first;
// 关键断言:旧失败不得清空新成功结果或重新标记本次加载失败。
expect(review.intakeParseContext.value?.attachment.filename).toBe('latest.pdf');
expect(review.intakeParseLoadFailed.value).toBe(false);
expect(review.intakeParseLoading.value).toBe(false);
});
it('clears activeCase immediately while switching and keeps empty shell on failure (UI-01)', async () => {
// 关键断言:loading 期间不得保留旧 Case 业务对象;失败后也不得回显旧值。
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
const caseOld = buildCase({ case_no: 'CASE-OLD', document: { id: 1, file_name: 'old.pdf' } });
const caseNew = buildCase({ case_no: 'CASE-NEW', document: { id: 2, file_name: 'new.pdf' } });
api.getCase.mockImplementation((caseNo: string) => {
if (caseNo === 'CASE-NEW') {
return new Promise<ShippingOrderReviewCase>((resolve) => {
resolveCase = resolve;
});
}
return Promise.resolve(caseOld);
});
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
await review.selectCase('CASE-OLD');
expect(review.activeCase.value?.case_no).toBe('CASE-OLD');
const pending = review.selectCase('CASE-NEW');
expect(review.caseSwitchLoading.value).toBe(true);
// 切换期间保留已确认快照,避免整个工作台清空。
expect(review.activeCase.value?.case_no).toBe('CASE-OLD');
expect(review.requestedCaseNo.value).toBe('CASE-NEW');
resolveCase?.(caseNew);
await pending;
expect(review.activeCase.value?.case_no).toBe('CASE-NEW');
expect(review.caseSwitchLoading.value).toBe(false);
});
it('keeps empty skeleton when selectCase fails (UI-01 failure mode 2)', async () => {
api.getCase.mockResolvedValueOnce(buildCase({ case_no: 'CASE-OLD' }));
api.getEvidence.mockResolvedValueOnce({ items: [] });
const review = useShippingOrderReview();
await review.selectCase('CASE-OLD');
expect(review.activeCase.value?.case_no).toBe('CASE-OLD');
api.getCase.mockRejectedValueOnce(new Error('boom'));
api.getEvidence.mockRejectedValueOnce(new Error('boom'));
await review.selectCase('CASE-FAIL');
expect(review.caseSwitchFailed.value).toBe(true);
// 新请求失败时仍保留最近一次稳定 Case,避免白屏。
expect(review.activeCase.value?.case_no).toBe('CASE-OLD');
expect(review.requestedCaseNo.value).toBe('CASE-FAIL');
});
it('beginCrossRunSwitch keeps workbench shell but drops previous OT projection authority', async () => {
// 关键断言:跨 Run 不清空 activeCase(避免大骨架),但必须撤销旧 OT,防止右卡/库存串味。
api.getCase.mockResolvedValueOnce(buildCase({ case_no: 'CASE-OLD' }));
api.getEvidence.mockResolvedValueOnce({ items: [] });
const review = useShippingOrderReview();
await review.selectCase('CASE-OLD');
review.reviewProgressContext.value = {
item_no: 'WI-1',
workflow_no: 'WF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_version_no: 1,
current_run_no: 'RUN-1',
current_case_no: 'CASE-OLD',
user_task_no: 'OT-OLD',
user_task_authoritative: true,
lifecycle_status: 'fulfillment_prep',
current_stage: 'fulfillment_prep',
lock_version: 1,
} as any;
review.beginCrossRunSwitch('CASE-NEW');
expect(review.caseSwitchLoading.value).toBe(true);
expect(review.requestedCaseNo.value).toBe('CASE-NEW');
expect(review.activeCase.value?.case_no).toBe('CASE-OLD');
expect(review.reviewProgressContext.value?.current_case_no).toBe('CASE-NEW');
expect(review.reviewProgressContext.value?.user_task_no).toBeNull();
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
});
it('beginCrossRunSwitch drops the previous file intake context and rejects its stale success', async () => {
// 关键断言:跨 Run 切文件(如 PO_6075309 → PO_6075316)切换即清空接收解析上下文,
// 迟到的旧 Case 上下文成功响应也不得把旧附件名/邮件正文写回新文件工作面。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(review.intakeParseContext.value?.attachment.filename).toBe('order.pdf');
let resolveStale: ((value: Record<string, unknown>) => void) | null = null;
api.getIntakeParseContext.mockImplementationOnce(
() => new Promise((resolve) => { resolveStale = resolve; }),
);
const pendingStale = review.ensureIntakeParseContextLoaded('CASE-1');
review.beginCrossRunSwitch('CASE-2');
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoading.value).toBe(false);
expect(review.intakeParseLoadFailed.value).toBe(false);
resolveStale?.({
case_no: 'CASE-1',
attachment: { document_id: 1, filename: 'order.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' },
email: null,
});
await pendingStale;
expect(review.intakeParseContext.value).toBeNull();
});
it('load fast path drops the stale intake context when the target Case changes', async () => {
// 关键断言:稳定工作台直达 load 换 Case(重解析落位/重试等入口)同样撤销旧上下文。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await review.load('RUN-1', 'CASE-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoading.value).toBe(false);
});
it('discards stale selectCase responses when switching PDFs quickly', async () => {
// 关键断言:A 后发先至不得覆盖后选的 B;切换时先清空瞬态。
let resolveA: ((value: ShippingOrderReviewCase) => void) | null = null;
const caseA = buildCase({ case_no: 'CASE-A', document: { id: 1, file_name: 'a.pdf' } });
const caseB = buildCase({ case_no: 'CASE-B', document: { id: 2, file_name: 'b.pdf' } });
api.getCase.mockImplementation((caseNo: string) => {
if (caseNo === 'CASE-A') {
return new Promise<ShippingOrderReviewCase>((resolve) => {
resolveA = resolve;
});
}
return Promise.resolve(caseB);
});
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
const pendingA = review.selectCase('CASE-A');
await review.selectCase('CASE-B');
expect(review.activeCase.value?.case_no).toBe('CASE-B');
expect(review.requestedCaseNo.value).toBe('CASE-B');
resolveA?.(caseA);
await pendingA;
expect(review.activeCase.value?.case_no).toBe('CASE-B');
});
it('aborts the previous Case snapshot request when the user immediately selects another PDF', async () => {
let firstSignal: AbortSignal | undefined;
let firstEvidenceSignal: AbortSignal | undefined;
api.getCase.mockImplementation((caseNo: string, signal?: AbortSignal) => {
if (caseNo !== 'CASE-A') return Promise.resolve(buildCase({ case_no: caseNo }));
firstSignal = signal;
return new Promise((_, reject) => {
signal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')));
});
});
api.getEvidence.mockImplementation((_caseNo: string, signal?: AbortSignal) => {
if (!firstEvidenceSignal) firstEvidenceSignal = signal;
return Promise.resolve({ items: [] });
});
const review = useShippingOrderReview();
const pendingA = review.selectCase('CASE-A');
await review.selectCase('CASE-B');
// 关键断言:快速跳过 A 时必须释放其仍在途的快照读取,不能只在 UI 丢弃迟到结果。
expect(firstSignal?.aborted).toBe(true);
expect(firstEvidenceSignal?.aborted).toBe(true);
await expect(pendingA).resolves.toBeUndefined();
expect(review.activeCase.value?.case_no).toBe('CASE-B');
});
it('keeps the latest Run and Case when an older load response arrives last', async () => {
// 关键断言:重识别跳转新版本后,旧 Run 的迟到响应不得覆盖新版工作面。
let resolveOldRun: ((value: Record<string, unknown>) => void) | null = null;
api.getRun.mockImplementation((runNo: string) => (runNo === 'RUN-OLD'
? new Promise<Record<string, unknown>>((resolve) => { resolveOldRun = resolve; })
: Promise.resolve({
run_no: runNo,
summary: {},
items: [{ case_no: 'CASE-NEW', document_id: 2, status: 'draft', issue_count: 0 }],
})));
api.getQueue.mockImplementation((runNo: string) => Promise.resolve({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{
case_no: runNo === 'RUN-OLD' ? 'CASE-OLD' : 'CASE-NEW',
document_id: runNo === 'RUN-OLD' ? 1 : 2,
source_run_no: runNo,
status: 'draft', issue_count: 0, available_actions: [],
}],
}));
api.getCase.mockImplementation((caseNo: string) => Promise.resolve(buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-OLD' ? 'RUN-OLD' : 'RUN-NEW',
document: {
id: caseNo === 'CASE-OLD' ? 1 : 2,
file_name: caseNo === 'CASE-OLD' ? 'old.pdf' : 'new.pdf',
},
})));
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
const olderLoad = review.load('RUN-OLD', 'CASE-OLD');
await Promise.resolve();
await review.load('RUN-NEW', 'CASE-NEW');
resolveOldRun?.({
run_no: 'RUN-OLD',
summary: {},
items: [{ case_no: 'CASE-OLD', document_id: 1, status: 'superseded', issue_count: 0 }],
});
await olderLoad;
expect(review.reviewRun.value?.run_no).toBe('RUN-NEW');
expect(review.activeCase.value?.case_no).toBe('CASE-NEW');
});
it('marks only the first successful Run read as initial loading', async () => {
// 关键断言:后续 Run 切换仍可有 Run 读取态,但不能再被页面当作首次整页加载。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(review.initialLoading.value).toBe(false);
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => {
resolveRun = resolve;
}));
const pending = review.load('RUN-2', 'CASE-2');
expect(review.runLoading.value).toBe(true);
expect(review.initialLoading.value).toBe(false);
resolveRun?.({
run_no: 'RUN-2', summary: {},
items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }],
});
await pending;
});
it('shows the cross-Run target Case when its snapshot arrives before slow navigation summaries', async () => {
// 关键断言:目标 Case/Evidence 是当前 PDF 的事实源;慢 Run/Queue 仅延后导航校准,
// 绝不能继续阻塞用户看到已完成读取的目标文件。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
const previousQueue = review.reviewQueue.value;
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
let resolveQueue: ((value: Record<string, unknown>) => void) | null = null;
let resolveCase: ((value: ShippingOrderReviewCase) => void) | null = null;
let resolveEvidence: ((value: { items: unknown[] }) => void) | null = null;
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveRun = resolve; }));
api.getQueue.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveQueue = resolve; }));
api.getCase.mockImplementationOnce(() => new Promise<ShippingOrderReviewCase>((resolve) => { resolveCase = resolve; }));
api.getEvidence.mockImplementationOnce(() => new Promise<{ items: unknown[] }>((resolve) => { resolveEvidence = resolve; }));
const pending = review.load('RUN-2', 'CASE-2');
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
expect(review.reviewQueue.value).toBe(previousQueue);
expect(review.activeCase.value?.case_no).toBe('CASE-1');
await vi.waitFor(() => expect(resolveRun).toBeTypeOf('function'));
await vi.waitFor(() => expect(resolveQueue).toBeTypeOf('function'));
await vi.waitFor(() => expect(resolveCase).toBeTypeOf('function'));
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
expect(review.activeCase.value?.case_no).toBe('CASE-1');
resolveCase?.(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2', document: { id: 2, file_name: 'second.pdf' } }));
await vi.waitFor(() => expect(resolveEvidence).toBeTypeOf('function'));
resolveEvidence?.({ items: [] });
await vi.waitFor(() => expect(review.activeCase.value?.case_no).toBe('CASE-2'));
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
expect(review.reviewQueue.value).toBe(previousQueue);
resolveRun?.({ run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }] });
resolveQueue?.({ summary: { total: 1, needs_action: 1, processing: 0, completed: 0 }, items: [{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }] });
await pending;
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
expect(review.reviewQueue.value?.items[0]?.case_no).toBe('CASE-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
});
it('starts the preferred Case and Evidence reads without waiting for a slow cross-Run summary', async () => {
// 关键断言:导航已提供目标 Case 时,Run/Queue 摘要不能把详情读取串行化。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
let resolveRun: ((value: Record<string, unknown>) => void) | null = null;
let resolveQueue: ((value: Record<string, unknown>) => void) | null = null;
api.getCase.mockClear();
api.getEvidence.mockClear();
api.getRun.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveRun = resolve; }));
api.getQueue.mockImplementationOnce(() => new Promise<Record<string, unknown>>((resolve) => { resolveQueue = resolve; }));
const pending = review.load('RUN-2', 'CASE-2');
await vi.waitFor(() => expect(api.getCase).toHaveBeenCalledWith('CASE-2'));
await vi.waitFor(() => expect(api.getEvidence).toHaveBeenCalledWith('CASE-2'));
await vi.waitFor(() => expect(review.runLoading.value).toBe(true));
expect(review.activeCase.value?.case_no).toBe('CASE-1');
resolveRun?.({ run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', document_id: 2, status: 'draft', issue_count: 0 }] });
resolveQueue?.({ summary: { total: 1, needs_action: 1, processing: 0, completed: 0 }, items: [{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }] });
await pending;
});
it('keeps the stable workbench on a cross-Run load failure', async () => {
// 关键断言:目标 Run 读取失败时,用户可继续查看上一份稳定工作面,不能退回整页空白。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
api.getCase.mockResolvedValueOnce(buildCase({ case_no: 'CASE-2', run_no: 'RUN-2' }));
api.getEvidence.mockResolvedValueOnce({ items: [] });
api.getRun.mockImplementationOnce(() => Promise.reject(new Error('target unavailable')));
api.getQueue.mockImplementationOnce(() => Promise.reject(new Error('target unavailable')));
await review.load('RUN-2', 'CASE-2');
expect(review.loadFailed.value).toBe(false);
expect(review.runSwitchFailed.value).toBe(true);
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
expect(review.reviewQueue.value?.items[0]?.case_no).toBe('CASE-1');
expect(review.activeCase.value?.case_no).toBe('CASE-1');
});
it('blocks confirm when build eligibility cannot build', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await expect(review.confirm()).rejects.toMatchObject({
code: REVIEW_BUILD_ELIGIBILITY_BLOCKED,
});
expect(api.confirmCase).not.toHaveBeenCalled();
});
it('starts workflow progress polling after successful confirm', async () => {
vi.useFakeTimers();
const readyCase: ShippingOrderReviewCase = {
case_no: 'CASE-1',
run_no: 'RUN-1',
document: { id: 1, file_name: 'a.pdf' },
status: 'ready',
schema: { schema_version_id: 1, fields: [] },
draft: {
draft_version: 2,
header_values: { values: {} },
lines: [],
issues: [],
validation: {},
build_eligibility: {
can_build: true,
status: 'ready',
line_projections: [],
},
},
available_actions: ['edit_draft', 'confirm'],
};
api.getCase.mockResolvedValue(readyCase);
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'ready', available_actions: ['confirm'] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockResolvedValue({ preview_url: '' });
api.getProcessingWorkItem.mockResolvedValueOnce({
work_item_no: 'OT-1',
status: 'building_order',
});
api.getProcessingWorkItem.mockResolvedValueOnce({
work_item_no: 'OT-1',
status: 'completed',
});
api.confirmCase.mockResolvedValue({
task_no: 'SN-1',
order_task_no: 'OT-1',
shipping_notice_no: 'SN-1',
idempotent_replay: false,
workflow_id: 'WF-1',
order_task_no: 'OT-1',
shipping_notice_no: 'SN-1',
case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' },
auto_progress_started: true,
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
const response = await review.confirm();
expect(response?.order_task_no).toBe('OT-1');
expect(response?.shipping_notice_no || response?.task_no).toBeTruthy();
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-1');
expect(review.showWorkflowProgress.value).toBe(true);
expect(review.workflowProgressPolling.value).toBe(true);
expect(api.getProcessingWorkItem).toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(review.workflowProgressPolling.value).toBe(false);
review.stopWorkflowProgressPolling();
vi.useRealTimers();
});
it('stops workflow progress polling once the unified work item is interrupted (waiting_human)', async () => {
vi.useFakeTimers();
const readyCase = buildCase({
status: 'ready',
draft: {
...buildCase().draft!,
build_eligibility: { can_build: true, status: 'ready', line_projections: [] },
},
});
const confirmedCase = {
...readyCase,
status: 'confirmed',
confirmed_task_no: 'OT-1',
order_task_no: 'OT-1',
has_formal_ot: true,
};
api.getCase.mockResolvedValue(confirmedCase);
api.getRun.mockResolvedValue({
run_no: 'RUN-1', summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'ready', available_actions: ['confirm'] }],
});
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{
case_no: 'CASE-1', document_id: 1, source_run_no: 'RUN-1', status: 'confirmed',
lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
}],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockResolvedValue({ preview_url: '' });
api.getProcessingWorkItem.mockResolvedValue({
workItemNo: 'OT-1',
status: 'waiting_human',
userStatus: 'waiting_human',
stage: 'inventory_matching',
currentGate: { gateCode: 'inventory_matching', status: 'blocked_manual' },
uiState: {
status: 'waiting_human',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current' }],
},
});
api.confirmCase.mockResolvedValue({
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
case: confirmedCase, auto_progress_started: true,
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
const queueCallsBeforeConfirm = api.getQueue.mock.calls.length;
await review.confirm();
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
// 中断(waiting_human)停轮询前须刷新 Case/Queue,否则自动跳阶段拿不到 lifecycle。
expect(api.getQueue.mock.calls.length).toBeGreaterThan(queueCallsBeforeConfirm);
expect(review.workflowProgressPolling.value).toBe(false);
review.stopWorkflowProgressPolling();
vi.useRealTimers();
});
it('refreshes the active Case and queue while post-confirm automation is still active', async () => {
vi.useFakeTimers();
const readyCase = buildCase({
status: 'ready',
draft: {
...buildCase().draft!,
build_eligibility: { can_build: true, status: 'ready', line_projections: [] },
},
});
const runningCase = {
...readyCase,
status: 'confirmed',
confirmed_task_no: 'OT-1',
automation: { status: 'running', phase: 'post_ot_progress' },
};
api.getCase
.mockResolvedValueOnce(readyCase)
.mockResolvedValue(runningCase);
api.getRun.mockResolvedValue({
run_no: 'RUN-1', summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'confirmed', lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [] }],
});
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 1, completed: 0 },
items: [{ case_no: 'CASE-1', document_id: 1, source_run_no: 'RUN-1', status: 'confirmed', lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getProcessingWorkItem.mockResolvedValue({
work_item_no: 'OT-1', status: 'processing', stage: 'inventory_preparation',
currentGate: { gateCode: 'inventory_preparation', status: 'running' },
});
api.confirmCase.mockResolvedValue({
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
case: runningCase, auto_progress_started: true,
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
await review.confirm();
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
// 关键断言:活动窗口内同步刷新 Case 与队列,让顶部五阶段读取到后端已推进的通知准备。
expect(api.getCase.mock.calls.length).toBeGreaterThanOrEqual(2);
expect(api.getQueue.mock.calls.length).toBeGreaterThanOrEqual(2);
expect(review.activeCase.value?.confirmed_task_no).toBe('OT-1');
expect(review.reviewQueue.value?.items[0]?.lifecycle_stage).toBe('fulfillment_prep');
review.stopWorkflowProgressPolling();
vi.useRealTimers();
});
it('keeps polling after a recoverable RPA failure so a later callback can refresh the workflow', async () => {
vi.useFakeTimers();
const onWorkflowRefresh = vi.fn();
const readyCase: ShippingOrderReviewCase = {
case_no: 'CASE-1', run_no: 'RUN-1', document: { id: 1, file_name: 'a.pdf' }, status: 'ready',
schema: { schema_version_id: 1, fields: [] },
draft: { draft_version: 2, header_values: { values: {} }, lines: [], issues: [], validation: {}, build_eligibility: { can_build: true, status: 'ready', line_projections: [] } },
available_actions: ['edit_draft', 'confirm'],
};
api.getCase.mockResolvedValue(readyCase);
api.getRun.mockResolvedValue({ run_no: 'RUN-1', summary: {}, items: [{ case_no: 'CASE-1', document_id: 1, status: 'ready', available_actions: ['confirm'] }] });
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockResolvedValue({ preview_url: '' });
api.getProcessingWorkItem
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'building_order' })
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'retryable', retryable: true })
.mockResolvedValueOnce({ work_item_no: 'OT-1', status: 'completed' });
api.confirmCase.mockResolvedValue({
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
workflow_id: 'WF-1', case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' }, auto_progress_started: true,
});
const review = useShippingOrderReview({ onWorkflowRefresh });
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
await review.confirm();
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(onWorkflowRefresh).toHaveBeenCalled();
// RPA 可重试失败不是工作流关闭;必须继续读取后续成功回调的 Projection。
expect(review.workflowProgressPolling.value).toBe(true);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(review.workflowProgressPolling.value).toBe(false);
review.stopWorkflowProgressPolling();
vi.useRealTimers();
});
it('does not fall back to extraction run root OT when case has candidate binding', async () => {
api.getCase.mockResolvedValue(buildCase({
candidate_id: 42,
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
order_task_no: 'OT-CAND',
}));
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'draft', available_actions: ['edit_draft'] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-CAND');
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(true);
});
it('uses confirmed OT number when case order_task_no is empty but confirmed_task_no is OT-prefixed', async () => {
// 关键断言:正式任务下游 Case.order_task_no 可能暂空,但 confirmed_task_no 已是 OT 时
// 仍须启动 work-item 投影;否则右卡永久「正在获取最新状态 / 待机」。
api.getCase.mockResolvedValue(buildCase({
candidate_id: 42,
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
status: 'confirmed',
has_formal_ot: true,
confirmed_task_no: 'OT-CONFIRMED-ONLY',
order_task_no: null,
}));
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'confirmed', available_actions: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-CONFIRMED-ONLY');
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(true);
});
it('does not treat SN confirmed_task_no as order_task work-item key', async () => {
api.getCase.mockResolvedValue(buildCase({
candidate_id: 42,
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
status: 'confirmed',
has_formal_ot: true,
confirmed_task_no: 'SN-NOTICE-1',
order_task_no: null,
}));
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'confirmed', available_actions: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
expect(review.reviewProgressContext.value?.user_task_no).toBeNull();
});
it('leaves OT unset while waiting for a reparse Case when candidate-bound case lacks order_task_no', async () => {
vi.useFakeTimers();
api.getCase.mockResolvedValue(buildCase({
candidate_id: 42,
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
}));
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'reparse_pending', available_actions: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.reparseDocument.mockResolvedValue({
run: { run_no: 'RUN-2' },
reused: false,
});
api.getExtractionRun.mockResolvedValue({
run_no: 'RUN-2',
status: 'extracting',
user_task_no: 'OT-ROOT',
current_activity: { user_visible_stage: 'extracting' },
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
await review.reparseDocument('layout_issue');
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(review.reviewProgressContext.value?.user_task_no).toBeNull();
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
review.stopReparseCaseRefreshPolling();
vi.useRealTimers();
});
it('loads the new review version when completed reparse has activated its Stream Case', async () => {
vi.useFakeTimers();
let reparsePollCount = 0;
api.reparseDocument.mockImplementation(async () => ({
run: { run_no: 'RUN-2', items: [], summary: {} },
reused: false,
}));
api.getRun.mockImplementation(async (runNo: string) => ({
run_no: runNo,
status: runNo === 'RUN-2' ? 'completed' : 'review_required',
summary: {},
items: [{ case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1', status: 'draft', issue_count: 0 }],
}));
api.getQueue.mockImplementation(async (runNo: string) => ({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{
case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1',
document_id: 1,
source_run_no: runNo,
status: 'draft', issue_count: 0, available_actions: [],
}],
}));
api.getExtractionRun.mockImplementation(async (runNo: string) => {
reparsePollCount += 1;
const ready = runNo === 'RUN-2' && reparsePollCount >= 2;
return {
run_no: runNo,
status: ready ? 'completed' : 'extracting',
current_activity: { user_visible_stage: ready ? 'completed' : 'extracting' },
};
});
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
}));
const onReparseCaseReady = vi.fn();
const review = useShippingOrderReview({ onReparseCaseReady });
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
await review.reparseDocument('document_quality');
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
// 关键断言:只有新版 Case 真正落到 activeCase 后,页面才接收可同步深链的目标。
expect(onReparseCaseReady).toHaveBeenCalledWith({ runNo: 'RUN-2', caseNo: 'CASE-2', documentId: 1 });
review.stopReparseCaseRefreshPolling();
vi.useRealTimers();
});
it('loads a partially completed reparse result without a legacy read-only progress state', async () => {
vi.useFakeTimers();
api.reparseDocument.mockImplementation(async () => ({
run: { run_no: 'RUN-PARTIAL', items: [], summary: {} },
reused: false,
}));
api.getRun.mockImplementation(async (runNo: string) => ({
run_no: runNo,
status: runNo === 'RUN-PARTIAL' ? 'partially_completed' : 'review_required',
summary: {},
items: [{ case_no: runNo === 'RUN-PARTIAL' ? 'CASE-PARTIAL' : 'CASE-1', status: 'draft', issue_count: 0 }],
}));
api.getExtractionRun.mockImplementation(async (runNo: string) => ({
run_no: runNo,
status: runNo === 'RUN-PARTIAL' ? 'partially_completed' : 'review_required',
current_activity: { user_visible_stage: 'review_required' },
}));
api.getQueue.mockImplementation(async (runNo: string) => ({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{
case_no: runNo === 'RUN-PARTIAL' ? 'CASE-PARTIAL' : 'CASE-1',
document_id: 1,
source_run_no: runNo,
status: 'draft', issue_count: 0, available_actions: [],
}],
}));
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-PARTIAL' ? 'RUN-PARTIAL' : 'RUN-1',
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
await review.reparseDocument('document_quality');
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(review.reviewRun.value?.run_no).toBe('RUN-PARTIAL');
expect(review.activeCase.value?.case_no).toBe('CASE-PARTIAL');
expect(review.isReadOnly.value).toBe(false);
expect(review.statusMessage.value).not.toBe('reparse_in_progress');
review.stopReparseCaseRefreshPolling();
vi.useRealTimers();
});
it('opens the Stream current version instead of retaining a historical Case', async () => {
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
items: [{ case_no: 'CASE-2', document_id: 1, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] }],
});
api.getRun.mockImplementation(async (runNo: string) => ({
run_no: runNo, summary: {},
items: [{ case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1', document_id: 1, status: 'draft', issue_count: 0 }],
}));
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo, run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
review.reviewRun.value!.superseded_by_run_no = 'RUN-2';
const target = await review.openCurrentVersion();
expect(target).toEqual({ runNo: 'RUN-2', caseNo: 'CASE-2' });
expect(review.activeCase.value?.case_no).toBe('CASE-2');
});
it('does not jump to a different PDF when the Stream contains multiple documents', async () => {
api.getRun.mockImplementation(async (runNo: string) => runNo === 'RUN-1'
? {
run_no: runNo,
summary: {},
items: [{ case_no: 'CASE-1', status: 'superseded', issue_count: 0 }],
}
: {
run_no: runNo,
summary: {},
items: [{ case_no: runNo === 'RUN-3' ? 'CASE-1-NEW' : 'CASE-2', status: 'draft', issue_count: 0 }],
});
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-1-NEW' ? 'RUN-3' : caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
status: caseNo === 'CASE-1-NEW' || caseNo === 'CASE-2' ? 'draft' : 'superseded',
}));
api.getQueue.mockResolvedValue({
summary: { total: 2, needs_action: 2, processing: 0, completed: 0 },
items: [
{ case_no: 'CASE-1-NEW', document_id: 1, source_run_no: 'RUN-3', status: 'draft', issue_count: 0, available_actions: [] },
{ case_no: 'CASE-2', document_id: 2, source_run_no: 'RUN-2', status: 'draft', issue_count: 0, available_actions: [] },
],
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
review.reviewRun.value!.superseded_by_run_no = 'RUN-2';
const target = await review.openCurrentVersion();
expect(target).toEqual({ runNo: 'RUN-3', caseNo: 'CASE-1-NEW' });
expect(review.reviewRun.value?.run_no).toBe('RUN-3');
expect(review.activeCase.value?.case_no).toBe('CASE-1-NEW');
});
it('stops waiting when reparse fails without exposing a synthetic stage', async () => {
vi.useFakeTimers();
api.reparseDocument.mockResolvedValue({
run: { run_no: 'RUN-FAILED', items: [], summary: {} }, reused: false,
});
api.getExtractionRun.mockResolvedValue({ run_no: 'RUN-FAILED', status: 'failed' });
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
await review.reparseDocument('document_quality');
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
review.stopReparseCaseRefreshPolling();
vi.useRealTimers();
});
it('[选法 2] defers review Case + Evidence load on a formal downstream work item', async () => {
api.getRun.mockResolvedValue({ run_no: 'RUN-1', summary: {}, items: [] });
api.getQueue.mockResolvedValue({
summary: { total: 1, needs_action: 0, processing: 0, completed: 1 },
items: [{
case_no: 'CASE-1', document_id: 1, status: 'confirmed',
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'SN-1',
}],
});
api.getCase.mockClear();
api.getEvidence.mockClear();
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
// 正式任务下游阶段:首屏不拉复核 Case 快照 + Evidence。
expect(api.getCase).not.toHaveBeenCalled();
expect(api.getEvidence).not.toHaveBeenCalled();
});
it('[选法 2] selectCase skips Case + Evidence on formal downstream nav items', async () => {
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [
{
case_no: 'CASE-1', document_id: 1, status: 'confirmed',
lifecycle_stage: 'freight_upload', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'OT-1',
},
{
case_no: 'CASE-2', document_id: 2, status: 'confirmed',
lifecycle_stage: 'freight_upload', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'OT-2',
},
],
});
api.getQueue.mockResolvedValue({
summary: { total: 2, needs_action: 0, processing: 0, completed: 2 },
items: [
{
case_no: 'CASE-1', document_id: 1, status: 'confirmed',
lifecycle_stage: 'freight_upload', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'OT-1',
},
{
case_no: 'CASE-2', document_id: 2, status: 'confirmed',
lifecycle_stage: 'freight_upload', lifecycle_entries: [],
has_formal_ot: true, confirmed_task_no: 'OT-2',
},
],
});
api.getCase.mockClear();
api.getEvidence.mockClear();
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
api.getCase.mockClear();
api.getEvidence.mockClear();
await review.selectCase('CASE-2');
expect(api.getCase).not.toHaveBeenCalled();
expect(api.getEvidence).not.toHaveBeenCalled();
expect(review.requestedCaseNo.value).toBe('CASE-2');
expect(review.activeCase.value).toBeNull();
expect(review.evidence.value).toEqual([]);
});
it('[选法 2] loadReviewCase lazily fetches review Case + Evidence on demand', async () => {
api.getCase.mockClear();
api.getEvidence.mockClear();
api.getCase.mockResolvedValue({
case: buildCase({ case_no: 'CASE-1' }),
projection_version: 1,
loading_context: null,
});
api.getEvidence.mockResolvedValue({ case_no: 'CASE-1', items: [] });
const review = useShippingOrderReview();
await review.loadReviewCase('CASE-1');
expect(api.getCase).toHaveBeenCalledWith('CASE-1');
expect(api.getEvidence).toHaveBeenCalledWith('CASE-1');
});
it('[选法 2] loadReviewCase can skip Evidence for fulfillment_prep write-path debt', async () => {
api.getCase.mockClear();
api.getEvidence.mockClear();
api.getCase.mockResolvedValue({
case: buildCase({ case_no: 'CASE-1' }),
projection_version: 1,
loading_context: null,
});
const review = useShippingOrderReview();
await review.loadReviewCase('CASE-1', { includeEvidence: false });
expect(api.getCase).toHaveBeenCalledWith('CASE-1');
expect(api.getEvidence).not.toHaveBeenCalled();
expect(review.activeCase.value?.case_no).toBe('CASE-1');
});
});
describe('inventory routing recovery', () => {
beforeEach(() => {
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{
case_no: 'CASE-1',
document_id: 1,
file_name: 'order.pdf',
status: 'draft',
draft_version: 2,
issue_count: 0,
available_actions: ['edit_draft', 'validate', 'confirm'],
}],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockResolvedValue(new Blob());
api.getProcessingWorkItem.mockRejectedValue(
Object.assign(new Error('not found'), { name: 'BusinessError', status: 404, code: 'NOT_FOUND' }),
);
api.getCase.mockResolvedValue(buildCase());
});
afterEach(() => {
vi.clearAllMocks();
});
it('detects automatic routing recovery lines', () => {
expect(lineNeedsInventoryRoutingRecovery({
can_build: true,
unavailable_source_codes: ['OFFLINE_SRC'],
})).toBe(true);
});
it('exposes routingRecoveryLines for blocked rule rows', async () => {
api.getCase.mockResolvedValue(buildCase({
draft: {
...buildCase().draft!,
build_eligibility: {
can_build: true,
status: 'ready',
line_projections: [{
draft_line_id: 'line-pending',
line_index: 0,
can_build: false,
block_reason: 'inventory_source_unavailable',
rule_suggestion_source_codes: ['DSV360_AWSDU'],
candidate_inventory_source_codes: ['DSV360_AWSHK'],
selection_mode: 'manual',
}],
},
},
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
expect(review.routingRecoveryLines.value).toHaveLength(1);
expect(review.routingRecoveryLines.value[0]?.draft_line_id).toBe('line-pending');
});
it('reroutes inventory routing with idempotency_key and expected_draft_version', async () => {
const updated = buildCase({ draft: { ...buildCase().draft!, draft_version: 3 } });
api.rerouteInventoryRouting.mockResolvedValue(updated);
const uuidSpy = vi.spyOn(crypto, 'randomUUID').mockReturnValue('idem-reroute-1');
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.rerouteInventoryRouting('line-1');
expect(api.rerouteInventoryRouting).toHaveBeenCalledWith('CASE-1', {
expected_draft_version: 2,
idempotency_key: 'idem-reroute-1',
draft_line_id: 'line-1',
});
expect(review.activeCase.value?.draft?.draft_version).toBe(3);
uuidSpy.mockRestore();
});
it('sets draftConflict on 409 VERSION_MISMATCH during reroute', async () => {
api.rerouteInventoryRouting.mockRejectedValue(
new BusinessError({ message: 'stale', code: REVIEW_DRAFT_VERSION_MISMATCH }),
);
api.getCase
.mockResolvedValueOnce(buildCase())
.mockResolvedValueOnce(buildCase({
draft: { ...buildCase().draft!, draft_version: 9 },
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await expect(review.rerouteInventoryRouting('line-1')).rejects.toMatchObject({
code: REVIEW_DRAFT_VERSION_MISMATCH,
});
expect(review.draftConflict.value).toMatchObject({
localVersion: 2,
serverVersion: 9,
});
expect(review.saveFailed.value).toBe(true);
});
});