feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:18:37 +08:00
1 parent 3a9fbac2fc
commit d2b3d74def
571 files changed
+78064 -24681

No files matched your search

@@ -1,106 +1,120 @@
/**
* features/chat/shipping/useShippingNoticeWorkflow.spec.ts
* 用途:覆盖 Workflow 轮询退避、多批次选择、停轮询条件与取消/重识别后刷新。
* 用途:覆盖 ShippingProcessing 恢复、轮询退避与跨会话迟到响应隔离。
* 依赖:Vitest、vue、shipping.api mock。
* 逻辑:断言 backoff 封顶、终态停轮询、选中保留、cancelItem/reparseItem 调 API 后 refresh。
* 逻辑:co8 后仅验证统一 shipping-processing 读源与轮询策略;无 Workflow 空壳字段。
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { nextTick, ref } from 'vue';
import {
resolveSelectedWorkflowNo,
resolveWorkflowPollBackoffMs,
shouldContinueWorkflowPolling,
resolveProcessingPollBackoffMs,
shouldContinueProcessingPolling,
useShippingNoticeWorkflow,
} from './useShippingNoticeWorkflow';
import type { ShippingWorkflow, ShippingWorkflowItem } from '../types/shipping.api.types';
import type { ConversationProcessingProjection } from '../types/shipping.api.types';
const api = vi.hoisted(() => ({
listWorkflows: vi.fn(),
cancelItem: vi.fn(),
reparseItem: vi.fn(),
getShippingProcessing: vi.fn(async () => {
throw new Error('unified_unavailable');
}),
focusTask: vi.fn(),
markViewed: vi.fn(),
}));
vi.mock('../api/shipping.api', () => ({
listWorkspaceShippingWorkflows: api.listWorkflows,
cancelWorkspaceShippingWorkflowItem: api.cancelItem,
reparseWorkspaceShippingWorkflowItem: api.reparseItem,
getWorkspaceShippingProcessing: api.getShippingProcessing,
focusWorkspaceConversationTask: api.focusTask,
markWorkspaceConversationTaskViewed: api.markViewed,
}));
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
/**
* 构造历史会话右侧任务投影。
*/
function buildProcessing(conversationId = 'conv-1'): ConversationProcessingProjection {
return {
item_no: 'SWI-1',
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_document_filename: 'notice-a.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
...patch,
conversation_id: conversationId,
summary: {
total_tasks: 1,
total_files: 2,
processing: 0,
needs_action: 1,
completed: 0,
history: 0,
},
processing: [],
needs_action: [{
user_task_no: `OT-${conversationId}`,
group: 'needs_action',
can_append: false,
file_count: 2,
}],
completed: [],
history: [],
};
}
function buildWorkflow(patch: Partial<ShippingWorkflow> = {}): ShippingWorkflow {
const items = patch.items ?? [buildItem()];
/**
* 构造统一 shipping-processing 响应(内嵌 conversation_processing)。
*/
function buildUnifiedProcessing(conversationId = 'conv-1') {
return {
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: {
total: items.length,
processing: items.length,
pending_review: 0,
failed: 0,
completed: 0,
},
items,
...patch,
conversation_id: conversationId,
work_items: [],
conversation_processing: buildProcessing(conversationId),
};
}
/**
* 创建可手动完成的 Promise。
*/
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
describe('useShippingNoticeWorkflow helpers', () => {
it('caps failure backoff at 8s', () => {
expect(resolveWorkflowPollBackoffMs(1)).toBe(2000);
expect(resolveWorkflowPollBackoffMs(2)).toBe(4000);
expect(resolveWorkflowPollBackoffMs(3)).toBe(8000);
expect(resolveWorkflowPollBackoffMs(10)).toBe(8000);
expect(resolveProcessingPollBackoffMs(1)).toBe(2000);
expect(resolveProcessingPollBackoffMs(2)).toBe(4000);
expect(resolveProcessingPollBackoffMs(3)).toBe(8000);
expect(resolveProcessingPollBackoffMs(10)).toBe(8000);
});
it('stops polling on terminal workflow status', () => {
const workflow = buildWorkflow({ status: 'completed' });
expect(shouldContinueWorkflowPolling([workflow])).toBe(false);
it('stops when processing idle', () => {
expect(shouldContinueProcessingPolling(null)).toBe(false);
expect(shouldContinueProcessingPolling({
summary: { total_tasks: 0, processing: 0, needs_action: 0, history: 0 },
processing: [],
needs_action: [],
history: [],
})).toBe(false);
});
it('continues while layout_parsing items remain', () => {
const items = [buildItem({ lifecycle_status: 'layout_parsing' })];
const workflow = buildWorkflow({ status: 'open', items });
expect(shouldContinueWorkflowPolling([workflow])).toBe(true);
});
it('stops when open workflow has only closed items', () => {
const items = [buildItem({ lifecycle_status: 'closed' })];
const workflow = buildWorkflow({ status: 'open', items });
expect(shouldContinueWorkflowPolling([workflow])).toBe(false);
});
it('keeps previous selection when still present, else first', () => {
const a = buildWorkflow({ workflow_no: 'SNWF-A' });
const b = buildWorkflow({ workflow_no: 'SNWF-B' });
expect(resolveSelectedWorkflowNo([a, b], 'SNWF-B')).toBe('SNWF-B');
expect(resolveSelectedWorkflowNo([a, b], 'SNWF-GONE')).toBe('SNWF-A');
expect(resolveSelectedWorkflowNo([a, b], 'SNWF-A', 'SNWF-B')).toBe('SNWF-B');
it('continues when processing projection is active', () => {
expect(shouldContinueProcessingPolling({
summary: { total_tasks: 1, processing: 1, needs_action: 0, history: 0 },
processing: [{
user_task_no: 'OT-1',
group: 'processing',
can_append: true,
}],
needs_action: [],
history: [],
})).toBe(true);
});
});
describe('useShippingNoticeWorkflow', () => {
beforeEach(() => {
api.listWorkflows.mockReset();
api.cancelItem.mockReset();
api.reparseItem.mockReset();
api.getShippingProcessing.mockReset();
api.getShippingProcessing.mockRejectedValue(new Error('unified_unavailable'));
api.focusTask.mockReset();
api.markViewed.mockReset();
vi.useFakeTimers();
});
@@ -108,20 +122,8 @@ describe('useShippingNoticeWorkflow', () => {
vi.useRealTimers();
});
it('loads open workflow items and exposes cancelItem refresh', async () => {
const workflow = buildWorkflow({
items: [
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),
],
});
api.listWorkflows.mockResolvedValue({
conversation_id: 'conv-1',
workflows: [workflow],
});
api.cancelItem.mockResolvedValue({
item: buildItem({ item_no: 'SWI-A', lifecycle_status: 'cancelled' }),
});
it('loads processing projection without workflow shells', async () => {
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing());
const conversationId = ref('conv-1');
const ctl = useShippingNoticeWorkflow({ conversationId });
@@ -129,67 +131,15 @@ describe('useShippingNoticeWorkflow', () => {
await nextTick();
await Promise.resolve();
expect(api.listWorkflows).toHaveBeenCalled();
expect(ctl.items.value.map((row) => row.item_no)).toEqual(['SWI-A', 'SWI-B']);
expect(ctl.selectedWorkflowNo.value).toBe('SNWF-1');
await ctl.cancelItem('SWI-A', { reason: 'user cancel', expected_lock_version: 1 });
expect(api.cancelItem).toHaveBeenCalledWith('SWI-A', {
reason: 'user cancel',
expected_lock_version: 1,
});
expect(api.listWorkflows.mock.calls.length).toBeGreaterThanOrEqual(2);
ctl.stop();
});
it('selects among multiple workflows and reparses', async () => {
const first = buildWorkflow({
workflow_no: 'SNWF-1',
items: [buildItem({ item_no: 'SWI-1', workflow_no: 'SNWF-1' })],
});
const second = buildWorkflow({
workflow_no: 'SNWF-2',
items: [
buildItem({
item_no: 'SWI-2',
workflow_no: 'SNWF-2',
lifecycle_status: 'failed',
current_document_filename: 'fail.pdf',
}),
],
});
api.listWorkflows.mockResolvedValue({
conversation_id: 'conv-1',
workflows: [first, second],
});
api.reparseItem.mockResolvedValue({
item: buildItem({ item_no: 'SWI-2', lifecycle_status: 'extracting' }),
});
const conversationId = ref('conv-1');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.workflows.value).toHaveLength(2);
expect(ctl.selectedWorkflowNo.value).toBe('SNWF-1');
ctl.selectWorkflow('SNWF-2');
expect(ctl.selectedWorkflowNo.value).toBe('SNWF-2');
expect(ctl.items.value[0]?.item_no).toBe('SWI-2');
await ctl.reparseItem('SWI-2', { reason: 'retry', comment: 'note' });
expect(api.reparseItem).toHaveBeenCalledWith('SWI-2', {
reason: 'retry',
comment: 'note',
});
expect(api.getShippingProcessing).toHaveBeenCalled();
expect(ctl.processing.value?.summary.needs_action).toBe(1);
expect(ctl.processingWorkItems.value).toEqual([]);
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('records recoverable error without throwing', async () => {
api.listWorkflows.mockRejectedValue(new Error('network down'));
const conversationId = ref('conv-1');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
@@ -198,4 +148,200 @@ describe('useShippingNoticeWorkflow', () => {
expect(ctl.error.value).toBe('network_recoverable');
ctl.stop();
});
it('restores processing tasks from unified shipping-processing', async () => {
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing());
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.processing.value?.summary.needs_action).toBe(1);
expect(ctl.processing.value?.summary.total_files).toBe(2);
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('uses unified work_items as the sole processing read source', async () => {
api.getShippingProcessing.mockResolvedValue({
conversation_id: 'conv-1',
work_items: [{
workItemType: 'order_task',
workItemNo: 'OT-UNIFIED',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-UNIFIED',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: {
gateCode: 'order_freeze_readiness',
status: 'blocked',
nextActionCode: 'open_order_review',
},
availableActions: ['open_order_review'],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-1',
},
childOrderTasks: [],
}],
conversation_processing: null,
});
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(api.getShippingProcessing).toHaveBeenCalled();
expect(ctl.processingWorkItems.value).toHaveLength(1);
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-UNIFIED');
ctl.stop();
});
it('derives sibling OT tasks from work_items when embedded conversation_processing omits them', async () => {
api.getShippingProcessing.mockResolvedValue({
conversation_id: 'conv-1',
work_items: [
{
workItemType: 'order_task',
workItemNo: 'OT-ROOT',
sourceType: 'eml',
rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: ['open_order_review'],
sourceSummary: {
emailSubject: null,
filename: 'root.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-ROOT',
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-SIBLING',
sourceType: 'eml',
rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'candidate_creating',
progressVersion: 1,
lastActivityAt: '2026-08-05T01:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null,
filename: 'sibling.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-SIB',
},
childOrderTasks: [],
},
],
conversation_processing: {
summary: {
total_tasks: 1,
total_files: 1,
processing: 0,
needs_action: 1,
completed: 0,
history: 0,
},
focused_task_no: 'OT-ROOT',
recent_task_no: 'OT-SIBLING',
needs_action: [{
user_task_no: 'OT-ROOT',
group: 'needs_action',
can_append: false,
file_count: 1,
}],
processing: [],
completed: [],
history: [],
},
});
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.processing.value?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
expect(ctl.processing.value?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
expect(ctl.processing.value?.focused_task_no).toBe('OT-ROOT');
expect(ctl.processing.value?.recent_task_no).toBe('OT-SIBLING');
ctl.stop();
});
it('retries a failed initial processing restore instead of freezing at empty state', async () => {
api.getShippingProcessing
.mockRejectedValueOnce(new Error('temporary auth recovery'))
.mockResolvedValue(buildUnifiedProcessing());
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
expect(ctl.error.value).toBe('network_recoverable');
await vi.advanceTimersByTimeAsync(2000);
await nextTick();
await Promise.resolve();
expect(api.getShippingProcessing).toHaveBeenCalledTimes(2);
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-conv-1');
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('ignores an old conversation response that completes after the restored conversation', async () => {
const oldUnified = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing
.mockImplementationOnce(() => oldUnified.promise)
.mockResolvedValueOnce(buildUnifiedProcessing('conv-new'));
const conversationId = ref('conv-old');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
conversationId.value = 'conv-new';
await nextTick();
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(ctl.processing.value?.conversation_id).toBe('conv-new');
oldUnified.resolve(buildUnifiedProcessing('conv-old'));
await Promise.resolve();
await nextTick();
expect(ctl.processing.value?.conversation_id).toBe('conv-new');
ctl.stop();
});
});