feat(shipping): 实现订单批处理聊天聚合展示与优化后端逻辑

This commit is contained in:
hugo committed 2026-08-13 17:40:43 +08:00
1 parent 11cef575b4
commit 523b791c92
38 files changed
+2868 -414

No files matched your search

@@ -50,6 +50,15 @@ export function buildTaskSemanticKey(
): 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,
}));
return JSON.stringify({
taskNo: task.user_task_no,
group: task.group,
@@ -83,6 +92,7 @@ export function buildTaskSemanticKey(
: null,
availableActions: normalizeActionCodes(task.available_actions || []),
canAppend: task.can_append ?? null,
aggregateChildren,
});
}
@@ -791,7 +801,22 @@ export function groupConversationProcessingTasks(
export function mapShippingProcessingStatusToTaskGroup(
item: ShippingProcessingProjection,
): ConversationProcessingTaskGroup {
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
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())
@@ -859,7 +884,10 @@ export function resolveConversationProcessingFromUnified(
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
// 则延迟回退 embedded,保持 previousProjection 不变,避免闪烁;
// - 否则仍走 embedded,但强制 normalize 成 waiting_review。
const hasOrderTask = items.some((item) => item.workItemType === 'order_task');
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);
@@ -945,24 +973,27 @@ export function normalizeConversationProcessingProjection(
}
/**
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
* 从统一 work_items 合成 ConversationProcessingProjection(order_task 与 EML order_intake)。
*
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组;
* 核心逻辑:order_task 与 EML order_intake 均进入状态区;非 EML intake 不入组;
* available_actions 使用标准化(去重、排序)动作码;按 previousProjection 复用旧对象引用。
*
* @param workItems - 统一投影 work_items
* @param previousProjection - 上一版投影(语义稳定化复用旧对象)
* @returns 兼容投影;无 order_task 时返回 null
* @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');
const orderTasks = items.filter((row) => (
row.workItemType === 'order_task'
|| (row.workItemType === 'order_intake' && row.sourceType === 'eml')
));
if (!orderTasks.length) return null;
const rawTasks: ConversationProcessingUserTask[] = [];
const rawTaskEntries: Array<{ task: ConversationProcessingUserTask; item: ShippingProcessingProjection }> = [];
for (const item of orderTasks) {
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
@@ -1019,15 +1050,111 @@ export function projectConversationProcessingFromWorkItems(
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,
retryable: typeof item.retryable === 'boolean' ? item.retryable : false,
userCurrentGateCode: item.userCurrentGateCode ?? null,
legacyStatus: item.legacyStatus ?? null,
legacyStage: item.legacyStage ?? null,
aggregateSummary: item.aggregateSummary ?? null,
aggregateChildren: item.aggregateChildren ?? [],
};
rawTasks.push(task);
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 documentNames = [...new Set(entries.flatMap(({ task }) => task.document_names || []).filter(Boolean))];
const fileCount = entries.reduce((sum, { task }) => sum + Number(task.file_count || 0), 0);
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: entries.flatMap(({ item }) => item.aggregateChildren || [item]),
userGroup: aggregateUserGroup as ConversationProcessingUserTask['userGroup'],
});
}
if (!rawTasks.length) return null;
@@ -1082,6 +1209,15 @@ export function projectConversationProcessingFromWorkItems(
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,
@@ -1097,5 +1233,6 @@ export function projectConversationProcessingFromWorkItems(
processing,
completed,
history,
status_groups,
};
}