feat(shipping-notice): 实现对话级批量重试自动推进功能,优化库存与PDF匹配逻辑

- 新增对话级批量重试自动推进的完整链路:后端服务、API、数据投影逻辑
- 前端新增对话级重试按钮、多语言国际化支持与API类型定义
- 优化行级库存重试控制,新增retryable字段统一管控重试按钮展示,清理废弃的view_fulfillment_detail动作,标准化前端动作码排序逻辑
- 修复PDF坐标匹配的fail-close防护逻辑,避免生成伪精确匹配分数
- 调整订单确认后流程,提前进入库存获取阶段,移除冗余的确认建单按钮,优化用户流转体验
- 新增对应单元测试用例覆盖核心业务逻辑
This commit is contained in:
hugo committed 2026-08-07 16:30:45 +08:00
1 parent fd6a23f870
commit 1008911a7e
41 files changed
+3956 -1256

No files matched your search

@@ -15,6 +15,10 @@ import {
groupConversationProcessingTasks,
mapUserTaskObjectsToFileRows,
resolveConversationProcessingFromUnified,
normalizeActionCodes,
buildTaskSemanticKey,
buildProcessingSemanticKey,
stabilizeTaskObjects,
} from './conversationProcessingProjection';
import type {
ShippingProcessingProjection,
@@ -730,3 +734,166 @@ describe('conversationProcessingProjection', () => {
expect(merged?.recent_task_no).toBe('OT-RECENT');
});
});
/**
* 方案 1~4 的防御链单元测试:
* normalize → semanticKey → stabilize;任何一环击穿都会导致轮询按钮闪烁。
* 对应验收:动作顺序变化按钮不变 / updated_at 变化按钮不变 / 轮询相同数据按钮 DOM 不变。
*/
describe('conversationProcessingProjection — normalize & semantic & stabilize', () => {
it('normalizeActionCodes: 去空白、小写、去重、字典序排序', () => {
expect(normalizeActionCodes([' View_Details ', 'Confirm_Customer', 'view_details', ' confirm_customer ']))
.toEqual(['confirm_customer', 'view_details']);
expect(normalizeActionCodes([null, undefined, '', ' ', 'cancel', '0']))
.toEqual(['0', 'cancel']);
expect(normalizeActionCodes([])).toEqual([]);
expect(normalizeActionCodes([undefined, null])).toEqual([]);
});
it('buildTaskSemanticKey: available_actions 乱序 → 同一签名(不影响按钮顺序)', () => {
const base: Parameters<typeof projectConversationProcessingFromWorkItems>[0][number] = {
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-1',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-10T00:00:00Z',
currentGate: {
gateCode: 'order_freeze_readiness',
status: 'blocked',
nextActionCode: 'open_order_review',
blockingReasonCode: 'review_case_draft',
attemptNo: 0,
},
availableActions: ['open_order_review', 'view_details'],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 0,
customerName: null,
poNumber: 'PO-1',
},
childOrderTasks: [],
};
const p1 = projectConversationProcessingFromWorkItems([{ ...base }]);
const p2 = projectConversationProcessingFromWorkItems([
{ ...base, availableActions: ['view_details', 'open_order_review'], lastActivityAt: '2099-01-01T00:00:00Z' },
]);
const t1 = p1!.needs_action[0]!;
const t2 = p2!.needs_action[0]!;
// 相同语义字段 -> 同签名;即使 available_actions 顺序不同、lastActivityAt 不同。
expect(buildTaskSemanticKey(t1)).toBe(buildTaskSemanticKey(t2));
// available_actions 内永远是 normalized 排序后的数组,不是原始后端乱序。
expect(t1.available_actions).toEqual(['open_order_review', 'view_details']);
expect(t2.available_actions).toEqual(['open_order_review', 'view_details']);
});
it('stabilizeTaskObjects: 同一 user_task_no 且语义相同,优先复用旧对象引用(避免 DOM 重建)', () => {
const baseTask = (no: string, updatedAt: string) => ({
user_task_no: no,
group: 'processing' as const,
status_label: 'document_parsing',
run_no: 'RUN-1',
title: '订单识别任务',
primary_action: 'view_details',
display_kind: 'single_document_task',
file_count: 1,
can_append: false,
updated_at: updatedAt,
last_activity_at: updatedAt,
available_actions: ['view_details'],
current_gate: null,
user_task_authoritative: true,
documents: [],
});
const oldOne = baseTask('OT-1', '2026-08-10T00:00:00Z');
const nextOne = baseTask('OT-1', '2026-08-10T00:00:02Z');
const oldTasks = [oldOne];
const nextRawTasks = [nextOne];
const stabilized = stabilizeTaskObjects(oldTasks, nextRawTasks);
// updated_at/last_activity_at 不参与 semanticKey 比较 -> 复用旧引用。
expect(stabilized[0]).toBe(oldOne);
expect(stabilized[0].updated_at).toBe('2026-08-10T00:00:00Z');
});
it('buildProcessingSemanticKey: 只基于语义字段,忽略 updated_at/last_activity_at 扰动', () => {
function makeProjection() {
return projectConversationProcessingFromWorkItems([{
workItemType: 'order_task',
workItemNo: 'OT-A',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-A',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-10T00:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null, filename: 'a.pdf',
documentCount: 1, parsedDocumentCount: 1, candidateCount: 0,
customerName: null, poNumber: null,
},
childOrderTasks: [],
}])!;
}
const pA = makeProjection();
const pB = makeProjection();
// 模拟轮询差异:updated_at / last_activity_at / created_at 等辅助字段都变。
pA.processing[0]!.updated_at = '2026-08-10T00:00:00Z';
pA.processing[0]!.last_activity_at = '2026-08-10T00:00:00Z';
pB.processing[0]!.updated_at = '2026-08-10T00:00:02Z';
pB.processing[0]!.last_activity_at = '2026-08-10T00:00:02Z';
expect(buildProcessingSemanticKey(pA)).toBe(buildProcessingSemanticKey(pB));
});
it('stabilizeTaskObjects: 语义变化时(status 改变)必须返回新对象,不能错误冻结旧状态', () => {
const oldTask = {
user_task_no: 'OT-1',
group: 'processing' as const,
status_label: 'document_parsing',
run_no: 'RUN-1',
title: '订单识别任务',
primary_action: 'view_details',
display_kind: 'single_document_task',
file_count: 1,
can_append: false,
updated_at: '2026-08-10T00:00:00Z',
last_activity_at: '2026-08-10T00:00:00Z',
available_actions: ['view_details'],
current_gate: null,
user_task_authoritative: true,
documents: [],
};
const nextTask = {
...oldTask,
group: 'needs_action' as const,
status_label: 'waiting_review',
primary_action: 'open_order_review',
available_actions: ['open_order_review', 'view_details'],
updated_at: '2026-08-10T00:00:10Z',
last_activity_at: '2026-08-10T00:00:10Z',
current_gate: {
blockingReasonCode: 'review_case_draft',
nextActionCode: 'open_order_review',
},
};
const stabilized = stabilizeTaskObjects([oldTask], [nextTask]);
// 状态从 processing→needs_action 语义已变,必须替换成新引用。
expect(stabilized[0]).not.toBe(oldTask);
expect(stabilized[0].status_label).toBe('waiting_review');
expect(stabilized[0].available_actions).toEqual(['open_order_review', 'view_details']);
});
});
@@ -6,6 +6,7 @@
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
* 可由统一 work_items(order_task)合成兼容分组。
* 语义签名与任务稳定化:轮询返回相同业务状态时复用旧对象,避免按钮闪烁。
*/
import type {
@@ -19,8 +20,111 @@ import type {
WorkflowNodeStatus,
} from '@/features/chat/types/shipping.api.types';
/**
* 标准化动作码列表:去空白、小写、去重、字典序排序。
* 核心逻辑:后端返回顺序或临时字段变化时,确保前端动作集合稳定。
*
* @param actions - 原始动作码数组
* @returns 标准化后的动作码数组(唯一、已排序)
*/
export function normalizeActionCodes(actions: unknown[]): string[] {
return [...new Set(
(actions || [])
.map((item) => String(item || '').trim().toLowerCase())
.filter(Boolean),
)].sort();
}
/**
* 构建单个用户任务的语义签名:只包含决定按钮与展示的核心字段。
* 排除 updated_at / last_activity_at 等仅用于辅助提示的字段。
*
* @param task - 用户可见任务
* @returns 语义签名字符串;任务为 null 时返回空串
*/
export function buildTaskSemanticKey(
task: ConversationProcessingUserTask | null | undefined,
): string {
if (!task) return '';
return JSON.stringify({
taskNo: task.user_task_no,
group: task.group,
status: task.status_label,
runNo: task.run_no,
displayKind: task.display_kind,
fileCount: task.file_count,
title: task.title,
primaryAction: task.primary_action || null,
currentGate: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
.current_gate
? {
blockingReasonCode: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
.current_gate?.blockingReasonCode || null,
nextActionCode: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
.current_gate?.nextActionCode || null,
}
: null,
availableActions: normalizeActionCodes(task.available_actions || []),
canAppend: task.can_append ?? null,
});
}
/**
* 构建整个会话处理投影的语义签名:summary + 各分组任务签名。
*
* @param projection - 会话处理投影
* @returns 语义签名字符串;投影为 null 时返回空串
*/
export function buildProcessingSemanticKey(
projection: ConversationProcessingProjection | null | undefined,
): string {
if (!projection) return '';
return JSON.stringify({
summary: {
total_tasks: projection.summary?.total_tasks || 0,
total_files: projection.summary?.total_files || 0,
processing: projection.summary?.processing || 0,
needs_action: projection.summary?.needs_action || 0,
completed: projection.summary?.completed || 0,
history: projection.summary?.history || 0,
},
focused_task_no: projection.focused_task_no || null,
recent_task_no: projection.recent_task_no || null,
needs_action: (projection.needs_action || []).map(buildTaskSemanticKey),
processing: (projection.processing || []).map(buildTaskSemanticKey),
completed: (projection.completed || []).map(buildTaskSemanticKey),
history: (projection.history || []).map(buildTaskSemanticKey),
});
}
/**
* 按任务号复用旧对象:语义签名相同时返回旧引用,保证 Vue v-for 复用 DOM。
*
* @param previousTasks - 上一次渲染的任务列表
* @param nextRawTasks - 本次轮询生成的新任务列表(原始未稳定化)
* @returns 稳定化后的任务列表;语义未变的任务沿用旧引用
*/
export function stabilizeTaskObjects(
previousTasks: ConversationProcessingUserTask[],
nextRawTasks: ConversationProcessingUserTask[],
): ConversationProcessingUserTask[] {
const previousByTaskNo = new Map(
(previousTasks || []).map((task) => [String(task.user_task_no || ''), task]),
);
return (nextRawTasks || []).map((nextTask) => {
const previous = previousByTaskNo.get(String(nextTask.user_task_no || ''));
if (!previous) return nextTask;
if (buildTaskSemanticKey(previous) === buildTaskSemanticKey(nextTask)) {
return previous;
}
return nextTask;
});
}
/** 需要人工处理的生命周期集合。 */
const NEEDS_ACTION_LIFECYCLES = new Set([
'blocked',
'waiting_review',
'pending_review',
'manual_upload_pending',
'failed',
@@ -28,6 +132,16 @@ const NEEDS_ACTION_LIFECYCLES = new Set([
'upload_rpa_failed',
]);
const HUMAN_ACTION_CODES = new Set([
'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate',
'open_order_review', 'open_order_processing', 'enter_manual_review',
'open_inventory_source_review', 'confirm_inventory_source',
'open_inventory_match_review', 'rematch', 'match_inventory',
'open_shortage_review', 'upload_inventory_file', 'open_manual_upload',
'wait_manual_upload', 'retry', 'retry_parse', 'retry_failed_documents',
'retry_failed_attachments', 'open_profile_review',
]);
/** 处理中生命周期集合。 */
const PROCESSING_LIFECYCLES = new Set([
'queued',
@@ -288,7 +402,7 @@ export function classifyConversationProcessingGroup(
status: string | null | undefined,
options?: { hasBlockingGate?: boolean; needsCustomerConfirm?: boolean },
): ConversationProcessingTaskGroup {
if (options?.hasBlockingGate || options?.needsCustomerConfirm) return 'needs_action';
if (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';
@@ -297,7 +411,7 @@ export function classifyConversationProcessingGroup(
if (normalized === 'review_required' || normalized === 'partially_completed') {
return 'needs_action';
}
if (normalized === 'failed' || normalized === 'cancelled') return 'needs_action';
if (normalized === 'failed') return 'needs_action';
if (normalized === 'completed') return 'completed';
if (normalized === 'processing' || normalized === 'queued') return 'processing';
return 'processing';
@@ -431,10 +545,16 @@ export function projectConversationProcessingTasks(
const effectiveItems = uniqueDocuments.map((row) => row.source_item);
// 任务级分组/操作只由最近代表 Item 决定;旧 Run 仅贡献未受影响的 PDF,不得反向污染状态。
const statuses = [resolveItemDisplayStatus(primaryItem)];
const hasGate = Boolean(primaryItem.process_gate?.current_blocking_gate);
const primaryActions = Array.isArray(primaryItem.available_actions)
? primaryItem.available_actions
: [];
const hasHumanAction = primaryActions.some((value) => {
const code = String(value || '').trim().toLowerCase();
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
});
let group: ConversationProcessingTaskGroup = 'history';
for (const status of statuses) {
const g = classifyConversationProcessingGroup(status, { hasBlockingGate: hasGate });
const g = classifyConversationProcessingGroup(status, { needsCustomerConfirm: hasHumanAction });
if (g === 'needs_action') {
group = 'needs_action';
break;
@@ -523,12 +643,27 @@ export function groupConversationProcessingTasks(
options?: {
focusedTaskNo?: string | null;
recentTaskNo?: string | null;
/** 上一版投影(语义稳定化复用旧对象引用)。 */
previousProjection?: ConversationProcessingProjection | 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 previousTasks: ConversationProcessingUserTask[] = options?.previousProjection
? [
...(options.previousProjection.needs_action || []),
...(options.previousProjection.processing || []),
...(options.previousProjection.completed || []),
...(options.previousProjection.history || []),
]
: [];
const stabilized = stabilizeTaskObjects(previousTasks, tasks);
const needs_action_raw = stabilized.filter((t) => t.group === 'needs_action');
const processing_raw = stabilized.filter((t) => t.group === 'processing');
const completed_raw = stabilized.filter((t) => t.group === 'completed');
const history_raw = stabilized.filter((t) => t.group === 'history');
const needs_action = stabilizeTaskObjects(options?.previousProjection?.needs_action || [], needs_action_raw);
const processing = stabilizeTaskObjects(options?.previousProjection?.processing || [], processing_raw);
const completed = stabilizeTaskObjects(options?.previousProjection?.completed || [], completed_raw);
const history = stabilizeTaskObjects(options?.previousProjection?.history || [], history_raw);
const all = [...needs_action, ...processing, ...completed, ...history];
const summary: ConversationProcessingSummary = {
total_tasks: all.length,
@@ -572,14 +707,15 @@ export function mapShippingProcessingStatusToTaskGroup(
item: ShippingProcessingProjection,
): ConversationProcessingTaskGroup {
const status = String(item.status || '').trim().toLowerCase();
const gateAction = String(item.currentGate?.nextActionCode || '').trim();
const gateAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase();
const hasHumanAction = [gateAction, ...(item.availableActions || [])]
.map((value) => String(value || '').trim().toLowerCase())
.some((value) => HUMAN_ACTION_CODES.has(value) || value.startsWith('retry_failed_'));
if (
status === 'waiting_review'
|| status === 'blocked'
|| status === 'failed'
|| gateAction === 'open_order_review'
|| gateAction === 'retry_parse'
|| gateAction === 'retry_failed_documents'
|| hasHumanAction
) {
return 'needs_action';
}
@@ -615,19 +751,22 @@ export function mergeConversationProcessingFocusMetadata(
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
* 核心逻辑:work_items 非空时始终由 order_task 工作项合成任务列表;禁止优先 embedded
* (兄弟 OT 仅出现在 work_items,embedded 可能缺 sibling)。
* 语义稳定化:对比 previousProjection 的签名,复用未变的任务对象引用。
*
* @param workItems - unified.work_items
* @param embedded - unified.conversation_processing
* @param previousProjection - 上一版投影(用于任务对象稳定化)
* @returns 会话处理投影;无可用数据时 null
*/
export function resolveConversationProcessingFromUnified(
workItems: ShippingProcessingProjection[] | null | undefined,
embedded: ConversationProcessingProjection | null | undefined,
previousProjection?: ConversationProcessingProjection | null,
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
if (items.length > 0) {
return mergeConversationProcessingFocusMetadata(
projectConversationProcessingFromWorkItems(items),
projectConversationProcessingFromWorkItems(items, previousProjection),
embedded,
);
}
@@ -638,22 +777,22 @@ export function resolveConversationProcessingFromUnified(
/**
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
*
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组。
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组;
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
*
* @param workItems - 统一投影 work_items
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
* @returns 兼容投影;无 order_task 时返回 null
*/
export function projectConversationProcessingFromWorkItems(
workItems: ShippingProcessingProjection[] | null | undefined,
previousProjection?: ConversationProcessingProjection | null,
): 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[] = [];
const rawTasks: ConversationProcessingUserTask[] = [];
for (const item of orderTasks) {
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
@@ -661,6 +800,8 @@ export function projectConversationProcessingFromWorkItems(
const group = mapShippingProcessingStatusToTaskGroup(item);
const docCount = Number(item.sourceSummary?.documentCount || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
const normalizedActions = normalizeActionCodes(item.availableActions || []);
const gateNextAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase() || null;
const task: ConversationProcessingUserTask = {
user_task_no: taskNo,
user_task_authoritative: true,
@@ -670,22 +811,30 @@ export function projectConversationProcessingFromWorkItems(
group,
status_label: String(item.status || '') || null,
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
// [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] : [],
primary_action: item.currentGate?.nextActionCode || item.availableActions?.[0] || null,
available_actions: normalizedActions,
primary_action: gateNextAction || normalizedActions[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);
rawTasks.push(task);
}
const active = [...needs_action, ...processing, ...completed];
if (!active.length && !history.length) return null;
// 后端未返回 embedded 汇总时,仍按 OT 主 PDF ID 去重,禁止兄弟 OT 重复累计。
if (!rawTasks.length) return null;
const needs_action_raw: ConversationProcessingUserTask[] = [];
const processing_raw: ConversationProcessingUserTask[] = [];
const completed_raw: ConversationProcessingUserTask[] = [];
const history_raw: ConversationProcessingUserTask[] = [];
for (const task of rawTasks) {
if (task.group === 'needs_action') needs_action_raw.push(task);
else if (task.group === 'processing') processing_raw.push(task);
else if (task.group === 'completed') completed_raw.push(task);
else history_raw.push(task);
}
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))
@@ -694,6 +843,35 @@ export function projectConversationProcessingFromWorkItems(
const totalFiles = documentIds.size > 0
? documentIds.size
: active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
const stabilizedAll = stabilizeTaskObjects(
previousProjection
? [
...(previousProjection.needs_action || []),
...(previousProjection.processing || []),
...(previousProjection.completed || []),
...(previousProjection.history || []),
]
: [],
rawTasks,
);
const needs_action = stabilizeTaskObjects(
previousProjection?.needs_action || [],
stabilizedAll.filter((t) => t.group === 'needs_action'),
);
const processing = stabilizeTaskObjects(
previousProjection?.processing || [],
stabilizedAll.filter((t) => t.group === 'processing'),
);
const completed = stabilizeTaskObjects(
previousProjection?.completed || [],
stabilizedAll.filter((t) => t.group === 'completed'),
);
const history = stabilizeTaskObjects(
previousProjection?.history || [],
stabilizedAll.filter((t) => t.group === 'history'),
);
return {
summary: {
total_tasks: active.length,
@@ -4,7 +4,10 @@
* 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing;
* focus/viewed 写路径优先应用响应中的 work_items;
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;无活跃任务时停轮询。
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;
* 分层轮询:系统处理中 2s 轮询,待复核 30s 轮询;
* 区分 initialLoading / manualRefreshing / polling 三种 loading 态;
* 语义签名比较:业务状态未变化时不替换投影对象,防止按钮闪烁与 DOM 重建。
*/
import {
computed,
@@ -27,7 +30,10 @@ import type {
ConversationProcessingProjection,
ShippingProcessingProjection,
} from '../types/shipping.api.types';
import { resolveConversationProcessingFromUnified } from './conversationProcessingProjection';
import {
buildProcessingSemanticKey,
resolveConversationProcessingFromUnified,
} from './conversationProcessingProjection';
const FOREGROUND_POLL_MS = 2000;
const BACKGROUND_POLL_MS = 8000;
@@ -46,7 +52,14 @@ export type UseShippingNoticeWorkflowReturn = {
processing: Ref<ConversationProcessingProjection | null>;
/** 统一 ShippingProcessing work_items。 */
processingWorkItems: Ref<ShippingProcessingProjection[]>;
/** 兼容旧消费者:任何加载状态均为 true。 */
loading: Ref<boolean>;
/** 首次打开会话加载中(投影仍为空)。 */
initialLoading: Ref<boolean>;
/** 用户主动点击刷新或执行重试/重解析/取消等写操作后加载。 */
manualRefreshing: Ref<boolean>;
/** 后台静默轮询中(不显示 loading,不禁用按钮)。 */
polling: Ref<boolean>;
error: Ref<string | null>;
refresh: () => Promise<void>;
focusConversationTask: (taskNo: string) => Promise<void>;
@@ -67,12 +80,19 @@ function readOption<T>(source: MaybeRefOrGetter<T>): T {
}
/**
* 按页面可见性选择轮询间隔。
* 按页面可见性 + 业务状态选择轮询间隔。
* 分层策略:系统处理中 2s;待人工复核 30s;后台标签页 8s(若仍需轮询)。
*/
function resolvePollMs(): number {
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;
}
@@ -87,14 +107,16 @@ export function resolveProcessingPollBackoffMs(failureCount: number): number {
/**
* 判断是否应继续轮询统一 ShippingProcessing。
* 核心逻辑:processing / needs_action 有活跃项则继续。
* 核心逻辑:仅系统处理中(processing>0)时持续 2s 轮询;
* 待人工复核不触发后台轮询;全部完成/取消/历史时停止轮询。
*/
export function shouldContinueProcessingPolling(
processing?: ConversationProcessingProjection | null,
): boolean {
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;
const processingCount = Number(
processing?.summary?.processing || processing?.processing?.length || 0,
);
return processingCount > 0;
}
/**
@@ -109,8 +131,13 @@ export function useShippingNoticeWorkflow(
): UseShippingNoticeWorkflowReturn {
const processing = ref<ConversationProcessingProjection | null>(null);
const processingWorkItems = ref<ShippingProcessingProjection[]>([]);
const loading = ref(false);
const initialLoading = ref(false);
const manualRefreshing = ref(false);
const polling = ref(false);
const error = ref<string | null>(null);
const loading = computed(() => (
initialLoading.value || manualRefreshing.value || polling.value
));
let pollTimer: ReturnType<typeof setTimeout> | null = null;
let pollGeneration = 0;
@@ -119,6 +146,7 @@ export function useShippingNoticeWorkflow(
let inFlightRefresh: { conversationId: string; promise: Promise<void> } | null = null;
let failureCount = 0;
let pollingStopped = false;
let lastSemanticKey = '';
const normalizedConversationId = computed(() =>
String(readOption(options.conversationId) || '').trim(),
@@ -152,12 +180,21 @@ export function useShippingNoticeWorkflow(
/**
* 仅拉取统一 shipping-processing 投影。
* 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据;
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据。
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据;
* 语义签名相同则不替换 projection 对象,避免 DOM 重建与按钮闪烁。
*
* @param conversationId - 会话 ID
* @param mode - 请求模式:initial=首次加载 / manual=用户主动触发 / poll=后台轮询
* @returns Promise<void>;可恢复网络失败写入 error,不向页面抛出。
*/
async function executeRefresh(conversationId: string): Promise<void> {
async function executeRefresh(
conversationId: string,
mode: 'initial' | 'manual' | 'poll',
): Promise<void> {
const generation = ++requestGeneration;
loading.value = true;
if (mode === 'initial') initialLoading.value = true;
else if (mode === 'manual') manualRefreshing.value = true;
else polling.value = true;
const controller = createRequestController();
try {
// [STEP 1] 统一投影为唯一读源。
@@ -170,8 +207,19 @@ export function useShippingNoticeWorkflow(
const workItems = Array.isArray(unified?.work_items) ? unified.work_items : [];
const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined;
const prevProjection = processing.value;
const nextProjection = resolveConversationProcessingFromUnified(
workItems,
embedded,
prevProjection,
);
const nextSemanticKey = buildProcessingSemanticKey(nextProjection);
processingWorkItems.value = workItems;
processing.value = resolveConversationProcessingFromUnified(workItems, embedded);
if (nextSemanticKey !== lastSemanticKey) {
processing.value = nextProjection;
lastSemanticKey = nextSemanticKey;
}
error.value = null;
failureCount = 0;
} catch (reason) {
@@ -186,12 +234,17 @@ export function useShippingNoticeWorkflow(
: 'network_recoverable';
} finally {
if (requestController === controller) requestController = null;
if (generation === requestGeneration) loading.value = false;
if (generation === requestGeneration) {
if (mode === 'initial') initialLoading.value = false;
else if (mode === 'manual') manualRefreshing.value = false;
else polling.value = false;
}
}
}
/**
* 拉取统一进度;同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。
* 拉取统一进度(用户主动刷新模式:显示刷新图标旋转,不轮询)。
* 同一会话已有请求时复用该 Promise,避免首屏触发源互相取消重发。
*/
function refresh(): Promise<void> {
const conversationId = normalizedConversationId.value;
@@ -199,12 +252,15 @@ export function useShippingNoticeWorkflow(
processing.value = null;
processingWorkItems.value = [];
error.value = null;
lastSemanticKey = '';
return Promise.resolve();
}
if (inFlightRefresh?.conversationId === conversationId) {
return inFlightRefresh.promise;
}
const promise = executeRefresh(conversationId).finally(() => {
const isFirstLoad = processing.value === null && !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;
});
inFlightRefresh = { conversationId, promise };
@@ -213,7 +269,8 @@ export function useShippingNoticeWorkflow(
/**
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块。
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块;
* 每次回写后更新语义签名,避免下一轮轮询误判为「无变化」。
*/
function applyMutationProcessingResponse(response: {
processing?: ConversationProcessingProjection | null;
@@ -222,13 +279,25 @@ export function useShippingNoticeWorkflow(
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
if (workItems.length > 0) {
processingWorkItems.value = workItems as typeof processingWorkItems.value;
processing.value = resolveConversationProcessingFromUnified(
const nextProjection = resolveConversationProcessingFromUnified(
workItems as typeof processingWorkItems.value,
response.processing ?? null,
processing.value,
);
const nextKey = buildProcessingSemanticKey(nextProjection);
if (nextKey !== lastSemanticKey) {
processing.value = nextProjection;
lastSemanticKey = nextKey;
}
return;
}
if (response.processing) processing.value = response.processing;
if (response.processing) {
const nextKey = buildProcessingSemanticKey(response.processing);
if (nextKey !== lastSemanticKey) {
processing.value = response.processing;
lastSemanticKey = nextKey;
}
}
}
/**
@@ -257,6 +326,23 @@ export function useShippingNoticeWorkflow(
applyMutationProcessingResponse(response);
}
/**
* 执行后台静默轮询:不设置 manualRefreshing,使用 polling 态。
* 失败时复用 executeRefresh 的 failureCount 统计。
*/
async function runBackgroundPoll(conversationId: string): Promise<void> {
const existing = inFlightRefresh;
if (existing?.conversationId === conversationId) {
await existing.promise;
return;
}
const promise = executeRefresh(conversationId, 'poll').finally(() => {
if (inFlightRefresh?.promise === promise) inFlightRefresh = null;
});
inFlightRefresh = { conversationId, promise };
await promise;
}
/**
* 调度下一次轮询;失败时按退避间隔。
*/
@@ -264,7 +350,10 @@ export function useShippingNoticeWorkflow(
if (pollTimer) clearTimeout(pollTimer);
pollTimer = setTimeout(async () => {
if (generation !== pollGeneration || pollingStopped) return;
await refresh();
const conversationId = normalizedConversationId.value;
if (conversationId) {
await runBackgroundPoll(conversationId);
}
if (generation !== pollGeneration || pollingStopped) return;
if (!normalizedConversationId.value) return;
if (error.value) {
@@ -276,7 +365,7 @@ export function useShippingNoticeWorkflow(
}
const nextDelay = failureCount > 0
? resolveProcessingPollBackoffMs(failureCount)
: resolvePollMs();
: resolvePollMs(processing.value);
schedulePoll(generation, nextDelay);
}, delayMs);
}
@@ -300,7 +389,7 @@ export function useShippingNoticeWorkflow(
return;
}
if (!shouldContinueProcessingPolling(processing.value)) return;
schedulePoll(generation, resolvePollMs());
schedulePoll(generation, resolvePollMs(processing.value));
});
}
@@ -315,6 +404,7 @@ export function useShippingNoticeWorkflow(
processing.value = null;
processingWorkItems.value = [];
error.value = null;
lastSemanticKey = '';
}
restartPolling();
}, { immediate: true });
@@ -344,6 +434,9 @@ export function useShippingNoticeWorkflow(
processing,
processingWorkItems,
loading,
initialLoading,
manualRefreshing,
polling,
error,
refresh,
focusConversationTask,