feat(shipping-notice): 落地 XFA 统一视觉拆分确认门禁与处理投影收敛

闭合拆分预览令牌单次消费、样本 checksum 绑定与确认审计;正式提取改为 bindings-only。
同步统一标注工作台交互,并补齐进度投影/任务中心与迁移文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:21:25 +08:00
1 parent d2b3d74def
commit 84a881b554
195 files changed
+20269 -3463

No files matched your search

@@ -481,6 +481,8 @@ describe('conversationProcessingProjection', () => {
sourceType: 'eml',
rootOrderTaskNo: 'OT-WAIT',
shippingNoticeNo: null,
runNo: 'RUN-WAIT',
caseNo: 'CASE-WAIT',
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-2',
@@ -545,6 +547,53 @@ describe('conversationProcessingProjection', () => {
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');
// [P0] 合成任务必须透传 run_no,禁止写死 null。
expect(projection!.needs_action[0]?.run_no).toBe('RUN-WAIT');
});
it('deduplicates conversation total_files by authoritative PDF id', () => {
const base = {
sourceType: 'direct_pdf' as const,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review' as const,
stage: 'waiting_review' as const,
progressVersion: 1,
lastActivityAt: '2026-08-06T00:00:00Z',
currentGate: null,
availableActions: ['open_order_review'],
childOrderTasks: [],
};
const workItems: ShippingProcessingProjection[] = [
{
...base,
workItemType: 'order_task',
workItemNo: 'OT-A',
rootOrderTaskNo: 'OT-A',
sourceSummary: {
emailSubject: null, filename: 'a.pdf', documentId: 17,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-A',
},
},
{
...base,
workItemType: 'order_task',
workItemNo: 'OT-B',
rootOrderTaskNo: 'OT-A',
sourceSummary: {
emailSubject: null, filename: 'a.pdf', documentId: 17,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-B',
},
},
];
const projection = projectConversationProcessingFromWorkItems(workItems);
// 异常重复绑定同一主 PDF 时,顶部必须仍显示 1 个文件。
expect(projection?.summary.total_files).toBe(1);
});
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
@@ -529,10 +529,9 @@ export function groupConversationProcessingTasks(
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,
total_files: active.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
processing: processing.length,
needs_action: needs_action.length,
completed: completed.length,
@@ -661,7 +660,8 @@ export function projectConversationProcessingFromWorkItems(
group,
status_label: String(item.status || '') || null,
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
run_no: null,
// [P0] 消费后端投影 run_no,禁止写死 null 导致「进入订单处理」静默失败。
run_no: String(item.runNo || '').trim() || null,
can_append: false,
last_activity_at: item.lastActivityAt || null,
available_actions: Array.isArray(item.availableActions) ? [...item.availableActions] : [],
@@ -675,7 +675,15 @@ export function projectConversationProcessingFromWorkItems(
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);
// 后端未返回 embedded 汇总时,仍按 OT 主 PDF ID 去重,禁止兄弟 OT 重复累计。
const documentIds = new Set(
orderTasks
.map((item) => Number(item.sourceSummary?.documentId || 0))
.filter((id) => id > 0),
);
const totalFiles = documentIds.size > 0
? documentIds.size
: active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
return {
summary: {
total_tasks: active.length,
@@ -35,6 +35,7 @@ describe('normalizeShippingProcessingProjection', () => {
source_summary: {
email_subject: null,
filename: 'a.pdf',
document_id: 17,
document_count: 1,
parsed_document_count: 1,
candidate_count: 1,
@@ -53,10 +54,27 @@ describe('normalizeShippingProcessingProjection', () => {
expect(normalized!.currentGate?.gateCode).toBe('field_conflict_resolution');
expect(normalized!.currentGate?.attemptNo).toBe(1);
expect(normalized!.sourceSummary.filename).toBe('a.pdf');
expect(normalized!.sourceSummary.documentId).toBe(17);
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
expect(normalized!.availableActions).toEqual(['open_review']);
});
it('normalizes stage_nodes from backend', () => {
const normalized = normalizeShippingProcessingProjection({
work_item_no: 'OT-2',
work_item_type: 'order_task',
status: 'processing',
stage: 'document_parsing',
stage_nodes: [
{ stage: 'upload_received', absolute_index: 0, status: 'passed' },
{ stage: 'document_parsing', absolute_index: 2, status: 'running' },
],
});
expect(normalized?.stageNodes).toHaveLength(2);
expect(normalized?.stageNodes?.[1]?.status).toBe('running');
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
});
it('returns null when work_item_no missing', () => {
expect(normalizeShippingProcessingProjection({ status: 'processing' })).toBeNull();
});
@@ -11,6 +11,8 @@ import type {
ShippingOrderTaskSummary,
ShippingProcessingProjection,
ShippingProcessingStage,
ShippingProcessingStageNode,
ShippingProcessingStageNodeStatus,
ShippingProcessingStatus,
ShippingProcessingWorkItemType,
} from '../types/shipping.api.types';
@@ -76,6 +78,26 @@ function normalizeGate(raw: unknown): ProcessGateSummary | null {
};
}
/**
* 规范单个 stage_node(兼容 snake / camel)。
*/
function normalizeStageNode(raw: unknown): ShippingProcessingStageNode | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const stage = readString(item, 'stage', 'stage') as ShippingProcessingStage;
if (!stage) return null;
const absoluteIndexRaw = item.absolute_index ?? item.absoluteIndex;
const absoluteIndex = Number.isFinite(Number(absoluteIndexRaw))
? Number(absoluteIndexRaw)
: 0;
const status = readString(item, 'status', 'status') as ShippingProcessingStageNodeStatus;
return {
stage,
absoluteIndex,
status: status || 'pending',
};
}
/**
* 将后端 / 混合字段投影规范为 ShippingProcessingProjection。
* 核心逻辑:缺字段给安全默认值,保证四页面可渲染;非法输入返回 null。
@@ -100,6 +122,10 @@ export function normalizeShippingProcessingProjection(
const availableActions = Array.isArray(actionsRaw)
? actionsRaw.map((action) => String(action || '').trim()).filter(Boolean)
: [];
const stageNodesRaw = item.stage_nodes ?? item.stageNodes;
const stageNodes = Array.isArray(stageNodesRaw)
? stageNodesRaw.map(normalizeStageNode).filter((row): row is ShippingProcessingStageNode => Boolean(row))
: undefined;
return {
workItemType: (readString(item, 'work_item_type', 'workItemType') || 'order_task') as ShippingProcessingWorkItemType,
@@ -107,6 +133,8 @@ export function normalizeShippingProcessingProjection(
sourceType: (readNullableString(item, 'source_type', 'sourceType') || 'eml') as OrderIntakeSourceType,
rootOrderTaskNo: readNullableString(item, 'root_order_task_no', 'rootOrderTaskNo'),
shippingNoticeNo: readNullableString(item, 'shipping_notice_no', 'shippingNoticeNo'),
runNo: readNullableString(item, 'run_no', 'runNo'),
caseNo: readNullableString(item, 'case_no', 'caseNo'),
conversationId: readNullableString(item, 'conversation_id', 'conversationId'),
submissionNo: readString(item, 'submission_no', 'submissionNo'),
intakeNo: readString(item, 'intake_no', 'intakeNo'),
@@ -114,11 +142,13 @@ export function normalizeShippingProcessingProjection(
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'),
stageNodes: stageNodes?.length ? stageNodes : undefined,
currentGate: normalizeGate(item.current_gate ?? item.currentGate),
availableActions,
sourceSummary: {
emailSubject: readNullableString(summaryRaw, 'email_subject', 'emailSubject'),
filename: readNullableString(summaryRaw, 'filename', 'filename'),
documentId: Number(summaryRaw.document_id ?? summaryRaw.documentId ?? 0) || null,
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,
@@ -17,6 +17,7 @@ const LEGACY_STATUS_TO_PROCESSING: Record<string, string> = {
cancelling: 'processing',
blocked: 'blocked',
automating: 'automating',
review_case_draft: 'waiting_review',
};
/**
@@ -139,6 +139,22 @@ describe('useShippingNoticeWorkflow', () => {
ctl.stop();
});
it('coalesces concurrent refreshes for the same conversation', async () => {
const pending = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing.mockImplementation(() => pending.promise);
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
const manualRefresh = ctl.refresh();
await nextTick();
// 首轮恢复、页面刷新和可见性触发命中同一会话时只能产生一个网络请求。
expect(api.getShippingProcessing).toHaveBeenCalledTimes(1);
pending.resolve(buildUnifiedProcessing());
await manualRefresh;
expect(ctl.processing.value?.summary.needs_action).toBe(1);
ctl.stop();
});
it('records recoverable error without throwing', async () => {
const conversationId = ref('conv-1');
const ctl = useShippingNoticeWorkflow({ conversationId });
@@ -116,6 +116,7 @@ export function useShippingNoticeWorkflow(
let pollGeneration = 0;
let requestController: AbortController | null = null;
let requestGeneration = 0;
let inFlightRefresh: { conversationId: string; promise: Promise<void> } | null = null;
let failureCount = 0;
let pollingStopped = false;
@@ -151,17 +152,10 @@ export function useShippingNoticeWorkflow(
/**
* 仅拉取统一 shipping-processing 投影。
* 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据;
* 新请求会中止旧请求,且只有最新一代请求可回写 loading / error / 会话数据。
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据。
* @returns Promise<void>;可恢复网络失败写入 error,不向页面抛出。
*/
async function refresh(): Promise<void> {
const conversationId = normalizedConversationId.value;
if (!conversationId) {
processing.value = null;
processingWorkItems.value = [];
error.value = null;
return;
}
async function executeRefresh(conversationId: string): Promise<void> {
const generation = ++requestGeneration;
loading.value = true;
const controller = createRequestController();
@@ -196,6 +190,27 @@ export function useShippingNoticeWorkflow(
}
}
/**
* 拉取统一进度;同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。
*/
function refresh(): Promise<void> {
const conversationId = normalizedConversationId.value;
if (!conversationId) {
processing.value = null;
processingWorkItems.value = [];
error.value = null;
return Promise.resolve();
}
if (inFlightRefresh?.conversationId === conversationId) {
return inFlightRefresh.promise;
}
const promise = executeRefresh(conversationId).finally(() => {
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
});
inFlightRefresh = { conversationId, promise };
return promise;
}
/**
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块。
@@ -1,8 +1,8 @@
/**
* features/chat/shipping/useShippingOrderExtractionRuns.spec.ts
* 用途:验证订单抽取 Run 的状态映射、消息幂等持久化与轮询生命周期。
* 用途:验证订单抽取 Run 的状态映射、单状态卡消息持久化与轮询生命周期。
* 依赖:Vitest、Vue refs、shipping.api mock、useShippingOrderExtractionRuns。
* 逻辑:覆盖状态契约、新会话启动、无变化轮询、恢复失败及切会话迟到响应。
* 逻辑:覆盖新建/追加提交不生成重复反馈气泡、状态契约、无变化轮询及恢复隔离。
*/
import { computed, ref } from 'vue';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -98,7 +98,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
vi.useRealTimers();
});
it('persists stable user and assistant formIds and does not write unchanged polling state again', async () => {
it('persists one user message and one Run state card without duplicate submission feedback', async () => {
const queued = run({
run_no: 'SNER-START',
conversation_id: 'conv-created',
@@ -126,14 +126,41 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
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(3);
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(1000);
expect(api.getRun).toHaveBeenCalledWith('SNER-START', expect.any(AbortSignal));
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(3);
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
harness.runs.stopPolling();
});
it('keeps an appended submission in the user message and the existing Run state card only', async () => {
const queued = run({
run_no: 'SNER-APPENDED',
conversation_id: 'conv-existing',
user_task_no: 'OT-EXISTING',
});
api.createSubmission.mockResolvedValue({
decision: 'appended',
user_task_no: 'OT-EXISTING',
run_no: 'SNER-APPENDED',
created_new: false,
operation_id: 'op-appended',
});
api.getRun.mockResolvedValue(queued);
const harness = createHarness();
harness.conversationId.value = 'conv-existing';
await harness.runs.startRun('追加附件', ['SNI-1'], []);
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
'shipping-order-extraction-user:SNER-APPENDED',
'shipping-order-extraction-run:SNER-APPENDED',
]);
expect(harness.messages.value[0]?.payload?.submission_decision).toBe('appended');
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
harness.runs.stopPolling();
});
@@ -177,6 +204,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
expect.objectContaining({ content: '' }),
undefined,
);
expect(harness.messages.value).toHaveLength(2);
harness.runs.stopPolling();
});
@@ -1,9 +1,9 @@
/**
* features/chat/shipping/useShippingOrderExtractionRuns.ts
* 用途:把货代订单抽取作为独立 Run 启动、轮询并投影到聊天状态消息。
* 依赖:shipping.api 统一提交/Run 接口、shippingSubmissionFeedback、chat.types、Vue refs。
* 依赖:shipping.api 统一提交/Run 接口、shippingSubmissionFeedback 标识生成器、chat.types、Vue refs。
* 逻辑:发送处理器调用 startRun → createWorkspaceOrderExtractionSubmission(后端裁决 append/create);
* 写入用户消息 + 非阻塞决策系统消息后轮询 Run;终态后仍保留 run_no 供状态卡展示。
* 写入用户消息 + 唯一 Run 状态卡后轮询;终态后仍保留 run_no 供状态卡展示。
* 右侧「本次处理」由 processing / Workflow 投影驱动,本模块在终态/重识别后触发刷新回调。
* 轮询前台 2s / 后台 5–10s;取消走请求语义 API,刷新为只读 GET。
* 持久化去重签名必须包含 handling_items / primary_notice,避免处理说明变化后历史会话仍读到旧卡。
@@ -23,7 +23,6 @@ import type { ChatMessage, ChatMessageAttachment, ShippingOrderExtractionReviewA
import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
import type { ShippingNoticeCandidate } from '../types/shipping.types';
import {
buildShippingSubmissionFeedback,
createComposerContextId,
createShippingSubmissionId,
} from './shippingSubmissionFeedback';
@@ -430,7 +429,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
};
/**
* 启动订单抽取统一提交:后端裁决 append/create,并把用户操作与状态卡持久化到本地会话。
* 启动订单抽取统一提交:后端裁决 append/create,并只持久化用户操作与唯一 Run 状态卡。
* @param query - 用户本次备注;允许为空,不发送给 Dify Chatflow。
* @param intakeNos - 本次冻结的 Intake 编号。
* @param attachments - 用户消息中的安全附件快照。
@@ -463,11 +462,6 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
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',
type: 'text',
@@ -479,29 +473,12 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
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,
submission_decision: submission.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);