feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环
This commit is contained in:
1 parent
cfa19a0b7b
commit
8e0bbf7a81
180 files changed
+31210
-1864
No files matched your search
@@ -15,6 +15,9 @@ import type {
|
||||
ConversationProcessingSummary,
|
||||
ConversationProcessingTaskGroup,
|
||||
ConversationProcessingUserTask,
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingFacts,
|
||||
ShippingProcessingPrimaryAction,
|
||||
ShippingProcessingProjection,
|
||||
ShippingWorkflowItem,
|
||||
WorkflowNodeStatus,
|
||||
@@ -46,22 +49,36 @@ export function buildTaskSemanticKey(
|
||||
task: ConversationProcessingUserTask | null | undefined,
|
||||
): string {
|
||||
if (!task) return '';
|
||||
const rawStatus = (task as ConversationProcessingUserTask & { userStatus?: string | null }).userStatus ?? task.status_label;
|
||||
return JSON.stringify({
|
||||
taskNo: task.user_task_no,
|
||||
group: task.group,
|
||||
status: task.status_label,
|
||||
status: normalizeLifecycleStatus(rawStatus),
|
||||
runNo: task.run_no,
|
||||
displayKind: task.display_kind,
|
||||
fileCount: task.file_count,
|
||||
title: task.title,
|
||||
primaryAction: task.primary_action || null,
|
||||
currentGate: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
|
||||
primaryAction: (task as ConversationProcessingUserTask & { primaryAction?: { code?: string } | null }).primaryAction?.code
|
||||
?? task.primary_action
|
||||
?? 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 || null,
|
||||
nextActionCode: (task as ConversationProcessingUserTask & { current_gate?: { blockingReasonCode?: string; nextActionCode?: string } })
|
||||
.current_gate?.nextActionCode || null,
|
||||
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.available_actions || []),
|
||||
@@ -125,6 +142,7 @@ export function stabilizeTaskObjects(
|
||||
const NEEDS_ACTION_LIFECYCLES = new Set([
|
||||
'blocked',
|
||||
'waiting_review',
|
||||
'waiting_human',
|
||||
'pending_review',
|
||||
'manual_upload_pending',
|
||||
'failed',
|
||||
@@ -132,6 +150,75 @@ const NEEDS_ACTION_LIFECYCLES = new Set([
|
||||
'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',
|
||||
@@ -403,14 +490,11 @@ export function classifyConversationProcessingGroup(
|
||||
options?: { hasBlockingGate?: boolean; needsCustomerConfirm?: boolean },
|
||||
): ConversationProcessingTaskGroup {
|
||||
if (options?.needsCustomerConfirm) return 'needs_action';
|
||||
const normalized = String(status || '').trim();
|
||||
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 === 'review_required' || normalized === 'partially_completed') {
|
||||
return 'needs_action';
|
||||
}
|
||||
if (normalized === 'failed') return 'needs_action';
|
||||
if (normalized === 'completed') return 'completed';
|
||||
if (normalized === 'processing' || normalized === 'queued') return 'processing';
|
||||
@@ -433,7 +517,8 @@ function fallbackTaskIdentityKey(item: ShippingWorkflowItem): string {
|
||||
if (filename) return `fn:${filename}`;
|
||||
const runNo = String(item.current_run_no || '').trim();
|
||||
if (runNo) return `run:${runNo}`;
|
||||
return `item:${String(item.item_no || '').trim()}`;
|
||||
const itemNo = String(item.item_no || '').trim();
|
||||
return `item:${itemNo}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -544,7 +629,7 @@ export function projectConversationProcessingTasks(
|
||||
const uniqueDocuments = dedupeFallbackDocuments(groupItems);
|
||||
const effectiveItems = uniqueDocuments.map((row) => row.source_item);
|
||||
// 任务级分组/操作只由最近代表 Item 决定;旧 Run 仅贡献未受影响的 PDF,不得反向污染状态。
|
||||
const statuses = [resolveItemDisplayStatus(primaryItem)];
|
||||
const statuses = [normalizeLifecycleStatus(resolveItemDisplayStatus(primaryItem))];
|
||||
const primaryActions = Array.isArray(primaryItem.available_actions)
|
||||
? primaryItem.available_actions
|
||||
: [];
|
||||
@@ -706,8 +791,8 @@ export function groupConversationProcessingTasks(
|
||||
export function mapShippingProcessingStatusToTaskGroup(
|
||||
item: ShippingProcessingProjection,
|
||||
): ConversationProcessingTaskGroup {
|
||||
const status = String(item.status || '').trim().toLowerCase();
|
||||
const gateAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase();
|
||||
const status = String(item.userStatus ?? item.status ?? '').trim().toLowerCase();
|
||||
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_'));
|
||||
@@ -715,6 +800,8 @@ export function mapShippingProcessingStatusToTaskGroup(
|
||||
status === 'waiting_review'
|
||||
|| status === 'blocked'
|
||||
|| status === 'failed'
|
||||
|| status === 'waiting_human'
|
||||
|| status === 'retryable'
|
||||
|| hasHumanAction
|
||||
) {
|
||||
return 'needs_action';
|
||||
@@ -737,7 +824,9 @@ export function mergeConversationProcessingFocusMetadata(
|
||||
embedded: ConversationProcessingProjection | null | undefined,
|
||||
): ConversationProcessingProjection | null {
|
||||
if (!derived) {
|
||||
return embedded && typeof embedded === 'object' ? embedded : null;
|
||||
return embedded && typeof embedded === 'object'
|
||||
? normalizeConversationProcessingProjection(embedded)
|
||||
: null;
|
||||
}
|
||||
if (!embedded || typeof embedded !== 'object') return derived;
|
||||
return {
|
||||
@@ -762,18 +851,99 @@ 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 : [];
|
||||
if (items.length > 0) {
|
||||
// [TRANSITION] 只有统一投影里明确存在 order_task,才认为 OT 维度已经成形。
|
||||
// 仅 order_intake 存在时视为过渡阶段:
|
||||
// - 如果此会话/全局在此之前已见到过 order_task(2s 窗口内),
|
||||
// 则延迟回退 embedded,保持 previousProjection 不变,避免闪烁;
|
||||
// - 否则仍走 embedded,但强制 normalize 成 waiting_review。
|
||||
const hasOrderTask = items.some((item) => item.workItemType === 'order_task');
|
||||
const convId = stabilizer?.conversationId;
|
||||
if (hasOrderTask) {
|
||||
stabilizer?.markSeen?.(convId);
|
||||
return mergeConversationProcessingFocusMetadata(
|
||||
projectConversationProcessingFromWorkItems(items, previousProjection),
|
||||
embedded,
|
||||
);
|
||||
}
|
||||
if (embedded && typeof embedded === 'object') return 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 normalizeTask = (task: ConversationProcessingUserTask): ConversationProcessingUserTask => {
|
||||
const rawStatus = task.userStatus ?? task.status_label;
|
||||
const normalizedStatus = normalizeLifecycleStatus(rawStatus);
|
||||
const availableActions = Array.isArray(task.available_actions) ? task.available_actions : [];
|
||||
const hasHumanAction = availableActions.some((value) => {
|
||||
const code = String(value || '').trim().toLowerCase();
|
||||
return HUMAN_ACTION_CODES.has(code) || code.startsWith('retry_failed_');
|
||||
});
|
||||
const recomputedGroup = classifyConversationProcessingGroup(normalizedStatus || rawStatus, {
|
||||
needsCustomerConfirm: hasHumanAction,
|
||||
});
|
||||
const finalGroup: ConversationProcessingTaskGroup = (() => {
|
||||
// [LEGACY-UNIFY] waiting_human 旧投影若被归在 processing / history,强制迁入 needs_action。
|
||||
if (recomputedGroup === 'needs_action') return 'needs_action';
|
||||
if (normalizedStatus === 'waiting_review') return 'needs_action';
|
||||
return task.group || recomputedGroup;
|
||||
})();
|
||||
return {
|
||||
...task,
|
||||
status_label: normalizedStatus || (task.status_label ?? ''),
|
||||
// userStatus 保持原有强类型;会话侧展示统一走 status_label/group,避免放宽成 string 破坏类型契约。
|
||||
userStatus: task.userStatus ?? null,
|
||||
group: finalGroup,
|
||||
};
|
||||
};
|
||||
const normalizedAll = [
|
||||
...(projection.needs_action || []),
|
||||
...(projection.processing || []),
|
||||
...(projection.completed || []),
|
||||
...(projection.history || []),
|
||||
].map(normalizeTask);
|
||||
const needs_action = normalizedAll.filter((task) => task.group === 'needs_action');
|
||||
const processing = normalizedAll.filter((task) => task.group === 'processing');
|
||||
const completed = normalizedAll.filter((task) => task.group === 'completed');
|
||||
const history = normalizedAll.filter((task) => task.group === 'history');
|
||||
return {
|
||||
...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,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
|
||||
*
|
||||
@@ -801,7 +971,39 @@ export function projectConversationProcessingFromWorkItems(
|
||||
const docCount = Number(item.sourceSummary?.documentCount || 0);
|
||||
const filename = String(item.sourceSummary?.filename || '').trim();
|
||||
const normalizedActions = normalizeActionCodes(item.availableActions || []);
|
||||
const gateNextAction = String(item.currentGate?.nextActionCode || '').trim().toLowerCase() || null;
|
||||
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,
|
||||
@@ -809,13 +1011,21 @@ export function projectConversationProcessingFromWorkItems(
|
||||
display_kind: docCount > 1 ? 'multi_document_task' : 'single_document_task',
|
||||
document_names: filename ? [filename] : [],
|
||||
group,
|
||||
status_label: String(item.status || '') || null,
|
||||
status_label: effectiveStatus,
|
||||
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
|
||||
run_no: String(item.runNo || '').trim() || null,
|
||||
can_append: false,
|
||||
last_activity_at: item.lastActivityAt || null,
|
||||
available_actions: normalizedActions,
|
||||
primary_action: gateNextAction || normalizedActions[0] || null,
|
||||
userStatus: item.userStatus ?? null,
|
||||
blockingReason: userBlocking,
|
||||
primaryAction: userPrimaryAction,
|
||||
facts: userFacts,
|
||||
retryable: typeof item.retryable === 'boolean' ? item.retryable : false,
|
||||
userCurrentGateCode: item.userCurrentGateCode ?? null,
|
||||
legacyStatus: item.legacyStatus ?? null,
|
||||
legacyStage: item.legacyStage ?? null,
|
||||
};
|
||||
rawTasks.push(task);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user