1048 lines
44 KiB
TypeScript
1048 lines
44 KiB
TypeScript
/**
|
||
* features/chat/shipping/conversationProcessingProjection.ts
|
||
* 用途:将 OT / 统一 processing 投影为对话「本次处理中」对象、任务分组与文件行。
|
||
* 依赖:shipping.api.types(ConversationProcessingObject / UserTask / WorkflowNodeStatus /
|
||
* ShippingProcessingProjection、合成 ShippingWorkflowItem)。
|
||
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
|
||
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
|
||
* 会话卡直接消费后端 status_groups,不从 work_items 二次聚合。
|
||
* 语义签名与任务稳定化:轮询返回相同业务状态时复用旧对象,避免按钮闪烁。
|
||
*/
|
||
|
||
import type {
|
||
ConversationProcessingObject,
|
||
ConversationProcessingProjection,
|
||
ConversationProcessingSummary,
|
||
ConversationProcessingTaskGroup,
|
||
ConversationProcessingUserTask,
|
||
ShippingProcessingBlockingReason,
|
||
ShippingProcessingLifecycleEntry,
|
||
ShippingProcessingPrimaryAction,
|
||
ShippingProcessingProjection,
|
||
ShippingWorkflowItem,
|
||
WorkflowNodeStatus,
|
||
} from '@/features/chat/types/shipping.api.types';
|
||
import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing';
|
||
|
||
/**
|
||
* 展开工作项中的业务文件叶子。
|
||
* EML 只是来源容器,不是可处理业务文件;只有其下真实附件(PDF/XLSX 等)
|
||
* 以及 direct_pdf 自身进入文件计数和文件名列表。该函数不修改后端投影。
|
||
*/
|
||
export function flattenBusinessFileProjections(
|
||
items: readonly ShippingProcessingProjection[] | null | undefined,
|
||
): ShippingProcessingProjection[] {
|
||
const rows: ShippingProcessingProjection[] = [];
|
||
const visit = (item: ShippingProcessingProjection) => {
|
||
const nested = Array.isArray(item.aggregateChildren) ? item.aggregateChildren : [];
|
||
if (nested.length) {
|
||
nested.forEach(visit);
|
||
return;
|
||
}
|
||
const filename = String(item.sourceSummary?.filename || '').trim();
|
||
if (filename.toLowerCase().endsWith('.eml')) return;
|
||
// 没有文件名的聚合容器不能伪造一个文件行。
|
||
if (!filename && item.sourceType === 'eml') return;
|
||
rows.push(item);
|
||
};
|
||
(items || []).forEach(visit);
|
||
return rows;
|
||
}
|
||
|
||
/** 以文档 ID 优先、文件名兜底,对叶子业务文件稳定去重。 */
|
||
export function businessFileKeys(
|
||
items: readonly ShippingProcessingProjection[] | null | undefined,
|
||
): string[] {
|
||
const keys = new Set<string>();
|
||
for (const item of flattenBusinessFileProjections(items)) {
|
||
const id = Number(item.sourceSummary?.documentId || 0);
|
||
const filename = String(item.sourceSummary?.filename || '').trim().toLowerCase();
|
||
const key = id > 0 ? `document:${id}` : filename ? `filename:${filename}` : '';
|
||
if (key) keys.add(key);
|
||
}
|
||
return [...keys];
|
||
}
|
||
|
||
/**
|
||
* 标准化动作码列表:去空白、小写、去重、字典序排序。
|
||
* 核心逻辑:后端返回顺序或临时字段变化时,确保前端动作集合稳定。
|
||
*
|
||
* @param actions - 原始动作码数组
|
||
* @returns 标准化后的动作码数组(唯一、已排序)
|
||
*/
|
||
export function normalizeActionCodes(actions: unknown[]): string[] {
|
||
return [...new Set(
|
||
(actions || [])
|
||
.map((item) => String(item || '').trim().toLowerCase())
|
||
.filter(Boolean),
|
||
)].sort();
|
||
}
|
||
|
||
/**
|
||
* 构建单个用户任务的语义签名:只包含决定按钮与展示的核心字段。
|
||
* 排除 updated_at / last_activity_at 等仅用于辅助提示的字段。
|
||
*
|
||
* @param task - 用户可见任务
|
||
* @returns 语义签名字符串;任务为 null 时返回空串
|
||
*/
|
||
export function buildTaskSemanticKey(
|
||
task: ConversationProcessingUserTask | null | undefined,
|
||
): string {
|
||
if (!task) return '';
|
||
const rawStatus = (task as ConversationProcessingUserTask & { userStatus?: string | null }).userStatus ?? task.status_label;
|
||
const aggregateChildren = (task.aggregateChildren || []).map((child) => ({
|
||
workItemNo: child.workItemNo,
|
||
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?.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,
|
||
targetSurface: entry.targetSurface,
|
||
disabledReasonKey: entry.disabledReasonKey ?? null,
|
||
})) ?? [],
|
||
}));
|
||
return JSON.stringify({
|
||
taskNo: task.user_task_no,
|
||
group: task.group,
|
||
status: normalizeLifecycleStatus(rawStatus),
|
||
runNo: task.run_no,
|
||
displayKind: task.display_kind,
|
||
fileCount: task.file_count,
|
||
title: task.title,
|
||
// [AUTHORITY] 新会话批次的可操作动作由 ui_state 单独版本化;把它纳入语义键,
|
||
// 避免状态未变但后端撤销/切换按钮时前端错误复用旧任务对象。
|
||
primaryAction: task.uiState?.primary_action?.code ?? null,
|
||
// 生命周期入口由后端独立裁决;入口被撤销/禁用时必须替换缓存对象,不能保留旧按钮。
|
||
lifecycleEntries: task.uiState?.lifecycleEntries?.map((entry) => ({
|
||
code: entry.code,
|
||
state: entry.state,
|
||
targetSurface: entry.targetSurface,
|
||
disabledReasonKey: entry.disabledReasonKey ?? null,
|
||
})) ?? [],
|
||
currentGate: (task as ConversationProcessingUserTask & {
|
||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||
blockingReason?: { code?: string } | null;
|
||
})
|
||
.current_gate
|
||
? {
|
||
blockingReasonCode: (task as ConversationProcessingUserTask & {
|
||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||
})
|
||
.current_gate?.blockingReasonCode
|
||
?? (task as ConversationProcessingUserTask & { blockingReason?: { code?: string } | null }).blockingReason?.code
|
||
?? null,
|
||
nextActionCode: (task as ConversationProcessingUserTask & {
|
||
current_gate?: { blockingReasonCode?: string; nextActionCode?: string };
|
||
}).current_gate?.nextActionCode ?? null,
|
||
}
|
||
: null,
|
||
availableActions: normalizeActionCodes(
|
||
task.uiState?.secondary_actions.filter((action) => action.enabled).map((action) => action.code) || [],
|
||
),
|
||
canAppend: task.can_append ?? null,
|
||
aggregateChildren,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 构建整个会话处理投影的语义签名:summary + 各分组任务签名。
|
||
*
|
||
* @param projection - 会话处理投影
|
||
* @returns 语义签名字符串;投影为 null 时返回空串
|
||
*/
|
||
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,
|
||
total_files: projection.summary?.total_files || 0,
|
||
submitted_files: projection.summary?.submitted_files || 0,
|
||
processing: projection.summary?.processing || 0,
|
||
needs_action: projection.summary?.needs_action || 0,
|
||
completed: projection.summary?.completed || 0,
|
||
history: projection.summary?.history || 0,
|
||
},
|
||
focused_task_no: projection.focused_task_no || null,
|
||
recent_task_no: projection.recent_task_no || null,
|
||
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),
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 按任务号复用旧对象:语义签名相同时返回旧引用,保证 Vue v-for 复用 DOM。
|
||
*
|
||
* @param previousTasks - 上一次渲染的任务列表
|
||
* @param nextRawTasks - 本次轮询生成的新任务列表(原始未稳定化)
|
||
* @returns 稳定化后的任务列表;语义未变的任务沿用旧引用
|
||
*/
|
||
export function stabilizeTaskObjects(
|
||
previousTasks: ConversationProcessingUserTask[],
|
||
nextRawTasks: ConversationProcessingUserTask[],
|
||
): ConversationProcessingUserTask[] {
|
||
const previousByTaskNo = new Map(
|
||
(previousTasks || []).map((task) => [String(task.user_task_no || ''), task]),
|
||
);
|
||
return (nextRawTasks || []).map((nextTask) => {
|
||
const previous = previousByTaskNo.get(String(nextTask.user_task_no || ''));
|
||
if (!previous) return nextTask;
|
||
if (buildTaskSemanticKey(previous) === buildTaskSemanticKey(nextTask)) {
|
||
return previous;
|
||
}
|
||
return nextTask;
|
||
});
|
||
}
|
||
|
||
/** 需要人工处理的生命周期集合。 */
|
||
const NEEDS_ACTION_LIFECYCLES = new Set([
|
||
'blocked',
|
||
'waiting_review',
|
||
'waiting_human',
|
||
'pending_review',
|
||
'manual_upload_pending',
|
||
'failed',
|
||
'reparse_failed',
|
||
'upload_rpa_failed',
|
||
]);
|
||
|
||
/**
|
||
* Intake / OT 过渡稳定器。
|
||
* 用途:后端 Intake 与 ShippingOrderTask 往往不在同一事务窗出现。
|
||
* 一旦看到过 order_task 后,接下来 2 秒内即便 work_items 里没有 order_task,
|
||
* 也不立即回退 embedded,避免轮询刷新在「待复核 ⇄ 待复核(兼容态」之间
|
||
* 跳变,实际上是 OT 还没在本次响应里出现,下一轮就有。
|
||
*/
|
||
export interface IntakeOtStabilizer {
|
||
/** 注入「此会话是否已经至少出现过一次 order_task」。 */
|
||
hasSeenOrderTaskBefore(conversationId?: string | null): boolean;
|
||
/** 当且仅当 work_items 里确实有 order_task 时调用,记录“见过 OT 并更新时间戳。 */
|
||
markSeen(conversationId?: string | null): void;
|
||
/** 手动刷新/重载/离开页面重进时清空时间戳,允许回到 embedded 兼容态。 */
|
||
reset(conversationId?: string | null): void;
|
||
}
|
||
|
||
export function createIntakeOtStabilizer(options?: { graceMs?: number }): IntakeOtStabilizer {
|
||
const graceMs = Number(options?.graceMs ?? 2000);
|
||
const seen = new Map<string, number>();
|
||
const global: { ts: number | null } = { ts: null };
|
||
function getNow() {
|
||
return Date.now();
|
||
}
|
||
return {
|
||
hasSeenOrderTaskBefore(conversationId?: string | null): boolean {
|
||
const now = getNow();
|
||
if (conversationId) {
|
||
const ts = seen.get(conversationId);
|
||
if (typeof ts === 'number' && now - ts <= graceMs) return true;
|
||
}
|
||
const gts = global.ts;
|
||
if (typeof gts === 'number' && now - gts <= graceMs) return true;
|
||
return false;
|
||
},
|
||
markSeen(conversationId?: string | null): void {
|
||
const now = getNow();
|
||
global.ts = now;
|
||
if (conversationId) seen.set(conversationId, now);
|
||
},
|
||
reset(conversationId?: string | null): void {
|
||
global.ts = null;
|
||
if (conversationId) seen.delete(conversationId);
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 归一化生命周期状态:把旧/兼容形态统一映射为新的单一状态。
|
||
* 核心逻辑:waiting_human(旧 conversation_processing 兜底)一律归并为
|
||
* waiting_review(新统一投影);pending_review 收敛到 waiting_review;
|
||
* 其它保持原值。用于避免两套投影切换时造成状态文本闪烁、语义签名漂移。
|
||
* @param status - 原始 lifecycle / userStatus / status_label
|
||
* @returns 归一化后的生命周期状态码
|
||
*/
|
||
export function normalizeLifecycleStatus(
|
||
status: string | null | undefined,
|
||
): string {
|
||
const raw = String(status || '').trim().toLowerCase();
|
||
if (!raw) return '';
|
||
// [LEGACY-UNIFY] 旧兼容状态一律收敛为 waiting_review,保证显示「待复核」而非 waiting human。
|
||
if (raw === 'waiting_human' || raw === 'pending_review' || raw === 'review_required') {
|
||
return 'waiting_review';
|
||
}
|
||
if (raw === 'partially_completed') return 'waiting_review';
|
||
if (raw === 'manual_upload' || raw === 'waiting_manual_upload') return 'manual_upload_pending';
|
||
if (raw === 'retryable') return 'failed';
|
||
return raw;
|
||
}
|
||
|
||
const HUMAN_ACTION_CODES = new Set([
|
||
'confirm_customer', 'resolve_field_conflicts', 'adjudicate_duplicate',
|
||
'open_order_review', 'open_order_processing', 'enter_manual_review',
|
||
'open_inventory_match_review', 'rematch', 'match_inventory',
|
||
'open_shortage_review', 'upload_inventory_file', 'open_manual_upload',
|
||
'wait_manual_upload', 'retry', 'retry_parse', 'retry_failed_documents',
|
||
'retry_failed_attachments', 'open_profile_review',
|
||
]);
|
||
|
||
/** 处理中生命周期集合。 */
|
||
const PROCESSING_LIFECYCLES = new Set([
|
||
'queued',
|
||
'layout_parsing',
|
||
'extracting',
|
||
'building_order',
|
||
'inventory_matching',
|
||
'generating_excel',
|
||
'upload_rpa_pending',
|
||
'upload_rpa_running',
|
||
]);
|
||
|
||
/** 历史生命周期集合(已关闭/取消;completed 单独进「已完成」通知组)。 */
|
||
const HISTORY_LIFECYCLES = new Set([
|
||
'closed',
|
||
'cancelled',
|
||
]);
|
||
|
||
/** 识别完成、仍应在右侧展示的成功通知生命周期。 */
|
||
const COMPLETED_LIFECYCLES = new Set([
|
||
'completed',
|
||
]);
|
||
|
||
/**
|
||
* 将生命周期状态映射为 WorkflowNodeStatus(展示用,非进度百分比)。
|
||
*/
|
||
export function mapLifecycleToNodeStatus(
|
||
lifecycle: string | null | undefined,
|
||
): WorkflowNodeStatus {
|
||
const status = String(lifecycle || '').trim();
|
||
if (!status || status === 'queued') return 'pending';
|
||
if (
|
||
status === 'layout_parsing'
|
||
|| status === 'extracting'
|
||
|| status === 'building_order'
|
||
|| status === 'inventory_matching'
|
||
|| status === 'generating_excel'
|
||
) {
|
||
return 'running';
|
||
}
|
||
if (status === 'failed' || status === 'reparse_failed') return 'failed';
|
||
if (status === 'upload_rpa_pending' || status === 'upload_rpa_running') {
|
||
return 'running';
|
||
}
|
||
if (status === 'upload_rpa_failed') return 'failed';
|
||
if (status === 'pending_review' || status === 'manual_upload_pending') {
|
||
return 'manual_takeover';
|
||
}
|
||
if (status === 'closed' || status === 'cancelled') return 'succeeded';
|
||
return 'pending';
|
||
}
|
||
|
||
/**
|
||
* 取 Item 用户可见状态:细粒度 display/current_stage 优先。
|
||
*/
|
||
export function resolveItemDisplayStatus(item: ShippingWorkflowItem): string {
|
||
const display = String(item.display_lifecycle_status || '').trim();
|
||
if (display) return display;
|
||
const stage = String(item.current_stage || '').trim();
|
||
if (
|
||
stage === 'upload_rpa_pending'
|
||
|| stage === 'upload_rpa_running'
|
||
|| stage === 'upload_rpa_failed'
|
||
) {
|
||
return stage;
|
||
}
|
||
return String(item.lifecycle_status || '').trim();
|
||
}
|
||
|
||
/**
|
||
* 将 OT 任务卡内 document objects 映射为侧栏文件行(合成 ShippingWorkflowItem 形态)。
|
||
* 核心逻辑:仅消费 kind=document;item_no 优先 workflow_item_no / object_key;
|
||
* available_actions / reparse_kind 可从 object 扩展字段透传(单测与后端可选投影)。
|
||
*
|
||
* @param task - 当前展开的用户可见任务
|
||
* @returns 文件明细行;无文档对象时为空数组
|
||
*/
|
||
export function mapUserTaskObjectsToFileRows(
|
||
task: ConversationProcessingUserTask | null | undefined,
|
||
): ShippingWorkflowItem[] {
|
||
if (!task) return [];
|
||
const rows: ShippingWorkflowItem[] = [];
|
||
for (const [index, object] of (task.objects || []).entries()) {
|
||
if (object.kind !== 'document') continue;
|
||
const documentId = Number(object.document_id || 0);
|
||
const rootId = Number(object.root_document_id || documentId || 0);
|
||
const status = String(object.status_label || task.status_label || 'queued').trim() || 'queued';
|
||
const itemNo = String(
|
||
object.workflow_item_no || object.object_key || `DOC-${documentId || index + 1}`,
|
||
).trim();
|
||
const extra = object as ConversationProcessingObject & {
|
||
available_actions?: string[];
|
||
reparse_kind?: string | null;
|
||
lock_version?: number;
|
||
};
|
||
rows.push({
|
||
item_no: itemNo,
|
||
workflow_no: String(task.workflow_no || 'SNWF-OT').trim() || 'SNWF-OT',
|
||
conversation_id: '',
|
||
root_document_id: rootId,
|
||
current_document_id: documentId || rootId,
|
||
current_document_filename: object.filename || object.label || null,
|
||
content_hash: object.content_hash || null,
|
||
current_version_no: Number(object.current_version_no || 1) || 1,
|
||
current_run_no: object.current_run_no || object.run_no || task.run_no || null,
|
||
current_case_no: object.case_no || null,
|
||
current_task_no: object.task_no || task.user_task_no || null,
|
||
user_task_no: task.user_task_no,
|
||
user_task_authoritative: task.user_task_authoritative,
|
||
lifecycle_status: status,
|
||
current_stage: status,
|
||
display_lifecycle_status: status,
|
||
lock_version: Number(extra.lock_version || 1) || 1,
|
||
available_actions: Array.isArray(extra.available_actions)
|
||
? extra.available_actions
|
||
: (Array.isArray(task.available_actions) ? task.available_actions : undefined),
|
||
reparse_kind: extra.reparse_kind ?? null,
|
||
});
|
||
}
|
||
return rows;
|
||
}
|
||
|
||
/**
|
||
* 从 Workflow Items 聚合 Run / Candidate / Task / Process Gate 侧栏行。
|
||
*
|
||
* 核心逻辑:同一 run_no / task_no 去重;Gate 取每项首个阻断门禁;
|
||
* focusTaskNo 命中时标记 focused。
|
||
*
|
||
* @param items - 当前会话 Workflow Items
|
||
* @param options.focusTaskNo - 当前聚焦 Task
|
||
* @param options.focusRunNo - 当前聚焦 Run
|
||
*/
|
||
export function projectConversationProcessingObjects(
|
||
items: ShippingWorkflowItem[],
|
||
options?: {
|
||
focusTaskNo?: string | null;
|
||
focusRunNo?: string | null;
|
||
focusCandidateNo?: string | null;
|
||
},
|
||
): ConversationProcessingObject[] {
|
||
const focusTask = String(options?.focusTaskNo || '').trim().toUpperCase();
|
||
const focusRun = String(options?.focusRunNo || '').trim();
|
||
const focusCandidate = String(options?.focusCandidateNo || '').trim();
|
||
const rows: ConversationProcessingObject[] = [];
|
||
const seenRuns = new Set<string>();
|
||
const seenTasks = new Set<string>();
|
||
const seenGates = new Set<string>();
|
||
|
||
for (const item of items || []) {
|
||
const runNo = String(item.current_run_no || '').trim();
|
||
const taskNo = String(item.current_task_no || '').trim().toUpperCase();
|
||
const caseNo = String(item.current_case_no || '').trim();
|
||
const itemNo = String(item.item_no || '').trim();
|
||
const documentId = Number(item.current_document_id || 0) || null;
|
||
// 优先消费后端权威 node_status;缺失时才用 lifecycle 本地映射。
|
||
const displayStatus = resolveItemDisplayStatus(item);
|
||
const backendNodeStatus = String(item.node_status || '').trim() as WorkflowNodeStatus | '';
|
||
const nodeStatus = backendNodeStatus || mapLifecycleToNodeStatus(displayStatus);
|
||
|
||
if (runNo && !seenRuns.has(runNo)) {
|
||
seenRuns.add(runNo);
|
||
rows.push({
|
||
kind: 'run',
|
||
object_key: `run:${runNo}`,
|
||
label: runNo,
|
||
status_label: displayStatus,
|
||
node_status: mapLifecycleToNodeStatus(displayStatus),
|
||
run_no: runNo,
|
||
case_no: caseNo || null,
|
||
document_id: documentId,
|
||
workflow_item_no: itemNo || null,
|
||
primary_action: caseNo || item.lifecycle_status === 'pending_review'
|
||
? 'open_review'
|
||
: 'expand',
|
||
focused: Boolean(focusRun && focusRun === runNo),
|
||
});
|
||
}
|
||
|
||
// Candidate:尚无独立列表时,以待复核 Case 作为候选处理对象入口。
|
||
if (caseNo && (item.lifecycle_status === 'pending_review' || focusCandidate)) {
|
||
const candidateKey = `candidate:${caseNo}`;
|
||
if (!rows.some((row) => row.object_key === candidateKey)) {
|
||
rows.push({
|
||
kind: 'candidate',
|
||
object_key: candidateKey,
|
||
label: caseNo,
|
||
status_label: 'pending_review',
|
||
qualification_status: 'review_required',
|
||
run_no: runNo || null,
|
||
candidate_no: focusCandidate || null,
|
||
case_no: caseNo,
|
||
document_id: documentId,
|
||
workflow_item_no: itemNo || null,
|
||
primary_action: 'open_review',
|
||
focused: Boolean(
|
||
(focusCandidate && focusCandidate === caseNo)
|
||
|| (focusCandidate && focusCandidate === String(focusCandidate)),
|
||
),
|
||
});
|
||
}
|
||
}
|
||
|
||
if (taskNo && !seenTasks.has(taskNo)) {
|
||
seenTasks.add(taskNo);
|
||
rows.push({
|
||
kind: 'task',
|
||
object_key: `task:${taskNo}`,
|
||
label: taskNo,
|
||
status_label: displayStatus,
|
||
node_status: nodeStatus,
|
||
run_no: runNo || null,
|
||
task_no: taskNo,
|
||
case_no: caseNo || null,
|
||
document_id: documentId,
|
||
workflow_item_no: itemNo || null,
|
||
primary_action: 'focus_task',
|
||
focused: Boolean(focusTask && focusTask === taskNo),
|
||
});
|
||
}
|
||
|
||
const gateSummary = item.process_gate;
|
||
const blockingGate = gateSummary?.current_blocking_gate;
|
||
const gateCode = String(
|
||
blockingGate?.gate_code
|
||
|| gateSummary?.blocking_reason_code
|
||
|| '',
|
||
).trim();
|
||
const gateStatus = String(blockingGate?.status || gateSummary?.status || '').trim();
|
||
if (gateCode && blockingGate) {
|
||
const gateKey = `gate:${taskNo || runNo || itemNo}:${gateCode}`;
|
||
if (!seenGates.has(gateKey)) {
|
||
seenGates.add(gateKey);
|
||
rows.push({
|
||
kind: 'process_gate',
|
||
object_key: gateKey,
|
||
label: gateCode,
|
||
status_label: gateStatus || 'blocked',
|
||
node_status: 'failed',
|
||
run_no: runNo || null,
|
||
task_no: taskNo || gateSummary?.task_no || null,
|
||
case_no: caseNo || gateSummary?.case_no || null,
|
||
document_id: documentId,
|
||
workflow_item_no: itemNo || null,
|
||
primary_action: 'open_gate',
|
||
focused: false,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
return rows;
|
||
}
|
||
|
||
/**
|
||
* 按生命周期/门禁将状态归入 needs_action | processing | completed | history。
|
||
*/
|
||
export function classifyConversationProcessingGroup(
|
||
status: string | null | undefined,
|
||
options?: { hasBlockingGate?: boolean; needsCustomerConfirm?: boolean },
|
||
): ConversationProcessingTaskGroup {
|
||
if (options?.needsCustomerConfirm) return 'needs_action';
|
||
const normalized = normalizeLifecycleStatus(status);
|
||
if (NEEDS_ACTION_LIFECYCLES.has(normalized)) return 'needs_action';
|
||
if (COMPLETED_LIFECYCLES.has(normalized)) return 'completed';
|
||
if (HISTORY_LIFECYCLES.has(normalized)) return 'history';
|
||
if (PROCESSING_LIFECYCLES.has(normalized)) return 'processing';
|
||
if (normalized === 'failed') return 'needs_action';
|
||
if (normalized === 'completed') return 'completed';
|
||
if (normalized === 'processing' || normalized === 'queued') return 'processing';
|
||
return 'processing';
|
||
}
|
||
|
||
/**
|
||
* 兜底任务身份键:稳定业务身份优先,文件名仅作最弱兜底。
|
||
* 顺序:user_task_no → content_hash → root_document_id → filename → run/item。
|
||
* 普通重传会换 root_document_id,故不得把 root 放在 content_hash 之前。
|
||
*/
|
||
function fallbackTaskIdentityKey(item: ShippingWorkflowItem): string {
|
||
const userTaskNo = String(item.user_task_no || '').trim();
|
||
if (userTaskNo) return `task:${userTaskNo}`;
|
||
const contentHash = String(item.content_hash || '').trim().toLowerCase();
|
||
if (contentHash) return `hash:${contentHash}`;
|
||
const rootId = Number(item.root_document_id || 0);
|
||
if (rootId > 0) return `root:${rootId}`;
|
||
const filename = String(item.current_document_filename || '').trim().toLowerCase();
|
||
if (filename) return `fn:${filename}`;
|
||
const runNo = String(item.current_run_no || '').trim();
|
||
if (runNo) return `run:${runNo}`;
|
||
const itemNo = String(item.item_no || '').trim();
|
||
return `item:${itemNo}`;
|
||
}
|
||
|
||
/**
|
||
* 降级路径:按稳定身份去重 Workflow Items 中的业务 PDF。
|
||
* 顺序:content_hash → root_document_id → current_document_id;禁止仅按文件名去重。
|
||
*/
|
||
function dedupeFallbackDocuments(items: ShippingWorkflowItem[]): Array<{
|
||
filename: string | null;
|
||
content_hash: string | null;
|
||
root_document_id: number;
|
||
document_id: number;
|
||
status_label: string;
|
||
current_run_no: string | null;
|
||
source_item: ShippingWorkflowItem;
|
||
}> {
|
||
const unique: Array<{
|
||
filename: string | null;
|
||
content_hash: string | null;
|
||
root_document_id: number;
|
||
document_id: number;
|
||
status_label: string;
|
||
current_run_no: string | null;
|
||
source_item: ShippingWorkflowItem;
|
||
recency: number;
|
||
identity: string;
|
||
}> = [];
|
||
const seen = new Map<string, number>();
|
||
for (const item of items || []) {
|
||
const contentHash = String(item.content_hash || '').trim().toLowerCase();
|
||
const rootId = Number(item.root_document_id || 0);
|
||
const documentId = Number(item.current_document_id || 0);
|
||
const identity = contentHash
|
||
? `hash:${contentHash}`
|
||
: rootId > 0
|
||
? `root:${rootId}`
|
||
: documentId > 0
|
||
? `doc:${documentId}`
|
||
: `item:${String(item.item_no || '').trim()}`;
|
||
const filename = String(item.current_document_filename || '').trim() || null;
|
||
const row = {
|
||
filename,
|
||
content_hash: contentHash || null,
|
||
root_document_id: rootId,
|
||
document_id: documentId,
|
||
status_label: resolveItemDisplayStatus(item),
|
||
current_run_no: String(item.current_run_no || '').trim() || null,
|
||
source_item: item,
|
||
recency: Date.parse(String(item.last_activity_at || item.updated_at || '').trim()) || 0,
|
||
identity,
|
||
};
|
||
const existingIndex = seen.get(identity);
|
||
if (existingIndex == null) {
|
||
seen.set(identity, unique.length);
|
||
unique.push(row);
|
||
continue;
|
||
}
|
||
const existing = unique[existingIndex]!;
|
||
if (row.recency > existing.recency
|
||
|| (row.recency === existing.recency && documentId >= existing.document_id)) {
|
||
unique[existingIndex] = row;
|
||
}
|
||
}
|
||
return unique;
|
||
}
|
||
|
||
/**
|
||
* 从 Workflow Items 聚合为用户可见任务列表(后端 processing 未就绪时的前端兜底)。
|
||
* 核心逻辑:先按稳定任务身份(user_task_no / hash…)归并全部 Item,再按 PDF 去重计
|
||
* file_count;禁止先按 run_no 拆桶再丢弃同 OT 的另一份 PDF;单 PDF 才用文件名作 title。
|
||
*/
|
||
export function projectConversationProcessingTasks(
|
||
items: ShippingWorkflowItem[],
|
||
options?: {
|
||
focusTaskNo?: string | null;
|
||
focusRunNo?: string | null;
|
||
focusUserTaskNo?: string | null;
|
||
},
|
||
): ConversationProcessingUserTask[] {
|
||
const byIdentity = new Map<string, ShippingWorkflowItem[]>();
|
||
for (const item of items || []) {
|
||
const identity = fallbackTaskIdentityKey(item);
|
||
if (!identity || identity === 'item:') continue;
|
||
const bucket = byIdentity.get(identity) || [];
|
||
bucket.push(item);
|
||
byIdentity.set(identity, bucket);
|
||
}
|
||
|
||
const focusUserTask = String(options?.focusUserTaskNo || '').trim();
|
||
const focusRun = String(options?.focusRunNo || '').trim();
|
||
const tasks: ConversationProcessingUserTask[] = [];
|
||
|
||
for (const [identity, groupItems] of byIdentity) {
|
||
void identity;
|
||
if (!groupItems.length) continue;
|
||
// [STEP 1] 取最近活动 Item 作为任务级代表 Run;PDF 则跨 Run 独立选择最新版本。
|
||
const sorted = [...groupItems].sort((a, b) => {
|
||
const aAt = Date.parse(String(a.last_activity_at || a.updated_at || '').trim()) || 0;
|
||
const bAt = Date.parse(String(b.last_activity_at || b.updated_at || '').trim()) || 0;
|
||
if (bAt !== aAt) return bAt - aAt;
|
||
return String(b.current_run_no || '').localeCompare(String(a.current_run_no || ''));
|
||
});
|
||
const primaryItem = sorted[0];
|
||
if (!primaryItem) continue;
|
||
const runNo = String(
|
||
primaryItem.current_run_no || primaryItem.workflow_no || primaryItem.item_no || '',
|
||
).trim();
|
||
// [STEP 2] 同 OT 的旧 Run 仍可能承载未重识别 PDF,禁止整批过滤到代表 Run。
|
||
const uniqueDocuments = dedupeFallbackDocuments(groupItems);
|
||
const effectiveItems = uniqueDocuments.map((row) => row.source_item);
|
||
// 任务级分组/操作只由最近代表 Item 决定;旧 Run 仅贡献未受影响的 PDF,不得反向污染状态。
|
||
const statuses = [normalizeLifecycleStatus(resolveItemDisplayStatus(primaryItem))];
|
||
const primaryActions = Array.isArray(primaryItem.available_actions)
|
||
? primaryItem.available_actions
|
||
: [];
|
||
const hasHumanAction = primaryActions.some((value) => {
|
||
const code = String(value || '').trim().toLowerCase();
|
||
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
|
||
});
|
||
let group: ConversationProcessingTaskGroup = 'history';
|
||
for (const status of statuses) {
|
||
const g = classifyConversationProcessingGroup(status, { needsCustomerConfirm: hasHumanAction });
|
||
if (g === 'needs_action') {
|
||
group = 'needs_action';
|
||
break;
|
||
}
|
||
if (g === 'processing') {
|
||
group = 'processing';
|
||
continue;
|
||
}
|
||
if (g === 'completed' && group !== 'processing') {
|
||
group = 'completed';
|
||
}
|
||
}
|
||
const primaryStatus = statuses.find((s) => NEEDS_ACTION_LIFECYCLES.has(s))
|
||
|| statuses.find((s) => PROCESSING_LIFECYCLES.has(s))
|
||
|| statuses.find((s) => COMPLETED_LIFECYCLES.has(s))
|
||
|| statuses[0]
|
||
|| 'queued';
|
||
// [UI-01] 必须原样输出后端真实 OT;仅缺省时才用本地兼容号,且不得用于写接口。
|
||
const authoritativeTaskNo = String(
|
||
effectiveItems.map((row) => row.user_task_no).find((value) => String(value || '').trim())
|
||
|| groupItems.map((row) => row.user_task_no).find((value) => String(value || '').trim())
|
||
|| '',
|
||
).trim();
|
||
const userTaskNo = authoritativeTaskNo || `OT-${runNo}`;
|
||
const documentNames = uniqueDocuments
|
||
.map((row) => String(row.filename || '').trim())
|
||
.filter(Boolean);
|
||
const isMulti = uniqueDocuments.length > 1;
|
||
const title = isMulti
|
||
? null
|
||
: (documentNames[0] || String(primaryItem.current_document_filename || '').trim() || null);
|
||
const activityRaw = String(primaryItem.last_activity_at || primaryItem.updated_at || '').trim();
|
||
const documentObjects = uniqueDocuments.map((row) => ({
|
||
kind: 'document' as const,
|
||
object_key: row.document_id > 0
|
||
? `DOC-${row.document_id}`
|
||
: `DOC-${row.root_document_id || row.filename || 'unknown'}`,
|
||
label: row.filename || `DOC-${row.document_id || row.root_document_id}`,
|
||
status_label: row.status_label,
|
||
document_id: row.document_id || null,
|
||
root_document_id: row.root_document_id || null,
|
||
filename: row.filename,
|
||
content_hash: row.content_hash,
|
||
run_no: row.current_run_no,
|
||
current_run_no: row.current_run_no,
|
||
user_task_no: userTaskNo,
|
||
focused: false,
|
||
}));
|
||
tasks.push({
|
||
user_task_no: userTaskNo,
|
||
user_task_authoritative: Boolean(authoritativeTaskNo),
|
||
title,
|
||
display_kind: isMulti ? 'multi_document_task' : 'single_document_task',
|
||
document_names: documentNames,
|
||
group,
|
||
status_label: primaryStatus,
|
||
file_count: uniqueDocuments.length,
|
||
run_no: runNo || null,
|
||
workflow_no: String(primaryItem.workflow_no || '').trim() || null,
|
||
can_append: false,
|
||
append_block_reason: 'input_already_frozen',
|
||
last_activity_at: activityRaw || null,
|
||
focused: Boolean(
|
||
(focusUserTask && focusUserTask === userTaskNo)
|
||
|| (focusRun && focusRun === runNo),
|
||
),
|
||
objects: [
|
||
...projectConversationProcessingObjects(effectiveItems, {
|
||
focusTaskNo: options?.focusTaskNo,
|
||
focusRunNo: runNo,
|
||
}),
|
||
...documentObjects,
|
||
],
|
||
});
|
||
}
|
||
|
||
return tasks;
|
||
}
|
||
|
||
/**
|
||
* 将任务列表按分组装入 ConversationProcessingProjection。
|
||
* 核心逻辑:summary.total_* 含 history;合成路径无截断,has_more=false。
|
||
*/
|
||
export function groupConversationProcessingTasks(
|
||
tasks: ConversationProcessingUserTask[],
|
||
options?: {
|
||
focusedTaskNo?: string | null;
|
||
recentTaskNo?: string | null;
|
||
/** 上一版投影(语义稳定化复用旧对象引用)。 */
|
||
previousProjection?: ConversationProcessingProjection | null;
|
||
},
|
||
): ConversationProcessingProjection {
|
||
const previousTasks: ConversationProcessingUserTask[] = options?.previousProjection
|
||
? [
|
||
...(options.previousProjection.needs_action || []),
|
||
...(options.previousProjection.processing || []),
|
||
...(options.previousProjection.completed || []),
|
||
...(options.previousProjection.history || []),
|
||
]
|
||
: [];
|
||
const stabilized = stabilizeTaskObjects(previousTasks, tasks);
|
||
const needs_action_raw = stabilized.filter((t) => t.group === 'needs_action');
|
||
const processing_raw = stabilized.filter((t) => t.group === 'processing');
|
||
const completed_raw = stabilized.filter((t) => t.group === 'completed');
|
||
const history_raw = stabilized.filter((t) => t.group === 'history');
|
||
const needs_action = stabilizeTaskObjects(options?.previousProjection?.needs_action || [], needs_action_raw);
|
||
const processing = stabilizeTaskObjects(options?.previousProjection?.processing || [], processing_raw);
|
||
const completed = stabilizeTaskObjects(options?.previousProjection?.completed || [], completed_raw);
|
||
const history = stabilizeTaskObjects(options?.previousProjection?.history || [], history_raw);
|
||
const all = [...needs_action, ...processing, ...completed, ...history];
|
||
const summary: ConversationProcessingSummary = {
|
||
total_tasks: all.length,
|
||
total_files: all.reduce((sum, task) => sum + Number(task.file_count || 0), 0),
|
||
processing: processing.length,
|
||
needs_action: needs_action.length,
|
||
completed: completed.length,
|
||
history: history.length,
|
||
returned: {
|
||
needs_action: needs_action.length,
|
||
processing: processing.length,
|
||
completed: completed.length,
|
||
history: history.length,
|
||
},
|
||
truncated: { active: false, history: false },
|
||
has_more_active: false,
|
||
has_more_history: false,
|
||
};
|
||
return {
|
||
summary,
|
||
focused_task_no: options?.focusedTaskNo || null,
|
||
recent_task_no: options?.recentTaskNo || null,
|
||
needs_action,
|
||
processing,
|
||
completed,
|
||
history,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 用 Workflow 兜底投影补齐后端 processing 的多 PDF 标题/文件数。
|
||
* 核心逻辑:同 user_task_no / run_no 时,若兜底 file_count 更大,采用兜底的
|
||
* display_kind / title / document_names / objects(文档子对象)。
|
||
*/
|
||
/**
|
||
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
|
||
* 核心逻辑:新版 embedded.status_groups 是后端已完成“当前文件代表项 → EML 容器”
|
||
* 裁决的唯一列表读源,存在时绝不能再从 work_items 重建;否则旧 Run 会重新进入
|
||
* 文件清单。旧接口未返回 status_groups 时,才从 work_items 合成兼容任务列表。
|
||
* 语义稳定化:对比 previousProjection 的签名,复用未变的任务对象引用。
|
||
*
|
||
* @param workItems - unified.work_items
|
||
* @param embedded - unified.conversation_processing
|
||
* @param previousProjection - 上一版投影(用于任务对象稳定化)
|
||
* @returns 会话处理投影;无可用数据时 null
|
||
*/
|
||
export function resolveConversationProcessingFromUnified(
|
||
_workItems: ShippingProcessingProjection[] | null | undefined,
|
||
embedded: ConversationProcessingProjection | null | undefined,
|
||
_previousProjection?: ConversationProcessingProjection | null,
|
||
_stabilizer?: { hasSeenOrderTaskBefore?(conversationId?: string | null): boolean; markSeen?(conversationId?: string | null): void; reset?(conversationId?: string | null): void; conversationId?: string | null },
|
||
): ConversationProcessingProjection | null {
|
||
// [AUTHORITY] 会话进度只能消费后端一次裁决的状态→EML→PDF树;从 work_items
|
||
// 二次聚合会让前端重新承担业务状态裁决并重新引入旧四组的重复响应。
|
||
if (!embedded || typeof embedded !== 'object' || !embedded.status_groups) return null;
|
||
return normalizeConversationProcessingProjection(embedded);
|
||
}
|
||
|
||
/**
|
||
* 归一化旧 conversation_processing 投影的生命周期状态。
|
||
* 核心逻辑:将所有组的 userStatus/status_label 统一为新形态,waiting_human 归并为 waiting_review,
|
||
* 避免 work_items 为空回退时,旧投影状态与统一 work_items 状态来回切换造成文案闪烁。
|
||
*
|
||
* @param projection - 原始 embedded conversation_processing 投影
|
||
* @returns 归一化后的投影(新对象,浅拷贝 tasks 并覆盖 userStatus/status_label)
|
||
*/
|
||
export function normalizeConversationProcessingProjection(
|
||
projection: ConversationProcessingProjection,
|
||
): ConversationProcessingProjection {
|
||
const normalizeUiState = (
|
||
rawState: ConversationProcessingUserTask['uiState'] | undefined,
|
||
): ConversationProcessingUserTask['uiState'] | undefined => {
|
||
if (!rawState || typeof rawState !== 'object') return undefined;
|
||
const state = rawState as ConversationProcessingUserTask['uiState'] & {
|
||
lifecycle_stage?: ConversationProcessingUserTask['uiState'] extends { lifecycleStage?: infer S } ? S : never;
|
||
lifecycle_entries?: Array<Record<string, unknown>>;
|
||
};
|
||
const normalizeAction = (
|
||
action: ShippingProcessingPrimaryAction | null | undefined,
|
||
): ShippingProcessingPrimaryAction | null => {
|
||
if (!action || typeof action !== 'object') return null;
|
||
const rawAction = action as ShippingProcessingPrimaryAction & {
|
||
i18n_key?: string | null;
|
||
execution_mode?: string | null;
|
||
target_surface?: string | null;
|
||
target_lifecycle_stage?: string | null;
|
||
};
|
||
return {
|
||
...rawAction,
|
||
i18nKey: rawAction.i18nKey ?? rawAction.i18n_key ?? null,
|
||
// embedded conversation_processing 与 work_items 同为后端 snake_case DTO;
|
||
// 跳转目标必须在 API 边界完整规范化,否则已授权的主按钮会点击无响应。
|
||
executionMode: (
|
||
rawAction.executionMode === 'navigate' || rawAction.executionMode === 'execute'
|
||
? rawAction.executionMode
|
||
: (rawAction.execution_mode === 'navigate' || rawAction.execution_mode === 'execute'
|
||
? rawAction.execution_mode
|
||
: undefined)
|
||
),
|
||
targetSurface: (
|
||
rawAction.targetSurface === 'order_lifecycle_workbench'
|
||
? rawAction.targetSurface
|
||
: (rawAction.target_surface === 'order_lifecycle_workbench'
|
||
? rawAction.target_surface
|
||
: null)
|
||
),
|
||
targetLifecycleStage: (
|
||
['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
|
||
String(rawAction.targetLifecycleStage),
|
||
)
|
||
? rawAction.targetLifecycleStage
|
||
: (['intake_parse', 'order_review', 'fulfillment_prep', 'freight_upload', 'upload_complete'].includes(
|
||
String(rawAction.target_lifecycle_stage),
|
||
)
|
||
? rawAction.target_lifecycle_stage
|
||
: null)
|
||
) as ShippingProcessingPrimaryAction['targetLifecycleStage'],
|
||
};
|
||
};
|
||
const normalizeReason = (reason: ShippingProcessingBlockingReason | null | undefined) => {
|
||
if (!reason || typeof reason !== 'object') return null;
|
||
const rawReason = reason as ShippingProcessingBlockingReason & { i18n_key?: string | null };
|
||
return {
|
||
...rawReason,
|
||
i18nKey: rawReason.i18nKey ?? rawReason.i18n_key ?? null,
|
||
};
|
||
};
|
||
return {
|
||
...state,
|
||
blocking_reason: normalizeReason(state.blocking_reason),
|
||
primary_action: normalizeAction(state.primary_action),
|
||
// 次动作与主动作同属后端 ui_state 授权契约。若仅透传原始 snake_case,
|
||
// 文件行点击会看不到导航目标并错误落入旧兼容分支。
|
||
secondary_actions: (state.secondary_actions || [])
|
||
.map((action) => {
|
||
const normalized = normalizeAction(action);
|
||
return normalized && 'code' in action && 'enabled' in action
|
||
? { ...normalized, code: String(action.code), enabled: action.enabled !== false }
|
||
: null;
|
||
})
|
||
.filter((action): action is ShippingProcessingPrimaryAction & { code: string; enabled: boolean } => Boolean(action)),
|
||
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'];
|
||
blocking_reason?: ConversationProcessingUserTask['blockingReason'];
|
||
primary_action?: ConversationProcessingUserTask['primaryAction'] | string | null;
|
||
aggregate_summary?: ConversationProcessingUserTask['aggregateSummary'];
|
||
aggregate_children?: unknown[];
|
||
};
|
||
const aggregateChildren = Array.isArray(raw.aggregate_children)
|
||
? raw.aggregate_children
|
||
.map(normalizeShippingProcessingProjection)
|
||
.filter((item): item is ShippingProcessingProjection => Boolean(item))
|
||
: [];
|
||
return {
|
||
...task,
|
||
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'] }).ui_state,
|
||
),
|
||
group: task.group,
|
||
};
|
||
};
|
||
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 {
|
||
...authoritativeProjection,
|
||
// [AUTHORITY] summary 与 status_groups 同属后端一次裁决。前端不得从局部 EML
|
||
// 行重算任务/文件统计,也不得重新生成旧四组镜像。
|
||
summary: projection.summary,
|
||
status_groups: normalizedGroups,
|
||
lifecycle_nodes: projection.lifecycle_nodes || [],
|
||
unclassified_summary: projection.unclassified_summary || { count: 0 },
|
||
// [AUTHORITY] 批次级 ui_state 与任务级 uiState 同为后端 snake_case DTO,必须统一
|
||
// 归一化(blocking_reason/primary_action 增补 i18nKey;lifecycle_stage→lifecycleStage),
|
||
// 否则三面阶段口径与工作台导航会读到两套字段名。
|
||
ui_state: normalizeUiState(projection.ui_state) || undefined,
|
||
output_artifacts: projection.output_artifacts || [],
|
||
};
|
||
}
|