Merge branch 'dev' into runny827
feat(training): 新增精益培训视频与周任务管理 # Conflicts: # backend/app/models/__init__.py
This commit is contained in:
1 parent
85d27e9ffa
commit
91b7233872
812 files changed
+73763
-18908
No files matched your search
@@ -11,12 +11,20 @@ import {
|
||||
businessFileKeys,
|
||||
flattenBusinessFileProjections,
|
||||
normalizeConversationProcessingProjection,
|
||||
normalizeLifecycleStatus,
|
||||
resolveConversationProcessingFromUnified,
|
||||
stabilizeTaskObjects,
|
||||
} from './conversationProcessingProjection';
|
||||
import type { ShippingProcessingProjection } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
describe('conversationProcessingProjection', () => {
|
||||
it('normalizeLifecycleStatus keeps F2 waiting_human (no fold to waiting_review)', () => {
|
||||
expect(normalizeLifecycleStatus('waiting_human')).toBe('waiting_human');
|
||||
expect(normalizeLifecycleStatus('waiting_review')).toBe('waiting_review');
|
||||
expect(normalizeLifecycleStatus('pending_review')).toBe('pending_review');
|
||||
expect(normalizeLifecycleStatus('retryable')).toBe('failed');
|
||||
});
|
||||
|
||||
it('EML 容器不计为业务文件,只保留附件叶子', () => {
|
||||
const items = [{
|
||||
sourceType: 'eml', sourceSummary: { filename: 'mail.eml' },
|
||||
|
||||
@@ -175,6 +175,7 @@ export function buildProcessingSemanticKey(
|
||||
summary: {
|
||||
total_tasks: projection.summary?.total_tasks || 0,
|
||||
total_files: projection.summary?.total_files || 0,
|
||||
submitted_files: projection.summary?.submitted_files || 0,
|
||||
processing: projection.summary?.processing || 0,
|
||||
needs_action: projection.summary?.needs_action || 0,
|
||||
completed: projection.summary?.completed || 0,
|
||||
@@ -276,23 +277,17 @@ export function createIntakeOtStabilizer(options?: { graceMs?: number }): Intake
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化生命周期状态:把旧/兼容形态统一映射为新的单一状态。
|
||||
* 核心逻辑:waiting_human(旧 conversation_processing 兜底)一律归并为
|
||||
* waiting_review(新统一投影);pending_review 收敛到 waiting_review;
|
||||
* 其它保持原值。用于避免两套投影切换时造成状态文本闪烁、语义签名漂移。
|
||||
* 透传生命周期/用户态码;禁止把 F2 user_status 压成 stage 词。
|
||||
* 核心逻辑:waiting_human 保持 waiting_human;waiting_review 仅当输入本就
|
||||
* 是 stage/progress 码时原样返回。不再做 LEGACY-UNIFY 同义词折叠。
|
||||
* @param status - 原始 lifecycle / userStatus / status_label
|
||||
* @returns 归一化后的生命周期状态码
|
||||
* @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;
|
||||
@@ -887,8 +882,8 @@ export function resolveConversationProcessingFromUnified(
|
||||
|
||||
/**
|
||||
* 归一化旧 conversation_processing 投影的生命周期状态。
|
||||
* 核心逻辑:将所有组的 userStatus/status_label 统一为新形态,waiting_human 归并为 waiting_review,
|
||||
* 避免 work_items 为空回退时,旧投影状态与统一 work_items 状态来回切换造成文案闪烁。
|
||||
* 核心逻辑:浅拷贝 tasks 并规范 ui_state;userStatus/status_label 保持 F2 原词,
|
||||
* 禁止把 waiting_human 折叠为 waiting_review。
|
||||
*
|
||||
* @param projection - 原始 embedded conversation_processing 投影
|
||||
* @returns 归一化后的投影(新对象,浅拷贝 tasks 并覆盖 userStatus/status_label)
|
||||
@@ -1037,7 +1032,10 @@ export function normalizeConversationProcessingProjection(
|
||||
status_groups: normalizedGroups,
|
||||
lifecycle_nodes: projection.lifecycle_nodes || [],
|
||||
unclassified_summary: projection.unclassified_summary || { count: 0 },
|
||||
ui_state: projection.ui_state || undefined,
|
||||
// [AUTHORITY] 批次级 ui_state 与任务级 uiState 同为后端 snake_case DTO,必须统一
|
||||
// 归一化(blocking_reason/primary_action 增补 i18nKey;lifecycle_stage→lifecycleStage),
|
||||
// 否则三面阶段口径与工作台导航会读到两套字段名。
|
||||
ui_state: normalizeUiState(projection.ui_state) || undefined,
|
||||
output_artifacts: projection.output_artifacts || [],
|
||||
};
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export * from './shippingDownload';
|
||||
export * from './shippingDecisionFormat';
|
||||
export * from './shippingUploadPrompt';
|
||||
export * from './shippingParseReview';
|
||||
export * from './shippingUiPosition';
|
||||
export * from './shippingMatchResult';
|
||||
export * from './shippingStepper';
|
||||
export * from './shippingLocalMessages';
|
||||
|
||||
@@ -108,6 +108,20 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalized?.stageNodes?.[1]?.absoluteIndex).toBe(2);
|
||||
});
|
||||
|
||||
it('normalizes the EML status-partition file count', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'INTAKE:SNI-EML',
|
||||
work_item_type: 'order_task',
|
||||
aggregate_summary: {
|
||||
intake_no: 'SNI-EML', total: 3, in_group: 2,
|
||||
},
|
||||
});
|
||||
|
||||
expect(normalized?.aggregateSummary).toMatchObject({
|
||||
intakeNo: 'SNI-EML', total: 3, inGroup: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it('保留后端五阶段生命周期入口,包括 freight_upload', () => {
|
||||
const normalized = normalizeShippingProcessingProjection({
|
||||
work_item_no: 'OT-LIFECYCLE-5',
|
||||
@@ -198,6 +212,19 @@ describe('normalizeShippingProcessingProjection', () => {
|
||||
expect(normalizeShippingProcessingProjection({ status: 'processing' })).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for already-camelCase DTO (must only run at API snake boundary)', () => {
|
||||
// 关键断言:normalize 只读 snake;若 composable 对 API 已规范化结果再跑一遍,
|
||||
// 会把 workItemNo 读空并整包洗成 null(右卡永久「获取中/待机」)。
|
||||
expect(normalizeShippingProcessingProjection({
|
||||
workItemNo: 'OT-1',
|
||||
workItemType: 'order_task',
|
||||
status: 'waiting_review',
|
||||
stage: 'inventory_matching',
|
||||
userStatus: 'waiting_human',
|
||||
uiState: { status: 'waiting_human', lifecycleStage: 'fulfillment_prep' },
|
||||
})).toBeNull();
|
||||
});
|
||||
|
||||
it('normalizes work_items arrays', () => {
|
||||
const items = normalizeShippingProcessingWorkItems([
|
||||
{ work_item_no: 'OT-A', work_item_type: 'order_task', status: 'processing', stage: 'document_parsing' },
|
||||
|
||||
@@ -179,6 +179,7 @@ function normalizeLifecycleEntries(raw: unknown): NonNullable<ConversationProces
|
||||
function normalizeFacts(raw: unknown): ShippingProcessingFacts | undefined {
|
||||
if (!raw || typeof raw !== 'object') return undefined;
|
||||
const item = raw as Record<string, unknown>;
|
||||
const out: ShippingProcessingFacts = {};
|
||||
const toStrArr = (value: unknown): string[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.map((c) => String(c ?? '').trim()).filter(Boolean);
|
||||
@@ -187,7 +188,12 @@ function normalizeFacts(raw: unknown): ShippingProcessingFacts | undefined {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter((row): row is Record<string, unknown> => Boolean(row) && typeof row === 'object');
|
||||
};
|
||||
const out: ShippingProcessingFacts = {};
|
||||
// 冻结选择计划中「已选但尚未物化/未识别」的附件诊断标记;仅 false 显式落盘,
|
||||
// 已识别/缺省不设 recognize,便于前端以 facts.recognized === false 识别未识别行。
|
||||
if (item.recognized === false) out.recognized = false;
|
||||
if (item.plan_state != null || item.planState != null) {
|
||||
out.planState = String(item.plan_state ?? item.planState);
|
||||
}
|
||||
if ('inventory_source_status' in item || 'inventorySourceStatus' in item) {
|
||||
out.inventorySourceStatus =
|
||||
item.inventory_source_status != null
|
||||
@@ -278,6 +284,7 @@ function normalizeAggregateSummary(
|
||||
return {
|
||||
intakeNo,
|
||||
total: count('total'),
|
||||
inGroup: count('in_group') || count('inGroup'),
|
||||
completed: count('completed'),
|
||||
processing: count('processing'),
|
||||
needsAction: count('needs_action') || count('needsAction'),
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
formatOrderExtractionElapsed,
|
||||
resolveOrderExtractionRunStageKey,
|
||||
resolveOrderExtractionUserStageKey,
|
||||
} from './orderExtractionProgressDisplay';
|
||||
|
||||
@@ -27,3 +28,18 @@ describe('orderExtractionProgressDisplay', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveOrderExtractionRunStageKey(v2 输出不变契约)', () => {
|
||||
it('与改造前页面内联字面量逐字一致', () => {
|
||||
// 关键断言:有 stage → UserStage key(与原 `chat.shippingOrderExtractionUserStage.${stage}` 完全一致)
|
||||
expect(resolveOrderExtractionRunStageKey('layout_parsing_started', 'processing'))
|
||||
.toBe('chat.shippingOrderExtractionUserStage.layout_parsing_started');
|
||||
expect(resolveOrderExtractionRunStageKey('review_required', 'review_required'))
|
||||
.toBe('chat.shippingOrderExtractionUserStage.review_required');
|
||||
// 关键断言:无 stage → CardTitle key(与原 `chat.shippingOrderExtractionCardTitle.${status}` 完全一致)
|
||||
expect(resolveOrderExtractionRunStageKey(null, 'completed'))
|
||||
.toBe('chat.shippingOrderExtractionCardTitle.completed');
|
||||
expect(resolveOrderExtractionRunStageKey(undefined, 'failed'))
|
||||
.toBe('chat.shippingOrderExtractionCardTitle.failed');
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,8 @@
|
||||
* features/chat/shipping/orderExtractionProgressDisplay.ts
|
||||
* 用途:订单抽取进度展示的纯函数(阶段文案 key、耗时格式化),禁止前端发明阶段码。
|
||||
* 依赖:无;由 ShippingOrderExtractionCard / ShippingWorkflowTimeline 调用。
|
||||
* 逻辑:仅映射后端投影字段到 i18n key 与可读耗时;阈值与阶段判定一律以后端为准。
|
||||
* 逻辑:仅映射后端投影字段到 i18n key 与可读耗时;阈值与阶段判定一律以后端为准;
|
||||
* v2 新增 run 级阶段/状态 key 唯一出口(任务中心与聊天卡同源,输出不变契约见 spec §5.5)。
|
||||
*/
|
||||
|
||||
/** 将秒数格式化为「Xm Ys」风格;空值返回空串。 */
|
||||
@@ -35,3 +36,20 @@ export function resolveOrderExtractionUserStageKey(
|
||||
if (status) return `chat.shippingOrderExtractionDocumentStatus.${status}`;
|
||||
return 'chat.shippingOrderExtractionActivity.generic_processing';
|
||||
}
|
||||
|
||||
/**
|
||||
* run 级阶段/状态展示 key 的唯一出口(任务中心「我的识别」与聊天抽取卡同源消费)。
|
||||
* 核心逻辑:有 user_visible_stage → UserStage 短语文案族;否则回退 run status 的
|
||||
* CardTitle 文案族。仅做事实→key 的受控映射,禁止发明新阶段码。
|
||||
* @param userVisibleStage - 后端 current_activity.user_visible_stage
|
||||
* @param runStatus - 后端 run.status(queued/processing/completed/…)
|
||||
* @returns i18n key(输出不变契约:与改造前页面内联字面量逐字一致)
|
||||
*/
|
||||
export function resolveOrderExtractionRunStageKey(
|
||||
userVisibleStage: string | null | undefined,
|
||||
runStatus: string,
|
||||
): string {
|
||||
const stage = String(userVisibleStage || '').trim();
|
||||
if (stage) return `chat.shippingOrderExtractionUserStage.${stage}`;
|
||||
return `chat.shippingOrderExtractionCardTitle.${String(runStatus || '').trim()}`;
|
||||
}
|
||||
@@ -6,10 +6,16 @@
|
||||
*/
|
||||
/**
|
||||
* 将 submit_decision 结果格式化为本地 assistant 消息 Markdown。
|
||||
*
|
||||
* @param decision - 决策动作码
|
||||
* @param result - API 响应(可读 position,不参与文案拼接)
|
||||
* @param taskId - 任务编号尾注
|
||||
* @param fallbackDoneMessage - 缺省 message 时的兜底文案
|
||||
* @returns Markdown 正文
|
||||
*/
|
||||
export function formatShippingDecisionAssistantMessage(
|
||||
decision: string,
|
||||
result: { message?: string; data?: Record<string, unknown>; checkpoint?: string },
|
||||
result: { message?: string; data?: Record<string, unknown>; position?: string },
|
||||
taskId: string,
|
||||
fallbackDoneMessage: string,
|
||||
): string {
|
||||
|
||||
@@ -1,20 +1,31 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingParseReview.ts
|
||||
* 用途:从 ChatMessage 读取 shipping-parse-review 类型 payload。
|
||||
* 依赖:chat.types、shipping.types。
|
||||
* 逻辑:ShippingParseReviewMessage 渲染 parse_review 可编辑订单表时使用。
|
||||
*/
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingParseReviewPayload } from '../types/shipping.types';
|
||||
|
||||
/** 从 shipping-parse-review 消息提取 taskId、checkpoint 与 lines。 */
|
||||
export function getShippingParseReviewPayload(chatMsg: ChatMessage): ShippingParseReviewPayload | null {
|
||||
if (!chatMsg || chatMsg.type !== 'shipping-parse-review') return null;
|
||||
const payload = chatMsg.payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
const taskId = String((payload as ShippingParseReviewPayload).taskId || '').trim();
|
||||
const checkpoint = String((payload as ShippingParseReviewPayload).checkpoint || '').trim();
|
||||
const lines = (payload as ShippingParseReviewPayload).lines;
|
||||
if (!taskId || !checkpoint || !Array.isArray(lines)) return null;
|
||||
return payload as ShippingParseReviewPayload;
|
||||
}
|
||||
/**
|
||||
* features/chat/shipping/shippingParseReview.ts
|
||||
* 用途:从 ChatMessage 读取 shipping-parse-review 类型 payload。
|
||||
* 依赖:chat.types、shipping.types。
|
||||
* 逻辑:ShippingParseReviewMessage 渲染 parse_review 可编辑订单表时使用;
|
||||
* 新消息以 taskId+lines 为准,position 缺省视为 parse_review。
|
||||
*/
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingParseReviewPayload } from '../types/shipping.types';
|
||||
|
||||
/**
|
||||
* 从 shipping-parse-review 消息提取 taskId 与 lines。
|
||||
*
|
||||
* 核心逻辑:校验 taskId + lines;position 仅为展示标签,不参与门禁。
|
||||
*
|
||||
* @param chatMsg - 聊天消息
|
||||
* @returns 校验通过的 payload;否则 null
|
||||
*/
|
||||
export function getShippingParseReviewPayload(chatMsg: ChatMessage): ShippingParseReviewPayload | null {
|
||||
if (!chatMsg || chatMsg.type !== 'shipping-parse-review') return null;
|
||||
const payload = chatMsg.payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
const typed = { ...(payload as ShippingParseReviewPayload) };
|
||||
const taskId = String(typed.taskId || '').trim();
|
||||
const lines = typed.lines;
|
||||
if (!taskId || !Array.isArray(lines)) return null;
|
||||
// 归一化:缺省 position 时用 parse_review,避免渲染路径空串。
|
||||
typed.position = String(typed.position || 'parse_review').trim() || 'parse_review';
|
||||
return typed;
|
||||
}
|
||||
␍
|
||||
@@ -81,20 +81,21 @@ export function projectionRequiresManualUploadWorkbench(
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Gate 摘要 / checkpoint 判断是否展示「待人工上传登记」提示。
|
||||
* 从 Gate 摘要 / 用户模式判断是否展示「待人工上传登记」提示。
|
||||
*
|
||||
* @param params.nextActionCode - process_gate 或 current_blocking_gate 的 next_action_code
|
||||
* @param params.checkpointKind - ui_state.checkpoint_kind
|
||||
* @param params.userMode - derive_user_mode / ui_state.user_mode
|
||||
* @param params.availableActions - 后端允许的 action 列表
|
||||
* @returns 是否展示人工上传说明
|
||||
*/
|
||||
export function gateSummaryIndicatesManualUpload(params: {
|
||||
nextActionCode?: string | null;
|
||||
checkpointKind?: string | null;
|
||||
userMode?: string | null;
|
||||
availableActions?: string[] | null;
|
||||
}): boolean {
|
||||
if (isManualUploadGateAction(params.nextActionCode)) return true;
|
||||
if (String(params.checkpointKind || '').trim() === 'wait_manual_upload') return true;
|
||||
const mode = String(params.userMode || '').trim();
|
||||
if (mode === 'wait_manual_upload') return true;
|
||||
const actions = Array.isArray(params.availableActions) ? params.availableActions : [];
|
||||
return actions.some((action) => isManualUploadGateAction(action));
|
||||
}
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
extractExtractionProgressReasonCode,
|
||||
isRedundantExtractionDetail,
|
||||
resolveExtractionActivityMessage,
|
||||
resolveRunLifecycleUserStatus,
|
||||
resolveShippingProcessingReasonLabel,
|
||||
resolveShippingProcessingMessage,
|
||||
resolveShippingProcessingStageLabel,
|
||||
@@ -13,9 +17,12 @@ import {
|
||||
} from './shippingProcessingLabels';
|
||||
|
||||
describe('shippingProcessingLabels', () => {
|
||||
it('bridges pending_review to waiting_review key', () => {
|
||||
it('maps waiting_human to its own status key (no LEGACY bridge to waiting_review)', () => {
|
||||
expect(shippingProcessingStatusKey('waiting_human')).toBe(
|
||||
'chat.shippingProcessing.status.waiting_human',
|
||||
);
|
||||
expect(shippingProcessingStatusKey('pending_review')).toBe(
|
||||
'chat.shippingProcessing.status.waiting_review',
|
||||
'chat.shippingProcessing.status.pending_review',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -32,10 +39,15 @@ describe('shippingProcessingLabels', () => {
|
||||
expect(resolveShippingProcessingStatusLabel('queued', te, t)).toBe('排队中');
|
||||
});
|
||||
|
||||
it('uses unified label when available', () => {
|
||||
const te = (key: string) => key === 'chat.shippingProcessing.status.waiting_review';
|
||||
const t = (key: string) => (key.includes('waiting_review') ? '待复核' : key);
|
||||
expect(resolveShippingProcessingStatusLabel('pending_review', te, t)).toBe('待复核');
|
||||
it('does not treat dirty pending_review as waiting_review label', () => {
|
||||
const te = (key: string) => key === 'chat.shippingProcessing.status.waiting_review'
|
||||
|| key === 'chat.shippingProcessing.taskStatus.unknown';
|
||||
const t = (key: string) => {
|
||||
if (key.includes('waiting_review')) return '待复核';
|
||||
if (key.endsWith('.unknown')) return '状态待确认';
|
||||
return key;
|
||||
};
|
||||
expect(resolveShippingProcessingStatusLabel('pending_review', te, t)).toBe('状态待确认');
|
||||
});
|
||||
|
||||
it('uses the safe unknown label instead of exposing an unrecognized status code', () => {
|
||||
@@ -73,3 +85,93 @@ describe('shippingProcessingLabels', () => {
|
||||
expect(resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: 2 })).toBe('需要你处理 · 2');
|
||||
});
|
||||
});
|
||||
|
||||
describe('extraction lifecycle display (v2 状态展示统一)', () => {
|
||||
const PROGRESS_TEXT: Record<string, string> = {
|
||||
'chat.shippingProcessing.progress.step.document_queued': '正在等待解析任务启动',
|
||||
'chat.shippingProcessing.progress.systemProcessingNeed': '系统正在自动处理,请稍候或刷新进度',
|
||||
'chat.shippingProcessing.progress.lifecycleWaitingNeed': '当前步骤需要人工处理',
|
||||
'chat.shippingProcessing.progress.lifecycleReason.review_required': '当前结果需要人工复核。',
|
||||
'chat.shippingProcessing.progress.lifecycleReason.failed': '当前步骤处理失败,请查看详情后重试。',
|
||||
'chat.shippingProcessing.progress.lifecycleReason.cancelled': '本次处理已取消。',
|
||||
'chat.shippingProcessing.progress.lifecycleReason.queue_backlog': '当前步骤正在排队等待执行。',
|
||||
'chat.shippingProcessing.progress.lifecycleReason.processing_slow': '当前步骤耗时较长,系统仍在继续。',
|
||||
};
|
||||
const te = (key: string) => key in PROGRESS_TEXT;
|
||||
const t = (key: string) => PROGRESS_TEXT[key] ?? key;
|
||||
const base = { lifecycle_stage: 'intake_parse', completed_step_codes: [], health_status: 'normal' };
|
||||
|
||||
it('extractExtractionProgressReasonCode 只取受控后缀,非模糊匹配', () => {
|
||||
// 关键断言:末段解析;无 key 返回空串
|
||||
expect(extractExtractionProgressReasonCode({
|
||||
...base, lifecycle_status: 'waiting',
|
||||
blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.review_required',
|
||||
} as any)).toBe('review_required');
|
||||
expect(extractExtractionProgressReasonCode({ ...base, lifecycle_status: 'waiting' } as any)).toBe('');
|
||||
expect(extractExtractionProgressReasonCode(null)).toBe('');
|
||||
});
|
||||
|
||||
it('resolveRunLifecycleUserStatus:running/waiting/failed 兑底,completed/cancelled/未知不映射', () => {
|
||||
expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'running' } as any)).toBe('running');
|
||||
expect(resolveRunLifecycleUserStatus({
|
||||
...base, lifecycle_status: 'waiting',
|
||||
blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.review_required',
|
||||
} as any)).toBe('waiting_human');
|
||||
expect(resolveRunLifecycleUserStatus({
|
||||
...base, lifecycle_status: 'waiting',
|
||||
blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.queue_backlog',
|
||||
} as any)).toBe('running');
|
||||
expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'waiting' } as any)).toBeNull();
|
||||
expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'failed' } as any)).toBe('failed');
|
||||
expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'completed' } as any)).toBeNull();
|
||||
expect(resolveRunLifecycleUserStatus({ ...base, lifecycle_status: 'some_unknown' } as any)).toBeNull();
|
||||
expect(resolveRunLifecycleUserStatus(null)).toBeNull();
|
||||
});
|
||||
|
||||
it('resolveExtractionActivityMessage:running 取步骤句;waiting/failed/cancelled 只取原因句', () => {
|
||||
// 关键断言:running + 步骤 → 步骤句
|
||||
expect(resolveExtractionActivityMessage({
|
||||
...base, lifecycle_status: 'running',
|
||||
current_step_i18n_key: 'chat.shippingProcessing.progress.step.document_queued',
|
||||
} as any, { t, te })).toEqual({ text: '正在等待解析任务启动', running: true });
|
||||
// 关键断言:running 无步骤 → 通用处理中
|
||||
expect(resolveExtractionActivityMessage({ ...base, lifecycle_status: 'running' } as any, { t, te }))
|
||||
.toEqual({ text: '系统正在自动处理,请稍候或刷新进度', running: true });
|
||||
// 关键断言:running + 诊断原因(processing_slow)→ 原因句优先于步骤句
|
||||
expect(resolveExtractionActivityMessage({
|
||||
...base, lifecycle_status: 'running',
|
||||
current_step_i18n_key: 'chat.shippingProcessing.progress.step.document_queued',
|
||||
blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.processing_slow',
|
||||
} as any, { t, te })).toEqual({ text: '当前步骤耗时较长,系统仍在继续。', running: true });
|
||||
// 关键断言:waiting → 原因句;无原因 → 中性等待(绝不复用 step 文案)
|
||||
expect(resolveExtractionActivityMessage({
|
||||
...base, lifecycle_status: 'waiting',
|
||||
blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.review_required',
|
||||
} as any, { t, te })).toEqual({ text: '当前结果需要人工复核。', running: false });
|
||||
expect(resolveExtractionActivityMessage({ ...base, lifecycle_status: 'waiting' } as any, { t, te }))
|
||||
.toEqual({ text: '当前步骤需要人工处理', running: false });
|
||||
// 关键断言:failed/cancelled 文本强制来自原因 key,不复用 running 的 step 文案
|
||||
expect(resolveExtractionActivityMessage({
|
||||
...base, lifecycle_status: 'failed',
|
||||
current_step_i18n_key: 'chat.shippingProcessing.progress.step.document_queued',
|
||||
} as any, { t, te })).toEqual({ text: '当前步骤处理失败,请查看详情后重试。', running: false });
|
||||
expect(resolveExtractionActivityMessage({
|
||||
...base, lifecycle_status: 'cancelled',
|
||||
current_step_i18n_key: 'chat.shippingProcessing.progress.step.document_queued',
|
||||
} as any, { t, te })).toEqual({ text: '本次处理已取消。', running: false });
|
||||
// 白名单外一律 null
|
||||
expect(resolveExtractionActivityMessage({ ...base, lifecycle_status: 'completed' } as any, { t, te })).toBeNull();
|
||||
expect(resolveExtractionActivityMessage({ ...base, lifecycle_status: 'weird_state' } as any, { t, te })).toBeNull();
|
||||
expect(resolveExtractionActivityMessage(null, { t, te })).toBeNull();
|
||||
});
|
||||
|
||||
it('isRedundantExtractionDetail:仅 review_required 且映射结果==当前状态才隐藏', () => {
|
||||
expect(isRedundantExtractionDetail('review_required', 'waiting_human')).toBe(true);
|
||||
expect(isRedundantExtractionDetail('review_required', 'running')).toBe(false);
|
||||
expect(isRedundantExtractionDetail('queue_backlog', 'running')).toBe(false);
|
||||
expect(isRedundantExtractionDetail('processing_slow', 'running')).toBe(false);
|
||||
expect(isRedundantExtractionDetail('processing_attention', 'running')).toBe(false);
|
||||
expect(isRedundantExtractionDetail('unknown_reason', 'waiting_human')).toBe(false);
|
||||
expect(isRedundantExtractionDetail('', 'waiting_human')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,14 +3,23 @@
|
||||
* 用途:将统一 ShippingProcessing 状态/阶段码映射到四语言 i18n 键。
|
||||
* 依赖:vue-i18n Composer(由调用方传入 t / te)。
|
||||
* 逻辑:统一读 chat.shippingProcessing.*;阶段展示优先消费后端 label_key
|
||||
* (如 waiting_system_start),禁止把 stage code 直接当用户文案。
|
||||
* (如 waiting_system_start),禁止把 stage code 直接当用户文案;
|
||||
* v2 新增 Run 级 lifecycle_progress 的状态兜底映射与动态说明解析
|
||||
* (设计:docs/superpowers/specs/2026-08-31-shipping-review-status-display-unification-design.md)。
|
||||
*/
|
||||
import type {
|
||||
ShippingOrderExtractionLifecycleProgress,
|
||||
ShippingUserProcessingStatus,
|
||||
} from '@/features/chat/types/shipping.api.types';
|
||||
import {
|
||||
LIFECYCLE_STAGE_LABEL_KEYS,
|
||||
mapProcessingStageToLifecycle,
|
||||
} from '@/features/shipping-progress/stageMapping';
|
||||
|
||||
/** 会话 processing 旧 status_label → 统一 ShippingProcessingStatus。 */
|
||||
/** status_label / F2 user_status → i18n 用 ShippingProcessingStatus(禁止脏词桥到 waiting_review)。 */
|
||||
const LEGACY_STATUS_TO_PROCESSING: Record<string, string> = {
|
||||
queued: 'processing',
|
||||
processing: 'processing',
|
||||
pending_review: 'waiting_review',
|
||||
waiting_review: 'waiting_review',
|
||||
waiting_human: 'waiting_human',
|
||||
failed: 'failed',
|
||||
@@ -19,7 +28,6 @@ const LEGACY_STATUS_TO_PROCESSING: Record<string, string> = {
|
||||
cancelling: 'processing',
|
||||
blocked: 'blocked',
|
||||
automating: 'automating',
|
||||
review_case_draft: 'waiting_review',
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -137,7 +145,16 @@ export function resolveShippingProcessingStageLabel(
|
||||
if (te(reviewKey)) return t(reviewKey);
|
||||
}
|
||||
const code = String(stage || '').trim();
|
||||
if (!code) return '—';
|
||||
if (!code) {
|
||||
// [契约 §1.1「当前门禁 —」] 已知正式 OT 必有阶段,投影恒有 stage/lifecycle_stage;
|
||||
// 投影未就绪由右卡 :loading 驱动骨架占位。此处禁止落「—」,改为统一的「获取中」占位文案,
|
||||
// 避免用户看到无信息的破折号。仍在无 stage 且非 loading(连降级阶段都没有)时中性呈现。
|
||||
const loadingKey = 'chat.shippingOrderReview.currentProcessing.stageLoading';
|
||||
if (te(loadingKey)) return t(loadingKey);
|
||||
const waitingKey = 'chat.shippingProcessing.stageLabel.waiting_system_start';
|
||||
if (te(waitingKey)) return t(waitingKey);
|
||||
return '正在获取最新状态…';
|
||||
}
|
||||
const stageKey = shippingProcessingStageKey(code);
|
||||
if (te(stageKey)) return t(stageKey);
|
||||
const reviewCodeKey = `chat.shippingOrderReview.currentProcessing.stages.${code}`;
|
||||
@@ -148,6 +165,57 @@ export function resolveShippingProcessingStageLabel(
|
||||
: '等待系统启动';
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析「5 业务阶段」用户文案(批次中心与工作台共用词汇)。
|
||||
*
|
||||
* 三方统一约定:内联卡、右侧批次中心、工作台只消费后端 ui_state.lifecycle_stage,
|
||||
* 映射 `chat.shippingNoticeUi.stage.<code>`(接收解析/订单复核/通知准备/货代上传/上传完成)。
|
||||
* 入参可能是 5 业务阶段码或旧 15 技术阶段码:非业务码时按共享映射聚拢,确保永不显示
|
||||
* “等待系统启动”这类技术阶段措辞。
|
||||
*
|
||||
* @param stage - ui_state.lifecycle_stage(业务码),或兼容的技术阶段码
|
||||
* @param te - i18n te
|
||||
* @param t - i18n t
|
||||
* @returns 本地化文案;未知码回退 `—`
|
||||
*/
|
||||
export function resolveShippingLifecycleStageLabel(
|
||||
stage: string | null | undefined,
|
||||
te: (key: string) => boolean,
|
||||
t: (key: string) => string,
|
||||
): string {
|
||||
const raw = String(stage || '').trim();
|
||||
if (!raw) return '—';
|
||||
const code = LIFECYCLE_STAGE_LABEL_KEYS[raw]
|
||||
? raw
|
||||
: mapProcessingStageToLifecycle(raw);
|
||||
const labelKey = LIFECYCLE_STAGE_LABEL_KEYS[code];
|
||||
const stageKey = `chat.shippingNoticeUi.stage.${labelKey}`;
|
||||
if (labelKey && te(stageKey)) return t(stageKey);
|
||||
return '—';
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定阻塞原因是否为「通用兜底」(应在行内隐藏,避免与状态芯片重复)。
|
||||
*
|
||||
* 三方约定:仅当下发到具体、非兜底的阻塞原因(有真实 i18n 文案)才展示原因行;
|
||||
* 进到 reasonCode.unknown / 无 i18n_key 的通用码一律视为重复信息。
|
||||
*
|
||||
* @param reason - 后端 blocking_reason(code / i18n_key)
|
||||
* @param te - i18n te
|
||||
* @returns true=通用兜底(应隐藏)
|
||||
*/
|
||||
export function isGenericBlockingReason(
|
||||
reason: { code?: string | null; i18nKey?: string | null; i18n_key?: string | null } | null | undefined,
|
||||
te: (key: string) => boolean,
|
||||
): boolean {
|
||||
if (!reason) return true;
|
||||
const i18nKey = String(reason.i18nKey || reason.i18n_key || '').trim();
|
||||
if (i18nKey && te(i18nKey)) return false;
|
||||
const code = String(reason.code || '').trim();
|
||||
if (code && code !== 'unknown' && te(`chat.shippingProcessing.reasonCode.${code}`)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析工作项类型文案键。
|
||||
* @param workItemType - order_intake | order_task
|
||||
@@ -171,3 +239,117 @@ export function shippingProcessingSourceTypeKey(sourceType: string): string {
|
||||
? `chat.shippingProcessing.sourceType.${code}`
|
||||
: 'chat.shippingProcessing.sourceType.eml';
|
||||
}
|
||||
|
||||
/** ========================================================================
|
||||
* v2(状态展示统一):Run 级 lifecycle_progress 的状态兜底与动态说明。
|
||||
* 仅消费后端下发码;受控常量禁止运行时扩充。
|
||||
* ======================================================================== */
|
||||
|
||||
/** lifecycle_status 白名单:白名单外(completed/未知)一律不产生说明与状态映射。 */
|
||||
const EXTRACTION_ACTIVITY_STATUS_ALLOWLIST = new Set(['running', 'waiting', 'failed', 'cancelled']);
|
||||
|
||||
/**
|
||||
* Run 级 lifecycle_status → 用户态兜底映射(spec §5.1)。
|
||||
* 核心逻辑:waiting + 表内原因码才补充/细化用户态;表外原因码不映射(维持待机)。
|
||||
* queue_backlog / processing_slow / processing_attention 属 health tip,可与 running 并存。
|
||||
*/
|
||||
const RUN_STATUS_FALLBACK_MAP: Readonly<Record<string, ShippingUserProcessingStatus>> = {
|
||||
review_required: 'waiting_human',
|
||||
queue_backlog: 'running',
|
||||
processing_slow: 'running',
|
||||
processing_attention: 'running',
|
||||
};
|
||||
|
||||
/**
|
||||
* 允许隐藏动态说明的原因码白名单(spec §5.2)。
|
||||
* 核心逻辑:仅登记"纯重复状态语义"的原因;排队/偏慢/需关注属诊断信息,一律保留说明。
|
||||
* review_required 若未来文案携带更具体原因,应移出本集合。
|
||||
*/
|
||||
const REDUNDANT_DETAIL_REASON_CODES: ReadonlySet<string> = new Set(['review_required']);
|
||||
|
||||
/**
|
||||
* 从 lifecycle_progress 提取受控原因码。
|
||||
* 核心逻辑:取 blocking_reason_i18n_key 末段(受控后缀解析),禁止模糊关键词匹配;
|
||||
* 仅认 RUN_STATUS_FALLBACK_MAP 登记过的码,其余一律空串。
|
||||
* @param progress - Run 级生命周期进度投影
|
||||
* @returns 原因码(如 review_required);无则空串
|
||||
*/
|
||||
export function extractExtractionProgressReasonCode(
|
||||
progress: ShippingOrderExtractionLifecycleProgress | null | undefined,
|
||||
): string {
|
||||
const key = String(progress?.blocking_reason_i18n_key || '').trim();
|
||||
if (!key) return '';
|
||||
const segment = key.split('.').pop() || '';
|
||||
return segment in RUN_STATUS_FALLBACK_MAP ? segment : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Run 级 lifecycle_status → 用户态兜底(spec §5.1;仅供 currentTaskUserStatus 链尾使用)。
|
||||
* 核心逻辑:running/waiting/failed 才补充用户态;原因码只能"补充/细化",
|
||||
* 不能覆盖 failed/cancelled/completed;completed/cancelled/未知一律 null
|
||||
* (避免误伤本页 next-step 与按钮逻辑)。
|
||||
* @param progress - Run 级生命周期进度投影
|
||||
* @returns 用户态 6 值之一;无可兜底值时 null
|
||||
*/
|
||||
export function resolveRunLifecycleUserStatus(
|
||||
progress: ShippingOrderExtractionLifecycleProgress | null | undefined,
|
||||
): ShippingUserProcessingStatus | null {
|
||||
const status = String(progress?.lifecycle_status || '').trim().toLowerCase();
|
||||
if (status === 'running') return 'running';
|
||||
if (status === 'failed') return 'failed';
|
||||
if (status === 'waiting') {
|
||||
return RUN_STATUS_FALLBACK_MAP[extractExtractionProgressReasonCode(progress)] ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 Run 级 lifecycle_progress 的一行动态说明(spec §5.2 detailMessage / §5.3 轻提示共用)。
|
||||
* 核心逻辑:白名单外(completed/未知)返回 null,绝不回退成"等待启动";
|
||||
* running 才可声称自动处理:诊断原因(health tip)优先于步骤句,缺省通用处理中;
|
||||
* waiting 只用原因句、缺省中性等待;failed/cancelled 强制原因 key,禁止复用 running 的 step 文案。
|
||||
* @param progress - Run 级生命周期进度投影
|
||||
* @param i18n - 调用方传入的 te / t
|
||||
* @returns 单行说明文本 + running 位;无可展示内容时 null
|
||||
*/
|
||||
export function resolveExtractionActivityMessage(
|
||||
progress: ShippingOrderExtractionLifecycleProgress | null | undefined,
|
||||
i18n: { te: (key: string) => boolean; t: (key: string) => string },
|
||||
): { text: string; running: boolean } | null {
|
||||
const status = String(progress?.lifecycle_status || '').trim().toLowerCase();
|
||||
if (!progress || !EXTRACTION_ACTIVITY_STATUS_ALLOWLIST.has(status)) return null;
|
||||
const { t, te } = i18n;
|
||||
const localized = (key: string | null | undefined): string => {
|
||||
const normalized = String(key || '').trim();
|
||||
return normalized && te(normalized) ? t(normalized) : '';
|
||||
};
|
||||
const stepText = localized(progress.current_step_i18n_key);
|
||||
const reasonText = localized(progress.blocking_reason_i18n_key);
|
||||
if (status === 'running') {
|
||||
return { text: reasonText || stepText || t('chat.shippingProcessing.progress.systemProcessingNeed'), running: true };
|
||||
}
|
||||
if (status === 'waiting') {
|
||||
return { text: reasonText || t('chat.shippingProcessing.progress.lifecycleWaitingNeed'), running: false };
|
||||
}
|
||||
const terminalKey = status === 'failed'
|
||||
? 'chat.shippingProcessing.progress.lifecycleReason.failed'
|
||||
: 'chat.shippingProcessing.progress.lifecycleReason.cancelled';
|
||||
return { text: te(terminalKey) ? t(terminalKey) : reasonText, running: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定动态说明是否属"纯重复"可隐藏(spec §5.2)。
|
||||
* 核心逻辑:仅白名单内原因码且其状态兜底映射结果 == 当前展示 user_status 才隐藏;
|
||||
* 未知原因默认保留;不做模糊匹配、不比较任何语言的渲染文本。
|
||||
* @param reasonCode - extractExtractionProgressReasonCode 的输出
|
||||
* @param userStatus - 当前展示的用户态
|
||||
* @returns true=隐藏说明行
|
||||
*/
|
||||
export function isRedundantExtractionDetail(
|
||||
reasonCode: string,
|
||||
userStatus: string | null | undefined,
|
||||
): boolean {
|
||||
const code = String(reasonCode || '').trim();
|
||||
if (!REDUNDANT_DETAIL_REASON_CODES.has(code)) return false;
|
||||
return RUN_STATUS_FALLBACK_MAP[code] === String(userStatus || '').trim();
|
||||
}
|
||||
@@ -275,7 +275,7 @@ export function sanitizeShippingConversationText(text: string, enabled: boolean)
|
||||
.replace(/\braw_text\b/gi, '通知原文');
|
||||
result = result.replace(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, '');
|
||||
result = result.replace(
|
||||
/\b(pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[^\s,;]+[「"'`]?/gi,
|
||||
/\b(pending_human_reason|review_status|position|user_mode|match_status|human_options)\s*[::=]\s*[「"'`]?[^\s,;]+[「"'`]?/gi,
|
||||
'',
|
||||
);
|
||||
for (const token of SHIPPING_INTERNAL_STATUS_TOKENS) {
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingUiPosition.spec.ts
|
||||
* 用途:锁定聊天侧 Gate-first 位置/终态/parse_review 判定,只认 position / user_mode。
|
||||
* 依赖:vitest、shippingUiPosition。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
isShippingUiParseReview,
|
||||
isShippingUiTerminal,
|
||||
resolveShippingUiPosition,
|
||||
resolveShippingUiUserMode,
|
||||
} from './shippingUiPosition';
|
||||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
function ui(partial: Partial<ShippingTaskUiState>): ShippingTaskUiState {
|
||||
return {
|
||||
task_no: 'OT-1',
|
||||
steps: [],
|
||||
summary: { title: 't', message: 'm' },
|
||||
...partial,
|
||||
};
|
||||
}
|
||||
describe('shippingUiPosition', () => {
|
||||
it('prefers review_status disposition over flat position', () => {
|
||||
expect(resolveShippingUiPosition(ui({
|
||||
review_status: 'parse_review',
|
||||
position: 'order_freeze',
|
||||
}))).toBe('parse_review');
|
||||
});
|
||||
it('maps order_field_extraction gate to parse_review', () => {
|
||||
expect(resolveShippingUiPosition(ui({
|
||||
process_gate: {
|
||||
execution_no: 'SPE-1',
|
||||
status: 'blocked',
|
||||
current_gate_code: 'order_field_extraction',
|
||||
},
|
||||
position: 'order_freeze',
|
||||
}))).toBe('parse_review');
|
||||
});
|
||||
it('reads flat position when gate absent', () => {
|
||||
expect(resolveShippingUiPosition(ui({
|
||||
position: 'inventory_pending',
|
||||
}))).toBe('inventory_pending');
|
||||
});
|
||||
it('reads summary.position when top-level absent', () => {
|
||||
expect(resolveShippingUiPosition(ui({
|
||||
summary: { title: 't', message: 'm', position: 'ready_to_export' },
|
||||
}))).toBe('ready_to_export');
|
||||
});
|
||||
it('detects terminal via lifecycle and user mode before position', () => {
|
||||
expect(isShippingUiTerminal(ui({
|
||||
lifecycle_stage: 'upload_complete',
|
||||
position: 'inventory_pending',
|
||||
}))).toBe(true);
|
||||
expect(isShippingUiTerminal(ui({
|
||||
user_mode: 'complete',
|
||||
position: 'ready_to_match',
|
||||
}))).toBe(true);
|
||||
expect(isShippingUiTerminal(ui({
|
||||
review_status: 'rejected',
|
||||
}))).toBe(true);
|
||||
expect(isShippingUiTerminal(ui({
|
||||
position: 'uploaded',
|
||||
}))).toBe(true);
|
||||
});
|
||||
it('detects parse_review via review_status or gate', () => {
|
||||
expect(isShippingUiParseReview(ui({ review_status: 'parse_review' }))).toBe(true);
|
||||
expect(isShippingUiParseReview(ui({
|
||||
process_gate: {
|
||||
execution_no: 'SPE-1',
|
||||
status: 'blocked',
|
||||
current_gate_code: 'order_field_extraction',
|
||||
},
|
||||
}))).toBe(true);
|
||||
expect(isShippingUiParseReview(ui({ position: 'inventory_pending' }))).toBe(false);
|
||||
});
|
||||
it('reads user mode from user_mode / summary.user_mode', () => {
|
||||
expect(resolveShippingUiUserMode(ui({ user_mode: 'must_human' }))).toBe('must_human');
|
||||
expect(resolveShippingUiUserMode(ui({
|
||||
summary: { title: 't', message: 'm', user_mode: 'wait_manual_upload' },
|
||||
}))).toBe('wait_manual_upload');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingUiPosition.ts
|
||||
* 用途:从 ui_state 解析位置 / 用户模式 / 终态与 parse_review,优先 Gate、review_status、lifecycle。
|
||||
* 依赖:shipping.api.types.ShippingTaskUiState。
|
||||
* 逻辑:聊天刷新与复核同步消费本模块;只读 flat position / user_mode(含 summary 同名字段),禁止再读 checkpoint_*。
|
||||
*/
|
||||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
/** 复核处置即位置(与后端 derive_position 对齐)。 */
|
||||
const REVIEW_DISPOSITION_POSITIONS = new Set([
|
||||
'parse_review',
|
||||
'rsv_req',
|
||||
'quality_issue',
|
||||
'customer_review',
|
||||
'rejected',
|
||||
]);
|
||||
/** 终态位置标签。 */
|
||||
const TERMINAL_POSITIONS = new Set(['uploaded', 'completed', 'rejected']);
|
||||
/** 终态生命周期。 */
|
||||
const TERMINAL_LIFECYCLE = new Set(['upload_complete', 'completed']);
|
||||
/** Gate code → 位置(仅聊天判定用最小集;完整映射在后端 derive_position)。 */
|
||||
const GATE_CODE_TO_POSITION: Record<string, string> = {
|
||||
order_field_extraction: 'parse_review',
|
||||
customer_resolution: 'customer_review',
|
||||
reservation_validation: 'rsv_req',
|
||||
manual_upload_handoff: 'waiting_upload',
|
||||
artifact_generation: 'export_ready',
|
||||
freight_upload_rpa: 'upload_failed',
|
||||
};
|
||||
/**
|
||||
* 解析用户处置模式(等同后端 derive_user_mode)。
|
||||
*
|
||||
* 核心逻辑:顶层 user_mode → summary.user_mode。
|
||||
*
|
||||
* @param ui - 后端 ui_state
|
||||
* @returns auto_continue | must_human | wait_manual_upload | complete | ''
|
||||
*/
|
||||
export function resolveShippingUiUserMode(ui?: ShippingTaskUiState | null): string {
|
||||
return String(
|
||||
ui?.user_mode
|
||||
|| ui?.summary?.user_mode
|
||||
|| '',
|
||||
).trim();
|
||||
}
|
||||
/**
|
||||
* 解析当前位置标签(等同后端 derive_position)。
|
||||
*
|
||||
* 核心逻辑:review 处置 → Gate code 映射 → flat position / summary.position。
|
||||
*
|
||||
* @param ui - 后端 ui_state
|
||||
* @returns 位置字符串;无法解析时为空
|
||||
*/
|
||||
export function resolveShippingUiPosition(ui?: ShippingTaskUiState | null): string {
|
||||
const review = String(ui?.review_status || '').trim();
|
||||
if (REVIEW_DISPOSITION_POSITIONS.has(review)) {
|
||||
return review;
|
||||
}
|
||||
const gate = ui?.process_gate || ui?.summary?.process_gate;
|
||||
const gateCode = String(gate?.current_gate_code || '').trim();
|
||||
if (gateCode && GATE_CODE_TO_POSITION[gateCode]) {
|
||||
return GATE_CODE_TO_POSITION[gateCode];
|
||||
}
|
||||
return String(
|
||||
ui?.position
|
||||
|| ui?.summary?.position
|
||||
|| '',
|
||||
).trim();
|
||||
}
|
||||
/**
|
||||
* 是否已达终态(上传完成 / 驳回 / user_mode=complete)。
|
||||
*
|
||||
* @param ui - 后端 ui_state
|
||||
*/
|
||||
export function isShippingUiTerminal(ui?: ShippingTaskUiState | null): boolean {
|
||||
if (!ui) return false;
|
||||
const lifecycle = String(ui.lifecycle_stage || ui.stage?.code || '').trim();
|
||||
if (TERMINAL_LIFECYCLE.has(lifecycle)) return true;
|
||||
if (resolveShippingUiUserMode(ui) === 'complete') return true;
|
||||
const review = String(ui.review_status || '').trim();
|
||||
if (review === 'rejected') return true;
|
||||
return TERMINAL_POSITIONS.has(resolveShippingUiPosition(ui));
|
||||
}
|
||||
/**
|
||||
* 是否处于解析复核位(需同步 shipping-parse-review 消息)。
|
||||
*
|
||||
* @param ui - 后端 ui_state
|
||||
*/
|
||||
export function isShippingUiParseReview(ui?: ShippingTaskUiState | null): boolean {
|
||||
if (!ui) return false;
|
||||
if (String(ui.review_status || '').trim() === 'parse_review') return true;
|
||||
const gate = ui.process_gate || ui.summary?.process_gate;
|
||||
if (String(gate?.current_gate_code || '').trim() === 'order_field_extraction') return true;
|
||||
return resolveShippingUiPosition(ui) === 'parse_review';
|
||||
}
|
||||
@@ -6,9 +6,6 @@
|
||||
*/
|
||||
import i18n from '@/i18n';
|
||||
|
||||
/**
|
||||
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
|
||||
*/
|
||||
/**
|
||||
* 根据通知提交 API 响应生成发给 Dify 的 follow-up 提示语(触发完整订单抽取链)。
|
||||
*/
|
||||
|
||||
@@ -30,7 +30,7 @@ export interface ShippingParseReviewContext {
|
||||
/**
|
||||
* 创建发货通知 parse review 卡片处理器。
|
||||
*
|
||||
* 核心逻辑:根据任务详情与 checkpoint 维护本地复核卡片,并把单头/订单行编辑回写到后端。
|
||||
* 核心逻辑:根据任务详情与 Gate/review 位置维护本地复核卡片,并把单头/订单行编辑回写到后端。
|
||||
* @param ctx - parse review 卡片上下文
|
||||
* @returns 复核卡片同步与编辑处理函数集合
|
||||
*/
|
||||
|
||||
@@ -42,11 +42,12 @@ describe('useChatShippingRefresh', () => {
|
||||
it('syncs ui_state for notifications without attaching chat action buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-FOCUS-B',
|
||||
checkpoint: 'ready_export',
|
||||
match_status: 'matched',
|
||||
lifecycle_stage: 'fulfillment_prep',
|
||||
user_mode: 'auto_continue',
|
||||
position: 'ready_to_export',
|
||||
match_status: 'fulfillable',
|
||||
review_status: null,
|
||||
pending_human_reason: null,
|
||||
match_status: 'fulfillable',
|
||||
current_step: null,
|
||||
steps: [],
|
||||
summary: {
|
||||
@@ -102,11 +103,12 @@ describe('useChatShippingRefresh', () => {
|
||||
it('clears legacy shipping_actions even when api returns action_buttons', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-SOURCE-001',
|
||||
checkpoint: 'ready_export',
|
||||
match_status: 'matched',
|
||||
lifecycle_stage: 'fulfillment_prep',
|
||||
user_mode: 'auto_continue',
|
||||
position: 'ready_to_export',
|
||||
match_status: 'fulfillable',
|
||||
review_status: null,
|
||||
pending_human_reason: null,
|
||||
match_status: 'fulfillable',
|
||||
current_step: null,
|
||||
steps: [],
|
||||
summary: {
|
||||
@@ -187,4 +189,33 @@ describe('useChatShippingRefresh', () => {
|
||||
expect(getWorkspaceShippingTaskUiState).not.toHaveBeenCalled();
|
||||
expect(messages.value[0].shipping_actions).toBeUndefined();
|
||||
});
|
||||
|
||||
it('treats lifecycle upload_complete as terminal without position code', async () => {
|
||||
getWorkspaceShippingTaskUiState.mockResolvedValue({
|
||||
task_no: 'SN-DONE-001',
|
||||
lifecycle_stage: 'upload_complete',
|
||||
user_mode: 'complete',
|
||||
steps: [],
|
||||
summary: { title: '已完成', message: '上传完成' },
|
||||
});
|
||||
const messages = ref([
|
||||
{
|
||||
role: 'assistant' as const,
|
||||
content: '处理中',
|
||||
shipping_actions: [{ id: 'x', label: 'x', message: 'x', variant: 'primary' as const }],
|
||||
},
|
||||
]);
|
||||
const { refreshShippingActions } = createShippingActionsRefresher({
|
||||
isShippingNoticeAgent: computed(() => true),
|
||||
messages,
|
||||
conversationId: ref('conv-done'),
|
||||
isThinking: ref(false),
|
||||
resolvedShippingTaskId: ref('SN-DONE-001'),
|
||||
shippingTaskIdFromQuery: computed(() => ''),
|
||||
getActiveShippingTaskId: () => 'SN-DONE-001',
|
||||
});
|
||||
await refreshShippingActions();
|
||||
expect(messages.value[0].shipping_actions).toBeUndefined();
|
||||
expect(messages.value[0].shipping_ui_state?.lifecycle_stage).toBe('upload_complete');
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,12 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingRefresh.ts
|
||||
* 用途:刷新聊天区发货通知 UI State,同步后端 summary/checkpoint 到消息,供通知展示。
|
||||
* 依赖:shipping.api、shippingTaskId、shippingNoticeActions 常量、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用本文件;只读取后端 /ui-state 并净化正文中的动作菜单文案,不再把 action_buttons 映射为消息按钮。
|
||||
* 用途:刷新聊天区发货通知 UI State,同步后端 summary 到消息,供通知展示。
|
||||
* 依赖:shipping.api、shippingTaskId、shippingUiPosition、shippingText、chat.types。
|
||||
* 逻辑:由 useChatShipping 调用;终态判定走 Gate/lifecycle/position/user_mode(isShippingUiTerminal)。
|
||||
*/
|
||||
import { getWorkspaceShippingTaskUiState } from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
|
||||
import { findLatestShippingTaskId } from './shippingTaskId';
|
||||
import { isShippingUiTerminal } from './shippingUiPosition';
|
||||
import { stripShippingActionListByButtons, stripShippingPlainActionMenu } from './shippingText';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
@@ -118,12 +118,8 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
// keep existing SSE-delivered ui_state if present
|
||||
}
|
||||
}
|
||||
const apiCheckpoint = String(
|
||||
apiState?.checkpoint?.code
|
||||
|| apiState?.checkpoint_code
|
||||
|| '',
|
||||
).trim() || null;
|
||||
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
|
||||
// [STEP] 终态:清空履约按钮并全量同步 ui_state;判定优先 lifecycle / user_mode / review。
|
||||
if (apiResolved && isShippingUiTerminal(apiState)) {
|
||||
msgs.forEach((rawMsg) => {
|
||||
const m = rawMsg as ChatMessage;
|
||||
if (m.role === 'assistant') {
|
||||
|
||||
@@ -208,7 +208,6 @@ export function mapServerCandidate(remote: ShippingNoticeCandidateResponse): Shi
|
||||
fieldAdjudication: remote.field_adjudication && typeof remote.field_adjudication === 'object'
|
||||
? remote.field_adjudication
|
||||
: null,
|
||||
customerMatches: Array.isArray(remote.customer_matches) ? remote.customer_matches : [],
|
||||
businessSummary: remote.business_summary || {},
|
||||
duplicate,
|
||||
duplicateResolution: remote.duplicate_resolution
|
||||
|
||||
@@ -409,6 +409,167 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-LATEST', expect.any(AbortSignal));
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('restores the submission primary instead of a newer sibling Run without client_submission_id', async () => {
|
||||
const sibling = Object.assign(run({
|
||||
run_no: 'SNER-SIBLING',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'processing',
|
||||
created_at: '2026-09-07T11:25:47Z',
|
||||
}), { client_submission_id: null, upload_batch_id: null });
|
||||
const primary = Object.assign(run({
|
||||
run_no: 'SNER-PRIMARY',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'processing',
|
||||
created_at: '2026-09-07T10:54:34Z',
|
||||
}), { client_submission_id: 'SUB-ONCE', upload_batch_id: null });
|
||||
// 模拟后端会话短列表:sibling 虽更新,但 primary 排前(或至少出现在列表中)。
|
||||
api.listRuns.mockResolvedValue({ items: [sibling, primary] });
|
||||
api.getRun.mockResolvedValue(primary);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-PRIMARY', expect.any(AbortSignal));
|
||||
expect(harness.runs.getActiveRunNo()).toBe('SNER-PRIMARY');
|
||||
expect(harness.messages.value.filter((item) => item.shipping_order_extraction_state)).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.payload).toMatchObject({
|
||||
order_extraction_run_no: 'SNER-PRIMARY',
|
||||
shipping_order_extraction_client_submission_id: 'SUB-ONCE',
|
||||
});
|
||||
harness.runs.stopPolling();
|
||||
});
|
||||
|
||||
it('keeps an existing primary progress card instead of upserting a sibling on restore', async () => {
|
||||
const primary = Object.assign(run({
|
||||
run_no: 'SNER-PRIMARY',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'partially_completed',
|
||||
}), { client_submission_id: 'SUB-ONCE', upload_batch_id: null });
|
||||
const sibling = Object.assign(run({
|
||||
run_no: 'SNER-SIBLING',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'partially_completed',
|
||||
}), { client_submission_id: null, upload_batch_id: null });
|
||||
api.listRuns.mockResolvedValue({ items: [sibling] });
|
||||
api.getRun.mockResolvedValue(primary);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
harness.messages.value = [{
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: '',
|
||||
local_id: 'existing-primary-card',
|
||||
shipping_order_extraction_state: {
|
||||
status: 'partially_completed',
|
||||
runNo: 'SNER-PRIMARY',
|
||||
clientSubmissionId: 'SUB-ONCE',
|
||||
uploadBatchId: null,
|
||||
summary: {
|
||||
totalDocuments: 22,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 15,
|
||||
reviewRequiredDocuments: 7,
|
||||
failedDocuments: 0,
|
||||
cancelledDocuments: 0,
|
||||
candidateCount: 0,
|
||||
},
|
||||
availableActions: [],
|
||||
terminal: true,
|
||||
refreshFailed: false,
|
||||
},
|
||||
payload: {
|
||||
formId: 'shipping-order-extraction-run:SNER-PRIMARY',
|
||||
order_extraction_run_no: 'SNER-PRIMARY',
|
||||
shipping_order_extraction_client_submission_id: 'SUB-ONCE',
|
||||
},
|
||||
}];
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
// sibling 不在已有卡列表命中时,仍应直拉已有卡 run_no,而不是 list[0] sibling。
|
||||
expect(api.getRun).toHaveBeenCalledWith('SNER-PRIMARY', expect.any(AbortSignal));
|
||||
expect(harness.messages.value.filter((item) => item.shipping_order_extraction_state)).toHaveLength(1);
|
||||
expect(harness.messages.value[0]?.payload?.order_extraction_run_no).toBe('SNER-PRIMARY');
|
||||
});
|
||||
|
||||
it('prunes an orphan sibling progress card when restoring a submission primary', async () => {
|
||||
const primary = Object.assign(run({
|
||||
run_no: 'SNER-PRIMARY',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'partially_completed',
|
||||
}), { client_submission_id: 'SUB-ONCE', upload_batch_id: null });
|
||||
api.listRuns.mockResolvedValue({ items: [primary] });
|
||||
api.getRun.mockResolvedValue(primary);
|
||||
const harness = createHarness();
|
||||
harness.conversationId.value = 'conv-1';
|
||||
harness.messages.value = [
|
||||
{
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: '',
|
||||
local_id: 'primary-card',
|
||||
shipping_order_extraction_state: {
|
||||
status: 'partially_completed',
|
||||
runNo: 'SNER-PRIMARY',
|
||||
clientSubmissionId: 'SUB-ONCE',
|
||||
summary: {
|
||||
totalDocuments: 1,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
cancelledDocuments: 0,
|
||||
candidateCount: 0,
|
||||
},
|
||||
availableActions: [],
|
||||
terminal: true,
|
||||
refreshFailed: false,
|
||||
},
|
||||
payload: {
|
||||
formId: 'shipping-order-extraction-run:SNER-PRIMARY',
|
||||
order_extraction_run_no: 'SNER-PRIMARY',
|
||||
shipping_order_extraction_client_submission_id: 'SUB-ONCE',
|
||||
},
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: '',
|
||||
local_id: 'orphan-sibling-card',
|
||||
shipping_order_extraction_state: {
|
||||
status: 'partially_completed',
|
||||
runNo: 'SNER-SIBLING',
|
||||
summary: {
|
||||
totalDocuments: 1,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
cancelledDocuments: 0,
|
||||
candidateCount: 0,
|
||||
},
|
||||
availableActions: [],
|
||||
terminal: true,
|
||||
refreshFailed: false,
|
||||
},
|
||||
payload: {
|
||||
formId: 'shipping-order-extraction-run:SNER-SIBLING',
|
||||
order_extraction_run_no: 'SNER-SIBLING',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
await harness.runs.restoreForConversation('conv-1');
|
||||
|
||||
const cards = harness.messages.value.filter((item) => item.shipping_order_extraction_state);
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]?.payload?.order_extraction_run_no).toBe('SNER-PRIMARY');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* 右侧「本次处理」由 processing / Workflow 投影驱动,本模块在终态/重识别后触发刷新回调。
|
||||
* 轮询前台 2s / 后台 5–10s;取消走请求语义 API,刷新为只读 GET。
|
||||
* 持久化去重签名必须包含 handling_items / primary_notice,避免处理说明变化后历史会话仍读到旧卡。
|
||||
* 会话恢复锚定 submission primary(client_submission_id)或已有进度卡,禁止 sibling Run 再写第二张卡。
|
||||
*/
|
||||
import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from 'vue';
|
||||
import {
|
||||
@@ -72,6 +73,7 @@ export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtraction
|
||||
submissionOrdinal: run.submission_ordinal ?? null,
|
||||
composerContextId: run.composer_context_id || null,
|
||||
uploadBatchId: run.upload_batch_id || null,
|
||||
clientSubmissionId: run.client_submission_id || null,
|
||||
runNo: run.run_no,
|
||||
sourceRunNo: run.reparse?.source_run_no || null,
|
||||
supersedingRunNo: run.reparse?.superseding_run_no || null,
|
||||
@@ -268,6 +270,8 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
|
||||
/**
|
||||
* 查找或创建当前 Run 的助手状态消息,仅在业务状态真正变化时持久化。
|
||||
* 核心逻辑:按 formId / run_no / upload_batch_id / client_submission_id 合并;
|
||||
* 同一次提交的 sibling(无 submission 键)不得因 run_no 不同再建第二张卡。
|
||||
* @param run - 用户态 Run 摘要,不包含 Provider 快照或原始文档。
|
||||
* @returns 当前会话内原位更新后的助手状态消息。
|
||||
*/
|
||||
@@ -278,6 +282,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const formId = `shipping-order-extraction-run:${run.run_no}`;
|
||||
const state = mapOrderExtractionRunToMessageState(run);
|
||||
const uploadBatchId = String(run.upload_batch_id || '').trim();
|
||||
const clientSubmissionId = String(run.client_submission_id || '').trim();
|
||||
const stateCards = options.messages.value.filter((item) => {
|
||||
if (item.role !== 'assistant') return false;
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
@@ -286,9 +291,15 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
|| item.shipping_order_extraction_state?.uploadBatchId
|
||||
|| '',
|
||||
).trim();
|
||||
const cardSubmissionId = String(
|
||||
payload.shipping_order_extraction_client_submission_id
|
||||
|| item.shipping_order_extraction_state?.clientSubmissionId
|
||||
|| '',
|
||||
).trim();
|
||||
return payload.formId === formId
|
||||
|| payload.order_extraction_run_no === run.run_no
|
||||
|| Boolean(uploadBatchId && cardBatchId === uploadBatchId);
|
||||
|| Boolean(uploadBatchId && cardBatchId === uploadBatchId)
|
||||
|| Boolean(clientSubmissionId && cardSubmissionId === clientSubmissionId);
|
||||
});
|
||||
let message = stateCards.find((item) => {
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload as Record<string, unknown> : {};
|
||||
@@ -313,6 +324,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
formId,
|
||||
order_extraction_run_no: run.run_no,
|
||||
shipping_order_extraction_upload_batch_id: run.upload_batch_id || null,
|
||||
shipping_order_extraction_client_submission_id: run.client_submission_id || null,
|
||||
shipping_order_extraction_state: state,
|
||||
order_extraction_reparse: run.reparse || null,
|
||||
shipping_order_extraction_review: reviewAttachments || [],
|
||||
@@ -673,7 +685,12 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
}));
|
||||
};
|
||||
|
||||
/** 刷新或进入既有会话时恢复最新 Run 状态卡;活动 Run 继续轮询。右侧 Workflow 面板由独立投影恢复。 */
|
||||
/**
|
||||
* 刷新或进入既有会话时恢复最新进度卡。
|
||||
* 核心逻辑:优先锚定已有消息中的 Run 卡;否则取列表中的 submission primary
|
||||
* (client_submission_id 非空)。禁止按 created_at 最新的 sibling 再建第二张卡。
|
||||
* 活动 Run 继续轮询;右侧 Workflow 面板由独立投影恢复。
|
||||
*/
|
||||
const restoreForConversation = async (conversationId: string): Promise<void> => {
|
||||
clearActiveRun();
|
||||
try {
|
||||
@@ -681,9 +698,39 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
const request = createRequestController(generation);
|
||||
const { items } = await listWorkspaceShippingOrderExtractionRuns(conversationId, 20, request.signal).finally(request.release);
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
const latest = items[0];
|
||||
if (!latest) return;
|
||||
const displayRun = await getWorkspaceShippingOrderExtractionRun(latest.run_no, request.signal);
|
||||
if (!items.length) return;
|
||||
|
||||
// [STEP 1] 已有进度卡优先:历史消息中的 primary 卡可能不在短列表窗口内。
|
||||
const existingCardRunNos: string[] = [];
|
||||
for (const message of options.messages.value) {
|
||||
if (!message.shipping_order_extraction_state) continue;
|
||||
const payload = message.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
: {};
|
||||
const runNo = String(
|
||||
payload.order_extraction_run_no
|
||||
|| message.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
if (runNo) existingCardRunNos.push(runNo);
|
||||
}
|
||||
|
||||
// [STEP 2] 选择恢复锚点:已有卡 → submission primary → 列表首项(后端会话列表已 primary 优先)。
|
||||
const preferredFromExisting = items.find((item) => existingCardRunNos.includes(item.run_no));
|
||||
const preferredPrimary = items.find((item) => Boolean(String(item.client_submission_id || '').trim()));
|
||||
const existingOnlyRunNo = !preferredFromExisting && existingCardRunNos.length
|
||||
? existingCardRunNos[existingCardRunNos.length - 1]
|
||||
: '';
|
||||
const selectedRunNo = String(
|
||||
preferredFromExisting?.run_no
|
||||
|| preferredPrimary?.run_no
|
||||
|| existingOnlyRunNo
|
||||
|| items[0]?.run_no
|
||||
|| '',
|
||||
).trim();
|
||||
if (!selectedRunNo) return;
|
||||
|
||||
const displayRun = await getWorkspaceShippingOrderExtractionRun(selectedRunNo, request.signal);
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
activeRunNo = displayRun.run_no;
|
||||
const reviewAttachments = ACTIVE_RUN_STATUSES.has(displayRun.status)
|
||||
@@ -691,11 +738,42 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
|
||||
: await refreshTerminalFacts(displayRun);
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
await upsertRunMessage(displayRun, reviewAttachments);
|
||||
// [STEP 3] 清掉同会话里无 submission/batch 键的孤儿 sibling 卡(历史误写),避免两张进度并排。
|
||||
// 有独立 client_submission_id 或 upload_batch_id 的卡保留(另一次真实提交)。
|
||||
const preferredRunNo = String(displayRun.run_no || '').trim();
|
||||
const preferredSubmissionId = String(displayRun.client_submission_id || '').trim();
|
||||
if (preferredRunNo && preferredSubmissionId) {
|
||||
options.messages.value = options.messages.value.filter((message) => {
|
||||
if (!message.shipping_order_extraction_state) return true;
|
||||
const payload = message.payload && typeof message.payload === 'object'
|
||||
? message.payload as Record<string, unknown>
|
||||
: {};
|
||||
const runNo = String(
|
||||
payload.order_extraction_run_no
|
||||
|| message.shipping_order_extraction_state.runNo
|
||||
|| '',
|
||||
).trim();
|
||||
if (!runNo || runNo === preferredRunNo) return true;
|
||||
const batchId = String(
|
||||
payload.shipping_order_extraction_upload_batch_id
|
||||
|| message.shipping_order_extraction_state.uploadBatchId
|
||||
|| '',
|
||||
).trim();
|
||||
const submissionId = String(
|
||||
payload.shipping_order_extraction_client_submission_id
|
||||
|| message.shipping_order_extraction_state.clientSubmissionId
|
||||
|| '',
|
||||
).trim();
|
||||
if (submissionId && submissionId !== preferredSubmissionId) return true;
|
||||
if (batchId) return true;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
await acknowledgeTerminalRunWhenVisible(displayRun);
|
||||
options.onWorkflowRefresh?.();
|
||||
if (options.conversationId.value !== conversationId) return;
|
||||
if (ACTIVE_RUN_STATUSES.has(displayRun.status)) {
|
||||
beginPolling(latest.run_no, 1000);
|
||||
beginPolling(displayRun.run_no, 1000);
|
||||
}
|
||||
} catch {
|
||||
// 会话历史仍可正常使用;下一次进入会话或手动刷新时重新恢复 Run。
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* features/chat/shipping/useShippingProcessingWorkItem.spec.ts
|
||||
* 用途:验收 work-item 轮询 composable 不二次 normalize、能落盘 API 已规范化投影。
|
||||
* 依赖:Vitest、Vue、useShippingProcessingWorkItem。
|
||||
* 逻辑:API 层已 snake→camel;若 composable 再 normalize(只认 snake),会把投影洗成 null。
|
||||
*/
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { defineComponent, nextTick, ref } from 'vue';
|
||||
import { mount, flushPromises } from '@vue/test-utils';
|
||||
|
||||
const getWorkspaceShippingProcessingWorkItem = vi.fn();
|
||||
|
||||
vi.mock('../api/shipping.api', () => ({
|
||||
getWorkspaceShippingProcessingWorkItem: (...args: unknown[]) => (
|
||||
getWorkspaceShippingProcessingWorkItem(...args)
|
||||
),
|
||||
}));
|
||||
|
||||
import { useShippingProcessingWorkItem } from './useShippingProcessingWorkItem';
|
||||
|
||||
describe('useShippingProcessingWorkItem', () => {
|
||||
beforeEach(() => {
|
||||
getWorkspaceShippingProcessingWorkItem.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('keeps API-normalized camelCase projection (must not re-normalize to null)', async () => {
|
||||
// 关键断言:右卡「正在获取最新状态/待机」曾因二次 normalize 只读 snake 把
|
||||
// workItemNo 读空、整包洗成 null;API 已返回的 camelCase 投影必须原样落盘。
|
||||
getWorkspaceShippingProcessingWorkItem.mockResolvedValue({
|
||||
workItemType: 'order_task',
|
||||
workItemNo: 'OT-20260905-DAC55F90',
|
||||
sourceType: 'eml',
|
||||
status: 'waiting_review',
|
||||
stage: 'inventory_matching',
|
||||
progressVersion: 24,
|
||||
lastActivityAt: '2026-09-05T11:25:45Z',
|
||||
submissionNo: 'SOS-1',
|
||||
intakeNo: 'SNI-1',
|
||||
userStatus: 'waiting_human',
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
stage: 'inventory_matching',
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [],
|
||||
blocking_reason: { code: 'inventory_shortage_review_required' },
|
||||
primary_action: { code: 'retry_inventory_matching' },
|
||||
secondary_actions: [],
|
||||
},
|
||||
sourceSummary: {
|
||||
emailSubject: null,
|
||||
filename: 'a.pdf',
|
||||
documentId: 1,
|
||||
documentCount: 1,
|
||||
parsedDocumentCount: 1,
|
||||
candidateCount: 1,
|
||||
customerName: null,
|
||||
poNumber: null,
|
||||
},
|
||||
childOrderTasks: [],
|
||||
hasFormalOt: false,
|
||||
});
|
||||
|
||||
const workItemNo = ref('OT-20260905-DAC55F90');
|
||||
let api: ReturnType<typeof useShippingProcessingWorkItem> | null = null;
|
||||
const Comp = defineComponent({
|
||||
setup() {
|
||||
api = useShippingProcessingWorkItem('order_task', workItemNo, {
|
||||
continuousPolling: false,
|
||||
monotonicProgressVersion: true,
|
||||
});
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
mount(Comp);
|
||||
await flushPromises();
|
||||
await nextTick();
|
||||
|
||||
expect(getWorkspaceShippingProcessingWorkItem).toHaveBeenCalledWith(
|
||||
'order_task',
|
||||
'OT-20260905-DAC55F90',
|
||||
);
|
||||
expect(api!.projection.value).not.toBeNull();
|
||||
expect(api!.projection.value?.workItemNo).toBe('OT-20260905-DAC55F90');
|
||||
expect(api!.projection.value?.userStatus).toBe('waiting_human');
|
||||
expect(api!.projection.value?.uiState?.lifecycleStage).toBe('fulfillment_prep');
|
||||
expect(api!.projection.value?.uiState?.primary_action?.code).toBe('retry_inventory_matching');
|
||||
expect(api!.error.value).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
/**
|
||||
* features/chat/shipping/useShippingProcessingWorkItem.ts
|
||||
* 用途:按 work_item_type + work_item_no 轮询统一 ShippingProcessingProjection。
|
||||
* 依赖:shipping.api、normalizeShippingProcessing、mergeWorkbenchProcessingProjection。
|
||||
* 依赖:shipping.api(已在边界 normalize)、mergeWorkbenchProcessingProjection。
|
||||
* 逻辑:复核台 / 任务中心双读;工作台可启用 monotonicProgressVersion;404 时保持 null。
|
||||
* 禁止对本 composable 再跑 normalize:API 已输出 camelCase,二次 normalize
|
||||
* 只认 snake_case 会把 workItemNo 读空并整包洗成 null(右卡永久「获取中/待机」)。
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -18,13 +20,18 @@ import { BusinessError } from '@/shared/api/client';
|
||||
import { mergeWorkbenchProcessingProjection } from '@/features/shipping-progress/mergeProcessingProjection';
|
||||
import { getWorkspaceShippingProcessingWorkItem } from '../api/shipping.api';
|
||||
import type { ShippingProcessingProjection } from '../types/shipping.api.types';
|
||||
import { normalizeShippingProcessingProjection } from './normalizeShippingProcessing';
|
||||
|
||||
const DEFAULT_POLL_MS = 3000;
|
||||
const TERMINAL_STATUSES = new Set([
|
||||
'completed',
|
||||
'cancelled',
|
||||
]);
|
||||
/** 用户态“中断/失败/等待人工”状态:结果不会自行变化,停止轮询(约定:中断不轮询)。 */
|
||||
const INTERRUPTED_USER_STATUSES = new Set([
|
||||
'waiting_human',
|
||||
'failed',
|
||||
'interrupted',
|
||||
]);
|
||||
|
||||
export type ShippingProcessingWorkItemTypeArg = 'order_intake' | 'order_task';
|
||||
|
||||
@@ -87,6 +94,7 @@ export function useShippingProcessingWorkItem(
|
||||
|
||||
/**
|
||||
* 拉取一次投影;失败保留上一帧。
|
||||
* 核心逻辑:直接消费 API 已 normalize 的 camelCase 投影,禁止二次 normalize。
|
||||
*/
|
||||
async function refresh(): Promise<void> {
|
||||
const no = String(toValue(workItemNo) || '').trim();
|
||||
@@ -105,17 +113,22 @@ export function useShippingProcessingWorkItem(
|
||||
loading.value = true;
|
||||
const request = (async () => {
|
||||
try {
|
||||
const raw = await getWorkspaceShippingProcessingWorkItem(workItemType, no);
|
||||
// [STEP 1] API 边界已完成 snake→camel;此处不得再 normalize(会读空 workItemNo → null)。
|
||||
const incoming = await getWorkspaceShippingProcessingWorkItem(workItemType, no);
|
||||
if (stopped || gen !== generation) return;
|
||||
const normalized = normalizeShippingProcessingProjection(raw);
|
||||
// [STEP] 工作台单调合并:旧包丢弃;新包整包替换;同版本浅合并。任务中心不启用。
|
||||
// [STEP 2] 工作台单调合并:旧包丢弃;新包整包替换;同版本浅合并。任务中心不启用。
|
||||
projection.value = monotonic
|
||||
? mergeWorkbenchProcessingProjection(projection.value, normalized)
|
||||
: normalized;
|
||||
? mergeWorkbenchProcessingProjection(projection.value, incoming)
|
||||
: incoming;
|
||||
error.value = null;
|
||||
clearTimer();
|
||||
const next = projection.value;
|
||||
if (continuousPolling && next && !TERMINAL_STATUSES.has(next.status) && !stopped) {
|
||||
const userStatus = String(next?.userStatus || '').trim().toLowerCase();
|
||||
const stoppedByState = Boolean(next) && (
|
||||
TERMINAL_STATUSES.has(next!.status)
|
||||
|| INTERRUPTED_USER_STATUSES.has(userStatus)
|
||||
);
|
||||
if (continuousPolling && next && !stoppedByState && !stopped) {
|
||||
timer = window.setTimeout(() => {
|
||||
void refresh();
|
||||
}, pollMs);
|
||||
|
||||
Reference in new issue
Block a user