feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环
This commit is contained in:
1 parent
cfa19a0b7b
commit
8e0bbf7a81
180 files changed
+31210
-1864
No files matched your search
@@ -16,11 +16,15 @@ import {
|
||||
mapUserTaskObjectsToFileRows,
|
||||
resolveConversationProcessingFromUnified,
|
||||
normalizeActionCodes,
|
||||
normalizeLifecycleStatus,
|
||||
normalizeConversationProcessingProjection,
|
||||
createIntakeOtStabilizer,
|
||||
buildTaskSemanticKey,
|
||||
buildProcessingSemanticKey,
|
||||
stabilizeTaskObjects,
|
||||
} from './conversationProcessingProjection';
|
||||
import type {
|
||||
ConversationProcessingProjection,
|
||||
ShippingProcessingProjection,
|
||||
ShippingWorkflowItem,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
@@ -896,4 +900,283 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
|
||||
expect(stabilized[0].status_label).toBe('waiting_review');
|
||||
expect(stabilized[0].available_actions).toEqual(['open_order_review', 'view_details']);
|
||||
});
|
||||
|
||||
it('normalizeLifecycleStatus: waiting_human / pending_review / review_required 一律归并为 waiting_review', () => {
|
||||
expect(normalizeLifecycleStatus('waiting_human')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('WAITING_HUMAN ')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('pending_review')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('review_required')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('partially_completed')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('waiting_manual_upload')).toBe('manual_upload_pending');
|
||||
expect(normalizeLifecycleStatus('retryable')).toBe('failed');
|
||||
expect(normalizeLifecycleStatus('completed')).toBe('completed');
|
||||
expect(normalizeLifecycleStatus('')).toBe('');
|
||||
expect(normalizeLifecycleStatus(null)).toBe('');
|
||||
});
|
||||
|
||||
it('buildTaskSemanticKey: waiting_human 与 waiting_review 语义相同 → 同签名(不闪烁)', () => {
|
||||
const shared = {
|
||||
user_task_no: 'OT-SAME',
|
||||
group: 'needs_action' as const,
|
||||
run_no: 'RUN-1',
|
||||
display_kind: 'single_document_task' as const,
|
||||
file_count: 1,
|
||||
title: 'a.pdf',
|
||||
primary_action: 'open_order_review',
|
||||
available_actions: ['open_order_review', 'view_details'],
|
||||
can_append: false,
|
||||
user_task_authoritative: true,
|
||||
objects: [],
|
||||
};
|
||||
const t1 = { ...shared, status_label: 'waiting_human' };
|
||||
const t2 = { ...shared, status_label: 'waiting_review' };
|
||||
expect(buildTaskSemanticKey(t1)).toBe(buildTaskSemanticKey(t2));
|
||||
// updated_at 不影响,这里再确认 userStatus 为 waiting_human 也一致。
|
||||
const t3 = { ...shared, status_label: 'queued', userStatus: 'waiting_human' } as typeof t1 & { userStatus: string };
|
||||
const t4 = { ...shared, status_label: 'queued', userStatus: 'waiting_review' } as typeof t1 & { userStatus: string };
|
||||
expect(buildTaskSemanticKey(t3)).toBe(buildTaskSemanticKey(t4));
|
||||
});
|
||||
|
||||
it('normalizeConversationProcessingProjection: embedded waiting_human → waiting_review / needs_action', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 0, completed: 0, history: 0 },
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action: [],
|
||||
processing: [
|
||||
{
|
||||
user_task_no: 'OT-LEGACY',
|
||||
user_task_authoritative: false,
|
||||
title: 'a.pdf',
|
||||
display_kind: 'single_document_task',
|
||||
document_names: ['a.pdf'],
|
||||
// 旧投影错误地把 waiting_human 放进了 processing 组
|
||||
group: 'processing',
|
||||
status_label: 'waiting_human',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-LEG',
|
||||
can_append: false,
|
||||
available_actions: ['enter_manual_review', 'view_details'],
|
||||
primary_action: 'enter_manual_review',
|
||||
},
|
||||
],
|
||||
completed: [],
|
||||
history: [],
|
||||
};
|
||||
const normalized = normalizeConversationProcessingProjection(embedded);
|
||||
const task = normalized.needs_action[0];
|
||||
expect(task).toBeDefined();
|
||||
expect(task!.status_label).toBe('waiting_review');
|
||||
// waiting_human → waiting_review → 必须迁入 needs_action
|
||||
expect(task!.group).toBe('needs_action');
|
||||
expect(normalized.processing.length).toBe(0);
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified: work_items 为空时,embedded waiting_human 任务迁入 needs_action 且统一文案', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action: [],
|
||||
processing: [
|
||||
{
|
||||
user_task_no: 'OT-LEG2',
|
||||
user_task_authoritative: false,
|
||||
title: 'b.pdf',
|
||||
display_kind: 'single_document_task',
|
||||
document_names: ['b.pdf'],
|
||||
group: 'processing',
|
||||
status_label: 'waiting_human',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-LEG2',
|
||||
can_append: false,
|
||||
available_actions: [],
|
||||
primary_action: 'view_details',
|
||||
},
|
||||
],
|
||||
completed: [],
|
||||
history: [],
|
||||
};
|
||||
const result = resolveConversationProcessingFromUnified([], embedded);
|
||||
expect(result).not.toBeNull();
|
||||
// waiting_human 任务从 processing 组迁入 needs_action
|
||||
expect(result!.processing.length).toBe(0);
|
||||
expect(result!.needs_action.length).toBe(1);
|
||||
expect(result!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
expect(result!.needs_action[0]!.title).toBe('b.pdf');
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified: work_items 仅含 order_intake 时,仍走 embedded normalize 路径(过渡窗口不跳状态)', () => {
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
|
||||
focused_task_no: 'OT-LEG3',
|
||||
recent_task_no: 'OT-LEG3',
|
||||
needs_action: [],
|
||||
processing: [
|
||||
{
|
||||
user_task_no: 'OT-LEG3',
|
||||
user_task_authoritative: false,
|
||||
title: 'c.pdf',
|
||||
display_kind: 'single_document_task',
|
||||
document_names: ['c.pdf'],
|
||||
group: 'processing',
|
||||
status_label: 'waiting_human',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-LEG3',
|
||||
can_append: false,
|
||||
available_actions: ['enter_manual_review'],
|
||||
primary_action: 'enter_manual_review',
|
||||
},
|
||||
],
|
||||
completed: [],
|
||||
history: [],
|
||||
};
|
||||
const workItems: ShippingProcessingProjection[] = [
|
||||
{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'building_order',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'c.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 0,
|
||||
candidateCount: 0,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
},
|
||||
];
|
||||
const result = resolveConversationProcessingFromUnified(workItems, embedded);
|
||||
expect(result).not.toBeNull();
|
||||
// 过渡阶段:order_intake 不触发统一投影派生;embedded waiting_human 必须 normalize 成 waiting_review/needs_action
|
||||
expect(result!.focused_task_no).toBe('OT-LEG3');
|
||||
expect(result!.processing.length).toBe(0);
|
||||
expect(result!.needs_action.length).toBe(1);
|
||||
expect(result!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
expect(result!.needs_action[0]!.title).toBe('c.pdf');
|
||||
expect(result!.needs_action[0]!.group).toBe('needs_action');
|
||||
});
|
||||
|
||||
it('resolveConversationProcessingFromUnified + IntakeOtStabilizer: 看到 order_task 后 2s 内暂缺 OT 保持 previousProjection(避免轮询抖动)', () => {
|
||||
const stabilizer = createIntakeOtStabilizer();
|
||||
const embedded: ConversationProcessingProjection = {
|
||||
summary: { total_tasks: 1, total_files: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
|
||||
focused_task_no: null,
|
||||
recent_task_no: null,
|
||||
needs_action: [
|
||||
{
|
||||
user_task_no: 'OT-LG',
|
||||
user_task_authoritative: false,
|
||||
title: 'fallback.pdf',
|
||||
display_kind: 'single_document_task',
|
||||
document_names: ['fallback.pdf'],
|
||||
group: 'needs_action',
|
||||
status_label: 'waiting_human',
|
||||
file_count: 1,
|
||||
run_no: 'RUN-LG',
|
||||
can_append: false,
|
||||
available_actions: [],
|
||||
primary_action: 'enter_manual_review',
|
||||
},
|
||||
],
|
||||
processing: [],
|
||||
completed: [],
|
||||
history: [],
|
||||
};
|
||||
const intakeOnly: ShippingProcessingProjection[] = [
|
||||
{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: null,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'building_order',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: { filename: 'a.pdf', documentCount: 1 },
|
||||
childOrderTasks: [],
|
||||
},
|
||||
];
|
||||
const withOrderTask: ShippingProcessingProjection[] = [
|
||||
{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-NEW',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-NEW',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
runNo: 'RUN-NEW',
|
||||
caseNo: 'CASE-NEW',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
userStatus: 'waiting_review',
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_human_review',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-06T00:00:01Z',
|
||||
primaryAction: { code: 'open_order_review', i18nKey: 'chat.shippingProcessing.action.open_order_review' },
|
||||
currentGate: null,
|
||||
availableActions: ['open_order_review', 'cancel_task'],
|
||||
sourceSummary: { filename: 'a.pdf', documentCount: 1 },
|
||||
},
|
||||
];
|
||||
// Step 1: 初始只有 intake,还没见过 OT → 走 embedded normalize
|
||||
const step1 = resolveConversationProcessingFromUnified(
|
||||
intakeOnly,
|
||||
embedded,
|
||||
null,
|
||||
{ conversationId: 'conv-1', ...stabilizer },
|
||||
);
|
||||
expect(step1!.needs_action[0]!.title).toBe('fallback.pdf');
|
||||
expect(step1!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
|
||||
// Step 2: 第一轮看到 OT → derived 生成,同时 markSeen
|
||||
const step2 = resolveConversationProcessingFromUnified(
|
||||
withOrderTask,
|
||||
embedded,
|
||||
step1,
|
||||
{ conversationId: 'conv-1', ...stabilizer },
|
||||
);
|
||||
expect(step2!.needs_action[0]!.user_task_no).toBe('OT-NEW');
|
||||
expect(step2!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
|
||||
// Step 3: 下一次轮询只有 intake(本次响应暂缺 OT)→ 保持 previousProjection,不抖回 embedded
|
||||
const step3 = resolveConversationProcessingFromUnified(
|
||||
intakeOnly,
|
||||
embedded,
|
||||
step2,
|
||||
{ conversationId: 'conv-1', ...stabilizer },
|
||||
);
|
||||
expect(step3).toBe(step2);
|
||||
|
||||
// Step 4: 用户点刷新 reset 后,允许走 embedded(业务认为需要重新建立稳定态)
|
||||
stabilizer.reset('conv-1');
|
||||
const step4 = resolveConversationProcessingFromUnified(
|
||||
intakeOnly,
|
||||
embedded,
|
||||
step2,
|
||||
{ conversationId: 'conv-1', ...stabilizer },
|
||||
);
|
||||
expect(step4!.needs_action[0]!.title).toBe('fallback.pdf');
|
||||
expect(step4!.needs_action[0]!.status_label).toBe('waiting_review');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -75,6 +75,51 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('normalizes structured inventory candidate facts', () => {
|
||||
const projection = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'SN-001',
|
||||
work_item_type: 'order_task',
|
||||
source_type: 'eml',
|
||||
submission_no: 'SUB-1',
|
||||
intake_no: 'INT-1',
|
||||
status: 'processing',
|
||||
stage: 'inventory_matching',
|
||||
progress_version: 2,
|
||||
last_activity_at: '2026-08-08T22:00:00',
|
||||
source_summary: {},
|
||||
available_actions: [],
|
||||
child_order_tasks: [],
|
||||
blocking_reason: {
|
||||
code: 'inventory_candidates_missing',
|
||||
i18n_key: 'workspace.shippingNotice.processGate.reasons.inventory_candidates_missing',
|
||||
},
|
||||
facts: {
|
||||
candidate_set_id: 12,
|
||||
candidate_set_version: 3,
|
||||
candidate_set_status: 'frozen',
|
||||
candidate_source_codes: ['DBS_DUB'],
|
||||
prepared_source_codes: ['DBS_DUB'],
|
||||
pending_source_codes: ['DBS_RTM'],
|
||||
failed_source_codes: ['DBS_SIN'],
|
||||
source_attempts: {
|
||||
DBS_DUB: { status: 'consumed', attempt_no: 1 },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(projection?.facts?.candidateSetId).toBe(12);
|
||||
expect(projection?.facts?.candidateSetVersion).toBe(3);
|
||||
expect(projection?.facts?.candidateSetStatus).toBe('frozen');
|
||||
expect(projection?.facts?.candidateSourceCodes).toEqual(['DBS_DUB']);
|
||||
expect(projection?.facts?.preparedSourceCodes).toEqual(['DBS_DUB']);
|
||||
expect(projection?.facts?.pendingSourceCodes).toEqual(['DBS_RTM']);
|
||||
expect(projection?.facts?.failedSourceCodes).toEqual(['DBS_SIN']);
|
||||
expect(projection?.facts?.sourceAttempts).toEqual({
|
||||
DBS_DUB: { status: 'consumed', attempt_no: 1 },
|
||||
});
|
||||
expect(projection?.blockingReason?.code).toBe('inventory_candidates_missing');
|
||||
});
|
||||
|
||||
it('returns null when work_item_no missing', () => {
|
||||
expect(normalizeShippingProcessingProjection({ status: 'processing' })).toBeNull();
|
||||
});
|
||||
|
||||
@@ -8,7 +8,12 @@
|
||||
import type {
|
||||
OrderIntakeSourceType,
|
||||
ProcessGateSummary,
|
||||
ShippingInventoryPerSourceAttempt,
|
||||
ShippingInventoryPreparationSummary,
|
||||
ShippingOrderTaskSummary,
|
||||
ShippingProcessingBlockingReason,
|
||||
ShippingProcessingFacts,
|
||||
ShippingProcessingPrimaryAction,
|
||||
ShippingProcessingProjection,
|
||||
ShippingProcessingStage,
|
||||
ShippingProcessingStageNode,
|
||||
@@ -98,6 +103,186 @@ function normalizeStageNode(raw: unknown): ShippingProcessingStageNode | null {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* [T9 用户态 Projection] 规范 blocking_reason(后端 snake_case {code, i18n_key, details})。
|
||||
*/
|
||||
function normalizeBlockingReason(raw: unknown): ShippingProcessingBlockingReason | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const code = String(item.code ?? '').trim();
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
details:
|
||||
typeof item.details === 'object' && item.details != null
|
||||
? (item.details as Record<string, unknown>)
|
||||
: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* [T9 用户态 Projection] 规范 primary_action(后端 snake_case {code, i18n_key, parameters})。
|
||||
*/
|
||||
function normalizePrimaryAction(raw: unknown): ShippingProcessingPrimaryAction | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const code = String(item.code ?? '').trim();
|
||||
if (!code) return null;
|
||||
return {
|
||||
code,
|
||||
i18nKey: item.i18n_key != null ? String(item.i18n_key) : (item.i18nKey != null ? String(item.i18nKey) : null),
|
||||
parameters:
|
||||
typeof item.parameters === 'object' && item.parameters != null
|
||||
? (item.parameters as Record<string, unknown>)
|
||||
: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* [T9 用户态 Projection] 规范 facts(后端 snake_case 子状态字典;camelCase key)。
|
||||
*/
|
||||
function normalizeFacts(raw: unknown): ShippingProcessingFacts | undefined {
|
||||
if (!raw || typeof raw !== 'object') return undefined;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const toStrArr = (value: unknown): string[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.map((c) => String(c ?? '').trim()).filter(Boolean);
|
||||
};
|
||||
const toLineArr = (value: unknown): Record<string, unknown>[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter((row): row is Record<string, unknown> => Boolean(row) && typeof row === 'object');
|
||||
};
|
||||
const out: ShippingProcessingFacts = {};
|
||||
if ('inventory_source_status' in item || 'inventorySourceStatus' in item) {
|
||||
out.inventorySourceStatus =
|
||||
item.inventory_source_status != null
|
||||
? String(item.inventory_source_status)
|
||||
: item.inventorySourceStatus != null
|
||||
? String(item.inventorySourceStatus)
|
||||
: null;
|
||||
}
|
||||
if ('candidate_set_id' in item || 'candidateSetId' in item) {
|
||||
const v = item.candidate_set_id ?? item.candidateSetId;
|
||||
out.candidateSetId = v == null || v === '' ? null : Number(v);
|
||||
}
|
||||
if ('candidate_set_version' in item || 'candidateSetVersion' in item) {
|
||||
const v = item.candidate_set_version ?? item.candidateSetVersion;
|
||||
out.candidateSetVersion = v == null || v === '' ? null : Number(v);
|
||||
}
|
||||
if ('candidate_set_status' in item || 'candidateSetStatus' in item) {
|
||||
const v = item.candidate_set_status ?? item.candidateSetStatus;
|
||||
out.candidateSetStatus = v == null || v === '' ? null : String(v) as ShippingProcessingFacts['candidateSetStatus'];
|
||||
}
|
||||
if ('candidate_source_codes' in item || 'candidateSourceCodes' in item) {
|
||||
out.candidateSourceCodes = toStrArr(item.candidate_source_codes ?? item.candidateSourceCodes);
|
||||
}
|
||||
if ('prepared_source_codes' in item || 'preparedSourceCodes' in item) {
|
||||
out.preparedSourceCodes = toStrArr(item.prepared_source_codes ?? item.preparedSourceCodes);
|
||||
}
|
||||
if ('pending_source_codes' in item || 'pendingSourceCodes' in item) {
|
||||
out.pendingSourceCodes = toStrArr(item.pending_source_codes ?? item.pendingSourceCodes);
|
||||
}
|
||||
if ('failed_source_codes' in item || 'failedSourceCodes' in item) {
|
||||
out.failedSourceCodes = toStrArr(item.failed_source_codes ?? item.failedSourceCodes);
|
||||
}
|
||||
if ('source_attempts' in item || 'sourceAttempts' in item) {
|
||||
const v = item.source_attempts ?? item.sourceAttempts;
|
||||
out.sourceAttempts = typeof v === 'object' && v != null ? v as Record<string, unknown> : {};
|
||||
}
|
||||
if ('line_resolutions' in item || 'lineResolutions' in item) {
|
||||
out.lineResolutions = toLineArr(item.line_resolutions ?? item.lineResolutions);
|
||||
}
|
||||
if ('export_state' in item || 'exportState' in item) {
|
||||
const v = item.export_state ?? item.exportState;
|
||||
out.exportState = v == null ? 'not_created' : String(v);
|
||||
}
|
||||
if ('upload_state' in item || 'uploadState' in item) {
|
||||
const v = item.upload_state ?? item.uploadState;
|
||||
out.uploadState = v == null ? 'not_created' : String(v);
|
||||
}
|
||||
if ('switch_state' in item || 'switchState' in item) {
|
||||
const v = item.switch_state ?? item.switchState;
|
||||
out.switchState = v == null ? 'not_triggered' : String(v);
|
||||
}
|
||||
if ('forced_match_source_code' in item || 'forcedMatchSourceCode' in item) {
|
||||
const v = item.forced_match_source_code ?? item.forcedMatchSourceCode;
|
||||
out.forcedMatchSourceCode = v == null || v === '' ? null : String(v).toUpperCase();
|
||||
}
|
||||
for (const [k, v] of Object.entries(item)) {
|
||||
if (!(k in out)) {
|
||||
out[k] = v;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 题4A:规范 inventory_preparation 结构化字段(snake_case → camelCase)。
|
||||
* 注意:failed_sources 会进一步透传到 exhausted_sources 分开(二者互斥;仅 max_attempts 耗尽的源进 exhausted)。
|
||||
*/
|
||||
function normalizeInventoryPreparation(raw: unknown): ShippingInventoryPreparationSummary | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const toStrArr = (value: unknown): string[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.map((c) => String(c ?? '').trim()).filter(Boolean);
|
||||
};
|
||||
const requiredSources = toStrArr(item.required_sources ?? item.requiredSources);
|
||||
if (!requiredSources.length) {
|
||||
// required_sources 空代表 inventory_preparation 实际尚未进入 inventory 阶段,返回 null 避免前端误判。
|
||||
return null;
|
||||
}
|
||||
const preparedSources = toStrArr(item.prepared_sources ?? item.preparedSources);
|
||||
const pendingSources = toStrArr(item.pending_sources ?? item.pendingSources);
|
||||
const failedSources = toStrArr(item.failed_sources ?? item.failedSources);
|
||||
const exhaustedSources = toStrArr(item.exhausted_sources ?? item.exhaustedSources);
|
||||
const activeAttemptCount = Number(item.active_attempt_count ?? item.activeAttemptCount ?? 0) || 0;
|
||||
const gateAttemptActive = Boolean(item.gate_attempt_active ?? item.gateAttemptActive ?? false);
|
||||
const latestRaw = (item.latest_attempts ?? item.latestAttempts) as Record<string, unknown> | undefined;
|
||||
const latestAttempts: Record<string, ShippingInventoryPerSourceAttempt> = {};
|
||||
if (latestRaw && typeof latestRaw === 'object') {
|
||||
for (const [key, val] of Object.entries(latestRaw)) {
|
||||
if (!val || typeof val !== 'object') continue;
|
||||
const row = val as Record<string, unknown>;
|
||||
const sourceCode = String(row.source_code ?? row.sourceCode ?? key ?? '').trim().toUpperCase();
|
||||
if (!sourceCode) continue;
|
||||
const attemptNo = Number(row.attempt_no ?? row.attemptNo ?? 0) || 0;
|
||||
const status = String(row.status || '').trim().toLowerCase() || 'unknown';
|
||||
const entry: ShippingInventoryPerSourceAttempt = {
|
||||
sourceCode,
|
||||
attemptNo,
|
||||
status,
|
||||
manualRetryable: (() => {
|
||||
if (row.manual_retryable != null) return Boolean(row.manual_retryable);
|
||||
if (row.manualRetryable != null) return Boolean(row.manualRetryable);
|
||||
return ['failed', 'exhausted'].includes(status);
|
||||
})(),
|
||||
message:
|
||||
(row.error_message as string | null | undefined) ??
|
||||
(row.errorMessage as string | null | undefined) ??
|
||||
(row.message as string | null | undefined) ??
|
||||
null,
|
||||
updatedAt:
|
||||
readNullableString(row, 'updated_at', 'updatedAt') ??
|
||||
readNullableString(row, 'finished_at', 'finishedAt') ??
|
||||
readNullableString(row, 'started_at', 'startedAt'),
|
||||
};
|
||||
latestAttempts[sourceCode] = entry;
|
||||
}
|
||||
}
|
||||
return {
|
||||
requiredSources,
|
||||
preparedSources,
|
||||
pendingSources,
|
||||
failedSources,
|
||||
exhaustedSources,
|
||||
activeAttemptCount,
|
||||
gateAttemptActive,
|
||||
latestAttempts: Object.keys(latestAttempts).length ? latestAttempts : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将后端 / 混合字段投影规范为 ShippingProcessingProjection。
|
||||
* 核心逻辑:缺字段给安全默认值,保证四页面可渲染;非法输入返回 null。
|
||||
@@ -160,6 +345,23 @@ export function normalizeShippingProcessingProjection(
|
||||
assetStatus: readNullableString(summaryRaw, 'asset_status', 'assetStatus'),
|
||||
},
|
||||
childOrderTasks: children,
|
||||
// [T9 用户态 Projection 7 字段] 优先读后端 user_* / blocking_reason / retryable / primary_action / facts;
|
||||
// 缺省为 null(旧后端不会下发,旧前端不读取,完全兼容)。
|
||||
userStatus: readNullableString(item, 'user_status', 'userStatus') as ShippingProcessingProjection['userStatus'],
|
||||
userStage: readNullableString(item, 'user_stage', 'userStage') as ShippingProcessingProjection['userStage'],
|
||||
userCurrentGateCode: readNullableString(item, 'user_current_gate_code', 'userCurrentGateCode'),
|
||||
blockingReason: normalizeBlockingReason(item.blocking_reason ?? item.blockingReason),
|
||||
retryable:
|
||||
(item.retryable as boolean | undefined) == null ? false : Boolean(item.retryable),
|
||||
primaryAction: normalizePrimaryAction(item.primary_action ?? item.primaryAction),
|
||||
facts: normalizeFacts(item.facts),
|
||||
legacyStatus: readNullableString(item, 'legacy_status', 'legacyStatus'),
|
||||
legacyStage: readNullableString(item, 'legacy_stage', 'legacyStage'),
|
||||
hasFormalOt:
|
||||
(item.has_formal_ot as boolean | undefined) == null ? false : Boolean(item.has_formal_ot),
|
||||
inventoryPreparation: normalizeInventoryPreparation(
|
||||
item.inventory_preparation ?? item.inventoryPreparation,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,39 @@ function buildUnifiedProcessing(conversationId = 'conv-1') {
|
||||
};
|
||||
}
|
||||
|
||||
function buildOrderTaskWorkItem(
|
||||
taskNo = 'OT-conv-1',
|
||||
patch: Record<string, unknown> = {},
|
||||
) {
|
||||
return {
|
||||
workItemType: 'order_task',
|
||||
workItemNo: taskNo,
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: taskNo,
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'document_parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:00Z',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'po.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: 'PO-1',
|
||||
},
|
||||
childOrderTasks: [],
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建可手动完成的 Promise。
|
||||
*/
|
||||
@@ -182,36 +215,16 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
it('uses unified work_items as the sole processing read source', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [{
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-UNIFIED',
|
||||
sourceType: 'direct_pdf',
|
||||
rootOrderTaskNo: 'OT-UNIFIED',
|
||||
shippingNoticeNo: null,
|
||||
conversationId: 'conv-1',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
work_items: [buildOrderTaskWorkItem('OT-UNIFIED', {
|
||||
status: 'waiting_review',
|
||||
stage: 'waiting_review',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:00Z',
|
||||
currentGate: {
|
||||
gateCode: 'order_freeze_readiness',
|
||||
status: 'blocked',
|
||||
nextActionCode: 'open_order_review',
|
||||
},
|
||||
availableActions: ['open_order_review'],
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'po.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: 'PO-1',
|
||||
},
|
||||
childOrderTasks: [],
|
||||
}],
|
||||
})],
|
||||
conversation_processing: null,
|
||||
});
|
||||
|
||||
@@ -226,6 +239,60 @@ describe('useShippingNoticeWorkflow', () => {
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('preserves previous order_task work_items when stabilizer keeps previous projection', async () => {
|
||||
api.getShippingProcessing
|
||||
.mockResolvedValueOnce({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [buildOrderTaskWorkItem('OT-STABLE')],
|
||||
conversation_processing: null,
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
conversation_id: 'conv-1',
|
||||
work_items: [{
|
||||
workItemType: 'order_intake',
|
||||
workItemNo: 'SNI-1',
|
||||
sourceType: 'email',
|
||||
conversationId: 'conv-1',
|
||||
intakeNo: 'SNI-1',
|
||||
status: 'processing',
|
||||
stage: 'parsing',
|
||||
progressVersion: 1,
|
||||
lastActivityAt: '2026-08-05T00:00:01Z',
|
||||
currentGate: null,
|
||||
availableActions: [],
|
||||
sourceSummary: {
|
||||
emailSubject: 'mail',
|
||||
filename: 'po.pdf',
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 0,
|
||||
candidateCount: 0,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
}],
|
||||
conversation_processing: buildProcessing(),
|
||||
});
|
||||
|
||||
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(ctl.processing.value?.processing[0]?.user_task_no).toBe('OT-STABLE');
|
||||
expect(ctl.processingWorkItems.value).toHaveLength(1);
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemType).toBe('order_task');
|
||||
expect(ctl.processingWorkItems.value[0]?.workItemNo).toBe('OT-STABLE');
|
||||
ctl.stop();
|
||||
});
|
||||
|
||||
it('derives sibling OT tasks from work_items when embedded conversation_processing omits them', async () => {
|
||||
api.getShippingProcessing.mockResolvedValue({
|
||||
conversation_id: 'conv-1',
|
||||
|
||||
@@ -32,6 +32,7 @@ import type {
|
||||
} from '../types/shipping.api.types';
|
||||
import {
|
||||
buildProcessingSemanticKey,
|
||||
createIntakeOtStabilizer,
|
||||
resolveConversationProcessingFromUnified,
|
||||
} from './conversationProcessingProjection';
|
||||
|
||||
@@ -147,6 +148,27 @@ export function useShippingNoticeWorkflow(
|
||||
let failureCount = 0;
|
||||
let pollingStopped = false;
|
||||
let lastSemanticKey = '';
|
||||
const intakeOtStabilizer = createIntakeOtStabilizer();
|
||||
|
||||
/**
|
||||
* 在 Intake→OT 过渡窗里,若 projection 被稳定器保留为上一轮 OT 视图,
|
||||
* 则 work_items 也必须同步保留上一轮 order_task;否则卡片正文与侧边进度条
|
||||
* 会来自两轮不同响应,导致右侧布局在“带进度条/只剩按钮”之间来回切换。
|
||||
*/
|
||||
function resolveStableWorkItems(
|
||||
nextWorkItems: ShippingProcessingProjection[],
|
||||
previousProjection: ConversationProcessingProjection | null,
|
||||
nextProjection: ConversationProcessingProjection | null,
|
||||
): ShippingProcessingProjection[] {
|
||||
const hasNextOrderTask = nextWorkItems.some((item) => item.workItemType === 'order_task');
|
||||
if (hasNextOrderTask) return nextWorkItems;
|
||||
if (!previousProjection || nextProjection !== previousProjection) return nextWorkItems;
|
||||
const currentWorkItems = Array.isArray(processingWorkItems.value)
|
||||
? processingWorkItems.value
|
||||
: [];
|
||||
const hasCurrentOrderTask = currentWorkItems.some((item) => item.workItemType === 'order_task');
|
||||
return hasCurrentOrderTask ? currentWorkItems : nextWorkItems;
|
||||
}
|
||||
|
||||
const normalizedConversationId = computed(() =>
|
||||
String(readOption(options.conversationId) || '').trim(),
|
||||
@@ -212,10 +234,20 @@ export function useShippingNoticeWorkflow(
|
||||
workItems,
|
||||
embedded,
|
||||
prevProjection,
|
||||
{
|
||||
conversationId,
|
||||
hasSeenOrderTaskBefore: (cId) => intakeOtStabilizer.hasSeenOrderTaskBefore(cId),
|
||||
markSeen: (cId) => intakeOtStabilizer.markSeen(cId),
|
||||
reset: (cId) => intakeOtStabilizer.reset(cId),
|
||||
},
|
||||
);
|
||||
const nextSemanticKey = buildProcessingSemanticKey(nextProjection);
|
||||
|
||||
processingWorkItems.value = workItems;
|
||||
processingWorkItems.value = resolveStableWorkItems(
|
||||
workItems,
|
||||
prevProjection,
|
||||
nextProjection,
|
||||
);
|
||||
if (nextSemanticKey !== lastSemanticKey) {
|
||||
processing.value = nextProjection;
|
||||
lastSemanticKey = nextSemanticKey;
|
||||
@@ -255,6 +287,7 @@ export function useShippingNoticeWorkflow(
|
||||
lastSemanticKey = '';
|
||||
return Promise.resolve();
|
||||
}
|
||||
intakeOtStabilizer.reset(conversationId);
|
||||
if (inFlightRefresh?.conversationId === conversationId) {
|
||||
return inFlightRefresh.promise;
|
||||
}
|
||||
@@ -278,12 +311,16 @@ export function useShippingNoticeWorkflow(
|
||||
}): void {
|
||||
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
|
||||
if (workItems.length > 0) {
|
||||
processingWorkItems.value = workItems as typeof processingWorkItems.value;
|
||||
const nextProjection = resolveConversationProcessingFromUnified(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
response.processing ?? null,
|
||||
processing.value,
|
||||
);
|
||||
processingWorkItems.value = resolveStableWorkItems(
|
||||
workItems as typeof processingWorkItems.value,
|
||||
processing.value,
|
||||
nextProjection,
|
||||
);
|
||||
const nextKey = buildProcessingSemanticKey(nextProjection);
|
||||
if (nextKey !== lastSemanticKey) {
|
||||
processing.value = nextProjection;
|
||||
|
||||
Reference in new issue
Block a user