chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑

This commit is contained in:
hugo committed 2026-08-17 19:56:51 +08:00
1 parent 5ef8329bd8
commit 4ec4e57005
183 files changed
+14653 -3936

No files matched your search

@@ -25,6 +25,7 @@ import {
flattenBusinessFileProjections,
businessFileKeys,
} from './conversationProcessingProjection';
import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing';
import type {
ConversationProcessingProjection,
ShippingProcessingProjection,
@@ -813,6 +814,35 @@ describe('conversationProcessingProjection', () => {
expect(projection?.recent_task_no).toBe('OT-SIBLING');
});
it('uses backend status_groups instead of rebuilding a file list from work_items', () => {
const workItems: ShippingProcessingProjection[] = [{
workItemType: 'order_task', workItemNo: 'OT-LIVE', sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-LIVE', shippingNoticeNo: null, conversationId: 'conv-live',
submissionNo: 'SOS-LIVE', intakeNo: 'SNI-LIVE', status: 'waiting_review',
stage: 'order_review', progressVersion: 9, lastActivityAt: '2026-08-16T00:00:00Z',
currentGate: null, availableActions: ['open_order_review'], childOrderTasks: [],
sourceSummary: { emailSubject: null, filename: 'live.pdf', documentCount: 1,
parsedDocumentCount: 1, candidateCount: 1, customerName: null, poNumber: 'PO-LIVE' },
}];
const backendProjection = {
summary: { total_tasks: 1, total_files: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
status_groups: {
failed: [], waiting_human: [{
user_task_no: 'OT-LIVE', group: 'needs_action', status_label: 'waiting_human',
file_count: 1, can_append: false,
}], processing: [], completed: [], cancelled: [], archived: [],
},
needs_action: [], processing: [{ user_task_no: 'OT-HISTORY', status_label: 'extracting' }],
completed: [], history: [], focused_task_no: null, recent_task_no: null,
};
const projection = resolveConversationProcessingFromUnified(workItems, backendProjection);
// 后端已排除的历史条目不允许被前端 work_items 重建回页面。
expect(projection?.needs_action.map((task) => task.user_task_no)).toEqual(['OT-LIVE']);
expect(projection?.processing).toEqual([]);
});
it('merges focus metadata from embedded onto work_items-derived projection', () => {
const derived = projectConversationProcessingFromWorkItems([{
workItemType: 'order_task',
@@ -939,6 +969,56 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
expect(buildTaskSemanticKey(before)).not.toBe(buildTaskSemanticKey(after));
});
it('buildTaskSemanticKey: 后端撤销生命周期入口时必须改变签名', () => {
const shared = {
user_task_no: 'INTAKE:SNI-LIFECYCLE', group: 'needs_action' as const,
status_label: 'waiting_human', file_count: 1, can_append: false,
uiState: {
status: 'waiting_human', stage: 'waiting_review', blocking_reason: null,
primary_action: null, secondary_actions: [],
lifecycleEntries: [{ code: 'order_review' as const, state: 'current' as const, targetSurface: 'order_lifecycle_workbench' as const }],
},
};
const revoked = {
...shared,
uiState: { ...shared.uiState, lifecycleEntries: [] },
};
expect(buildTaskSemanticKey(shared)).not.toBe(buildTaskSemanticKey(revoked));
});
it('buildTaskSemanticKey: EML 子文件入口被撤销时必须替换聚合卡', () => {
const child = {
workItemNo: 'OT-LEAF-1',
intakeNo: 'SNI-LEAF',
status: 'waiting_human',
stage: 'order_review',
sourceSummary: { filename: 'leaf.pdf', documentId: 801 },
uiState: {
status: 'waiting_human', stage: 'order_review', blocking_reason: null,
primary_action: null, secondary_actions: [],
lifecycleEntries: [{
code: 'order_review' as const, state: 'current' as const,
targetSurface: 'order_lifecycle_workbench' as const,
}],
},
} as any;
const task = {
user_task_no: 'INTAKE:SNI-LEAF', group: 'needs_action' as const,
status_label: 'waiting_human', file_count: 1, can_append: false,
uiState: { status: 'waiting_human', stage: 'order_review', blocking_reason: null, primary_action: null, secondary_actions: [] },
aggregateChildren: [child],
} as any;
const revoked = {
...task,
aggregateChildren: [{
...child,
uiState: { ...child.uiState, lifecycleEntries: [] },
}],
};
expect(buildTaskSemanticKey(task)).not.toBe(buildTaskSemanticKey(revoked));
});
it('buildTaskSemanticKey: authoritative ui_state without a primary action ignores stale legacy action', () => {
const shared = {
user_task_no: 'INTAKE:SNI-NO-ACTION', group: 'processing' as const,
@@ -1173,6 +1253,161 @@ describe('conversationProcessingProjection — normalize & semantic & stabilize'
expect(normalized.output_artifacts?.[0]?.action.enabled).toBe(true);
});
it('normalizes backend lifecycle_entries in status groups without recreating entries', () => {
const backendProjection = {
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: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-LIFECYCLE-SNAKE', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'field_completeness', lifecycle_stage: 'order_review',
lifecycle_entries: [{ code: 'intake_parse', state: 'available', target_surface: 'order_lifecycle_workbench' }, {
code: 'order_review', state: 'current', target_surface: 'order_lifecycle_workbench',
}],
blocking_reason: null, primary_action: null, secondary_actions: [],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const normalized = normalizeConversationProcessingProjection(backendProjection);
const task = normalized.status_groups!.waiting_human[0]!;
expect(task.uiState?.lifecycleStage).toBe('order_review');
expect(task.uiState?.lifecycleEntries).toEqual([
{ code: 'intake_parse', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
]);
});
it('normalizes embedded primary-action lifecycle navigation fields from backend snake_case', () => {
const embedded = {
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: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-FULFILLMENT-NAV', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [], blocking_reason: null,
primary_action: {
code: 'open_inventory_match_review', execution_mode: 'navigate',
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'fulfillment_prep',
}, secondary_actions: [],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const action = normalizeConversationProcessingProjection(embedded)
.status_groups!.waiting_human[0]!.uiState!.primary_action!;
expect(action.executionMode).toBe('navigate');
expect(action.targetSurface).toBe('order_lifecycle_workbench');
expect(action.targetLifecycleStage).toBe('fulfillment_prep');
});
it('normalizes embedded secondary-action lifecycle navigation fields from backend snake_case', () => {
const embedded = {
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: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-VIEW-NAV', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [], blocking_reason: null, primary_action: null,
secondary_actions: [{
code: 'view_result', enabled: true, execution_mode: 'navigate',
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'fulfillment_prep',
}],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const action = normalizeConversationProcessingProjection(embedded)
.status_groups!.waiting_human[0]!.uiState!.secondary_actions[0]!;
// 次动作与主动作一样来自后端授权;缺失导航字段会使文件级查看结果静默失效。
expect(action.executionMode).toBe('navigate');
expect(action.targetSurface).toBe('order_lifecycle_workbench');
expect(action.targetLifecycleStage).toBe('fulfillment_prep');
});
it('fails closed for unsupported embedded primary-action navigation targets', () => {
const embedded = {
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: [], processing: [], completed: [], history: [],
status_groups: {
failed: [],
waiting_human: [{
user_task_no: 'OT-INVALID-NAV', title: 'order.pdf', display_kind: 'single_document_task',
document_names: ['order.pdf'], group: 'needs_action', status_label: 'waiting_human', file_count: 1,
can_append: false, available_actions: [],
ui_state: {
status: 'waiting_human', stage: 'inventory_matching', lifecycle_stage: 'fulfillment_prep',
lifecycle_entries: [], blocking_reason: null,
primary_action: {
code: 'open_inventory_match_review', execution_mode: 'unknown',
target_surface: 'unsupported_surface', target_lifecycle_stage: 'unsupported_stage',
}, secondary_actions: [],
},
}],
processing: [], completed: [], cancelled: [], archived: [],
},
} as unknown as ConversationProcessingProjection;
const action = normalizeConversationProcessingProjection(embedded)
.status_groups!.waiting_human[0]!.uiState!.primary_action!;
expect(action.executionMode).toBeUndefined();
expect(action.targetSurface).toBeNull();
expect(action.targetLifecycleStage).toBeNull();
});
it('keeps backend intake_parse primary-action target instead of dropping it', () => {
const normalized = normalizeShippingProcessingProjection({
work_item_no: 'OT-INTAKE-ACTION', source_type: 'direct_pdf', status: 'waiting_human',
stage: 'intake_parse', progress_version: 1, last_activity_at: '2026-08-16T00:00:00Z',
source_summary: {}, available_actions: [], child_order_tasks: [],
ui_state: {
status: 'waiting_human', stage: 'intake_parse', lifecycle_stage: 'intake_parse',
lifecycle_entries: [{ code: 'intake_parse', state: 'current', target_surface: 'order_lifecycle_workbench' }],
blocking_reason: null,
primary_action: {
code: 'open_intake_parse', parameters: {}, execution_mode: 'navigate',
target_surface: 'order_lifecycle_workbench', target_lifecycle_stage: 'intake_parse',
},
secondary_actions: [],
},
});
// 后端指定接收解析时,前端仅透传该目标,不得由现有三阶段白名单裁决或改写。
expect(normalized?.uiState?.primary_action?.targetLifecycleStage).toBe('intake_parse');
expect(normalized?.uiState?.lifecycleEntries).toEqual([
{ code: 'intake_parse', state: 'current', targetSurface: 'order_lifecycle_workbench', disabledReasonKey: null },
]);
});
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 },
@@ -17,6 +17,7 @@ import type {
ConversationProcessingUserTask,
ShippingProcessingBlockingReason,
ShippingProcessingFacts,
ShippingProcessingLifecycleEntry,
ShippingProcessingPrimaryAction,
ShippingProcessingProjection,
ShippingWorkflowItem,
@@ -98,6 +99,17 @@ export function buildTaskSemanticKey(
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,
@@ -114,6 +126,13 @@ export function buildTaskSemanticKey(
: ((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;
@@ -911,8 +930,9 @@ export function mergeConversationProcessingFocusMetadata(
/**
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
* 核心逻辑:work_items 非空时始终由 order_task 工作项合成任务列表;禁止优先 embedded
* (兄弟 OT 仅出现在 work_items,embedded 可能缺 sibling)。
* 核心逻辑:新版 embedded.status_groups 是后端已完成“当前文件代表项 → EML 容器”
* 裁决的唯一列表读源,存在时绝不能再从 work_items 重建;否则旧 Run 会重新进入
* 文件清单。旧接口未返回 status_groups 时,才从 work_items 合成兼容任务列表。
* 语义稳定化:对比 previousProjection 的签名,复用未变的任务对象引用。
*
* @param workItems - unified.work_items
@@ -927,11 +947,13 @@ export function resolveConversationProcessingFromUnified(
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] 新版接口已经由后端完成「状态 → EML → 业务文件」聚合。
// 会话卡与批次中心必须直接使用该结果;前端从 work_items 重建只保留给旧响应兼容。
// [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 窗口内),
@@ -981,13 +1003,49 @@ export function normalizeConversationProcessingProjection(
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) => {
const normalizeAction = (
action: ShippingProcessingPrimaryAction | null | undefined,
): ShippingProcessingPrimaryAction | null => {
if (!action || typeof action !== 'object') return null;
const rawAction = action as ShippingProcessingPrimaryAction & { i18n_key?: string | 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) => {
@@ -1002,7 +1060,29 @@ export function normalizeConversationProcessingProjection(
...state,
blocking_reason: normalizeReason(state.blocking_reason ?? state.blockingReason),
primary_action: normalizeAction(state.primary_action ?? state.primaryAction),
secondary_actions: state.secondary_actions ?? state.secondaryActions ?? [],
// 次动作与主动作同属后端 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 => {
@@ -1114,6 +1194,7 @@ export function normalizeConversationProcessingProjection(
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 || [],
};
@@ -6,6 +6,7 @@
*/
import type {
ConversationProcessingUiState,
OrderIntakeSourceType,
ProcessGateSummary,
ShippingInventoryPerSourceAttempt,
@@ -23,6 +24,9 @@ import type {
ShippingProcessGateUserSummary,
} from '../types/shipping.api.types';
/** 后端可裁决并透传到订单生命周期工作台的阶段;前端不根据本地状态补造入口。 */
const lifecycleStages = ['intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete'] as const;
/**
* 读取原始对象上的字符串字段(兼容 snake / camel)。
*/
@@ -137,9 +141,40 @@ function normalizePrimaryAction(raw: unknown): ShippingProcessingPrimaryAction |
typeof item.parameters === 'object' && item.parameters != null
? (item.parameters as Record<string, unknown>)
: {},
executionMode: item.execution_mode === 'navigate' || item.executionMode === 'navigate'
? 'navigate'
: item.execution_mode === 'execute' || item.executionMode === 'execute'
? 'execute'
: undefined,
targetSurface: item.target_surface === 'order_lifecycle_workbench' || item.targetSurface === 'order_lifecycle_workbench'
? 'order_lifecycle_workbench'
: null,
targetLifecycleStage: lifecycleStages.includes(
String(item.target_lifecycle_stage ?? item.targetLifecycleStage ?? '') as typeof lifecycleStages[number],
)
? String(item.target_lifecycle_stage ?? item.targetLifecycleStage) as ShippingProcessingPrimaryAction['targetLifecycleStage']
: null,
};
}
/** 规范后端生命周期入口,前端不得由候选数或当前阶段补造入口。 */
function normalizeLifecycleEntries(raw: unknown): NonNullable<ConversationProcessingUiState['lifecycleEntries']> {
if (!Array.isArray(raw)) return [];
return raw
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
.map((item) => ({
code: String(item.code ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['code'],
state: String(item.state ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['state'],
targetSurface: String(item.target_surface ?? item.targetSurface ?? '') as NonNullable<ConversationProcessingUiState['lifecycleEntries']>[number]['targetSurface'],
disabledReasonKey: item.disabled_reason_key != null
? String(item.disabled_reason_key)
: item.disabledReasonKey != null ? String(item.disabledReasonKey) : null,
}))
.filter((item) => lifecycleStages.includes(item.code as typeof lifecycleStages[number])
&& ['available', 'current', 'unavailable'].includes(item.state)
&& item.targetSurface === 'order_lifecycle_workbench');
}
/**
* [T9 用户态 Projection] 规范 facts(后端 snake_case 子状态字典;camelCase key)。
*/
@@ -430,15 +465,17 @@ function normalizeProcessingUiState(raw: unknown): ShippingProcessingProjection[
const secondaryActions = Array.isArray(secondaryRaw)
? secondaryRaw
.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === 'object'))
.map((item) => ({
code: readString(item, 'code', 'code'),
enabled: item.enabled !== false,
}))
.filter((item) => Boolean(item.code))
.map((item) => {
const normalized = normalizePrimaryAction(item);
return normalized ? { ...normalized, enabled: item.enabled !== false } : null;
})
.filter((item): item is NonNullable<typeof item> => item !== null)
: [];
return {
status: (readString(state, 'status', 'status') || 'running') as NonNullable<ShippingProcessingProjection['userStatus']>,
stage: readString(state, 'stage', 'stage'),
lifecycleStage: readString(state, 'lifecycle_stage', 'lifecycleStage') as ConversationProcessingUiState['lifecycleStage'],
lifecycleEntries: normalizeLifecycleEntries(state.lifecycle_entries ?? state.lifecycleEntries),
blocking_reason: normalizeBlockingReason(state.blocking_reason ?? state.blockingReason),
primary_action: normalizePrimaryAction(state.primary_action ?? state.primaryAction),
secondary_actions: secondaryActions,
@@ -1,14 +1,31 @@
/**
* features/chat/shipping/shippingDownload.ts
* 用途:工作台发货 Excel 浏览器端下载(触发 a[download])。
* 依赖:shipping.api.workspaceShippingExportUrl、shared/utils/auth。
* 逻辑:useChatShippingSendHandler 在用户请求下载 Excel 时调用。
* 用途:工作台发货 Excel 与任务已关联库存快照的浏览器端受控下载(触发 a[download])。
* 依赖:shipping.api 的任务下载 URL、shared/utils/auth。
* 逻辑:聊天入口下载通知 Excel;通知准备工作面仅在后端声明库存文件可用时调用库存下载。
*/
import { workspaceShippingExportUrl } from '@/features/chat/api/shipping.api';
import {
downloadWorkspaceShippingExportArchive as requestShippingExportArchive,
workspaceShippingExportUrl,
workspaceShippingInventoryFileUrl,
} from '@/features/chat/api/shipping.api';
import { getAuthHeaders } from '@/shared/utils/auth';
export async function downloadWorkspaceShippingExcelFile(taskId: string): Promise<void> {
const url = workspaceShippingExportUrl(taskId);
await downloadWorkspaceShippingFile(workspaceShippingExportUrl(taskId), `${taskId}.xlsx`);
}
/**
* 下载当前任务活动关联的库存快照。
* 核心逻辑:浏览器只发起受控 URL;后端复核任务归属、active link 与物理文件,不按库存源猜测文件。
* @param taskId - 正式发货任务号,必须来自当前详情快照。
* @returns 下载完成后解析并触发浏览器保存。
*/
export async function downloadWorkspaceShippingInventoryFile(taskId: string): Promise<void> {
await downloadWorkspaceShippingFile(workspaceShippingInventoryFileUrl(taskId), `${taskId}-inventory.xlsx`);
}
async function downloadWorkspaceShippingFile(url: string, fallbackName: string): Promise<void> {
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) {
const body = await res.json().catch(() => ({}));
@@ -19,7 +36,7 @@ export async function downloadWorkspaceShippingExcelFile(taskId: string): Promis
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = objectUrl;
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || `${taskId}.xlsx`;
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || fallbackName;
try {
a.download = decodeURIComponent(rawName);
} catch {
@@ -30,3 +47,9 @@ export async function downloadWorkspaceShippingExcelFile(taskId: string): Promis
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
}
/** 批次 ZIP 下载只转发后端归档响应;选择和授权均不在前端重算。 */
export const downloadWorkspaceShippingExportArchive = (payload: {
batch_no?: string;
task_nos?: string[];
}) => requestShippingExportArchive(payload);
@@ -5,7 +5,9 @@
*/
import { describe, expect, it } from 'vitest';
import {
resolveShippingProcessingReasonLabel,
resolveShippingProcessingMessage,
resolveShippingProcessingStageLabel,
resolveShippingProcessingStatusLabel,
shippingProcessingStatusKey,
} from './shippingProcessingLabels';
@@ -36,6 +38,33 @@ describe('shippingProcessingLabels', () => {
expect(resolveShippingProcessingStatusLabel('pending_review', te, t)).toBe('待复核');
});
it('uses the safe unknown label instead of exposing an unrecognized status code', () => {
const te = (key: string) => key === 'chat.shippingProcessing.taskStatus.unknown';
const t = (key: string) => key.endsWith('.unknown') ? '状态待确认' : key;
expect(resolveShippingProcessingStatusLabel('internal_processing_state', te, t)).toBe('状态待确认');
});
it('uses the reason i18n key regardless of snake or camel case', () => {
const te = (key: string) => key === 'chat.shippingProcessing.reasonCode.generic_extraction_disabled';
const t = () => '当前文件不满足自动解析条件,需要人工复核';
expect(resolveShippingProcessingReasonLabel({
code: 'generic_extraction_disabled',
i18n_key: 'chat.shippingProcessing.reasonCode.generic_extraction_disabled',
}, te, t)).toBe('当前文件不满足自动解析条件,需要人工复核');
});
it('uses a safe reason label instead of exposing an unknown internal reason code', () => {
const te = (key: string) => key === 'chat.shippingProcessing.reasonCode.unknown';
const t = (key: string) => key.endsWith('.unknown') ? '当前步骤需要人工处理' : key;
expect(resolveShippingProcessingReasonLabel({ code: 'internal_gate_reason' }, te, t)).toBe('当前步骤需要人工处理');
});
it('uses a safe stage label instead of exposing an unknown internal stage code', () => {
const te = (key: string) => key === 'chat.shippingProcessing.stageLabel.waiting_system_start';
const t = (key: string) => key.endsWith('waiting_system_start') ? '等待系统启动' : key;
expect(resolveShippingProcessingStageLabel('internal_gate_stage', te, t)).toBe('等待系统启动');
});
it('resolves group messages from shippingProcessing', () => {
const te = (key: string) => key === 'chat.shippingProcessing.groupNeedsAction';
const t = (key: string, params?: Record<string, unknown>) => (
@@ -42,7 +42,7 @@ export function shippingProcessingStatusKey(status: string): string {
* @param code - 后端 status / status_label
* @param te - i18n te
* @param t - i18n t
* @returns 本地化文案;皆无则回退原码
* @returns 本地化文案;未知状态统一显示“状态待确认”,禁止暴露内部码
*/
export function resolveShippingProcessingStatusLabel(
code: string,
@@ -55,7 +55,28 @@ export function resolveShippingProcessingStatusLabel(
if (te(processingKey)) return t(processingKey);
const taskStatusKey = `chat.shippingProcessing.taskStatus.${raw}`;
if (te(taskStatusKey)) return t(taskStatusKey);
return raw;
const unknownKey = 'chat.shippingProcessing.taskStatus.unknown';
return te(unknownKey) ? t(unknownKey) : '状态待确认';
}
/**
* 解析后端阻塞原因的用户文案。
* 核心逻辑:先消费后端 i18n_key(兼容 snake/camel case),再使用原因码专用键;
* 未知原因只显示安全兜底,内部原因码仍保留在响应中供审计使用。
*/
export function resolveShippingProcessingReasonLabel(
reason: { code?: string | null; i18nKey?: string | null; i18n_key?: string | null } | null | undefined,
te: (key: string) => boolean,
t: (key: string) => string,
): string {
if (!reason) return '';
const i18nKey = String(reason.i18nKey || reason.i18n_key || '').trim();
if (i18nKey && te(i18nKey)) return t(i18nKey);
const code = String(reason.code || '').trim();
const reasonCodeKey = code ? `chat.shippingProcessing.reasonCode.${code}` : '';
if (reasonCodeKey && te(reasonCodeKey)) return t(reasonCodeKey);
const unknownKey = 'chat.shippingProcessing.reasonCode.unknown';
return te(unknownKey) ? t(unknownKey) : '当前步骤需要人工处理';
}
/**
@@ -124,7 +145,7 @@ export function resolveShippingProcessingStageLabel(
// 禁止把码当文案:无键时回退通用等待文案,而非裸 code。
return te('chat.shippingProcessing.stageLabel.waiting_system_start')
? t('chat.shippingProcessing.stageLabel.waiting_system_start')
: code;
: '等待系统启动';
}
/**
@@ -18,8 +18,8 @@ describe('shippingStepper', () => {
steps: [
{ id: 'shipping-stage-1', code: 'intake_parse', label: '接收解析', status: 'completed' },
{ id: 'shipping-stage-2', code: 'order_review', label: '订单复核', status: 'completed' },
{ id: 'shipping-stage-3', code: 'fulfillment_prep', label: '发货准备', status: 'blocked' },
{ id: 'shipping-stage-4', code: 'upload_complete', label: '上传完成', status: 'pending' },
{ id: 'shipping-stage-3', code: 'fulfillment_prep', label: '通知准备', status: 'blocked' },
{ id: 'shipping-stage-4', code: 'upload_complete', label: '通知完成', status: 'pending' },
],
},
});
@@ -69,7 +69,7 @@ export type UseShippingNoticeWorkflowOptions = {
};
export type UseShippingNoticeWorkflowReturn = {
/** 后端 conversation_processing / 由 work_items 合成。 */
/** 后端 conversation_processing;仅旧接口缺状态组时由 work_items 兼容合成。 */
processing: Ref<ConversationProcessingProjection | null>;
/** 统一 ShippingProcessing work_items。 */
processingWorkItems: Ref<ShippingProcessingProjection[]>;
@@ -204,11 +204,23 @@ export function useShippingNoticeWorkflow(
stage: item.uiState?.stage ?? item.userStage ?? item.stage,
gate: item.uiState?.blocking_reason?.code ?? item.blockingReason?.code ?? null,
action: item.uiState?.primary_action?.code ?? item.primaryAction?.code ?? null,
lifecycleEntries: item.uiState?.lifecycleEntries?.map((entry) => ({
code: entry.code,
state: entry.state,
targetSurface: entry.targetSurface,
disabledReasonKey: entry.disabledReasonKey ?? null,
})) ?? [],
version: item.progressVersion,
files: (item.aggregateChildren || []).map((child) => ({
no: child.workItemNo,
status: child.uiState?.status ?? child.userStatus ?? child.status,
stage: child.uiState?.stage ?? child.userStage ?? child.stage,
lifecycleEntries: child.uiState?.lifecycleEntries?.map((entry) => ({
code: entry.code,
state: entry.state,
targetSurface: entry.targetSurface,
disabledReasonKey: entry.disabledReasonKey ?? null,
})) ?? [],
file: child.sourceSummary?.filename ?? null,
})),
})));
@@ -293,7 +305,7 @@ export function useShippingNoticeWorkflow(
/**
* 仅拉取统一 shipping-processing 投影。
* 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据;
* 核心逻辑:后端 status_groups 存在时直接使用;仅旧响应缺状态组才由 work_items 合成;
* 同会话在途请求合并;跨会话请求中止,且只有最新一代可回写页面数据;
* 语义签名相同则不替换 projection 对象,避免 DOM 重建与按钮闪烁。
*