feat(shipping-notice): 新增通用解析能力,优化性能并清理遗留废弃代码
This commit is contained in:
1 parent
935bf26fa6
commit
7cfd5d167e
230 files changed
+9337
-10989
No files matched your search
@@ -49,7 +49,7 @@ export function getPrimaryDocumentName(
|
||||
|
||||
/**
|
||||
* 汇总正式 OT 任务文件数(不含 order_intake)。
|
||||
* 核心逻辑:优先 summary.total_files;缺失时对 needs_action+processing+completed 的 file_count 求和。
|
||||
* 核心逻辑:优先 summary.total_files;缺失时仅对 status_groups 的活动状态求和。
|
||||
* @param projection - 会话 processing 投影
|
||||
*/
|
||||
export function resolveFormalTaskFileCount(
|
||||
@@ -60,10 +60,12 @@ export function resolveFormalTaskFileCount(
|
||||
if (Number.isFinite(fromSummary) && fromSummary >= 0 && projection.summary?.total_files != null) {
|
||||
return fromSummary;
|
||||
}
|
||||
const groups = projection.status_groups;
|
||||
const tasks = [
|
||||
...(projection.needs_action || []),
|
||||
...(projection.processing || []),
|
||||
...(projection.completed || []),
|
||||
...(groups?.failed || []),
|
||||
...(groups?.waiting_human || []),
|
||||
...(groups?.processing || []),
|
||||
...(groups?.completed || []),
|
||||
];
|
||||
return tasks.reduce((sum, task) => {
|
||||
const count = Number(task.file_count);
|
||||
@@ -83,10 +85,13 @@ export function resolveFormalTaskCount(
|
||||
if (Number.isFinite(fromSummary) && fromSummary >= 0 && projection.summary?.total_tasks != null) {
|
||||
return fromSummary;
|
||||
}
|
||||
const groups = projection.status_groups;
|
||||
return (
|
||||
(projection.needs_action?.length || 0)
|
||||
+ (projection.processing?.length || 0)
|
||||
+ (projection.completed?.length || 0)
|
||||
+ (projection.history?.length || 0)
|
||||
(groups?.failed.length || 0)
|
||||
+ (groups?.waiting_human.length || 0)
|
||||
+ (groups?.processing.length || 0)
|
||||
+ (groups?.completed.length || 0)
|
||||
+ (groups?.cancelled.length || 0)
|
||||
+ (groups?.archived.length || 0)
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,7 @@
|
||||
* ShippingProcessingProjection、合成 ShippingWorkflowItem)。
|
||||
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
|
||||
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
|
||||
* 可由统一 work_items(order_task)合成兼容分组。
|
||||
* 会话卡直接消费后端 status_groups,不从 work_items 二次聚合。
|
||||
* 语义签名与任务稳定化:轮询返回相同业务状态时复用旧对象,避免按钮闪烁。
|
||||
*/
|
||||
|
||||
@@ -16,7 +16,6 @@ import type {
|
||||
ConversationProcessingTaskGroup,
|
||||
ConversationProcessingUserTask,
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingFacts,
|
||||
ShippingProcessingLifecycleEntry,
|
||||
ShippingProcessingPrimaryAction,
|
||||
ShippingProcessingProjection,
|
||||
@@ -96,14 +95,21 @@ export function buildTaskSemanticKey(
|
||||
intakeNo: child.intakeNo,
|
||||
status: child.userStatus ?? child.status,
|
||||
stage: child.userStage ?? child.stage,
|
||||
runNo: child.runNo ?? null,
|
||||
caseNo: child.caseNo ?? null,
|
||||
uploadState: child.facts?.uploadState ?? null,
|
||||
filename: child.sourceSummary?.filename ?? null,
|
||||
reason: child.blockingReason?.code ?? child.sourceSummary?.failureReasonCode ?? null,
|
||||
// EML 父卡会缓存其叶子对象。子文件的入口与按钮同样是后端裁决,
|
||||
// 必须进入父卡语义签名;否则父卡引用被复用时会残留已撤销的入口。
|
||||
primaryAction: child.uiState
|
||||
? (child.uiState.primary_action?.code ?? null)
|
||||
: (child.primaryAction?.code ?? null),
|
||||
primaryAction: child.uiState?.primary_action
|
||||
? {
|
||||
code: child.uiState.primary_action.code,
|
||||
executionMode: child.uiState.primary_action.executionMode ?? null,
|
||||
targetSurface: child.uiState.primary_action.targetSurface ?? null,
|
||||
targetLifecycleStage: child.uiState.primary_action.targetLifecycleStage ?? null,
|
||||
}
|
||||
: null,
|
||||
lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
state: entry.state,
|
||||
@@ -121,11 +127,7 @@ export function buildTaskSemanticKey(
|
||||
title: task.title,
|
||||
// [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),
|
||||
primaryAction: task.uiState?.primary_action?.code ?? null,
|
||||
// 生命周期入口由后端独立裁决;入口被撤销/禁用时必须替换缓存对象,不能保留旧按钮。
|
||||
lifecycleEntries: task.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
@@ -147,16 +149,11 @@ export function buildTaskSemanticKey(
|
||||
?? null,
|
||||
nextActionCode: (task as ConversationProcessingUserTask & {
|
||||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||||
})
|
||||
.current_gate?.nextActionCode
|
||||
?? (task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? null,
|
||||
}).current_gate?.nextActionCode ?? null,
|
||||
}
|
||||
: null,
|
||||
availableActions: normalizeActionCodes(
|
||||
task.uiState
|
||||
? task.uiState.secondary_actions.filter((action) => action.enabled).map((action) => action.code)
|
||||
: (task.available_actions || []),
|
||||
task.uiState?.secondary_actions.filter((action) => action.enabled).map((action) => action.code) || [],
|
||||
),
|
||||
canAppend: task.can_append ?? null,
|
||||
aggregateChildren,
|
||||
@@ -173,6 +170,7 @@ export function buildProcessingSemanticKey(
|
||||
projection: ConversationProcessingProjection | null | undefined,
|
||||
): string {
|
||||
if (!projection) return '';
|
||||
const groups = projection.status_groups;
|
||||
return JSON.stringify({
|
||||
summary: {
|
||||
total_tasks: projection.summary?.total_tasks || 0,
|
||||
@@ -184,10 +182,14 @@ export function buildProcessingSemanticKey(
|
||||
},
|
||||
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),
|
||||
status_groups: {
|
||||
failed: (groups?.failed || []).map(buildTaskSemanticKey),
|
||||
waiting_human: (groups?.waiting_human || []).map(buildTaskSemanticKey),
|
||||
processing: (groups?.processing || []).map(buildTaskSemanticKey),
|
||||
completed: (groups?.completed || []).map(buildTaskSemanticKey),
|
||||
cancelled: (groups?.cancelled || []).map(buildTaskSemanticKey),
|
||||
archived: (groups?.archived || []).map(buildTaskSemanticKey),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -859,74 +861,6 @@ export function groupConversationProcessingTasks(
|
||||
* 核心逻辑:同 user_task_no / run_no 时,若兜底 file_count 更大,采用兜底的
|
||||
* display_kind / title / document_names / objects(文档子对象)。
|
||||
*/
|
||||
/**
|
||||
* 将统一 ShippingProcessing status/gate 映射为会话任务分组。
|
||||
* 核心逻辑:waiting_review/blocked/failed → needs_action;completed → completed;
|
||||
* cancelled → history;其余 → processing。
|
||||
*/
|
||||
export function mapShippingProcessingStatusToTaskGroup(
|
||||
item: ShippingProcessingProjection,
|
||||
): ConversationProcessingTaskGroup {
|
||||
const userGroup = String(item.userGroup || '').trim().toLowerCase();
|
||||
const status = normalizeLifecycleStatus(String(item.userStatus ?? item.status ?? '').trim());
|
||||
const childStatuses = (item.aggregateChildren || []).map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
|
||||
const childHasFailure = childStatuses.some((value) => value === 'failed');
|
||||
const childNeedsHuman = childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready');
|
||||
const childAllUploaded = childStatuses.length > 0
|
||||
&& childStatuses.every((value, index) => value === 'completed' && item.aggregateChildren?.[index]?.facts?.uploadState === 'succeeded');
|
||||
if (childHasFailure) return 'needs_action';
|
||||
if (childNeedsHuman) return 'needs_action';
|
||||
if (childAllUploaded) return 'completed';
|
||||
// 子项真实状态优先于父级 userGroup,避免 review_required/failed 被旧 processing 覆盖。
|
||||
if (status === 'failed' || status === 'waiting_review' || status === 'manual_upload_pending') return 'needs_action';
|
||||
if (userGroup === 'failed' || userGroup === 'waiting_human') return 'needs_action';
|
||||
if (userGroup === 'completed') return 'completed';
|
||||
if (userGroup === 'cancelled' || userGroup === 'archived') return 'history';
|
||||
if (userGroup === 'processing') return 'processing';
|
||||
const gateAction = String(item.primaryAction?.code ?? 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'
|
||||
|| status === 'waiting_human'
|
||||
|| status === 'retryable'
|
||||
|| hasHumanAction
|
||||
) {
|
||||
return 'needs_action';
|
||||
}
|
||||
if (status === 'completed') return 'completed';
|
||||
if (status === 'cancelled') return 'history';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 embedded conversation_processing 的焦点元数据合并到 work_items 派生投影。
|
||||
* 核心逻辑:任务列表必须来自 work_items;仅 focused_task_no / recent_task_no 可取自 embedded。
|
||||
*
|
||||
* @param derived - 由 projectConversationProcessingFromWorkItems 生成的投影
|
||||
* @param embedded - API 内嵌 conversation_processing(可选)
|
||||
* @returns 合并后的投影;derived 为空时回退 embedded
|
||||
*/
|
||||
export function mergeConversationProcessingFocusMetadata(
|
||||
derived: ConversationProcessingProjection | null,
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
): ConversationProcessingProjection | null {
|
||||
if (!derived) {
|
||||
return embedded && typeof embedded === 'object'
|
||||
? normalizeConversationProcessingProjection(embedded)
|
||||
: null;
|
||||
}
|
||||
if (!embedded || typeof embedded !== 'object') return derived;
|
||||
return {
|
||||
...derived,
|
||||
focused_task_no: embedded.focused_task_no ?? derived.focused_task_no ?? null,
|
||||
recent_task_no: embedded.recent_task_no ?? derived.recent_task_no ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
|
||||
* 核心逻辑:新版 embedded.status_groups 是后端已完成“当前文件代表项 → EML 容器”
|
||||
@@ -940,46 +874,15 @@ export function mergeConversationProcessingFocusMetadata(
|
||||
* @returns 会话处理投影;无可用数据时 null
|
||||
*/
|
||||
export function resolveConversationProcessingFromUnified(
|
||||
workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
_workItems: ShippingProcessingProjection[] | null | undefined,
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
previousProjection?: ConversationProcessingProjection | null,
|
||||
stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
|
||||
_previousProjection?: ConversationProcessingProjection | null,
|
||||
_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] conversation_processing.status_groups 与 lifecycle_nodes / ui_state
|
||||
// 同属后端一次裁决。即使顶层 work_items 非空,也不得前端二次聚合或用旧快照覆盖。
|
||||
if (embedded && typeof embedded === 'object' && embedded.status_groups) {
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
// [AUTHORITY] 新版接口已经由后端完成「状态 → EML → 业务文件」聚合。
|
||||
// 会话卡与批次中心必须直接使用该结果;前端从 work_items 重建只保留给旧响应兼容。
|
||||
// [TRANSITION] 只有统一投影里明确存在 order_task,才认为 OT 维度已经成形。
|
||||
// 仅 order_intake 存在时视为过渡阶段:
|
||||
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
|
||||
// 则延迟回退 embedded,保持 previousProjection 不变,避免闪烁;
|
||||
// - 否则仍走 embedded,但强制 normalize 成 waiting_review。
|
||||
const hasOrderTask = items.some((item) => (
|
||||
item.workItemType === 'order_task'
|
||||
|| (item.workItemType === 'order_intake' && item.sourceType === 'eml')
|
||||
));
|
||||
const convId = stabilizer?.conversationId;
|
||||
if (hasOrderTask) {
|
||||
stabilizer?.markSeen?.(convId);
|
||||
return mergeConversationProcessingFocusMetadata(
|
||||
projectConversationProcessingFromWorkItems(items, previousProjection),
|
||||
embedded,
|
||||
);
|
||||
}
|
||||
const sawOrderTaskRecently = stabilizer?.hasSeenOrderTaskBefore?.(convId) === true;
|
||||
if (sawOrderTaskRecently && previousProjection) {
|
||||
// 刚刚看到过 OT 但这轮响应暂缺 OT:不立即切回 embedded,保持上一轮投影。
|
||||
// 这样 2s 内轮询不会把右侧任务卡从 order_task 派生结果抖回旧 projection。
|
||||
return previousProjection;
|
||||
}
|
||||
if (embedded && typeof embedded === 'object') {
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
return null;
|
||||
// [AUTHORITY] 会话进度只能消费后端一次裁决的状态→EML→PDF树;从 work_items
|
||||
// 二次聚合会让前端重新承担业务状态裁决并重新引入旧四组的重复响应。
|
||||
if (!embedded || typeof embedded !== 'object' || !embedded.status_groups) return null;
|
||||
return normalizeConversationProcessingProjection(embedded);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -993,15 +896,11 @@ 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 }>;
|
||||
lifecycle_stage?: ConversationProcessingUserTask['uiState'] extends { lifecycleStage?: infer S } ? S : never;
|
||||
lifecycle_entries?: Array<Record<string, unknown>>;
|
||||
};
|
||||
@@ -1057,11 +956,11 @@ export function normalizeConversationProcessingProjection(
|
||||
};
|
||||
return {
|
||||
...state,
|
||||
blocking_reason: normalizeReason(state.blocking_reason ?? state.blockingReason),
|
||||
primary_action: normalizeAction(state.primary_action ?? state.primaryAction),
|
||||
blocking_reason: normalizeReason(state.blocking_reason),
|
||||
primary_action: normalizeAction(state.primary_action),
|
||||
// 次动作与主动作同属后端 ui_state 授权契约。若仅透传原始 snake_case,
|
||||
// 文件行点击会看不到导航目标并错误落入旧兼容分支。
|
||||
secondary_actions: (state.secondary_actions ?? state.secondaryActions ?? [])
|
||||
secondary_actions: (state.secondary_actions || [])
|
||||
.map((action) => {
|
||||
const normalized = normalizeAction(action);
|
||||
return normalized && 'code' in action && 'enabled' in action
|
||||
@@ -1069,23 +968,22 @@ export function normalizeConversationProcessingProjection(
|
||||
: null;
|
||||
})
|
||||
.filter((action): action is ShippingProcessingPrimaryAction & { code: string; enabled: boolean } => Boolean(action)),
|
||||
lifecycleStage: state.lifecycleStage ?? state.lifecycle_stage,
|
||||
lifecycleEntries: Array.isArray(state.lifecycleEntries)
|
||||
? state.lifecycleEntries.filter((entry) => Boolean(entry?.code && entry?.state && entry?.targetSurface))
|
||||
: (Array.isArray(state.lifecycle_entries)
|
||||
? state.lifecycle_entries.map((entry) => {
|
||||
const rawEntry = entry as { code?: unknown; state?: unknown; target_surface?: unknown; targetSurface?: unknown };
|
||||
return {
|
||||
code: String(rawEntry.code || '') as ShippingProcessingLifecycleEntry['code'],
|
||||
state: String(rawEntry.state || '') as ShippingProcessingLifecycleEntry['state'],
|
||||
targetSurface: String(rawEntry.targetSurface ?? rawEntry.target_surface ?? '') as ShippingProcessingLifecycleEntry['targetSurface'],
|
||||
};
|
||||
}).filter((entry) => Boolean(entry.code && entry.state && entry.targetSurface))
|
||||
: []),
|
||||
lifecycleStage: state.lifecycle_stage,
|
||||
lifecycleEntries: Array.isArray(state.lifecycle_entries)
|
||||
? state.lifecycle_entries.map((entry) => {
|
||||
const rawEntry = entry as { code?: unknown; state?: unknown; target_surface?: unknown };
|
||||
return {
|
||||
code: String(rawEntry.code || '') as ShippingProcessingLifecycleEntry['code'],
|
||||
state: String(rawEntry.state || '') as ShippingProcessingLifecycleEntry['state'],
|
||||
targetSurface: String(rawEntry.target_surface || '') as ShippingProcessingLifecycleEntry['targetSurface'],
|
||||
};
|
||||
}).filter((entry) => Boolean(entry.code && entry.state && entry.targetSurface))
|
||||
: [],
|
||||
};
|
||||
};
|
||||
const normalizeTask = (task: ConversationProcessingUserTask): ConversationProcessingUserTask => {
|
||||
const raw = task as ConversationProcessingUserTask & {
|
||||
user_task_no?: string | null;
|
||||
user_status?: ConversationProcessingUserTask['userStatus'];
|
||||
user_stage?: ConversationProcessingUserTask['userStage'];
|
||||
user_group?: ConversationProcessingUserTask['userGroup'];
|
||||
@@ -1094,407 +992,52 @@ export function normalizeConversationProcessingProjection(
|
||||
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 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 finalGroup: ConversationProcessingTaskGroup = backendAuthoritative
|
||||
? task.group
|
||||
: classifyConversationProcessingGroup(normalizedStatus || rawStatus, {
|
||||
needsCustomerConfirm: legacyHasHumanAction,
|
||||
});
|
||||
const aggregateChildren = Array.isArray(raw.aggregate_children)
|
||||
? raw.aggregate_children
|
||||
.map(normalizeShippingProcessingProjection)
|
||||
.filter((item): item is ShippingProcessingProjection => Boolean(item))
|
||||
: [];
|
||||
return {
|
||||
...task,
|
||||
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,
|
||||
status_label: task.status_label,
|
||||
userStatus: raw.user_status ?? null,
|
||||
userStage: raw.user_stage ?? null,
|
||||
userGroup: raw.user_group ?? null,
|
||||
blockingReason: raw.blocking_reason ?? null,
|
||||
primaryAction: null,
|
||||
primary_action: task.primary_action,
|
||||
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,
|
||||
(raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).ui_state,
|
||||
),
|
||||
group: finalGroup,
|
||||
group: task.group,
|
||||
};
|
||||
};
|
||||
const normalizedLegacyTasks = [
|
||||
...(projection.needs_action || []),
|
||||
...(projection.processing || []),
|
||||
...(projection.completed || []),
|
||||
...(projection.history || []),
|
||||
].map(normalizeTask);
|
||||
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');
|
||||
const normalizedGroups = {
|
||||
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),
|
||||
};
|
||||
const {
|
||||
needs_action: _legacyNeedsAction,
|
||||
processing: _legacyProcessing,
|
||||
completed: _legacyCompleted,
|
||||
history: _legacyHistory,
|
||||
...authoritativeProjection
|
||||
} = projection;
|
||||
return {
|
||||
...projection,
|
||||
// [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,
|
||||
lifecycle_nodes: projection.lifecycle_nodes || projection.four_stage_nodes || [],
|
||||
four_stage_nodes: projection.four_stage_nodes || projection.lifecycle_nodes || [],
|
||||
...authoritativeProjection,
|
||||
// [AUTHORITY] summary 与 status_groups 同属后端一次裁决。前端不得从局部 EML
|
||||
// 行重算任务/文件统计,也不得重新生成旧四组镜像。
|
||||
summary: projection.summary,
|
||||
status_groups: normalizedGroups,
|
||||
lifecycle_nodes: projection.lifecycle_nodes || [],
|
||||
unclassified_summary: projection.unclassified_summary || { count: 0 },
|
||||
ui_state: projection.ui_state || undefined,
|
||||
output_artifacts: projection.output_artifacts || [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 work_items 合成 ConversationProcessingProjection(order_task 与 EML order_intake)。
|
||||
*
|
||||
* 核心逻辑:order_task 与 EML order_intake 均进入状态区;非 EML intake 不入组;
|
||||
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
|
||||
*
|
||||
* @param workItems - 统一投影 work_items
|
||||
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
|
||||
* @returns 兼容投影;无可展示任务时返回 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'
|
||||
|| (row.workItemType === 'order_intake' && row.sourceType === 'eml')
|
||||
));
|
||||
if (!orderTasks.length) return null;
|
||||
|
||||
const rawTaskEntries: Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }> = [];
|
||||
|
||||
for (const item of orderTasks) {
|
||||
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
|
||||
if (!taskNo) continue;
|
||||
const group = mapShippingProcessingStatusToTaskGroup(item);
|
||||
// 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;
|
||||
const userBlocking: ConversationProcessingUserTask['blockingReason'] = (item.blockingReason && typeof item.blockingReason === 'object')
|
||||
? {
|
||||
code: item.blockingReason.code,
|
||||
i18nKey: (item.blockingReason as { i18nKey?: string | null }).i18nKey
|
||||
?? (item.blockingReason as { i18n_key?: string | null }).i18n_key
|
||||
?? undefined,
|
||||
details: (item.blockingReason as { details?: Record<string, unknown> }).details,
|
||||
} satisfies ShippingProcessingBlockingReason
|
||||
: null;
|
||||
const userPrimaryAction: ConversationProcessingUserTask['primaryAction'] = item.primaryAction
|
||||
? {
|
||||
code: item.primaryAction.code,
|
||||
i18nKey: (item.primaryAction as { i18nKey?: string | null }).i18nKey
|
||||
?? (item.primaryAction as { i18n_key?: string | null }).i18n_key
|
||||
?? undefined,
|
||||
parameters: (item.primaryAction as { parameters?: Record<string, unknown> }).parameters,
|
||||
} satisfies ShippingProcessingPrimaryAction
|
||||
: null;
|
||||
const userFacts: ConversationProcessingUserTask['facts'] = item.facts
|
||||
? {
|
||||
inventorySourceStatus: (item.facts as { inventorySourceStatus?: string | null }).inventorySourceStatus ?? undefined,
|
||||
candidateSourceCodes: (item.facts as { candidateSourceCodes?: string[] }).candidateSourceCodes ?? [],
|
||||
preparedSourceCodes: (item.facts as { preparedSourceCodes?: string[] }).preparedSourceCodes ?? [],
|
||||
pendingSourceCodes: (item.facts as { pendingSourceCodes?: string[] }).pendingSourceCodes ?? [],
|
||||
lineResolutions: (item.facts as { lineResolutions?: Record<string, unknown>[] }).lineResolutions ?? undefined,
|
||||
exportState: (item.facts as { exportState?: string }).exportState ?? undefined,
|
||||
uploadState: (item.facts as { uploadState?: string }).uploadState ?? undefined,
|
||||
switchState: (item.facts as { switchState?: string }).switchState ?? undefined,
|
||||
forcedMatchSourceCode: (item.facts as { forcedMatchSourceCode?: string | null }).forcedMatchSourceCode ?? undefined,
|
||||
} satisfies ShippingProcessingFacts
|
||||
: undefined;
|
||||
const task: ConversationProcessingUserTask = {
|
||||
user_task_no: taskNo,
|
||||
user_task_authoritative: true,
|
||||
title: filename || null,
|
||||
display_kind: docCount > 1 ? 'multi_document_task' : 'single_document_task',
|
||||
document_names: leafNames.length ? leafNames : (isEmlContainer ? [] : (filename ? [filename] : [])),
|
||||
group,
|
||||
status_label: effectiveStatus,
|
||||
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,
|
||||
primary_action: gateNextAction || normalizedActions[0] || null,
|
||||
userStatus: item.userStatus ?? null,
|
||||
userStage: item.userStage ?? null,
|
||||
blockingReason: userBlocking,
|
||||
primaryAction: userPrimaryAction,
|
||||
facts: userFacts,
|
||||
userGroup: item.userGroup ?? null,
|
||||
userCurrentGateCode: item.userCurrentGateCode ?? null,
|
||||
legacyStatus: item.legacyStatus ?? null,
|
||||
legacyStage: item.legacyStage ?? null,
|
||||
aggregateSummary: item.aggregateSummary ?? null,
|
||||
aggregateChildren: item.aggregateChildren ?? [],
|
||||
};
|
||||
rawTaskEntries.push({ task, item });
|
||||
}
|
||||
|
||||
const rawTasks: ConversationProcessingUserTask[] = [];
|
||||
const emlGroups = new Map<string, Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }>>();
|
||||
for (const entry of rawTaskEntries) {
|
||||
if (entry.item.sourceType !== 'eml' || !entry.item.intakeNo) {
|
||||
rawTasks.push(entry.task);
|
||||
continue;
|
||||
}
|
||||
const key = String(entry.item.intakeNo).trim();
|
||||
const group = emlGroups.get(key) || [];
|
||||
group.push(entry);
|
||||
emlGroups.set(key, group);
|
||||
}
|
||||
for (const [intakeNo, entries] of emlGroups) {
|
||||
if (entries.length === 1) {
|
||||
rawTasks.push({
|
||||
...entries[0]!.task,
|
||||
aggregateChildren: entries[0]!.task.aggregateChildren?.length
|
||||
? entries[0]!.task.aggregateChildren
|
||||
: entries[0]!.item.aggregateChildren || [],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const completed = entries.filter(({ item }) => String(item.userStatus ?? item.status).toLowerCase() === 'completed').length;
|
||||
const failed = entries.filter(({ item }) => ['failed', 'retryable'].includes(String(item.userStatus ?? item.status).toLowerCase())).length;
|
||||
const needsAction = entries.filter(({ task }) => task.group === 'needs_action').length;
|
||||
const processing = entries.filter(({ task }) => task.group === 'processing').length;
|
||||
const stages = [...new Set(entries.flatMap(({ item }) => [item.userStage, item.stage].filter(Boolean).map(String)))];
|
||||
const reasonCodes = [...new Set(entries.flatMap(({ item }) => [
|
||||
item.blockingReason?.code,
|
||||
item.sourceSummary?.failureReasonCode,
|
||||
].filter(Boolean).map(String)))];
|
||||
const entryGroups = entries.map(({ task, item }) => {
|
||||
const children = item.aggregateChildren || [];
|
||||
const childStatuses = children.map((child) => normalizeLifecycleStatus(String(child.userStatus ?? child.status ?? '').trim()));
|
||||
if (childStatuses.some((value) => value === 'failed')) return 'failed';
|
||||
if (childStatuses.some((value) => value === 'waiting_review' || value === 'manual_upload_pending' || value === 'candidate_ready')) return 'waiting_human';
|
||||
if (childStatuses.length > 0 && childStatuses.every((value, index) => value === 'completed' && children[index]?.facts?.uploadState === 'succeeded')) return 'completed';
|
||||
const explicit = String(item.userGroup || '').trim().toLowerCase();
|
||||
if (explicit) return explicit;
|
||||
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
|
||||
if (status === 'failed' || status === 'retryable') return 'failed';
|
||||
if (task.group === 'needs_action') return 'waiting_human';
|
||||
if (task.group === 'completed' && status === 'completed') return 'completed';
|
||||
if (task.group === 'history') return status === 'cancelled' ? 'cancelled' : 'archived';
|
||||
return 'processing';
|
||||
});
|
||||
const aggregateUserGroup = entryGroups.includes('failed')
|
||||
? 'failed'
|
||||
: entryGroups.includes('waiting_human')
|
||||
? 'waiting_human'
|
||||
: entryGroups.includes('processing')
|
||||
? 'processing'
|
||||
: entryGroups.includes('completed') && entryGroups.every((value) => value === 'completed')
|
||||
? 'completed'
|
||||
: entryGroups.includes('cancelled')
|
||||
? 'cancelled'
|
||||
: entryGroups.includes('archived')
|
||||
? 'archived'
|
||||
: 'processing';
|
||||
const group = aggregateUserGroup === 'failed' || aggregateUserGroup === 'waiting_human'
|
||||
? 'needs_action'
|
||||
: aggregateUserGroup === 'completed'
|
||||
? 'completed'
|
||||
: aggregateUserGroup === 'cancelled' || aggregateUserGroup === 'archived'
|
||||
? 'history'
|
||||
: 'processing';
|
||||
const representative = entries[0]!.task;
|
||||
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}`,
|
||||
display_kind: fileCount > 1 ? 'multi_document_task' : representative.display_kind,
|
||||
document_names: documentNames,
|
||||
file_count: fileCount,
|
||||
group,
|
||||
available_actions: [...new Set(entries.flatMap(({ task }) => task.available_actions || []))].sort(),
|
||||
aggregateSummary: {
|
||||
intakeNo,
|
||||
total: entries.length,
|
||||
completed,
|
||||
processing,
|
||||
needsAction,
|
||||
failed,
|
||||
stages,
|
||||
reasonCodes,
|
||||
},
|
||||
aggregateChildren,
|
||||
userGroup: aggregateUserGroup as ConversationProcessingUserTask['userGroup'],
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
// 统计口径与卡片完全一致:递归叶子业务文件,排除 EML 容器。
|
||||
const totalFiles = businessFileKeys(orderTasks).length || 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'),
|
||||
);
|
||||
|
||||
const status_groups = {
|
||||
failed: stabilizedAll.filter((task) => task.userGroup === 'failed'),
|
||||
waiting_human: stabilizedAll.filter((task) => task.userGroup === 'waiting_human'),
|
||||
processing: stabilizedAll.filter((task) => task.userGroup === 'processing'),
|
||||
completed: stabilizedAll.filter((task) => task.userGroup === 'completed'),
|
||||
cancelled: stabilizedAll.filter((task) => task.userGroup === 'cancelled'),
|
||||
archived: stabilizedAll.filter((task) => task.userGroup === 'archived'),
|
||||
};
|
||||
|
||||
return {
|
||||
summary: {
|
||||
total_tasks: active.length,
|
||||
total_files: totalFiles,
|
||||
processing: processing.length,
|
||||
needs_action: needs_action.length,
|
||||
completed: completed.length,
|
||||
history: history.length,
|
||||
},
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action,
|
||||
processing,
|
||||
completed,
|
||||
history,
|
||||
status_groups,
|
||||
};
|
||||
}
|
||||
@@ -82,7 +82,7 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
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!.availableActions).toEqual(['resolve_field_conflicts', 'view_details']);
|
||||
expect(normalized!.uiState).toMatchObject({
|
||||
status: 'waiting_human',
|
||||
stage: 'order_review',
|
||||
@@ -108,6 +108,35 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('保留后端五阶段生命周期入口,包括 freight_upload', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'OT-LIFECYCLE-5',
|
||||
work_item_type: 'order_task',
|
||||
status: 'waiting_review',
|
||||
stage: 'freight_uploading',
|
||||
ui_state: {
|
||||
status: 'waiting_human',
|
||||
stage: 'freight_uploading',
|
||||
lifecycle_stage: 'freight_upload',
|
||||
lifecycle_entries: [
|
||||
{ code: 'intake_parse', state: 'available', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'order_review', state: 'available', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'available', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'current', target_surface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', target_surface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(normalized?.uiState?.lifecycleEntries).toEqual([
|
||||
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'freight_upload', state: 'current', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
|
||||
]);
|
||||
});
|
||||
|
||||
it('normalizes structured inventory candidate facts', () => {
|
||||
const projection = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'SN-001',
|
||||
|
||||
@@ -25,25 +25,23 @@ import type {
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
/** 后端可裁决并透传到订单生命周期工作台的阶段;前端不根据本地状态补造入口。 */
|
||||
const lifecycleStages = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
|
||||
const lifecycleStages = ['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'] as const;
|
||||
|
||||
/**
|
||||
* 读取原始对象上的字符串字段(兼容 snake / camel)。
|
||||
*/
|
||||
function readString(raw: Record<string, unknown>, snake: string, camel: string): string {
|
||||
const value = raw[snake] ?? raw[camel];
|
||||
/** 读取后端正式 snake_case DTO 的字符串字段。 */
|
||||
function readString(raw: Record<string, unknown>, snake: string, _removedLegacyCamel?: string): string {
|
||||
const value = raw[snake];
|
||||
return value == null ? '' : String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取可空字符串。
|
||||
* 读取后端正式 snake_case DTO 的可空字符串。
|
||||
*/
|
||||
function readNullableString(
|
||||
raw: Record<string, unknown>,
|
||||
snake: string,
|
||||
camel: string,
|
||||
_removedLegacyCamel?: string,
|
||||
): string | null {
|
||||
const value = raw[snake] ?? raw[camel];
|
||||
const value = raw[snake];
|
||||
if (value == null || value === '') return null;
|
||||
return String(value);
|
||||
}
|
||||
@@ -118,7 +116,7 @@ function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
|
||||
details:
|
||||
typeof item.details === 'object' && item.details != null
|
||||
? (item.details as Record<string, unknown>)
|
||||
@@ -136,23 +134,23 @@ function normalizePrimaryAction(raw: unknown): ShippingProcessingPrimaryAction |
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : null,
|
||||
parameters:
|
||||
typeof item.parameters === 'object' && item.parameters != null
|
||||
? (item.parameters as Record<string, unknown>)
|
||||
: {},
|
||||
executionMode: item.execution_mode === 'navigate' || item.executionMode === 'navigate'
|
||||
executionMode: item.execution_mode === 'navigate'
|
||||
? 'navigate'
|
||||
: item.execution_mode === 'execute' || item.executionMode === 'execute'
|
||||
: item.execution_mode === 'execute'
|
||||
? 'execute'
|
||||
: undefined,
|
||||
targetSurface: item.target_surface === 'order_lifecycle_workbench' || item.targetSurface === 'order_lifecycle_workbench'
|
||||
targetSurface: item.target_surface === 'order_lifecycle_workbench'
|
||||
? 'order_lifecycle_workbench'
|
||||
: null,
|
||||
targetLifecycleStage: lifecycleStages.includes(
|
||||
String(item.target_lifecycle_stage ?? item.targetLifecycleStage ?? '') as typeof lifecycleStages[number],
|
||||
String(item.target_lifecycle_stage ?? '') as typeof lifecycleStages[number],
|
||||
)
|
||||
? String(item.target_lifecycle_stage ?? item.targetLifecycleStage) as ShippingProcessingPrimaryAction['targetLifecycleStage']
|
||||
? String(item.target_lifecycle_stage) as ShippingProcessingPrimaryAction['targetLifecycleStage']
|
||||
: null,
|
||||
};
|
||||
}
|
||||
@@ -165,10 +163,10 @@ function normalizeLifecycleEntries(raw: unknown): NonNullable<ConversationProces
|
||||
.map((item) => ({
|
||||
code: String(item.code ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['code'],
|
||||
state: String(item.state ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['state'],
|
||||
targetSurface: String(item.target_surface ?? item.targetSurface ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['targetSurface'],
|
||||
targetSurface: String(item.target_surface ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['targetSurface'],
|
||||
disabledReasonKey: item.disabled_reason_key != null
|
||||
? String(item.disabled_reason_key)
|
||||
: item.disabledReasonKey != null ? String(item.disabledReasonKey) : null,
|
||||
: null,
|
||||
}))
|
||||
.filter((item) => lifecycleStages.includes(item.code as typeof lifecycleStages[number])
|
||||
&& ['available', 'current', 'unavailable'].includes(item.state)
|
||||
@@ -373,9 +371,13 @@ export function normalizeShippingProcessingProjection(
|
||||
const children = Array.isArray(childrenRaw)
|
||||
? childrenRaw.map(normalizeChildTask).filter((row): row is ShippingOrderTaskSummary => Boolean(row))
|
||||
: [];
|
||||
const actionsRaw = item.available_actions ?? item.availableActions;
|
||||
const availableActions = Array.isArray(actionsRaw)
|
||||
? actionsRaw.map((action) => String(action || '').trim()).filter(Boolean)
|
||||
// ui_state 是处理进度唯一的用户态/动作合同。旧顶层动作字段已下线,
|
||||
// 客户端只能由该合同派生本地展示索引,不能读取或补造历史 available_actions。
|
||||
const uiState = normalizeProcessingUiState(item.ui_state);
|
||||
const availableActions = uiState
|
||||
? [uiState.primary_action, ...uiState.secondary_actions]
|
||||
.map((action) => String(action?.code || '').trim())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const stageNodesRaw = item.stage_nodes ?? item.stageNodes;
|
||||
const stageNodes = Array.isArray(stageNodesRaw)
|
||||
@@ -428,14 +430,12 @@ export function normalizeShippingProcessingProjection(
|
||||
userStage: readNullableString(item, 'user_stage', 'userStage') as ShippingProcessingProjection['userStage'],
|
||||
userCurrentGateCode: readNullableString(item, 'user_current_gate_code', 'userCurrentGateCode'),
|
||||
blockingReason: normalizeBlockingReason(item.blocking_reason ?? item.blockingReason),
|
||||
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
|
||||
uiState: normalizeProcessingUiState(item.ui_state ?? item.uiState),
|
||||
primaryAction: uiState?.primary_action ?? null,
|
||||
uiState,
|
||||
facts: normalizeFacts(item.facts),
|
||||
userGroup: readNullableString(item, 'user_group', 'userGroup') as ShippingProcessingProjection['userGroup'],
|
||||
aggregateSummary: normalizeAggregateSummary(item.aggregate_summary ?? item.aggregateSummary),
|
||||
aggregateChildren: aggregateChildren?.length ? aggregateChildren : undefined,
|
||||
legacyStatus: readNullableString(item, 'legacy_status', 'legacyStatus'),
|
||||
legacyStage: readNullableString(item, 'legacy_stage', 'legacyStage'),
|
||||
hasFormalOt:
|
||||
(item.has_formal_ot as boolean | undefined) == null ? false : Boolean(item.has_formal_ot),
|
||||
inventoryPreparation: normalizeInventoryPreparation(
|
||||
@@ -453,11 +453,11 @@ function normalizeProcessGateSummary(raw: unknown): ShippingProcessGateUserSumma
|
||||
: null;
|
||||
}
|
||||
|
||||
/** 规范化单项后端 UI 裁决;缺失时返回 undefined 以保留旧响应兼容。 */
|
||||
/** 规范化单项后端 UI 裁决;缺失时不展示动作,禁止从旧顶层字段回退。 */
|
||||
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 secondaryRaw = state.secondary_actions;
|
||||
const secondaryActions = Array.isArray(secondaryRaw)
|
||||
? secondaryRaw
|
||||
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
|
||||
@@ -470,10 +470,10 @@ function normalizeProcessingUiState(raw: unknown): ShippingProcessingProjection[
|
||||
return {
|
||||
status: (readString(state, 'status', 'status') || 'running') as NonNullable<ShippingProcessingProjection['userStatus']>,
|
||||
stage: readString(state, 'stage', 'stage'),
|
||||
lifecycleStage: readString(state, 'lifecycle_stage', 'lifecycleStage') as ConversationProcessingUiState['lifecycleStage'],
|
||||
lifecycleEntries: normalizeLifecycleEntries(state.lifecycle_entries ?? state.lifecycleEntries),
|
||||
blocking_reason: normalizeBlockingReason(state.blocking_reason ?? state.blockingReason),
|
||||
primary_action: normalizePrimaryAction(state.primary_action ?? state.primaryAction),
|
||||
lifecycleStage: readString(state, 'lifecycle_stage') as ConversationProcessingUiState['lifecycleStage'],
|
||||
lifecycleEntries: normalizeLifecycleEntries(state.lifecycle_entries),
|
||||
blocking_reason: normalizeBlockingReason(state.blocking_reason),
|
||||
primary_action: normalizePrimaryAction(state.primary_action),
|
||||
secondary_actions: secondaryActions,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface ShippingConversationContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; display_query?: string },
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,7 @@ async function downloadWorkspaceShippingFile(url: string, fallbackName: string):
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
|
||||
/** 批次 ZIP 下载只转发后端归档响应;选择和授权均不在前端重算。 */
|
||||
/** 多任务 ZIP 下载只转发后端归档响应;选择和授权均不在前端重算。 */
|
||||
export const downloadWorkspaceShippingExportArchive = (payload: {
|
||||
batch_no?: string;
|
||||
task_nos?: string[];
|
||||
}) => requestShippingExportArchive(payload);
|
||||
@@ -34,12 +34,10 @@ export function resolveShippingChatTurn(
|
||||
/**
|
||||
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
|
||||
*/
|
||||
export function buildShippingTurnRefs(taskNo: string, batchNo?: string): Record<string, string> {
|
||||
export function buildShippingTurnRefs(taskNo: string): Record<string, string> {
|
||||
const refs: Record<string, string> = {};
|
||||
const task = String(taskNo || '').trim().toUpperCase();
|
||||
const batch = String(batchNo || '').trim();
|
||||
if (task) refs.task_no = task;
|
||||
if (batch) refs.batch_no = batch;
|
||||
return refs;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/shipping/shippingUploadPrompt.ts
|
||||
* 用途:通知上传后提示语构建、文件格式识别与临时库存声明判断。
|
||||
* 依赖:无;useChatShippingUploadHandler 在上传成功后调用。
|
||||
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify 完整动态订单抽取。
|
||||
* 逻辑:按提交结果生成 follow-up 提示;通知进入 Intake 后触发完整动态订单抽取。
|
||||
*/
|
||||
import i18n from '@/i18n';
|
||||
|
||||
@@ -10,17 +10,12 @@ import i18n from '@/i18n';
|
||||
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
|
||||
*/
|
||||
/**
|
||||
* 根据通知建批 API 响应生成发给 Dify 的 follow-up 提示语(触发完整订单抽取链)。
|
||||
* 根据通知提交 API 响应生成发给 Dify 的 follow-up 提示语(触发完整订单抽取链)。
|
||||
*/
|
||||
export function buildShippingNoticeUploadPrompt(
|
||||
result: Record<string, unknown> | null | undefined,
|
||||
options?: { fileCount?: number; fileName?: string },
|
||||
): string {
|
||||
const batchNo = String(
|
||||
(result?.batch_no as string | undefined)
|
||||
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|
||||
|| '',
|
||||
).trim();
|
||||
const taskId = String(
|
||||
((result?.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|
||||
|| (result?.task_id as string | undefined)
|
||||
@@ -39,9 +34,6 @@ export function buildShippingNoticeUploadPrompt(
|
||||
? String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelMulti', { fileCount }))
|
||||
: String(i18n.global.t('chat.shippingNoticePrompt.notice.fileLabelDefault')));
|
||||
const parts = [String(i18n.global.t('chat.shippingNoticePrompt.notice.uploadedPrefix', { fileLabel }))];
|
||||
if (batchNo) {
|
||||
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.batchLabel', { batchNo })));
|
||||
}
|
||||
if (taskId) {
|
||||
parts.push(String(i18n.global.t('chat.shippingNoticePrompt.notice.taskLabel', { taskId })));
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ const createContext = (
|
||||
isThinking: ref(false),
|
||||
currentAgentId: computed(() => 42),
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
getActiveShippingBatchNo: () => 'BATCH-001',
|
||||
messages: ref([]),
|
||||
sendShippingMenuMessage: vi.fn(async () => undefined),
|
||||
openShippingInventoryPicker: vi.fn((_taskId?: string) => true),
|
||||
|
||||
@@ -14,6 +14,7 @@ export interface ShippingMenuHandlerContext {
|
||||
getActiveShippingTaskId: () => string;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
openShippingInventoryPicker: (taskId?: string) => boolean;
|
||||
openShippingNoticePicker: (taskId?: string) => boolean;
|
||||
openShippingCustomerDialog: (taskId: string) => Promise<void>;
|
||||
executeShippingDecision: (
|
||||
@@ -76,6 +77,10 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
ctx.openShippingNoticePicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id === 'upload_inventory_file') {
|
||||
ctx.openShippingInventoryPicker(resolveTaskId());
|
||||
return;
|
||||
}
|
||||
if (action.id && [
|
||||
'freeze_order', 'match_inventory', 'rematch',
|
||||
'generate_excel', 'retry_upload', 'mark_manual_uploaded', 'reparse_inventory',
|
||||
|
||||
@@ -21,18 +21,18 @@ describe('useChatShippingRefresh', () => {
|
||||
getWorkspaceShippingTaskUiState.mockReset();
|
||||
});
|
||||
|
||||
it('prefers current batch focus task over other explicit anchors', () => {
|
||||
it('prefers active task over message, resolved and query anchors', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: 'sn-batch-001',
|
||||
activeTaskId: 'sn-active-001',
|
||||
messageTaskId: 'sn-message-001',
|
||||
resolvedTaskId: 'sn-resolved-001',
|
||||
queryTaskId: 'sn-query-001',
|
||||
})).toBe('SN-BATCH-001');
|
||||
})).toBe('SN-ACTIVE-001');
|
||||
});
|
||||
|
||||
it('returns empty string when no explicit task anchor is available', () => {
|
||||
expect(resolvePreferredShippingTaskId({
|
||||
batchTaskId: '',
|
||||
activeTaskId: '',
|
||||
messageTaskId: '',
|
||||
resolvedTaskId: '',
|
||||
queryTaskId: '',
|
||||
@@ -42,7 +42,6 @@ describe('useChatShippingRefresh', () => {
|
||||
it('syncs ui_state for notifications without attaching chat action buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-FOCUS-B',
|
||||
batch_no: 'SB-FOCUS-001',
|
||||
checkpoint: 'ready_export',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
@@ -70,7 +69,7 @@ describe('useChatShippingRefresh', () => {
|
||||
const messages = ref([
|
||||
{
|
||||
role: 'assistant' as const,
|
||||
content: '请继续处理当前批次',
|
||||
content: '请继续处理当前任务',
|
||||
shipping_actions: [
|
||||
{
|
||||
id: 'old-action',
|
||||
@@ -89,7 +88,7 @@ describe('useChatShippingRefresh', () => {
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId,
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-FOCUS-B',
|
||||
getActiveShippingTaskId: () => 'SN-FOCUS-B',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
@@ -103,7 +102,6 @@ describe('useChatShippingRefresh', () => {
|
||||
it('clears legacy shipping_actions even when api returns action_buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-SOURCE-001',
|
||||
batch_no: 'SB-SOURCE-001',
|
||||
checkpoint: 'ready_export',
|
||||
match_status: 'matched',
|
||||
review_status: null,
|
||||
@@ -158,7 +156,7 @@ describe('useChatShippingRefresh', () => {
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId: ref('SN-SOURCE-001'),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => 'SN-SOURCE-001',
|
||||
getActiveShippingTaskId: () => 'SN-SOURCE-001',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
@@ -181,7 +179,7 @@ describe('useChatShippingRefresh', () => {
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveBatchTaskId: () => '',
|
||||
getActiveShippingTaskId: () => '',
|
||||
});
|
||||
|
||||
await refreshShippingActions();
|
||||
|
||||
@@ -19,25 +19,27 @@ export interface ShippingRefreshContext {
|
||||
isThinking: Ref<boolean>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
getActiveBatchTaskId: () => string;
|
||||
getActiveShippingTaskId: () => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前聊天页最可靠的发货任务编号。
|
||||
*
|
||||
* 核心逻辑:优先使用批次当前焦点任务,其次才回退到消息内嵌任务号、已解析状态和路由参数;
|
||||
* 核心逻辑:优先使用消息内嵌任务号,再回退到已解析状态和路由参数;
|
||||
* 禁止再按 conversation 标题“猜”一票,避免多票会话把状态挂错任务。
|
||||
* @param params - 当前聊天页中可用的任务定位线索
|
||||
* @returns 可信的任务编号;无法明确定位时返回空字符串
|
||||
*/
|
||||
export function resolvePreferredShippingTaskId(params: {
|
||||
activeTaskId?: string | null;
|
||||
batchTaskId?: string | null;
|
||||
messageTaskId?: string | null;
|
||||
resolvedTaskId?: string | null;
|
||||
queryTaskId?: string | null;
|
||||
}) {
|
||||
return String(
|
||||
params.batchTaskId
|
||||
params.activeTaskId
|
||||
|| params.batchTaskId
|
||||
|| params.messageTaskId
|
||||
|| params.resolvedTaskId
|
||||
|| params.queryTaskId
|
||||
@@ -71,7 +73,7 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
const msgs = ctx.messages.value;
|
||||
if (!msgs.length) return;
|
||||
const taskId = resolvePreferredShippingTaskId({
|
||||
batchTaskId: ctx.getActiveBatchTaskId(),
|
||||
activeTaskId: ctx.getActiveShippingTaskId(),
|
||||
messageTaskId: findLatestShippingTaskId(msgs),
|
||||
resolvedTaskId: ctx.resolvedShippingTaskId.value,
|
||||
queryTaskId: ctx.shippingTaskIdFromQuery.value,
|
||||
|
||||
@@ -19,7 +19,6 @@ const createContext = (
|
||||
attachments: ref([]),
|
||||
shippingAutoFlowRequested: ref(true),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
getActiveShippingBatchNo: () => '',
|
||||
currentAgentId: computed(() => 1),
|
||||
selectedKb: ref(''),
|
||||
attachmentPolicy: computed(() => ({ anyEnabled: true })),
|
||||
@@ -47,7 +46,6 @@ const createContext = (
|
||||
getParsedIntakeNos: () => [],
|
||||
startOrderExtractionRun: vi.fn(async () => true),
|
||||
applyShippingMessageRecovery: vi.fn(async () => false),
|
||||
applyShippingBatchSnapshot: vi.fn(() => false),
|
||||
syncShippingConversationWorkspace: vi.fn(async () => true),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
shippingSuggestedPrompt: computed(() => ''),
|
||||
@@ -254,7 +252,6 @@ describe('useChatShippingSendHandler', () => {
|
||||
|
||||
it('warns and consumes send when user tries batch task switching (co8 batch API retired)', async () => {
|
||||
const ctx = createContext({
|
||||
getActiveShippingBatchNo: () => 'SB-TEST',
|
||||
});
|
||||
const { tryHandleShippingSend } = createShippingSendHandlers(ctx);
|
||||
|
||||
|
||||
@@ -33,7 +33,6 @@ export interface ShippingSendHandlerContext {
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
shippingAutoFlowRequested: Ref<boolean>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
getActiveShippingBatchNo: () => string;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
selectedKb: Ref<string>;
|
||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||
@@ -45,7 +44,7 @@ export interface ShippingSendHandlerContext {
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
context?: { task_id?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
@@ -72,8 +71,6 @@ export interface ShippingSendHandlerContext {
|
||||
uploadBatchId?: string,
|
||||
) => Promise<boolean>;
|
||||
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
|
||||
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
|
||||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
isShippingShortageQueryIntent: (text: string) => boolean;
|
||||
|
||||
@@ -7,9 +7,7 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
clearPendingNoticeBatchRetry,
|
||||
createShippingUploadHandlers,
|
||||
onNoticeBatchConversationChanging,
|
||||
resetShippingNoticeBatchSubmitStateForTests,
|
||||
type ShippingUploadHandlerContext,
|
||||
} from './useChatShippingUploadHandler';
|
||||
@@ -47,9 +45,6 @@ const createContext = (
|
||||
pendingShippingNoticeTaskId: ref(''),
|
||||
pendingShippingInventoryFile: ref(null),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
resolvedShippingBatchNo: ref(''),
|
||||
shippingBatchSummary: ref(null),
|
||||
shippingBatchTasks: ref([]),
|
||||
shippingInventorySelectionActive: ref(false),
|
||||
shippingInventorySelectionTaskId: ref(''),
|
||||
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
|
||||
@@ -222,12 +217,6 @@ describe('useChatShippingUploadHandler', () => {
|
||||
expect(ctx.msg.warning).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('compatibility hooks for pending batch retry remain callable after co8', () => {
|
||||
clearPendingNoticeBatchRetry();
|
||||
onNoticeBatchConversationChanging('conv-b', 'conv-a');
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
|
||||
it('does not open notice picker when both explicit taskId and active task are missing', () => {
|
||||
const noticeClick = vi.fn();
|
||||
const warning = vi.fn();
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
* 单票覆盖仍经 replace_notice Turn;库存文件先成为私有临时资产再进 Dify 分析分支。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
|
||||
@@ -18,25 +17,6 @@ import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
let noticeBatchSubmitting = false;
|
||||
|
||||
/**
|
||||
* 显式清理待重试建批幂等状态(co8 后建批已下线,保留空实现供会话切换调用方兼容)。
|
||||
*/
|
||||
export function clearPendingNoticeBatchRetry(): void {
|
||||
/* no-op: shipping_batches 已 DROP */
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户主动切换会话时的钩子(co8 后无幂等键可清)。
|
||||
* @param _nextId - 新会话 ID
|
||||
* @param _prevId - 旧会话 ID
|
||||
*/
|
||||
export function onNoticeBatchConversationChanging(
|
||||
_nextId: string,
|
||||
_prevId?: string | null,
|
||||
): void {
|
||||
/* no-op */
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询发货通知建批是否正在提交中(供发送拦截器消费重复点击)。
|
||||
*/
|
||||
@@ -47,7 +27,6 @@ export function isShippingNoticeBatchSubmitting(): boolean {
|
||||
/** 单测重置模块级建批提交状态。 */
|
||||
export function resetShippingNoticeBatchSubmitStateForTests(): void {
|
||||
noticeBatchSubmitting = false;
|
||||
clearPendingNoticeBatchRetry();
|
||||
}
|
||||
|
||||
export interface ShippingUploadHandlerContext {
|
||||
@@ -62,9 +41,6 @@ export interface ShippingUploadHandlerContext {
|
||||
pendingShippingNoticeTaskId: Ref<string>;
|
||||
pendingShippingInventoryFile: Ref<File | null>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
resolvedShippingBatchNo: Ref<string>;
|
||||
shippingBatchSummary: Ref<unknown | null>;
|
||||
shippingBatchTasks: Ref<ShippingTaskSummary[]>;
|
||||
shippingInventorySelectionActive: Ref<boolean>;
|
||||
shippingInventorySelectionTaskId: Ref<string>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
@@ -160,11 +136,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
|
||||
|
||||
const syncBatchContextFromTurnMessage = (assistantMsg: ChatMessage) => {
|
||||
const payload = assistantMsg.payload && typeof assistantMsg.payload === 'object'
|
||||
? assistantMsg.payload as { batch_no?: string; task_no?: string; orchestrator_started?: boolean }
|
||||
? assistantMsg.payload as { task_no?: string; orchestrator_started?: boolean }
|
||||
: {};
|
||||
const batchNo = String(payload.batch_no || assistantMsg.shipping_ui_state?.batch_no || '').trim();
|
||||
const taskId = String(payload.task_no || assistantMsg.shipping_ui_state?.task_no || '').trim();
|
||||
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
};
|
||||
|
||||
|
||||
@@ -201,6 +201,42 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('uses summary PDF leaves as the minimal live work items for the batch center', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [{
|
||||
workItemType: 'order_task', workItemNo: 'DOCUMENT:1', rootOrderTaskNo: 'OT-1',
|
||||
sourceType: 'direct_pdf', status: 'processing', stage: 'document_parsing',
|
||||
sourceSummary: { documentId: 1, filename: 'po.pdf', documentCount: 1 },
|
||||
}],
|
||||
conversation_processing: buildProcessing(),
|
||||
});
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processingWorkItems.value[0]?.sourceSummary.filename).toBe('po.pdf');
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('applies a current conversation response that completes after 10 seconds', async () => {
|
||||
const pending = deferred<ReturnType<typeof buildUnifiedProcessing>>();
|
||||
api.getShippingProcessing.mockImplementation(() => pending.promise);
|
||||
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
// API 层拥有共享请求的 30 秒超时;10 秒后当前会话不能先把消费者标为取消。
|
||||
await vi.advanceTimersByTimeAsync(10_001);
|
||||
pending.resolve(buildUnifiedProcessing('conv-1'));
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
|
||||
expect(ctl.processing.value?.conversation_id).toBe('conv-1');
|
||||
expect(ctl.initialLoading.value).toBe(false);
|
||||
expect(ctl.error.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('records recoverable error without throwing', async () => {
|
||||
const conversationId = ref('conv-1');
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId });
|
||||
@@ -243,7 +279,7 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('uses unified work_items as the sole processing read source', async () => {
|
||||
it('does not rebuild conversation processing from work_items without status_groups', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [buildOrderTaskWorkItem('OT-UNIFIED', {
|
||||
@@ -265,12 +301,12 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(api.getShippingProcessing).toHaveBeenCalled();
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(1);
|
||||
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-UNIFIED');
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(0);
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('preserves previous order_task work_items when stabilizer keeps previous projection', async () => {
|
||||
it('does not retain a legacy work_items-derived projection across sparse responses', async () => {
|
||||
api.getShippingProcessing
|
||||
.mockResolvedValueOnce({
|
||||
conversation_id: 'conv-1',
|
||||
@@ -310,21 +346,17 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(1);
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemNo).toBe('OT-STABLE');
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('aggregates sibling EML OT work_items into one highest-attention Intake card', async () => {
|
||||
it('does not aggregate sibling work_items in the browser when status_groups is absent', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [
|
||||
@@ -409,15 +441,8 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
|
||||
expect(ctl.processing.value?.processing).toEqual([]);
|
||||
expect(ctl.processing.value?.needs_action[0]?.aggregateSummary).toMatchObject({
|
||||
intakeNo: 'SNI-1',
|
||||
total: 2,
|
||||
processing: 1,
|
||||
});
|
||||
expect(ctl.processing.value?.focused_task_no).toBe('OT-ROOT');
|
||||
expect(ctl.processing.value?.recent_task_no).toBe('OT-SIBLING');
|
||||
expect(ctl.processing.value).toBeNull();
|
||||
expect(ctl.processingWorkItems.value).toEqual([]);
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
@@ -436,7 +461,7 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(api.getShippingProcessing).toHaveBeenCalledTimes(2);
|
||||
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-conv-1');
|
||||
expect(ctl.processing.value?.status_groups?.waiting_human[0]?.user_task_no).toBe('OT-conv-1');
|
||||
expect(ctl.error.value).toBeNull();
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。
|
||||
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing;
|
||||
* focus/viewed 写路径优先应用响应中的 work_items;
|
||||
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;
|
||||
* 前台 2s / 后台 8s;共享请求的超时由 API 层统一管理;会话切换/卸载才取消当前消费者;失败指数退避至 8s;
|
||||
* 分层轮询:仅系统处理中 2s 轮询;外部 Run 轮询不会在待人工处理时反复唤醒本读接口;
|
||||
* 区分 initialLoading / manualRefreshing / polling 三种 loading 态;
|
||||
* 语义签名比较:业务状态未变化时不替换投影对象,防止按钮闪烁与 DOM 重建。
|
||||
@@ -40,7 +40,6 @@ 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 = 30000;
|
||||
const SNAPSHOT_CACHE_LIMIT = 20;
|
||||
|
||||
@@ -137,7 +136,7 @@ export function shouldContinueProcessingPolling(
|
||||
processing?: ConversationProcessingProjection | null,
|
||||
): boolean {
|
||||
const processingCount = Number(
|
||||
processing?.summary?.processing || processing?.processing?.length || 0,
|
||||
processing?.summary?.processing ?? processing?.status_groups?.processing.length ?? 0,
|
||||
);
|
||||
return processingCount > 0;
|
||||
}
|
||||
@@ -200,10 +199,22 @@ export function useShippingNoticeWorkflow(
|
||||
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,
|
||||
status: item.uiState?.status ?? null,
|
||||
stage: item.uiState?.stage ?? null,
|
||||
runNo: item.runNo ?? null,
|
||||
caseNo: item.caseNo ?? null,
|
||||
gate: item.uiState?.blocking_reason?.code ?? null,
|
||||
action: (() => {
|
||||
const action = item.uiState?.primary_action ?? null;
|
||||
return action
|
||||
? {
|
||||
code: action.code,
|
||||
executionMode: action.executionMode ?? null,
|
||||
targetSurface: action.targetSurface ?? null,
|
||||
targetLifecycleStage: action.targetLifecycleStage ?? null,
|
||||
}
|
||||
: null;
|
||||
})(),
|
||||
lifecycleEntries: item.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
state: entry.state,
|
||||
@@ -215,6 +226,16 @@ export function useShippingNoticeWorkflow(
|
||||
no: child.workItemNo,
|
||||
status: child.uiState?.status ?? child.userStatus ?? child.status,
|
||||
stage: child.uiState?.stage ?? child.userStage ?? child.stage,
|
||||
runNo: child.runNo ?? null,
|
||||
caseNo: child.caseNo ?? null,
|
||||
primaryAction: child.uiState?.primary_action
|
||||
? {
|
||||
code: child.uiState.primary_action.code,
|
||||
executionMode: child.uiState.primary_action.executionMode ?? null,
|
||||
targetSurface: child.uiState.primary_action.targetSurface ?? null,
|
||||
targetLifecycleStage: child.uiState.primary_action.targetLifecycleStage ?? null,
|
||||
}
|
||||
: null,
|
||||
lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({
|
||||
code: entry.code,
|
||||
state: entry.state,
|
||||
@@ -292,20 +313,22 @@ export function useShippingNoticeWorkflow(
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建带超时的 AbortController。
|
||||
* 创建当前会话代际的 AbortController。
|
||||
*
|
||||
* 共享 API 请求自行持有 30 秒超时,不能在此再设更短的消费者超时:
|
||||
* 否则底层请求虽仍可成功返回,当前代际会因 signal 已 aborted 而丢弃响应,
|
||||
* 导致首屏永久停留在权威投影骨架。这里仅用于会话切换或组件卸载的真实取消。
|
||||
*/
|
||||
function createRequestController(): AbortController {
|
||||
requestController?.abort();
|
||||
const controller = new AbortController();
|
||||
requestController = controller;
|
||||
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
||||
controller.signal.addEventListener('abort', () => clearTimeout(timeout), { once: true });
|
||||
return controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅拉取统一 shipping-processing 投影。
|
||||
* 核心逻辑:后端 status_groups 存在时直接使用;仅旧响应缺状态组才由 work_items 合成;
|
||||
* 核心逻辑:只消费后端 status_groups;
|
||||
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据;
|
||||
* 语义签名相同则不替换 projection 对象,避免 DOM 重建与按钮闪烁。
|
||||
*
|
||||
@@ -450,7 +473,7 @@ export function useShippingNoticeWorkflow(
|
||||
|
||||
/**
|
||||
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
|
||||
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块;
|
||||
* 核心逻辑:只回写后端返回的 status_groups;work_items 仅提供最小附件叶子。
|
||||
* 每次回写后更新语义签名,避免下一轮轮询误判为「无变化」。
|
||||
*/
|
||||
function applyMutationProcessingResponse(response: {
|
||||
@@ -458,12 +481,12 @@ export function useShippingNoticeWorkflow(
|
||||
work_items?: unknown[];
|
||||
}): void {
|
||||
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
|
||||
if (workItems.length > 0) {
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
response.processing ?? null,
|
||||
processing.value,
|
||||
);
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
response.processing ?? null,
|
||||
processing.value,
|
||||
);
|
||||
if (nextProjection) {
|
||||
processingWorkItems.value = resolveStableWorkItems(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
processing.value,
|
||||
@@ -476,13 +499,6 @@ export function useShippingNoticeWorkflow(
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (response.processing) {
|
||||
const nextKey = buildProcessingSemanticKey(response.processing);
|
||||
if (nextKey !== lastSemanticKey) {
|
||||
processing.value = response.processing;
|
||||
lastSemanticKey = nextKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -136,7 +136,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('merges sibling Runs from one upload batch into one chat status card', async () => {
|
||||
it('keeps the submitted Run card independent from sibling Runs in the same upload batch', async () => {
|
||||
const first = Object.assign(run({
|
||||
run_no: 'SNER-BATCH-1',
|
||||
conversation_id: 'conv-batch',
|
||||
@@ -191,7 +191,6 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
operation_id: 'op-batch',
|
||||
});
|
||||
api.getRun.mockResolvedValue(first);
|
||||
api.listRuns.mockResolvedValue({ items: [first, second] });
|
||||
const harness = createHarness();
|
||||
|
||||
await harness.runs.startRun('', ['SNI-BATCH-1', 'SNI-BATCH-2'], [], 'upload-batch-1');
|
||||
@@ -199,14 +198,14 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
const cards = harness.messages.value.filter((message) => message.shipping_order_extraction_state);
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]?.shipping_order_extraction_state?.summary).toMatchObject({
|
||||
totalDocuments: 2,
|
||||
totalDocuments: 1,
|
||||
pendingDocuments: 1,
|
||||
processingDocuments: 1,
|
||||
processingDocuments: 0,
|
||||
});
|
||||
expect(cards[0]?.shipping_order_extraction_state?.documents?.map((item) => item.fileName)).toEqual([
|
||||
'notice-a.pdf',
|
||||
'notice-b.pdf',
|
||||
]);
|
||||
expect(api.listRuns).not.toHaveBeenCalled();
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
@@ -290,25 +289,27 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
api.getRun.mockReturnValueOnce(pending.promise);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-old';
|
||||
await harness.runs.restoreForConversation('conv-old');
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
const oldRestore = harness.runs.restoreForConversation('conv-old');
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-OLD', expect.any(AbortSignal));
|
||||
|
||||
harness.conversationId.value = 'conv-new';
|
||||
await expect(harness.runs.restoreForConversation('conv-new')).resolves.toBeUndefined();
|
||||
pending.resolve(run({ run_no: 'SNER-OLD', conversation_id: 'conv-old', status: 'completed' }));
|
||||
await Promise.resolve();
|
||||
await oldRestore;
|
||||
expect(harness.runs.getActiveRunNo()).toBe('');
|
||||
expect(harness.messages.value).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.shipping_order_extraction_state?.status).toBe('processing');
|
||||
expect(harness.messages.value).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('notifies session work items refresh after restoring a terminal run', async () => {
|
||||
api.listRuns.mockResolvedValue({
|
||||
items: [run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' })],
|
||||
});
|
||||
const summary = run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' });
|
||||
const detail = run({ run_no: 'SNER-DONE', status: 'completed', phase: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [summary] });
|
||||
api.getRun.mockResolvedValue(detail);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-DONE', expect.any(AbortSignal));
|
||||
expect(harness.options.onWorkflowRefresh).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -348,7 +349,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
const queued = run({ run_no: 'SNER-RETRY', status: 'queued', phase: 'manual_retry_queued', error: null });
|
||||
api.listRuns.mockResolvedValue({ items: [failed] });
|
||||
api.retryRun.mockResolvedValue({ run: queued, reused: false });
|
||||
api.getRun.mockResolvedValue(queued);
|
||||
api.getRun.mockResolvedValueOnce(failed).mockResolvedValue(queued);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
@@ -381,7 +382,7 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
});
|
||||
api.listRuns.mockResolvedValue({ items: [source] });
|
||||
api.reparseRun.mockResolvedValue({ run: replacement, reused: false });
|
||||
api.getRun.mockResolvedValue(replacement);
|
||||
api.getRun.mockResolvedValueOnce(source).mockResolvedValueOnce(source).mockResolvedValue(replacement);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
@@ -393,6 +394,21 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(harness.messages.value).toHaveLength(2);
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('uses a lightweight Run list only to locate the latest Run before loading one detail', async () => {
|
||||
const latest = run({ run_no: 'SNER-LATEST', conversation_id: 'conv-1', status: 'processing' });
|
||||
const older = run({ run_no: 'SNER-OLDER', conversation_id: 'conv-1', status: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [latest, older] });
|
||||
api.getRun.mockResolvedValue(latest);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
expect(api.getRun).toHaveBeenCalledTimes(1);
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-LATEST', expect.any(AbortSignal));
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -644,6 +660,7 @@ describe('mapOrderExtractionRunToMessageState', () => {
|
||||
it('acknowledges a terminal Run only after it is restored into the active conversation', async () => {
|
||||
const terminal = run({ run_no: 'SNER-SEEN', status: 'completed' });
|
||||
api.listRuns.mockResolvedValue({ items: [terminal] });
|
||||
api.getRun.mockResolvedValue(terminal);
|
||||
api.markSeen.mockResolvedValue({ seen: true });
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
@@ -36,7 +36,6 @@ interface UseShippingOrderExtractionRunsOptions {
|
||||
refreshNoticeIntakeStatuses: () => Promise<void>;
|
||||
getOrderExtractionReview: (intakeNos: string[]) => ShippingOrderExtractionReviewAttachment[];
|
||||
clearConsumedNoticeAttachments: () => void;
|
||||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
onConversationResolved: (conversationId: string) => Promise<void> | void;
|
||||
@@ -54,69 +53,6 @@ const ACTIVE_RUN_STATUSES = new Set(['queued', 'processing']);
|
||||
const FOREGROUND_POLL_MS = 2000;
|
||||
const BACKGROUND_POLL_MS = 8000;
|
||||
|
||||
/**
|
||||
* 将同一上传批次的独立 Run 合成单张聊天状态卡。
|
||||
*
|
||||
* 核心逻辑:Run 仍按 Intake 独立执行、审计和复核;仅把同会话同 upload_batch_id
|
||||
* 的用户态摘要相加,保证一次文件选择在聊天区只出现一个卡片。
|
||||
*/
|
||||
function mergeUploadBatchRuns(primary: ShippingOrderExtractionRun, runs: ShippingOrderExtractionRun[]): ShippingOrderExtractionRun {
|
||||
const batchId = String(primary.upload_batch_id || '').trim();
|
||||
if (!batchId) return primary;
|
||||
const members = runs.filter((item) => (
|
||||
item.conversation_id === primary.conversation_id
|
||||
&& String(item.upload_batch_id || '').trim() === batchId
|
||||
));
|
||||
if (members.length <= 1) return primary;
|
||||
const activeMembers = members.filter((item) => ACTIVE_RUN_STATUSES.has(item.status));
|
||||
const status = activeMembers.some((item) => item.status === 'processing')
|
||||
? 'processing'
|
||||
: activeMembers.length > 0
|
||||
? 'queued'
|
||||
: members.some((item) => item.status === 'failed')
|
||||
? 'failed'
|
||||
: members.some((item) => item.status === 'review_required')
|
||||
? 'review_required'
|
||||
: members.some((item) => item.status === 'partially_completed')
|
||||
? 'partially_completed'
|
||||
: 'completed';
|
||||
const failedParseMembers = members.filter((item) => (
|
||||
item.documents || []
|
||||
).some((document) => document.reason_code === 'intake_parse_failed' || String(document.user_visible_stage || '') === 'parse_failed'));
|
||||
const effectiveStatus = failedParseMembers.length > 0 && activeMembers.length === 0 ? 'failed' : status;
|
||||
const summaryKeys = [
|
||||
'total_documents', 'pending_documents', 'processing_documents', 'completed_documents',
|
||||
'review_required_documents', 'failed_documents', 'cancelled_documents', 'candidate_count',
|
||||
'opened_existing_documents',
|
||||
] as const;
|
||||
const summary = summaryKeys.reduce((result, key) => {
|
||||
result[key] = members.reduce((total, item) => total + Number(item.summary?.[key] || 0), 0);
|
||||
return result;
|
||||
}, {} as ShippingOrderExtractionRun['summary']);
|
||||
const documentIds = new Set<number>();
|
||||
const documents = members.flatMap((item) => item.documents || []).filter((item) => {
|
||||
const id = Number(item.document_id || 0);
|
||||
if (id && documentIds.has(id)) return false;
|
||||
if (id) documentIds.add(id);
|
||||
return true;
|
||||
});
|
||||
const mostRecent = [...members].sort((left, right) => String(right.last_activity_at || '').localeCompare(String(left.last_activity_at || '')))[0] || primary;
|
||||
return {
|
||||
...primary,
|
||||
status: effectiveStatus,
|
||||
phase: effectiveStatus,
|
||||
intake_nos: [...new Set(members.flatMap((item) => item.intake_nos || []))],
|
||||
summary,
|
||||
documents,
|
||||
current_activity: mostRecent.current_activity || primary.current_activity,
|
||||
available_actions: [...new Set(members.flatMap((item) => item.available_actions || []))],
|
||||
handling_items: members.flatMap((item) => item.handling_items || []),
|
||||
health_tips: members.flatMap((item) => item.health_tips || []),
|
||||
progress_version: Math.max(...members.map((item) => Number(item.progress_version || 0))),
|
||||
last_activity_at: mostRecent.last_activity_at || primary.last_activity_at,
|
||||
};
|
||||
}
|
||||
|
||||
/** 按页面可见性选择轮询间隔;后台放慢,失败退避另算。 */
|
||||
function resolvePollIntervalMs(failureCount = 0): number {
|
||||
if (failureCount > 0) {
|
||||
@@ -296,21 +232,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
return composerContextId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取同批次兄弟 Run 后生成聊天展示快照。
|
||||
*
|
||||
* 仅在服务端已返回 upload_batch_id 时查询;旧 Run 或重识别 Run 保持原有单卡逻辑。
|
||||
*/
|
||||
const loadDisplayRun = async (run: ShippingOrderExtractionRun): Promise<ShippingOrderExtractionRun> => {
|
||||
if (!String(run.upload_batch_id || '').trim()) return run;
|
||||
try {
|
||||
const response = await listWorkspaceShippingOrderExtractionRuns(run.conversation_id, 100);
|
||||
return mergeUploadBatchRuns(run, response.items || []);
|
||||
} catch {
|
||||
// 聚合读失败时宁可显示本 Run 的真实状态,也不阻断轮询或误改业务状态。
|
||||
return run;
|
||||
}
|
||||
};
|
||||
/** Run 卡只消费该 Run 的完整权威详情;批次聚合由独立处理投影负责。 */
|
||||
const loadDisplayRun = async (run: ShippingOrderExtractionRun): Promise<ShippingOrderExtractionRun> => run;
|
||||
|
||||
/** 停止当前 Run 短轮询;切会话和组件卸载时再清空 activeRunNo。 */
|
||||
const stopPolling = () => {
|
||||
@@ -452,14 +375,6 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
reviewAttachments = options.getOrderExtractionReview(run.intake_nos);
|
||||
}
|
||||
options.clearConsumedNoticeAttachments();
|
||||
try {
|
||||
if (!(await options.syncShippingConversationWorkspace({ preferLatest: true }))) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
await options.syncShippingConversationWorkspace({ preferLatest: true });
|
||||
}
|
||||
} catch {
|
||||
// Run 状态卡已持久化;工作台可由页面下一次刷新继续恢复。
|
||||
}
|
||||
await Promise.allSettled([options.loadHistory()]);
|
||||
options.onWorkflowRefresh?.();
|
||||
return reviewAttachments;
|
||||
@@ -768,8 +683,9 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
const latest = items[0];
|
||||
if (!latest) return;
|
||||
activeRunNo = latest.run_no;
|
||||
const displayRun = mergeUploadBatchRuns(latest, items);
|
||||
const displayRun = await getWorkspaceShippingOrderExtractionRun(latest.run_no, request.signal);
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
activeRunNo = displayRun.run_no;
|
||||
const reviewAttachments = ACTIVE_RUN_STATUSES.has(displayRun.status)
|
||||
? undefined
|
||||
: await refreshTerminalFacts(displayRun);
|
||||
|
||||
Reference in new issue
Block a user