清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
1500 lines
66 KiB
TypeScript
1500 lines
66 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;
|
||
* 可由统一 work_items(order_task)合成兼容分组。
|
||
* 语义签名与任务稳定化:轮询返回相同业务状态时复用旧对象,避免按钮闪烁。
|
||
*/
|
||
|
||
import type {
|
||
ConversationProcessingObject,
|
||
ConversationProcessingProjection,
|
||
ConversationProcessingSummary,
|
||
ConversationProcessingTaskGroup,
|
||
ConversationProcessingUserTask,
|
||
ShippingProcessingBlockingReason,
|
||
ShippingProcessingFacts,
|
||
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,
|
||
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),
|
||
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
|
||
? (task.uiState.primary_action?.code ?? null)
|
||
: ((task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||
?? task.primary_action
|
||
?? 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
|
||
?? (task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||
?? null,
|
||
}
|
||
: null,
|
||
availableActions: normalizeActionCodes(
|
||
task.uiState
|
||
? task.uiState.secondary_actions.filter((action) => action.enabled).map((action) => action.code)
|
||
: (task.available_actions || []),
|
||
),
|
||
canAppend: task.can_append ?? null,
|
||
aggregateChildren,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 构建整个会话处理投影的语义签名:summary + 各分组任务签名。
|
||
*
|
||
* @param projection - 会话处理投影
|
||
* @returns 语义签名字符串;投影为 null 时返回空串
|
||
*/
|
||
export function buildProcessingSemanticKey(
|
||
projection: ConversationProcessingProjection | null | undefined,
|
||
): string {
|
||
if (!projection) return '';
|
||
return JSON.stringify({
|
||
summary: {
|
||
total_tasks: projection.summary?.total_tasks || 0,
|
||
total_files: projection.summary?.total_files || 0,
|
||
processing: projection.summary?.processing || 0,
|
||
needs_action: projection.summary?.needs_action || 0,
|
||
completed: projection.summary?.completed || 0,
|
||
history: projection.summary?.history || 0,
|
||
},
|
||
focused_task_no: projection.focused_task_no || null,
|
||
recent_task_no: projection.recent_task_no || null,
|
||
needs_action: (projection.needs_action || []).map(buildTaskSemanticKey),
|
||
processing: (projection.processing || []).map(buildTaskSemanticKey),
|
||
completed: (projection.completed || []).map(buildTaskSemanticKey),
|
||
history: (projection.history || []).map(buildTaskSemanticKey),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 按任务号复用旧对象:语义签名相同时返回旧引用,保证 Vue v-for 复用 DOM。
|
||
*
|
||
* @param previousTasks - 上一次渲染的任务列表
|
||
* @param nextRawTasks - 本次轮询生成的新任务列表(原始未稳定化)
|
||
* @returns 稳定化后的任务列表;语义未变的任务沿用旧引用
|
||
*/
|
||
export function stabilizeTaskObjects(
|
||
previousTasks: ConversationProcessingUserTask[],
|
||
nextRawTasks: ConversationProcessingUserTask[],
|
||
): ConversationProcessingUserTask[] {
|
||
const previousByTaskNo = new Map(
|
||
(previousTasks || []).map((task) => [String(task.user_task_no || ''), task]),
|
||
);
|
||
return (nextRawTasks || []).map((nextTask) => {
|
||
const previous = previousByTaskNo.get(String(nextTask.user_task_no || ''));
|
||
if (!previous) return nextTask;
|
||
if (buildTaskSemanticKey(previous) === buildTaskSemanticKey(nextTask)) {
|
||
return previous;
|
||
}
|
||
return nextTask;
|
||
});
|
||
}
|
||
|
||
/** 需要人工处理的生命周期集合。 */
|
||
const NEEDS_ACTION_LIFECYCLES = new Set([
|
||
'blocked',
|
||
'waiting_review',
|
||
'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(文档子对象)。
|
||
*/
|
||
/**
|
||
* 将统一 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 容器”
|
||
* 裁决的唯一列表读源,存在时绝不能再从 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 {
|
||
const items = Array.isArray(workItems) ? workItems : [];
|
||
// [AUTHORITY] conversation_processing.status_groups 与 four_stage_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;
|
||
}
|
||
|
||
/**
|
||
* 归一化旧 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 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>>;
|
||
};
|
||
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', 'upload_complete'].includes(
|
||
String(rawAction.targetLifecycleStage),
|
||
)
|
||
? rawAction.targetLifecycleStage
|
||
: (['intake_parse', 'order_review', 'fulfillment_prep', '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 ?? state.blockingReason),
|
||
primary_action: normalizeAction(state.primary_action ?? state.primaryAction),
|
||
// 次动作与主动作同属后端 ui_state 授权契约。若仅透传原始 snake_case,
|
||
// 文件行点击会看不到导航目标并错误落入旧兼容分支。
|
||
secondary_actions: (state.secondary_actions ?? state.secondaryActions ?? [])
|
||
.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.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))
|
||
: []),
|
||
};
|
||
};
|
||
const normalizeTask = (task: ConversationProcessingUserTask): ConversationProcessingUserTask => {
|
||
const raw = task as ConversationProcessingUserTask & {
|
||
user_status?: ConversationProcessingUserTask['userStatus'];
|
||
user_stage?: ConversationProcessingUserTask['userStage'];
|
||
user_group?: ConversationProcessingUserTask['userGroup'];
|
||
blocking_reason?: ConversationProcessingUserTask['blockingReason'];
|
||
primary_action?: ConversationProcessingUserTask['primaryAction'] | string | null;
|
||
aggregate_summary?: ConversationProcessingUserTask['aggregateSummary'];
|
||
aggregate_children?: unknown[];
|
||
};
|
||
const rawPrimaryAction = raw.primaryAction ?? raw.primary_action ?? null;
|
||
const aggregateChildren = Array.isArray(raw.aggregateChildren)
|
||
? raw.aggregateChildren
|
||
: (Array.isArray(raw.aggregate_children)
|
||
? raw.aggregate_children
|
||
.map(normalizeShippingProcessingProjection)
|
||
.filter((item): item is ShippingProcessingProjection => Boolean(item))
|
||
: []);
|
||
// 新批次投影的 group/user_group 已由后端裁决;旧 embedded 响应没有 status_groups,
|
||
// 仅在该兼容分支维持历史规范化,避免旧服务端响应把待人工留在处理中。
|
||
const rawStatus = task.userStatus ?? task.status_label;
|
||
const normalizedStatus = normalizeLifecycleStatus(rawStatus);
|
||
const 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,
|
||
});
|
||
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,
|
||
aggregateChildren,
|
||
uiState: normalizeUiState(
|
||
(raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).uiState
|
||
?? (raw as ConversationProcessingUserTask & { ui_state?: ConversationProcessingUserTask['uiState'] }).ui_state,
|
||
),
|
||
group: finalGroup,
|
||
};
|
||
};
|
||
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');
|
||
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,
|
||
four_stage_nodes: projection.four_stage_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,
|
||
};
|
||
}
|