feat(shipping-notice): 新增通用解析能力,优化性能并清理遗留废弃代码
This commit is contained in:
1 parent
935bf26fa6
commit
7cfd5d167e
230 files changed
+9337
-10989
No files matched your search
@@ -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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user