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

@@ -7,9 +7,19 @@
import { describe, expect, it } from 'vitest';
import {
mapLifecycleToNodeStatus,
mapShippingProcessingStatusToTaskGroup,
mergeConversationProcessingFocusMetadata,
projectConversationProcessingFromWorkItems,
projectConversationProcessingObjects,
projectConversationProcessingTasks,
groupConversationProcessingTasks,
mapUserTaskObjectsToFileRows,
resolveConversationProcessingFromUnified,
} from './conversationProcessingProjection';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
import type {
ShippingProcessingProjection,
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
return {
@@ -84,4 +94,581 @@ describe('conversationProcessingProjection', () => {
// 关键断言:侧栏 Task 使用后端权威 node_status,不覆盖为 running。
expect(rows.find((row) => row.kind === 'task')?.node_status).toBe('manual_takeover');
});
it('groups tasks into needs_action / processing / completed; closed stays history', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 1,
lifecycle_status: 'pending_review',
current_document_filename: 'a.pdf',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 2,
lifecycle_status: 'extracting',
current_document_filename: 'b.pdf',
}),
item({
item_no: 'WI-DONE',
current_run_no: 'RUN-DONE',
root_document_id: 3,
lifecycle_status: 'completed',
current_document_filename: 'done.pdf',
}),
item({
item_no: 'WI-C',
current_run_no: 'RUN-C',
root_document_id: 4,
lifecycle_status: 'closed',
current_document_filename: 'c.pdf',
}),
item({
item_no: 'WI-NO-NAME',
current_run_no: 'RUN-NO-NAME',
root_document_id: 5,
lifecycle_status: 'extracting',
current_document_filename: null,
}),
]);
const projection = groupConversationProcessingTasks(tasks, { focusedTaskNo: 'OT-RUN-A' });
// 右侧总数不含 history;completed 独立成组。
expect(projection.summary).toEqual({
total_tasks: 4,
total_files: 4,
processing: 2,
needs_action: 1,
completed: 1,
history: 1,
});
expect(projection.needs_action[0]?.user_task_no).toBe('OT-RUN-A');
expect(projection.processing.map((t) => t.user_task_no).sort()).toEqual([
'OT-RUN-B',
'OT-RUN-NO-NAME',
]);
expect(projection.completed?.[0]?.user_task_no).toBe('OT-RUN-DONE');
expect(projection.history[0]?.user_task_no).toBe('OT-RUN-C');
// [UI-02] 缺文件名时 title 为空,交给卡片回退「未命名 PDF」。
const unnamed = projection.processing.find((t) => t.user_task_no === 'OT-RUN-NO-NAME');
expect(unnamed?.title).toBeNull();
});
it('uses multi_document_task when one run has two different PDFs', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-MULTI',
root_document_id: 91,
current_document_id: 91,
content_hash: 'hash-a',
user_task_no: 'OT-MULTI',
lifecycle_status: 'extracting',
current_document_filename: '4518838152.pdf',
}),
item({
item_no: 'WI-2',
current_run_no: 'RUN-MULTI',
root_document_id: 92,
current_document_id: 92,
content_hash: 'hash-b',
user_task_no: 'OT-MULTI',
lifecycle_status: 'layout_parsing',
current_document_filename: '4518838154.pdf',
}),
]);
expect(tasks).toHaveLength(1);
expect(tasks[0]?.title).toBeNull();
expect(tasks[0]?.display_kind).toBe('multi_document_task');
expect(tasks[0]?.file_count).toBe(2);
expect(tasks[0]?.document_names).toEqual(['4518838152.pdf', '4518838154.pdf']);
const docs = (tasks[0]?.objects || []).filter((row) => row.kind === 'document');
expect(docs).toHaveLength(2);
});
it('keeps multi PDF when same OT spans different run_nos', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-A',
root_document_id: 91,
current_document_id: 91,
content_hash: 'hash-a',
user_task_no: 'OT-SHARED',
lifecycle_status: 'pending_review',
current_document_filename: 'a.pdf',
last_activity_at: '2026-08-04T01:00:00Z',
}),
item({
item_no: 'WI-2',
current_run_no: 'RUN-B',
root_document_id: 92,
current_document_id: 92,
content_hash: 'hash-b',
user_task_no: 'OT-SHARED',
lifecycle_status: 'pending_review',
current_document_filename: 'b.pdf',
last_activity_at: '2026-08-04T02:00:00Z',
}),
]);
// 同 OT 跨 Run 时按 PDF 身份选最新版;未在新 Run 重识别的 PDF 继续有效。
expect(tasks).toHaveLength(1);
expect(tasks[0]?.file_count).toBe(2);
expect(tasks[0]?.display_kind).toBe('multi_document_task');
expect(tasks[0]?.title).toBeNull();
expect(tasks[0]?.document_names).toEqual(['a.pdf', 'b.pdf']);
expect(tasks[0]?.run_no).toBe('RUN-B');
const documents = tasks[0]?.objects.filter((row) => row.kind === 'document') || [];
expect(documents.map((row) => row.current_run_no)).toEqual(['RUN-A', 'RUN-B']);
});
it('keeps only latest version when same PDF spans different run_nos', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-OLD',
current_run_no: 'RUN-A',
root_document_id: 91,
current_document_id: 91,
content_hash: 'hash-a',
user_task_no: 'OT-SHARED',
lifecycle_status: 'failed',
current_document_filename: 'old.pdf',
last_activity_at: '2026-08-04T01:00:00Z',
}),
item({
item_no: 'WI-NEW',
current_run_no: 'RUN-B',
root_document_id: 91,
current_document_id: 191,
content_hash: 'hash-a',
user_task_no: 'OT-SHARED',
lifecycle_status: 'pending_review',
current_document_filename: 'latest.pdf',
last_activity_at: '2026-08-04T02:00:00Z',
}),
]);
expect(tasks).toHaveLength(1);
expect(tasks[0]?.file_count).toBe(1);
expect(tasks[0]?.title).toBe('latest.pdf');
const document = tasks[0]?.objects.find((row) => row.kind === 'document');
expect(document?.document_id).toBe(191);
expect(document?.current_run_no).toBe('RUN-B');
});
it('keeps single PDF filename title for one-document run', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-ONE',
root_document_id: 7,
content_hash: 'solo',
user_task_no: 'OT-ONE',
lifecycle_status: 'extracting',
current_document_filename: 'solo.pdf',
}),
]);
expect(tasks[0]?.title).toBe('solo.pdf');
expect(tasks[0]?.display_kind).toBe('single_document_task');
expect(tasks[0]?.file_count).toBe(1);
});
it('merges same root_document_id across runs into one fallback task', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-OLD',
current_run_no: 'RUN-OLD',
root_document_id: 42,
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-NEW',
current_run_no: 'RUN-NEW',
root_document_id: 42,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-01] 同 root 只保留当前有效版本(处理中),旧失败不再单独出卡。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing).toHaveLength(1);
expect(projection.needs_action).toHaveLength(0);
expect(projection.processing[0]?.run_no).toBe('RUN-NEW');
expect(projection.processing[0]?.title).toBe('order.pdf');
});
it('merges different root_document_id with same content_hash into one fallback task', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 101,
content_hash: 'aaa111',
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 202,
content_hash: 'aaa111',
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-01] 普通重传换 root,但同内容哈希只保留当前有效版本。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing).toHaveLength(1);
expect(projection.processing[0]?.run_no).toBe('RUN-B');
});
it('merges different root_document_id with same user_task_no into one fallback task', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 301,
user_task_no: 'OT-SHARED',
content_hash: 'hash-a',
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 302,
user_task_no: 'OT-SHARED',
content_hash: 'hash-b',
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// user_task_no 优先于 content_hash / root;输出必须原样保留真实 OT。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing[0]?.run_no).toBe('RUN-B');
expect(projection.processing[0]?.user_task_no).toBe('OT-SHARED');
expect(projection.processing[0]?.user_task_authoritative).toBe(true);
});
it('preserves authoritative user_task_no for focus/viewed APIs', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-XXX',
root_document_id: 55,
user_task_no: 'OT-REAL-001',
content_hash: 'abc',
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
// [UI-01] 禁止输出伪造 OT-${runNo},否则 focus/viewed 会打到不存在的任务号。
expect(tasks).toHaveLength(1);
expect(tasks[0]?.user_task_no).toBe('OT-REAL-001');
expect(tasks[0]?.user_task_no).not.toBe('OT-RUN-XXX');
expect(tasks[0]?.user_task_authoritative).toBe(true);
});
it('marks fabricated fallback task no as non-authoritative', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-LOCAL',
root_document_id: 66,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
}),
]);
expect(tasks[0]?.user_task_no).toBe('OT-RUN-LOCAL');
expect(tasks[0]?.user_task_authoritative).toBe(false);
});
it('does not merge different root_document_id with same filename', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 101,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 202,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-01] 同名不同内容(不同 root)不得合并成一张卡。
expect(projection.summary.total_tasks).toBe(2);
expect(projection.processing).toHaveLength(2);
});
it('prefers newer failed over older processing for same identity', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-OLD',
current_run_no: 'RUN-OLD',
root_document_id: 77,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-NEW',
current_run_no: 'RUN-NEW',
root_document_id: 77,
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-02] 最新有效版本按活动时间,不按 processing 严重度遮盖新失败。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing).toHaveLength(0);
expect(projection.needs_action).toHaveLength(1);
expect(projection.needs_action[0]?.run_no).toBe('RUN-NEW');
expect(projection.needs_action[0]?.status_label).toBe('failed');
});
it('synthesizes conversation groups from unified order_task work_items', () => {
const workItems: ShippingProcessingProjection[] = [
{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'failed',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: ['retry_parse'],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 0,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-WAIT',
sourceType: 'eml',
rootOrderTaskNo: 'OT-WAIT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-2',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 2,
lastActivityAt: '2026-08-05T01:00:00Z',
currentGate: {
gateCode: 'order_freeze_readiness',
status: 'blocked',
nextActionCode: 'open_order_review',
blockingReasonCode: 'review_case_draft',
attemptNo: 0,
},
availableActions: ['open_order_review'],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 2,
parsedDocumentCount: 2,
candidateCount: 1,
customerName: 'ACME',
poNumber: 'PO-1',
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-RUN',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-RUN',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-2',
intakeNo: 'SNI-3',
status: 'processing',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T02:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null,
filename: 'solo.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
},
];
expect(mapShippingProcessingStatusToTaskGroup(workItems[1]!)).toBe('needs_action');
expect(mapShippingProcessingStatusToTaskGroup(workItems[2]!)).toBe('processing');
const projection = projectConversationProcessingFromWorkItems(workItems);
// 关键断言:仅 order_task 入组;intake 不进入 conversation groups。
expect(projection).not.toBeNull();
expect(projection!.needs_action.map((t) => t.user_task_no)).toEqual(['OT-WAIT']);
expect(projection!.processing.map((t) => t.user_task_no)).toEqual(['OT-RUN']);
expect(projection!.needs_action[0]?.file_count).toBe(2);
expect(projection!.needs_action[0]?.display_kind).toBe('multi_document_task');
});
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
const workItems: ShippingProcessingProjection[] = [
{
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: [],
},
];
const embedded = {
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 projection = resolveConversationProcessingFromUnified(workItems, embedded);
// 关键断言:兄弟 OT 仅出现在 work_items;embedded 缺 sibling 时不得覆盖任务列表。
expect(projection?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
expect(projection?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
expect(projection?.focused_task_no).toBe('OT-ROOT');
expect(projection?.recent_task_no).toBe('OT-SIBLING');
});
it('merges focus metadata from embedded onto work_items-derived projection', () => {
const derived = projectConversationProcessingFromWorkItems([{
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-1',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
}]);
const merged = mergeConversationProcessingFocusMetadata(derived, {
summary: derived!.summary,
focused_task_no: 'OT-FOCUS',
recent_task_no: 'OT-RECENT',
needs_action: [{ user_task_no: 'OT-STALE', group: 'needs_action', can_append: false }],
processing: [],
history: [],
});
expect(merged?.processing[0]?.user_task_no).toBe('OT-1');
expect(merged?.focused_task_no).toBe('OT-FOCUS');
expect(merged?.recent_task_no).toBe('OT-RECENT');
});
});
@@ -1,17 +1,56 @@
/**
* features/chat/shipping/conversationProcessingProjection.ts
* 用途:将现有 Workflow Items 投影为对话「本次处理中」统一对象行。
* 依赖:shipping.api.types(ConversationProcessingObject / WorkflowNodeStatus)。
* 逻辑:Timeline 复用本投影;Task 优先消费后端 node_status / progress_nodes;
* 不伪造进度百分比。
* 用途:将 OT / 统一 processing 投影为对话「本次处理中」对象、任务分组与文件行。
* 依赖:shipping.api.types(ConversationProcessingObject / UserTask / WorkflowNodeStatus /
* ShippingProcessingProjection、合成 ShippingWorkflowItem)。
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
* 可由统一 work_items(order_task)合成兼容分组。
*/
import type {
ConversationProcessingObject,
ConversationProcessingProjection,
ConversationProcessingSummary,
ConversationProcessingTaskGroup,
ConversationProcessingUserTask,
ShippingProcessingProjection,
ShippingWorkflowItem,
WorkflowNodeStatus,
} from '@/features/chat/types/shipping.api.types';
/** 需要人工处理的生命周期集合。 */
const NEEDS_ACTION_LIFECYCLES = new Set([
'pending_review',
'manual_upload_pending',
'failed',
'reparse_failed',
'upload_rpa_failed',
]);
/** 处理中生命周期集合。 */
const PROCESSING_LIFECYCLES = new Set([
'queued',
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'generating_excel',
'upload_rpa_pending',
'upload_rpa_running',
]);
/** 历史生命周期集合(已关闭/取消;completed 单独进「已完成」通知组)。 */
const HISTORY_LIFECYCLES = new Set([
'closed',
'cancelled',
]);
/** 识别完成、仍应在右侧展示的成功通知生命周期。 */
const COMPLETED_LIFECYCLES = new Set([
'completed',
]);
/**
* 将生命周期状态映射为 WorkflowNodeStatus(展示用,非进度百分比)。
*/
@@ -58,6 +97,59 @@ export function resolveItemDisplayStatus(item: ShippingWorkflowItem): string {
return String(item.lifecycle_status || '').trim();
}
/**
* 将 OT 任务卡内 document objects 映射为侧栏文件行(合成 ShippingWorkflowItem 形态)。
* 核心逻辑:仅消费 kind=document;item_no 优先 workflow_item_no / object_key;
* available_actions / reparse_kind 可从 object 扩展字段透传(单测与后端可选投影)。
*
* @param task - 当前展开的用户可见任务
* @returns 文件明细行;无文档对象时为空数组
*/
export function mapUserTaskObjectsToFileRows(
task: ConversationProcessingUserTask | null | undefined,
): ShippingWorkflowItem[] {
if (!task) return [];
const rows: ShippingWorkflowItem[] = [];
for (const [index, object] of (task.objects || []).entries()) {
if (object.kind !== 'document') continue;
const documentId = Number(object.document_id || 0);
const rootId = Number(object.root_document_id || documentId || 0);
const status = String(object.status_label || task.status_label || 'queued').trim() || 'queued';
const itemNo = String(
object.workflow_item_no || object.object_key || `DOC-${documentId || index + 1}`,
).trim();
const extra = object as ConversationProcessingObject & {
available_actions?: string[];
reparse_kind?: string | null;
lock_version?: number;
};
rows.push({
item_no: itemNo,
workflow_no: String(task.workflow_no || 'SNWF-OT').trim() || 'SNWF-OT',
conversation_id: '',
root_document_id: rootId,
current_document_id: documentId || rootId,
current_document_filename: object.filename || object.label || null,
content_hash: object.content_hash || null,
current_version_no: Number(object.current_version_no || 1) || 1,
current_run_no: object.current_run_no || object.run_no || task.run_no || null,
current_case_no: object.case_no || null,
current_task_no: object.task_no || task.user_task_no || null,
user_task_no: task.user_task_no,
user_task_authoritative: task.user_task_authoritative,
lifecycle_status: status,
current_stage: status,
display_lifecycle_status: status,
lock_version: Number(extra.lock_version || 1) || 1,
available_actions: Array.isArray(extra.available_actions)
? extra.available_actions
: (Array.isArray(task.available_actions) ? task.available_actions : undefined),
reparse_kind: extra.reparse_kind ?? null,
});
}
return rows;
}
/**
* 从 Workflow Items 聚合 Run / Candidate / Task / Process Gate 侧栏行。
*
@@ -188,3 +280,416 @@ export function projectConversationProcessingObjects(
return rows;
}
/**
* 按生命周期/门禁将状态归入 needs_action | processing | completed | history。
*/
export function classifyConversationProcessingGroup(
status: string | null | undefined,
options?: { hasBlockingGate?: boolean; needsCustomerConfirm?: boolean },
): ConversationProcessingTaskGroup {
if (options?.hasBlockingGate || options?.needsCustomerConfirm) return 'needs_action';
const normalized = String(status || '').trim();
if (NEEDS_ACTION_LIFECYCLES.has(normalized)) return 'needs_action';
if (COMPLETED_LIFECYCLES.has(normalized)) return 'completed';
if (HISTORY_LIFECYCLES.has(normalized)) return 'history';
if (PROCESSING_LIFECYCLES.has(normalized)) return 'processing';
if (normalized === 'review_required' || normalized === 'partially_completed') {
return 'needs_action';
}
if (normalized === 'failed' || normalized === 'cancelled') return 'needs_action';
if (normalized === 'completed') return 'completed';
if (normalized === 'processing' || normalized === 'queued') return 'processing';
return 'processing';
}
/**
* 兜底任务身份键:稳定业务身份优先,文件名仅作最弱兜底。
* 顺序:user_task_no → content_hash → root_document_id → filename → run/item。
* 普通重传会换 root_document_id,故不得把 root 放在 content_hash 之前。
*/
function fallbackTaskIdentityKey(item: ShippingWorkflowItem): string {
const userTaskNo = String(item.user_task_no || '').trim();
if (userTaskNo) return `task:${userTaskNo}`;
const contentHash = String(item.content_hash || '').trim().toLowerCase();
if (contentHash) return `hash:${contentHash}`;
const rootId = Number(item.root_document_id || 0);
if (rootId > 0) return `root:${rootId}`;
const filename = String(item.current_document_filename || '').trim().toLowerCase();
if (filename) return `fn:${filename}`;
const runNo = String(item.current_run_no || '').trim();
if (runNo) return `run:${runNo}`;
return `item:${String(item.item_no || '').trim()}`;
}
/**
* 降级路径:按稳定身份去重 Workflow Items 中的业务 PDF。
* 顺序:content_hash → root_document_id → current_document_id;禁止仅按文件名去重。
*/
function dedupeFallbackDocuments(items: ShippingWorkflowItem[]): Array<{
filename: string | null;
content_hash: string | null;
root_document_id: number;
document_id: number;
status_label: string;
current_run_no: string | null;
source_item: ShippingWorkflowItem;
}> {
const unique: Array<{
filename: string | null;
content_hash: string | null;
root_document_id: number;
document_id: number;
status_label: string;
current_run_no: string | null;
source_item: ShippingWorkflowItem;
recency: number;
identity: string;
}> = [];
const seen = new Map<string, number>();
for (const item of items || []) {
const contentHash = String(item.content_hash || '').trim().toLowerCase();
const rootId = Number(item.root_document_id || 0);
const documentId = Number(item.current_document_id || 0);
const identity = contentHash
? `hash:${contentHash}`
: rootId > 0
? `root:${rootId}`
: documentId > 0
? `doc:${documentId}`
: `item:${String(item.item_no || '').trim()}`;
const filename = String(item.current_document_filename || '').trim() || null;
const row = {
filename,
content_hash: contentHash || null,
root_document_id: rootId,
document_id: documentId,
status_label: resolveItemDisplayStatus(item),
current_run_no: String(item.current_run_no || '').trim() || null,
source_item: item,
recency: Date.parse(String(item.last_activity_at || item.updated_at || '').trim()) || 0,
identity,
};
const existingIndex = seen.get(identity);
if (existingIndex == null) {
seen.set(identity, unique.length);
unique.push(row);
continue;
}
const existing = unique[existingIndex]!;
if (row.recency > existing.recency
|| (row.recency === existing.recency && documentId >= existing.document_id)) {
unique[existingIndex] = row;
}
}
return unique;
}
/**
* 从 Workflow Items 聚合为用户可见任务列表(后端 processing 未就绪时的前端兜底)。
* 核心逻辑:先按稳定任务身份(user_task_no / hash…)归并全部 Item,再按 PDF 去重计
* file_count;禁止先按 run_no 拆桶再丢弃同 OT 的另一份 PDF;单 PDF 才用文件名作 title。
*/
export function projectConversationProcessingTasks(
items: ShippingWorkflowItem[],
options?: {
focusTaskNo?: string | null;
focusRunNo?: string | null;
focusUserTaskNo?: string | null;
},
): ConversationProcessingUserTask[] {
const byIdentity = new Map<string, ShippingWorkflowItem[]>();
for (const item of items || []) {
const identity = fallbackTaskIdentityKey(item);
if (!identity || identity === 'item:') continue;
const bucket = byIdentity.get(identity) || [];
bucket.push(item);
byIdentity.set(identity, bucket);
}
const focusUserTask = String(options?.focusUserTaskNo || '').trim();
const focusRun = String(options?.focusRunNo || '').trim();
const tasks: ConversationProcessingUserTask[] = [];
for (const [identity, groupItems] of byIdentity) {
void identity;
if (!groupItems.length) continue;
// [STEP 1] 取最近活动 Item 作为任务级代表 Run;PDF 则跨 Run 独立选择最新版本。
const sorted = [...groupItems].sort((a, b) => {
const aAt = Date.parse(String(a.last_activity_at || a.updated_at || '').trim()) || 0;
const bAt = Date.parse(String(b.last_activity_at || b.updated_at || '').trim()) || 0;
if (bAt !== aAt) return bAt - aAt;
return String(b.current_run_no || '').localeCompare(String(a.current_run_no || ''));
});
const primaryItem = sorted[0];
if (!primaryItem) continue;
const runNo = String(
primaryItem.current_run_no || primaryItem.workflow_no || primaryItem.item_no || '',
).trim();
// [STEP 2] 同 OT 的旧 Run 仍可能承载未重识别 PDF,禁止整批过滤到代表 Run。
const uniqueDocuments = dedupeFallbackDocuments(groupItems);
const effectiveItems = uniqueDocuments.map((row) => row.source_item);
// 任务级分组/操作只由最近代表 Item 决定;旧 Run 仅贡献未受影响的 PDF,不得反向污染状态。
const statuses = [resolveItemDisplayStatus(primaryItem)];
const hasGate = Boolean(primaryItem.process_gate?.current_blocking_gate);
let group: ConversationProcessingTaskGroup = 'history';
for (const status of statuses) {
const g = classifyConversationProcessingGroup(status, { hasBlockingGate: hasGate });
if (g === 'needs_action') {
group = 'needs_action';
break;
}
if (g === 'processing') {
group = 'processing';
continue;
}
if (g === 'completed' && group !== 'processing') {
group = 'completed';
}
}
const primaryStatus = statuses.find((s) => NEEDS_ACTION_LIFECYCLES.has(s))
|| statuses.find((s) => PROCESSING_LIFECYCLES.has(s))
|| statuses.find((s) => COMPLETED_LIFECYCLES.has(s))
|| statuses[0]
|| 'queued';
// [UI-01] 必须原样输出后端真实 OT;仅缺省时才用本地兼容号,且不得用于写接口。
const authoritativeTaskNo = String(
effectiveItems.map((row) => row.user_task_no).find((value) => String(value || '').trim())
|| groupItems.map((row) => row.user_task_no).find((value) => String(value || '').trim())
|| '',
).trim();
const userTaskNo = authoritativeTaskNo || `OT-${runNo}`;
const documentNames = uniqueDocuments
.map((row) => String(row.filename || '').trim())
.filter(Boolean);
const isMulti = uniqueDocuments.length > 1;
const title = isMulti
? null
: (documentNames[0] || String(primaryItem.current_document_filename || '').trim() || null);
const activityRaw = String(primaryItem.last_activity_at || primaryItem.updated_at || '').trim();
const documentObjects = uniqueDocuments.map((row) => ({
kind: 'document' as const,
object_key: row.document_id > 0
? `DOC-${row.document_id}`
: `DOC-${row.root_document_id || row.filename || 'unknown'}`,
label: row.filename || `DOC-${row.document_id || row.root_document_id}`,
status_label: row.status_label,
document_id: row.document_id || null,
root_document_id: row.root_document_id || null,
filename: row.filename,
content_hash: row.content_hash,
run_no: row.current_run_no,
current_run_no: row.current_run_no,
user_task_no: userTaskNo,
focused: false,
}));
tasks.push({
user_task_no: userTaskNo,
user_task_authoritative: Boolean(authoritativeTaskNo),
title,
display_kind: isMulti ? 'multi_document_task' : 'single_document_task',
document_names: documentNames,
group,
status_label: primaryStatus,
file_count: uniqueDocuments.length,
run_no: runNo || null,
workflow_no: String(primaryItem.workflow_no || '').trim() || null,
can_append: false,
append_block_reason: 'input_already_frozen',
last_activity_at: activityRaw || null,
focused: Boolean(
(focusUserTask && focusUserTask === userTaskNo)
|| (focusRun && focusRun === runNo),
),
objects: [
...projectConversationProcessingObjects(effectiveItems, {
focusTaskNo: options?.focusTaskNo,
focusRunNo: runNo,
}),
...documentObjects,
],
});
}
return tasks;
}
/**
* 将任务列表按分组装入 ConversationProcessingProjection。
*/
export function groupConversationProcessingTasks(
tasks: ConversationProcessingUserTask[],
options?: {
focusedTaskNo?: string | null;
recentTaskNo?: string | null;
},
): ConversationProcessingProjection {
const needs_action = tasks.filter((t) => t.group === 'needs_action');
const processing = tasks.filter((t) => t.group === 'processing');
const completed = tasks.filter((t) => t.group === 'completed');
const history = tasks.filter((t) => t.group === 'history');
const active = [...needs_action, ...processing, ...completed];
const totalFiles = active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
const summary: ConversationProcessingSummary = {
total_tasks: needs_action.length + processing.length + completed.length,
total_files: totalFiles,
processing: processing.length,
needs_action: needs_action.length,
completed: completed.length,
history: history.length,
};
return {
summary,
focused_task_no: options?.focusedTaskNo || null,
recent_task_no: options?.recentTaskNo || null,
needs_action,
processing,
completed,
history,
};
}
/**
* 用 Workflow 兜底投影补齐后端 processing 的多 PDF 标题/文件数。
* 核心逻辑:同 user_task_no / run_no 时,若兜底 file_count 更大,采用兜底的
* display_kind / title / document_names / objects(文档子对象)。
*/
/**
* 将统一 ShippingProcessing status/gate 映射为会话任务分组。
* 核心逻辑:waiting_review/blocked/failed → needs_action;completed → completed;
* cancelled → history;其余 → processing。
*/
export function mapShippingProcessingStatusToTaskGroup(
item: ShippingProcessingProjection,
): ConversationProcessingTaskGroup {
const status = String(item.status || '').trim().toLowerCase();
const gateAction = String(item.currentGate?.nextActionCode || '').trim();
if (
status === 'waiting_review'
|| status === 'blocked'
|| status === 'failed'
|| gateAction === 'open_order_review'
|| gateAction === 'retry_parse'
|| gateAction === 'retry_failed_documents'
) {
return 'needs_action';
}
if (status === 'completed') return 'completed';
if (status === 'cancelled') return 'history';
return 'processing';
}
/**
* 将 embedded conversation_processing 的焦点元数据合并到 work_items 派生投影。
* 核心逻辑:任务列表必须来自 work_items;仅 focused_task_no / recent_task_no 可取自 embedded。
*
* @param derived - 由 projectConversationProcessingFromWorkItems 生成的投影
* @param embedded - API 内嵌 conversation_processing(可选)
* @returns 合并后的投影;derived 为空时回退 embedded
*/
export function mergeConversationProcessingFocusMetadata(
derived: ConversationProcessingProjection | null,
embedded: ConversationProcessingProjection | null | undefined,
): ConversationProcessingProjection | null {
if (!derived) {
return embedded && typeof embedded === 'object' ? embedded : null;
}
if (!embedded || typeof embedded !== 'object') return derived;
return {
...derived,
focused_task_no: embedded.focused_task_no ?? derived.focused_task_no ?? null,
recent_task_no: embedded.recent_task_no ?? derived.recent_task_no ?? null,
};
}
/**
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
* 核心逻辑:work_items 非空时始终由 order_task 工作项合成任务列表;禁止优先 embedded
* (兄弟 OT 仅出现在 work_items,embedded 可能缺 sibling)。
*
* @param workItems - unified.work_items
* @param embedded - unified.conversation_processing
* @returns 会话处理投影;无可用数据时 null
*/
export function resolveConversationProcessingFromUnified(
workItems: ShippingProcessingProjection[] | null | undefined,
embedded: ConversationProcessingProjection | null | undefined,
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
if (items.length > 0) {
return mergeConversationProcessingFocusMetadata(
projectConversationProcessingFromWorkItems(items),
embedded,
);
}
if (embedded && typeof embedded === 'object') return embedded;
return null;
}
/**
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
*
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组。
*
* @param workItems - 统一投影 work_items
* @returns 兼容投影;无 order_task 时返回 null
*/
export function projectConversationProcessingFromWorkItems(
workItems: ShippingProcessingProjection[] | null | undefined,
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
const orderTasks = items.filter((row) => row.workItemType === 'order_task');
if (!orderTasks.length) return null;
const needs_action: ConversationProcessingUserTask[] = [];
const processing: ConversationProcessingUserTask[] = [];
const completed: ConversationProcessingUserTask[] = [];
const history: ConversationProcessingUserTask[] = [];
for (const item of orderTasks) {
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
if (!taskNo) continue;
const group = mapShippingProcessingStatusToTaskGroup(item);
const docCount = Number(item.sourceSummary?.documentCount || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
const task: ConversationProcessingUserTask = {
user_task_no: taskNo,
user_task_authoritative: true,
title: filename || null,
display_kind: docCount > 1 ? 'multi_document_task' : 'single_document_task',
document_names: filename ? [filename] : [],
group,
status_label: String(item.status || '') || null,
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
run_no: null,
can_append: false,
last_activity_at: item.lastActivityAt || null,
available_actions: Array.isArray(item.availableActions) ? [...item.availableActions] : [],
primary_action: item.currentGate?.nextActionCode || item.availableActions?.[0] || null,
};
if (group === 'needs_action') needs_action.push(task);
else if (group === 'processing') processing.push(task);
else if (group === 'completed') completed.push(task);
else history.push(task);
}
const active = [...needs_action, ...processing, ...completed];
if (!active.length && !history.length) return null;
const totalFiles = active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
return {
summary: {
total_tasks: active.length,
total_files: totalFiles,
processing: processing.length,
needs_action: needs_action.length,
completed: completed.length,
history: history.length,
},
focused_task_no: null,
recent_task_no: null,
needs_action,
processing,
completed,
history,
};
}
@@ -0,0 +1,62 @@
/**
* features/chat/shipping/conversationProcessingState.spec.ts
* 用途:验收会话「本次处理中」焦点/查看/折叠状态不被普通轮询覆盖。
* 依赖:Vitest、conversationProcessingState。
* 逻辑:手动焦点优先于服务端;toggle 详情互斥;history 展开独立。
*/
import { describe, expect, it } from 'vitest';
import {
createConversationProcessingUiState,
focusTaskManually,
markTaskViewed,
resolveFocusedTask,
shouldExpandTaskDetails,
toggleTaskDetails,
} from './conversationProcessingState';
describe('conversationProcessingState', () => {
it('prefers manual focus over server focused / recent', () => {
const state = createConversationProcessingUiState();
focusTaskManually(state, 'OT-2', { expandDetails: true });
expect(resolveFocusedTask(state, {
serverFocusedTaskNo: 'OT-1',
recentTaskNo: 'OT-3',
})).toBe('OT-2');
expect(state.expandedDetailTaskNo).toBe('OT-2');
});
it('falls back to server then recent when no manual focus', () => {
const state = createConversationProcessingUiState();
expect(resolveFocusedTask(state, {
serverFocusedTaskNo: 'OT-1',
recentTaskNo: 'OT-3',
})).toBe('OT-1');
expect(resolveFocusedTask(state, { recentTaskNo: 'OT-3' })).toBe('OT-3');
});
it('marks viewed without implying resolved', () => {
const state = createConversationProcessingUiState();
markTaskViewed(state, 'OT-9');
expect(state.viewedTaskNos.has('OT-9')).toBe(true);
});
it('toggles file details and keeps only one expanded task', () => {
const state = createConversationProcessingUiState();
toggleTaskDetails(state, 'OT-A');
expect(state.expandedDetailTaskNo).toBe('OT-A');
toggleTaskDetails(state, 'OT-B');
expect(state.expandedDetailTaskNo).toBe('OT-B');
toggleTaskDetails(state, 'OT-B');
expect(state.expandedDetailTaskNo).toBeNull();
});
it('expands only when user explicitly toggles details', () => {
const state = createConversationProcessingUiState();
expect(shouldExpandTaskDetails(state, 'OT-1', { focusedTaskNo: 'OT-1' })).toBe(false);
state.expandedDetailTaskNo = 'OT-1';
expect(shouldExpandTaskDetails(state, 'OT-1', { focusedTaskNo: 'OT-1' })).toBe(true);
state.expandedDetailTaskNo = 'OT-2';
expect(shouldExpandTaskDetails(state, 'OT-1', { focusedTaskNo: 'OT-1' })).toBe(false);
expect(shouldExpandTaskDetails(state, 'OT-2', { focusedTaskNo: 'OT-1' })).toBe(true);
});
});
@@ -0,0 +1,117 @@
/**
* features/chat/shipping/conversationProcessingState.ts
* 用途:管理会话「本次处理中」焦点、已查看与文件详情展开的客户端状态。
* 依赖:无 IO;由 ShippingConversationProcessingCard / useShippingNoticeWorkflow 消费。
* 逻辑:普通轮询只合并服务端摘要,不覆盖用户手动折叠/焦点;高优先级状态只高亮不抢焦点。
*/
import { reactive } from 'vue';
export interface ConversationProcessingUiState {
/** 用户主动聚焦的用户可见任务号 */
manualFocusedTaskNo: string | null;
/** 已打开过详情的任务 */
viewedTaskNos: Set<string>;
/** 文件详情展开的任务(通常至多一个) */
expandedDetailTaskNo: string | null;
/** 处理记录分组是否展开 */
historyExpanded: boolean;
}
/**
* 创建会话级 UI 状态容器(按 conversation 实例化,切会话时重建)。
*/
export function createConversationProcessingUiState(): ConversationProcessingUiState {
return reactive({
manualFocusedTaskNo: null,
viewedTaskNos: new Set<string>(),
expandedDetailTaskNo: null,
historyExpanded: false,
});
}
/**
* 重置会话级 UI 状态(切 conversation 时调用)。
*/
export function resetConversationProcessingUiState(
state: ConversationProcessingUiState,
): void {
state.manualFocusedTaskNo = null;
state.viewedTaskNos.clear();
state.expandedDetailTaskNo = null;
state.historyExpanded = false;
}
/**
* 解析有效焦点:手动焦点优先,否则用服务端 focused_task_no / recent。
*/
export function resolveFocusedTask(
state: ConversationProcessingUiState,
options?: {
serverFocusedTaskNo?: string | null;
recentTaskNo?: string | null;
},
): string | null {
const manual = String(state.manualFocusedTaskNo || '').trim();
if (manual) return manual;
const server = String(options?.serverFocusedTaskNo || '').trim();
if (server) return server;
const recent = String(options?.recentTaskNo || '').trim();
return recent || null;
}
/**
* 用户点击任务卡:设置手动焦点并可选展开详情。
*/
export function focusTaskManually(
state: ConversationProcessingUiState,
taskNo: string,
options?: { expandDetails?: boolean },
): void {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
state.manualFocusedTaskNo = normalized;
if (options?.expandDetails !== false) {
state.expandedDetailTaskNo = normalized;
}
}
/**
* 标记任务已查看(可折叠 history;不等于 resolved)。
*/
export function markTaskViewed(state: ConversationProcessingUiState, taskNo: string): void {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
state.viewedTaskNos.add(normalized);
}
/**
* 是否展开某任务文件详情:仅当用户显式展开(expandedDetailTaskNo),不因焦点自动展开。
*/
export function shouldExpandTaskDetails(
state: ConversationProcessingUiState,
taskNo: string,
options?: {
focusedTaskNo?: string | null;
forceExpand?: boolean;
},
): boolean {
const normalized = String(taskNo || '').trim();
if (!normalized) return false;
if (options?.forceExpand) return true;
return state.expandedDetailTaskNo === normalized;
}
/**
* 切换文件详情展开;同一时刻只保留一个展开任务。
*/
export function toggleTaskDetails(
state: ConversationProcessingUiState,
taskNo: string,
): void {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
state.expandedDetailTaskNo = state.expandedDetailTaskNo === normalized
? null
: normalized;
}
@@ -0,0 +1,72 @@
/**
* features/chat/shipping/normalizeShippingProcessing.spec.ts
* 用途:验收 snake_case → camelCase 规范与缺字段安全默认。
* 依赖:Vitest、normalizeShippingProcessing。
*/
import { describe, expect, it } from 'vitest';
import {
normalizeShippingProcessingProjection,
normalizeShippingProcessingWorkItems,
} from './normalizeShippingProcessing';
describe('normalizeShippingProcessingProjection', () => {
it('maps snake_case backend payload to camelCase DTO', () => {
const normalized = normalizeShippingProcessingProjection({
work_item_type: 'order_task',
work_item_no: 'OT-1',
source_type: 'direct_pdf',
root_order_task_no: 'OT-1',
shipping_notice_no: null,
conversation_id: 'conv-1',
submission_no: 'SOS-1',
intake_no: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progress_version: 3,
last_activity_at: '2026-08-04T12:00:00Z',
current_gate: {
gate_code: 'field_conflict_resolution',
status: 'blocked',
next_action_code: 'resolve_field_conflicts',
blocking_reason_code: 'pdf_preferred_critical_conflict',
attempt_no: 1,
},
available_actions: ['open_review'],
source_summary: {
email_subject: null,
filename: 'a.pdf',
document_count: 1,
parsed_document_count: 1,
candidate_count: 1,
customer_name: 'ACME',
po_number: 'PO-1',
failure_reason_code: null,
parse_attempt_count: 0,
asset_status: 'ready',
},
child_order_tasks: [],
});
expect(normalized).not.toBeNull();
expect(normalized!.workItemNo).toBe('OT-1');
expect(normalized!.sourceType).toBe('direct_pdf');
expect(normalized!.status).toBe('waiting_review');
expect(normalized!.currentGate?.gateCode).toBe('field_conflict_resolution');
expect(normalized!.currentGate?.attemptNo).toBe(1);
expect(normalized!.sourceSummary.filename).toBe('a.pdf');
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
expect(normalized!.availableActions).toEqual(['open_review']);
});
it('returns null when work_item_no missing', () => {
expect(normalizeShippingProcessingProjection({ status: 'processing' })).toBeNull();
});
it('normalizes work_items arrays', () => {
const items = normalizeShippingProcessingWorkItems([
{ work_item_no: 'OT-A', work_item_type: 'order_task', status: 'processing', stage: 'document_parsing' },
{ status: 'processing' },
]);
expect(items).toHaveLength(1);
expect(items[0].workItemNo).toBe('OT-A');
});
});
@@ -0,0 +1,143 @@
/**
* features/chat/shipping/normalizeShippingProcessing.ts
* 用途:将后端 snake_case ShippingProcessingProjection 规范为前端 camelCase DTO。
* 依赖:shipping.api.types ShippingProcessingProjection / ProcessGateSummary。
* 逻辑:API 边界一次性转换;透传 Gate attemptNo 与 Intake 失败恢复摘要字段。
*/
import type {
OrderIntakeSourceType,
ProcessGateSummary,
ShippingOrderTaskSummary,
ShippingProcessingProjection,
ShippingProcessingStage,
ShippingProcessingStatus,
ShippingProcessingWorkItemType,
} from '../types/shipping.api.types';
/**
* 读取原始对象上的字符串字段(兼容 snake / camel)。
*/
function readString(raw: Record<string, unknown>, snake: string, camel: string): string {
const value = raw[snake] ?? raw[camel];
return value == null ? '' : String(value);
}
/**
* 读取可空字符串。
*/
function readNullableString(
raw: Record<string, unknown>,
snake: string,
camel: string,
): string | null {
const value = raw[snake] ?? raw[camel];
if (value == null || value === '') return null;
return String(value);
}
/**
* 规范单个 OT 摘要。
*/
function normalizeChildTask(raw: unknown): ShippingOrderTaskSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const orderTaskNo = readString(item, 'order_task_no', 'orderTaskNo');
if (!orderTaskNo) return null;
return {
orderTaskNo,
status: readString(item, 'status', 'status') as ShippingProcessingStatus,
stage: readString(item, 'stage', 'stage') as ShippingProcessingStage,
customerName: readNullableString(item, 'customer_name', 'customerName'),
poNumber: readNullableString(item, 'po_number', 'poNumber'),
lastActivityAt: readNullableString(item, 'last_activity_at', 'lastActivityAt'),
};
}
/**
* 规范 Gate 摘要。
*/
function normalizeGate(raw: unknown): ProcessGateSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const gateCode = readString(item, 'gate_code', 'gateCode');
if (!gateCode) return null;
return {
gateCode,
status: readString(item, 'status', 'status') || 'unknown',
nextActionCode: readNullableString(item, 'next_action_code', 'nextActionCode'),
blockingReasonCode: readNullableString(item, 'blocking_reason_code', 'blockingReasonCode'),
attemptNo: (() => {
const rawAttempt = item.attempt_no ?? item.attemptNo;
if (rawAttempt == null || rawAttempt === '') return null;
const n = Number(rawAttempt);
return Number.isFinite(n) ? n : null;
})(),
};
}
/**
* 将后端 / 混合字段投影规范为 ShippingProcessingProjection。
* 核心逻辑:缺字段给安全默认值,保证四页面可渲染;非法输入返回 null。
*
* @param raw - API 原始对象
* @returns 规范化投影;无法识别时 null
*/
export function normalizeShippingProcessingProjection(
raw: unknown,
): ShippingProcessingProjection | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const workItemNo = readString(item, 'work_item_no', 'workItemNo');
if (!workItemNo) return null;
const summaryRaw = (item.source_summary ?? item.sourceSummary ?? {}) as Record<string, unknown>;
const childrenRaw = item.child_order_tasks ?? item.childOrderTasks;
const children = Array.isArray(childrenRaw)
? childrenRaw.map(normalizeChildTask).filter((row): row is ShippingOrderTaskSummary => Boolean(row))
: [];
const actionsRaw = item.available_actions ?? item.availableActions;
const availableActions = Array.isArray(actionsRaw)
? actionsRaw.map((action) => String(action || '').trim()).filter(Boolean)
: [];
return {
workItemType: (readString(item, 'work_item_type', 'workItemType') || 'order_task') as ShippingProcessingWorkItemType,
workItemNo,
sourceType: (readNullableString(item, 'source_type', 'sourceType') || 'eml') as OrderIntakeSourceType,
rootOrderTaskNo: readNullableString(item, 'root_order_task_no', 'rootOrderTaskNo'),
shippingNoticeNo: readNullableString(item, 'shipping_notice_no', 'shippingNoticeNo'),
conversationId: readNullableString(item, 'conversation_id', 'conversationId'),
submissionNo: readString(item, 'submission_no', 'submissionNo'),
intakeNo: readString(item, 'intake_no', 'intakeNo'),
status: (readString(item, 'status', 'status') || 'processing') as ShippingProcessingStatus,
stage: (readString(item, 'stage', 'stage') || 'upload_received') as ShippingProcessingStage,
progressVersion: Number(item.progress_version ?? item.progressVersion ?? 0) || 0,
lastActivityAt: readString(item, 'last_activity_at', 'lastActivityAt'),
currentGate: normalizeGate(item.current_gate ?? item.currentGate),
availableActions,
sourceSummary: {
emailSubject: readNullableString(summaryRaw, 'email_subject', 'emailSubject'),
filename: readNullableString(summaryRaw, 'filename', 'filename'),
documentCount: Number(summaryRaw.document_count ?? summaryRaw.documentCount ?? 0) || 0,
parsedDocumentCount: Number(summaryRaw.parsed_document_count ?? summaryRaw.parsedDocumentCount ?? 0) || 0,
candidateCount: Number(summaryRaw.candidate_count ?? summaryRaw.candidateCount ?? 0) || 0,
customerName: readNullableString(summaryRaw, 'customer_name', 'customerName'),
poNumber: readNullableString(summaryRaw, 'po_number', 'poNumber'),
failureReasonCode: readNullableString(summaryRaw, 'failure_reason_code', 'failureReasonCode'),
parseAttemptCount: Number(summaryRaw.parse_attempt_count ?? summaryRaw.parseAttemptCount ?? 0) || 0,
assetStatus: readNullableString(summaryRaw, 'asset_status', 'assetStatus'),
},
childOrderTasks: children,
};
}
/**
* 将会话级统一投影响应中的 work_items 规范为数组。
*/
export function normalizeShippingProcessingWorkItems(raw: unknown): ShippingProcessingProjection[] {
if (!Array.isArray(raw)) return [];
return raw
.map(normalizeShippingProcessingProjection)
.filter((item): item is ShippingProcessingProjection => Boolean(item));
}
@@ -0,0 +1,135 @@
/**
* features/chat/shipping/shippingProcessingFulfillment.ts
*
* 用途:履约相关节点索引与人工上传 Gate 动作判定(过渡期兼容)。
* 依赖:ShippingProcessingProjection / ProcessGateSummary 的轻量字段形状。
* 逻辑:ReviewWorkflowProgressPanel、ShippingTaskWorkbench、TaskTodoPanel 共用;
* 禁止用 WorkflowItem.lifecycle 推断人工上传或节点高亮。
* FULFILLMENT_PROGRESS_NODES 四节点不是 UI 主进度真相;主真相为
* ShippingProcessingProjection 15 阶(阶段 2 换 UnifiedProgressTrack)。
*/
/** 复核/任务台共用的履约四节点 stage 键。 */
export const FULFILLMENT_PROGRESS_NODES = [
'building_order',
'inventory_matching',
'generating_excel',
'freight_uploading',
] as const;
export type FulfillmentProgressNodeKey = typeof FULFILLMENT_PROGRESS_NODES[number];
/** 指人工上传登记的任务台 / Gate 动作码(不含 RPA retry)。 */
export const MANUAL_UPLOAD_GATE_ACTIONS = new Set([
'wait_manual_upload',
'mark_manual_uploaded',
'regenerate_manual_upload_todo',
]);
/** 统一 ShippingProcessing 终态 status(停止轮询)。 */
export const TERMINAL_PROCESSING_STATUSES = new Set([
'completed',
'cancelled',
'failed',
]);
/** 统一 ShippingProcessing 非终态 status(可继续轮询)。 */
export const IN_PROGRESS_PROCESSING_STATUSES = new Set([
'queued',
'processing',
'waiting_review',
'automating',
'blocked',
'needs_action',
]);
/**
* 判定 Gate next_action / available_action 是否指人工上传登记。
*
* @param code - next_action_code 或 available_actions 项
* @returns 是否为人工上传相关动作
*/
export function isManualUploadGateAction(code: string | null | undefined): boolean {
const normalized = String(code || '').trim().toLowerCase();
return MANUAL_UPLOAD_GATE_ACTIONS.has(normalized);
}
/**
* 从统一投影判断是否需要展示任务台人工上传入口。
*
* 核心逻辑:读 currentGate.nextActionCode 与 availableActions;RPA automating /
* freight_uploading 阶段一律不算人工上传。
*
* @param projection - 统一 ShippingProcessing 投影
* @returns 是否应展示人工上传任务台入口
*/
export function projectionRequiresManualUploadWorkbench(
projection: {
status?: string | null;
stage?: string | null;
currentGate?: { nextActionCode?: string | null; blockingReasonCode?: string | null } | null;
availableActions?: string[] | null;
} | null | undefined,
): boolean {
if (!projection) return false;
const status = String(projection.status || '').trim().toLowerCase();
const stage = String(projection.stage || '').trim().toLowerCase();
if (status === 'automating' || stage === 'freight_uploading') return false;
const gate = projection.currentGate;
if (isManualUploadGateAction(gate?.nextActionCode)) return true;
const actions = Array.isArray(projection.availableActions) ? projection.availableActions : [];
return actions.some((action) => isManualUploadGateAction(action));
}
/**
* 从 Gate 摘要 / checkpoint 判断是否展示「待人工上传登记」提示。
*
* @param params.nextActionCode - process_gate 或 current_blocking_gate 的 next_action_code
* @param params.checkpointKind - ui_state.checkpoint_kind
* @param params.availableActions - 后端允许的 action 列表
* @returns 是否展示人工上传说明
*/
export function gateSummaryIndicatesManualUpload(params: {
nextActionCode?: string | null;
checkpointKind?: string | null;
availableActions?: string[] | null;
}): boolean {
if (isManualUploadGateAction(params.nextActionCode)) return true;
if (String(params.checkpointKind || '').trim() === 'wait_manual_upload') return true;
const actions = Array.isArray(params.availableActions) ? params.availableActions : [];
return actions.some((action) => isManualUploadGateAction(action));
}
/**
* 将统一 stage/status 映射到履约四节点索引(0..3)。
*
* @param stage - ShippingProcessingStage
* @param status - ShippingProcessingStatus
* @returns 当前节点索引;无法映射时返回 -1
*/
export function fulfillmentNodeIndexFromStage(
stage?: string | null,
status?: string | null,
): number {
const s = String(stage || '').trim().toLowerCase();
const st = String(status || '').trim().toLowerCase();
if (st === 'completed' || s === 'completed') return 3;
if (s === 'freight_uploading' || st === 'automating') return 3;
if (s === 'excel_generating' || s === 'generating_excel') return 2;
if (s === 'inventory_matching' || s.startsWith('inventory_')) return 1;
if (
s === 'building_order'
|| s === 'order_creating'
|| s === 'document_parsing'
|| s === 'upload_received'
|| s.startsWith('email_')
|| s === 'waiting_review'
|| s === 'customer_resolving'
|| s === 'duplicate_checking'
|| s === 'candidate_creating'
) {
return 0;
}
if (s) return 0;
return -1;
}
@@ -0,0 +1,40 @@
/**
* features/chat/shipping/shippingProcessingLabels.spec.ts
* 用途:验收统一状态文案映射到 chat.shippingProcessing。
* 依赖:Vitest、shippingProcessingLabels。
*/
import { describe, expect, it } from 'vitest';
import {
resolveShippingProcessingMessage,
resolveShippingProcessingStatusLabel,
shippingProcessingStatusKey,
} from './shippingProcessingLabels';
describe('shippingProcessingLabels', () => {
it('bridges pending_review to waiting_review key', () => {
expect(shippingProcessingStatusKey('pending_review')).toBe(
'chat.shippingProcessing.status.waiting_review',
);
});
it('falls back to shippingProcessing.taskStatus when unified status missing', () => {
// 关键断言:旧 taskStatus 已合并进 shippingProcessing。
const te = (key: string) => key === 'chat.shippingProcessing.taskStatus.queued';
const t = (key: string) => (key.endsWith('queued') ? '排队中' : key);
expect(resolveShippingProcessingStatusLabel('queued', te, t)).toBe('排队中');
});
it('uses unified label when available', () => {
const te = (key: string) => key === 'chat.shippingProcessing.status.waiting_review';
const t = (key: string) => (key.includes('waiting_review') ? '待复核' : key);
expect(resolveShippingProcessingStatusLabel('pending_review', te, t)).toBe('待复核');
});
it('resolves group messages from shippingProcessing', () => {
const te = (key: string) => key === 'chat.shippingProcessing.groupNeedsAction';
const t = (key: string, params?: Record<string, unknown>) => (
key.includes('groupNeedsAction') ? `需要你处理 · ${params?.count}` : key
);
expect(resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: 2 })).toBe('需要你处理 · 2');
});
});
@@ -0,0 +1,114 @@
/**
* features/chat/shipping/shippingProcessingLabels.ts
* 用途:将统一 ShippingProcessing 状态/阶段码映射到四语言 i18n 键。
* 依赖:vue-i18n Composer(由调用方传入 t / te)。
* 逻辑:统一读 chat.shippingProcessing.*(含原 shippingWorkflow 合并键,如 taskStatus)。
*/
/** 会话 processing 旧 status_label → 统一 ShippingProcessingStatus。 */
const LEGACY_STATUS_TO_PROCESSING: Record<string, string> = {
queued: 'processing',
processing: 'processing',
pending_review: 'waiting_review',
waiting_review: 'waiting_review',
failed: 'failed',
completed: 'completed',
cancelled: 'cancelled',
cancelling: 'processing',
blocked: 'blocked',
automating: 'automating',
};
/**
* 解析统一处理状态的展示文案键。
* 核心逻辑:优先 `chat.shippingProcessing.status.<code>`。
* @param status - ShippingProcessingStatus 码
* @returns i18n key
*/
export function shippingProcessingStatusKey(status: string): string {
const code = String(status || '').trim();
const mapped = LEGACY_STATUS_TO_PROCESSING[code] || code;
return mapped
? `chat.shippingProcessing.status.${mapped}`
: 'chat.shippingProcessing.status.processing';
}
/**
* 解析任务状态展示文案。
*
* @param code - 后端 status / status_label
* @param te - i18n te
* @param t - i18n t
* @returns 本地化文案;皆无则回退原码
*/
export function resolveShippingProcessingStatusLabel(
code: string,
te: (key: string) => boolean,
t: (key: string) => string,
): string {
const raw = String(code || '').trim();
if (!raw) return '—';
const processingKey = shippingProcessingStatusKey(raw);
if (te(processingKey)) return t(processingKey);
const taskStatusKey = `chat.shippingProcessing.taskStatus.${raw}`;
if (te(taskStatusKey)) return t(taskStatusKey);
return raw;
}
/**
* 解析统一处理文案。
*
* @param leaf - 文案叶子键(如 groupNeedsAction)
* @param te - i18n te
* @param t - i18n t
* @param params - 插值参数
* @returns 本地化文案
*/
export function resolveShippingProcessingMessage(
leaf: string,
te: (key: string) => boolean,
t: (key: string, params?: Record<string, unknown>) => string,
params?: Record<string, unknown>,
): string {
const code = String(leaf || '').trim();
if (!code) return '';
const primary = `chat.shippingProcessing.${code}`;
if (te(primary)) return t(primary, params);
return code;
}
/**
* 解析统一处理阶段的展示文案键。
* @param stage - ShippingProcessingStage 码
* @returns i18n key
*/
export function shippingProcessingStageKey(stage: string): string {
const code = String(stage || '').trim();
return code
? `chat.shippingProcessing.stage.${code}`
: 'chat.shippingProcessing.stage.upload_received';
}
/**
* 解析工作项类型文案键。
* @param workItemType - order_intake | order_task
* @returns i18n key
*/
export function shippingProcessingWorkItemTypeKey(workItemType: string): string {
const code = String(workItemType || '').trim();
return code
? `chat.shippingProcessing.workItemType.${code}`
: 'chat.shippingProcessing.workItemType.order_task';
}
/**
* 解析来源类型文案键(eml / direct_pdf)。
* @param sourceType - OrderIntakeSourceType
* @returns i18n key
*/
export function shippingProcessingSourceTypeKey(sourceType: string): string {
const code = String(sourceType || '').trim();
return code
? `chat.shippingProcessing.sourceType.${code}`
: 'chat.shippingProcessing.sourceType.eml';
}
@@ -5,7 +5,10 @@
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingWorkflowSteps } from './shippingStepper';
import {
applyShippingProcessingStageToSteps,
buildShippingWorkflowSteps,
} from './shippingStepper';
describe('shippingStepper', () => {
it('marks inventory step as blocked when RPA inventory is exhausted', () => {
@@ -29,4 +32,19 @@ describe('shippingStepper', () => {
expect(steps[2]?.status).toBe('blocked');
});
it('overlays unified processing stage onto base stepper steps', () => {
const base = buildShippingWorkflowSteps({
process_status: 'parsed',
current_step: 'step2_parse_confirm',
});
const overlaid = applyShippingProcessingStageToSteps(base, {
status: 'waiting_review',
stage: 'waiting_review',
currentGate: { status: 'blocked' },
});
// 关键断言:统一投影 waiting_review 应把第 2 步标为 blocked,而非沿用旧 process_status。
expect(overlaid[1]?.status).toBe('blocked');
expect(overlaid[0]?.status).toBe('completed');
});
});
@@ -1,9 +1,15 @@
/**
* features/chat/shipping/shippingStepper.ts
* 用途:基于 shipping task 状态推导前端七步 Stepper 展示数据。
* 依赖:无外部模块;ShippingWorkflowStepper.vue 消费本模块输出。
* 逻辑:buildShippingWorkflowSteps 将 process_status / checkpoint 等映射为步骤 id 与 done/active 状态。
* 用途:基于 shipping task 状态推导前端 Stepper 展示数据(七步 legacy / 四步履约)。
* 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。
* 逻辑:任务台优先 buildFulfillmentWorkflowSteps(四节点);无投影时不回退旧 ui_state;
* resolveShippingWorkflowSteps 仍供对话等未切流页面作 legacy 回退。
*/
import {
FULFILLMENT_PROGRESS_NODES,
fulfillmentNodeIndexFromStage,
type FulfillmentProgressNodeKey,
} from './shippingProcessingFulfillment';
export interface ShippingTaskStepperSource {
process_status?: string | null;
review_status?: string | null;
@@ -135,6 +141,64 @@ function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined):
return 0;
}
/** 统一 ShippingProcessingStage → 粗粒度 Stepper 下标(过渡期;阶段 2 换 UnifiedProgressTrack)。 */
const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
upload_received: 0,
email_parsing: 1,
document_parsing: 1,
email_adjudicating: 1,
candidate_creating: 1,
customer_resolving: 1,
duplicate_checking: 1,
// 业务 15 阶中库存源在复核前;七步 legacy 仍映射到「库存准备」步。
inventory_source_resolving: 2,
waiting_review: 1,
order_creating: 1,
inventory_fetching: 2,
inventory_matching: 4,
excel_generating: 5,
freight_uploading: 6,
completed: 6,
};
/**
* 用统一投影 stage/status 覆盖 Stepper 当前步(切流主源)。
*
* 核心逻辑:有投影时按 stage 重算 completed/current/pending;blocked/failed 标当前步 blocked;
* 无投影或无法映射时原样返回 baseSteps。
*
* @param baseSteps - ui_state / process_status 推导的步骤
* @param projection - 统一 order_task 投影
*/
export function applyShippingProcessingStageToSteps(
baseSteps: ShippingWorkflowStepItem[],
projection: { status?: string | null; stage?: string | null; currentGate?: { status?: string | null } | null } | null | undefined,
): ShippingWorkflowStepItem[] {
if (!projection || !baseSteps.length) return baseSteps;
const stage = String(projection.stage || '').trim();
const status = String(projection.status || '').trim().toLowerCase();
const stageIndex = PROCESSING_STAGE_INDEX_MAP[stage];
if (stageIndex === undefined && status !== 'completed' && status !== 'failed' && status !== 'blocked') {
return baseSteps;
}
const currentIndex = status === 'completed' ? baseSteps.length - 1 : (stageIndex ?? 0);
const gateBlocked = String(projection.currentGate?.status || '').trim().toLowerCase() === 'blocked'
|| status === 'blocked'
|| status === 'failed'
|| status === 'waiting_review';
return baseSteps.map((step, index) => {
let nextStatus: ShippingWorkflowStepItem['status'] = 'pending';
if (status === 'completed' || status === 'cancelled') {
nextStatus = 'completed';
} else if (index < currentIndex) {
nextStatus = 'completed';
} else if (index === currentIndex) {
nextStatus = gateBlocked ? 'blocked' : 'current';
}
return { ...step, status: nextStatus };
});
}
/**
* 将 task 状态映射为七步 Stepper 项(id / label / done / active)。
*/
@@ -178,3 +242,45 @@ export function buildShippingWorkflowSteps(
};
});
}
/**
* 从统一 ShippingProcessing 投影构建履约四节点 Stepper(任务台主源)。
*
* 核心逻辑:仅在有投影时返回步骤;节点标签由调用方传入 i18n 文案。
*
* @param projection - 统一 order_task 投影
* @param nodeLabels - 四节点展示文案(building_order … freight_uploading)
* @returns 四步 Stepper 项;无投影时返回 null
*/
export function buildFulfillmentWorkflowSteps(
projection: {
stage?: string | null;
status?: string | null;
currentGate?: { status?: string | null } | null;
} | null | undefined,
nodeLabels: Record<FulfillmentProgressNodeKey, string>,
): ShippingWorkflowStepItem[] | null {
if (!projection) return null;
const activeIndex = fulfillmentNodeIndexFromStage(projection.stage, projection.status);
const status = String(projection.status || '').trim().toLowerCase();
const gateBlocked = String(projection.currentGate?.status || '').trim().toLowerCase() === 'blocked'
|| status === 'blocked'
|| status === 'failed'
|| status === 'waiting_review';
return FULFILLMENT_PROGRESS_NODES.map((key, index) => {
let stepStatus: ShippingWorkflowStepItem['status'] = 'pending';
if (status === 'completed' || status === 'cancelled') {
stepStatus = 'completed';
} else if (activeIndex >= 0 && index < activeIndex) {
stepStatus = 'completed';
} else if (activeIndex >= 0 && index === activeIndex) {
stepStatus = gateBlocked ? 'blocked' : 'current';
}
return {
id: `fulfillment-${key}`,
label: nodeLabels[key as FulfillmentProgressNodeKey],
status: stepStatus,
};
});
}
@@ -0,0 +1,42 @@
/**
* features/chat/shipping/shippingSubmissionFeedback.spec.ts
* 用途:验收统一提交决策反馈结构(无弹窗、含短时标签码)。
* 依赖:Vitest、shippingSubmissionFeedback。
*/
import { describe, expect, it } from 'vitest';
import {
buildShippingSubmissionFeedback,
createComposerContextId,
createShippingSubmissionId,
} from './shippingSubmissionFeedback';
describe('shippingSubmissionFeedback', () => {
it('maps appended / created decisions to badge codes', () => {
expect(buildShippingSubmissionFeedback({
decision: 'appended',
user_task_no: 'OT-1',
run_no: 'RUN-1',
created_new: false,
}, 3)).toMatchObject({
decision: 'appended',
badgeCode: 'just_appended',
fileCount: 3,
recentAppendCount: 3,
});
expect(buildShippingSubmissionFeedback({
decision: 'created',
user_task_no: 'OT-2',
run_no: 'RUN-2',
created_new: true,
}, 1)).toMatchObject({
decision: 'created',
badgeCode: 'just_created',
createdNew: true,
});
});
it('creates stable-looking submission and composer ids', () => {
expect(createShippingSubmissionId()).toMatch(/^SUB-/);
expect(createComposerContextId()).toMatch(/^CMP-/);
});
});
@@ -0,0 +1,63 @@
/**
* features/chat/shipping/shippingSubmissionFeedback.ts
* 用途:根据统一提交决策生成聊天区非阻塞系统文案与右侧短时标签。
* 依赖:OrderExtractionSubmissionResponse;不含敏感数据。
* 逻辑:由 useShippingOrderExtractionRuns / ChatMessageBubble 消费;不弹窗、不作为唯一 Toast。
*/
import type { OrderExtractionSubmissionResponse } from '@/features/chat/types/shipping.api.types';
export interface ShippingSubmissionFeedback {
/** 聊天区可回看系统消息正文(调用方再走 i18n 模板时也可只用 decision) */
decision: 'appended' | 'created';
fileCount: number;
userTaskNo: string;
runNo: string;
createdNew: boolean;
reasonCode?: string | null;
/** 右侧任务卡短时标签码 */
badgeCode: 'just_appended' | 'just_created';
recentAppendCount?: number;
}
/**
* 从提交响应生成用户可见反馈结构。
* @param response - 统一提交 API 响应
* @param fileCount - 本次发送附件数
*/
export function buildShippingSubmissionFeedback(
response: OrderExtractionSubmissionResponse,
fileCount: number,
): ShippingSubmissionFeedback {
const decision = response.decision === 'appended' ? 'appended' : 'created';
return {
decision,
fileCount: Math.max(0, Number(fileCount) || 0),
userTaskNo: String(response.user_task_no || '').trim(),
runNo: String(response.run_no || '').trim(),
createdNew: Boolean(response.created_new),
reasonCode: response.reason_code ?? null,
badgeCode: decision === 'appended' ? 'just_appended' : 'just_created',
recentAppendCount: decision === 'appended' ? Math.max(0, Number(fileCount) || 0) : undefined,
};
}
/**
* 生成稳定 submission_id(同一次发送重试用同一 id)。
*/
export function createShippingSubmissionId(): string {
if (typeof globalThis.crypto?.randomUUID === 'function') {
return `SUB-${globalThis.crypto.randomUUID()}`;
}
return `SUB-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
/**
* 生成输入区短生命周期 composer_context_id。
*/
export function createComposerContextId(): string {
if (typeof globalThis.crypto?.randomUUID === 'function') {
return `CMP-${globalThis.crypto.randomUUID()}`;
}
return `CMP-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
@@ -1,43 +1,24 @@
/**
* features/chat/shipping/shippingTurnActions.spec.ts
* 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
* 用途:验证决策/冻结等 Chat Turn 映射(不含已下线的 create_batch)。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingCreateBatchFromIntakesTurn, buildShippingCreateBatchTurn, resolveShippingChatTurn } from './shippingTurnActions';
import { resolveShippingChatTurn } from './shippingTurnActions';
describe('shippingTurnActions', () => {
it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
const files = [
new File(['notice-a'], 'notice-a.txt', { type: 'text/plain' }),
new File(['notice-b'], 'notice-b.txt', { type: 'text/plain' }),
];
const turn = buildShippingCreateBatchTurn(files, 'conv-001', 'idem-key-001');
expect(turn.actionType).toBe('shipping.create_batch_from_notices');
expect(turn.payload.conversation_id).toBe('conv-001');
expect(turn.payload.file_count).toBe(2);
expect(turn.payload.idempotency_key).toBe('idem-key-001');
expect(turn.files).toEqual(files);
});
it('buildShippingCreateBatchFromIntakesTurn includes selected candidate_nos', () => {
const turn = buildShippingCreateBatchFromIntakesTurn(
['SNI-001'],
'conv-001',
'idem-candidate-001',
['SNC-001', 'SNC-003'],
);
expect(turn.actionType).toBe('shipping.create_batch_from_intakes');
expect(turn.payload.intake_nos).toEqual(['SNI-001']);
expect(turn.payload.candidate_nos).toEqual(['SNC-001', 'SNC-003']);
});
it('maps freeze_order only with the version shown to the user', () => {
// 关键断言:缺版本不得构造 freeze Turn,避免乐观锁盲写。
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001')).toBeNull();
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001', { expectedOrderDataVersion: 7 })).toEqual({
actionType: 'shipping.freeze_order',
payload: { task_no: 'SN-FREEZE-001', expected_order_data_version: 7 },
});
});
it('maps confirm decision to submit_decision', () => {
expect(resolveShippingChatTurn('confirm', 'sn-1')).toEqual({
actionType: 'shipping.submit_decision',
payload: { task_no: 'SN-1', decision: 'confirm' },
});
});
});
@@ -2,7 +2,8 @@
* features/chat/shipping/shippingTurnActions.ts
* 用途:将发货通知菜单/决策 action.id 映射为 Chat Turn action_type + payload。
* 依赖:constants/shipping。
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息。
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息;
* co8 后已移除 create_batch / switch_batch_focus Turn 构造器,上传改走 Intake + order extraction。
*/
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
@@ -82,55 +83,6 @@ export function buildShippingSubmitDecisionTurn(
},
};
}
/**
* 构造发货通知建批 Chat Turn(multipart 上传)。
*/
export function buildShippingCreateBatchTurn(
files: File[],
conversationId?: string | null,
idempotencyKey?: string,
): { actionType: string; displayText: string; payload: Record<string, unknown>; files: File[] } {
const count = files.length;
const displayText = count === 1
? `上传发货通知:${files[0]?.name || '附件'}`
: `上传 ${count} 份发货通知`;
return {
actionType: 'shipping.create_batch_from_notices',
displayText,
payload: {
conversation_id: conversationId || undefined,
file_count: count,
idempotency_key: idempotencyKey,
},
files,
};
}
/**
* 构造发货通知建批 Chat Turn(基于已解析 intake,不再携带 files)。
*/
export function buildShippingCreateBatchFromIntakesTurn(
intakeNos: string[],
conversationId?: string | null,
idempotencyKey?: string,
candidateNos?: string[],
): { actionType: string; displayText: string; payload: Record<string, unknown> } {
const count = intakeNos.length;
const displayText = count === 1
? `确认建单:${intakeNos[0]}`
: `确认建单:${count} 份发货通知`;
return {
actionType: 'shipping.create_batch_from_intakes',
displayText,
payload: {
intake_nos: intakeNos,
conversation_id: conversationId || undefined,
idempotency_key: idempotencyKey,
candidate_nos: candidateNos,
},
};
}
/**
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
*/
@@ -143,6 +95,9 @@ export function buildShippingTurnRefs(taskNo: string, batchNo?: string): Record<
return refs;
}
/**
* 构造重新上传发货通知 Chat Turn。
*/
export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) {
const task = String(taskNo || '').trim().toUpperCase();
return {
@@ -154,17 +109,9 @@ export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) {
};
}
export function buildShippingSwitchFocusTurn(batchNo: string, taskNo: string, displayText: string) {
const batch = String(batchNo || '').trim();
const task = String(taskNo || '').trim().toUpperCase();
return {
actionType: 'shipping.switch_batch_focus',
displayText,
payload: { batch_no: batch, task_no: task },
refs: buildShippingTurnRefs(task, batch),
};
}
/**
* 构造短缺明细查询 Chat Turn。
*/
export function buildShippingQueryShortageTurn(taskNo: string, displayText: string) {
const task = String(taskNo || '').trim().toUpperCase();
return {
@@ -251,4 +251,17 @@ describe('useChatShippingSendHandler', () => {
expect(attachments.value).toEqual([attachment]);
expect(ctx.msg.warning).toHaveBeenCalledWith('run create failed');
});
it('warns and consumes send when user tries batch task switching (co8 batch API retired)', async () => {
const ctx = createContext({
getActiveShippingBatchNo: () => 'SB-TEST',
});
const { tryHandleShippingSend } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingSend(undefined, '下一票', '下一票');
expect(consumed).toBe(true);
expect(ctx.startChatTurn).not.toHaveBeenCalled();
expect(ctx.msg.warning).toHaveBeenCalledWith('chat.shippingNoticeUi.batchSwitchRemoved');
});
});
@@ -1,15 +1,13 @@
/**
* features/chat/shipping/useChatShippingSendHandler.ts
* 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本和附件自动流程。
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingDownload、chat.types。
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;其他业务动作经 Chat Turn / handleShippingMenuAction。
* 依赖:shipping.api(任务详情)、shippingIntents、shippingMenu、shippingDownload、chat.types。
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;co8 后切票不再调用 shipping_batches API,改提示用户使用 processing 工作台。
*/
import {
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
} from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
import { buildShippingSwitchFocusTurn } from './shippingTurnActions';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import {
isShippingDownloadExcelIntent,
@@ -146,58 +144,17 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
}
};
/**
* 拦截切票/切任务意图(co8 已下线批次 API)。
*
* 核心逻辑:识别切换意图后提示用户使用右侧 processing 工作台,消费发送且不发起网络请求。
* @param content - 用户输入
* @returns 识别到切换意图时恒为 true
*/
const trySwitchShippingTask = async (content: string): Promise<boolean> => {
const intent = parseShippingTaskSwitchIntent(content);
if (!intent) return false;
const batchNo = ctx.getActiveShippingBatchNo();
if (!batchNo) {
ctx.msg.warning('当前没有可切换的批次');
return true;
}
try {
const detail = await getWorkspaceShippingBatch(batchNo);
const tasks = Array.isArray(detail.tasks) ? detail.tasks : [];
if (tasks.length <= 1) {
ctx.msg.info('当前批次只有 1 票,无需切换');
return true;
}
const focusTaskNo = String(detail.focus_task?.task_no || detail.current_focus_task_no || '').trim().toUpperCase();
const currentIndex = Math.max(tasks.findIndex((item) => String(item.task_no || '').trim().toUpperCase() === focusTaskNo), 0);
let targetTaskNo = '';
if (intent.mode === 'task') {
targetTaskNo = String(intent.taskNo || '').trim().toUpperCase();
} else if (intent.mode === 'next') {
targetTaskNo = String(tasks[Math.min(currentIndex + 1, tasks.length - 1)]?.task_no || '').trim().toUpperCase();
} else {
targetTaskNo = String(tasks[Math.max(currentIndex - 1, 0)]?.task_no || '').trim().toUpperCase();
}
if (!targetTaskNo) {
ctx.msg.warning('未找到要切换的任务');
return true;
}
if (targetTaskNo === focusTaskNo) {
ctx.msg.info(intent.mode === 'next' ? '已经是最后一票' : intent.mode === 'prev' ? '已经是第一票' : '已在当前任务');
return true;
}
ctx.resolvedShippingTaskId.value = targetTaskNo;
const turn = buildShippingSwitchFocusTurn(batchNo, targetTaskNo, content.trim());
await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
refs: turn.refs,
hooks: {
onAssistantMessageFinished: async () => {
void ctx.refreshShippingActions();
},
},
});
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '切换任务失败';
ctx.msg.warning(errorMessage);
}
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.batchSwitchRemoved'));
return true;
};
@@ -293,10 +250,11 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
}
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
if (!trimmed || requestedAutoFlow) {
// co8:本地文件改走 Intake 入队,不再清空后打 create_batch Chat Turn。
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
try {
await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file));
ctx.attachments.value = ctx.attachments.value.filter((item) => item.kind !== 'local');
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
ctx.msg.warning(errorMessage);
@@ -2,7 +2,7 @@
* features/chat/shipping/useChatShippingUploadHandler.spec.ts
* 用途:验证发货通知上传 handler 在显式 taskId 场景下不会把库存/通知文件错投到当前激活任务。
* 依赖:vitest、vue refs、shipping.api、useChatShippingUploadHandler。
* 逻辑:覆盖库存/通知 picker 的任务锁定,以及 Chat Turn 建批/覆盖路径。
* 逻辑:覆盖库存/通知 picker 的任务锁定、replace_notice Turn,以及 Intake/OT 提交路径。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -55,8 +55,10 @@ const createContext = (
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
startChatTurn: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
msg: { warning: vi.fn() },
msg: { warning: vi.fn(), info: vi.fn() },
t: (key: string) => key,
enqueueNoticeFiles: vi.fn(async () => undefined),
startOrderExtractionRun: vi.fn(async () => true),
sendTemporaryInventoryMessage: vi.fn(async () => undefined),
...overrides,
});
@@ -148,33 +150,50 @@ describe('useChatShippingUploadHandler', () => {
expect(ctx.pendingShippingNoticeTaskId.value).toBe('');
});
it('creates notice batch via Chat Turn instead of local assistant push', async () => {
it('enqueues notice files as intakes instead of create_batch Chat Turn', async () => {
const enqueueNoticeFiles = vi.fn(async () => undefined);
const ctx = createContext({
getActiveShippingTaskId: () => '',
enqueueNoticeFiles,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
inputType: 'upload_followup',
actionType: 'shipping.create_batch_from_notices',
displayText: expect.stringContaining('notice.pdf'),
files: [file],
}),
);
expect(enqueueNoticeFiles).toHaveBeenCalledWith([file]);
expect(ctx.startChatTurn).not.toHaveBeenCalled();
});
it('double click only calls startChatTurn once and keeps stable idempotency key', async () => {
const startChatTurn = vi.fn(async () => {
it('submits parsed intakes via order extraction instead of create_batch_from_intakes', async () => {
const startOrderExtractionRun = vi.fn(async () => true);
const clearConsumedNoticeAttachments = vi.fn();
const ctx = createContext({
getActiveShippingTaskId: () => '',
getParsedIntakeNos: () => ['SNI-1'],
startOrderExtractionRun,
clearConsumedNoticeAttachments,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
await handleShippingAutoUploadNoticeBatch([]);
expect(startOrderExtractionRun).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultUserMessage',
['SNI-1'],
[],
);
expect(clearConsumedNoticeAttachments).toHaveBeenCalled();
expect(ctx.startChatTurn).not.toHaveBeenCalled();
});
it('double click only enqueues notice files once', async () => {
const enqueueNoticeFiles = vi.fn(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
return true;
});
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
enqueueNoticeFiles,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
@@ -183,168 +202,30 @@ describe('useChatShippingUploadHandler', () => {
const second = handleShippingAutoUploadNoticeBatch([file]);
await Promise.all([first, second]);
expect(startChatTurn).toHaveBeenCalledTimes(1);
const payload = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload;
expect(payload?.idempotency_key).toBeTruthy();
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1);
});
it('reuses idempotency key on retry and generates new key after success', async () => {
let attempt = 0;
const startChatTurn = vi.fn(async () => {
attempt += 1;
return attempt >= 2;
it('releases submit lock when enqueueNoticeFiles fails', async () => {
const enqueueNoticeFiles = vi.fn(async () => {
throw new Error('enqueue failed');
});
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const thirdKey = (startChatTurn.mock.calls[2]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBe(secondKey);
expect(thirdKey).not.toBe(secondKey);
});
it('generates new idempotency key when files change after a failed attempt', async () => {
const startChatTurn = vi.fn(async () => false);
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const firstFile = new File(['notice-a'], 'notice-a.pdf', { type: 'application/pdf' });
const secondFile = new File(['notice-b'], 'notice-b.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([firstFile]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([secondFile]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('reuses idempotency key when conversation upgrades from empty to server-assigned after network failure', async () => {
const conversationId = ref<string | null>(null);
const startChatTurn = vi.fn(async () => {
conversationId.value = 'conv-server-new';
return false;
});
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBe(firstKey);
});
it('generates new idempotency key when switching from new chat to historical session', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref<string | null>(null);
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
onNoticeBatchConversationChanging('conv-history', '');
conversationId.value = 'conv-history';
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('generates new idempotency key after explicit clearPendingNoticeBatchRetry', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref('conv-a');
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
clearPendingNoticeBatchRetry();
conversationId.value = null;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('generates new idempotency key when conversation changes after a failed attempt', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref('conv-a');
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
onNoticeBatchConversationChanging('conv-b', 'conv-a');
conversationId.value = 'conv-b';
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('releases submit lock when fingerprint computation fails', async () => {
computeNoticeFilesContentFingerprint.mockRejectedValueOnce(new Error('digest failed'));
const startChatTurn = vi.fn(async () => true);
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
enqueueNoticeFiles,
});
const { handleShippingAutoUploadNoticeBatch, isShippingNoticeBatchSubmitting } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await expect(handleShippingAutoUploadNoticeBatch([file])).rejects.toThrow('digest failed');
expect(startChatTurn).not.toHaveBeenCalled();
expect(isShippingNoticeBatchSubmitting()).toBe(false);
computeNoticeFilesContentFingerprint.mockResolvedValueOnce('fp-notice');
await handleShippingAutoUploadNoticeBatch([file]);
expect(startChatTurn).toHaveBeenCalledTimes(1);
expect(ctx.startChatTurn).not.toHaveBeenCalled();
expect(isShippingNoticeBatchSubmitting()).toBe(false);
expect(ctx.msg.warning).toHaveBeenCalled();
});
it('compatibility hooks for pending batch retry remain callable after co8', () => {
clearPendingNoticeBatchRetry();
onNoticeBatchConversationChanging('conv-b', 'conv-a');
expect(true).toBe(true);
});
it('does not open notice picker when both explicit taskId and active task are missing', () => {
@@ -1,83 +1,39 @@
/**
* features/chat/shipping/useChatShippingUploadHandler.ts
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
* 用途:处理发货通知与库存文件上传、订单抽取提交和附件建议提示。
* 依赖:shipping.api、file-assets.api、shippingUploadPrompt、shipping 常量、chat.types。
* 逻辑:发货通知建批和单票覆盖经 Chat Turn;对话上传库存文件先成为私有临时资产,再进入 Dify 受控分析分支。
* 逻辑:co8 后不再走 shipping_batches Chat Turn;新通知经 enqueueNoticeFiles / startOrderExtractionRun;
* 单票覆盖仍经 replace_notice Turn;库存文件先成为私有临时资产再进 Dify 分析分支。
*/
import { computed } from 'vue';
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import { extractExt } from '../constants/shipping';
import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
import { computeNoticeFilesContentFingerprint, computeNoticeIntakeNosFingerprint } from './shippingNoticeBatchIdempotency';
import { buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
import type { PendingAttachment } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
let noticeBatchSubmitting = false;
interface PendingNoticeBatchRetryState {
conversationId: string;
idempotencyKey: string;
fileFingerprint: string;
}
let pendingNoticeBatchRetry: PendingNoticeBatchRetryState | null = null;
function normalizeConversationId(conversationId: string | null | undefined): string {
return String(conversationId || '').trim();
}
function clearPendingNoticeBatchRetryState(): void {
pendingNoticeBatchRetry = null;
}
/**
* 显式清理待重试建批幂等状态(新建聊天、切换 Agent 等不经 onConversationIdChanging 的路径)。
* 显式清理待重试建批幂等状态(co8 后建批已下线,保留空实现供会话切换调用方兼容)。
*/
export function clearPendingNoticeBatchRetry(): void {
clearPendingNoticeBatchRetryState();
/* no-op: shipping_batches 已 DROP */
}
/**
* 判断待重试状态是否应绑定到当前会话。
* 核心逻辑:允许「尚未分配会话」升级绑定服务端新 ID;两个非空且不同、或旧非空而新为空时清理。
*/
function reconcilePendingNoticeBatchConversation(
pending: PendingNoticeBatchRetryState,
conversationKey: string,
): void {
const pendingKey = pending.conversationId;
if (pendingKey === conversationKey) {
return;
}
if (!pendingKey && conversationKey) {
pending.conversationId = conversationKey;
return;
}
if (pendingKey && !conversationKey) {
clearPendingNoticeBatchRetryState();
return;
}
if (pendingKey && conversationKey && pendingKey !== conversationKey) {
clearPendingNoticeBatchRetryState();
}
}
/**
* 用户主动切换会话时清理待重试建批状态,避免跨会话复用幂等键。
* 仅由 onConversationIdChanging 调用;SSE 自动分配 conversation_id 不经过此函数。
* 用户主动切换会话时的钩子(co8 后无幂等键可清)。
* @param _nextId - 新会话 ID
* @param _prevId - 旧会话 ID
*/
export function onNoticeBatchConversationChanging(
nextId: string,
prevId?: string | null,
_nextId: string,
_prevId?: string | null,
): void {
const next = normalizeConversationId(nextId);
const prev = normalizeConversationId(prevId);
if (next !== prev) {
clearPendingNoticeBatchRetryState();
}
/* no-op */
}
/**
@@ -113,11 +69,20 @@ export interface ShippingUploadHandlerContext {
getActiveShippingTaskId: () => string;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
msg: { warning: (text: string) => void };
msg: { warning: (text: string) => void; info?: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
getParsedIntakeNos?: () => string[];
getSelectedCandidateNos?: () => string[];
clearConsumedNoticeAttachments?: () => void;
/** 将本地文件加入输入栏并创建 Intake(替代旧 create_batch_from_notices)。 */
enqueueNoticeFiles?: (files: File[]) => Promise<void>;
/** 对已解析 Intake 发起订单抽取提交。 */
startOrderExtractionRun?: (
query: string,
intakeNos: string[],
attachments: ChatMessageAttachment[],
uploadBatchId?: string,
) => Promise<boolean>;
sendTemporaryInventoryMessage: (assetNo: string, fileName: string) => Promise<unknown>;
}
@@ -202,56 +167,28 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
};
/**
* 将本地通知文件加入输入栏并创建 Intake(不再走 shipping_batches Chat Turn)。
* @param files - 用户选择的发货通知文件
* @returns 是否完成入队
*/
const runNoticeBatchChatTurn = async (files: File[]) => {
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
const conversationKey = normalizeConversationId(ctx.conversationId.value);
const fileFingerprint = await computeNoticeFilesContentFingerprint(files);
if (pendingNoticeBatchRetry) {
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
}
if (
pendingNoticeBatchRetry
&& pendingNoticeBatchRetry.fileFingerprint !== fileFingerprint
) {
clearPendingNoticeBatchRetryState();
}
if (!pendingNoticeBatchRetry) {
pendingNoticeBatchRetry = {
conversationId: conversationKey,
idempotencyKey: crypto.randomUUID(),
fileFingerprint,
};
} else {
pendingNoticeBatchRetry.fileFingerprint = fileFingerprint;
}
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value, idempotencyKey);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
if (ok) {
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
clearPendingNoticeBatchRetryState();
}
} else {
if (!ctx.enqueueNoticeFiles) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
}
return ok;
await ctx.enqueueNoticeFiles(files);
ctx.msg.info?.(ctx.t('chat.shippingNoticeWaitingForParse'));
void ctx.refreshShippingActions();
return true;
} catch {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
} finally {
noticeBatchSubmitting = false;
}
@@ -278,61 +215,34 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return ok;
};
const runNoticeBatchFromIntakes = async (intakeNos: string[], candidateNos: string[]) => {
/**
* 对已解析 Intake 发起订单抽取提交(替代 create_batch_from_intakes)。
* @param intakeNos - 已解析 Intake 编号
* @param _candidateNos - 保留签名;候选选择由提交服务侧裁决
* @returns 是否提交成功
*/
const runNoticeBatchFromIntakes = async (intakeNos: string[], _candidateNos: string[]) => {
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
const conversationKey = normalizeConversationId(ctx.conversationId.value);
const intakeFingerprint = computeNoticeIntakeNosFingerprint([...intakeNos, ...candidateNos]);
if (pendingNoticeBatchRetry) {
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
if (!ctx.startOrderExtractionRun) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
}
if (
pendingNoticeBatchRetry
&& pendingNoticeBatchRetry.fileFingerprint !== intakeFingerprint
) {
clearPendingNoticeBatchRetryState();
}
if (!pendingNoticeBatchRetry) {
pendingNoticeBatchRetry = {
conversationId: conversationKey,
idempotencyKey: crypto.randomUUID(),
fileFingerprint: intakeFingerprint,
};
} else {
pendingNoticeBatchRetry.fileFingerprint = intakeFingerprint;
}
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
const turn = buildShippingCreateBatchFromIntakesTurn(
intakeNos,
ctx.conversationId.value,
idempotencyKey,
candidateNos,
);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
const query = ctx.input.value.trim() || ctx.t('chat.shippingOrderExtractionDefaultUserMessage');
const ok = await ctx.startOrderExtractionRun(query, intakeNos, []);
if (ok) {
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
clearPendingNoticeBatchRetryState();
}
ctx.clearConsumedNoticeAttachments?.();
void ctx.refreshShippingActions();
} else {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
}
return ok;
} catch {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
} finally {
noticeBatchSubmitting = false;
}
@@ -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();
});
});
@@ -1,10 +1,10 @@
/**
* features/chat/shipping/useShippingNoticeWorkflow.ts
* 用途:会话级 Shipping Notice Workflow 前台轮询、批次选择与取消/重识别编排。
* 依赖:shipping.api workflows / workflow-items、Vue 响应式、BusinessError。
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;支持多批次 workflows[];
* 选中优先显式选择,否则保留仍在列表中的上一选,否则取首个;
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;终态停轮询。
* 用途:会话级货代发货通知「本次处理」投影轮询(统一 ShippingProcessing)。
* 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing;
* focus/viewed 写路径优先应用响应中的 work_items;
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;无活跃任务时停轮询。
*/
import {
computed,
@@ -19,37 +19,21 @@ import {
} from 'vue';
import { BusinessError } from '@/shared/api/client';
import {
cancelWorkspaceShippingWorkflowItem,
listWorkspaceShippingWorkflows,
reparseWorkspaceShippingWorkflowItem,
focusWorkspaceConversationTask,
getWorkspaceShippingProcessing,
markWorkspaceConversationTaskViewed,
} from '../api/shipping.api';
import type {
ShippingWorkflow,
ShippingWorkflowItem,
ConversationProcessingProjection,
ShippingProcessingProjection,
} from '../types/shipping.api.types';
import { resolveConversationProcessingFromUnified } from './conversationProcessingProjection';
const FOREGROUND_POLL_MS = 2000;
const BACKGROUND_POLL_MS = 8000;
const REQUEST_TIMEOUT_MS = 10000;
const MAX_BACKOFF_MS = 8000;
/** 仍需轮询的 Item 生命周期(含待人工上传登记;仅 closed/cancelled 为终态)。 */
const OPEN_ACTIVE_STATUSES = new Set([
'queued',
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'generating_excel',
'pending_review',
'manual_upload_pending',
'reparse_failed',
'failed',
]);
/** Workflow 批次终态。 */
const TERMINAL_WORKFLOW_STATUSES = new Set(['completed', 'cancelled', 'failed']);
export type UseShippingNoticeWorkflowOptions = {
/** 当前会话 ID;空则停轮询并清空。 */
conversationId: MaybeRefOrGetter<string | null | undefined>;
@@ -58,27 +42,15 @@ export type UseShippingNoticeWorkflowOptions = {
};
export type UseShippingNoticeWorkflowReturn = {
/** 会话内全部开放 Workflow。 */
workflows: Ref<ShippingWorkflow[]>;
/** 当前选中的 Workflow 编号。 */
selectedWorkflowNo: Ref<string | null>;
/** 切换选中批次。 */
selectWorkflow: (workflowNo: string) => void;
/** 当前选中的 Workflow(或 null)。 */
workflow: Ref<ShippingWorkflow | null>;
/** 当前选中 Workflow 下的 Items。 */
items: Ref<ShippingWorkflowItem[]>;
/** 后端 conversation_processing / 由 work_items 合成。 */
processing: Ref<ConversationProcessingProjection | null>;
/** 统一 ShippingProcessing work_items。 */
processingWorkItems: Ref<ShippingProcessingProjection[]>;
loading: Ref<boolean>;
error: Ref<string | null>;
refresh: () => Promise<void>;
cancelItem: (
itemNo: string,
payload: { reason: string; expected_lock_version?: number | null },
) => Promise<ShippingWorkflowItem | null>;
reparseItem: (
itemNo: string,
payload: { reason: string; comment?: string | null },
) => Promise<ShippingWorkflowItem | null>;
focusConversationTask: (taskNo: string) => Promise<void>;
markConversationTaskViewed: (taskNo: string) => Promise<void>;
stop: () => void;
};
@@ -108,71 +80,42 @@ function resolvePollMs(): number {
* 失败退避:2s → 4s → 8s(封顶)。
* @param failureCount - 连续失败次数(≥1)
*/
export function resolveWorkflowPollBackoffMs(failureCount: number): number {
export function resolveProcessingPollBackoffMs(failureCount: number): number {
const n = Math.max(1, Math.floor(failureCount));
return Math.min(FOREGROUND_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS);
}
/**
* 在列表中解析应保留的选中 Workflow 编号。
* 核心逻辑:显式 preferred → 仍在列表中的 previous → 首个。
* 判断是否应继续轮询统一 ShippingProcessing。
* 核心逻辑:processing / needs_action 有活跃项则继续。
*/
export function resolveSelectedWorkflowNo(
list: ShippingWorkflow[],
previous: string | null | undefined,
preferred?: string | null,
): string | null {
if (!list.length) return null;
const preferredNo = String(preferred || '').trim();
if (preferredNo && list.some((row) => row.workflow_no === preferredNo)) {
return preferredNo;
}
const previousNo = String(previous || '').trim();
if (previousNo && list.some((row) => row.workflow_no === previousNo)) {
return previousNo;
}
return String(list[0]?.workflow_no || '').trim() || null;
}
/**
* 判断是否应继续轮询。
* 核心逻辑:任一非终态 Workflow 仍有开放处理项则继续;空列表停止(等 refreshTrigger 重启)。
*/
export function shouldContinueWorkflowPolling(
workflows: ShippingWorkflow[],
export function shouldContinueProcessingPolling(
processing?: ConversationProcessingProjection | null,
): boolean {
if (!workflows.length) return false;
return workflows.some((workflow) => {
const status = String(workflow.status || '').trim();
if (TERMINAL_WORKFLOW_STATUSES.has(status)) return false;
const items = Array.isArray(workflow.items) ? workflow.items : [];
const hasOpen = items.some((item) =>
OPEN_ACTIVE_STATUSES.has(String(item.lifecycle_status || '').trim()),
);
return hasOpen || items.length === 0;
});
const processingCount = Number(processing?.summary?.processing || processing?.processing?.length || 0);
const needsActionCount = Number(processing?.summary?.needs_action || processing?.needs_action?.length || 0);
return processingCount > 0 || needsActionCount > 0;
}
/**
* 会话 Workflow 轮询 composable。
* 会话级 ShippingProcessing 轮询 composable。
*
* @param options.conversationId - 会话 ID
* @param options.refreshTrigger - 外部刷新触发器
* @returns workflows / selectedWorkflowNo / selectWorkflow / workflow / items / …
* @returns processing / processingWorkItems / loading / error …
*/
export function useShippingNoticeWorkflow(
options: UseShippingNoticeWorkflowOptions,
): UseShippingNoticeWorkflowReturn {
const workflows = ref<ShippingWorkflow[]>([]);
const selectedWorkflowNo = ref<string | null>(null);
/** 用户显式点选后锁定,直到会话切换或列表不再包含该编号。 */
const explicitSelectionNo = ref<string | null>(null);
const processing = ref<ConversationProcessingProjection | null>(null);
const processingWorkItems = ref<ShippingProcessingProjection[]>([]);
const loading = ref(false);
const error = ref<string | null>(null);
let pollTimer: ReturnType<typeof setTimeout> | null = null;
let pollGeneration = 0;
let requestController: AbortController | null = null;
let requestGeneration = 0;
let failureCount = 0;
let pollingStopped = false;
@@ -180,16 +123,6 @@ export function useShippingNoticeWorkflow(
String(readOption(options.conversationId) || '').trim(),
);
const workflow = computed((): ShippingWorkflow | null => {
const no = selectedWorkflowNo.value;
if (!no) return null;
return workflows.value.find((row) => row.workflow_no === no) || null;
});
const items = computed((): ShippingWorkflowItem[] => (
Array.isArray(workflow.value?.items) ? [...workflow.value!.items!] : []
));
/**
* 中止进行中的请求与定时器。
*/
@@ -199,6 +132,7 @@ export function useShippingNoticeWorkflow(
pollTimer = null;
requestController?.abort();
requestController = null;
requestGeneration += 1;
pollGeneration += 1;
}
@@ -215,102 +149,97 @@ export function useShippingNoticeWorkflow(
}
/**
* 用户显式切换批次;写入 preferred 并刷新派生选中项。
*/
function selectWorkflow(workflowNo: string) {
const normalized = String(workflowNo || '').trim();
if (!normalized) return;
if (!workflows.value.some((row) => row.workflow_no === normalized)) return;
explicitSelectionNo.value = normalized;
selectedWorkflowNo.value = normalized;
}
/**
* 根据列表与显式选择同步 selectedWorkflowNo。
*/
function syncSelection(list: ShippingWorkflow[]) {
const next = resolveSelectedWorkflowNo(
list,
selectedWorkflowNo.value,
explicitSelectionNo.value,
);
if (explicitSelectionNo.value && next !== explicitSelectionNo.value) {
explicitSelectionNo.value = null;
}
selectedWorkflowNo.value = next;
}
/**
* 拉取会话开放 Workflow 列表,并保持选中策略。
* 仅拉取统一 shipping-processing 投影。
* 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据;
* 新请求会中止旧请求,且只有最新一代请求可回写 loading / error / 会话数据。
* @returns Promise<void>;可恢复网络失败写入 error,不向页面抛出。
*/
async function refresh(): Promise<void> {
const conversationId = normalizedConversationId.value;
if (!conversationId) {
workflows.value = [];
selectedWorkflowNo.value = null;
explicitSelectionNo.value = null;
processing.value = null;
processingWorkItems.value = [];
error.value = null;
return;
}
if (loading.value) return;
const generation = ++requestGeneration;
loading.value = true;
const controller = createRequestController();
try {
const projection = await listWorkspaceShippingWorkflows(conversationId, {
signal: controller.signal,
});
if (controller.signal.aborted) return;
const list = Array.isArray(projection.workflows) ? [...projection.workflows] : [];
workflows.value = list;
syncSelection(list);
// [STEP 1] 统一投影为唯一读源。
const unified = await getWorkspaceShippingProcessing(conversationId, controller.signal);
if (
controller.signal.aborted
|| generation !== requestGeneration
|| conversationId !== normalizedConversationId.value
) return;
const workItems = Array.isArray(unified?.work_items) ? unified.work_items : [];
const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined;
processingWorkItems.value = workItems;
processing.value = resolveConversationProcessingFromUnified(workItems, embedded);
error.value = null;
failureCount = 0;
} catch (err) {
if (controller.signal.aborted) return;
} catch (reason) {
if (
controller.signal.aborted
|| generation !== requestGeneration
|| conversationId !== normalizedConversationId.value
) return;
failureCount += 1;
error.value = err instanceof BusinessError
? err.message
error.value = reason instanceof BusinessError
? reason.message
: 'network_recoverable';
} finally {
if (requestController === controller) requestController = null;
loading.value = false;
if (generation === requestGeneration) loading.value = false;
}
}
/**
* 取消单个 Item 后刷新列表。
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块。
*/
async function cancelItem(
itemNo: string,
payload: { reason: string; expected_lock_version?: number | null },
): Promise<ShippingWorkflowItem | null> {
const normalized = String(itemNo || '').trim();
const reason = String(payload.reason || '').trim();
if (!normalized || !reason) return null;
const response = await cancelWorkspaceShippingWorkflowItem(normalized, {
reason,
expected_lock_version: payload.expected_lock_version,
});
await refresh();
return response.item || null;
function applyMutationProcessingResponse(response: {
processing?: ConversationProcessingProjection | null;
work_items?: unknown[];
}): void {
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
if (workItems.length > 0) {
processingWorkItems.value = workItems as typeof processingWorkItems.value;
processing.value = resolveConversationProcessingFromUnified(
workItems as typeof processingWorkItems.value,
response.processing ?? null,
);
return;
}
if (response.processing) processing.value = response.processing;
}
/**
* 重试/重新识别单个 Item 后刷新列表。
* 标记用户可见任务为焦点(写审计并刷新 processing)。
*/
async function reparseItem(
itemNo: string,
payload: { reason: string; comment?: string | null },
): Promise<ShippingWorkflowItem | null> {
const normalized = String(itemNo || '').trim();
const reason = String(payload.reason || '').trim();
if (!normalized || !reason) return null;
const response = await reparseWorkspaceShippingWorkflowItem(normalized, {
reason,
comment: payload.comment,
async function focusConversationTask(taskNo: string): Promise<void> {
const normalized = String(taskNo || '').trim();
const conversationId = normalizedConversationId.value;
if (!normalized || !conversationId) return;
const response = await focusWorkspaceConversationTask(normalized, {
conversation_id: conversationId,
});
await refresh();
return response.item || null;
applyMutationProcessingResponse(response);
}
/**
* 标记用户可见任务已查看(不等于业务已处理)。
*/
async function markConversationTaskViewed(taskNo: string): Promise<void> {
const normalized = String(taskNo || '').trim();
const conversationId = normalizedConversationId.value;
if (!normalized || !conversationId) return;
const response = await markWorkspaceConversationTaskViewed(normalized, {
conversation_id: conversationId,
});
applyMutationProcessingResponse(response);
}
/**
@@ -323,11 +252,15 @@ export function useShippingNoticeWorkflow(
await refresh();
if (generation !== pollGeneration || pollingStopped) return;
if (!normalizedConversationId.value) return;
if (!shouldContinueWorkflowPolling(workflows.value)) {
if (error.value) {
schedulePoll(generation, resolveProcessingPollBackoffMs(failureCount));
return;
}
if (!shouldContinueProcessingPolling(processing.value)) {
return;
}
const nextDelay = failureCount > 0
? resolveWorkflowPollBackoffMs(failureCount)
? resolveProcessingPollBackoffMs(failureCount)
: resolvePollMs();
schedulePoll(generation, nextDelay);
}, delayMs);
@@ -341,16 +274,17 @@ export function useShippingNoticeWorkflow(
pollingStopped = false;
const conversationId = normalizedConversationId.value;
if (!conversationId) {
workflows.value = [];
selectedWorkflowNo.value = null;
explicitSelectionNo.value = null;
error.value = null;
return;
}
const generation = pollGeneration;
void refresh().then(() => {
if (generation !== pollGeneration || pollingStopped) return;
if (!shouldContinueWorkflowPolling(workflows.value)) return;
if (error.value) {
schedulePoll(generation, resolveProcessingPollBackoffMs(failureCount));
return;
}
if (!shouldContinueProcessingPolling(processing.value)) return;
schedulePoll(generation, resolvePollMs());
});
}
@@ -361,8 +295,12 @@ export function useShippingNoticeWorkflow(
schedulePoll(pollGeneration, 0);
}
watch(normalizedConversationId, () => {
explicitSelectionNo.value = null;
watch(normalizedConversationId, (nextConversationId, previousConversationId) => {
if (nextConversationId !== previousConversationId) {
processing.value = null;
processingWorkItems.value = [];
error.value = null;
}
restartPolling();
}, { immediate: true });
@@ -388,16 +326,13 @@ export function useShippingNoticeWorkflow(
}
return {
workflows,
selectedWorkflowNo,
selectWorkflow,
workflow,
items,
processing,
processingWorkItems,
loading,
error,
refresh,
cancelItem,
reparseItem,
focusConversationTask,
markConversationTaskViewed,
stop,
};
}
@@ -11,7 +11,7 @@ import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
import type { ChatMessage } from '../types/chat.types';
const api = vi.hoisted(() => ({
createRun: vi.fn(),
createSubmission: vi.fn(),
getRun: vi.fn(),
listRuns: vi.fn(),
markSeen: vi.fn(),
@@ -22,7 +22,7 @@ const api = vi.hoisted(() => ({
}));
vi.mock('../api/shipping.api', () => ({
createWorkspaceShippingOrderExtractionRun: api.createRun,
createWorkspaceOrderExtractionSubmission: api.createSubmission,
getWorkspaceShippingOrderExtractionRun: api.getRun,
listWorkspaceShippingOrderExtractionRuns: api.listRuns,
markWorkspaceShippingOrderExtractionRunSeen: api.markSeen,
@@ -74,6 +74,8 @@ const createHarness = () => {
onConversationResolved: vi.fn(async () => undefined),
onRetryError: vi.fn(),
onWorkflowRefresh: vi.fn(),
getFocusedUserTaskNo: vi.fn(() => null),
setFocusedUserTaskNo: vi.fn(),
t: (key: string) => key,
};
return { messages, conversationId, options, runs: useShippingOrderExtractionRuns(options) };
@@ -97,30 +99,58 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
});
it('persists stable user and assistant formIds and does not write unchanged polling state again', async () => {
const queued = run({ run_no: 'SNER-START', conversation_id: 'conv-created' });
api.createRun.mockResolvedValue({ run: queued, reused: false });
const queued = run({
run_no: 'SNER-START',
conversation_id: 'conv-created',
user_task_no: 'OT-SNER-START',
});
api.createSubmission.mockResolvedValue({
decision: 'created',
user_task_no: 'OT-SNER-START',
run_no: 'SNER-START',
created_new: true,
operation_id: 'op-1',
});
api.getRun.mockResolvedValue(queued);
const harness = createHarness();
await harness.runs.startRun('解析附件', ['SNI-1'], [], 'batch-1');
expect(api.createRun).toHaveBeenCalledWith(expect.objectContaining({ upload_batch_id: 'batch-1' }));
expect(api.createSubmission).toHaveBeenCalledWith(expect.objectContaining({
upload_batch_id: 'batch-1',
intake_nos: ['SNI-1'],
composer_context_id: expect.stringMatching(/^CMP-/),
submission_id: expect.stringMatching(/^SUB-/),
}));
expect(harness.options.setFocusedUserTaskNo).toHaveBeenCalledWith('OT-SNER-START');
expect(harness.conversationId.value).toBe('conv-created');
expect(harness.options.onConversationResolved).toHaveBeenCalledWith('conv-created');
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
'shipping-order-extraction-user:SNER-START',
'shipping-submission-decision:op-1',
'shipping-order-extraction-run:SNER-START',
]);
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(3);
await vi.advanceTimersByTimeAsync(1000);
expect(api.getRun).toHaveBeenCalledWith('SNER-START', expect.any(AbortSignal));
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(3);
harness.runs.stopPolling();
});
it('persists an attachment-only user message when the run starts without a text note', async () => {
const queued = run({ run_no: 'SNER-EMPTY-NOTE', conversation_id: 'conv-empty-note' });
api.createRun.mockResolvedValue({ run: queued, reused: false });
const queued = run({
run_no: 'SNER-EMPTY-NOTE',
conversation_id: 'conv-empty-note',
user_task_no: 'OT-SNER-EMPTY-NOTE',
});
api.createSubmission.mockResolvedValue({
decision: 'created',
user_task_no: 'OT-SNER-EMPTY-NOTE',
run_no: 'SNER-EMPTY-NOTE',
created_new: true,
operation_id: 'op-empty',
});
api.getRun.mockResolvedValue(queued);
const harness = createHarness();
await harness.runs.startRun('', ['SNI-1'], [{
@@ -181,17 +211,33 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
});
it('aborts a hanging Run query after ten seconds and keeps polling as a transport failure', async () => {
api.createRun.mockResolvedValue({ run: run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }), reused: false });
api.getRun.mockImplementation((_runNo: string, signal: AbortSignal) => new Promise((_resolve, reject) => {
signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
}));
api.createSubmission.mockResolvedValue({
decision: 'created',
user_task_no: 'OT-SNER-TIMEOUT',
run_no: 'SNER-TIMEOUT',
created_new: true,
operation_id: 'op-timeout',
});
api.getRun.mockResolvedValue(run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }));
// 首次 GET(提交后投影)已返回;后续轮询挂起直至 Abort。
let pollCalls = 0;
api.getRun.mockImplementation((_runNo: string, signal?: AbortSignal) => {
pollCalls += 1;
if (pollCalls === 1) {
return Promise.resolve(run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }));
}
return new Promise((_resolve, reject) => {
signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
});
});
const harness = createHarness();
await harness.runs.startRun('解析附件', ['SNI-1'], []);
await vi.advanceTimersByTimeAsync(11000);
expect(api.getRun).toHaveBeenCalledWith('SNER-TIMEOUT', expect.any(AbortSignal));
expect(harness.runs.getActiveRunNo()).toBe('SNER-TIMEOUT');
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('queued');
const runMessage = harness.messages.value.find((item) => item.shipping_order_extraction_state);
expect(runMessage?.shipping_order_extraction_state?.status).toBe('queued');
harness.runs.stopPolling();
});
@@ -1,9 +1,10 @@
/**
* features/chat/shipping/useShippingOrderExtractionRuns.ts
* 用途:把货代订单抽取作为独立 Run 启动、轮询并投影到聊天状态消息。
* 依赖:shipping.api Run 接口、chat.types、Vue refs。
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run;终态后仍保留 run_no 供状态卡展示。
* 右侧「本次处理」由 Workflow 投影驱动,本模块仅在终态/重识别后触发其刷新回调。
* 依赖:shipping.api 统一提交/Run 接口、shippingSubmissionFeedback、chat.types、Vue refs。
* 逻辑:发送处理器调用 startRun → createWorkspaceOrderExtractionSubmission(后端裁决 append/create);
* 写入用户消息 + 非阻塞决策系统消息后轮询 Run;终态后仍保留 run_no 供状态卡展示。
* 右侧「本次处理」由 processing / Workflow 投影驱动,本模块在终态/重识别后触发刷新回调。
* 轮询前台 2s / 后台 5–10s;取消走请求语义 API,刷新为只读 GET。
* 持久化去重签名必须包含 handling_items / primary_notice,避免处理说明变化后历史会话仍读到旧卡。
*/
@@ -11,7 +12,7 @@ import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from
import {
cancelWorkspaceShippingOrderExtractionDocument,
cancelWorkspaceShippingOrderExtractionRun,
createWorkspaceShippingOrderExtractionRun,
createWorkspaceOrderExtractionSubmission,
getWorkspaceShippingOrderExtractionRun,
listWorkspaceShippingOrderExtractionRuns,
markWorkspaceShippingOrderExtractionRunSeen,
@@ -21,6 +22,11 @@ import {
import type { ChatMessage, ChatMessageAttachment, ShippingOrderExtractionReviewAttachment, ShippingOrderExtractionState } from '../types/chat.types';
import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
import type { ShippingNoticeCandidate } from '../types/shipping.types';
import {
buildShippingSubmissionFeedback,
createComposerContextId,
createShippingSubmissionId,
} from './shippingSubmissionFeedback';
interface UseShippingOrderExtractionRunsOptions {
messages: Ref<ChatMessage[]>;
@@ -38,6 +44,10 @@ interface UseShippingOrderExtractionRunsOptions {
onRetryError: (message: string) => void;
/** 终态/重识别/恢复后通知右侧 Workflow 面板立即刷新。 */
onWorkflowRefresh?: () => void;
/** 当前页面聚焦的用户可见任务(OT-…);参与追加优先级第 2 档。 */
getFocusedUserTaskNo?: () => string | null;
/** 新建任务后回写焦点,供下次追加与侧栏高亮。 */
setFocusedUserTaskNo?: (taskNo: string | null) => void;
t: (key: string, params?: Record<string, unknown>) => string;
}
@@ -60,6 +70,14 @@ function resolvePollIntervalMs(failureCount = 0): number {
export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtractionRun): ShippingOrderExtractionState {
return {
status: run.status,
userTaskNo: run.user_task_no || null,
submissionOrdinal: run.submission_ordinal ?? null,
composerContextId: run.composer_context_id || null,
runNo: run.run_no,
sourceRunNo: run.reparse?.source_run_no || null,
supersedingRunNo: run.reparse?.superseding_run_no || null,
isCurrent: !run.reparse?.superseding_run_no,
readOnlyReason: run.reparse?.superseding_run_no ? 'superseded_by_newer_run' : null,
summary: {
totalDocuments: Number(run.summary?.total_documents || 0),
pendingDocuments: Number(run.summary?.pending_documents || 0),
@@ -185,6 +203,21 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
let pollFailureCount = 0;
let pollGeneration = 0;
const persistedSignatures = new Map<string, string>();
/** 输入区短生命周期上下文;切会话时轮换,同会话多次发送可命中追加优先级第 1 档。 */
let composerContextId = createComposerContextId();
let composerBoundConversationId = String(options.conversationId.value || '').trim();
/**
* 确保 composer_context_id 绑定当前会话;会话变化时轮换。
*/
function ensureComposerContext(): string {
const conversationId = String(options.conversationId.value || '').trim();
if (conversationId && conversationId !== composerBoundConversationId) {
composerContextId = createComposerContextId();
composerBoundConversationId = conversationId;
}
return composerContextId;
}
/** 停止当前 Run 短轮询;切会话和组件卸载时再清空 activeRunNo。 */
const stopPolling = () => {
@@ -397,11 +430,12 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
};
/**
* 启动订单抽取后台 Run,并把用户操作和状态卡持久化到本地会话。
* 启动订单抽取统一提交:后端裁决 append/create,并把用户操作与状态卡持久化到本地会话。
* @param query - 用户本次备注;允许为空,不发送给 Dify Chatflow。
* @param intakeNos - 本次冻结的 Intake 编号。
* @param attachments - 用户消息中的安全附件快照。
* @returns Run 已成功创建或幂等复用时为 true。
* @param uploadBatchId - 上传批次隔离键;禁止当作 user_task_no。
* @returns 提交成功(含幂等重放)时为 true。
*/
const startRun = async (
query: string,
@@ -410,14 +444,29 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
uploadBatchId?: string,
): Promise<boolean> => {
stopPolling();
const response = await createWorkspaceShippingOrderExtractionRun({
const submissionId = createShippingSubmissionId();
const composerContext = ensureComposerContext();
const focusedUserTaskNo = String(options.getFocusedUserTaskNo?.() || '').trim() || null;
const submission = await createWorkspaceOrderExtractionSubmission({
agent_id: options.currentAgentId.value,
conversation_id: options.conversationId.value || undefined,
conversation_id: options.conversationId.value || '',
intake_nos: intakeNos,
upload_batch_id: uploadBatchId || '',
submission_id: submissionId,
upload_batch_id: uploadBatchId || undefined,
composer_context_id: composerContext,
focused_user_task_no: focusedUserTaskNo,
});
const run = response.run;
if (!options.conversationId.value) options.conversationId.value = run.conversation_id;
// 统一提交只返回决策摘要;再拉 Run 投影供状态卡与轮询。
const run = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
if (!options.conversationId.value) {
options.conversationId.value = run.conversation_id;
composerBoundConversationId = run.conversation_id;
}
const feedback = buildShippingSubmissionFeedback(submission, attachments.length);
const decisionKey = feedback.decision === 'appended'
? 'chat.shippingSubmission.appended'
: 'chat.shippingSubmission.created';
const userMessage: ChatMessage = {
role: 'user',
@@ -429,13 +478,37 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
payload: {
formId: `shipping-order-extraction-user:${run.run_no}`,
order_extraction_run_no: run.run_no,
user_task_no: submission.user_task_no,
submission_decision: feedback.decision,
},
};
options.messages.value.push(userMessage);
await options.saveLocalMessageToBackend(userMessage, query || undefined);
// 非阻塞系统反馈:可回看,不弹窗。
const systemMessage: ChatMessage = {
role: 'assistant',
type: 'text',
content: options.t(decisionKey, { count: feedback.fileCount }),
local_id: options.newLocalMessageId('shipping-submission-decision'),
local_only: true,
payload: {
formId: `shipping-submission-decision:${submission.operation_id || submissionId}`,
submission_decision: feedback.decision,
user_task_no: submission.user_task_no,
run_no: submission.run_no,
},
};
options.messages.value.push(systemMessage);
await options.saveLocalMessageToBackend(systemMessage);
// 新建任务自动聚焦;追加则保持/回写当前 OT。
options.setFocusedUserTaskNo?.(submission.user_task_no || null);
await upsertRunMessage(run);
await acknowledgeTerminalRunWhenVisible(run);
await options.onConversationResolved(run.conversation_id);
options.onWorkflowRefresh?.();
if (ACTIVE_RUN_STATUSES.has(run.status)) {
beginPolling(run.run_no, 1000);
} else {
@@ -0,0 +1,159 @@
/**
* features/chat/shipping/useShippingProcessingWorkItem.ts
* 用途:按 work_item_type + work_item_no 轮询统一 ShippingProcessingProjection。
* 依赖:shipping.api getWorkspaceShippingProcessingWorkItem、normalizeShippingProcessing。
* 逻辑:复核台 / 任务中心双读接入;404 或权威 OT 缺失时保持 null,不打断旧进度 UI。
*/
import {
getCurrentInstance,
onBeforeUnmount,
ref,
watch,
type MaybeRefOrGetter,
type Ref,
toValue,
} from 'vue';
import { BusinessError } from '@/shared/api/client';
import { getWorkspaceShippingProcessingWorkItem } from '../api/shipping.api';
import type { ShippingProcessingProjection } from '../types/shipping.api.types';
import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing';
const DEFAULT_POLL_MS = 3000;
const TERMINAL_STATUSES = new Set([
'completed',
'failed',
'cancelled',
]);
export type ShippingProcessingWorkItemTypeArg = 'order_intake' | 'order_task';
/**
* 轮询单个统一处理工作项投影。
*
* @param workItemType - order_intake | order_task
* @param workItemNo - Intake 编号或 OT 编号(MaybeRef)
* @param options.enabled - 是否启用;options.pollMs - 轮询间隔
* @returns projection / loading / error / refresh / stop
*/
export function useShippingProcessingWorkItem(
workItemType: ShippingProcessingWorkItemTypeArg,
workItemNo: MaybeRefOrGetter<string | null | undefined>,
options: {
enabled?: MaybeRefOrGetter<boolean>;
pollMs?: number;
} = {},
): {
projection: Ref<ShippingProcessingProjection | null>;
loading: Ref<boolean>;
error: Ref<string | null>;
refresh: () => Promise<void>;
stop: () => void;
} {
const projection = ref<ShippingProcessingProjection | null>(null);
const loading = ref(false);
const error = ref<string | null>(null);
let timer: ReturnType<typeof window.setTimeout> | null = null;
let generation = 0;
let stopped = false;
const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
/**
* 清除轮询定时器。
*/
function clearTimer() {
if (timer != null) {
window.clearTimeout(timer);
timer = null;
}
}
/**
* 停止轮询并递增代际,丢弃在途响应写回。
*/
function stop() {
stopped = true;
generation += 1;
clearTimer();
}
/**
* 拉取一次投影;失败保留上一帧。
*/
async function refresh(): Promise<void> {
const no = String(toValue(workItemNo) || '').trim();
const enabled = options.enabled == null ? true : Boolean(toValue(options.enabled));
if (!enabled || !no) {
projection.value = null;
error.value = null;
clearTimer();
return;
}
const gen = generation;
loading.value = true;
try {
const raw = await getWorkspaceShippingProcessingWorkItem(workItemType, no);
if (stopped || gen !== generation) return;
const normalized = normalizeShippingProcessingProjection(raw);
projection.value = normalized;
error.value = null;
clearTimer();
if (normalized && !TERMINAL_STATUSES.has(normalized.status) && !stopped) {
timer = window.setTimeout(() => {
void refresh();
}, pollMs);
}
} catch (err) {
if (stopped || gen !== generation) return;
// 404 / 业务不存在:清空投影但不抛到页面主流程。
if (err instanceof BusinessError && (err.status === 404 || err.code?.includes('NOT_FOUND'))) {
projection.value = null;
error.value = null;
clearTimer();
return;
}
error.value = err instanceof BusinessError ? err.message : 'network_recoverable';
clearTimer();
if (!stopped) {
timer = window.setTimeout(() => {
void refresh();
}, pollMs);
}
} finally {
if (gen === generation) loading.value = false;
}
}
watch(
() => [String(toValue(workItemNo) || ''), Boolean(toValue(options.enabled ?? true))] as const,
([no, enabled], _prev, onCleanup) => {
stopped = false;
generation += 1;
clearTimer();
onCleanup(() => {
clearTimer();
});
if (!enabled || !no) {
projection.value = null;
error.value = null;
return;
}
void refresh();
},
{ immediate: true },
);
if (getCurrentInstance()) {
onBeforeUnmount(() => {
stop();
});
}
return {
projection,
loading,
error,
refresh,
stop,
};
}