refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段

统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成
设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程
删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本
替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段
更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
This commit is contained in:
hugo committed 2026-08-15 10:19:10 +08:00
1 parent 6684e7181a
commit 5ef8329bd8
178 files changed
+5091 -1734

No files matched your search

@@ -22,6 +22,8 @@ import {
buildTaskSemanticKey,
buildProcessingSemanticKey,
stabilizeTaskObjects,
flattenBusinessFileProjections,
businessFileKeys,
} from './conversationProcessingProjection';
import type {
ConversationProcessingProjection,
@@ -29,6 +31,28 @@ import type {
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
describe('EML business-file projection', () => {
it('excludes the EML container and keeps its PDF/XLSX leaf attachments', () => {
const eml = {
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml',
sourceSummary: { filename: 'mail.eml', documentCount: 2 },
aggregateChildren: [
{ workItemType: 'order_task', workItemNo: 'OT-1', sourceType: 'eml', sourceSummary: { filename: 'notice-a.pdf', documentId: 101, documentCount: 1 } },
{ workItemType: 'order_task', workItemNo: 'OT-2', sourceType: 'eml', sourceSummary: { filename: 'items.xlsx', documentId: 102, documentCount: 1 } },
],
} as ShippingProcessingProjection;
const directPdf = {
workItemType: 'order_task', workItemNo: 'OT-3', sourceType: 'direct_pdf',
sourceSummary: { filename: 'direct.pdf', documentId: 103, documentCount: 1 },
} as ShippingProcessingProjection;
// EML 仅为来源分组,3 个业务附件才是唯一文件集合。
expect(flattenBusinessFileProjections([eml, directPdf]).map((row) => row.sourceSummary.filename))
.toEqual(['notice-a.pdf', 'items.xlsx', 'direct.pdf']);
expect(businessFileKeys([eml, directPdf])).toEqual(['document:101', 'document:102', 'document:103']);
});
});
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
return {
item_no: 'WI-1',
@@ -891,6 +915,43 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
expect(t2.available_actions).toEqual(['open_order_review', 'view_details']);
});
it('buildTaskSemanticKey: ui_state 动作变化必须改变签名', () => {
const shared = {
user_task_no: 'INTAKE:SNI-UI', group: 'needs_action' as const,
status_label: 'waiting_human', file_count: 1, can_append: false,
available_actions: ['retry_parse'],
};
const before = {
...shared,
uiState: {
status: 'waiting_human', stage: 'order_review', blocking_reason: null,
primary_action: { code: 'open_order_review', i18nKey: 'action.open_order_review', parameters: {} },
secondary_actions: [],
},
};
const after = {
...before,
uiState: {
...before.uiState,
primary_action: { code: 'retry_parse', i18nKey: 'action.retry_parse', parameters: {} },
},
};
expect(buildTaskSemanticKey(before)).not.toBe(buildTaskSemanticKey(after));
});
it('buildTaskSemanticKey: authoritative ui_state without a primary action ignores stale legacy action', () => {
const shared = {
user_task_no: 'INTAKE:SNI-NO-ACTION', group: 'processing' as const,
status_label: 'processing', file_count: 1, can_append: false,
primary_action: 'retry_parse', available_actions: ['retry_parse'],
uiState: { status: 'processing', stage: 'document_parsing', blocking_reason: null, primary_action: null, secondary_actions: [] },
};
const withoutLegacy = { ...shared, primary_action: null, available_actions: [] };
// 后端 ui_state 已明确“无动作”时,旧字段变动不能让状态卡语义闪烁或伪造 CTA。
expect(buildTaskSemanticKey(shared)).toBe(buildTaskSemanticKey(withoutLegacy));
});
it('stabilizeTaskObjects: 同一 user_task_no 且语义相同,优先复用旧对象引用(避免 DOM 重建)', () => {
const baseTask = (no: string, updatedAt: string) => ({
user_task_no: no,
@@ -1063,6 +1124,55 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
expect(normalized.processing.length).toBe(0);
});
it('normalizes backend status-group task UI state and EML children without recalculating batch facts', () => {
const backendProjection = {
// 统计是后端按完整批次裁决的事实,不能由当前返回的局部 EML/附件数组替代。
summary: { total_tasks: 1, total_files: 7, processing: 0, needs_action: 1, completed: 0, history: 0 },
focused_task_no: 'INTAKE:SNI-API',
recent_task_no: 'INTAKE:SNI-API',
needs_action: [], processing: [], completed: [], history: [],
status_groups: {
failed: [{
user_task_no: 'INTAKE:SNI-API', title: 'source.eml', display_kind: 'multi_document_task',
document_names: ['a.pdf', 'b.pdf'], group: 'needs_action', status_label: 'failed', file_count: 2,
can_append: false, available_actions: [], primary_action: null,
ui_state: {
status: 'failed', stage: 'document_parsing',
blocking_reason: { code: 'PARSE_FAILED', i18n_key: 'shipping.parse_failed', details: {} },
primary_action: { code: 'retry', i18n_key: 'shipping.retry', parameters: {} }, secondary_actions: [],
},
aggregate_children: [{
work_item_type: 'order_task', work_item_no: 'OT-API-1', source_type: 'direct_pdf',
root_order_task_no: 'OT-API-1', shipping_notice_no: null, conversation_id: 'conv-api',
submission_no: 'SUB-1', intake_no: 'SNI-API', status: 'failed', stage: 'document_parsing',
progress_version: 1, last_activity_at: '2026-08-14T00:00:00Z', current_gate: null, available_actions: [],
source_summary: { email_subject: 'Subject', filename: 'a.pdf', document_count: 1, parsed_document_count: 0, candidate_count: 0 },
child_order_tasks: [], ui_state: {
status: 'failed', stage: 'document_parsing', blocking_reason: { code: 'PARSE_FAILED', details: {} },
primary_action: { code: 'retry', parameters: {} }, secondary_actions: [],
},
}],
}],
waiting_human: [], processing: [], completed: [], cancelled: [], archived: [],
},
four_stage_nodes: [{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }],
output_artifacts: [{ order_task_no: 'OT-API-1', filename: 'shipping.xlsx', type: 'excel', status: 'ready', action: { code: 'download_excel', enabled: true } }],
} as unknown as ConversationProcessingProjection;
const normalized = normalizeConversationProcessingProjection(backendProjection);
const eml = normalized.status_groups!.failed[0]!;
// 后端裁决的状态/按钮必须在 EML 与附件层均可直接消费,前端不重新推导。
expect(eml.uiState?.primary_action?.code).toBe('retry');
expect(eml.uiState?.primary_action?.i18nKey).toBe('shipping.retry');
expect(eml.aggregateChildren?.[0]?.uiState?.primary_action?.code).toBe('retry');
expect(eml.aggregateChildren?.[0]?.sourceSummary.filename).toBe('a.pdf');
// 批次统计、四阶段与产物均是后端事实,适配时不得从附件重算或丢失。
expect(normalized.summary.total_files).toBe(7);
expect(normalized.four_stage_nodes).toEqual([{ code: 'intake_parse', label_key: 'shipping.stage.intake', status: 'blocked' }]);
expect(normalized.output_artifacts?.[0]?.action.enabled).toBe(true);
});
it('resolveConversationProcessingFromUnified: work_items 为空时,embedded waiting_human 任务迁入 needs_action 且统一文案', () => {
const embedded: ConversationProcessingProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
@@ -22,6 +22,46 @@ import type {
ShippingWorkflowItem,
WorkflowNodeStatus,
} from '@/features/chat/types/shipping.api.types';
import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing';
/**
* 展开工作项中的业务文件叶子。
* EML 只是来源容器,不是可处理业务文件;只有其下真实附件(PDF/XLSX 等)
* 以及 direct_pdf 自身进入文件计数和文件名列表。该函数不修改后端投影。
*/
export function flattenBusinessFileProjections(
items: readonly ShippingProcessingProjection[] | null | undefined,
): ShippingProcessingProjection[] {
const rows: ShippingProcessingProjection[] = [];
const visit = (item: ShippingProcessingProjection) => {
const nested = Array.isArray(item.aggregateChildren) ? item.aggregateChildren : [];
if (nested.length) {
nested.forEach(visit);
return;
}
const filename = String(item.sourceSummary?.filename || '').trim();
if (filename.toLowerCase().endsWith('.eml')) return;
// 没有文件名的聚合容器不能伪造一个文件行。
if (!filename && item.sourceType === 'eml') return;
rows.push(item);
};
(items || []).forEach(visit);
return rows;
}
/** 以文档 ID 优先、文件名兜底,对叶子业务文件稳定去重。 */
export function businessFileKeys(
items: readonly ShippingProcessingProjection[] | null | undefined,
): string[] {
const keys = new Set<string>();
for (const item of flattenBusinessFileProjections(items)) {
const id = Number(item.sourceSummary?.documentId || 0);
const filename = String(item.sourceSummary?.filename || '').trim().toLowerCase();
const key = id > 0 ? `document:${id}` : filename ? `filename:${filename}` : '';
if (key) keys.add(key);
}
return [...keys];
}
/**
* 标准化动作码列表:去空白、小写、去重、字典序排序。
@@ -67,9 +107,13 @@ export function buildTaskSemanticKey(
displayKind: task.display_kind,
fileCount: task.file_count,
title: task.title,
primaryAction: (task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
?? task.primary_action
?? null,
// [AUTHORITY] 新会话批次的可操作动作由 ui_state 单独版本化;把它纳入语义键,
// 避免状态未变但后端撤销/切换按钮时前端错误复用旧任务对象。
primaryAction: task.uiState
? (task.uiState.primary_action?.code ?? null)
: ((task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
?? task.primary_action
?? null),
currentGate: (task as ConversationProcessingUserTask & {
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
blockingReason?: { code?: string } | null;
@@ -90,7 +134,11 @@ export function buildTaskSemanticKey(
?? null,
}
: null,
availableActions: normalizeActionCodes(task.available_actions || []),
availableActions: normalizeActionCodes(
task.uiState
? task.uiState.secondary_actions.filter((action) => action.enabled).map((action) => action.code)
: (task.available_actions || []),
),
canAppend: task.can_append ?? null,
aggregateChildren,
});
@@ -879,6 +927,11 @@ export function resolveConversationProcessingFromUnified(
stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
// [AUTHORITY] 新版接口已经由后端完成「状态 → EML → 业务文件」聚合。
// 会话卡与批次中心必须直接使用该结果;前端从 work_items 重建只保留给旧响应兼容。
if (embedded && typeof embedded === 'object' && embedded.status_groups) {
return normalizeConversationProcessingProjection(embedded);
}
// [TRANSITION] 只有统一投影里明确存在 order_task,才认为 OT 维度已经成形。
// 仅 order_intake 存在时视为过渡阶段:
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
@@ -919,56 +972,150 @@ export function resolveConversationProcessingFromUnified(
export function normalizeConversationProcessingProjection(
projection: ConversationProcessingProjection,
): ConversationProcessingProjection {
const backendAuthoritative = Boolean(projection.status_groups);
const normalizeUiState = (
rawState: ConversationProcessingUserTask['uiState'] | undefined,
): ConversationProcessingUserTask['uiState'] | undefined => {
if (!rawState || typeof rawState !== 'object') return undefined;
const state = rawState as ConversationProcessingUserTask['uiState'] & {
blockingReason?: ShippingProcessingBlockingReason | null;
primaryAction?: ShippingProcessingPrimaryAction | null;
secondaryActions?: Array<{ code: string; enabled: boolean }>;
};
const normalizeAction = (action: ShippingProcessingPrimaryAction | null | undefined) => {
if (!action || typeof action !== 'object') return null;
const rawAction = action as ShippingProcessingPrimaryAction & { i18n_key?: string | null };
return {
...rawAction,
i18nKey: rawAction.i18nKey ?? rawAction.i18n_key ?? null,
};
};
const normalizeReason = (reason: ShippingProcessingBlockingReason | null | undefined) => {
if (!reason || typeof reason !== 'object') return null;
const rawReason = reason as ShippingProcessingBlockingReason & { i18n_key?: string | null };
return {
...rawReason,
i18nKey: rawReason.i18nKey ?? rawReason.i18n_key ?? null,
};
};
return {
...state,
blocking_reason: normalizeReason(state.blocking_reason ?? state.blockingReason),
primary_action: normalizeAction(state.primary_action ?? state.primaryAction),
secondary_actions: state.secondary_actions ?? state.secondaryActions ?? [],
};
};
const normalizeTask = (task: ConversationProcessingUserTask): ConversationProcessingUserTask => {
const raw = task as ConversationProcessingUserTask & {
user_status?: ConversationProcessingUserTask['userStatus'];
user_stage?: ConversationProcessingUserTask['userStage'];
user_group?: ConversationProcessingUserTask['userGroup'];
blocking_reason?: ConversationProcessingUserTask['blockingReason'];
primary_action?: ConversationProcessingUserTask['primaryAction'] | string | null;
aggregate_summary?: ConversationProcessingUserTask['aggregateSummary'];
aggregate_children?: unknown[];
};
const rawPrimaryAction = raw.primaryAction ?? raw.primary_action ?? null;
const aggregateChildren = Array.isArray(raw.aggregateChildren)
? raw.aggregateChildren
: (Array.isArray(raw.aggregate_children)
? raw.aggregate_children
.map(normalizeShippingProcessingProjection)
.filter((item): item is ShippingProcessingProjection => Boolean(item))
: []);
// 新批次投影的 group/user_group 已由后端裁决;旧 embedded 响应没有 status_groups,
// 仅在该兼容分支维持历史规范化,避免旧服务端响应把待人工留在处理中。
const rawStatus = task.userStatus ?? task.status_label;
const normalizedStatus = normalizeLifecycleStatus(rawStatus);
const availableActions = Array.isArray(task.available_actions) ? task.available_actions : [];
const hasHumanAction = availableActions.some((value) => {
const legacyActions = Array.isArray(task.available_actions) ? task.available_actions : [];
const legacyHasHumanAction = legacyActions.some((value) => {
const code = String(value || '').trim().toLowerCase();
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
});
const recomputedGroup = classifyConversationProcessingGroup(normalizedStatus || rawStatus, {
needsCustomerConfirm: hasHumanAction,
});
const finalGroup: ConversationProcessingTaskGroup = (() => {
// [LEGACY-UNIFY] waiting_human 旧投影若被归在 processing / history,强制迁入 needs_action。
if (recomputedGroup === 'needs_action') return 'needs_action';
if (normalizedStatus === 'waiting_review') return 'needs_action';
return task.group || recomputedGroup;
})();
const finalGroup: ConversationProcessingTaskGroup = backendAuthoritative
? task.group
: classifyConversationProcessingGroup(normalizedStatus || rawStatus, {
needsCustomerConfirm: legacyHasHumanAction,
});
return {
...task,
status_label: normalizedStatus || (task.status_label ?? ''),
// userStatus 保持原有强类型;会话侧展示统一走 status_label/group,避免放宽成 string 破坏类型契约。
userStatus: task.userStatus ?? null,
status_label: backendAuthoritative
? task.status_label
: (normalizedStatus || task.status_label),
userStatus: raw.userStatus ?? raw.user_status ?? null,
userStage: raw.userStage ?? raw.user_stage ?? null,
userGroup: raw.userGroup ?? raw.user_group ?? null,
blockingReason: raw.blockingReason ?? raw.blocking_reason ?? null,
primaryAction: typeof rawPrimaryAction === 'object' ? rawPrimaryAction : null,
primary_action: typeof rawPrimaryAction === 'string' ? rawPrimaryAction : task.primary_action,
aggregateSummary: raw.aggregateSummary ?? raw.aggregate_summary ?? null,
aggregateChildren,
uiState: normalizeUiState(
(raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).uiState
?? (raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).ui_state,
),
group: finalGroup,
};
};
const normalizedAll = [
const normalizedLegacyTasks = [
...(projection.needs_action || []),
...(projection.processing || []),
...(projection.completed || []),
...(projection.history || []),
].map(normalizeTask);
const needs_action = normalizedAll.filter((task) => task.group === 'needs_action');
const processing = normalizedAll.filter((task) => task.group === 'processing');
const completed = normalizedAll.filter((task) => task.group === 'completed');
const history = normalizedAll.filter((task) => task.group === 'history');
const normalizedGroups = projection.status_groups
? {
failed: (projection.status_groups.failed || []).map(normalizeTask),
waiting_human: (projection.status_groups.waiting_human || []).map(normalizeTask),
processing: (projection.status_groups.processing || []).map(normalizeTask),
completed: (projection.status_groups.completed || []).map(normalizeTask),
cancelled: (projection.status_groups.cancelled || []).map(normalizeTask),
archived: (projection.status_groups.archived || []).map(normalizeTask),
}
: null;
// status_groups 存在时,传统四组只是兼容镜像,可能为空;统计必须保留后端 summary,
// 绝不能据空镜像重新裁决成 0。
const normalizedAll = normalizedGroups
? [
...normalizedGroups.failed,
...normalizedGroups.waiting_human,
...normalizedGroups.processing,
...normalizedGroups.completed,
...normalizedGroups.cancelled,
...normalizedGroups.archived,
]
: normalizedLegacyTasks;
const needs_action = normalizedGroups
? [...normalizedGroups.failed, ...normalizedGroups.waiting_human]
: normalizedAll.filter((task) => task.group === 'needs_action');
const processing = normalizedGroups?.processing || normalizedAll.filter((task) => task.group === 'processing');
const completed = normalizedGroups?.completed || normalizedAll.filter((task) => task.group === 'completed');
const history = normalizedGroups
? [...normalizedGroups.cancelled, ...normalizedGroups.archived]
: normalizedAll.filter((task) => task.group === 'history');
return {
...projection,
summary: {
...(projection.summary || {}),
total_tasks: normalizedAll.length,
total_files: normalizedAll.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
needs_action: needs_action.length,
processing: processing.length,
completed: completed.length,
history: history.length,
},
// [AUTHORITY] 新批次 status_groups + summary 同属一次后端裁决。summary 可能覆盖完整批次,
// 而当前组只返回可见 EML;前端不得用局部行数覆盖后端文件/任务统计。
summary: backendAuthoritative
? projection.summary
: {
...(projection.summary || {}),
total_tasks: normalizedAll.length,
total_files: normalizedAll.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
needs_action: needs_action.length,
processing: processing.length,
completed: completed.length,
history: history.length,
},
needs_action,
processing,
completed,
history,
status_groups: normalizedGroups || projection.status_groups,
four_stage_nodes: projection.four_stage_nodes || [],
ui_state: projection.ui_state || undefined,
output_artifacts: projection.output_artifacts || [],
};
}
@@ -999,8 +1146,42 @@ export function projectConversationProcessingFromWorkItems(
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();
// EML 父项的 sourceSummary.filename 是邮件名,只能用于分组标题;
// 文件行与数量必须来自其真实附件叶子。
const leafFiles = flattenBusinessFileProjections([item]);
const leafKeys = businessFileKeys([item]);
const leafNames = [...new Set(leafFiles
.map((child) => String(child.sourceSummary?.filename || '').trim())
.filter(Boolean))];
const leafObjects = leafFiles.map((child, index) => {
const summary = child.sourceSummary || {};
const documentId = Number(summary.documentId || 0) || undefined;
const leafFilename = String(summary.filename || '').trim();
return {
kind: 'document' as const,
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-leaf-${index}`,
label: leafFilename || String(child.workItemNo || taskNo),
filename: leafFilename || undefined,
document_id: documentId,
status_label: String(child.userStatus ?? child.status ?? ''),
run_no: child.runNo || undefined,
current_run_no: child.runNo || undefined,
case_no: child.caseNo || undefined,
task_no: child.rootOrderTaskNo || undefined,
workflow_item_no: child.workItemNo || undefined,
};
});
const isEmlContainer = item.sourceType === 'eml' && Array.isArray(item.aggregateChildren)
&& item.aggregateChildren.length > 0;
const sourceDocCount = Number(item.sourceSummary?.documentCount || 0);
// 只有已展开的 EML 聚合以叶子集合覆盖后端摘要;普通/旧单项投影仍保留
// sourceSummary.documentCount,避免稀疏投影把一个多文件任务错误压成 1 个文件。
const docCount = isEmlContainer
? leafKeys.length
: (sourceDocCount || leafKeys.length);
const filename = isEmlContainer
? String(item.sourceSummary?.filename || '').trim()
: (leafNames[0] || String(item.sourceSummary?.filename || '').trim());
const normalizedActions = normalizeActionCodes(item.availableActions || []);
const gateNextAction = String(item.primaryAction?.code ?? item.currentGate?.nextActionCode ?? '').trim().toLowerCase() || null;
const effectiveStatus = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim()) || null;
@@ -1040,11 +1221,12 @@ export function projectConversationProcessingFromWorkItems(
user_task_authoritative: true,
title: filename || null,
display_kind: docCount > 1 ? 'multi_document_task' : 'single_document_task',
document_names: filename ? [filename] : [],
document_names: leafNames.length ? leafNames : (isEmlContainer ? [] : (filename ? [filename] : [])),
group,
status_label: effectiveStatus,
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
file_count: docCount > 0 ? docCount : (isEmlContainer ? 0 : (filename ? 1 : 0)),
run_no: String(item.runNo || '').trim() || null,
objects: leafObjects,
can_append: false,
last_activity_at: item.lastActivityAt || null,
available_actions: normalizedActions,
@@ -1132,8 +1314,11 @@ export function projectConversationProcessingFromWorkItems(
? 'history'
: 'processing';
const representative = entries[0]!.task;
const documentNames = [...new Set(entries.flatMap(({ task }) => task.document_names || []).filter(Boolean))];
const fileCount = entries.reduce((sum, { task }) => sum + Number(task.file_count || 0), 0);
const aggregateChildren = entries.flatMap(({ item }) => item.aggregateChildren || [item]);
const documentNames = [...new Set(flattenBusinessFileProjections(aggregateChildren)
.map((child) => String(child.sourceSummary?.filename || '').trim())
.filter(Boolean))];
const fileCount = businessFileKeys(aggregateChildren).length;
rawTasks.push({
...representative,
title: representative.title || `EML ${intakeNo}`,
@@ -1152,7 +1337,7 @@ export function projectConversationProcessingFromWorkItems(
stages,
reasonCodes,
},
aggregateChildren: entries.flatMap(({ item }) => item.aggregateChildren || [item]),
aggregateChildren,
userGroup: aggregateUserGroup as ConversationProcessingUserTask['userGroup'],
});
}
@@ -1172,14 +1357,11 @@ export function projectConversationProcessingFromWorkItems(
const active = [...needs_action_raw, ...processing_raw, ...completed_raw];
if (!active.length && !history_raw.length) return null;
const documentIds = new Set(
orderTasks
.map((item) => Number(item.sourceSummary?.documentId || 0))
.filter((id) => id > 0),
// 统计口径与卡片完全一致:递归叶子业务文件,排除 EML 容器。
const totalFiles = businessFileKeys(orderTasks).length || active.reduce(
(sum, task) => sum + Number(task.file_count || 0),
0,
);
const totalFiles = documentIds.size > 0
? documentIds.size
: active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
const stabilizedAll = stabilizeTaskObjects(
previousProjection
@@ -31,7 +31,27 @@ describe('normalizeShippingProcessingProjection', () => {
blocking_reason_code: 'pdf_preferred_critical_conflict',
attempt_no: 1,
},
process_gate: {
execution_no: 'EXE-1',
status: 'blocked',
current_gate_code: 'inventory_preparation',
expected_gate_version: 3,
current_blocking_gate: {
gate_code: 'inventory_preparation',
status: 'blocked_manual',
evaluation_version: 3,
},
next_action_code: 'retry_inventory_preparation',
allowed_actions: ['retry_inventory_preparation', 'upload_inventory_file'],
},
available_actions: ['open_review'],
ui_state: {
status: 'waiting_human',
stage: 'order_review',
blocking_reason: { code: 'pdf_preferred_critical_conflict' },
primary_action: { code: 'resolve_field_conflicts', i18n_key: 'action.resolve_field_conflicts' },
secondary_actions: [{ code: 'view_details', enabled: true }],
},
source_summary: {
email_subject: null,
filename: 'a.pdf',
@@ -53,10 +73,23 @@ describe('normalizeShippingProcessingProjection', () => {
expect(normalized!.status).toBe('waiting_review');
expect(normalized!.currentGate?.gateCode).toBe('field_conflict_resolution');
expect(normalized!.currentGate?.attemptNo).toBe(1);
expect(normalized!.processGate).toMatchObject({
execution_no: 'EXE-1',
current_gate_code: 'inventory_preparation',
expected_gate_version: 3,
next_action_code: 'retry_inventory_preparation',
});
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']);
expect(normalized!.uiState).toEqual({
status: 'waiting_human',
stage: 'order_review',
blocking_reason: { code: 'pdf_preferred_critical_conflict', i18nKey: null, details: {} },
primary_action: { code: 'resolve_field_conflicts', i18nKey: 'action.resolve_field_conflicts', parameters: {} },
secondary_actions: [{ code: 'view_details', enabled: true }],
});
});
it('normalizes stage_nodes from backend', () => {
@@ -20,6 +20,7 @@ import type {
ShippingProcessingStageNodeStatus,
ShippingProcessingStatus,
ShippingProcessingWorkItemType,
ShippingProcessGateUserSummary,
} from '../types/shipping.api.types';
/**
@@ -372,6 +373,7 @@ export function normalizeShippingProcessingProjection(
lastActivityAt: readString(item, 'last_activity_at', 'lastActivityAt'),
stageNodes: stageNodes?.length ? stageNodes : undefined,
currentGate: normalizeGate(item.current_gate ?? item.currentGate),
processGate: normalizeProcessGateSummary(item.process_gate ?? item.processGate),
availableActions,
sourceSummary: {
emailSubject: readNullableString(summaryRaw, 'email_subject', 'emailSubject'),
@@ -396,6 +398,7 @@ export function normalizeShippingProcessingProjection(
retryable:
(item.retryable as boolean | undefined) == null ? false : Boolean(item.retryable),
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
uiState: normalizeProcessingUiState(item.ui_state ?? item.uiState),
facts: normalizeFacts(item.facts),
userGroup: readNullableString(item, 'user_group', 'userGroup') as ShippingProcessingProjection['userGroup'],
aggregateSummary: normalizeAggregateSummary(item.aggregate_summary ?? item.aggregateSummary),
@@ -410,6 +413,38 @@ export function normalizeShippingProcessingProjection(
};
}
/** 保留后端 Gate 摘要原字段;写操作需要 execution_no 与 evaluation_version,不能降级为展示节点。 */
function normalizeProcessGateSummary(raw: unknown): ShippingProcessGateUserSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
return readString(item, 'execution_no', 'executionNo')
? item as unknown as ShippingProcessGateUserSummary
: null;
}
/** 规范化单项后端 UI 裁决;缺失时返回 undefined 以保留旧响应兼容。 */
function normalizeProcessingUiState(raw: unknown): ShippingProcessingProjection['uiState'] {
if (!raw || typeof raw !== 'object') return undefined;
const state = raw as Record<string, unknown>;
const secondaryRaw = state.secondary_actions ?? state.secondaryActions;
const secondaryActions = Array.isArray(secondaryRaw)
? secondaryRaw
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
.map((item) => ({
code: readString(item, 'code', 'code'),
enabled: item.enabled !== false,
}))
.filter((item) => Boolean(item.code))
: [];
return {
status: (readString(state, 'status', 'status') || 'running') as NonNullable<ShippingProcessingProjection['userStatus']>,
stage: readString(state, 'stage', 'stage'),
blocking_reason: normalizeBlockingReason(state.blocking_reason ?? state.blockingReason),
primary_action: normalizePrimaryAction(state.primary_action ?? state.primaryAction),
secondary_actions: secondaryActions,
};
}
/**
* 将会话级统一投影响应中的 work_items 规范为数组。
*/
@@ -17,6 +17,12 @@ describe('shippingProcessingLabels', () => {
);
});
it('uses the localized waiting_human label instead of exposing the status code', () => {
const te = (key: string) => key === 'chat.shippingProcessing.status.waiting_human';
const t = (key: string) => key.endsWith('waiting_human') ? '待人工处理' : key;
expect(resolveShippingProcessingStatusLabel('waiting_human', te, t)).toBe('待人工处理');
});
it('falls back to shippingProcessing.taskStatus when unified status missing', () => {
// 关键断言:旧 taskStatus 已合并进 shippingProcessing。
const te = (key: string) => key === 'chat.shippingProcessing.taskStatus.queued';
@@ -12,6 +12,7 @@ const LEGACY_STATUS_TO_PROCESSING: Record<string, string> = {
processing: 'processing',
pending_review: 'waiting_review',
waiting_review: 'waiting_review',
waiting_human: 'waiting_human',
failed: 'failed',
completed: 'completed',
cancelled: 'cancelled',
@@ -1,50 +1,49 @@
/**
* features/chat/shipping/shippingStepper.spec.ts
* 用途:验证发货通知七步 Stepper 的本地兜底状态映射。
* 用途:验证发货通知四阶段 Stepper 只消费后端 UI State 投影。
* 依赖:shippingStepper 纯函数、vitest。
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
*/
import { describe, expect, it } from 'vitest';
import {
applyShippingProcessingStageToSteps,
buildShippingWorkflowSteps,
normalizeShippingWorkflowSteps,
resolveShippingWorkflowSteps,
} from './shippingStepper';
describe('shippingStepper', () => {
it('marks inventory step as blocked when RPA inventory is exhausted', () => {
// 关键断言:库存 RPA 获取失败是业务阻断态,不能在步骤条里继续显示为普通 current。
const steps = buildShippingWorkflowSteps({
process_status: 'waiting_inventory',
pending_human_reason: 'rpa_exhausted',
current_step: 'step3_inventory_prepare',
it('renders exactly four stages from backend ui_state', () => {
const steps = resolveShippingWorkflowSteps({
ui_state: {
steps: [
{ id: 'shipping-stage-1', code: 'intake_parse', label: '接收解析', status: 'completed' },
{ id: 'shipping-stage-2', code: 'order_review', label: '订单复核', status: 'completed' },
{ id: 'shipping-stage-3', code: 'fulfillment_prep', label: '发货准备', status: 'blocked' },
{ id: 'shipping-stage-4', code: 'upload_complete', label: '上传完成', status: 'pending' },
],
},
});
expect(steps).toHaveLength(4);
expect(steps[2]?.status).toBe('blocked');
});
it('marks inventory step as blocked when inventory source is unavailable', () => {
// 关键断言:库存触发失败需要用户上传库存或重试,同样应在第 3 步显示异常。
const steps = buildShippingWorkflowSteps({
process_status: 'waiting_inventory',
pending_human_reason: 'inv_unavail',
current_step: 'step3_inventory_prepare',
});
expect(steps[2]?.status).toBe('blocked');
it('fails closed when backend ui_state is missing', () => {
expect(resolveShippingWorkflowSteps({ review_status: 'parse_review' } as never)).toEqual([]);
expect(normalizeShippingWorkflowSteps(null)).toEqual([]);
});
it('overlays unified processing stage onto base stepper steps', () => {
const base = buildShippingWorkflowSteps({
process_status: 'parsed',
current_step: 'step2_parse_confirm',
it('maps technical processing stages into the four business stages', () => {
const base = normalizeShippingWorkflowSteps([
{ code: 'intake_parse', status: 'pending' },
{ code: 'order_review', status: 'pending' },
{ code: 'fulfillment_prep', status: 'pending' },
{ code: 'upload_complete', status: 'pending' },
]);
const steps = applyShippingProcessingStageToSteps(base, {
stage: 'inventory_matching',
status: 'running',
});
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');
expect(steps.map((step) => step.status)).toEqual(['completed', 'completed', 'current', 'pending']);
});
});
@@ -1,9 +1,8 @@
/**
* features/chat/shipping/shippingStepper.ts
* 用途:基于 shipping task 状态推导前端 Stepper 展示数据(七步 legacy / 四步履约)。
* 用途:基于后端 ui_state 投影渲染四阶段业务 Stepper。
* 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。
* 逻辑:任务台优先 buildFulfillmentWorkflowSteps(四节点);无投影时不回退旧 ui_state;
* resolveShippingWorkflowSteps 仍供对话等未切流页面作 legacy 回退。
* 逻辑:只消费后端 ui_state.steps 四阶段投影;缺失投影时 fail-closed。
*/
import {
FULFILLMENT_PROGRESS_NODES,
@@ -11,12 +10,9 @@ import {
type FulfillmentProgressNodeKey,
} from './shippingProcessingFulfillment';
export interface ShippingTaskStepperSource {
process_status?: string | null;
review_status?: string | null;
pending_human_reason?: string | null;
match_status?: string | null;
export_file_name?: string | null;
current_step?: string | null;
ui_state?: {
steps?: ShippingWorkflowStepSource[] | null;
} | null;
}
export interface ShippingWorkflowStepItem {
@@ -33,32 +29,12 @@ type ShippingWorkflowStepSource = {
};
export const SHIPPING_WORKFLOW_STEP_LABELS = [
'chat.shippingNoticeUi.stepper.noticeSubmit',
'chat.shippingNoticeUi.stepper.parseConfirm',
'chat.shippingNoticeUi.stepper.inventoryPrepare',
'chat.shippingNoticeUi.stepper.alignConfirm',
'chat.shippingNoticeUi.stepper.matchInventory',
'chat.shippingNoticeUi.stepper.generateFile',
'chat.shippingNoticeUi.stepper.uploadFreight',
'chat.shippingNoticeUi.stage.intakeParse',
'chat.shippingNoticeUi.stage.orderReview',
'chat.shippingNoticeUi.stage.fulfillmentPrep',
'chat.shippingNoticeUi.stage.uploadComplete',
] as const;
const CURRENT_STEP_INDEX_MAP: Record<string, number> = {
step1_notice_submit: 0,
step2_parse_confirm: 1,
step3_inventory_prepare: 2,
step2_inventory_prepare: 2,
step4_align_confirm: 3,
step5_match_inventory: 4,
step3_inventory_match: 4,
step4_shortage_review: 4,
step6_generate_file: 5,
step5_export_excel: 5,
step7_upload_freight: 6,
step6_upload_freight: 6,
step7_finish: 6,
};
const TERMINAL_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
const WORKFLOW_STEP_STATUSES = new Set<ShippingWorkflowStepItem['status']>([
'completed',
'current',
@@ -80,7 +56,7 @@ export function normalizeShippingWorkflowSteps(
return null;
}
return {
id: String(step?.id || step?.code || `shipping-step-${index + 1}`),
id: String(step?.id || step?.code || `shipping-stage-${index + 1}`),
label: String(step?.label || SHIPPING_WORKFLOW_STEP_LABELS[index] || ''),
status: status as ShippingWorkflowStepItem['status'],
};
@@ -89,76 +65,32 @@ export function normalizeShippingWorkflowSteps(
}
/**
* 优先消费后端状态机 UI State steps;没有时按 task 状态本地推导。
* 只消费后端状态机 UI State steps;没有投影时返回空数组,禁止本地猜测阶段。
*/
export function resolveShippingWorkflowSteps(
task: (ShippingTaskStepperSource & { ui_state?: { steps?: ShippingWorkflowStepSource[] | null } | null }) | null | undefined,
task: ShippingTaskStepperSource | null | undefined,
): ShippingWorkflowStepItem[] {
const uiStateSteps = normalizeShippingWorkflowSteps(task?.ui_state?.steps);
return uiStateSteps.length ? uiStateSteps : buildShippingWorkflowSteps(task);
}
function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number {
const currentStep = String(task?.current_step || '').trim();
const processStatus = String(task?.process_status || '').trim();
const reviewStatus = String(task?.review_status || '').trim();
const pendingReason = String(task?.pending_human_reason || '').trim();
const matchStatus = String(task?.match_status || '').trim();
const hasExport = !!String(task?.export_file_name || '').trim();
if (currentStep) {
const currentStepIndex = CURRENT_STEP_INDEX_MAP[currentStep];
if (currentStepIndex !== undefined) {
return currentStepIndex;
}
}
if (TERMINAL_PROCESS_STATUSES.has(processStatus)) return 6;
if (processStatus === 'waiting_upload' || processStatus === 'upload_failed' || hasExport) return 5;
if (processStatus === 'matched') return 4;
if (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage') return 4;
if (processStatus === 'inventory_ready' || matchStatus) return 4;
if (
processStatus === 'waiting_inventory'
|| pendingReason === 'rpa_pending'
|| pendingReason === 'inv_unavail'
|| pendingReason === 'rpa_exhausted'
) {
return 2;
}
if (
processStatus === 'parsed'
|| processStatus === 'pending_review'
|| reviewStatus === 'pending_confirm'
|| reviewStatus === 'parse_review'
|| reviewStatus === 'rsv_required'
|| pendingReason === 'low_confidence'
|| pendingReason === 'rsv_required'
|| pendingReason === 'inventory_source_unresolved'
) {
return 1;
}
return 0;
return uiStateSteps;
}
/** 统一 ShippingProcessingStage → 粗粒度 Stepper 下标(过渡期;阶段 2 换 UnifiedProgressTrack)。 */
const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
upload_received: 0,
email_parsing: 1,
document_parsing: 1,
email_parsing: 0,
document_parsing: 0,
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_source_resolving: 2,
inventory_fetching: 2,
inventory_matching: 4,
excel_generating: 5,
freight_uploading: 6,
completed: 6,
inventory_matching: 2,
excel_generating: 2,
freight_uploading: 3,
completed: 3,
};
/**
@@ -167,7 +99,7 @@ const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
* 核心逻辑:有投影时按 stage 重算 completed/current/pending;blocked/failed 标当前步 blocked;
* 无投影或无法映射时原样返回 baseSteps。
*
* @param baseSteps - ui_state / process_status 推导的步骤
* @param baseSteps - ui_state 推导的步骤
* @param projection - 统一 order_task 投影
*/
export function applyShippingProcessingStageToSteps(
@@ -200,47 +132,12 @@ export function applyShippingProcessingStageToSteps(
}
/**
* 将 task 状态映射为七步 Stepper 项(id / label / done / active)。
* 缺少后端投影时 fail-closed,不根据 review/match/upload 等领域事实猜测阶段。
*/
export function buildShippingWorkflowSteps(
task: ShippingTaskStepperSource | null | undefined,
_task: ShippingTaskStepperSource | null | undefined,
): ShippingWorkflowStepItem[] {
const currentIndex = deriveCurrentIndex(task);
const reviewStatus = String(task?.review_status || '').trim();
const pendingReason = String(task?.pending_human_reason || '').trim();
const processStatus = String(task?.process_status || '').trim();
return SHIPPING_WORKFLOW_STEP_LABELS.map((label, index) => {
let status: ShippingWorkflowStepItem['status'] = 'pending';
// [STEP 1] uploaded/closed 是整票已完成的终态,不能再被 current_step 渲染成“第 7 步进行中”。
if (TERMINAL_PROCESS_STATUSES.has(processStatus)) {
status = 'completed';
} else if (index < currentIndex) {
status = 'completed';
} else if (index === currentIndex) {
status = 'current';
}
if (
(index === 1 && (
reviewStatus === 'parse_review'
|| pendingReason === 'low_confidence'
|| pendingReason === 'rsv_required'
|| pendingReason === 'inventory_source_unresolved'
))
|| (index === 2 && (pendingReason === 'inv_unavail' || pendingReason === 'rpa_exhausted'))
|| (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage'))
|| (index === 6 && processStatus === 'upload_failed')
) {
status = 'blocked';
}
return {
id: `shipping-step-${index + 1}`,
label,
status,
};
});
return [];
}
/**
@@ -275,7 +275,7 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
.replace(/\braw_text\b/gi, '通知原文');
result = result.replace(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, '');
result = result.replace(
/\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi,
/\b(pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[^\s,;]+[「"'`]?/gi,
'',
);
for (const token of SHIPPING_INTERNAL_STATUS_TOKENS) {
@@ -44,7 +44,7 @@ describe('useChatShippingRefresh', () => {
task_no: 'SN-FOCUS-B',
batch_no: 'SB-FOCUS-001',
checkpoint: 'ready_export',
process_status: 'matched',
match_status: 'matched',
review_status: null,
pending_human_reason: null,
match_status: 'fulfillable',
@@ -105,7 +105,7 @@ describe('useChatShippingRefresh', () => {
task_no: 'SN-SOURCE-001',
batch_no: 'SB-SOURCE-001',
checkpoint: 'ready_export',
process_status: 'matched',
match_status: 'matched',
review_status: null,
pending_human_reason: null,
match_status: 'fulfillable',
@@ -116,7 +116,11 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
// keep existing SSE-delivered ui_state if present
}
}
const apiCheckpoint = apiState?.checkpoint ? String(apiState.checkpoint) : null;
const apiCheckpoint = String(
apiState?.checkpoint?.code
|| apiState?.checkpoint_code
|| '',
).trim() || null;
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
msgs.forEach((rawMsg) => {
const m = rawMsg as ChatMessage;
@@ -140,20 +144,36 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
let cleanedText = stripShippingPlainActionMenu(String(chatMsg.content || ''));
if (index === targetAssistantIndex && apiState) {
chatMsg.shipping_ui_state = apiState;
if (apiState.action_buttons?.length) {
cleanedText = stripShippingActionListByButtons(cleanedText, apiState.action_buttons);
const projectedActions = [apiState.actions?.primary, ...(apiState.actions?.secondary || [])]
.filter(Boolean)
.map((action) => ({
id: String(action?.code || ''),
label: String(action?.label || ''),
message: String(action?.disabled_reason || ''),
variant: action?.kind === 'terminate' ? 'danger' : 'primary',
}));
if (projectedActions.length) {
cleanedText = stripShippingActionListByButtons(cleanedText, projectedActions);
}
} else if (!apiResolved && chatMsg.shipping_ui_state?.action_buttons?.length) {
} else if (!apiResolved && chatMsg.shipping_ui_state?.actions) {
const projectedActions = [chatMsg.shipping_ui_state.actions.primary, ...(chatMsg.shipping_ui_state.actions.secondary || [])]
.filter(Boolean)
.map((action) => ({
id: String(action?.code || ''),
label: String(action?.label || ''),
message: String(action?.disabled_reason || ''),
variant: action?.kind === 'terminate' ? 'danger' : 'primary',
}));
cleanedText = stripShippingActionListByButtons(
cleanedText,
chatMsg.shipping_ui_state.action_buttons,
projectedActions,
);
}
if (cleanedText !== String(chatMsg.content || '').trim()) {
chatMsg.content = cleanedText;
}
if (chatMsg.type === 'shipping-match-result' && chatMsg.payload && typeof chatMsg.payload === 'object') {
(chatMsg.payload as { action_buttons?: unknown[] }).action_buttons = [];
delete (chatMsg.payload as { action_buttons?: unknown[] }).action_buttons;
}
});
};
@@ -10,6 +10,7 @@ import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import { extractExt } from '../constants/shipping';
import { buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
import type { PendingAttachment } from '../types/shipping.types';
@@ -232,7 +233,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return false;
}
const query = ctx.input.value.trim();
const ok = await ctx.startOrderExtractionRun(query, intakeNos, []);
// 已解析的通知附件仍要固化到用户消息;此前传空数组会使发送后对话区丢失附件卡片。
const attachmentSnapshots = createChatMessageAttachmentSnapshots(
ctx.attachments.value.filter((attachment) => attachment.kind === 'shipping_notice'),
);
const ok = await ctx.startOrderExtractionRun(query, intakeNos, attachmentSnapshots);
if (ok) {
ctx.clearConsumedNoticeAttachments?.();
void ctx.refreshShippingActions();
@@ -136,7 +136,7 @@ function mapServerDuplicate(remote: ShippingNoticeIntakeResponse): {
fingerprintStrength: dup.fingerprint_strength,
matches: (dup.matches || []).map((item) => ({
taskNo: item.task_no,
processStatus: item.process_status,
processStatus: item.lifecycle || 'active',
documentVersion: Number(item.document_version || 1),
matchType: item.match_type,
matchedFields: listSafe(item.matched_fields),
@@ -170,7 +170,7 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
fingerprintStrength: remote.duplicate.fingerprint_strength,
matches: (remote.duplicate.matches || []).map((item) => ({
taskNo: item.task_no,
processStatus: item.process_status,
processStatus: item.lifecycle || 'active',
documentVersion: Number(item.document_version || 1),
matchType: item.match_type,
matchedFields: listSafe(item.matched_fields),
@@ -198,7 +198,6 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
candidateStatus: remote.candidate_status || 'provisional',
acceptanceMode: remote.acceptance_mode || undefined,
extractionSource: remote.extraction_source || undefined,
actionButtons: Array.isArray(remote.action_buttons) ? remote.action_buttons : [],
selected: Boolean(remote.selected),
conflicts: remote.conflicts || [],
missingFields: Array.isArray(remote.missing_fields) ? remote.missing_fields.map((item) => String(item)) : [],
@@ -7,6 +7,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { nextTick, ref } from 'vue';
import {
resolveProcessingPollIntervalMs,
resolveProcessingPollBackoffMs,
shouldContinueProcessingPolling,
useShippingNoticeWorkflow,
@@ -31,6 +32,12 @@ vi.mock('../api/shipping.api', () => ({
* 构造历史会话右侧任务投影。
*/
function buildProcessing(conversationId = 'conv-1'): ConversationProcessingProjection {
const needsAction = {
user_task_no: `OT-${conversationId}`,
group: 'needs_action' as const,
can_append: false,
file_count: 2,
};
return {
conversation_id: conversationId,
summary: {
@@ -42,14 +49,12 @@ function buildProcessing(conversationId = 'conv-1'): ConversationProcessingProje
history: 0,
},
processing: [],
needs_action: [{
user_task_no: `OT-${conversationId}`,
group: 'needs_action',
can_append: false,
file_count: 2,
}],
needs_action: [needsAction],
completed: [],
history: [],
status_groups: {
failed: [], waiting_human: [needsAction], processing: [], completed: [], cancelled: [], archived: [],
},
};
}
@@ -111,11 +116,19 @@ function deferred<T>() {
}
describe('useShippingNoticeWorkflow helpers', () => {
it('caps failure backoff at 8s', () => {
expect(resolveProcessingPollBackoffMs(1)).toBe(2000);
expect(resolveProcessingPollBackoffMs(2)).toBe(4000);
expect(resolveProcessingPollBackoffMs(3)).toBe(8000);
expect(resolveProcessingPollBackoffMs(10)).toBe(8000);
it('uses the specified 10s, 20s, 30s failure backoff', () => {
expect(resolveProcessingPollBackoffMs(1)).toBe(10000);
expect(resolveProcessingPollBackoffMs(2)).toBe(20000);
expect(resolveProcessingPollBackoffMs(3)).toBe(30000);
expect(resolveProcessingPollBackoffMs(10)).toBe(30000);
});
it('tiers active polling by elapsed time and page visibility', () => {
expect(resolveProcessingPollIntervalMs({ elapsedMs: 0, visibility: 'visible', hasProcessing: true, failureCount: 0 })).toBe(2000);
expect(resolveProcessingPollIntervalMs({ elapsedMs: 15000, visibility: 'visible', hasProcessing: true, failureCount: 0 })).toBe(5000);
expect(resolveProcessingPollIntervalMs({ elapsedMs: 60000, visibility: 'visible', hasProcessing: true, failureCount: 0 })).toBe(10000);
expect(resolveProcessingPollIntervalMs({ elapsedMs: 0, visibility: 'hidden', hasProcessing: true, failureCount: 0 })).toBe(30000);
expect(resolveProcessingPollIntervalMs({ elapsedMs: 0, visibility: 'visible', hasProcessing: false, failureCount: 0 })).toBeNull();
});
it('stops when processing idle', () => {
@@ -269,7 +282,7 @@ describe('useShippingNoticeWorkflow', () => {
work_items: [{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'email',
sourceType: 'eml',
conversationId: 'conv-1',
intakeNo: 'SNI-1',
status: 'processing',
@@ -418,7 +431,7 @@ describe('useShippingNoticeWorkflow', () => {
await nextTick();
expect(ctl.error.value).toBe('network_recoverable');
await vi.advanceTimersByTimeAsync(2000);
await vi.advanceTimersByTimeAsync(10000);
await nextTick();
await Promise.resolve();
@@ -450,4 +463,62 @@ describe('useShippingNoticeWorkflow', () => {
expect(ctl.processing.value?.conversation_id).toBe('conv-new');
ctl.stop();
});
it('immediately restores a cached conversation projection while it revalidates', async () => {
const revalidate = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing
.mockResolvedValueOnce(buildUnifiedProcessing('conv-a'))
.mockResolvedValueOnce(buildUnifiedProcessing('conv-b'))
.mockImplementationOnce(() => revalidate.promise);
const conversationId = ref('conv-a');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
conversationId.value = 'conv-b';
await nextTick();
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
conversationId.value = 'conv-a';
await nextTick();
// 已访问会话首帧使用本会话最后成功 Projection,不会退回骨架或 B 的数据。
expect(ctl.processing.value?.conversation_id).toBe('conv-a');
expect(ctl.initialLoading.value).toBe(false);
expect(ctl.isRefreshing.value).toBe(true);
revalidate.resolve(buildUnifiedProcessing('conv-a'));
ctl.stop();
});
it('drops a response whose server conversation id differs from the request target', async () => {
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing('wrong-conversation'));
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-a') });
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(ctl.processing.value).toBeNull();
ctl.stop();
});
it('marks the restored conversation as initial loading after aborting an old poll', async () => {
const oldPoll = deferred<ReturnType<typeof buildUnifiedProcessing>>();
const newInitial = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing
.mockImplementationOnce(() => oldPoll.promise)
.mockImplementationOnce(() => newInitial.promise);
const conversationId = ref('conv-old');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
conversationId.value = 'conv-new';
await nextTick();
await vi.advanceTimersByTimeAsync(0);
expect(ctl.initialLoading.value).toBe(true);
expect(ctl.manualRefreshing.value).toBe(false);
expect(ctl.polling.value).toBe(false);
newInitial.resolve(buildUnifiedProcessing('conv-new'));
await Promise.resolve();
ctl.stop();
});
});
@@ -36,10 +36,30 @@ import {
resolveConversationProcessingFromUnified,
} from './conversationProcessingProjection';
const FOREGROUND_POLL_MS = 2000;
const BACKGROUND_POLL_MS = 8000;
const FIRST_ACTIVE_POLL_MS = 2000;
const MID_ACTIVE_POLL_MS = 5000;
const LONG_ACTIVE_POLL_MS = 10000;
const BACKGROUND_POLL_MS = 30000;
const REQUEST_TIMEOUT_MS = 10000;
const MAX_BACKOFF_MS = 8000;
const MAX_BACKOFF_MS = 30000;
const SNAPSHOT_CACHE_LIMIT = 20;
type ProjectionSnapshot = {
conversationId: string;
processing: ConversationProcessingProjection;
workItems: ShippingProcessingProjection[];
semanticKey: string;
receivedAt: number;
lastAccessedAt: number;
processingStartedAt: number | null;
};
export type ProcessingPollContext = {
elapsedMs: number;
visibility: DocumentVisibilityState | 'visible' | 'hidden';
hasProcessing: boolean;
failureCount: number;
};
export type UseShippingNoticeWorkflowOptions = {
/** 当前会话 ID;空则停轮询并清空。 */
@@ -61,6 +81,12 @@ export type UseShippingNoticeWorkflowReturn = {
manualRefreshing: Ref<boolean>;
/** 后台静默轮询中(不显示 loading,不禁用按钮)。 */
polling: Ref<boolean>;
/** 当前会话任意 Projection GET 在途;不得作为整卡遮罩条件。 */
isFetching: Ref<boolean>;
/** 当前会话已有成功 Projection 时的刷新状态。 */
isRefreshing: Ref<boolean>;
/** 当前会话最后一次成功 Projection 接收时间。 */
snapshotUpdatedAt: Ref<number | null>;
error: Ref<string | null>;
refresh: () => Promise<void>;
focusConversationTask: (taskNo: string) => Promise<void>;
@@ -84,26 +110,22 @@ function readOption<T>(source: MaybeRefOrGetter<T>): T {
* 按页面可见性 + 业务状态选择轮询间隔。
* 分层策略:系统处理中 2s;待人工复核 30s;后台标签页 8s(若仍需轮询)。
*/
function resolvePollMs(
processing?: ConversationProcessingProjection | null,
): number {
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
return BACKGROUND_POLL_MS;
}
const processingCount = Number(
processing?.summary?.processing || processing?.processing?.length || 0,
);
if (processingCount > 0) return FOREGROUND_POLL_MS;
return FOREGROUND_POLL_MS;
export function resolveProcessingPollIntervalMs(context: ProcessingPollContext): number | null {
if (!context.hasProcessing) return null;
if (context.failureCount > 0) return resolveProcessingPollBackoffMs(context.failureCount);
if (context.visibility === 'hidden') return BACKGROUND_POLL_MS;
if (context.elapsedMs < 15000) return FIRST_ACTIVE_POLL_MS;
if (context.elapsedMs < 60000) return MID_ACTIVE_POLL_MS;
return LONG_ACTIVE_POLL_MS;
}
/**
* 失败退避:2s → 4s → 8s(封顶)。
* 失败退避:10s → 20s → 30s(封顶)。
* @param failureCount - 连续失败次数(≥1)
*/
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);
return Math.min(LONG_ACTIVE_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS);
}
/**
@@ -136,20 +158,84 @@ export function useShippingNoticeWorkflow(
const manualRefreshing = ref(false);
const polling = ref(false);
const error = ref<string | null>(null);
const snapshotUpdatedAt = ref<number | null>(null);
const isFetching = ref(false);
const snapshots = new Map<string, ProjectionSnapshot>();
const loading = computed(() => (
initialLoading.value || manualRefreshing.value || polling.value
));
const isRefreshing = computed(() => isFetching.value && processing.value !== null);
let pollTimer: ReturnType<typeof setTimeout> | null = null;
let pollGeneration = 0;
let requestController: AbortController | null = null;
let requestGeneration = 0;
const requestGenerations = new Map<string, number>();
let inFlightRefresh: { conversationId: string; promise: Promise<void> } | null = null;
let failureCount = 0;
let pollingStopped = false;
let lastSemanticKey = '';
const intakeOtStabilizer = createIntakeOtStabilizer();
function touchSnapshot(snapshot: ProjectionSnapshot): ProjectionSnapshot {
snapshot.lastAccessedAt = Date.now();
return snapshot;
}
function readSnapshot(conversationId: string): ProjectionSnapshot | null {
const snapshot = snapshots.get(conversationId);
return snapshot ? touchSnapshot(snapshot) : null;
}
function pruneSnapshots(): void {
while (snapshots.size > SNAPSHOT_CACHE_LIMIT) {
const oldest = [...snapshots.values()]
.sort((left, right) => left.lastAccessedAt - right.lastAccessedAt)[0];
if (!oldest) return;
snapshots.delete(oldest.conversationId);
}
}
function workItemsSemanticKey(items: ShippingProcessingProjection[]): string {
return JSON.stringify(items.map((item) => ({
no: item.workItemNo,
type: item.workItemType,
status: item.uiState?.status ?? item.userStatus ?? item.status,
stage: item.uiState?.stage ?? item.userStage ?? item.stage,
gate: item.uiState?.blocking_reason?.code ?? item.blockingReason?.code ?? null,
action: item.uiState?.primary_action?.code ?? item.primaryAction?.code ?? null,
version: item.progressVersion,
files: (item.aggregateChildren || []).map((child) => ({
no: child.workItemNo,
status: child.uiState?.status ?? child.userStatus ?? child.status,
stage: child.uiState?.stage ?? child.userStage ?? child.stage,
file: child.sourceSummary?.filename ?? null,
})),
})));
}
function applySnapshot(snapshot: ProjectionSnapshot | null): void {
processing.value = snapshot?.processing ?? null;
processingWorkItems.value = snapshot?.workItems ?? [];
snapshotUpdatedAt.value = snapshot?.receivedAt ?? null;
}
function currentPollElapsedMs(): number {
const snapshot = readSnapshot(normalizedConversationId.value);
return snapshot?.processingStartedAt === null || snapshot?.processingStartedAt === undefined
? 0
: Math.max(0, Date.now() - snapshot.processingStartedAt);
}
function resolveCurrentPollInterval(): number | null {
return resolveProcessingPollIntervalMs({
elapsedMs: currentPollElapsedMs(),
visibility: typeof document === 'undefined' ? 'visible' : document.visibilityState,
hasProcessing: shouldContinueProcessingPolling(processing.value),
failureCount,
});
}
/**
* 在 Intake→OT 过渡窗里,若 projection 被稳定器保留为上一轮 OT 视图,
* 则 work_items 也必须同步保留上一轮 order_task;否则卡片正文与侧边进度条
@@ -183,6 +269,12 @@ export function useShippingNoticeWorkflow(
pollTimer = null;
requestController?.abort();
requestController = null;
// 请求属于上一会话代际时 finally 会因 generation 不匹配而跳过清理;
// 必须在此同步清空,才能让新会话首个 GET 固定进入 initialLoading。
initialLoading.value = false;
manualRefreshing.value = false;
polling.value = false;
isFetching.value = false;
requestGeneration += 1;
pollGeneration += 1;
}
@@ -214,22 +306,31 @@ export function useShippingNoticeWorkflow(
mode: 'initial' | 'manual' | 'poll',
): Promise<void> {
const generation = ++requestGeneration;
if (mode === 'initial') initialLoading.value = true;
requestGenerations.set(conversationId, generation);
const existingSnapshot = readSnapshot(conversationId);
if (mode === 'initial' && !existingSnapshot) initialLoading.value = true;
else if (mode === 'manual') manualRefreshing.value = true;
else polling.value = true;
isFetching.value = true;
const controller = createRequestController();
try {
// [STEP 1] 统一投影为唯一读源。
const unified = await getWorkspaceShippingProcessing(conversationId, controller.signal);
if (
controller.signal.aborted
|| generation !== requestGeneration
|| requestGenerations.get(conversationId) !== generation
|| conversationId !== normalizedConversationId.value
|| String(unified?.conversation_id || '').trim() !== conversationId
) return;
const workItems = Array.isArray(unified?.work_items) ? unified.work_items : [];
// 记录该会话已见过 OT,供下一轮 Intake 稀疏响应在稳定窗口内保留上一投影。
if (workItems.some((item) => item.workItemType === 'order_task')) {
intakeOtStabilizer.markSeen(conversationId);
}
const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined;
const prevProjection = processing.value;
const previousSnapshot = readSnapshot(conversationId);
const prevProjection = previousSnapshot?.processing ?? null;
const nextProjection = resolveConversationProcessingFromUnified(
workItems,
embedded,
@@ -241,23 +342,55 @@ export function useShippingNoticeWorkflow(
reset: (cId) => intakeOtStabilizer.reset(cId),
},
);
const nextSemanticKey = buildProcessingSemanticKey(nextProjection);
processingWorkItems.value = resolveStableWorkItems(
if (!nextProjection) {
// 空投影同样是本次后端裁决,但不作为“成功 Projection”缓存;
// 保留已有 Snapshot 可避免短暂稀疏响应把业务卡卸载。
if (!previousSnapshot) applySnapshot(null);
error.value = null;
failureCount = 0;
return;
}
const nextSemanticKey = `${buildProcessingSemanticKey(nextProjection)}:${workItemsSemanticKey(workItems)}`;
const nextWorkItems = resolveStableWorkItems(
workItems,
prevProjection,
nextProjection,
);
if (nextSemanticKey !== lastSemanticKey) {
processing.value = nextProjection;
// Intake→OT 的短暂稀疏响应由稳定器明确裁决为上一版 Projection;
// 此时 work_items 也必须维持同一 Snapshot,不能因原始项差异替换。
const keepPreviousSnapshot = Boolean(
previousSnapshot
&& !workItems.some((item) => item.workItemType === 'order_task')
&& intakeOtStabilizer.hasSeenOrderTaskBefore(conversationId),
);
if (!previousSnapshot || (!keepPreviousSnapshot && nextSemanticKey !== previousSnapshot.semanticKey)) {
const now = Date.now();
const processingStartedAt = shouldContinueProcessingPolling(nextProjection)
? (previousSnapshot?.processingStartedAt ?? now)
: null;
const snapshot: ProjectionSnapshot = {
conversationId,
processing: nextProjection,
workItems: nextWorkItems,
semanticKey: nextSemanticKey,
receivedAt: now,
lastAccessedAt: now,
processingStartedAt,
};
snapshots.set(conversationId, snapshot);
pruneSnapshots();
applySnapshot(snapshot);
lastSemanticKey = nextSemanticKey;
} else {
touchSnapshot(previousSnapshot);
applySnapshot(previousSnapshot);
}
error.value = null;
failureCount = 0;
} catch (reason) {
if (
controller.signal.aborted
|| generation !== requestGeneration
|| requestGenerations.get(conversationId) !== generation
|| conversationId !== normalizedConversationId.value
) return;
failureCount += 1;
@@ -266,10 +399,14 @@ export function useShippingNoticeWorkflow(
: 'network_recoverable';
} finally {
if (requestController === controller) requestController = null;
if (generation === requestGeneration) {
if (
requestGenerations.get(conversationId) === generation
&& requestGeneration === generation
) {
if (mode === 'initial') initialLoading.value = false;
else if (mode === 'manual') manualRefreshing.value = false;
else polling.value = false;
isFetching.value = false;
}
}
}
@@ -281,8 +418,7 @@ export function useShippingNoticeWorkflow(
function refresh(): Promise<void> {
const conversationId = normalizedConversationId.value;
if (!conversationId) {
processing.value = null;
processingWorkItems.value = [];
applySnapshot(null);
error.value = null;
lastSemanticKey = '';
return Promise.resolve();
@@ -291,7 +427,7 @@ export function useShippingNoticeWorkflow(
if (inFlightRefresh?.conversationId === conversationId) {
return inFlightRefresh.promise;
}
const isFirstLoad = processing.value === null && !initialLoading.value && !manualRefreshing.value && !polling.value;
const isFirstLoad = !readSnapshot(conversationId) && !initialLoading.value && !manualRefreshing.value && !polling.value;
const mode: 'initial' | 'manual' = isFirstLoad ? 'initial' : 'manual';
const promise = executeRefresh(conversationId, mode).finally(() => {
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
@@ -400,10 +536,8 @@ export function useShippingNoticeWorkflow(
if (!shouldContinueProcessingPolling(processing.value)) {
return;
}
const nextDelay = failureCount > 0
? resolveProcessingPollBackoffMs(failureCount)
: resolvePollMs(processing.value);
schedulePoll(generation, nextDelay);
const nextDelay = resolveCurrentPollInterval();
if (nextDelay !== null) schedulePoll(generation, nextDelay);
}, delayMs);
}
@@ -426,7 +560,8 @@ export function useShippingNoticeWorkflow(
return;
}
if (!shouldContinueProcessingPolling(processing.value)) return;
schedulePoll(generation, resolvePollMs(processing.value));
const nextDelay = resolveCurrentPollInterval();
if (nextDelay !== null) schedulePoll(generation, nextDelay);
});
}
@@ -438,10 +573,9 @@ export function useShippingNoticeWorkflow(
watch(normalizedConversationId, (nextConversationId, previousConversationId) => {
if (nextConversationId !== previousConversationId) {
processing.value = null;
processingWorkItems.value = [];
applySnapshot(readSnapshot(nextConversationId));
error.value = null;
lastSemanticKey = '';
lastSemanticKey = readSnapshot(nextConversationId)?.semanticKey || '';
}
restartPolling();
}, { immediate: true });
@@ -477,6 +611,9 @@ export function useShippingNoticeWorkflow(
initialLoading,
manualRefreshing,
polling,
isFetching,
isRefreshing,
snapshotUpdatedAt,
error,
refresh,
focusConversationTask,